]>
git.defcon.no Git - test-repo/blob - main.c
2 #include <errno.h> /* Error number definitions */
3 #include <string.h> /* String function definitions */
9 #define DEVICE "/dev/ttyUSB0"
10 #define BAUDRATE B9600
12 int open_port ( char* device
)
17 f
= open ( DEVICE
, O_RDWR
| O_NOCTTY
); // Not using O_NDELAY, that caused ERR11: temp unavail.
24 // Fixed settings: 9600bps, 8 bits,
25 // no parity, no flow-control,
26 // local mode, read enabled
27 tio
.c_cflag
= BAUDRATE
| CS8
| CLOCAL
| CREAD
;
28 tio
.c_cflag
&= ~CRTSCTS
;
31 tio
.c_lflag
= 0; // Non-canonical read, no other options.
32 tio
.c_cc
[VMIN
] = 3; // Expect 3 characters, always.
33 tio
.c_cc
[VTIME
] = 60; // Wait for a max of 6 seconds
35 tcsetattr(f
,TCSANOW
,&tio
); // Apply this now.
40 int send_cmd ( int fd
, char cmd
)
46 tcflush(fd
, TCIFLUSH
); // Flush the serial input buffer.
48 res
= write( fd
, &cmd
, 1 ); // Send the command to the device
49 if ( res
< 0 ) return -1; // and return on failure.
51 res
= read( fd
, buf
, 5 );
54 printf("SERIAL read error %d: %s\n", errno
, strerror(errno
));
59 printf ("Null read\n");
65 // A response is supposed to be precisely three characters.
70 // And the first is supposed to be an echo of the given command.
73 printf("Error: echoed command not correct\n");
77 // The second is (a ':' is ignored, and the third is checked.
78 // The only valid responses are Locked, Open and Moving.
81 if ( (status
== 'O') || (status
== 'L') || (status
== 'M') )
86 int get_state ( int fd
)
88 return send_cmd( fd
, 's'); // Yashure. KISS
91 int set_state ( int fd
, int state
)
97 res
= send_cmd ( fd
, 'o');
100 res
= send_cmd ( fd
, 'l');
103 if ( (res
!= 'L') && ( res
!= 'O' ) ) return -1; // FAIL
104 // And, yes, I will call a status "Moving" a failed state-change attempt
109 int main ( int argc
, char** argv
)
116 fd
= open_port( DEVICE
);
123 printf("Enter command character, followed by enter/return\n");
124 printf("Valid commands are:\n l - Lock\n o - Open \n s - Status\n i - Invalid simulation\n");
125 printf("ESC Enter exits");
130 if ( res
== 10 ) continue;
132 if ( res
== 27 ) return 1;
136 printf("Locking...\n");
137 if ( set_state( fd
, 1 ) ) printf ( "set_state() failed\n");
140 printf("Opening...\n");
141 if ( set_state( fd
, 0 ) ) printf ( "set_state() failed\n");
144 printf("Requesting status...\n");
145 res
= get_state( fd
);
158 printf("Unknown status %d\n", res
);
162 printf("Sending invalid command...\n");
163 res
= send_cmd( fd
, (char)res
);
164 printf("Back from attempt. Got %d back\n", res
);