Initial move to common config code directory
[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 const char      *gsCoke_ModbusAddress = "130.95.13.73";
52 modbus_t        *gCoke_Modbus;
53 time_t  gtCoke_LastDispenseTime;
54 time_t  gtCoke_LastReconnectTime;
55  int    gbCoke_DummyMode = 1;
56  int    giCoke_NextCokeSlot = 0;
57
58 // == CODE ===
59 int Coke_InitHandler()
60 {
61         // Configuable dummy/blank mode (all dispenses succeed)
62         // TODO: Find a better way of handling missing/invalid options
63         if( Config_GetValueCount("coke_dummy_mode") > 0 )
64         {
65                 gbCoke_DummyMode = Config_GetValue_Bool("coke_dummy_mode", 0);
66                 if(gbCoke_DummyMode == -1)      gbCoke_DummyMode = 0;
67         }
68
69         // Open modbus
70         if( !gbCoke_DummyMode )
71         {
72                 Coke_int_ConnectToPLC();
73         }
74
75         return 0;
76 }
77
78 int Coke_CanDispense(int UNUSED(User), int Item)
79 {
80          int    slot;
81         
82         // Check for 'dummy' mode
83         if( gbCoke_DummyMode )
84                 return 0;
85
86         // Get slot
87         slot = Coke_int_GetSlotFromItem(Item, 0);
88         if(slot < 0)    return -1;
89
90         return Coke_int_IsSlotEmpty(slot);
91 }
92
93 /**
94  * \brief Actually do a dispense from the coke machine
95  */
96 int Coke_DoDispense(int UNUSED(User), int Item)
97 {
98          int    slot;
99         // Check for 'dummy' mode
100         if( gbCoke_DummyMode )
101                 return 0;
102
103         // Get slot
104         slot = Coke_int_GetSlotFromItem(Item, 1);
105         if(slot < 0)    return -1;
106         
107         // Make sure there are not two dispenses within n seconds
108         if( time(NULL) - gtCoke_LastDispenseTime < ciCoke_MinPeriod )
109         {
110                  int    delay = ciCoke_MinPeriod - (time(NULL) - gtCoke_LastDispenseTime);
111                 Debug_Debug("Waiting for %i seconds (rate limit)", delay);
112                 sleep( delay );
113                 Debug_Debug("wait done");
114         }
115         gtCoke_LastDispenseTime = time(NULL);
116
117         return Coke_int_DropSlot(slot);
118 }
119
120 // --- INTERNAL FUNCTIONS ---
121 int Coke_int_ConnectToPLC(void)
122 {
123         // Ratelimit
124         if( time(NULL) - gtCoke_LastReconnectTime < COKE_RECONNECT_RATELIMIT )
125                 return -1;
126
127         if( !gCoke_Modbus )
128         {
129                 gCoke_Modbus = modbus_new_tcp(gsCoke_ModbusAddress, 502);
130                 if( !gCoke_Modbus )
131                 {
132                         perror("coke - modbus_new_tcp");
133                         gtCoke_LastReconnectTime = time(NULL);
134                         return 1;
135                 }
136         }
137         else {
138                 // Preven resource leaks
139                 modbus_close(gCoke_Modbus);
140         }
141         Debug_Notice("Connecting to coke PLC machine on '%s'\n", gsCoke_ModbusAddress);
142         
143         if( modbus_connect(gCoke_Modbus) )
144         {
145                 gtCoke_LastReconnectTime = time(NULL);
146                 perror("coke - modbus_connect");
147                 modbus_free(gCoke_Modbus);
148                 gCoke_Modbus = NULL;
149                 return 1;
150         }
151
152         return 0;
153 }
154
155 int Coke_int_GetSlotFromItem(int Item, int bDispensing)
156 {
157         if( Item < 0 || Item > 6 )      return -1;
158
159         // Non-coke slots
160         if( Item < 6 )
161                 return Item;
162         
163         // Iterate though coke slots and find the first one with a drink avaliable
164         // `giCoke_NextCokeSlot` ensures that the slots rotate
165         for( int i = 0; i < 4; i ++ )
166         {
167                 int slot = 6 + (i + giCoke_NextCokeSlot) % 4;
168                 if( !Coke_int_IsSlotEmpty(slot) )
169                 {
170                         if(bDispensing) {
171                                 giCoke_NextCokeSlot ++;
172                                 if(giCoke_NextCokeSlot == 4)    giCoke_NextCokeSlot = 0;
173                         }
174                         return slot;    // Drink avaliable
175                 }
176         }
177
178         // Coke is empty!
179         // - Return 6, even if it's empty, the checks elsewhere will avoid problems
180         return 6;
181 }
182
183 int Coke_int_IsSlotEmpty(int Slot)
184 {
185         uint8_t status;
186
187         if( Slot < 0 || Slot > 9 )      return -1;
188
189         errno = 0;
190         if( _ReadBit(ciCoke_StatusBitBase + Slot, &status) )
191         {
192                 perror("Coke_int_IsSlotEmpty - modbus_read_bits");
193                 return -2;
194         }
195
196         return status == 0;
197 }
198
199 int Coke_int_DropSlot(int Slot)
200 {
201         uint8_t res;
202
203         if(Slot < 0 || Slot > 9)        return -1;
204
205         // Check if a dispense is in progress
206         if( _ReadBit(ciCoke_DropBitBase + Slot, &res) )
207         {
208                 perror("Coke_int_DropSlot - modbus_read_bits#1");
209                 return -2;
210         }
211         if( res != 0 )
212         {
213                 // Manual dispense in progress
214                 return -1;
215         }
216
217         // Dispense
218         if( _WriteBit(ciCoke_DropBitBase + Slot, 1) )
219         {
220                 perror("Coke_int_DropSlot - modbus_write_bit");
221                 return -2;
222         }
223
224         // Check that it started
225         usleep(1000);   // 1ms
226         if( _ReadBit(ciCoke_DropBitBase + Slot, &res) )
227         {
228                 perror("Coke_int_DropSlot - modbus_read_bits#2");
229                 return -2;
230         }
231         if( res == 0 )
232         {
233                 // Oops!, no drink
234                 Log_Error("Drink dispense failed, bit lowered too quickly");
235                 Debug_Notice("Drink dispense failed, bit lowered too quickly");
236                 return 1;
237         }
238         
239         return 0;
240 }
241
242 int _ReadBit(int BitNum, uint8_t *Value)
243 {
244         errno = 0;
245         if( !gCoke_Modbus && Coke_int_ConnectToPLC() )
246                 return -1;
247         if( modbus_read_bits( gCoke_Modbus, BitNum, 1, Value) >= 0 )
248                 return 0;
249         if( Coke_int_ConnectToPLC() )
250                 return -1;
251         if( modbus_read_bits( gCoke_Modbus, BitNum, 1, Value) >= 0 )
252                 return 0;
253         return -1;
254 }
255
256 int _WriteBit(int BitNum, uint8_t Value)
257 {
258         errno = 0;
259         if( !gCoke_Modbus && Coke_int_ConnectToPLC() )
260                 return -1;
261         if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
262                 return 0;
263         // Error case
264         if( Coke_int_ConnectToPLC() )
265                 return -1;
266         if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
267                 return 0;
268         return -1;
269 }
270

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