Example #1
0
        /// <summary>
        /// Running thread handler
        /// </summary>
        protected override void Worker()
        {
            //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);

                        //return the resulting data to the remote caller
                        byte[] outgoing = data
                                          .OutgoingData
                                          .ToArray();

                        this.Port.SendTo(
                            outgoing,
                            remote);
                    }
                }

                Thread.Sleep(0);
            }
        }
Example #2
0
        /// <summary>
        /// Running thread handler
        /// </summary>
        protected override void Worker()
        {
            Debug.Print("start");

            //start the local timer, which gets the session dying
            int counter = IdleTimeout;

            using (Timer timer = new Timer(
                       _ => counter--,
                       state: null,
                       dueTime: 1000,
                       period: 1000))
            {
                //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 (
                    this._closing == false &&
                    counter > 0)
                {
                    //look for incoming data
                    int length = this.Port.Available;

                    if (length > 0)
                    {
                        if (length > CacheSize)
                        {
                            length = CacheSize;
                        }

                        //read the data from the physical port
                        this.Port.Receive(
                            buffer,
                            length,
                            SocketFlags.None);

                        //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 = 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);

                            //return the resulting data to the remote caller
                            byte[] outgoing = data
                                              .OutgoingData
                                              .ToArray();

                            this.Port.Send(outgoing);

                            //reset the timer
                            counter = IdleTimeout;
                            writer  = null;
                        }
                        else if (result.Status == CommResponse.Ignore)
                        {
                            writer = null;
                        }
                    }

                    Thread.Sleep(0);
                }
            }

            this.Port.Close();
            Debug.Print("close");
        }
Example #3
0
        /// <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)
            {
                //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;

                //convert the request data as an ordinary byte array
                byte[] outgoing = data
                                  .OutgoingData
                                  .ToArray();

                //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++)
                {
                    //flush any residual content
                    this.Port
                    .DiscardInBuffer();

                    this.Port
                    .DiscardOutBuffer();

                    //phyiscal writing
                    this.Port
                    .Write(outgoing, 0, outgoing.Length);

                    incoming.Reset();

                    //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;
                                }

                                //read the incoming data from the physical port
                                this.Port
                                .Read(temp, 0, length);

                                //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
        }
Example #4
0
        /// <summary>
        /// Running thread handler
        /// </summary>
        private void Worker()
        {
            //create a writer for the incoming data
            ByteArrayWriter writer = null;

            //loop, until the host closes
            while (this._closing == false)
            {
                //look for incoming data
                int length = this.Port.BytesToRead;

                if (length > 0)
                {
                    var buffer = new byte[length];

                    //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();

                    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);

                        //return the resulting data to the remote caller
                        byte[] outgoing = data
                                          .OutgoingData
                                          .ToArray();

                        this.Port.Write(
                            outgoing,
                            0,
                            outgoing.Length);

                        writer = null;
                    }
                    else if (result.Status == CommResponse.Ignore)
                    {
                        writer = null;
                    }
                }

                Thread.Sleep(0);
            }
        }
Example #5
0
        public static void Main()
        {
#if MASTER_TCP || MASTER_UDP || SLAVE_TCP || SLAVE_UDP
            //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];
            _coils   = new OutputPort[6];
            _analogs = new AnalogInput[6];

            _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);

            _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);

            _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);
#else
            //define coils, inputs, and analogs
            _inputs  = new InputPort[4];
            _coils   = new OutputPort[6];
            _analogs = new AnalogInput[6];

            _inputs[0] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp);
            _inputs[1] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp);
            _inputs[2] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp);
            _inputs[3] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp);

            _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);

            _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);
#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, 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 = 1;

                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 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 = 1;

                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 SerialPort("COM2", 38400, Parity.Even, 8))
            {
                //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 = 1;

                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_RTU
            //create an UART port
            using (var uart = new SerialPort("COM2", 38400, Parity.Even, 8))
            {
                //open the serial port
                uart.Open();

                var prm = new SerialPortParams("38400,E,8,1");

                //create a server driver
                var server = new ModbusServer(new ModbusRtuCodec());
                server.Address = 1;

                //listen for an incoming request
                var listener = uart.GetListener(server);
                listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand);
                listener.Start();

                Thread.Sleep(Timeout.Infinite);
            }
#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 = 1;

                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 = 1;

                //listen for an incoming request
                var listener = socket.GetUdpListener(server);
                listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand);
                listener.Start();

                Thread.Sleep(Timeout.Infinite);
            }
#endif
        }