Files
hoodFieldOfView/头罩视野slove/头罩视野/ModbusHelper.cs

103 lines
3.1 KiB
C#
Raw Normal View History

2026-04-22 14:45:50 +08:00
using Modbus.Device;
using Microsoft.Win32;
2026-04-22 10:49:59 +08:00
using System;
using System.Collections.Generic;
using System.IO;
2026-04-22 14:45:50 +08:00
using System.Net.Sockets;
2026-04-22 10:49:59 +08:00
using System.Text;
using System.Windows;
2026-04-22 14:45:50 +08:00
using .Services.Data;
2026-04-22 10:49:59 +08:00
2026-04-21 13:36:09 +08:00
public static class ModbusHelper
{
// 全局唯一连接,所有页面共用
public static TcpClient TcpClient => ModbusResourceManager.Instance.TcpClient;
2026-04-22 14:45:50 +08:00
2026-04-21 13:36:09 +08:00
// 统一连接方法(全项目只调用一次)
public static bool Connect(string ip, int port = 502)
{
return ModbusResourceManager.Instance.Init(ip, port);
}
// 判断是否连接成功
public static bool IsConnected => TcpClient != null && TcpClient.Connected;
2026-04-22 10:49:59 +08:00
// <summary>
/// 公共保存方法(用户自选文件夹)
/// </summary>
/// <param name="dataList">你的数据集合</param>
/// <param name="defaultFileName">默认文件名</param>
public static void SaveToCsv(List<dynamic> dataList, string defaultFileName)
{
if (dataList == null || dataList.Count == 0)
{
MessageBox.Show("无数据可保存!");
return;
}
// 选择文件夹
var folderDialog = new OpenFolderDialog
{
Title = "请选择保存路径"
};
if (folderDialog.ShowDialog() != true)
return;
string folderPath = folderDialog.FolderName;
string filePath = Path.Combine(folderPath, defaultFileName);
// 写入 CSV
using (var sw = new StreamWriter(filePath, false, Encoding.UTF8))
{
var firstRow = (IDictionary<string, object>)dataList[0];
sw.WriteLine(string.Join(",", firstRow.Keys));
foreach (var item in dataList)
{
var dict = (IDictionary<string, object>)item;
sw.WriteLine(string.Join(",", dict.Values));
}
}
MessageBox.Show("保存成功!\n" + filePath);
}
2026-04-23 09:35:57 +08:00
/// <summary>
/// 计算单眼视野面积
/// </summary>
/// <param name="groupData">20组数据每组72个通道</param>
/// <param name="threshold">有效亮度阈值如80</param>
/// <param name="standardTotalArea">标准视野面积如120</param>
/// <returns>计算好的面积</returns>
///
public static double CalculateEyeArea(List<double[]> groupData, double threshold, double standardArea)
{
double[] avg = new double[72];
for (int c = 0; c < 72; c++)
{
double sum = 0;
foreach (var g in groupData) sum += g[c];
avg[c] = sum / groupData.Count;
}
int valid = avg.Count(v => v >= threshold);
return (valid / 72.0) * standardArea;
}
//计算单眼面积调用的方法
//double leftArea = CalculateEyeArea(
// leftEye20Groups, // 左眼20组数据
// 80, // 阈值
// 120 // 标准面积
//);
//double rightArea = .CalculateEyeArea(
// rightEye20Groups, // 右眼20组数据
// 80, // 阈值
// 120 // 标准面积
//);
}