Changed door code to use direct serial instead of llogin
[tpg/opendispense2.git] / src / server / handler_coke.c
index 867ac6a..79d0a46 100644 (file)
@@ -21,7 +21,7 @@
 #include <pthread.h>
 
 #define READ_TIMEOUT   2       // 2 seconds for ReadChar
-#define TRACE_COKE     0
+#define TRACE_COKE     1
 
 #if TRACE_COKE
 # define TRACE(v...) do{printf("%s: ",__func__);printf(v);}while(0)
@@ -53,13 +53,14 @@ char        *gsCoke_SerialPort = "/dev/ttyS0";
 regex_t        gCoke_StatusRegex;
  int   gaCoke_CachedStatus[7];
 pthread_mutex_t        gCoke_Mutex = PTHREAD_MUTEX_INITIALIZER;
+time_t gtCoke_LastDispenseTime;
 
 // == CODE ===
 int Coke_InitHandler()
 {
        CompileRegex(&gCoke_StatusRegex, "^slot\\s+([0-9]+)\\s+([^:]+):([a-zA-Z]+)\\s*", REG_EXTENDED);
        
-       printf("connecting to coke machine...\n");
+       printf("Connecting to coke machine on '%s'\n", gsCoke_SerialPort);
        
        giCoke_SerialFD = InitSerial(gsCoke_SerialPort, 9600);
        if( giCoke_SerialFD == -1 ) {
@@ -89,6 +90,8 @@ int Coke_InitHandler()
                        
                        Coke_int_UpdateSlotStatuses();
                }
+               else
+                       fprintf(stderr, "Coke machine timed out.\n");
        }
        
        AddPeriodicFunction(Coke_int_UpdateSlotStatuses);
@@ -153,7 +156,8 @@ void Coke_int_UpdateSlotStatuses(void)
        
        for( i = 0; i <= 6; i ++ )
        {
-               len = ReadLine(sizeof tmp, tmp);
+               // Read until non-blank line
+               while( (len = ReadLine(sizeof tmp, tmp)) == 0 ) ;
                if( len == -1 ) {
                        TRACE("Read failed on slot %i\n", i);
                        goto ret;       // I give up :(
@@ -199,6 +203,14 @@ int Coke_DoDispense(int UNUSED(User), int Item)
        // Can't dispense if the machine is not connected
        if( giCoke_SerialFD == -1 )
                return -2;
+
+       // Make sure there are not two dispenses within n seconds
+       if( time(NULL) - gtCoke_LastDispenseTime < 10 )
+       {
+               printf("Wait %li seconds?\n", 10 - (time(NULL) - gtCoke_LastDispenseTime));
+               sleep( 10 - (time(NULL) - gtCoke_LastDispenseTime) );
+               printf("wait done\n");
+       }
        
        // LOCK
        pthread_mutex_lock(&gCoke_Mutex);
@@ -266,6 +278,8 @@ int Coke_DoDispense(int UNUSED(User), int Item)
                char buf[512];
                read(giCoke_SerialFD, buf, 512);        // Flush
        }
+
+       gtCoke_LastDispenseTime = time(NULL);
        
        // Release and return
        pthread_mutex_unlock(&gCoke_Mutex);

UCC git Repository :: git.ucc.asn.au