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

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