private async void QueryDiscretes() { await TaskEx.Run(() => { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncReadInputDiscretes); command.Offset = 0; command.Count = InputCount; //execute the command synchronously CommResponse result = App.Modbus .ExecuteGeneric(App.Client, command); if (result.Status == CommResponse.Ack) { //command successfully Deployment.Current.Dispatcher.BeginInvoke(new Action(() => { for (int i = 0; i < command.Count; i++) { var input = this._inputs[i]; input.Value = command.Data[input.Offset] == 0; } })); } else { //some error } this._status = MachineState.CoilRequest; }); }
private void ExecuteWriteCommand(byte function) { try { ModbusCommand command = new ModbusCommand(function) { Offset = (int)this.StartAddress, Count = (int)this.DataLength, TransId = this._transactionId++, Data = new ushort[(int)this.DataLength] }; for (int index1 = 0; index1 < (int)this.DataLength; ++index1) { int index2 = (int)this.StartAddress + index1; if (index2 <= this._registerData.Length) { command.Data[index1] = this._registerData[index2]; } else { break; } } CommResponse commResponse = this._driver.ExecuteGeneric(this._portClient, command); this.AppendLog(commResponse.Status == 3 ? string.Format("Write succeeded: Function code:{0}", (object)function) : string.Format("Failed to execute Write: Error code:{0}", (object)commResponse.Status)); } catch (Exception ex) { this.AppendLog(ex.Message); } }
private async void QueryCoils() { await TaskEx.Run(() => { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncForceMultipleCoils); command.Offset = 0; command.Count = CoilCount; command.Data = new ushort[CoilCount]; for (int i = 0; i < CoilCount; i++) { var output = this._outputs[i]; command.Data[output.Offset] = (ushort)(output.Value ? 1 : 0); } //execute the command synchronously CommResponse result = App.Modbus .ExecuteGeneric(App.Client, command); if (result.Status == CommResponse.Ack) { //command successfully } else { //some error } this._status = MachineState.AnalogRequest; }); }
public bool ExecuteRead(int Offset, int Count) { if (medium == null) { throw new Exception("Medium is not yet initialyzed"); } FuncReadMultipleRegisters.Offset = Offset; FuncReadMultipleRegisters.Count = Count; CommResponse Response = driver.ExecuteGeneric(medium, FuncReadMultipleRegisters, 3, 500); if ((Response.Status == CommResponse.Ack) && (Response.Data.IncomingData != null)) { adapter.Read((ModbusCommand)Response.Data.UserData, ref RegistersData); foreach (string tagname in adapter.TagUsedLastRW) { RegistersData.OnPropertychanged(tagname); RegistersData.OnDeviceRegistersRead(tagname); } return(true); } else { return(false); } }
private void ExecuteReadCommand(byte function) { try { ModbusCommand command = new ModbusCommand(function) { Offset = (int)this.StartAddress, Count = (int)this.DataLength, TransId = this._transactionId++ }; CommResponse commResponse = this._driver.ExecuteGeneric(this._portClient, command); if (commResponse.Status == 3) { command.Data.CopyTo((Array)this._registerData, (int)this.StartAddress); this.UpdateDataTable(); this.AppendLog(string.Format("Read succeeded: Function code:{0}.", (object)function)); } else { this.AppendLog(string.Format("Failed to execute Read: Error code:{0}", (object)commResponse.Status)); } } catch (Exception ex) { this.AppendLog(ex.Message); } }
public CommResponse ExecuteReadCommand(byte function, ushort StartAddress, ushort DataLength) { CommResponse result = null; try { var command = new ModbusCommand(function) { Offset = StartAddress, Count = DataLength, TransId = _transactionId++ }; result = _driver.ExecuteGeneric(_portClient, command); if (result.Status == CommResponse.Ack) { //UInt16[] Data = new ushort[command.Data.Length]; //command.Data.CopyTo(Data, StartAddress); //foreach (var item in Data) //{ // Console.WriteLine(item); //} Console.WriteLine($"Read succeeded: Function code:{function} {_transactionId}"); } else { Console.WriteLine(String.Format("Failed to execute Read: Error code:{0}", result.Status)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(result); }
/// <summary> /// 组帧,通用应答 /// </summary> /// <param name="serialNo">流水号,这个流水号是Host字节序</param> /// <param name="msgId">回应的请求消息ID</param> /// <param name="respType"></param> /// <returns></returns> public byte[] Make8001Frame(Int16 serialNo, MsgId msgId, CommResponse respType) { byte[] arr = new byte[5]; arr[0] = Convert.ToByte((serialNo & 0xFF00) >> 8); //流水号,低字节 arr[1] = Convert.ToByte(serialNo & 0x00FF); //流水号高字节 arr[2] = Convert.ToByte((((int)msgId) & 0xFF00) >> 8); //消息ID,低字节 arr[3] = Convert.ToByte(((int)msgId) & 0x00FF); //消息ID高字节 arr[4] = (byte)respType; return(arr); }
public override bool ExecuteWrite(int offset) { FuncWriteMultipleRegisters.Offset = offset; FuncWriteMultipleRegisters.Count = GetCountRegsByTagOffset(offset); FuncWriteMultipleRegisters.Data = new ushort[FuncWriteMultipleRegisters.Count]; adapter.Write(FuncWriteMultipleRegisters, ref RegistersData); CommResponse Response = driver.ExecuteGeneric(medium, FuncWriteMultipleRegisters); return(Response.Status == CommResponse.Ack); }
/// <summary> /// Entry-point for submitting a query to the remote device /// </summary> /// <param name="data"></param> /// <returns></returns> public CommResponse Query(ClientCommData data) { //convert the request data as an ordinary byte array byte[] outgoing = data .OutgoingData .ToArray(); int totalTimeout = this.Latency + data.Timeout; //retries loop for (int attempt = 0, retries = data.Retries; attempt < retries; attempt++) { //phyiscal writing this.Send(outgoing); //create a writer for accumulate the incoming data var incoming = new ByteArrayWriter(); //read the incoming data from the physical port incoming.WriteBytes( this.Receive(totalTimeout) ); //try to decode the stream data.IncomingData = incoming.ToReader(); CommResponse result = data .OwnerProtocol .Codec .ClientDecode(data); //exit whether any concrete result: either good or bad if (result.Status == CommResponse.Ack) { return(result); } else if (result.Status == CommResponse.Critical) { return(result); } else if (result.Status != CommResponse.Unknown) { break; } //stop immediately if the host asked to abort //TODO } //for //no attempt was successful return(new CommResponse( data, CommResponse.Critical)); }
private void BtnWriteSingleCoilClick(object sender, EventArgs e) { try { ModbusCommand command = new ModbusCommand((byte)5) { Offset = (int)this.StartAddress, Count = 1, TransId = this._transactionId++, Data = new ushort[1] }; command.Data[0] = (ushort)((uint)this._registerData[(int)this.StartAddress] & 256U); CommResponse commResponse = this._driver.ExecuteGeneric(this._portClient, command); this.AppendLog(commResponse.Status == 3 ? string.Format("Write succeeded: Function code:{0}", (object)(byte)5) : string.Format("Failed to execute Write: Error code:{0}", (object)commResponse.Status)); } catch (Exception ex) { this.AppendLog(ex.Message); } }
public CommResponse ExecuteWriteCommand(byte function, ushort StartAddress, ushort DataLength, short[] data) { CommResponse result = null; try { var command = new ModbusCommand(function) { Offset = StartAddress, Count = DataLength, TransId = _transactionId++, Data = new ushort[DataLength] }; for (int i = 0; i < DataLength; i++) { //var index = StartAddress + i; //if (index > data.Length) //{ // break; //} //command.Data[i] = (ushort)data[index]; if (i > data.Length) { break; } command.Data[i] = (ushort)data[i]; } result = _driver.ExecuteGeneric(_portClient, command); Console.WriteLine(result.Status == CommResponse.Ack ? String.Format("Write succeeded: Function code:{0}", function) : String.Format("Failed to execute Write: Error code:{0}", result.Status)); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(result); }
/// <summary> /// Entry-point for submitting a query to the remote device /// </summary> /// <param name="data"></param> /// <returns></returns> public CommResponse Query(ClientCommData data) { lock (this.Port) { try { //set the proper parameters to the port this.Port.BaudRate = this.Setting.BaudRate; this.Port.Parity = this.Setting.Parity; this.Port.DataBits = this.Setting.DataBits; this.Port.StopBits = this.Setting.StopBits; this.Port.RtsEnable = this.Setting.RtsEnable; } catch (Exception ex) { return(new CommResponse( data, CommResponse.Critical, ex.Message)); } //convert the request data as an ordinary byte array byte[] outgoing = ((IByteArray)data.OutgoingData).Data; //create a writer for accumulate the incoming data var incoming = new ByteArrayWriter(); const int tempSize = 64; var temp = new byte[tempSize]; //retries loop for (int attempt = 0, retries = data.Retries; attempt < retries; attempt++) { try { //flush any residual content this.Port .DiscardInBuffer(); this.Port .DiscardOutBuffer(); #if NET45 //System.Diagnostics.Trace.WriteLine("TX: " + ByteArrayHelpers.ToHex(outgoing)); #endif //phyiscal writing this.Port.WriteTimeout = 500; this.Port .Write(outgoing, 0, outgoing.Length); } catch (Exception ex) { return(new CommResponse( data, CommResponse.Critical, ex.Message)); } incoming.Drop(); //start the local timer bool timeoutExpired; int totalTimeout = this.Latency + data.Timeout; using (Timer timer = new Timer( _ => timeoutExpired = true, state: null, dueTime: totalTimeout, period: Timeout.Infinite)) { //reception loop, until a valid response or timeout timeoutExpired = false; while (timeoutExpired == false) { int length = this.Port.BytesToRead; if (length > 0) { if (length > tempSize) { length = tempSize; } try { //read the incoming data from the physical port this.Port .Read(temp, 0, length); } catch (Exception ex) { return(new CommResponse( data, CommResponse.Critical, ex.Message)); } //append data to the writer incoming.WriteBytes( temp, 0, length); //try to decode the stream data.IncomingData = incoming.ToReader(); #if NET45 //System.Diagnostics.Trace.WriteLine("RX: " + ByteArrayHelpers.ToHex(incoming.ToByteArray())); #endif CommResponse result = data .OwnerProtocol .Codec .ClientDecode(data); //exit whether any concrete result: either good or bad if (result.Status == CommResponse.Ack) { return(result); } else if (result.Status == CommResponse.Critical) { return(result); } else if (result.Status != CommResponse.Unknown) { break; } } Thread.Sleep(0); //stop immediately if the host asked to abort //TODO } } //using (timer) } //for //no attempt was successful return(new CommResponse( data, CommResponse.Critical)); } //lock }
/// <summary> /// Entry-point for submitting a query to the remote device /// </summary> /// <param name="data"></param> /// <returns></returns> public CommResponse Query(ClientCommData data) { lock (this.Port) { //convert the request data as an ordinary byte array byte[] outgoing = ((IByteArray)data.OutgoingData).Data; //create a writer for accumulate the incoming data var incoming = new ByteArrayWriter(); const int tempSize = 64; var temp = new byte[tempSize]; //retries loop for (int attempt = 0, retries = data.Retries; attempt < retries; attempt++) { //phyiscal writing this.Port .Send(outgoing); incoming.Drop(); //start the local timer bool timeoutExpired; int totalTimeout = this.Latency + data.Timeout; using (Timer timer = new Timer( _ => timeoutExpired = true, state: null, dueTime: totalTimeout, period: Timeout.Infinite)) { //reception loop, until a valid response or timeout timeoutExpired = false; while (timeoutExpired == false) { var length = this.Port.Available; if (length > 0) { if (length > tempSize) { length = tempSize; } //read the incoming data from the physical port this.Port .Receive(temp, length, SocketFlags.None); //append data to the writer incoming.WriteBytes( temp, 0, length); //try to decode the stream data.IncomingData = incoming.ToReader(); CommResponse result = data .OwnerProtocol .Codec .ClientDecode(data); //exit whether any concrete result: either good or bad if (result.Status == CommResponse.Ack) { return(result); } else if (result.Status == CommResponse.Critical) { return(result); } else if (result.Status != CommResponse.Unknown) { break; } } Thread.Sleep(0); //stop immediately if the host asked to abort //TODO } } //using (timer) } //for //no attempt was successful return(new CommResponse( data, CommResponse.Critical)); } //lock }
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); } }
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 }
/// <summary> /// Running thread handler /// </summary> private void Worker() { #if NET45 System.Diagnostics.Trace.WriteLine("start"); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("start"); #endif //start the local timer, which gets the session dying int counter = IdleTimeout; int grace = 0; //create a writer for the incoming data ByteArrayWriter writer = null; var buffer = new byte[CacheSize]; using (Timer timer = new Timer( _ => { counter--; if (--grace == 0) { writer = null; } }, state: null, dueTime: 1000, period: 1000)) { //loop until the host closes, or the timer expires while ( this.Port.IsOpen && this._closing == false && counter > 0) { //look for incoming data int length = this.Port.BytesToRead; if (length > 0) { grace = 2; if (length > CacheSize) { length = CacheSize; } //read the data from the physical port this.Port.Read( buffer, 0, length); //append the data to the writer if (writer == null) { writer = new ByteArrayWriter(); } writer.WriteBytes( buffer, 0, length); //try to decode the incoming data var data = new ServerCommData(this.Protocol); data.IncomingData = writer.ToReader(); #if NET45 //System.Diagnostics.Trace.WriteLine("RX: " + ByteArrayHelpers.ToHex(((IByteArray)data.IncomingData).Data)); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("RX: " + ByteArrayHelpers.ToHex(((IByteArray)data.IncomingData).Data)); #endif CommResponse result = this.Protocol .Codec .ServerDecode(data); if (result.Status == CommResponse.Ack) { //the command is recognized, so call the host back this.OnServeCommand(data); //encode the host data this.Protocol .Codec .ServerEncode(data, 0); //return the resulting data to the remote caller byte[] outgoing = ((IByteArray)data.OutgoingData).Data; if (this.Port.IsOpen) { this.Port.Write( outgoing, 0, outgoing.Length); } else { break; } //reset the timer counter = IdleTimeout; writer = null; } //else if (result.Status == CommResponse.Ignore) //{ // writer = null; //} } Thread.Sleep(0); } } #if NET45 System.Diagnostics.Trace.WriteLine("close"); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("close"); #endif //marks the server not running this.IsRunning = false; }
/// <summary> /// Running thread handler /// </summary> protected override void Worker() { #if NET45 System.Diagnostics.Trace.WriteLine("start"); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("start"); #endif //loop, until the host closes while (this._closing == false) { //look for incoming data int length = this.Port.Available; if (length > 0) { var buffer = new byte[length]; EndPoint remote = new IPEndPoint(IPAddress.Any, 0); //read the data from the physical port this.Port.ReceiveFrom( buffer, ref remote); //try to decode the incoming data var data = new ServerCommData(this.Protocol); data.IncomingData = new ByteArrayReader(buffer); CommResponse result = this.Protocol .Codec .ServerDecode(data); if (result.Status == CommResponse.Ack) { //the command is recognized, so call the host back this.OnServeCommand(data); //encode the host data this.Protocol .Codec .ServerEncode(data, data.Address); //return the resulting data to the remote caller byte[] outgoing = ((IByteArray)data.OutgoingData).Data; this.Port.SendTo( outgoing, remote); } } Thread.Sleep(0); } #if NET45 System.Diagnostics.Trace.WriteLine("close"); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("close"); #endif //marks the server not running this.IsRunning = false; }
/// <summary> /// Running thread handler /// </summary> protected override void Worker() { #if NET45 System.Diagnostics.Trace.WriteLine("start"); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("start"); #endif try { //start the local timer, which gets the session dying var counter = IdleTimeout; Port.ReceiveTimeout = 1000; var grace = 0; //create a writer for the incoming data ByteArrayWriter writer = null; var buffer = new byte[CacheSize]; //loop, until the host closes, or the timer expires while ( _closing == false && counter-- > 0) { if (--grace == 0) { writer = null; } //look for incoming data int length; try { //read the data from the physical port length = Port.Receive( buffer, SocketFlags.None); //check whether the remote has closed if (length == 0) { break; } } catch (ObjectDisposedException) { break; } catch (SocketException ex) { //no data received due socket timeout Debug.WriteLine(ex.Message); length = 0; } if (length > 0) { grace = 2; //append the data to the writer if (writer == null) { writer = new ByteArrayWriter(); } writer.WriteBytes( buffer, 0, length ); //try to decode the incoming data var data = new ServerCommData(this.Protocol); data.IncomingData = writer.ToReader(); CommResponse result; try { result = this.Protocol .Codec .ServerDecode(data); } catch (Exception ex) { Debug.WriteLine(ex.Message); result = new CommResponse(null, CommResponse.Ignore); } if (result.Status == CommResponse.Ack) { //the command is recognized, so call the host back OnServeCommand(data); //encode the host data Protocol .Codec .ServerEncode(data); //return the resulting data to the remote caller var outgoing = data.OutgoingData.ToByteArray(); if (Port.Connected) { try { Port.Send(outgoing); } catch (Exception ex) { Trace.TraceError(ex.Message); } } //reset the timer counter = IdleTimeout; writer = null; } else if (result.Status == CommResponse.Ignore) { writer = null; } } Thread.Sleep(0); } } catch (ObjectDisposedException) { } finally { //ensure the local socket disposal Port.Close(); } #if NET45 System.Diagnostics.Trace.WriteLine("close"); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("close"); #endif //marks the server not running IsRunning = false; Disconnected?.Invoke(); }