#include <stdlib.h>
#include <string.h>
#include <syslog.h>
+#include <time.h>
#include <unistd.h>
#include <modbus.h>
va_end(args);
}
-static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
+static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level UNUSED, const char *message UNUSED)
{
// msg(L_INFO, "MQTT(%d): %s", level, message);
}
static modbus_t *modbus;
static bool mb_is_open;
-static void mb_error(const char *operation)
+static void mb_error(const char *operation, bool need_close)
{
msg(L_ERROR, "MODBUS: %s failed: %s", operation, modbus_strerror(errno));
- if (modbus) {
+ if (need_close && modbus) {
if (mb_is_open) {
modbus_close(modbus);
mb_is_open = false;
if (modbus)
return true;
- // FIXME: Find the right device. Reconnect if needed.
- modbus = modbus_new_rtu("/dev/ttyUSB1", 19200, 'E', 8, 1);
+ modbus = modbus_new_tcp("127.0.0.1", 4301);
+ // modbus = modbus_new_rtu("/dev/modbus-aircon", 19200, 'E', 8, 1);
if (!modbus) {
- mb_error("open");
+ mb_error("open", true);
return false;
}
+ // modbus_set_debug(modbus, 1);
modbus_set_slave(modbus, 42);
+ modbus_set_response_timeout(modbus, 5, 0);
if (modbus_connect(modbus) < 0) {
- mb_error("connect");
+ mb_error("connect", true);
return false;
}
mb_is_open = true;
+ return true;
}
/*** Main loop ***/
u16 regs[5];
if (modbus_read_input_registers(modbus, AIRCON_IREG_TEMP_FROM_INSIDE, 5, regs) < 0) {
- mb_error("read");
+ mb_error("read", true);
return;
}
return;
}
if (modbus_write_bit(modbus, AIRCON_COIL_EXCHANGER_BYPASS, x) < 0)
- msg(L_ERROR, "Modbus write failed: %s", modbus_strerror(errno));
+ mb_error("coil write", false);
} else if (!strcmp(m->topic, "burrow/air/exchanger-fan")) {
uint x;
const char *err;
return;
}
if (modbus_write_register(modbus, AIRCON_HREG_EXCHANGER_FAN, x) < 0)
- msg(L_ERROR, "Modbus write failed: %s", modbus_strerror(errno));
+ mb_error("fan register write", false);
+ } else if (!strcmp(m->topic, "burrow/air/aircon-remote")) {
+ if (strlen(val) != 1) {
+ msg(L_ERROR, "Received invalid aircon remote command %s", val);
+ return;
+ }
+ if (modbus_write_register(modbus, AIRCON_HREG_REMOTE_CONTROL, val[0]) < 0)
+ mb_error("remote control register write", false);
}
}