Initial move to common config code directory
[tpg/opendispense2.git] / src / server / handler_coke.c
index a8a1fee..b9a9cf3 100644 (file)
  * - Remember, the coke machine echoes your text back to you!
  */
 #include "common.h"
+#include "../common/config.h"
 #include <stdio.h>
 #include <string.h>
+#include <stdarg.h>
+#include <pthread.h>
 #include <unistd.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <regex.h>
+#include <modbus/modbus.h>
+#include <errno.h>
 
-#define READ_TIMEOUT   2       // 2 seconds for ReadChar
-#define TRACE_COKE     1
+#define MIN_DISPENSE_PERIOD    2
+#define COKE_RECONNECT_RATELIMIT       2
+
+// === CONSTANTS ===
+const int      ciCoke_MinPeriod = 5;
+const int      ciCoke_DropBitBase = 1024;
+const int      ciCoke_StatusBitBase = 16;
 
 // === IMPORTS ===
 
  int   Coke_InitHandler();
  int   Coke_CanDispense(int User, int Item);
  int   Coke_DoDispense(int User, int Item);
- int   Writef(const char *Format, ...);
- int   WaitForColon();
- int   ReadLine(int len, char *output);
+ int   Coke_int_ConnectToPLC(void);
+ int   Coke_int_GetSlotFromItem(int Item, int bDispensing);
+ int   Coke_int_IsSlotEmpty(int Slot);
+ int   Coke_int_DropSlot(int Slot);
+static int     _ReadBit(int BitNum, uint8_t *Value);
+static int     _WriteBit(int BitNum, uint8_t Value);
 
 // === GLOBALS ===
 tHandler       gCoke_Handler = {
@@ -38,307 +48,223 @@ tHandler  gCoke_Handler = {
        Coke_CanDispense,
        Coke_DoDispense
 };
-char   *gsCoke_SerialPort = "/dev/ttyS0";
- int   giCoke_SerialFD;
-regex_t        gCoke_StatusRegex;
+const char     *gsCoke_ModbusAddress = "130.95.13.73";
+modbus_t       *gCoke_Modbus;
+time_t gtCoke_LastDispenseTime;
+time_t gtCoke_LastReconnectTime;
+ int   gbCoke_DummyMode = 1;
+ int   giCoke_NextCokeSlot = 0;
 
 // == CODE ===
 int Coke_InitHandler()
 {
-       printf("connecting to coke machine...\n");
-       
-       giCoke_SerialFD = InitSerial(gsCoke_SerialPort, 9600);
-       if( giCoke_SerialFD == -1 ) {
-               fprintf(stderr, "ERROR: Unable to open coke serial port ('%s')\n", gsCoke_SerialPort);
+       // Configuable dummy/blank mode (all dispenses succeed)
+       // TODO: Find a better way of handling missing/invalid options
+       if( Config_GetValueCount("coke_dummy_mode") > 0 )
+       {
+               gbCoke_DummyMode = Config_GetValue_Bool("coke_dummy_mode", 0);
+               if(gbCoke_DummyMode == -1)      gbCoke_DummyMode = 0;
        }
-       else {
-               // Reset the slot names.
-               // - Dunno why this is needed, but the machine plays silly
-               //   sometimes.
-               Writef("n0 Slot0\n");
-               WaitForColon();
-               Writef("n1 Slot1\n");
-               WaitForColon();
-               Writef("n2 Slot2\n");
-               WaitForColon();
-               Writef("n3 Slot3\n");
-               WaitForColon();
-               Writef("n4 Slot4\n");
-               WaitForColon();
-               Writef("n5 Slot5\n");
-               WaitForColon();
-               Writef("n6 Coke\n");
+
+       // Open modbus
+       if( !gbCoke_DummyMode )
+       {
+               Coke_int_ConnectToPLC();
        }
-       
-       CompileRegex(&gCoke_StatusRegex, "^slot\\s+([0-9]+)\\s+([^:]+):([a-zA-Z]+)\\s*", REG_EXTENDED);
+
        return 0;
 }
 
 int Coke_CanDispense(int UNUSED(User), int Item)
 {
-       char    tmp[40], *status;
-       regmatch_t      matches[4];
-        int    ret;
-
-       // Sanity please
-       if( Item < 0 || Item > 6 )      return -1;      // -EYOURBAD
-       
-       // Can't dispense if the machine is not connected
-       if( giCoke_SerialFD == -1 )
-               return -2;
-       
-       #if TRACE_COKE
-       printf("Coke_CanDispense: Flushing\n");
-       #endif
+        int    slot;
        
+       // Check for 'dummy' mode
+       if( gbCoke_DummyMode )
+               return 0;
+
+       // Get slot
+       slot = Coke_int_GetSlotFromItem(Item, 0);
+       if(slot < 0)    return -1;
+
+       return Coke_int_IsSlotEmpty(slot);
+}
+
+/**
+ * \brief Actually do a dispense from the coke machine
+ */
+int Coke_DoDispense(int UNUSED(User), int Item)
+{
+        int    slot;
+       // Check for 'dummy' mode
+       if( gbCoke_DummyMode )
+               return 0;
+
+       // Get slot
+       slot = Coke_int_GetSlotFromItem(Item, 1);
+       if(slot < 0)    return -1;
        
-       // Wait for a prompt
-       ret = 0;
-       while( WaitForColon() && ret < 3 )
+       // Make sure there are not two dispenses within n seconds
+       if( time(NULL) - gtCoke_LastDispenseTime < ciCoke_MinPeriod )
        {
-               // Flush the input buffer
-               char    tmpbuf[512];
-               read(giCoke_SerialFD, tmpbuf, sizeof(tmpbuf));
-               #if TRACE_COKE
-               printf("Coke_CanDispense: sending 'd7'\n");
-               #endif
-               Writef("d7\r\n");
-               ret ++;
+                int    delay = ciCoke_MinPeriod - (time(NULL) - gtCoke_LastDispenseTime);
+               Debug_Debug("Waiting for %i seconds (rate limit)", delay);
+               sleep( delay );
+               Debug_Debug("wait done");
        }
-       // Check for a timeout error
-       if( !(ret < 3) ) {
-               fprintf(stderr, "Coke machine timed out\n");
-               return -2;      // -EMYBAD
+       gtCoke_LastDispenseTime = time(NULL);
+
+       return Coke_int_DropSlot(slot);
+}
+
+// --- INTERNAL FUNCTIONS ---
+int Coke_int_ConnectToPLC(void)
+{
+       // Ratelimit
+       if( time(NULL) - gtCoke_LastReconnectTime < COKE_RECONNECT_RATELIMIT )
+               return -1;
+
+       if( !gCoke_Modbus )
+       {
+               gCoke_Modbus = modbus_new_tcp(gsCoke_ModbusAddress, 502);
+               if( !gCoke_Modbus )
+               {
+                       perror("coke - modbus_new_tcp");
+                       gtCoke_LastReconnectTime = time(NULL);
+                       return 1;
+               }
        }
+       else {
+               // Preven resource leaks
+               modbus_close(gCoke_Modbus);
+       }
+       Debug_Notice("Connecting to coke PLC machine on '%s'\n", gsCoke_ModbusAddress);
        
-       // You need to do a 'd7' before reading the status
-       // - Otherwise it sometimes reports a full slot as empty
-       //   [TPG] (2011-02-19)
-       if( ret == 0 )
+       if( modbus_connect(gCoke_Modbus) )
        {
-               Writef("d7\r\n");
-               WaitForColon();
+               gtCoke_LastReconnectTime = time(NULL);
+               perror("coke - modbus_connect");
+               modbus_free(gCoke_Modbus);
+               gCoke_Modbus = NULL;
+               return 1;
        }
 
-       // TODO: Handle "not ok" response to D7
-       
-       #if TRACE_COKE
-       printf("Coke_CanDispense: sending 's%i'\n", Item);
-       #endif
+       return 0;
+}
+
+int Coke_int_GetSlotFromItem(int Item, int bDispensing)
+{
+       if( Item < 0 || Item > 6 )      return -1;
+
+       // Non-coke slots
+       if( Item < 6 )
+               return Item;
        
-       // Ask the coke machine
-       Writef("s%i\r\n", Item);
-
-       #if TRACE_COKE
-       printf("Coke_CanDispense: reading response\n");
-       #endif
-       // Read from the machine (ignoring empty lines)
-       while( (ret = ReadLine(sizeof(tmp)-1, tmp)) == 0 );
-       #if TRACE_COKE
-       printf("ret = %i, tmp = '%s'\n", ret, tmp);
-       #endif
-       // Read back-echoed lines
-       while( tmp[0] == ':' || tmp[1] != 'l' )
+       // Iterate though coke slots and find the first one with a drink avaliable
+       // `giCoke_NextCokeSlot` ensures that the slots rotate
+       for( int i = 0; i < 4; i ++ )
        {
-               ret = ReadLine(sizeof(tmp)-1, tmp);
-               printf("ret = %i, tmp = '%s'\n", ret, tmp);
-       }
-
-       // Catch an error       
-       if( ret <= 0 ) {
-               fprintf(stderr, "Coke machine is not being chatty (read = %i)\n", ret);
-               if( ret == -1 ) {
-                       perror("Coke Machine");
+               int slot = 6 + (i + giCoke_NextCokeSlot) % 4;
+               if( !Coke_int_IsSlotEmpty(slot) )
+               {
+                       if(bDispensing) {
+                               giCoke_NextCokeSlot ++;
+                               if(giCoke_NextCokeSlot == 4)    giCoke_NextCokeSlot = 0;
+                       }
+                       return slot;    // Drink avaliable
                }
-               return -1;
        }
-       
-       #if TRACE_COKE
-       printf("Coke_CanDispense: wait for the prompt again\n");
-       #endif
 
-       // Eat rest of response
-       WaitForColon();
+       // Coke is empty!
+       // - Return 6, even if it's empty, the checks elsewhere will avoid problems
+       return 6;
+}
 
-       // Parse status response
-       ret = RunRegex(&gCoke_StatusRegex, tmp, sizeof(matches)/sizeof(matches[0]), matches, "Bad Response");
-       if( ret ) {
-               return -1;
-       }
+int Coke_int_IsSlotEmpty(int Slot)
+{
+       uint8_t status;
 
-       // Get slot status
-       tmp[ matches[3].rm_eo ] = '\0';
-       status = &tmp[ matches[3].rm_so ];
-       
-       #if TRACE_COKE
-       printf("Coke_CanDispense: Machine responded slot status '%s'\n", status);
-       #endif
+       if( Slot < 0 || Slot > 9 )      return -1;
 
-       if( strcmp(status, "full") == 0 )
-               return 0;
+       errno = 0;
+       if( _ReadBit(ciCoke_StatusBitBase + Slot, &status) )
+       {
+               perror("Coke_int_IsSlotEmpty - modbus_read_bits");
+               return -2;
+       }
 
-       return 1;
+       return status == 0;
 }
 
-/**
- * \brief Actually do a dispense from the coke machine
- */
-int Coke_DoDispense(int UNUSED(User), int Item)
+int Coke_int_DropSlot(int Slot)
 {
-       char    tmp[32];
-        int    ret;
+       uint8_t res;
 
-       // Sanity please
-       if( Item < 0 || Item > 6 )      return -1;
+       if(Slot < 0 || Slot > 9)        return -1;
 
-       // Can't dispense if the machine is not connected
-       if( giCoke_SerialFD == -1 )
+       // Check if a dispense is in progress
+       if( _ReadBit(ciCoke_DropBitBase + Slot, &res) )
+       {
+               perror("Coke_int_DropSlot - modbus_read_bits#1");
                return -2;
-       
-       #if TRACE_COKE
-       printf("Coke_DoDispense: flushing input\n");
-       #endif
-       
-       // Wait for prompt
-       ret = 0;
-       while( WaitForColon() && ret < 3 )
+       }
+       if( res != 0 )
        {
-               // Flush the input buffer
-               char    tmpbuf[512];
-               read(giCoke_SerialFD, tmpbuf, sizeof(tmpbuf));
-               #if TRACE_COKE
-               printf("Coke_DoDispense: sending 'd7'\n");
-               #endif
-               Writef("d7\r\n");
+               // Manual dispense in progress
+               return -1;
        }
 
-       #if TRACE_COKE
-       printf("Coke_DoDispense: sending 'd%i'\n", Item);
-       #endif
        // Dispense
-       Writef("d%i\r\n", Item);
-       
-       // Read empty lines and echo-backs
-       do {
-               ret = ReadLine(sizeof(tmp)-1, tmp);
-               if( ret == -1 ) return -1;
-               #if TRACE_COKE
-               printf("Coke_DoDispense: read %i '%s'\n", ret, tmp);
-               #endif
-       } while( ret == 0 || tmp[0] == ':' || tmp[0] == 'd' );
-
-       WaitForColon(); // Eat up rest of response
-       
-       #if TRACE_COKE
-       printf("Coke_DoDispense: done\n");
-       #endif
-
-       // TODO: Regex
-       if( strcmp(tmp, "ok") == 0 ) {
-               // We think dispense worked
-               // - The machine returns 'ok' if an empty slot is dispensed, even if
-               //   it doesn't actually try to dispense (no sound)
-               return 0;
+       if( _WriteBit(ciCoke_DropBitBase + Slot, 1) )
+       {
+               perror("Coke_int_DropSlot - modbus_write_bit");
+               return -2;
        }
 
-       printf("Machine returned unknown value '%s'\n", tmp);   
-
-       return -1;
-}
-
-char ReadChar()
-{
-       fd_set  readfs;
-       char    ch = 0;
-        int    ret;
-       struct timeval  timeout;
-       
-       timeout.tv_sec = READ_TIMEOUT;
-       timeout.tv_usec = 0;
-       
-       FD_ZERO(&readfs);
-       FD_SET(giCoke_SerialFD, &readfs);
-       
-       ret = select(giCoke_SerialFD+1, &readfs, NULL, NULL, &timeout);
-       if( ret == 0 )  return 0;       // Timeout
-       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;
+       // Check that it started
+       usleep(1000);   // 1ms
+       if( _ReadBit(ciCoke_DropBitBase + Slot, &res) )
+       {
+               perror("Coke_int_DropSlot - modbus_read_bits#2");
+               return -2;
        }
-       
-       return ch;
-}
-
-int Writef(const char *Format, ...)
-{
-       va_list args;
-        int    len;
-       
-       va_start(args, Format);
-       len = vsnprintf(NULL, 0, Format, args);
-       va_end(args);
-       
+       if( res == 0 )
        {
-               char    buf[len+1];
-               va_start(args, Format);
-               vsnprintf(buf, len+1, Format, args);
-               va_end(args);
-               
-               #if DEBUG
-               printf("Writef: %s", buf);
-               #endif
-               
-               return write(giCoke_SerialFD, buf, len);
+               // Oops!, no drink
+               Log_Error("Drink dispense failed, bit lowered too quickly");
+               Debug_Notice("Drink dispense failed, bit lowered too quickly");
+               return 1;
        }
        
+       return 0;
 }
 
-int WaitForColon()
+int _ReadBit(int BitNum, uint8_t *Value)
 {
-       fd_set  readfs;
-       char    ch = 0;
-       
-       FD_SET(giCoke_SerialFD, &readfs);
-       
-       while( (ch = ReadChar()) != ':' && ch != 0);
-       
-       if( ch == 0 )   return -1;      // Timeout
-       
-       return 0;
+       errno = 0;
+       if( !gCoke_Modbus && Coke_int_ConnectToPLC() )
+               return -1;
+       if( modbus_read_bits( gCoke_Modbus, BitNum, 1, Value) >= 0 )
+               return 0;
+       if( Coke_int_ConnectToPLC() )
+               return -1;
+       if( modbus_read_bits( gCoke_Modbus, BitNum, 1, Value) >= 0 )
+               return 0;
+       return -1;
 }
 
-int ReadLine(int len, char *output)
+int _WriteBit(int BitNum, uint8_t Value)
 {
-       char    ch;
-        int    i = 0;
-       
-       for(;;)
-       {
-               ch = ReadChar();
-                       
-               if( i < len )
-                       output[i++] = ch;
-               
-               if( ch == '\0' ) {
-                       break;
-               }
-               if( ch == '\n' || ch == '\r' ) {
-                       if( i < len )
-                               output[--i] = '\0';
-                       break;
-               }
-       }
-
-       //printf("ReadLine: output=%s\n", output);
-
-       if( !ch )       return -1;
-       return i;
+       errno = 0;
+       if( !gCoke_Modbus && Coke_int_ConnectToPLC() )
+               return -1;
+       if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
+               return 0;
+       // Error case
+       if( Coke_int_ConnectToPLC() )
+               return -1;
+       if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
+               return 0;
+       return -1;
 }
 
-

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