]>
git.defcon.no Git - test-repo/blob - door_works.c
1 #include <termios.h> /* Terminal I/O support */
2 #include <errno.h> /* Error number definitions */
3 #include <string.h> /* String function definitions */
4 #include <stdio.h> /* Standard I/O */
5 #include <fcntl.h> /* File descriptor manipulation */
7 #define DEVICE "/dev/ttyUSB0"
9 int open_port ( char* device
)
14 f
= open ( DEVICE
, O_RDWR
| O_NOCTTY
); // Not using O_NDELAY, that caused ERR11: temp unavail.
21 // Fixed settings: 9600bps, 8 bits,
22 // no parity, no flow-control,
23 // local mode, read enabled
24 tio
.c_cflag
= B9600
| CS8
| CLOCAL
| CREAD
;
25 tio
.c_cflag
&= ~CRTSCTS
;
28 tio
.c_lflag
= 0; // Non-canonical read, no other options.
29 tio
.c_cc
[VMIN
] = 3; // Expect 3 characters, always.
30 tio
.c_cc
[VTIME
] = 60; // Wait for a max of 6 seconds
32 tcsetattr(f
,TCSANOW
,&tio
); // Apply this now.
37 int send_cmd ( int fd
, char cmd
)
43 tcflush(fd
, TCIFLUSH
); // Flush the serial input buffer.
45 res
= write( fd
, &cmd
, 1 ); // Send the command to the device
46 if ( res
< 0 ) return -1; // and return on failure.
48 res
= read( fd
, buf
, 5 );
51 printf("SERIAL read error %d: %s\n", errno
, strerror(errno
));
56 printf ("Null read\n");
62 // A response is supposed to be precisely three characters.
67 // And the first is supposed to be an echo of the given command.
70 printf("Error: echoed command not correct\n");
74 // The second is (a ':' is ignored, and the third is checked.
75 // The only valid responses are Locked, Open and Moving.
78 if ( (status
== 'O') || (status
== 'L') || (status
== 'M') )
83 int get_state ( int fd
)
85 return send_cmd( fd
, 's'); // Yashure. KISS
88 int set_state ( int fd
, int state
)
94 res
= send_cmd ( fd
, 'o');
97 res
= send_cmd ( fd
, 'l');
100 if ( (res
!= 'L') && ( res
!= 'O' ) ) return -1; // FAIL
101 // And, yes, I will call a status "Moving" a failed state-change attempt
106 int main ( int argc
, char** argv
)
113 fd
= open_port( DEVICE
);
120 printf("Enter command character, followed by enter/return\n");
121 printf("Valid commands are:\n l - Lock\n o - Open \n s - Status\n i - Invalid simulation\n");
122 printf("ESC Enter exits");
127 if ( res
== 10 ) continue;
129 if ( res
== 27 ) return 1;
133 printf("Locking...\n");
134 if ( set_state( fd
, 1 ) ) printf ( "set_state() failed\n");
137 printf("Opening...\n");
138 if ( set_state( fd
, 0 ) ) printf ( "set_state() failed\n");
141 printf("Requesting status...\n");
142 res
= get_state( fd
);
155 printf("Unknown status %d\n", res
);
159 printf("Sending invalid command...\n");
160 res
= send_cmd( fd
, (char)res
);
161 printf("Back from attempt. Got %d back\n", res
);