main.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. #define TTY_PATH "/dev/ttyUSB0"
  7. #define STATUS_PATH "/run/hangup-sensor/status"
  8. #define INTERVAL_MSEC 100
  9. #define CHECK_VALUE '\xff'
  10. #define S(a) a,(sizeof(a)-1)
  11. enum status {
  12. UNKNOWN,
  13. CONNECTED,
  14. DISCONNECTED,
  15. };
  16. int main()
  17. {
  18. int tty_fd;
  19. assert ( ( tty_fd = open ( TTY_PATH, O_RDWR ) ) != -1 );
  20. assert ( fcntl ( tty_fd, F_SETFL, fcntl ( tty_fd, F_GETFL ) | O_NONBLOCK ) != -1 );
  21. enum status status = UNKNOWN;
  22. static const uint8_t sendChar = CHECK_VALUE;
  23. while ( 1 ) {
  24. uint8_t recvChar;
  25. enum status newStatus;
  26. assert ( write ( tty_fd, &sendChar, 1 ) != -1 );
  27. usleep ( INTERVAL_MSEC * 1000 );
  28. recvChar = 0;
  29. ssize_t rsize = read ( tty_fd, &recvChar, 1 );
  30. newStatus = ( rsize == 1 && recvChar == sendChar ) ? CONNECTED : DISCONNECTED;
  31. if ( newStatus != status ) {
  32. int statusFile_fd;
  33. assert ( ( statusFile_fd = open ( STATUS_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0640 ) ) != -1 );
  34. switch ( newStatus ) {
  35. case CONNECTED:
  36. assert ( write ( statusFile_fd, S ( "connected\n" ) ) != -1 );
  37. break;
  38. case DISCONNECTED:
  39. assert ( write ( statusFile_fd, S ( "disconnected\n" ) ) != -1 );
  40. break;
  41. default:
  42. fprintf ( stderr, "This shouldn't happened" );
  43. return -1;
  44. }
  45. close ( statusFile_fd );
  46. }
  47. status = newStatus;
  48. }
  49. return 0;
  50. }