Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

main.cpp 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <iostream>
  2. #include<signal.h>
  3. #include <sstream>
  4. #include "DataAccess/ArduinoSerial.h"
  5. constexpr char hexmap[] = {'0', '1', '2', '3', '4', '5', '6', '7',
  6. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  7. std::string hexStr(std::string str)
  8. {
  9. std::string s(str.size() * 2, ' ');
  10. for (int i = 0; i < str.size(); ++i) {
  11. s[2 * i] = hexmap[(str[i] & 0xF0) >> 4];
  12. s[2 * i + 1] = hexmap[str[i] & 0x0F];
  13. }
  14. return s;
  15. }
  16. std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
  17. std::stringstream ss(s);
  18. std::string item;
  19. while (std::getline(ss, item, delim)) {
  20. elems.push_back(item);
  21. }
  22. return elems;
  23. }
  24. std::vector<std::string> split(const std::string &s, char delim) {
  25. std::vector<std::string> elems;
  26. split(s, delim, elems);
  27. return elems;
  28. }
  29. int lastSignal = 0;
  30. void sig_handler(int signo)
  31. {
  32. std::cout << "Signal catched " << signo << std::endl;
  33. lastSignal = signo;
  34. }
  35. int main()
  36. {
  37. signal(SIGINT, sig_handler);
  38. signal(SIGTERM, sig_handler);
  39. signal(SIGKILL, sig_handler);
  40. ArduinoSerial arduinoSerial("/dev/ttyUSB0", SERIAL_BAUDRATE);
  41. auto res = arduinoSerial.open();
  42. if (!res) {
  43. res.print();
  44. return 1;
  45. }
  46. while (lastSignal == 0)
  47. {
  48. auto data = arduinoSerial.read();
  49. if (!data) {
  50. data.print();
  51. return 2;
  52. }
  53. std::cout << (int) data.getData().first << " " << hexStr(data.getData().second)
  54. << " " << data.getData().second << std::endl;
  55. if (data.getData().first == PACKET_SELF_TEST) {
  56. SERIAL_PACKET_TYPE_INT status = ERROR_NONE;
  57. arduinoSerial.write((const char*)&status, sizeof(status));
  58. }
  59. if (data.getData().first == PACKET_LOGIN) {
  60. std::vector<std::string> login = split(data.getData().second, '\n');
  61. if (login.size() == 2) {
  62. std::string uid = login[0];
  63. std::string passwd = login[1];
  64. SERIAL_PACKET_TYPE_INT status = (uid == "4242" ? LOGIN_OK : LOGIN_FAILED);
  65. arduinoSerial.write((const char *) &status, sizeof(status));
  66. }
  67. }
  68. }
  69. return 0;
  70. }