Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

HostCommunication.cpp 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // Created by robin on 5/5/16.
  3. //
  4. #include "HostCommunication.h"
  5. #include <Arduino.h>
  6. HostCommunication::HostCommunication()
  7. {
  8. }
  9. void HostCommunication::init()
  10. {
  11. Serial.begin(SERIAL_BAUDRATE);
  12. debug("Starting...");
  13. }
  14. void HostCommunication::debug(String str)
  15. {
  16. #ifdef DEBUG
  17. send(PACKET_DEBUG, str);
  18. #endif
  19. }
  20. void HostCommunication::selfTest()
  21. {
  22. send(PACKET_SELF_TEST);
  23. }
  24. void HostCommunication::login(String uid, String password)
  25. {
  26. send(PACKET_LOGIN, uid + "\n" + password);
  27. }
  28. void HostCommunication::send(SERIAL_PACKET_TYPE type)
  29. {
  30. send(type, "");
  31. }
  32. void HostCommunication::send(SERIAL_PACKET_TYPE type, String str)
  33. {
  34. Serial.write((SERIAL_PACKET_TYPE)type);
  35. Serial.write((SERIAL_PACKET_LENGTH_TYPE)str.length());
  36. Serial.write(str.c_str());
  37. }
  38. HostCommunicationResult HostCommunication::read(int timeout)
  39. {
  40. HostCommunicationResult res;
  41. res.length = 0;
  42. res.data = 0;
  43. res.isSuccess = false;
  44. if (!waitData(timeout, sizeof(SERIAL_PACKET_LENGTH_TYPE))) {
  45. return res;
  46. }
  47. SERIAL_PACKET_LENGTH_TYPE length = 0;
  48. Serial.readBytes((char*)&length, sizeof(SERIAL_PACKET_LENGTH_TYPE));
  49. if (!waitData(timeout, length)) {
  50. return res;
  51. }
  52. res.data = new char[length];
  53. Serial.readBytes(res.data, length);
  54. res.isSuccess = true;
  55. res.length = length;
  56. return res;
  57. }
  58. bool HostCommunication::waitData(int timeout, int length)
  59. {
  60. unsigned long secs = millis();
  61. while (Serial.available() < length && millis() - secs < timeout) {
  62. delay(1);
  63. }
  64. return Serial.available() >= length;
  65. }