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 printf("Connecting to coke machine on '%s'\n", gsCoke_ModbusAddress);
52 // Configuable dummy/blank mode (all dispenses succeed)
53 // TODO: Find a better way of handling missing/invalid options
54 if( Config_GetValueCount("coke_dummy_mode") > 0 )
56 gbCoke_DummyMode = Config_GetValue_Bool("coke_dummy_mode", 0);
57 if(gbCoke_DummyMode == -1) gbCoke_DummyMode = 0;
61 modbus_new_tcp(gsCoke_ModbusAddress, 502);
64 perror("coke - modbus_new_tcp");
68 if( modbus_connect(gCoke_Modbus) )
70 perror("coke - modbus_connect");
77 int Coke_CanDispense(int UNUSED(User), int Item)
81 if( Item < 0 || Item > 6 ) return -1;
83 // Check for 'dummy' mode
84 if( gbCoke_DummyMode )
87 // Can't dispense if the machine is not connected
91 modbus_read_bits(gCoke_Modbus, ciCoke_StatusBitBase + Item, 1, &status);
97 * \brief Actually do a dispense from the coke machine
99 int Coke_DoDispense(int UNUSED(User), int Item)
102 if( Item < 0 || Item > 6 ) return -1;
104 // Check for 'dummy' mode
105 if( gbCoke_DummyMode )
108 // Can't dispense if the machine is not connected
112 // Make sure there are not two dispenses within n seconds
113 if( time(NULL) - gtCoke_LastDispenseTime < ciCoke_MinPeriod )
115 int delay = ciCoke_MinPeriod - (time(NULL) - gtCoke_LastDispenseTime);
116 printf("Wait %i seconds?\n", delay);
118 printf("wait done\n");
121 // Dispense (with locking)
122 modbus_write_bit(gCoke_Modbus, ciCoke_DropBitBase + Item, 1);