public override void ClientEncode( ModbusCommand command, ByteArrayWriter body) { body.WriteUInt16BE((ushort)command.Offset); body.WriteUInt16BE(command.Data[0]); }
public override void ClientDecode( ModbusCommand command, ByteArrayReader body) { ModbusCodecBase.PopDiscretes( command, body); }
public override void ServerEncode( ModbusCommand command, ByteArrayWriter body) { ModbusCodecBase.PushDiscretes( command, body); }
public override void ServerEncode( ModbusCommand command, ByteArrayWriter body) { ModbusCodecBase.PushRequestHeader( command, body); }
public override void ClientDecode( ModbusCommand command, ByteArrayReader body) { ModbusCodecBase.PopRequestHeader( command, body); }
public void ExecuteAsync( ICommClient port, ModbusCommand command) { var data = new ClientCommData(this); data.UserData = command; Codec.ClientEncode(data); port.QueryAsync(data); }
public override void ClientDecode( ModbusCommand command, ByteArrayReader body) { var count = body.ReadByte() / 2; command.Data = new ushort[count]; for (int i = 0; i < count; i++) command.Data[i] = body.ReadUInt16BE(); }
public override void ServerEncode( ModbusCommand command, ByteArrayWriter body) { var count = command.Count; body.WriteByte((byte)(count * 2)); for (int i = 0; i < count; i++) body.WriteUInt16BE(command.Data[i]); }
public override void ServerDecode( ModbusCommand command, ByteArrayReader body) { ModbusCodecBase.PopRequestHeader( command, body); command.Data = new ushort[command.Count]; command.QueryTotalLength += 2; }
public override void ServerDecode( ModbusCommand command, ByteArrayReader body) { command.Offset = body.ReadUInt16BE(); command.Count = 1; command.QueryTotalLength += 2; command.Data = new ushort[1]; command.Data[0] = body.ReadUInt16BE(); }
public override void ServerDecode( ModbusCommand command, ByteArrayReader body) { ModbusCodecBase.PopRequestHeader( command, body); ModbusCodecBase.PopDiscretes( command, body); }
public override void ClientEncode( ModbusCommand command, ByteArrayWriter body) { body.WriteUInt16BE((ushort)command.Offset); var value = command.Data[0] != 0 ? 0xFF00 : 0; body.WriteInt16BE((short)value); }
public override void ClientEncode( ModbusCommand command, ByteArrayWriter body) { ModbusCodecBase.PushRequestHeader( command, body); ModbusCodecBase.PushDiscretes( command, body); }
public override void ClientEncode( ModbusCommand command, ByteArrayWriter body) { ModbusCodecBase.PushRequestHeader( command, body); var count = command.Count; body.WriteByte((byte)(count * 2)); for (int i = 0; i < count; i++) body.WriteUInt16BE(command.Data[i]); }
/// <summary> /// Entry-point for submitting any command /// </summary> /// <param name="port">The client port for the transport</param> /// <param name="command">The command to be submitted</param> /// <returns>The result of the query</returns> public CommResponse ExecuteGeneric( ICommClient port, ModbusCommand command) { var data = new ClientCommData(this); data.UserData = command; Codec.ClientEncode(data); var rVal = port.Query(data); if (data.OutgoingData != null) OnOutgoingData(data.OutgoingData.ToArray()); if (data.IncomingData != null) OnIncommingData(data.IncomingData.ToArray()); return rVal; }
public override void ServerDecode( ModbusCommand command, ByteArrayReader body) { ModbusCodecBase.PopRequestHeader( command, body); var count = body.ReadByte() / 2; command.Data = new ushort[count]; command.QueryTotalLength += (count + 3); for (int i = 0; i < count; i++) command.Data[i] = body.ReadUInt16BE(); }
public static void Main() { //setup the board IP NetworkInterface.GetAllNetworkInterfaces()[0] .EnableStaticIP("192.168.0.99", "255.255.255.0", "192.168.0.1"); string localip = NetworkInterface.GetAllNetworkInterfaces()[0] .IPAddress; Debug.Print("The local IP address of your Netduino Plus is " + localip); //define coils, inputs, and analogs _inputs = new InputPort[8]; #if SLAVE_RTU _inputs[0] = new InputPort(Pins.GPIO_PIN_D0, true, Port.ResistorMode.PullUp); _inputs[1] = new InputPort(Pins.GPIO_PIN_D1, true, Port.ResistorMode.PullUp); _inputs[2] = null; _inputs[3] = null; _inputs[4] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp); _inputs[5] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp); _inputs[6] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp); _inputs[7] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp); #else _inputs[0] = new InputPort(Pins.GPIO_PIN_D0, true, Port.ResistorMode.PullUp); _inputs[1] = new InputPort(Pins.GPIO_PIN_D1, true, Port.ResistorMode.PullUp); _inputs[2] = new InputPort(Pins.GPIO_PIN_D2, true, Port.ResistorMode.PullUp); _inputs[3] = new InputPort(Pins.GPIO_PIN_D3, true, Port.ResistorMode.PullUp); _inputs[4] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp); _inputs[5] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp); _inputs[6] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp); _inputs[7] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp); #endif _coils = new OutputPort[6]; _coils[0] = new OutputPort(Pins.GPIO_PIN_D8, false); _coils[1] = new OutputPort(Pins.GPIO_PIN_D9, false); _coils[2] = new OutputPort(Pins.GPIO_PIN_D10, false); _coils[3] = new OutputPort(Pins.GPIO_PIN_D11, false); _coils[4] = new OutputPort(Pins.GPIO_PIN_D12, false); _coils[5] = new OutputPort(Pins.GPIO_PIN_D13, false); #if MF_FRAMEWORK_VERSION_V4_1 _analogs = new AnalogInput[6]; _analogs[0] = new AnalogInput(Pins.GPIO_PIN_A0); _analogs[1] = new AnalogInput(Pins.GPIO_PIN_A1); _analogs[2] = new AnalogInput(Pins.GPIO_PIN_A2); _analogs[3] = new AnalogInput(Pins.GPIO_PIN_A3); _analogs[4] = new AnalogInput(Pins.GPIO_PIN_A4); _analogs[5] = new AnalogInput(Pins.GPIO_PIN_A5); #elif MF_FRAMEWORK_VERSION_V4_2 _analogs = new AnalogInput[6]; _analogs[0] = new AnalogInput(Cpu.AnalogChannel.ANALOG_0); _analogs[1] = new AnalogInput(Cpu.AnalogChannel.ANALOG_1); _analogs[2] = new AnalogInput(Cpu.AnalogChannel.ANALOG_2); _analogs[3] = new AnalogInput(Cpu.AnalogChannel.ANALOG_3); _analogs[4] = new AnalogInput(Cpu.AnalogChannel.ANALOG_4); _analogs[5] = new AnalogInput(Cpu.AnalogChannel.ANALOG_5); #endif #if MASTER_TCP //create a TCP socket using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { //refine the socket settings socket.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true ); socket.SendTimeout = 2000; socket.ReceiveTimeout = 2000; //try the connection against the remote device var remoteip = new byte[4] { 192, 168, 0, 100 }; var ipaddr = new IPAddress(remoteip); var ept = new IPEndPoint(ipaddr, 502); socket.Connect(ept); //create a wrapper around the socket ICommClient portClient = socket.GetClient(); //create a client driver var driver = new ModbusClient(new ModbusTcpCodec()); driver.Address = DeviceAddress; while (true) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncReadInputDiscretes); command.Offset = 0; command.Count = 6; //execute the command synchronously CommResponse result = driver .ExecuteGeneric(portClient, command); if (result.Status == CommResponse.Ack) { //command successfully for (int i = 0; i < command.Count; i++) { _coils[i + command.Offset].Write(command.Data[i] != 0); } } else { //some error Debug.Print("Error=" + command.ExceptionCode); } //just a small delay Thread.Sleep(100); } } #endif #if MASTER_UDP //create a UDP socket using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { //try the connection against the remote device var remoteip = new byte[4] { 192, 168, 0, 60 }; var ipaddr = new IPAddress(remoteip); var ept = new IPEndPoint(ipaddr, 502); socket.Connect(ept); //create a wrapper around the socket ICommClient portClient = socket.GetClient(); //create a client driver var driver = new ModbusClient(new ModbusTcpCodec()); driver.Address = DeviceAddress; while (true) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncReadMultipleRegisters); command.Offset = 0; command.Count = 16; //execute the command synchronously CommResponse result = driver .ExecuteGeneric(portClient, command); if (result.Status == CommResponse.Ack) { //command successfully Debug.Print("Success!"); for (int i = 0; i < command.Count; i++) { Debug.Print("Reg#" + i + "=" + command.Data[i]); } } else { //some error Debug.Print("Error=" + command.ExceptionCode); } //just a small delay Thread.Sleep(1000); } } #endif #if MASTER_RTU //create an UART port using (var uart = new SerialPortEx("COM2", 38400, Parity.Even, 8, StopBits.One)) { //open the serial port uart.Open(); var prm = new SerialPortParams("38400,E,8,1"); //create a wrapper around the uart ICommClient portClient = uart .GetClient(prm); //create a client driver var driver = new ModbusClient(new ModbusRtuCodec()); driver.Address = DeviceAddress; while (true) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncWriteMultipleRegisters); command.Offset = 49; command.Count = 4; //attach the Netduino's input values as data command.Data = new ushort[4]; for (int i = 0; i < 4; i++) { command.Data[i] = (ushort)(_inputs[i].Read() ? 0 : 1); } //execute the command synchronously CommResponse result = driver .ExecuteGeneric(portClient, command); if (result.Status == CommResponse.Ack) { //command successfully } else { //some error Debug.Print("Error=" + command.ExceptionCode); } //just a small delay Thread.Sleep(1000); } } #endif #if SLAVE_TCP //create a TCP socket using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { //place it as listener on the port 502 (standard Modbus) var ept = new IPEndPoint(IPAddress.Any, 502); socket.Bind(ept); socket.Listen(10); //create a server driver var server = new ModbusServer(new ModbusTcpCodec()); server.Address = DeviceAddress; while (true) { //wait for an incoming connection var listener = socket.GetTcpListener(server); listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand); listener.Start(); Thread.Sleep(1); } } #endif #if SLAVE_UDP //create a UDP socket using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { //bind it to the port 502 (standard Modbus) var ept = new IPEndPoint(IPAddress.Any, 502); socket.Bind(ept); //create a server driver var server = new ModbusServer(new ModbusTcpCodec()); server.Address = DeviceAddress; //listen for an incoming request var listener = socket.GetUdpListener(server); listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand); listener.Start(); Thread.Sleep(Timeout.Infinite); } #endif #if SLAVE_RTU //create an UART port using (var uart = new SerialPortEx("COM2", 38400, Parity.Even, 8, StopBits.One)) { //open the serial port uart.Open(); //create a server driver var server = new ModbusServer(new ModbusRtuCodec()); server.Address = DeviceAddress; while (true) { //wait for an incoming connection var listener = uart.GetServer(server); listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand); listener.Start(); while (listener.IsRunning) { Thread.Sleep(1); } } } #endif }
CommResponse IProtocolCodec.ServerDecode(CommDataBase data) { var server = (ModbusServer)data.OwnerProtocol; var incoming = data.IncomingData; //validate header first var length = incoming.Length; if (length < 4) goto LabelUnknown; //address var address = incoming.ReadByte(); if (address == server.Address) { //function code var fncode = incoming.ReadByte(); if (CommandCodecs.ContainsKey(fncode)) { //create a new command var command = new ModbusCommand(fncode); data.UserData = command; command.QueryTotalLength = 6; //= addr + fn + offset + crc //get the command codec var codec = CommandCodecs[fncode]; //decode the command, where possible var body = new ByteArrayReader(incoming.ReadBytes(length - 4)); codec.ServerDecode(command, body); //calculate the CRC-16 over the received stream ushort crcCalc = ByteArrayHelpers.CalcCRC16( incoming.ToArray(), 0, command.QueryTotalLength - 2); //validate the CRC-16 var crcRead = ByteArrayHelpers.ReadInt16LE( ((IByteArray)incoming).Data, command.QueryTotalLength - 2); if (crcRead == (short)crcCalc) { return new CommResponse( data, CommResponse.Ack); } } } //exception return new CommResponse( data, CommResponse.Ignore); LabelUnknown: return new CommResponse( data, CommResponse.Unknown); }
public void Write(ModbusCommand command, ref T tags) { Parse(command, ParserWrite, ref tags); }
protected void RunCore( ICommClient medium, ModbusClient driver, CancellationToken token) { Action <bool> setPollingActivity = act => HardwareModel.Instance.IsPollingEnabled = act; int stage = 0; while (token.IsCancellationRequested == false) { //turn the polling activity on App.Current.Dispatcher.BeginInvoke( setPollingActivity, true); if (stage == 0) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncReadInputDiscretes); command.Offset = 0; command.Count = 8; //execute the command synchronously CommResponse result = driver .ExecuteGeneric(medium, command); if (result.Status == CommResponse.Ack) { //command successfully for (int i = 0; i < command.Count; i++) { HardwareModel.Instance.Coils[i].Write(command.Data[i] != 0); } stage = 1; } else { //some error Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode); } } else if (stage == 1) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncReadInputRegisters); command.Offset = 0; command.Count = 6; //execute the command synchronously CommResponse result = driver .ExecuteGeneric(medium, command); if (result.Status == CommResponse.Ack) { //command successfully for (int i = 0; i < command.Count; i++) { HardwareModel.Instance.Analogs[i].Value = command.Data[i] / 1023.0; } stage = 2; } else { //some error Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode); } } else if (stage == 2) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncForceMultipleCoils); command.Offset = 0; command.Count = 6; //attach the Netduino's input values as data command.Data = new ushort[command.Count]; for (int i = 0; i < command.Count; i++) { command.Data[i] = (ushort)(HardwareModel.Instance.Discretes[i].Read() ? 1 : 0); } //execute the command synchronously CommResponse result = driver .ExecuteGeneric(medium, command); if (result.Status == CommResponse.Ack) { //command successfully stage = 0; } else { //some error Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode); } } //turn the polling activity off App.Current.Dispatcher.Invoke( setPollingActivity, false); //just a small delay Thread.Sleep(100); } }
/// <summary> /// Encode the client-side command toward the remote slave device /// </summary> /// <param name="command"></param> /// <param name="body"></param> public virtual void ClientEncode( ModbusCommand command, ByteArrayWriter body) { }
private void Parse(ModbusCommand command, ParserAction ParserAction, ref T tags) { TagUsedLastRW.Clear(); foreach (KeyValuePair <string, int> p in Addresses) { FieldInfo tag = tags.GetType().GetField(p.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); int Address = p.Value; try { if (tag != null) { int len = TagsSize[tag.Name]; int offset = (((Address) >= command.Offset) && ((Address) < (command.Offset + command.Count))) ? offset = (Address) - command.Offset : -1; for (int i = 0; i < len; i++) { int step; string tp = tag.FieldType.Name.Replace("[]", ""); if ((tp == "DateTime") || (tp == "UInt32") || (tp == "Single")) { step = 2; } else { step = 1; } bool offset_i = (((Address + i * step) >= command.Offset) && ((Address + i * step + step - 1) < (command.Offset + command.Count))); if (offset_i) { Object value = tag.GetValue(tags); if (len != 1) { Array arr = value as Array; value = arr.GetValue(i); } ParserAction(tag.Name, offset, i, command, value, out Object Result); if (Result != null) { if (len != 1) { Array arr = tag.GetValue(tags) as Array; arr.SetValue(Result, i); } else { tag.SetValue(tags, Result); } } } } if (offset != -1) { try { string nn = tag.Name.IndexOf('_') == 0 ? tag.Name.Substring(1) : tag.Name; TagUsedLastRW.Add(nn); } catch (Exception e) { } } } } finally { } } }
public override void ClientDecode( ModbusCommand command, ByteArrayReader body) { //not used }
public override void ServerEncode(ModbusCommand command, ByteArrayWriter body) => ModbusCodecBase.PushRequestHeader(command, body);
CommResponse IProtocolCodec.ServerDecode(CommDataBase data) { var server = (ModbusServer)data.OwnerProtocol; var incoming = data.IncomingData; //validate header first var length = incoming.Length; if (length < 4) { goto LabelUnknown; } //address var address = incoming.ReadByte(); if (address == server.Address) { //function code var fncode = incoming.ReadByte(); if (CommandCodecs.ContainsKey(fncode)) { //create a new command var command = new ModbusCommand(fncode); data.UserData = command; command.QueryTotalLength = 6; //= addr + fn + offset + crc //get the command codec var codec = CommandCodecs[fncode]; //decode the command, where possible var body = new ByteArrayReader(incoming.ReadBytes(length - 4)); codec.ServerDecode(command, body); //calculate the CRC-16 over the received stream ushort crcCalc = ByteArrayHelpers.CalcCRC16( incoming.ToArray(), 0, command.QueryTotalLength - 2); //validate the CRC-16 var crcRead = ByteArrayHelpers.ReadInt16LE( ((IByteArray)incoming).Data, command.QueryTotalLength - 2); if (crcRead == (short)crcCalc) { return(new CommResponse( data, CommResponse.Ack)); } } } //exception return(new CommResponse( data, CommResponse.Ignore)); LabelUnknown: return(new CommResponse( data, CommResponse.Unknown)); }
private void IllegalFunction(ModbusCommand command) { AppendLog(String.Format("Illegal Function, expecting function code {0}.", FunctionCode)); command.ExceptionCode = ModbusCommand.ErrorIllegalFunction; }
public override void ClientDecode(ModbusCommand command, ByteArrayReader body) => ModbusCodecBase.PopRequestHeader(command, body);
/// <summary> /// Encode the server-side command toward the master remote device /// </summary> /// <param name="command"></param> /// <param name="body"></param> public virtual void ServerEncode( ModbusCommand command, ByteArrayWriter body) { }
public override void ServerDecode(ModbusCommand command, ByteArrayReader body) { ModbusCodecBase.PopRequestHeader(command, body); ModbusCodecBase.PopDiscretes(command, body); }
public void Read(ModbusCommand command, ref T tags) { Parse(command, ParserRead, ref tags); }
void ParserRead(string TagName, int offset, int index, ModbusCommand command, Object Current, out Object Result) { string k = Addresses[TagName] + ":" + index; string k_str = TagName + ":" + index; TagsChanged[k] = true; Result = null; try { int step = 2 * index; if (Current.GetType().Name == typeof(DateTime).Name) { double ts = ((ulong)(command.Data[offset + 1 + step]) << 16) + (ulong)command.Data[offset + step]; DateTime NewVal = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).AddSeconds(ts); if (StoredTagsValues.ContainsKey(k)) { TagsChanged[k] = IsEq <DateTime>(NewVal, (DateTime)StoredTagsValues[k]) ? false : true; StoredTagsValues[k] = NewVal; } else { StoredTagsValues.Add(k, NewVal); } Result = NewVal; } if (Current.GetType().Name == typeof(Int16).Name) { Int16 NewVal = command.Data[offset + index] > 0xffff ? (Int16)((long)command.Data[offset + index] - 0x10000) : (Int16)command.Data[offset + index]; if (StoredTagsValues.ContainsKey(k)) { TagsChanged[k] = IsEq <Int16>(NewVal, (Int16)StoredTagsValues[k]) ? false : true; StoredTagsValues[k] = NewVal; } else { StoredTagsValues.Add(k, NewVal); } Result = NewVal; } if (Current.GetType().Name == typeof(UInt16).Name) { UInt16 NewVal = command.Data[offset + index]; if (StoredTagsValues.ContainsKey(k)) { TagsChanged[k] = IsEq <UInt16>(NewVal, (UInt16)StoredTagsValues[k]) ? false : true; StoredTagsValues[k] = NewVal; } else { StoredTagsValues.Add(k, NewVal); } Result = NewVal; } if (Current.GetType().Name == typeof(UInt32).Name) { UInt32 NewVal = (UInt32)(command.Data[offset + step] << 16) + command.Data[offset + step + 1]; if (StoredTagsValues.ContainsKey(k)) { TagsChanged[k] = IsEq <UInt32>(NewVal, (UInt32)StoredTagsValues[k]) ? false : true; StoredTagsValues[k] = NewVal; } else { StoredTagsValues.Add(k, NewVal); } Result = NewVal; } if (Current.GetType().Name == typeof(Single).Name) { Single NewVal = ByteArrayHelpers.ReadIEEE(command.Data, offset + step); if (StoredTagsValues.ContainsKey(k)) { if (Precisions.ContainsKey(k_str)) { TagsChanged[k] = Math.Abs(NewVal - (Single)StoredTagsValues[k]) > (Single)Precisions[k_str] ? true : false; } else { TagsChanged[k] = IsEq <Single>(NewVal, (Single)StoredTagsValues[k]) ? false : true; } StoredTagsValues[k] = NewVal; } else { StoredTagsValues.Add(k, NewVal); } Result = NewVal; } } catch (Exception e) { Console.WriteLine(TagName + "[" + index + "] " + e.Message); Result = null; } finally { } }
/// <summary> /// Decode the incoming data from the remote slave device /// to a client-side command /// </summary> /// <param name="command"></param> /// <param name="body"></param> public virtual void ClientDecode( ModbusCommand command, ByteArrayReader body) { }
/// <summary> /// Decode the incoming data from the remote master device /// to a server-side command /// </summary> /// <param name="command"></param> /// <param name="body"></param> public virtual void ServerDecode( ModbusCommand command, ByteArrayReader body) { }
public override void ClientEncode(ModbusCommand command, ByteArrayWriter body) { ModbusCodecBase.PushRequestHeader(command, body); ModbusCodecBase.PushDiscretes(command, body); }