* - Remember, the coke machine echoes your text back to you!
*/
#include "common.h"
+#include "../common/config.h"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <modbus/modbus.h>
#include <errno.h>
-#define MIN_DISPENSE_PERIOD 5
+#define MIN_DISPENSE_PERIOD 2
#define COKE_RECONNECT_RATELIMIT 2
// === CONSTANTS ===
Coke_CanDispense,
Coke_DoDispense
};
+// - Config
const char *gsCoke_ModbusAddress = "130.95.13.73";
+ int giCoke_ModbusPort = 502;
+bool gbCoke_DummyMode = false;
+// - State
modbus_t *gCoke_Modbus;
time_t gtCoke_LastDispenseTime;
time_t gtCoke_LastReconnectTime;
- int gbCoke_DummyMode = 1;
int giCoke_NextCokeSlot = 0;
// == CODE ===
{
// Configuable dummy/blank mode (all dispenses succeed)
// TODO: Find a better way of handling missing/invalid options
- if( Config_GetValueCount("coke_dummy_mode") > 0 )
- {
- gbCoke_DummyMode = Config_GetValue_Bool("coke_dummy_mode", 0);
- if(gbCoke_DummyMode == -1) gbCoke_DummyMode = 0;
- }
+ Config_GetValue_Bool("coke_dummy_mode", &gbCoke_DummyMode);
// Open modbus
if( !gbCoke_DummyMode )
if( time(NULL) - gtCoke_LastDispenseTime < ciCoke_MinPeriod )
{
int delay = ciCoke_MinPeriod - (time(NULL) - gtCoke_LastDispenseTime);
- printf("Wait %i seconds?\n", delay);
+ Debug_Debug("Waiting for %i seconds (rate limit)", delay);
sleep( delay );
- printf("wait done\n");
+ Debug_Debug("wait done");
}
gtCoke_LastDispenseTime = time(NULL);
int Coke_int_ConnectToPLC(void)
{
// Ratelimit
- if( time(NULL) - gtCoke_LastReconnectTime < COKE_RECONNECT_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, 502);
+ gCoke_Modbus = modbus_new_tcp(gsCoke_ModbusAddress, giCoke_ModbusPort);
if( !gCoke_Modbus )
{
perror("coke - modbus_new_tcp");
return 1;
}
}
- printf("Connecting to coke PLC machine on '%s'\n", gsCoke_ModbusAddress);
- fprintf(stderr, "Connecting to coke PLC machine on '%s'\n", gsCoke_ModbusAddress);
+ else {
+ // Preven resource leaks
+ modbus_close(gCoke_Modbus);
+ }
+ Debug_Notice("Connecting to coke PLC machine on '%s':%i", gsCoke_ModbusAddress, giCoke_ModbusPort);
if( modbus_connect(gCoke_Modbus) )
{
if( res == 0 )
{
// Oops!, no drink
- printf("Drink dispense failed, bit lowered too quickly\n");
+ Log_Error("Drink dispense failed, bit lowered too quickly");
+ Debug_Notice("Drink dispense failed, bit lowered too quickly");
return 1;
}
return -1;
if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )
return 0;
+ // Error case
if( Coke_int_ConnectToPLC() )
return -1;
if( modbus_write_bit( gCoke_Modbus, BitNum, Value != 0 ) >= 0 )