Modbus设备信息加载的实现方式有很多种,这里讨论一种实现,思路比代码重要,具体类大家可以按自己的要求构建。
Load窗体事件中:
GlobalProperties.Device = LoadDevice(GroupPath, DevicePath, VariablePath);
具体的实现为, 这样所有的设备,参数
cs
/// <summary>
/// 添加设备信息
/// </summary>
/// <param name="groupPath"></param>
/// <param name="devicePath"></param>
/// <param name="variablePath"></param>
/// <returns></returns>
private Device LoadDevice(string groupPath, string devicePath, string variablePath)
{
if (!File.Exists(groupPath))
{
GlobalProperties.AddLog(1, "通信组文件不存在");
return null;
}
List<Group> GpList = LoadGroup(groupPath, variablePath);
if (GpList != null && GpList.Count > 0)
{
try
{
return new Device()
{
IPAddress = IniHelper.ReadDefult("设备参数", "IP地址", "", devicePath),
Port = Convert.ToInt32(IniHelper.ReadDefult("设备参数", "端口号", "502", devicePath)),
CurrentRecipe = IniHelper.ReadDefult("配方参数", "当前配方", "", devicePath),
GroupList = GpList,
};
}
catch (Exception ex)
{
GlobalProperties.AddLog(1, "通信组加载失败:" + ex.Message);
return null;
}
}
else
{
return null;
}
}
通信组及通信变量解析:
cs
/// <summary>
/// 通信组及通信变量解析
/// </summary>
/// <param name="groupPath"></param>
/// <param name="variablePath"></param>
/// <returns></returns>
private List<Group> LoadGroup(string groupPath, string variablePath)
{
//判断文件是否存在
if (!File.Exists(groupPath))
{
GlobalProperties.AddLog(1, "通信组文件不存在");
return null;
}
if (!File.Exists(variablePath))
{
GlobalProperties.AddLog(1, "通信变量文件不存在");
return null;
}
//解析通信组
List<Group> GpList = null;
try
{
GpList = MiniExcel.Query<Group>(groupPath).ToList();
}
catch (Exception ex)
{
GlobalProperties.AddLog(1, "通信组加载失败:" + ex.Message);
return null;
}
//解析变量组,把variable添加到每个group中
List<Variable> VarList = null;
try
{
VarList = MiniExcel.Query<Variable>(variablePath).ToList();
}
catch (Exception ex)
{
GlobalProperties.AddLog(1, "通信变量加载失败:" + ex.Message);
return null;
}
if (VarList != null && GpList != null)
{
foreach (var group in GpList)
{
group.VarList = VarList.FindAll(c => c.GroupName == group.GroupName).ToList();
}
return GpList;
}
else
{
return null;
}
}
C# Modbus设备信息加载的实现方式(2)-CSDN博客
https://blog.csdn.net/danielli/article/details/139994130?utm_relevant_index=8