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