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