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

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