您现在的位置是:网站首页> 编程资料编程资料
详解.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; }
相关内容
- ASP.NET Core使用EF为关系数据库建模_实用技巧_
- ASP.NET Core使用EF创建模型(索引、备用键、继承、支持字段)_实用技巧_
- ASP.NET Core使用EF创建关系模型_实用技巧_
- ASP.NET Core使用EF创建模型(必需和可选属性、最大长度、并发标记、阴影属性)_实用技巧_
- ASP.NET Core使用EF创建模型(包含属性、排除属性、主键和生成值)_实用技巧_
- ASP.NET Core基于现有数据库创建EF模型_实用技巧_
- Entity Framework Core基于数据模型创建数据库_实用技巧_
- ASP.NET Core中的通用主机HostBuilder_基础应用_
- ASP.NET Core配置和管理Web主机_基础应用_
- ASP.NET Core记录日志_实用技巧_
点击排行
本栏推荐
