int Coke_InitHandler();
int Coke_CanDispense(int User, int Item);
int Coke_DoDispense(int User, int Item);
+void WaitForColon();
+ int ReadLine(int len, char *output);
// === GLOBALS ===
tHandler gCoke_Handler = {
// Sanity please
if( Item < 0 || Item > 6 ) return -1; // -EYOURBAD
+ write(giCoke_SerialFD, "\r\n", 2);
+ write(giCoke_SerialFD, "\r\n", 2);
+ write(giCoke_SerialFD, "\r\n", 2);
+
+ WaitForColon();
+
// Ask the coke machine
- sprintf(tmp, "s%i\n", Item);
- write(giCoke_SerialFD, tmp, 2);
-
- // Wait a little
- sleep(250);
+ sprintf(tmp, "s%i\r\n", Item);
+ write(giCoke_SerialFD, tmp, 4);
+
+ WaitForColon();
- // Read the response
- tmp[0] = '\0';
- ret = read(giCoke_SerialFD, tmp, sizeof(tmp)-1);
- //printf("ret = %i\n", ret);
+ ret = ReadLine(sizeof(tmp)-1, tmp);
+ printf("ret = %i, tmp = '%s'\n", ret, tmp);
+
if( ret <= 0 ) {
fprintf(stderr, "Coke machine is not being chatty (read = %i)\n", ret);
+ if( ret == -1 ) {
+ perror("Coke Machine");
+ }
return -1;
}
ret = RunRegex(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, "Bad Response");
// Sanity please
if( Item < 0 || Item > 6 ) return -1;
+ WaitForColon();
+
// Dispense
- sprintf(tmp, "d%i\n", Item);
- write(giCoke_SerialFD, tmp, 2);
+ sprintf(tmp, "d%i\r\n", Item);
+ write(giCoke_SerialFD, tmp, 4);
- // Wait a little
- sleep(250);
+ WaitForColon();
// Get status
- read(giCoke_SerialFD, tmp, sizeof(tmp)-1);
- regexec(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, 0);
+ ReadLine(sizeof(tmp)-1, tmp);
tmp[ matches[3].rm_eo ] = '\0';
status = &tmp[ matches[3].rm_so ];
return 0;
}
+char ReadChar()
+{
+ fd_set readfs;
+ char ch = 0;
+ int ret;
+
+ FD_ZERO(&readfs);
+ FD_SET(giCoke_SerialFD, &readfs);
+
+ ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, NULL);
+ if( ret != 1 ) {
+ printf("readchar return %i\n", ret);
+ return 0;
+ }
+
+ ret = read(giCoke_SerialFD, &ch, 1);
+ if( ret != 1 ) {
+ printf("ret = %i\n", ret);
+ return 0;
+ }
+
+ return ch;
+}
+
+void WaitForColon()
+{
+ fd_set readfs;
+ char ch = 0;
+
+ FD_SET(giCoke_SerialFD, &readfs);
+
+ while( (ch = ReadChar()) != ':' && ch != 0);
+}
+
+int ReadLine(int len, char *output)
+{
+ char ch;
+ int i = 0;
+
+ for(;;)
+ {
+ ch = ReadChar();
+
+
+ if( i < len )
+ output[i++] = ch;
+
+ if( ch == '\0' ) {
+ return -1;
+ }
+ if( ch == '\n' || ch == '\r' ) {
+ if( i < len )
+ output[--i] = '\0';
+ return i;
+ }
+ }
+}
+
int baud;
int fd;
-
- fd = open(File, O_RDWR | O_NOCTTY);
+ fd = open(File, O_RDWR | O_NOCTTY | O_NONBLOCK);
if( fd == -1 ) return -1;
switch(BaudRate)
{
case 9600: baud = B9600; break;
- default: return ;
+ default: close(fd); return -1;
}
- cfmakeraw(&info); // Sets 8N1
+ info.c_lflag = 0; // Non-Canoical, No Echo
+ info.c_cflag = baud | CS8 | CLOCAL | CREAD; // baud, 8N1
cfsetspeed(&info, baud);
+ info.c_cc[VTIME] = 0; // No time limit
+ info.c_cc[VMIN] = 1; // Block until 1 char
+ tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &info);
return fd;