/// <summary> /// <para>Constructor.</para> /// </summary> /// <param name="command">The command</param> /// <param name="errorMessage">The error code</param> /// <param name="Message">The exception message</param> public NxtCommunicationProtocolException(NxtCommand command, NxtErrorMessage errorMessage, string Message) : base(Message.Trim()) { this.command = command; this.errorMessage = errorMessage; }
/// <summary> /// <para>Constructor.</para> /// </summary> /// <param name="command">The command</param> /// <param name="errorMessage">The error code</param> /// <param name="Message">The exception message</param> public NxtCommunicationProtocolException(NxtCommand command, NxtErrorMessage errorMessage, string Message) : base(Message.Trim()) { this.command = command; this.errorMessage = errorMessage; }
/// <summary> /// <para>Sends a request for the NXT brick, and if applicable, receive the reply.</para> /// </summary> /// <param name="request">The request</param> /// <returns>The reply as a byte-array, or null</returns> protected override byte[] Send(byte[] request) { lock (serialPortLock) { if (!IsConnected) { throw new NxtConnectionException("Can't send message: Not connected."); } int length = request.Length; // Create a Bluetooth request. byte[] btRequest = new byte[request.Length + 2]; btRequest[0] = (byte)(length & 0xFF); btRequest[1] = (byte)((length & 0xFF00) >> 8); request.CopyTo(btRequest, 2); // Write the request to the NXT brick. serialPort.Write(btRequest, 0, btRequest.Length); // 0x80 indicates that we should expect a reply. if ((request[0] & 0x80) == 0) { int lsb = serialPort.ReadByte(); int msb = serialPort.ReadByte(); length = msb * 256 + lsb; byte[] reply = new byte[length]; serialPort.Read(reply, 0, length); NxtCommand command = (NxtCommand)request[1]; NxtCommand commandEcho = (NxtCommand)reply[1]; if (reply[0] != 0x02) { throw new NxtCommunicationProtocolException(command, NxtErrorMessage.UndefinedError, string.Format("Expected a Reply Command byte (0x02); Got 0x{0:X2} instead.", reply[0])); } if (commandEcho != command) { throw new NxtCommunicationProtocolException(command, NxtErrorMessage.UndefinedError, string.Format("Expected a matching return Command byte (0x{0:X2}); Got 0x{1:X2} instead.", command, commandEcho)); } NxtErrorMessage statusByte = (NxtErrorMessage)reply[2]; if (statusByte != NxtErrorMessage.Succes) { string errorText = "The Status byte indicates an error: Request:"; foreach (byte requestByte in request) { errorText += string.Format(" 0x{0:X2}", requestByte); } errorText += "; Reply:"; foreach (byte replyByte in reply) { errorText += string.Format(" 0x{0:X2}", replyByte); } throw new NxtCommunicationProtocolException(command, statusByte, errorText); } return(reply); } else { return(null); } } }