private async Task <byte[]> ReadResponseAsync() { var remaining = 0; var packetIndex = 0; using (var response = new MemoryStream()) { do { var packetData = await HIDDevice.ReadAsync(); var responseDataPacket = GetResponseDataPacket(packetData, packetIndex, ref remaining); packetIndex++; if (responseDataPacket == null) { return(null); } response.Write(responseDataPacket, 0, responseDataPacket.Length); } while (remaining != 0); return(response.ToArray()); } }
private async Task <object> ReadResponseAsync() { var data = await HIDDevice.ReadAsync(); var firstByteNot63 = data[0] != (byte)'?'; var secondByteNot35 = data[1] != 35; var thirdByteNot35 = data[2] != 35; if (firstByteNot63 || secondByteNot35 || thirdByteNot35) { throw new Exception("An error occurred while attempting to read the message from the device."); } var typeInt = data[4]; if (!Enum.IsDefined(typeof(MessageType), (int)typeInt)) { throw new Exception("Not a valid MessageType"); } var messageType = (MessageType)Enum.Parse(typeof(MessageType), Enum.GetName(typeof(MessageType), typeInt)); var remainingDataLength = ((data[5] & 0xFF) << 24) + ((data[6] & 0xFF) << 16) + ((data[7] & 0xFF) << 8) + (data[8] & 0xFF); var length = Math.Min(data.Length - (FirstChunkResponseIdx), remainingDataLength); var allData = data.ToList().GetRange(FirstChunkResponseIdx, length); remainingDataLength -= allData.Count; var invalidChunksCounter = 0; while (remainingDataLength > 0) { data = await HIDDevice.ReadAsync(); if (data.Length <= 0) { continue; } length = Math.Min(data.Length, remainingDataLength); if (data[0] != (byte)'?') { if (invalidChunksCounter++ > 5) { throw new Exception("messageRead: too many invalid chunks (2)"); } } allData.InsertRange(allData.Count, data.ToList().GetRange(1, length - 1)); remainingDataLength -= (length - 1); //Super hack! Fix this! if (remainingDataLength != 1) { continue; } allData.InsertRange(allData.Count, data.ToList().GetRange(length, 1)); remainingDataLength = 0; } return(Helpers.ProtoBufDeserialize(GetContractType(messageType), allData.ToArray())); }