2b7d0f8e8d1ee1b60283b8799e6ab4fb0162280c
[tpg/opendispense2.git] / src / server / handler_coke.c
1 /*
2  * OpenDispense 2 
3  * UCC (University [of WA] Computer Club) Electronic Accounting System
4  *
5  * handler_coke.c - Coke controller code
6  *
7  * This file is licenced under the 3-clause BSD Licence. See the file
8  * COPYING for full details.
9  *
10  * NOTES:
11  * - Remember, the coke machine echoes your text back to you!
12  */
13 #include "common.h"
14 #include "../common/config.h"
15 #include <stdio.h>
16 #include <string.h>
17 #include <stdarg.h>
18 #include <pthread.h>
19 #include <unistd.h>
20 #include <modbus/modbus.h>
21 #include <errno.h>
22
23 #define MIN_DISPENSE_PERIOD     2
24 #define COKE_RECONNECT_RATELIMIT        2
25
26 // === CONSTANTS ===
27 const int       ciCoke_MinPeriod = 5;
28 const int       ciCoke_DropBitBase = 1024;
29 const int       ciCoke_StatusBitBase = 16;
30
31 // === IMPORTS ===
32
33 // === PROTOTYPES ===
34  int    Coke_InitHandler();
35  int    Coke_CanDispense(int User, int Item);
36  int    Coke_DoDispense(int User, int Item);
37  int    Coke_int_ConnectToPLC(void);
38  int    Coke_int_GetSlotFromItem(int Item, int bDispensing);
39  int    Coke_int_IsSlotEmpty(int Slot);
40  int    Coke_int_DropSlot(int Slot);
41 static int      _ReadBit(int BitNum, uint8_t *Value);
42 static int      _WriteBit(int BitNum, uint8_t Value);
43
44 // === GLOBALS ===
45 tHandler        gCoke_Handler = {
46         "coke",
47         Coke_InitHandler,
48         Coke_CanDispense,
49         Coke_DoDispense
50 };
51 // - Config
52 const char      *gsCoke_ModbusAddress = "130.95.13.73";
53  int            giCoke_ModbusPort = 502;
54 bool    gbCoke_DummyMode = false;
55 // - State
56 modbus_t        *gCoke_Modbus;
57 time_t  gtCoke_LastDispenseTime;
58 time_t  gtCoke_LastReconnectTime;
59  int    giCoke_NextCokeSlot = 0;
60
61 // == CODE ===
62 int Coke_InitHandler()
63 {
64         // Configuable dummy/blank mode (all dispenses succeed)
65         // TODO: Find a better way of handling missing/invalid options
66         Config_GetValue_Bool("coke_dummy_mode", &gbCoke_DummyMode);
67
68         // Open modbus
69         if( !gbCoke_DummyMode )
70         {
71                 Coke_int_ConnectToPLC();
72         }
73
74         return 0;
75 }
76
77 int Coke_CanDispense(int UNUSED(User), int Item)
78 {
79          int    slot;
80         
81         // Check for 'dummy' mode
82         if( gbCoke_DummyMode )
83                 return 0;
84
85         // Get slot
86         slot = Coke_int_GetSlotFromItem(Item, 0);
87         if(slot < 0)    return -1;
88
89         return Coke_int_IsSlotEmpty(slot);
90 }
91
92 /**
93  * \brief Actually do a dispense from the coke machine
94  */
95 int Coke_DoDispense(int UNUSED(User), int Item)
96 {
97          int    slot;
98         // Check for 'dummy' mode
99         if( gbCoke_DummyMode )
100                 return 0;
101
102         // Get slot
103         slot = Coke_int_GetSlotFromItem(Item, 1);
104         if(slot < 0)    return -1;
105         
106         // Make sure there are not two dispenses within n seconds
107         if( time(NULL) - gtCoke_LastDispenseTime < ciCoke_MinPeriod )
108         {
109                  int    delay = ciCoke_MinPeriod - (time(NULL) - gtCoke_LastDispenseTime);
110                 Debug_Debug("Waiting for %i seconds (rate limit)", delay);
111                 sleep( delay );
112                 Debug_Debug("wait done");
113         }
114         gtCoke_LastDispenseTime = time(NULL);
115
116         return Coke_int_DropSlot(slot);
117 }
118
119 // --- INTERNAL FUNCTIONS ---
120 int Coke_int_ConnectToPLC(void)
121 {
122         // Ratelimit
123         time_t elapsed = time(NULL) - gtCoke_LastReconnectTime;
124         if( elapsed < COKE_RECONNECT_RATELIMIT ) {
125                 Debug_Notice("Not reconnecting, only %llis have pased, %i limit", (long long)elapsed, COKE_RECONNECT_RATELIMIT);
126                 errno = EAGAIN;
127                 return -1;
128         }
129
130         if( !gCoke_Modbus )
131         {
132                 gCoke_Modbus = modbus_new_tcp(gsCoke_ModbusAddress, giCoke_ModbusPort);
133                 if( !gCoke_Modbus )
134                 {
135                         perror("coke - modbus_new_tcp");
136                         gtCoke_LastReconnectTime = time(NULL);
137                         return 1;
138                 }
139         }
140         else {
141                 // Preven resource leaks
142                 modbus_close(gCoke_Modbus);
143         }
144         Debug_Notice("Connecting to coke PLC machine on '%s':%i", gsCoke_ModbusAddress, giCoke_ModbusPort);
145         
146         if( modbus_connect(gCoke_Modbus) )
147         {
148                 gtCoke_LastReconnectTime = time(NULL);
149                 perror("coke - modbus_connect");
150                 modbus_free(gCoke_Modbus);
151                 gCoke_Modbus = NULL;
152                 return 1;
153         }
154
155         return 0;
156 }
157
158 int Coke_int_GetSlotFromItem(int Item, int bDispensing)
159 {
160         if( Item < 0 || Item > 6 )      return -1;
161
162         // Non-coke slots
163         if( Item < 6 )
164                 return Item;
165         
166         // Iterate though coke slots and find the first one with a drink avaliable
167         // `giCoke_NextCokeSlot` ensures that the slots rotate
168         for( int i = 0; i < 4; i ++ )
169         {
170                 int slot = 6 + (i + giCoke_NextCokeSlot) % 4;
171                 if( !Coke_int_IsSlotEmpty(slot) )
172                 {
173                         if(bDispensing) {
174                                 giCoke_NextCokeSlot ++;
175                                 if(giCoke_NextCokeSlot == 4)    giCoke_NextCokeSlot = 0;
176                         }
177                         return slot;    // Drink avaliable
178                 }
179         }
180
181         // Coke is empty!
182         // - Return 6, even if it's empty, the checks elsewhere will avoid problems
183         return 6;
184 }
185
186 int Coke_int_IsSlotEmpty(int Slot)
187 {
188         uint8_t status;
189
190         if( Slot < 0 || Slot > 9 )      return -1;
191
192         errno = 0;
193         if( _ReadBit(ciCoke_StatusBitBase + Slot, &status) )
194         {
195                 perror("Coke_int_IsSlotEmpty - modbus_read_bits");
196                 return -2;
197         }
198
199         return status == 0;
200 }
201
202 int Coke_int_DropSlot(int Slot)
203 {
204         uint8_t res;
205
206         if(Slot < 0 || Slot > 9)        return -1;
207
208         // Check if a dispense is in progress
209         if( _ReadBit(ciCoke_DropBitBase + Slot, &res) )
210         {
211                 perror("Coke_int_DropSlot - modbus_read_bits#1");
212                 return -2;
213         }
214         if( res != 0 )
215         {
216                 // Manual dispense in progress
217                 return -1;
218         }
219
220         // Dispense
221         if( _WriteBit(ciCoke_DropBitBase + Slot, 1) )
222         {
223                 perror("Coke_int_DropSlot - modbus_write_bit");
224                 return -2;
225         }
226
227         // Check that it started
228         usleep(1000);   // 1ms
229         if( _ReadBit(ciCoke_DropBitBase + Slot, &res) )
230         {
231                 perror("Coke_int_DropSlot - modbus_read_bits#2");
232                 return -2;
233         }
234         if( res == 0 )
235         {
236                 // Oops!, no drink
237                 Log_Error("Drink dispense failed, bit lowered too quickly");
238                 Debug_Notice("Drink dispense failed, bit lowered too quickly");
239                 return 1;
240         }
241         
242         return 0;
243 }
244
245 int _ReadBit(int BitNum, uint8_t *Value)
246 {
247         errno = 0;
248         if( !gCoke_Modbus && Coke_int_ConnectToPLC() )
249                 return -1;
250         if( modbus_read_bits( gCoke_Modbus, BitNum, 1, Value) >= 0 )
251                 return 0;
252         if( Coke_int_ConnectToPLC() )
253                 return -1;
254         if( modbus_read_bits( gCoke_Modbus, BitNum, 1, Value) >= 0 )
255                 return 0;
256         return -1;
257 }
258
259 int _WriteBit(int BitNum, uint8_t Value)
260 {
261         errno = 0;
262         if( !gCoke_Modbus && Coke_int_ConnectToPLC() )
263                 return -1;
264         if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
265                 return 0;
266         // Error case
267         if( Coke_int_ConnectToPLC() )
268                 return -1;
269         if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
270                 return 0;
271         return -1;
272 }
273

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