public async Task <Tuple <ushort[], bool[]> > ReadRegistersAndCoilsAsync(int regAddress, int regLength, int coilAddr, int coilLength) { ushort[] regData; bool[] coilData; if (this.CheckConnection()) { try { using TcpClient client = new TcpClient(this.IpAddress, this.Port); ModbusIpMaster master = ModbusIpMaster.CreateIp(client); if (this.SlaveAddress != 0) { regData = await master.ReadHoldingRegistersAsync(this.SlaveAddress, (ushort)regAddress, (ushort)regLength); coilData = await master.ReadCoilsAsync(this.SlaveAddress, (ushort)coilAddr, (ushort)coilLength); } else { regData = await master.ReadHoldingRegistersAsync((ushort)regAddress, (ushort)regLength); coilData = await master.ReadCoilsAsync((ushort)coilAddr, (ushort)coilLength); } client.Close(); master.Dispose(); return(new Tuple <ushort[], bool[]>(regData, coilData)); } catch { return(null); } } return(null); }
public async Task <ushort[]> ReadRegistersAsync(int address, int length) { ushort[] regData; if (this.CheckConnection()) { try { using TcpClient client = new TcpClient(this.IpAddress, this.Port); ModbusIpMaster master = ModbusIpMaster.CreateIp(client); if (this.SlaveAddress != 0) { regData = await master.ReadHoldingRegistersAsync(this.SlaveAddress, (ushort)address, (ushort)length); } else { regData = await master.ReadHoldingRegistersAsync((ushort)address, (ushort)length); } client.Close(); master.Dispose(); return(regData); } catch { return(null); } } return(null); }
public async Task <ushort[]> ReadRegistersAsync(FunctionCode fc, int baseAddress, int length) { ushort[] regData; if (this.CheckConnection()) { try { using TcpClient client = new TcpClient(this.IpAddress, this.Port); ModbusIpMaster master = ModbusIpMaster.CreateIp(client); switch (fc) { case FunctionCode.ReadInputRegisters: { regData = await master.ReadInputRegistersAsync(this.SlaveAddress, (ushort)baseAddress, (ushort)length); client.Close(); master.Dispose(); return(regData); } case FunctionCode.ReadHoldingRegisters: { regData = await master.ReadHoldingRegistersAsync(this.SlaveAddress, (ushort)baseAddress, (ushort)length); client.Close(); master.Dispose(); return(regData); } default: { client.Close(); master.Dispose(); return(null); } } } catch { return(null); } } return(null); }
private async Task Broadcast() { ushort[] regData; bool[] coilData; using (FacilityContext context = new FacilityContext()) { ModbusDevice device = context.ModbusDevices.FirstOrDefault(x => x.Identifier == "NH3_Box"); if (device != null) { using (TcpClient client = new TcpClient(device.IpAddress, device.Port)) { ModbusIpMaster master = ModbusIpMaster.CreateIp(client); regData = await master.ReadHoldingRegistersAsync(0, 70); coilData = await master.ReadCoilsAsync(0, 10); client.Close(); } AmmoniaBoxReading reading = new AmmoniaBoxReading(DateTime.Now, "Tank 2 Loaded", device); reading.Tank1Weight = BitConverter.ToInt32(BitConverter.GetBytes(regData[1]).Concat(BitConverter.GetBytes(regData[0])).ToArray(), 0); reading.Tank2Weight = BitConverter.ToInt32(BitConverter.GetBytes(regData[3]).Concat(BitConverter.GetBytes(regData[2])).ToArray(), 0); reading.Tank3Weight = BitConverter.ToInt32(BitConverter.GetBytes(regData[5]).Concat(BitConverter.GetBytes(regData[4])).ToArray(), 0); reading.Tank4Weight = BitConverter.ToInt32(BitConverter.GetBytes(regData[7]).Concat(BitConverter.GetBytes(regData[6])).ToArray(), 0); reading.Tank1Tare = (int)regData[56]; reading.Tank2Tare = (int)regData[57]; reading.Tank3Tare = (int)regData[58]; reading.Tank4Tare = (int)regData[59]; reading.Tank1Temperature = (int)regData[60]; reading.Tank2Temperature = (int)regData[61]; reading.Tank3Temperature = (int)regData[62]; reading.Tank4Temperature = (int)regData[63]; reading.Heater1DutyCycle = (int)regData[66]; reading.Heater2DutyCycle = (int)regData[67]; reading.Heater3DutyCycle = (int)regData[68]; reading.Heater4DutyCycle = (int)regData[69]; reading.Tank1Warning = coilData[2]; reading.Tank2Warning = coilData[3]; reading.Tank3Warning = coilData[4]; reading.Tank4Warning = coilData[5]; reading.Tank1Alarm = coilData[6]; reading.Tank2Alarm = coilData[7]; reading.Tank3Alarm = coilData[8]; reading.Tank4Alarm = coilData[9]; this._dataViews[0].Weight = Convert.ToDecimal(reading.Tank1Weight); this._dataViews[0].Temperature = Convert.ToDecimal(reading.Tank1Temperature); this._dataViews[0].Status = "Online"; this._dataViews[0].Alarm = (reading.Tank1Alarm) ? "Ammonia Is Below Limit" : "Okay"; this._dataViews[0].Warning = (reading.Tank1Alarm) ? "Ammonia Is Getting Low" : "Okay"; this._dataViews[1].Weight = Convert.ToDecimal(reading.Tank2Weight); this._dataViews[1].Temperature = Convert.ToDecimal(reading.Tank2Temperature); this._dataViews[1].Status = "Online"; this._dataViews[1].Alarm = (reading.Tank2Alarm) ? "Ammonia Is Below Limit" : "Okay"; this._dataViews[1].Warning = (reading.Tank2Alarm) ? "Ammonia Is Getting Low" : "Okay"; this._dataViews[2].Weight = Convert.ToDecimal(reading.Tank3Weight); this._dataViews[2].Temperature = Convert.ToDecimal(reading.Tank3Temperature); this._dataViews[2].Status = "Online"; this._dataViews[2].Alarm = (reading.Tank3Alarm) ? "Ammonia Is Below Limit" : "Okay"; this._dataViews[2].Warning = (reading.Tank3Alarm) ? "Ammonia Is Getting Low" : "Okay"; this._dataViews[3].Weight = Convert.ToDecimal(reading.Tank4Weight); this._dataViews[3].Temperature = Convert.ToDecimal(reading.Tank4Temperature); this._dataViews[3].Status = "Online"; this._dataViews[3].Alarm = (reading.Tank4Alarm) ? "Ammonia Is Below Limit" : "Okay"; this._dataViews[3].Warning = (reading.Tank4Alarm) ? "Ammonia Is Getting Low" : "Okay"; await this._hubContext.Clients.All.BroadcastAllTanks(this._dataViews); } } }
private bool RequestData(IO_DEVICE device, RealData realData, out string error, ModbusFragmentStore fragmentstore) { error = ""; try { if (udpClient != null) { //分段读取数据,如果是读取整个寄存器的话,一次只能最多读取123个, //如果是读取线圈的话最大只能读取1999个,因此要分段进行数据的读取 List <byte> allbytes = new List <byte>(); try { for (int i = 0; i < fragmentstore.Fragments.Count; i++) { ModbusFragment fragment = fragmentstore.Fragments[i]; switch (fragment.Code) { case "01": // 01和05是一个码 可写可读 { //返回的线圈状态,由于线圈是按位操作,转换也是按位转换 Task <bool[]> result = master.ReadCoilsAsync(byte.Parse(device.IO_DEVICE_ADDRESS), fragment.StartRegister, fragment.RegisterNum); byte[] bytes = ModbusConvert.BoolToByte(result.Result); fragment.StartIndex = allbytes.Count; fragment.Length = bytes.Length; allbytes.AddRange(bytes); } break; case "02": //只读属性 { //返回的线圈状态 Task <bool[]> result = master.ReadInputsAsync(byte.Parse(device.IO_DEVICE_ADDRESS), fragment.StartRegister, fragment.RegisterNum); byte[] bytes = ModbusConvert.BoolToByte(result.Result); fragment.StartIndex = allbytes.Count; fragment.Length = bytes.Length; allbytes.AddRange(bytes); } break; case "03": //HR保持寄存器,可写可读 { //返回的数据全部是ushort 需要将ushort 转换为byte在进行传递 Task <ushort[]> result = master.ReadHoldingRegistersAsync(byte.Parse(device.IO_DEVICE_ADDRESS), fragment.StartRegister, fragment.RegisterNum); byte[] bytes = ModbusConvert.Ushorts2Bytes(result.Result); fragment.StartIndex = allbytes.Count; fragment.Length = bytes.Length; allbytes.AddRange(bytes); } break; case "04": //只读属性 { //返回的数据全部是ushort 需要将ushort 转换为byte在进行传递 Task <ushort[]> result = master.ReadInputRegistersAsync(byte.Parse(device.IO_DEVICE_ADDRESS), fragment.StartRegister, fragment.RegisterNum); byte[] bytes = ModbusConvert.Ushorts2Bytes(result.Result); fragment.StartIndex = allbytes.Count; fragment.Length = bytes.Length; allbytes.AddRange(bytes); } break; } } } catch { //读取异常处理 this.DeviceStatus(this.IOServer, this.IOCommunication, device, null, "0");//tag为1表示上线,如果为0表示下线 } //将数据返回到采集客户端 if (allbytes.Count > 0) { device.IO_DEVICE_STATUS = 1; ReceiveData(this.IOServer, this.IOCommunication, device, allbytes.ToArray(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), fragmentstore); //设置设备状态 this.DeviceStatus(this.IOServer, this.IOCommunication, device, null, "1");//tag为1表示上线,如果为0表示下线 } else { device.IO_DEVICE_STATUS = 0; //设置设备状态 this.DeviceStatus(this.IOServer, this.IOCommunication, device, null, "0");//tag为1表示上线,如果为0表示下线 } } return(true); } catch { return(false); } }
public override async Task SendAsync(IConfigurationRoot root) { ModbusTcpManager.RebootModbusTcp = false; int iFrequency = 0; YamlBase.Modules.Where(c => c.Launcher == nameof(Communication.ModbusTcp)).Select(c => new { c.Frequency }).ToList().ForEach(c => { iFrequency = c.Frequency; }); List <MachineShell> MachineBoxes = new(); root.GetSection(nameof(ModbusTcpTitle.MachineBox)).GetChildren().Select(c => new { machineNo = c.GetValue <string>(nameof(ModbusTcpRoot.MachineNo)), production = c.GetValue <bool>(nameof(ModbusTcpRoot.Production)), disabled = c.GetValue <bool>(nameof(ModbusTcpRoot.Disabled)), vesion = c.GetValue <string>(nameof(ModbusTcpRoot.Version)), address = c.GetValue <string>(nameof(ModbusTcpRoot.Address)), port = c.GetValue <int>(nameof(ModbusTcpRoot.Port)), map = c.GetSection(nameof(ModbusTcpRoot.Map)).GetChildren().Select(c => new { disabled = c.GetValue <bool>(nameof(ElementBox.Disabled)), channel = c.GetValue <string>(nameof(ElementBox.Channel)), functionCode = c.GetValue <int>(nameof(ElementBox.FunctionCode)), slaveAddress = c.GetValue <byte>(nameof(ElementBox.SlaveAddress)), startAddress = c.GetValue <ushort>(nameof(ElementBox.StartAddress)), Points = c.GetSection(nameof(ElementBox.NumberOfPoints)).GetChildren().Select(c => new { pointNo = c.GetValue <int>(nameof(Numberofpoint.PointNo)), attribName = c.GetValue <string>(nameof(Numberofpoint.AttribName)) }).ToList() }).ToList() }).ToList().ForEach(c => { if (c.disabled) { return; } List <MessageBox> boxes = new(); c.map.ForEach(c => { if (c.disabled) { return; } HostChannel Channel = c.channel switch { nameof(HostChannel.Status) => HostChannel.Status, nameof(HostChannel.Parameter) => HostChannel.Parameter, nameof(HostChannel.Production) => HostChannel.Production, _ => HostChannel.Undefined }; if (Channel == HostChannel.Undefined) { return; } List <PickPoint> points = new(); c.Points.ForEach(c => { points.Add(new() { PointNo = c.pointNo, AttribName = c.attribName }); }); boxes.Add(new() { Channel = Channel, FunctionCode = c.functionCode, SlaveAddress = c.slaveAddress, StartAddress = c.startAddress, PickPoints = points }); }); MachineBoxes.Add(new() { MachineNo = c.machineNo, Production = c.production, Vesion = c.vesion, Address = c.address, Port = c.port, MessageBoxes = boxes }); }); void Working(object obj) { MachineBoxes.ForEach(async c => { await Task.Run(() => { int iPort = c.Port; string sMachineNo = c.MachineNo, sAddress = c.Address; lock (MachineSwitch) if (!MachineSwitch.ContainsKey(sMachineNo)) { MachineSwitch.Add(sMachineNo, true); } c.MessageBoxes.ForEach(async c => { try { if (c.PickPoints.Count == 0) { return; } using TcpClient client = new TcpClient(sAddress, iPort); using ModbusIpMaster master = ModbusIpMaster.CreateIp(client); ushort[] result = await master.ReadHoldingRegistersAsync(c.SlaveAddress, c.StartAddress, Convert.ToUInt16(c.PickPoints.Count)); if (result == null || result.Length == 0) { return; } MachineSwitch[sMachineNo] = true; c.PickPoints.ForEach(c => { string sKey = sMachineNo + "#" + c.AttribName; lock (RowBox) { if (!RowBox.ContainsKey(sKey)) { RowBox.Add(sKey, result[c.PointNo]); } else { RowBox[sKey] = result[c.PointNo]; } } }); } catch (Exception e) { if (MachineSwitch[sMachineNo] == true) { //webapi <== Console.WriteLine($" No.{sMachineNo} => {e.Message}"); } MachineSwitch[sMachineNo] = false; } }); }); }); } await Task.Run(() => { try { Callback += new TimerCallback(Working); Callback += new TimerCallback(RocketLaunch); Timer = new Timer(Callback, null, Timeout.Infinite, iFrequency); Timer.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(iFrequency)); } catch (Exception e) { Console.WriteLine("sMMP => " + e.Message + "\n" + e.StackTrace); } }); void RocketLaunch(object obj) { MachineBoxes.ToList().ForEach(async c => { await Task.Run(() => { bool bProduction = c.Production; string sMachineNo = c.MachineNo, sVersion = c.Vesion; List <Parameter> parameters = new(); c.MessageBoxes.ForEach(c => { c.PickPoints.ForEach(c => { string sKey = sMachineNo + "#" + c.AttribName; if (RowBox.ContainsKey(sKey)) { lock (HistoryBox) { if (!HistoryBox.ContainsKey(sKey)) { HistoryBox.Add(sKey, RowBox[sKey]); } else { if (RowBox[sKey] != HistoryBox[sKey]) { parameters.Add(new() { AttribNo = c.AttribName, AttribValue = RowBox[sKey] }); HistoryBox[sKey] = RowBox[sKey]; } } } } }); GlobalVariables globally = new(); GlobalApproach.PushDataToHost(c.Channel, new() { Version = sVersion, Production = bProduction, MachineNo = sMachineNo, ReportDateTime = globally.NowTime, Row = parameters }); }); }); }); } }