Server - Fixed leaked file handles in both itemdb and modbus
[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 <stdio.h>
15 #include <string.h>
16 #include <stdarg.h>
17 #include <pthread.h>
18 #include <unistd.h>
19 #include <modbus/modbus.h>
20 #include <errno.h>
21
22 #define MIN_DISPENSE_PERIOD     2
23 #define COKE_RECONNECT_RATELIMIT        2
24
25 // === CONSTANTS ===
26 const int       ciCoke_MinPeriod = 5;
27 const int       ciCoke_DropBitBase = 1024;
28 const int       ciCoke_StatusBitBase = 16;
29
30 // === IMPORTS ===
31
32 // === PROTOTYPES ===
33  int    Coke_InitHandler();
34  int    Coke_CanDispense(int User, int Item);
35  int    Coke_DoDispense(int User, int Item);
36  int    Coke_int_ConnectToPLC(void);
37  int    Coke_int_GetSlotFromItem(int Item, int bDispensing);
38  int    Coke_int_IsSlotEmpty(int Slot);
39  int    Coke_int_DropSlot(int Slot);
40 static int      _ReadBit(int BitNum, uint8_t *Value);
41 static int      _WriteBit(int BitNum, uint8_t Value);
42
43 // === GLOBALS ===
44 tHandler        gCoke_Handler = {
45         "coke",
46         Coke_InitHandler,
47         Coke_CanDispense,
48         Coke_DoDispense
49 };
50 const char      *gsCoke_ModbusAddress = "130.95.13.73";
51 modbus_t        *gCoke_Modbus;
52 time_t  gtCoke_LastDispenseTime;
53 time_t  gtCoke_LastReconnectTime;
54  int    gbCoke_DummyMode = 1;
55  int    giCoke_NextCokeSlot = 0;
56
57 // == CODE ===
58 int Coke_InitHandler()
59 {
60         // Configuable dummy/blank mode (all dispenses succeed)
61         // TODO: Find a better way of handling missing/invalid options
62         if( Config_GetValueCount("coke_dummy_mode") > 0 )
63         {
64                 gbCoke_DummyMode = Config_GetValue_Bool("coke_dummy_mode", 0);
65                 if(gbCoke_DummyMode == -1)      gbCoke_DummyMode = 0;
66         }
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         if( time(NULL) - gtCoke_LastReconnectTime < COKE_RECONNECT_RATELIMIT )
124                 return -1;
125
126         if( !gCoke_Modbus )
127         {
128                 gCoke_Modbus = modbus_new_tcp(gsCoke_ModbusAddress, 502);
129                 if( !gCoke_Modbus )
130                 {
131                         perror("coke - modbus_new_tcp");
132                         gtCoke_LastReconnectTime = time(NULL);
133                         return 1;
134                 }
135         }
136         else {
137                 // Preven resource leaks
138                 modbus_close(gCoke_Modbus);
139         }
140         Debug_Notice("Connecting to coke PLC machine on '%s'\n", gsCoke_ModbusAddress);
141         
142         if( modbus_connect(gCoke_Modbus) )
143         {
144                 gtCoke_LastReconnectTime = time(NULL);
145                 perror("coke - modbus_connect");
146                 modbus_free(gCoke_Modbus);
147                 gCoke_Modbus = NULL;
148                 return 1;
149         }
150
151         return 0;
152 }
153
154 int Coke_int_GetSlotFromItem(int Item, int bDispensing)
155 {
156         if( Item < 0 || Item > 6 )      return -1;
157
158         // Non-coke slots
159         if( Item < 6 )
160                 return Item;
161         
162         // Iterate though coke slots and find the first one with a drink avaliable
163         // `giCoke_NextCokeSlot` ensures that the slots rotate
164         for( int i = 0; i < 4; i ++ )
165         {
166                 int slot = 6 + (i + giCoke_NextCokeSlot) % 4;
167                 if( !Coke_int_IsSlotEmpty(slot) )
168                 {
169                         if(bDispensing) {
170                                 giCoke_NextCokeSlot ++;
171                                 if(giCoke_NextCokeSlot == 4)    giCoke_NextCokeSlot = 0;
172                         }
173                         return slot;    // Drink avaliable
174                 }
175         }
176
177         // Coke is empty!
178         // - Return 6, even if it's empty, the checks elsewhere will avoid problems
179         return 6;
180 }
181
182 int Coke_int_IsSlotEmpty(int Slot)
183 {
184         uint8_t status;
185
186         if( Slot < 0 || Slot > 9 )      return -1;
187
188         errno = 0;
189         if( _ReadBit(ciCoke_StatusBitBase + Slot, &status) )
190         {
191                 perror("Coke_int_IsSlotEmpty - modbus_read_bits");
192                 return -2;
193         }
194
195         return status == 0;
196 }
197
198 int Coke_int_DropSlot(int Slot)
199 {
200         uint8_t res;
201
202         if(Slot < 0 || Slot > 9)        return -1;
203
204         // Check if a dispense is in progress
205         if( _ReadBit(ciCoke_DropBitBase + Slot, &res) )
206         {
207                 perror("Coke_int_DropSlot - modbus_read_bits#1");
208                 return -2;
209         }
210         if( res != 0 )
211         {
212                 // Manual dispense in progress
213                 return -1;
214         }
215
216         // Dispense
217         if( _WriteBit(ciCoke_DropBitBase + Slot, 1) )
218         {
219                 perror("Coke_int_DropSlot - modbus_write_bit");
220                 return -2;
221         }
222
223         // Check that it started
224         usleep(1000);   // 1ms
225         if( _ReadBit(ciCoke_DropBitBase + Slot, &res) )
226         {
227                 perror("Coke_int_DropSlot - modbus_read_bits#2");
228                 return -2;
229         }
230         if( res == 0 )
231         {
232                 // Oops!, no drink
233                 Log_Error("Drink dispense failed, bit lowered too quickly");
234                 Debug_Notice("Drink dispense failed, bit lowered too quickly");
235                 return 1;
236         }
237         
238         return 0;
239 }
240
241 int _ReadBit(int BitNum, uint8_t *Value)
242 {
243         errno = 0;
244         if( !gCoke_Modbus && Coke_int_ConnectToPLC() )
245                 return -1;
246         if( modbus_read_bits( gCoke_Modbus, BitNum, 1, Value) >= 0 )
247                 return 0;
248         if( Coke_int_ConnectToPLC() )
249                 return -1;
250         if( modbus_read_bits( gCoke_Modbus, BitNum, 1, Value) >= 0 )
251                 return 0;
252         return -1;
253 }
254
255 int _WriteBit(int BitNum, uint8_t Value)
256 {
257         errno = 0;
258         if( !gCoke_Modbus && Coke_int_ConnectToPLC() )
259                 return -1;
260         if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
261                 return 0;
262         // Error case
263         if( Coke_int_ConnectToPLC() )
264                 return -1;
265         if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
266                 return 0;
267         return -1;
268 }
269

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