public void WriteMessage(Message message)
        {
            var messageLength = message.Data.Length + _headerSize;
            
            using (var memoryStream = new MemoryStream(messageLength))
            using (var writer = new BinaryWriter(memoryStream))
            {
                writer.Write(_messageSignature);
                writer.Write(message.Version);
                writer.Write(message.Flags);
                writer.Write((ushort) message.Data.Length);
                writer.Write(message.Intent);
                writer.Write(message.Data);

                var data = memoryStream.ToArray();
                var checksum = CalculateChecksum(data);

                _connection.Write(data);
                _connection.Write(new[] {checksum});
            }
        }
 private void SendMessage(ushort intent, byte[] data)
 {
     try
     {
         var message = new Message(_version, 0, intent, data);
         _messageReaderWriter.WriteMessage(message);
     }
     catch (Exception e)
     {
         _logger.Error("Error occurred on message sending", e);
     }
 }
        private void HandleMessage(Message message)
        {
            if (message.Version != _version)
                throw new InvalidOperationException("Invalid message version: " + message.Version);

            switch (message.Intent)
            {
                case Intents.Register:
                    RegisterDevice(message.Data);
                    break;

                case Intents.Register2:
                    RegisterDevice2(message.Data);
                    break;

                case Intents.NotifyCommandResult:
                    NotifyCommandResult(message.Data);
                    break;

                default: // in other case message should be custom notification message
                    HandleNotification(message.Intent, message.Data);
                    break;
            }
        }