Merge pull request #2670 from antvick/feature/modbus_64bit
[collectd.git] / src / modbus.c
1 /**
2  * collectd - src/modbus.c
3  * Copyright (C) 2010,2011  noris network AG
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU Lesser General Public License as published by
7  * the Free Software Foundation; only version 2.1 of the License is
8  * applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  *
19  * Authors:
20  *   Florian Forster <octo at noris.net>
21  **/
22
23 #include "collectd.h"
24
25 #include "common.h"
26 #include "configfile.h"
27 #include "plugin.h"
28
29 #include <modbus.h>
30 #include <netdb.h>
31 #include <sys/socket.h>
32
33 #ifndef LIBMODBUS_VERSION_CHECK
34 /* Assume version 2.0.3 */
35 #define LEGACY_LIBMODBUS 1
36 #else
37 /* Assume version 2.9.2 */
38 #endif
39
40 #ifndef MODBUS_TCP_DEFAULT_PORT
41 #ifdef MODBUS_TCP_PORT
42 #define MODBUS_TCP_DEFAULT_PORT MODBUS_TCP_PORT
43 #else
44 #define MODBUS_TCP_DEFAULT_PORT 502
45 #endif
46 #endif
47
48 /*
49  * <Data "data_name">
50  *   RegisterBase 1234
51  *   RegisterCmd ReadHolding
52  *   RegisterType float
53  *   Type gauge
54  *   Instance "..."
55  * </Data>
56  *
57  * <Host "name">
58  *   Address "addr"
59  *   Port "1234"
60  *   # Or:
61  *   # Device "/dev/ttyUSB0"
62  *   # Baudrate 38400
63  *   # (Assumes 8N1)
64  *   Interval 60
65  *
66  *   <Slave 1>
67  *     Instance "foobar" # optional
68  *     Collect "data_name"
69  *   </Slave>
70  * </Host>
71  */
72
73 /*
74  * Data structures
75  */
76 enum mb_register_type_e /* {{{ */
77 { REG_TYPE_INT16,
78   REG_TYPE_INT32,
79   REG_TYPE_INT32_CDAB,
80   REG_TYPE_UINT16,
81   REG_TYPE_UINT32,
82   REG_TYPE_UINT32_CDAB,
83   REG_TYPE_UINT64,
84   REG_TYPE_INT64,
85   REG_TYPE_FLOAT,
86   REG_TYPE_FLOAT_CDAB }; /* }}} */
87
88 enum mb_mreg_type_e /* {{{ */
89 { MREG_HOLDING,
90   MREG_INPUT }; /* }}} */
91 typedef enum mb_register_type_e mb_register_type_t;
92 typedef enum mb_mreg_type_e mb_mreg_type_t;
93
94 /* TCP or RTU depending on what is specified in host config block */
95 enum mb_conntype_e /* {{{ */
96 { MBCONN_TCP,
97   MBCONN_RTU }; /* }}} */
98 typedef enum mb_conntype_e mb_conntype_t;
99
100 struct mb_data_s;
101 typedef struct mb_data_s mb_data_t;
102 struct mb_data_s /* {{{ */
103 {
104   char *name;
105   int register_base;
106   mb_register_type_t register_type;
107   mb_mreg_type_t modbus_register_type;
108   char type[DATA_MAX_NAME_LEN];
109   char instance[DATA_MAX_NAME_LEN];
110
111   mb_data_t *next;
112 }; /* }}} */
113
114 struct mb_slave_s /* {{{ */
115 {
116   int id;
117   char instance[DATA_MAX_NAME_LEN];
118   mb_data_t *collect;
119 }; /* }}} */
120 typedef struct mb_slave_s mb_slave_t;
121
122 struct mb_host_s /* {{{ */
123 {
124   char host[DATA_MAX_NAME_LEN];
125   char node[NI_MAXHOST]; /* TCP hostname or RTU serial device */
126   /* char service[NI_MAXSERV]; */
127   int port;     /* for Modbus/TCP */
128   int baudrate; /* for Modbus/RTU */
129   mb_conntype_t conntype;
130   cdtime_t interval;
131
132   mb_slave_t *slaves;
133   size_t slaves_num;
134
135 #if LEGACY_LIBMODBUS
136   modbus_param_t connection;
137 #else
138   modbus_t *connection;
139 #endif
140   bool is_connected;
141 }; /* }}} */
142 typedef struct mb_host_s mb_host_t;
143
144 struct mb_data_group_s;
145 typedef struct mb_data_group_s mb_data_group_t;
146 struct mb_data_group_s /* {{{ */
147 {
148   mb_data_t *registers;
149   size_t registers_num;
150
151   mb_data_group_t *next;
152 }; /* }}} */
153
154 /*
155  * Global variables
156  */
157 static mb_data_t *data_definitions;
158
159 /*
160  * Functions
161  */
162 static mb_data_t *data_get_by_name(mb_data_t *src, /* {{{ */
163                                    const char *name) {
164   if (name == NULL)
165     return NULL;
166
167   for (mb_data_t *ptr = src; ptr != NULL; ptr = ptr->next)
168     if (strcasecmp(ptr->name, name) == 0)
169       return ptr;
170
171   return NULL;
172 } /* }}} mb_data_t *data_get_by_name */
173
174 static int data_append(mb_data_t **dst, mb_data_t *src) /* {{{ */
175 {
176   mb_data_t *ptr;
177
178   if ((dst == NULL) || (src == NULL))
179     return EINVAL;
180
181   ptr = *dst;
182
183   if (ptr == NULL) {
184     *dst = src;
185     return 0;
186   }
187
188   while (ptr->next != NULL)
189     ptr = ptr->next;
190
191   ptr->next = src;
192
193   return 0;
194 } /* }}} int data_append */
195
196 /* Copy a single mb_data_t and append it to another list. */
197 static int data_copy(mb_data_t **dst, const mb_data_t *src) /* {{{ */
198 {
199   mb_data_t *tmp;
200   int status;
201
202   if ((dst == NULL) || (src == NULL))
203     return EINVAL;
204
205   tmp = malloc(sizeof(*tmp));
206   if (tmp == NULL)
207     return ENOMEM;
208   memcpy(tmp, src, sizeof(*tmp));
209   tmp->name = NULL;
210   tmp->next = NULL;
211
212   tmp->name = strdup(src->name);
213   if (tmp->name == NULL) {
214     sfree(tmp);
215     return ENOMEM;
216   }
217
218   status = data_append(dst, tmp);
219   if (status != 0) {
220     sfree(tmp->name);
221     sfree(tmp);
222     return status;
223   }
224
225   return 0;
226 } /* }}} int data_copy */
227
228 /* Lookup a single mb_data_t instance, copy it and append the copy to another
229  * list. */
230 static int data_copy_by_name(mb_data_t **dst, mb_data_t *src, /* {{{ */
231                              const char *name) {
232   mb_data_t *ptr;
233
234   if ((dst == NULL) || (src == NULL) || (name == NULL))
235     return EINVAL;
236
237   ptr = data_get_by_name(src, name);
238   if (ptr == NULL)
239     return ENOENT;
240
241   return data_copy(dst, ptr);
242 } /* }}} int data_copy_by_name */
243
244 /* Read functions */
245
246 static int mb_submit(mb_host_t *host, mb_slave_t *slave, /* {{{ */
247                      mb_data_t *data, value_t value) {
248   value_list_t vl = VALUE_LIST_INIT;
249
250   if ((host == NULL) || (slave == NULL) || (data == NULL))
251     return EINVAL;
252
253   if (host->interval == 0)
254     host->interval = plugin_get_interval();
255
256   if (slave->instance[0] == 0)
257     snprintf(slave->instance, sizeof(slave->instance), "slave_%i", slave->id);
258
259   vl.values = &value;
260   vl.values_len = 1;
261   vl.interval = host->interval;
262   sstrncpy(vl.host, host->host, sizeof(vl.host));
263   sstrncpy(vl.plugin, "modbus", sizeof(vl.plugin));
264   sstrncpy(vl.plugin_instance, slave->instance, sizeof(vl.plugin_instance));
265   sstrncpy(vl.type, data->type, sizeof(vl.type));
266   sstrncpy(vl.type_instance, data->instance, sizeof(vl.type_instance));
267
268   return plugin_dispatch_values(&vl);
269 } /* }}} int mb_submit */
270
271 static float mb_register_to_float(uint16_t hi, uint16_t lo) /* {{{ */
272 {
273   union {
274     uint8_t b[4];
275     uint16_t s[2];
276     float f;
277   } conv;
278
279 #if BYTE_ORDER == LITTLE_ENDIAN
280   /* little endian */
281   conv.b[0] = lo & 0x00ff;
282   conv.b[1] = (lo >> 8) & 0x00ff;
283   conv.b[2] = hi & 0x00ff;
284   conv.b[3] = (hi >> 8) & 0x00ff;
285 #else
286   conv.b[3] = lo & 0x00ff;
287   conv.b[2] = (lo >> 8) & 0x00ff;
288   conv.b[1] = hi & 0x00ff;
289   conv.b[0] = (hi >> 8) & 0x00ff;
290 #endif
291
292   return conv.f;
293 } /* }}} float mb_register_to_float */
294
295 #if LEGACY_LIBMODBUS
296 /* Version 2.0.3 */
297 static int mb_init_connection(mb_host_t *host) /* {{{ */
298 {
299   int status;
300
301   if (host == NULL)
302     return EINVAL;
303
304 #if COLLECT_DEBUG
305   modbus_set_debug(&host->connection, 1);
306 #endif
307
308   /* We'll do the error handling ourselves. */
309   modbus_set_error_handling(&host->connection, NOP_ON_ERROR);
310
311   if (host->conntype == MBCONN_TCP) {
312     if ((host->port < 1) || (host->port > 65535))
313       host->port = MODBUS_TCP_DEFAULT_PORT;
314
315     DEBUG("Modbus plugin: Trying to connect to \"%s\", port %i.", host->node,
316           host->port);
317
318     modbus_init_tcp(&host->connection,
319                     /* host = */ host->node,
320                     /* port = */ host->port);
321   } else /* MBCONN_RTU */
322   {
323     DEBUG("Modbus plugin: Trying to connect to \"%s\".", host->node);
324
325     modbus_init_rtu(&host->connection,
326                     /* device = */ host->node,
327                     /* baudrate = */ host->baudrate, 'N', 8, 1, 0);
328   }
329
330   status = modbus_connect(&host->connection);
331   if (status != 0) {
332     ERROR("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
333           host->node, host->port ? host->port : host->baudrate, status);
334     return status;
335   }
336
337   host->is_connected = true;
338   return 0;
339 } /* }}} int mb_init_connection */
340 /* #endif LEGACY_LIBMODBUS */
341
342 #else /* if !LEGACY_LIBMODBUS */
343 /* Version 2.9.2 */
344 static int mb_init_connection(mb_host_t *host) /* {{{ */
345 {
346   int status;
347
348   if (host == NULL)
349     return EINVAL;
350
351   if (host->connection != NULL)
352     return 0;
353
354   if (host->conntype == MBCONN_TCP) {
355     if ((host->port < 1) || (host->port > 65535))
356       host->port = MODBUS_TCP_DEFAULT_PORT;
357
358     DEBUG("Modbus plugin: Trying to connect to \"%s\", port %i.", host->node,
359           host->port);
360
361     host->connection = modbus_new_tcp(host->node, host->port);
362     if (host->connection == NULL) {
363       ERROR("Modbus plugin: Creating new Modbus/TCP object failed.");
364       return -1;
365     }
366   } else {
367     DEBUG("Modbus plugin: Trying to connect to \"%s\", baudrate %i.",
368           host->node, host->baudrate);
369
370     host->connection = modbus_new_rtu(host->node, host->baudrate, 'N', 8, 1);
371     if (host->connection == NULL) {
372       ERROR("Modbus plugin: Creating new Modbus/RTU object failed.");
373       return -1;
374     }
375   }
376
377 #if COLLECT_DEBUG
378   modbus_set_debug(host->connection, 1);
379 #endif
380
381   /* We'll do the error handling ourselves. */
382   modbus_set_error_recovery(host->connection, 0);
383
384   status = modbus_connect(host->connection);
385   if (status != 0) {
386     ERROR("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
387           host->node, host->port ? host->port : host->baudrate, status);
388     modbus_free(host->connection);
389     host->connection = NULL;
390     return status;
391   }
392
393   return 0;
394 } /* }}} int mb_init_connection */
395 #endif /* !LEGACY_LIBMODBUS */
396
397 #define CAST_TO_VALUE_T(ds, vt, raw)                                           \
398   do {                                                                         \
399     if ((ds)->ds[0].type == DS_TYPE_COUNTER)                                   \
400       (vt).counter = (counter_t)(raw);                                         \
401     else if ((ds)->ds[0].type == DS_TYPE_GAUGE)                                \
402       (vt).gauge = (gauge_t)(raw);                                             \
403     else if ((ds)->ds[0].type == DS_TYPE_DERIVE)                               \
404       (vt).derive = (derive_t)(raw);                                           \
405     else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */                         \
406       (vt).absolute = (absolute_t)(raw);                                       \
407   } while (0)
408
409 static int mb_read_data(mb_host_t *host, mb_slave_t *slave, /* {{{ */
410                         mb_data_t *data) {
411   uint16_t values[4] = {0};
412   int values_num;
413   const data_set_t *ds;
414   int status = 0;
415
416   if ((host == NULL) || (slave == NULL) || (data == NULL))
417     return EINVAL;
418
419   ds = plugin_get_ds(data->type);
420   if (ds == NULL) {
421     ERROR("Modbus plugin: Type \"%s\" is not defined.", data->type);
422     return -1;
423   }
424
425   if (ds->ds_num != 1) {
426     ERROR("Modbus plugin: The type \"%s\" has %" PRIsz " data sources. "
427           "I can only handle data sets with only one data source.",
428           data->type, ds->ds_num);
429     return -1;
430   }
431
432   if ((ds->ds[0].type != DS_TYPE_GAUGE) &&
433       (data->register_type != REG_TYPE_INT32) &&
434       (data->register_type != REG_TYPE_INT32_CDAB) &&
435       (data->register_type != REG_TYPE_UINT32) &&
436       (data->register_type != REG_TYPE_INT64) &&
437       (data->register_type != REG_TYPE_UINT64) &&
438       (data->register_type != REG_TYPE_UINT32_CDAB)) {
439     NOTICE(
440         "Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
441         "This will most likely result in problems, because the register type "
442         "is not UINT32 OR UINT64.",
443         data->type, DS_TYPE_TO_STRING(ds->ds[0].type));
444   }
445
446   if ((data->register_type == REG_TYPE_INT32) ||
447       (data->register_type == REG_TYPE_INT32_CDAB) ||
448       (data->register_type == REG_TYPE_UINT32) ||
449       (data->register_type == REG_TYPE_UINT32_CDAB) ||
450       (data->register_type == REG_TYPE_FLOAT) ||
451       (data->register_type == REG_TYPE_FLOAT_CDAB))
452     values_num = 2;
453   else if ((data->register_type == REG_TYPE_UINT64) ||
454            (data->register_type == REG_TYPE_INT64))
455     values_num = 4;
456   else
457     values_num = 1;
458
459   if (host->connection == NULL) {
460     status = EBADF;
461   } else if (host->conntype == MBCONN_TCP) {
462     /* getpeername() is used only to determine if the socket is connected, not
463      * because we're really interested in the peer's IP address. */
464     if (getpeername(modbus_get_socket(host->connection),
465                     (void *)&(struct sockaddr_storage){0},
466                     &(socklen_t){sizeof(struct sockaddr_storage)}) != 0)
467       status = errno;
468   }
469
470   if ((status == EBADF) || (status == ENOTSOCK) || (status == ENOTCONN)) {
471     status = mb_init_connection(host);
472     if (status != 0) {
473       ERROR("Modbus plugin: mb_init_connection (%s/%s) failed. ", host->host,
474             host->node);
475       host->is_connected = false;
476       host->connection = NULL;
477       return -1;
478     }
479   } else if (status != 0) {
480 #if LEGACY_LIBMODBUS
481     modbus_close(&host->connection);
482 #else
483     modbus_close(host->connection);
484     modbus_free(host->connection);
485 #endif
486   }
487
488 #if LEGACY_LIBMODBUS
489 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
490  * id to each call of "read_holding_registers". */
491 #define modbus_read_registers(ctx, addr, nb, dest)                             \
492   read_holding_registers(&(ctx), slave->id, (addr), (nb), (dest))
493 #else /* if !LEGACY_LIBMODBUS */
494   /* Version 2.9.2: Set the slave id once before querying the registers. */
495   status = modbus_set_slave(host->connection, slave->id);
496   if (status != 0) {
497     ERROR("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
498           slave->id, status);
499     return -1;
500   }
501 #endif
502   if (data->modbus_register_type == MREG_INPUT) {
503     status = modbus_read_input_registers(host->connection,
504                                          /* start_addr = */ data->register_base,
505                                          /* num_registers = */ values_num,
506                                          /* buffer = */ values);
507   } else {
508     status = modbus_read_registers(host->connection,
509                                    /* start_addr = */ data->register_base,
510                                    /* num_registers = */ values_num,
511                                    /* buffer = */ values);
512   }
513   if (status != values_num) {
514     ERROR("Modbus plugin: modbus read function (%s/%s) failed. "
515           " status = %i, start_addr = %i, values_num = %i. Giving up.",
516           host->host, host->node, status, data->register_base, values_num);
517 #if LEGACY_LIBMODBUS
518     modbus_close(&host->connection);
519 #else
520     modbus_close(host->connection);
521     modbus_free(host->connection);
522 #endif
523     host->connection = NULL;
524     return -1;
525   }
526
527   DEBUG("Modbus plugin: mb_read_data: Success! "
528         "modbus_read_registers returned with status %i.",
529         status);
530
531   if (data->register_type == REG_TYPE_FLOAT) {
532     float float_value;
533     value_t vt;
534
535     float_value = mb_register_to_float(values[0], values[1]);
536     DEBUG("Modbus plugin: mb_read_data: "
537           "Returned float value is %g",
538           (double)float_value);
539
540     CAST_TO_VALUE_T(ds, vt, float_value);
541     mb_submit(host, slave, data, vt);
542   } else if (data->register_type == REG_TYPE_FLOAT_CDAB) {
543     float float_value;
544     value_t vt;
545
546     float_value = mb_register_to_float(values[1], values[0]);
547     DEBUG("Modbus plugin: mb_read_data: "
548           "Returned float value is %g",
549           (double)float_value);
550
551     CAST_TO_VALUE_T(ds, vt, float_value);
552     mb_submit(host, slave, data, vt);
553   } else if (data->register_type == REG_TYPE_INT32) {
554     union {
555       uint32_t u32;
556       int32_t i32;
557     } v;
558     value_t vt;
559
560     v.u32 = (((uint32_t)values[0]) << 16) | ((uint32_t)values[1]);
561     DEBUG("Modbus plugin: mb_read_data: "
562           "Returned int32 value is %" PRIi32,
563           v.i32);
564
565     CAST_TO_VALUE_T(ds, vt, v.i32);
566     mb_submit(host, slave, data, vt);
567   } else if (data->register_type == REG_TYPE_INT32_CDAB) {
568     union {
569       uint32_t u32;
570       int32_t i32;
571     } v;
572     value_t vt;
573
574     v.u32 = (((uint32_t)values[1]) << 16) | ((uint32_t)values[0]);
575     DEBUG("Modbus plugin: mb_read_data: "
576           "Returned int32 value is %" PRIi32,
577           v.i32);
578
579     CAST_TO_VALUE_T(ds, vt, v.i32);
580     mb_submit(host, slave, data, vt);
581   } else if (data->register_type == REG_TYPE_INT16) {
582     union {
583       uint16_t u16;
584       int16_t i16;
585     } v;
586     value_t vt;
587
588     v.u16 = values[0];
589
590     DEBUG("Modbus plugin: mb_read_data: "
591           "Returned int16 value is %" PRIi16,
592           v.i16);
593
594     CAST_TO_VALUE_T(ds, vt, v.i16);
595     mb_submit(host, slave, data, vt);
596   } else if (data->register_type == REG_TYPE_UINT32) {
597     uint32_t v32;
598     value_t vt;
599
600     v32 = (((uint32_t)values[0]) << 16) | ((uint32_t)values[1]);
601     DEBUG("Modbus plugin: mb_read_data: "
602           "Returned uint32 value is %" PRIu32,
603           v32);
604
605     CAST_TO_VALUE_T(ds, vt, v32);
606     mb_submit(host, slave, data, vt);
607   } else if (data->register_type == REG_TYPE_UINT32_CDAB) {
608     uint32_t v32;
609     value_t vt;
610
611     v32 = (((uint32_t)values[1]) << 16) | ((uint32_t)values[0]);
612     DEBUG("Modbus plugin: mb_read_data: "
613           "Returned uint32 value is %" PRIu32,
614           v32);
615
616     CAST_TO_VALUE_T(ds, vt, v32);
617     mb_submit(host, slave, data, vt);
618   } else if (data->register_type == REG_TYPE_UINT64) {
619     uint64_t v64;
620     value_t vt;
621
622     v64 = (((uint64_t)values[0]) << 48) | (((uint64_t)values[1]) << 32) |
623           (((uint64_t)values[2]) << 16) | (((uint64_t)values[3]));
624     DEBUG("Modbus plugin: mb_read_data: "
625           "Returned uint64 value is %" PRIu64,
626           v64);
627
628     CAST_TO_VALUE_T(ds, vt, v64);
629     mb_submit(host, slave, data, vt);
630   } else if (data->register_type == REG_TYPE_INT64) {
631     union {
632       uint64_t u64;
633       int64_t i64;
634     } v;
635     value_t vt;
636
637     v.u64 = (((uint64_t)values[0]) << 48) | (((uint64_t)values[1]) << 32) |
638             (((uint64_t)values[2]) << 16) | ((uint64_t)values[3]);
639     DEBUG("Modbus plugin: mb_read_data: "
640           "Returned uint64 value is %" PRIi64,
641           v.i64);
642
643     CAST_TO_VALUE_T(ds, vt, v.i64);
644     mb_submit(host, slave, data, vt);
645   } else /* if (data->register_type == REG_TYPE_UINT16) */
646   {
647     value_t vt;
648
649     DEBUG("Modbus plugin: mb_read_data: "
650           "Returned uint16 value is %" PRIu16,
651           values[0]);
652
653     CAST_TO_VALUE_T(ds, vt, values[0]);
654     mb_submit(host, slave, data, vt);
655   }
656
657   return 0;
658 } /* }}} int mb_read_data */
659
660 static int mb_read_slave(mb_host_t *host, mb_slave_t *slave) /* {{{ */
661 {
662   int success;
663   int status;
664
665   if ((host == NULL) || (slave == NULL))
666     return EINVAL;
667
668   success = 0;
669   for (mb_data_t *data = slave->collect; data != NULL; data = data->next) {
670     status = mb_read_data(host, slave, data);
671     if (status == 0)
672       success++;
673   }
674
675   if (success == 0)
676     return -1;
677   else
678     return 0;
679 } /* }}} int mb_read_slave */
680
681 static int mb_read(user_data_t *user_data) /* {{{ */
682 {
683   mb_host_t *host;
684   int success;
685   int status;
686
687   if ((user_data == NULL) || (user_data->data == NULL))
688     return EINVAL;
689
690   host = user_data->data;
691
692   success = 0;
693   for (size_t i = 0; i < host->slaves_num; i++) {
694     status = mb_read_slave(host, host->slaves + i);
695     if (status == 0)
696       success++;
697   }
698
699   if (success == 0)
700     return -1;
701   else
702     return 0;
703 } /* }}} int mb_read */
704
705 /* Free functions */
706
707 static void data_free_one(mb_data_t *data) /* {{{ */
708 {
709   if (data == NULL)
710     return;
711
712   sfree(data->name);
713   sfree(data);
714 } /* }}} void data_free_one */
715
716 static void data_free_all(mb_data_t *data) /* {{{ */
717 {
718   mb_data_t *next;
719
720   if (data == NULL)
721     return;
722
723   next = data->next;
724   data_free_one(data);
725
726   data_free_all(next);
727 } /* }}} void data_free_all */
728
729 static void slaves_free_all(mb_slave_t *slaves, size_t slaves_num) /* {{{ */
730 {
731   if (slaves == NULL)
732     return;
733
734   for (size_t i = 0; i < slaves_num; i++)
735     data_free_all(slaves[i].collect);
736   sfree(slaves);
737 } /* }}} void slaves_free_all */
738
739 static void host_free(void *void_host) /* {{{ */
740 {
741   mb_host_t *host = void_host;
742
743   if (host == NULL)
744     return;
745
746   slaves_free_all(host->slaves, host->slaves_num);
747   sfree(host);
748 } /* }}} void host_free */
749
750 /* Config functions */
751
752 static int mb_config_add_data(oconfig_item_t *ci) /* {{{ */
753 {
754   mb_data_t data = {0};
755   int status;
756
757   data.name = NULL;
758   data.register_type = REG_TYPE_UINT16;
759   data.next = NULL;
760
761   status = cf_util_get_string(ci, &data.name);
762   if (status != 0)
763     return status;
764
765   for (int i = 0; i < ci->children_num; i++) {
766     oconfig_item_t *child = ci->children + i;
767
768     if (strcasecmp("Type", child->key) == 0)
769       status = cf_util_get_string_buffer(child, data.type, sizeof(data.type));
770     else if (strcasecmp("Instance", child->key) == 0)
771       status = cf_util_get_string_buffer(child, data.instance,
772                                          sizeof(data.instance));
773     else if (strcasecmp("RegisterBase", child->key) == 0)
774       status = cf_util_get_int(child, &data.register_base);
775     else if (strcasecmp("RegisterType", child->key) == 0) {
776       char tmp[16];
777       status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
778       if (status != 0)
779         /* do nothing */;
780       else if (strcasecmp("Int16", tmp) == 0)
781         data.register_type = REG_TYPE_INT16;
782       else if (strcasecmp("Int32", tmp) == 0)
783         data.register_type = REG_TYPE_INT32;
784       else if (strcasecmp("Int32LE", tmp) == 0)
785         data.register_type = REG_TYPE_INT32_CDAB;
786       else if (strcasecmp("Uint16", tmp) == 0)
787         data.register_type = REG_TYPE_UINT16;
788       else if (strcasecmp("Uint32", tmp) == 0)
789         data.register_type = REG_TYPE_UINT32;
790       else if (strcasecmp("Uint32LE", tmp) == 0)
791         data.register_type = REG_TYPE_UINT32_CDAB;
792       else if (strcasecmp("Float", tmp) == 0)
793         data.register_type = REG_TYPE_FLOAT;
794       else if (strcasecmp("FloatLE", tmp) == 0)
795         data.register_type = REG_TYPE_FLOAT_CDAB;
796       else if (strcasecmp("Uint64", tmp) == 0)
797         data.register_type = REG_TYPE_UINT64;
798       else if (strcasecmp("Int64", tmp) == 0)
799         data.register_type = REG_TYPE_INT64;
800       else {
801         ERROR("Modbus plugin: The register type \"%s\" is unknown.", tmp);
802         status = -1;
803       }
804     } else if (strcasecmp("RegisterCmd", child->key) == 0) {
805 #if LEGACY_LIBMODBUS
806       ERROR("Modbus plugin: RegisterCmd parameter can not be used "
807             "with your libmodbus version");
808 #else
809       char tmp[16];
810       status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
811       if (status != 0)
812         /* do nothing */;
813       else if (strcasecmp("ReadHolding", tmp) == 0)
814         data.modbus_register_type = MREG_HOLDING;
815       else if (strcasecmp("ReadInput", tmp) == 0)
816         data.modbus_register_type = MREG_INPUT;
817       else {
818         ERROR("Modbus plugin: The modbus_register_type \"%s\" is unknown.",
819               tmp);
820         status = -1;
821       }
822 #endif
823     } else {
824       ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
825       status = -1;
826     }
827
828     if (status != 0)
829       break;
830   } /* for (i = 0; i < ci->children_num; i++) */
831
832   assert(data.name != NULL);
833   if (data.type[0] == 0) {
834     ERROR("Modbus plugin: Data block \"%s\": No type has been specified.",
835           data.name);
836     status = -1;
837   }
838
839   if (status == 0)
840     data_copy(&data_definitions, &data);
841
842   sfree(data.name);
843
844   return status;
845 } /* }}} int mb_config_add_data */
846
847 static int mb_config_set_host_address(mb_host_t *host, /* {{{ */
848                                       const char *address) {
849   struct addrinfo *ai_list;
850   int status;
851
852   if ((host == NULL) || (address == NULL))
853     return EINVAL;
854
855   struct addrinfo ai_hints = {
856       /* XXX: libmodbus can only handle IPv4 addresses. */
857       .ai_family = AF_INET,
858       .ai_flags = AI_ADDRCONFIG};
859
860   status = getaddrinfo(address, /* service = */ NULL, &ai_hints, &ai_list);
861   if (status != 0) {
862     ERROR("Modbus plugin: getaddrinfo failed: %s",
863           (status == EAI_SYSTEM) ? STRERRNO : gai_strerror(status));
864     return status;
865   }
866
867   for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
868        ai_ptr = ai_ptr->ai_next) {
869     status = getnameinfo(ai_ptr->ai_addr, ai_ptr->ai_addrlen, host->node,
870                          sizeof(host->node),
871                          /* service = */ NULL, /* length = */ 0,
872                          /* flags = */ NI_NUMERICHOST);
873     if (status == 0)
874       break;
875   } /* for (ai_ptr) */
876
877   freeaddrinfo(ai_list);
878
879   if (status != 0)
880     ERROR("Modbus plugin: Unable to translate node name: \"%s\"", address);
881   else /* if (status == 0) */
882   {
883     DEBUG("Modbus plugin: mb_config_set_host_address: %s -> %s", address,
884           host->node);
885   }
886
887   return status;
888 } /* }}} int mb_config_set_host_address */
889
890 static int mb_config_add_slave(mb_host_t *host, oconfig_item_t *ci) /* {{{ */
891 {
892   mb_slave_t *slave;
893   int status;
894
895   if ((host == NULL) || (ci == NULL))
896     return EINVAL;
897
898   slave = realloc(host->slaves, sizeof(*slave) * (host->slaves_num + 1));
899   if (slave == NULL)
900     return ENOMEM;
901   host->slaves = slave;
902   slave = host->slaves + host->slaves_num;
903   memset(slave, 0, sizeof(*slave));
904   slave->collect = NULL;
905
906   status = cf_util_get_int(ci, &slave->id);
907   if (status != 0)
908     return status;
909
910   for (int i = 0; i < ci->children_num; i++) {
911     oconfig_item_t *child = ci->children + i;
912
913     if (strcasecmp("Instance", child->key) == 0)
914       status = cf_util_get_string_buffer(child, slave->instance,
915                                          sizeof(slave->instance));
916     else if (strcasecmp("Collect", child->key) == 0) {
917       char buffer[1024];
918       status = cf_util_get_string_buffer(child, buffer, sizeof(buffer));
919       if (status == 0)
920         data_copy_by_name(&slave->collect, data_definitions, buffer);
921       status = 0; /* continue after failure. */
922     } else {
923       ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
924       status = -1;
925     }
926
927     if (status != 0)
928       break;
929   }
930
931   if ((status == 0) && (slave->collect == NULL))
932     status = EINVAL;
933
934   if (slave->id < 0)
935     status = EINVAL;
936
937   if (status == 0)
938     host->slaves_num++;
939   else /* if (status != 0) */
940     data_free_all(slave->collect);
941
942   return status;
943 } /* }}} int mb_config_add_slave */
944
945 static int mb_config_add_host(oconfig_item_t *ci) /* {{{ */
946 {
947   mb_host_t *host;
948   int status;
949
950   host = calloc(1, sizeof(*host));
951   if (host == NULL)
952     return ENOMEM;
953   host->slaves = NULL;
954
955   status = cf_util_get_string_buffer(ci, host->host, sizeof(host->host));
956   if (status != 0) {
957     sfree(host);
958     return status;
959   }
960   if (host->host[0] == 0) {
961     sfree(host);
962     return EINVAL;
963   }
964
965   for (int i = 0; i < ci->children_num; i++) {
966     oconfig_item_t *child = ci->children + i;
967     status = 0;
968
969     if (strcasecmp("Address", child->key) == 0) {
970       char buffer[NI_MAXHOST];
971       status = cf_util_get_string_buffer(child, buffer, sizeof(buffer));
972       if (status == 0)
973         status = mb_config_set_host_address(host, buffer);
974       if (status == 0)
975         host->conntype = MBCONN_TCP;
976     } else if (strcasecmp("Port", child->key) == 0) {
977       host->port = cf_util_get_port_number(child);
978       if (host->port <= 0)
979         status = -1;
980     } else if (strcasecmp("Device", child->key) == 0) {
981       status = cf_util_get_string_buffer(child, host->node, sizeof(host->node));
982       if (status == 0)
983         host->conntype = MBCONN_RTU;
984     } else if (strcasecmp("Baudrate", child->key) == 0)
985       status = cf_util_get_int(child, &host->baudrate);
986     else if (strcasecmp("Interval", child->key) == 0)
987       status = cf_util_get_cdtime(child, &host->interval);
988     else if (strcasecmp("Slave", child->key) == 0)
989       /* Don't set status: Gracefully continue if a slave fails. */
990       mb_config_add_slave(host, child);
991     else {
992       ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
993       status = -1;
994     }
995
996     if (status != 0)
997       break;
998   } /* for (i = 0; i < ci->children_num; i++) */
999
1000   assert(host->host[0] != 0);
1001   if (host->node[0] == 0) {
1002     ERROR("Modbus plugin: Data block \"%s\": No address or device has been "
1003           "specified.",
1004           host->host);
1005     status = -1;
1006   }
1007   if (host->conntype == MBCONN_RTU && !host->baudrate) {
1008     ERROR("Modbus plugin: Data block \"%s\": No serial baudrate has been "
1009           "specified.",
1010           host->host);
1011     status = -1;
1012   }
1013   if ((host->conntype == MBCONN_TCP && host->baudrate) ||
1014       (host->conntype == MBCONN_RTU && host->port)) {
1015     ERROR("Modbus plugin: Data block \"%s\": You've mixed up RTU and TCP "
1016           "options.",
1017           host->host);
1018     status = -1;
1019   }
1020
1021   if (status == 0) {
1022     char name[1024];
1023
1024     snprintf(name, sizeof(name), "modbus-%s", host->host);
1025
1026     plugin_register_complex_read(/* group = */ NULL, name,
1027                                  /* callback = */ mb_read,
1028                                  /* interval = */ host->interval,
1029                                  &(user_data_t){
1030                                      .data = host, .free_func = host_free,
1031                                  });
1032   } else {
1033     host_free(host);
1034   }
1035
1036   return status;
1037 } /* }}} int mb_config_add_host */
1038
1039 static int mb_config(oconfig_item_t *ci) /* {{{ */
1040 {
1041   if (ci == NULL)
1042     return EINVAL;
1043
1044   for (int i = 0; i < ci->children_num; i++) {
1045     oconfig_item_t *child = ci->children + i;
1046
1047     if (strcasecmp("Data", child->key) == 0)
1048       mb_config_add_data(child);
1049     else if (strcasecmp("Host", child->key) == 0)
1050       mb_config_add_host(child);
1051     else
1052       ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
1053   }
1054
1055   return 0;
1056 } /* }}} int mb_config */
1057
1058 /* ========= */
1059
1060 static int mb_shutdown(void) /* {{{ */
1061 {
1062   data_free_all(data_definitions);
1063   data_definitions = NULL;
1064
1065   return 0;
1066 } /* }}} int mb_shutdown */
1067
1068 void module_register(void) {
1069   plugin_register_complex_config("modbus", mb_config);
1070   plugin_register_shutdown("modbus", mb_shutdown);
1071 } /* void module_register */