コード例 #1
0
ファイル: ModbusRtuCodec.cs プロジェクト: josemotta/Netduino
        void IProtocolCodec.ServerEncode(CommDataBase data)
        {
            var server  = (ModbusServer)data.OwnerProtocol;
            var command = (ModbusCommand)data.UserData;
            var fncode  = command.FunctionCode;

            //encode the command body, if applies
            var body  = new ByteArrayWriter();
            var codec = CommandCodecs[fncode];

            if (codec != null)
            {
                codec.ServerEncode(command, body);
            }

            //calculate length field
            var length = (command.ExceptionCode == 0)
                ? 2 + body.Length
                : 3;

            //create a writer for the outgoing data
            var writer = new ByteArrayWriter();

            //unit identifier (address)
            writer.WriteByte(server.Address);

            if (command.ExceptionCode == 0)
            {
                //function code
                writer.WriteByte(fncode);

                //body data
                writer.WriteBytes(body);
            }
            else
            {
                //function code
                writer.WriteByte((byte)(command.FunctionCode | 0x80));

                //exception code
                writer.WriteByte(command.ExceptionCode);
            }

            //CRC-16
            ushort crc;

            unchecked
            {
                crc = (ushort)ModbusRtuCodec.Crc16.Compute(
                    ((IByteArray)writer).Data,
                    0,
                    writer.Length);
            }

            writer.WriteUInt16LE(crc);

            data.OutgoingData = writer.ToReader();
        }
コード例 #2
0
ファイル: ModbusRtuCodec.cs プロジェクト: josemotta/Netduino
        void IProtocolCodec.ClientEncode(CommDataBase data)
        {
            var client  = (ModbusClient)data.OwnerProtocol;
            var command = (ModbusCommand)data.UserData;
            var fncode  = command.FunctionCode;

            //encode the command body, if applies
            var body  = new ByteArrayWriter();
            var codec = CommandCodecs[fncode];

            if (codec != null)
            {
                codec.ClientEncode(command, body);
            }

            //create a writer for the outgoing data
            var writer = new ByteArrayWriter();

            //unit identifier (address)
            writer.WriteByte(client.Address);

            //function code
            writer.WriteByte(fncode);

            //body data
            writer.WriteBytes(body);

            //CRC-16
            ushort crc;

            unchecked
            {
                crc = (ushort)ModbusRtuCodec.Crc16.Compute(
                    ((IByteArray)writer).Data,
                    0,
                    writer.Length
                    );
            }

            writer.WriteUInt16LE(crc);

            data.OutgoingData = writer.ToReader();
        }