您现在的位置是:网站首页> 编程资料编程资料

详解.NET6下的Modbus通讯和数据库记录_实用技巧_

2023-05-24 481人已围观

简介 详解.NET6下的Modbus通讯和数据库记录_实用技巧_

所用的包:

        WinExe     net6.0-windows     enable     true     enable                                                                             all             runtime; build; native; contentfiles; analyzers; buildtransitive                                                                                                  PreserveNewest            

通信库:

using Modbus.Device; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using thinger.DataConvertLib; namespace EF6Demon {     public class NModBusHelper     {         private TcpClient tcpClient = null;         private ModbusIpMaster master;         public bool Connect(string ip, string port)         {             try             {                 tcpClient = new TcpClient();                 tcpClient.Connect(IPAddress.Parse(ip), int.Parse(port));                 master = ModbusIpMaster.CreateIp(tcpClient);             }             catch (Exception)             {                 return false;             }                          return tcpClient.Connected;         }         public bool Disconnect()         {             if (tcpClient != null)             {                 tcpClient.Close();                 return true;             }             else             {                 return false;             }         }                  public byte[] ReadKeepRegByteArr(string iAddress, string iLength)//偏移量,寄存器数量         {             try             {                 ushort[] des = master.ReadHoldingRegisters(ushort.Parse(iAddress), ushort.Parse(iLength));                 byte[] res = ByteArrayLib.GetByteArrayFromUShortArray(des);                 return res;             }             catch (Exception)             {                 return null;             }         }         public ushort[] ReadKeepRegUshort(string iAddress, string iLength)//偏移量,寄存器数量         {             try             {                 ushort[] des = master.ReadHoldingRegisters(ushort.Parse(iAddress), ushort.Parse(iLength));                 //byte[] res = ByteArrayLib.GetByteArrayFromUShortArray(des);                 return des;             }             catch (Exception)             {                 return null;             }         }         public List AnalyseData_4x(ushort[] des, string iAddress)         {             int StartByte;             StartByte = int.Parse(iAddress) * 2;             List floatArray = new List();             byte[] byteArray = ByteArrayLib.GetByteArrayFromUShortArray(des);             for (int i = StartByte; i < byteArray.Length; i += 4)             {                 floatArray.Add(FloatLib.GetFloatFromByteArray(byteArray, i));             }             return floatArray;         }     } }

主程序:

using Microsoft.Extensions.Configuration; using thinger.DataConvertLib; namespace EF6Demon {     public partial class FrmMain : Form     {         public FrmMain()         {             InitializeComponent();             this.Load += FrmMain_Load;         }         private ModelsResponsitory dbContext = new ModelsResponsitory();         private ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();         private IConfigurationRoot configRoot;         private CancellationTokenSource cts = new CancellationTokenSource();         ushort[] res;         string iAddress = "0";         string iLenth; //寄存器个数         private List floatList = new List();         private CancellationTokenSource cts1 = new CancellationTokenSource();         InsertDataSQLite objInsert = new InsertDataSQLite(10000);//10秒1次         private NModBusHelper objTcp;         private void FrmMain_Load(object? sender, EventArgs e)         {             //读取IP;             cfgBuilder.AddJsonFile("VariableNode.json", optional: true, reloadOnChange: true);             this.configRoot = cfgBuilder.Build();             CommonMethods.Ip = configRoot.GetSection("NodeClass:ModbusNode:ServerURL").Value;             CommonMethods.Port = configRoot.GetSection("NodeClass:ModbusNode:Port").Value;             CommonMethods.VarNum = configRoot.GetSection("NodeClass:ModbusNode:VarNum").Value;             //读取点表信息             //for (int i = 0; i < int.Parse(CommonMethods.VarNum); i++)             //{             //    Variable variable = configRoot.GetSection($"NodeClass:ModbusNode:ModbusGroup:Variable:{i}").Get();             //    CommonMethods.AllVarList.Add(variable);             //}             this.iLenth = configRoot.GetSection("NodeClass:ModbusNode:ModbusGroup:Length").Value;             CommonMethods.ModbusTCPList = dbContext.GetAllVariable();             foreach (var item in CommonMethods.ModbusTCPList)             {                 foreach (var item1 in item.ModbusNodes)                 {                     foreach (var item2 in item1.ModbusGroups)                     {                         CommonMethods.AllVarList.AddRange(item2.Variables);                     }                 }             }             InsertDataSQLite objInsert = new InsertDataSQLite(10000);//10秒1次             ModbusTCPInitialInfo();             Communication();         }         private void Communication()         {             if (CommonMethods.ModbusTCPList.Count() > 0)             {                 foreach (var t in CommonMethods.ModbusTCPList)                 {                     foreach (var dev in t.ModbusNodes)                     {                         if (bool.Parse(dev.IsActive))                         {                             Task.Run(async () =>                             {                                 while (!cts1.IsCancellationRequested)                                 {                                     if (CommonMethods.IsConnected)                                     {                                         await Task.Delay(500);                                         foreach (var gp in dev.ModbusGroups)                                         {                                             if (bool.Parse(gp.IsActive))                                             {                                                 //读取数据                                                 byte[] res = null;                                                 if (int.Parse(gp.StoreArea) == 40000)                                                 {                                                     res = objTcp.ReadKeepRegByteArr(gp.Start, gp.Length);                                                 }                                                 if (res != null && res.Length == int.Parse(gp.Length) * 2)                                                 {                                                     CommonMethods.ErrorTimes = 0;                                                     foreach (var variable in gp.Variables)                                                     {                                                         if (VerifyModbusAddress(false, variable.VarAddress, out int start, out int offset))                                                         {                                                             start -= int.Parse(gp.Start);                                                             start *= 2;                                                             // ABCD = 0,BADC = 1, CDAB = 2, DCBA = 3,                                                             switch (variable.VarType)                                                             {                                                                 case "Float":                                                                     variable.Value = FloatLib.GetFloatFromByteArray(res, start, DataFormat.ABCD).ToString();                                                                     break;                                                                 case "UShort":                                                                     variable.Value = UShortLib.GetUShortFromByteArray(res, start, DataFormat.ABCD).ToString();                                                                     break;                                                                 default:                                                                     break;                                                             }            
                
                

-六神源码网