Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. private byte[] WriteData(byte[] command, bool ack = true, int retries = 5)
  2. {
  3. byte[] ackBuffer = new byte[2];
  4. bool done = false;
  5.  
  6. while ((!done) && (retries-- > 0))
  7. {
  8. Port.Write(command, 0, command.Length);
  9.  
  10. if (ack)
  11. {
  12. while (Port.BytesToRead != 2) { Task.Delay(1).Wait(); }
  13. Port.Read(ackBuffer, 0, 2);
  14.  
  15. done = 0xEE07 != (ackBuffer[0] << 8 | ackBuffer[1]);
  16. }
  17. else
  18. done = true;
  19. }
  20.  
  21. if (!done)
  22. throw new Exception("WriteData retries exceeded");
  23. return ackBuffer;
  24. }
  25.  
  26. private byte[] ReadData(byte[] command, int readLength)
  27. {
  28. byte[] headerBuffer = new byte[2];
  29. byte[] returnBuffer = new byte[readLength];
  30.  
  31. Port.Write(command, 0, command.Length);
  32.  
  33. while (Port.BytesToRead != 2) { Task.Delay(1).Wait(); }
  34. Port.Read(headerBuffer, 0, 2);
  35.  
  36. if (headerBuffer[0] != 0xBB)
  37. throw new Exception(string.Format("ReadData error 0x{0:x2}{0:x2}", headerBuffer[0], headerBuffer[1]));
  38. if (headerBuffer[1] != readLength)
  39. throw new Exception(string.Format("ReadData error: failed to read {0} bytes. Read {1}", readLength, headerBuffer[1]));
  40.  
  41. while (Port.BytesToRead != readLength) { Task.Delay(1).Wait(); }
  42. Port.Read(returnBuffer, 0, readLength);
  43.  
  44. return returnBuffer;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement