Example #1
0
        public void Write(HJ212Message message)
        {
            _streamResource.DiscardInBuffer();

            byte[] frame = BuildMessageFrame(message);
            _streamResource.Write(frame, 0, frame.Length);
        }
Example #2
0
        internal bool ChecksumsMatch(HJ212Message message, byte[] messageFrame)
        {
            var crcString = Encoding.ASCII.GetString(messageFrame, messageFrame.Length - 4, 4);
            var crcBytes  = BytesUtility.HexToBytes(crcString);

            return(BitConverter.ToUInt16(crcBytes, 0) ==
                   BitConverter.ToUInt16(BytesUtility.CalculateCrc(message.MessageFrame), 0));
        }
Example #3
0
        public T UnicastMessage <T>(HJ212Message message) where T : HJ212Message, new()
        {
            HJ212Message response = null;

            lock (_syncLock)
            {
                Write(message);
                response = ReadResponse <T>();
            }
            ValidateResponse(message, response);
            return((T)response);
        }
Example #4
0
        internal byte[] BuildMessageFrame(HJ212Message message)
        {
            var messageFrame = message.MessageFrame;
            var crc          = BytesUtility.GetAsciiBytes(BytesUtility.CalculateCrc(messageFrame));
            var messageBody  = new MemoryStream(_header.Length + _len.Length +
                                                messageFrame.Length + crc.Length + _tailer.Length);

            messageBody.Write(Encoding.ASCII.GetBytes(_header), 0, _header.Length);
            messageBody.Write(Encoding.ASCII.GetBytes(_len), 0, _header.Length);
            messageBody.Write(messageFrame, 0, messageFrame.Length);
            messageBody.Write(crc, 0, crc.Length);
            messageBody.Write(Encoding.ASCII.GetBytes(_tailer), 0, _tailer.Length);

            return(messageBody.ToArray());
        }
Example #5
0
        internal void ValidateResponse(HJ212Message request, HJ212Message response)
        {
            // always check the function code and slave address, regardless of transport protocol
            if (request.QN != request.QN)
            {
                throw new IOException(String.Format(CultureInfo.InvariantCulture,
                                                    "Received response with unexpected QN. Expected {0}, received {1}.", request.QN,
                                                    response.QN));
            }

            if (request.MN != response.MN)
            {
                throw new IOException(String.Format(CultureInfo.InvariantCulture,
                                                    "Response MN does not match request. Expected {0}, received {1}.", response.MN,
                                                    request.MN));
            }

            // message specific validation
            if (request != null)
            {
                request.ValidateResponse(response);
            }
        }