123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- #include <assert.h>
- #include <stdio.h>
- #include <stdint.h>
- #include <unistd.h>
- #include <fcntl.h>
- #define TTY_PATH "/dev/ttyUSB0"
- #define STATUS_PATH "/run/hangup-sensor/status"
- #define INTERVAL_MSEC 100
- #define CHECK_VALUE '\xff'
- #define S(a) a,(sizeof(a)-1)
- enum status {
- UNKNOWN,
- CONNECTED,
- DISCONNECTED,
- };
- int main()
- {
- int tty_fd;
- assert ( ( tty_fd = open ( TTY_PATH, O_RDWR ) ) != -1 );
- assert ( fcntl ( tty_fd, F_SETFL, fcntl ( tty_fd, F_GETFL ) | O_NONBLOCK ) != -1 );
- enum status status = UNKNOWN;
- static const uint8_t sendChar = CHECK_VALUE;
- while ( 1 ) {
- uint8_t recvChar;
- enum status newStatus;
- assert ( write ( tty_fd, &sendChar, 1 ) != -1 );
- usleep ( INTERVAL_MSEC * 1000 );
- recvChar = 0;
- ssize_t rsize = read ( tty_fd, &recvChar, 1 );
- newStatus = ( rsize == 1 && recvChar == sendChar ) ? CONNECTED : DISCONNECTED;
- if ( newStatus != status ) {
- int statusFile_fd;
- assert ( ( statusFile_fd = open ( STATUS_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0640 ) ) != -1 );
- switch ( newStatus ) {
- case CONNECTED:
- assert ( write ( statusFile_fd, S ( "connected\n" ) ) != -1 );
- break;
- case DISCONNECTED:
- assert ( write ( statusFile_fd, S ( "disconnected\n" ) ) != -1 );
- break;
- default:
- fprintf ( stderr, "This shouldn't happened" );
- return -1;
- }
- close ( statusFile_fd );
- }
- status = newStatus;
- }
- return 0;
- }
|