- // Sanity please
- if( Item < 0 || Item > 6 ) return -1; // -EYOURBAD
-
- // Can't dispense if the machine is not connected
- if( giCoke_SerialFD == -1 )
- return -2;
+ // Ratelimit
+ time_t elapsed = time(NULL) - gtCoke_LastReconnectTime;
+ if( elapsed < COKE_RECONNECT_RATELIMIT ) {
+ Debug_Notice("Not reconnecting, only %llis have pased, %i limit", (long long)elapsed, COKE_RECONNECT_RATELIMIT);
+ errno = EAGAIN;
+ return -1;
+ }
+
+ if( !gCoke_Modbus )
+ {
+ gCoke_Modbus = modbus_new_tcp(gsCoke_ModbusAddress, giCoke_ModbusPort);
+ if( !gCoke_Modbus )
+ {
+ perror("coke - modbus_new_tcp");
+ gtCoke_LastReconnectTime = time(NULL);
+ return 1;
+ }
+ }
+ else {
+ // Preven resource leaks
+ modbus_close(gCoke_Modbus);
+ }
+ Debug_Notice("Connecting to coke PLC machine on '%s':%i", gsCoke_ModbusAddress, giCoke_ModbusPort);