3 * UCC (University [of WA] Computer Club) Electronic Accounting System
5 * handler_coke.c - Coke controller code
7 * This file is licenced under the 3-clause BSD Licence. See the file
8 * COPYING for full details.
11 * - Remember, the coke machine echoes your text back to you!
19 #include <modbus/modbus.h>
21 #define MIN_DISPENSE_PERIOD 5
24 const int ciCoke_MinPeriod = 5;
25 const int ciCoke_DropBitBase = 0;
26 const int ciCoke_StatusBitBase = 0;
31 int Coke_InitHandler();
32 int Coke_CanDispense(int User, int Item);
33 int Coke_DoDispense(int User, int Item);
36 tHandler gCoke_Handler = {
42 const char *gsCoke_ModbusAddress = "130.95.13.73";
43 modbus_t *gCoke_Modbus;
44 time_t gtCoke_LastDispenseTime;
45 int gbCoke_DummyMode = 1;
48 int Coke_InitHandler()
50 // Configuable dummy/blank mode (all dispenses succeed)
51 // TODO: Find a better way of handling missing/invalid options
52 if( Config_GetValueCount("coke_dummy_mode") > 0 )
54 gbCoke_DummyMode = Config_GetValue_Bool("coke_dummy_mode", 0);
55 if(gbCoke_DummyMode == -1) gbCoke_DummyMode = 0;
59 if( !gbCoke_DummyMode )
61 printf("Connecting to coke machine on '%s'\n", gsCoke_ModbusAddress);
63 modbus_new_tcp(gsCoke_ModbusAddress, 502);
66 perror("coke - modbus_new_tcp");
69 if( gCoke_Modbus && modbus_connect(gCoke_Modbus) )
71 perror("coke - modbus_connect");
72 modbus_free(gCoke_Modbus);
80 int Coke_CanDispense(int UNUSED(User), int Item)
84 if( Item < 0 || Item > 6 ) return -1;
86 // Check for 'dummy' mode
87 if( gbCoke_DummyMode )
90 // Can't dispense if the machine is not connected
94 if( modbus_read_bits(gCoke_Modbus, ciCoke_StatusBitBase + Item, 1, &status) )
96 // TODO: Check for a connection issue
97 perror("Coke_CanDispense - modbus_read_bits");
104 * \brief Actually do a dispense from the coke machine
106 int Coke_DoDispense(int UNUSED(User), int Item)
109 if( Item < 0 || Item > 6 ) return -1;
111 // Check for 'dummy' mode
112 if( gbCoke_DummyMode )
115 // Can't dispense if the machine is not connected
119 // Make sure there are not two dispenses within n seconds
120 if( time(NULL) - gtCoke_LastDispenseTime < ciCoke_MinPeriod )
122 int delay = ciCoke_MinPeriod - (time(NULL) - gtCoke_LastDispenseTime);
123 printf("Wait %i seconds?\n", delay);
125 printf("wait done\n");
129 if( modbus_write_bit(gCoke_Modbus, ciCoke_DropBitBase + Item, 1) )
131 // TODO: Handle connection issues
132 perror("Coke_DoDispense - modbus_write_bit");