]> mj.ucw.cz Git - home-hw.git/blob - aircon/daemon/burrow-aircond.c
c297a9f0d7a04ae61d27ca45003fd7f73c8d5fe5
[home-hw.git] / aircon / daemon / burrow-aircond.c
1 /*
2  *      A MQTT Gateway Daemon for the Air Conditioning Controller
3  *
4  *      (c) 2019 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <ucw/lib.h>
8 #include <ucw/log.h>
9 #include <ucw/opt.h>
10 #include <ucw/strtonum.h>
11 #include <ucw/stkstring.h>
12
13 #include <errno.h>
14 #include <stdio.h>
15 #include <stdarg.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <syslog.h>
19 #include <unistd.h>
20
21 #include <modbus.h>
22 #include <mosquitto.h>
23
24 #include "../firmware/registers.h"
25
26 /*** MQTT ***/
27
28 static struct mosquitto *mosq;
29 static bool mqtt_connected;
30
31 static void mqtt_error(const char *operation, int err, bool teardown)
32 {
33         msg(L_ERROR, "Mosquitto: %s failed: error %d", operation, err);
34
35         if (teardown) {
36                 mosquitto_destroy(mosq);
37                 mosq = NULL;
38                 mqtt_connected = false;
39         } else if (err == MOSQ_ERR_NO_CONN || err == MOSQ_ERR_CONN_REFUSED || err == MOSQ_ERR_CONN_LOST) {
40                 mqtt_connected = false;
41         }
42 }
43
44 static void mqtt_publish(const char *topic, const char *fmt, ...)
45 {
46         va_list args;
47         va_start(args, fmt);
48
49         if (mqtt_connected) {
50                 char m[256];
51                 int l = vsnprintf(m, sizeof(m), fmt, args);
52                 int err = mosquitto_publish(mosq, NULL, topic, l, m, 0, true);
53                 if (err != MOSQ_ERR_SUCCESS)
54                         mqtt_error("publish", err, false);
55         }
56
57         va_end(args);
58 }
59
60 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
61 {
62         // msg(L_INFO, "MQTT(%d): %s", level, message);
63 }
64
65 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m);
66
67 static bool mqtt_connect(void)
68 {
69         int err;
70
71         if (mqtt_connected)
72                 return true;
73
74         if (!mosq) {
75                 mosq = mosquitto_new("aircond", 1, NULL);
76                 if (!mosq)
77                         die("Mosquitto: initialization failed");
78
79                 mosquitto_log_callback_set(mosq, mqtt_log_callback);
80                 mosquitto_message_callback_set(mosq, mqtt_msg_callback);
81
82                 err = mosquitto_will_set(mosq, "status/aircon", 4, "dead", 0, true);
83                 if (err != MOSQ_ERR_SUCCESS) {
84                         mqtt_error("will_set", err, true);
85                         return false;
86                 }
87
88                 err = mosquitto_connect(mosq, "127.0.0.1", 1883, 60);
89                 if (err != MOSQ_ERR_SUCCESS) {
90                         mqtt_error("connect", err, true);
91                         return false;
92                 }
93         } else {
94                 err = mosquitto_reconnect(mosq);
95                 if (err != MOSQ_ERR_SUCCESS) {
96                         mqtt_error("reconnect", err, false);
97                         return false;
98                 }
99         }
100
101         err = mosquitto_subscribe(mosq, NULL, "burrow/air/#", 1);
102         if (err != MOSQ_ERR_SUCCESS) {
103                 mqtt_error("subscribe", err, false);
104                 return false;
105         }
106
107         mqtt_connected = true;
108
109         mqtt_publish("status/aircon", "ok");
110
111         return mqtt_connected;
112 }
113
114 /*** MODBUS ***/
115
116 static modbus_t *modbus;
117 static bool mb_is_open;
118
119 static void mb_error(const char *operation)
120 {
121         msg(L_ERROR, "MODBUS: %s failed: %s", operation, modbus_strerror(errno));
122
123         if (modbus) {
124                 if (mb_is_open) {
125                         modbus_close(modbus);
126                         mb_is_open = false;
127                 }
128                 modbus_free(modbus);
129                 modbus = NULL;
130         }
131 }
132
133 static bool mb_connect(void)
134 {
135         if (modbus)
136                 return true;
137
138         // FIXME: Find the right device. Reconnect if needed.
139         modbus = modbus_new_rtu("/dev/ttyUSB1", 19200, 'E', 8, 1);
140         if (!modbus) {
141                 mb_error("open");
142                 return false;
143         }
144
145         modbus_set_slave(modbus, 42);
146
147         if (modbus_connect(modbus) < 0) {
148                 mb_error("connect");
149                 return false;
150         }
151
152         mb_is_open = true;
153 }
154
155 /*** Main loop ***/
156
157 static void scan_temperatures(time_t now)
158 {
159         static const char * const temp_names[] = {
160                 "inside-intake",
161                 "inside-exhaust",
162                 "outside-intake",
163                 "outside-exhaust",
164                 "mixed",
165         };
166
167         u16 regs[5];
168         if (modbus_read_input_registers(modbus, AIRCON_IREG_TEMP_FROM_INSIDE, 5, regs) < 0) {
169                 mb_error("read");
170                 return;
171         }
172
173         for (uint i=0; i<5; i++) {
174                 if (regs[i] != 0x8000) {
175                         int t = regs[i];
176                         if (t >= 0x8000)
177                                 t -= 0x10000;
178                         mqtt_publish(stk_printf("burrow/air/%s", temp_names[i]), "%.3f %llu", t / 100., (unsigned long long) now);
179                 }
180         }
181 }
182
183 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
184 {
185         char val[256];
186         if (m->payloadlen >= sizeof(val) - 1) {
187                 msg(L_ERROR, "Invalid value for topic %s", m->topic);
188                 return;
189         }
190         memcpy(val, m->payload, m->payloadlen);
191         val[m->payloadlen] = 0;
192         msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
193
194         if (!strcmp(m->topic, "burrow/air/bypass")) {
195                 uint x;
196                 const char *err;
197                 if ((err = str_to_uint(&x, val, NULL, 10 | STN_WHOLE)) || x >= 2) {
198                         msg(L_ERROR, "Received invalid bypass setting %s: %s", val, err);
199                         return;
200                 }
201                 if (modbus_write_bit(modbus, AIRCON_COIL_EXCHANGER_BYPASS, x) < 0)
202                         msg(L_ERROR, "Modbus write failed: %s", modbus_strerror(errno));
203         } else if (!strcmp(m->topic, "burrow/air/exchanger-fan")) {
204                 uint x;
205                 const char *err;
206                 if ((err = str_to_uint(&x, val, NULL, 10 | STN_WHOLE)) || x >= 256) {
207                         msg(L_ERROR, "Received invalid exchanger fan setting %s: %s", val, err);
208                         return;
209                 }
210                 if (modbus_write_register(modbus, AIRCON_HREG_EXCHANGER_FAN, x) < 0)
211                         msg(L_ERROR, "Modbus write failed: %s", modbus_strerror(errno));
212         }
213 }
214
215 static int use_daemon;
216 static int use_debug;
217
218 static struct opt_section options = {
219         OPT_ITEMS {
220                 OPT_HELP("A daemon for controlling the air conditioning controller via MQTT"),
221                 OPT_HELP(""),
222                 OPT_HELP("Options:"),
223                 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
224                 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
225                 OPT_HELP_OPTION,
226                 OPT_CONF_OPTIONS,
227                 OPT_END
228         }
229 };
230
231 int main(int argc UNUSED, char **argv)
232 {
233         log_init(argv[0]);
234         opt_parse(&options, argv+1);
235
236         if (use_daemon) {
237                 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
238                 log_set_default_stream(ls);
239         }
240         if (!use_debug)
241                 log_default_stream()->levels &= ~(1U << L_DEBUG);
242
243         mosquitto_lib_init();
244
245         time_t next_run = 0;
246         for (;;) {
247                 if (!mqtt_connect() || !mb_connect()) {
248                         sleep(5);
249                         continue;
250                 }
251
252                 time_t now = time(NULL);
253                 if (now < next_run) {
254                         int err = mosquitto_loop(mosq, (next_run - now) * 1000, 1);
255                         if (err != MOSQ_ERR_SUCCESS)
256                                 mqtt_error("loop", err, false);
257                         continue;
258                 }
259
260                 next_run = now + 10;
261                 scan_temperatures(now);
262         }
263 }