Tree wide: Reformat with clang-format.
[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     ssnprintf(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     if (getpeername(modbus_get_socket(host->connection),
447                     (void *)&(struct sockaddr_storage){0},
448                     &(socklen_t){sizeof(struct sockaddr_storage)}) != 0)
449       status = errno;
450   }
451
452   if ((status == EBADF) || (status == ENOTSOCK) || (status == ENOTCONN)) {
453     status = mb_init_connection(host);
454     if (status != 0) {
455       ERROR("Modbus plugin: mb_init_connection (%s/%s) failed. ", host->host,
456             host->node);
457       host->is_connected = 0;
458       host->connection = NULL;
459       return (-1);
460     }
461   } else if (status != 0) {
462 #if LEGACY_LIBMODBUS
463     modbus_close(&host->connection);
464 #else
465     modbus_close(host->connection);
466     modbus_free(host->connection);
467 #endif
468   }
469
470 #if LEGACY_LIBMODBUS
471 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
472  * id to each call of "read_holding_registers". */
473 #define modbus_read_registers(ctx, addr, nb, dest)                             \
474   read_holding_registers(&(ctx), slave->id, (addr), (nb), (dest))
475 #else /* if !LEGACY_LIBMODBUS */
476   /* Version 2.9.2: Set the slave id once before querying the registers. */
477   status = modbus_set_slave(host->connection, slave->id);
478   if (status != 0) {
479     ERROR("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
480           slave->id, status);
481     return (-1);
482   }
483 #endif
484   if (data->modbus_register_type == MREG_INPUT) {
485     status = modbus_read_input_registers(host->connection,
486                                          /* start_addr = */ data->register_base,
487                                          /* num_registers = */ values_num,
488                                          /* buffer = */ values);
489   } else {
490     status = modbus_read_registers(host->connection,
491                                    /* start_addr = */ data->register_base,
492                                    /* num_registers = */ values_num,
493                                    /* buffer = */ values);
494   }
495   if (status != values_num) {
496     ERROR("Modbus plugin: modbus read function (%s/%s) failed. "
497           " status = %i, values_num = %i. Giving up.",
498           host->host, host->node, status, values_num);
499 #if LEGACY_LIBMODBUS
500     modbus_close(&host->connection);
501 #else
502     modbus_close(host->connection);
503     modbus_free(host->connection);
504 #endif
505     host->connection = NULL;
506     return (-1);
507   }
508
509   DEBUG("Modbus plugin: mb_read_data: Success! "
510         "modbus_read_registers returned with status %i.",
511         status);
512
513   if (data->register_type == REG_TYPE_FLOAT) {
514     float float_value;
515     value_t vt;
516
517     float_value = mb_register_to_float(values[0], values[1]);
518     DEBUG("Modbus plugin: mb_read_data: "
519           "Returned float value is %g",
520           (double)float_value);
521
522     CAST_TO_VALUE_T(ds, vt, float_value);
523     mb_submit(host, slave, data, vt);
524   } else if (data->register_type == REG_TYPE_INT32) {
525     union {
526       uint32_t u32;
527       int32_t i32;
528     } v;
529     value_t vt;
530
531     v.u32 = (((uint32_t)values[0]) << 16) | ((uint32_t)values[1]);
532     DEBUG("Modbus plugin: mb_read_data: "
533           "Returned int32 value is %" PRIi32,
534           v.i32);
535
536     CAST_TO_VALUE_T(ds, vt, v.i32);
537     mb_submit(host, slave, data, vt);
538   } else if (data->register_type == REG_TYPE_INT16) {
539     union {
540       uint16_t u16;
541       int16_t i16;
542     } v;
543     value_t vt;
544
545     v.u16 = values[0];
546
547     DEBUG("Modbus plugin: mb_read_data: "
548           "Returned int16 value is %" PRIi16,
549           v.i16);
550
551     CAST_TO_VALUE_T(ds, vt, v.i16);
552     mb_submit(host, slave, data, vt);
553   } else if (data->register_type == REG_TYPE_UINT32) {
554     uint32_t v32;
555     value_t vt;
556
557     v32 = (((uint32_t)values[0]) << 16) | ((uint32_t)values[1]);
558     DEBUG("Modbus plugin: mb_read_data: "
559           "Returned uint32 value is %" PRIu32,
560           v32);
561
562     CAST_TO_VALUE_T(ds, vt, v32);
563     mb_submit(host, slave, data, vt);
564   } else /* if (data->register_type == REG_TYPE_UINT16) */
565   {
566     value_t vt;
567
568     DEBUG("Modbus plugin: mb_read_data: "
569           "Returned uint16 value is %" PRIu16,
570           values[0]);
571
572     CAST_TO_VALUE_T(ds, vt, values[0]);
573     mb_submit(host, slave, data, vt);
574   }
575
576   return (0);
577 } /* }}} int mb_read_data */
578
579 static int mb_read_slave(mb_host_t *host, mb_slave_t *slave) /* {{{ */
580 {
581   int success;
582   int status;
583
584   if ((host == NULL) || (slave == NULL))
585     return (EINVAL);
586
587   success = 0;
588   for (mb_data_t *data = slave->collect; data != NULL; data = data->next) {
589     status = mb_read_data(host, slave, data);
590     if (status == 0)
591       success++;
592   }
593
594   if (success == 0)
595     return (-1);
596   else
597     return (0);
598 } /* }}} int mb_read_slave */
599
600 static int mb_read(user_data_t *user_data) /* {{{ */
601 {
602   mb_host_t *host;
603   int success;
604   int status;
605
606   if ((user_data == NULL) || (user_data->data == NULL))
607     return (EINVAL);
608
609   host = user_data->data;
610
611   success = 0;
612   for (size_t i = 0; i < host->slaves_num; i++) {
613     status = mb_read_slave(host, host->slaves + i);
614     if (status == 0)
615       success++;
616   }
617
618   if (success == 0)
619     return (-1);
620   else
621     return (0);
622 } /* }}} int mb_read */
623
624 /* Free functions */
625
626 static void data_free_one(mb_data_t *data) /* {{{ */
627 {
628   if (data == NULL)
629     return;
630
631   sfree(data->name);
632   sfree(data);
633 } /* }}} void data_free_one */
634
635 static void data_free_all(mb_data_t *data) /* {{{ */
636 {
637   mb_data_t *next;
638
639   if (data == NULL)
640     return;
641
642   next = data->next;
643   data_free_one(data);
644
645   data_free_all(next);
646 } /* }}} void data_free_all */
647
648 static void slaves_free_all(mb_slave_t *slaves, size_t slaves_num) /* {{{ */
649 {
650   if (slaves == NULL)
651     return;
652
653   for (size_t i = 0; i < slaves_num; i++)
654     data_free_all(slaves[i].collect);
655   sfree(slaves);
656 } /* }}} void slaves_free_all */
657
658 static void host_free(void *void_host) /* {{{ */
659 {
660   mb_host_t *host = void_host;
661
662   if (host == NULL)
663     return;
664
665   slaves_free_all(host->slaves, host->slaves_num);
666   sfree(host);
667 } /* }}} void host_free */
668
669 /* Config functions */
670
671 static int mb_config_add_data(oconfig_item_t *ci) /* {{{ */
672 {
673   mb_data_t data = {0};
674   int status;
675
676   data.name = NULL;
677   data.register_type = REG_TYPE_UINT16;
678   data.next = NULL;
679
680   status = cf_util_get_string(ci, &data.name);
681   if (status != 0)
682     return (status);
683
684   for (int i = 0; i < ci->children_num; i++) {
685     oconfig_item_t *child = ci->children + i;
686
687     if (strcasecmp("Type", child->key) == 0)
688       status = cf_util_get_string_buffer(child, data.type, sizeof(data.type));
689     else if (strcasecmp("Instance", child->key) == 0)
690       status = cf_util_get_string_buffer(child, data.instance,
691                                          sizeof(data.instance));
692     else if (strcasecmp("RegisterBase", child->key) == 0)
693       status = cf_util_get_int(child, &data.register_base);
694     else if (strcasecmp("RegisterType", child->key) == 0) {
695       char tmp[16];
696       status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
697       if (status != 0)
698         /* do nothing */;
699       else if (strcasecmp("Int16", tmp) == 0)
700         data.register_type = REG_TYPE_INT16;
701       else if (strcasecmp("Int32", tmp) == 0)
702         data.register_type = REG_TYPE_INT32;
703       else if (strcasecmp("Uint16", tmp) == 0)
704         data.register_type = REG_TYPE_UINT16;
705       else if (strcasecmp("Uint32", tmp) == 0)
706         data.register_type = REG_TYPE_UINT32;
707       else if (strcasecmp("Float", tmp) == 0)
708         data.register_type = REG_TYPE_FLOAT;
709       else {
710         ERROR("Modbus plugin: The register type \"%s\" is unknown.", tmp);
711         status = -1;
712       }
713     } else if (strcasecmp("RegisterCmd", child->key) == 0) {
714 #if LEGACY_LIBMODBUS
715       ERROR("Modbus plugin: RegisterCmd parameter can not be used "
716             "with your libmodbus version");
717 #else
718       char tmp[16];
719       status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
720       if (status != 0)
721         /* do nothing */;
722       else if (strcasecmp("ReadHolding", tmp) == 0)
723         data.modbus_register_type = MREG_HOLDING;
724       else if (strcasecmp("ReadInput", tmp) == 0)
725         data.modbus_register_type = MREG_INPUT;
726       else {
727         ERROR("Modbus plugin: The modbus_register_type \"%s\" is unknown.",
728               tmp);
729         status = -1;
730       }
731 #endif
732     } else {
733       ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
734       status = -1;
735     }
736
737     if (status != 0)
738       break;
739   } /* for (i = 0; i < ci->children_num; i++) */
740
741   assert(data.name != NULL);
742   if (data.type[0] == 0) {
743     ERROR("Modbus plugin: Data block \"%s\": No type has been specified.",
744           data.name);
745     status = -1;
746   }
747
748   if (status == 0)
749     data_copy(&data_definitions, &data);
750
751   sfree(data.name);
752
753   return (status);
754 } /* }}} int mb_config_add_data */
755
756 static int mb_config_set_host_address(mb_host_t *host, /* {{{ */
757                                       const char *address) {
758   struct addrinfo *ai_list;
759   int status;
760
761   if ((host == NULL) || (address == NULL))
762     return (EINVAL);
763
764   struct addrinfo ai_hints = {
765       /* XXX: libmodbus can only handle IPv4 addresses. */
766       .ai_family = AF_INET,
767       .ai_flags = AI_ADDRCONFIG};
768
769   status = getaddrinfo(address, /* service = */ NULL, &ai_hints, &ai_list);
770   if (status != 0) {
771     char errbuf[1024];
772     ERROR("Modbus plugin: getaddrinfo failed: %s",
773           (status == EAI_SYSTEM) ? sstrerror(errno, errbuf, sizeof(errbuf))
774                                  : gai_strerror(status));
775     return (status);
776   }
777
778   for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
779        ai_ptr = ai_ptr->ai_next) {
780     status = getnameinfo(ai_ptr->ai_addr, ai_ptr->ai_addrlen, host->node,
781                          sizeof(host->node),
782                          /* service = */ NULL, /* length = */ 0,
783                          /* flags = */ NI_NUMERICHOST);
784     if (status == 0)
785       break;
786   } /* for (ai_ptr) */
787
788   freeaddrinfo(ai_list);
789
790   if (status != 0)
791     ERROR("Modbus plugin: Unable to translate node name: \"%s\"", address);
792   else /* if (status == 0) */
793   {
794     DEBUG("Modbus plugin: mb_config_set_host_address: %s -> %s", address,
795           host->node);
796   }
797
798   return (status);
799 } /* }}} int mb_config_set_host_address */
800
801 static int mb_config_add_slave(mb_host_t *host, oconfig_item_t *ci) /* {{{ */
802 {
803   mb_slave_t *slave;
804   int status;
805
806   if ((host == NULL) || (ci == NULL))
807     return (EINVAL);
808
809   slave = realloc(host->slaves, sizeof(*slave) * (host->slaves_num + 1));
810   if (slave == NULL)
811     return (ENOMEM);
812   host->slaves = slave;
813   slave = host->slaves + host->slaves_num;
814   memset(slave, 0, sizeof(*slave));
815   slave->collect = NULL;
816
817   status = cf_util_get_int(ci, &slave->id);
818   if (status != 0)
819     return (status);
820
821   for (int i = 0; i < ci->children_num; i++) {
822     oconfig_item_t *child = ci->children + i;
823
824     if (strcasecmp("Instance", child->key) == 0)
825       status = cf_util_get_string_buffer(child, slave->instance,
826                                          sizeof(slave->instance));
827     else if (strcasecmp("Collect", child->key) == 0) {
828       char buffer[1024];
829       status = cf_util_get_string_buffer(child, buffer, sizeof(buffer));
830       if (status == 0)
831         data_copy_by_name(&slave->collect, data_definitions, buffer);
832       status = 0; /* continue after failure. */
833     } else {
834       ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
835       status = -1;
836     }
837
838     if (status != 0)
839       break;
840   }
841
842   if ((status == 0) && (slave->collect == NULL))
843     status = EINVAL;
844
845   if (slave->id < 0)
846     status = EINVAL;
847
848   if (status == 0)
849     host->slaves_num++;
850   else /* if (status != 0) */
851     data_free_all(slave->collect);
852
853   return (status);
854 } /* }}} int mb_config_add_slave */
855
856 static int mb_config_add_host(oconfig_item_t *ci) /* {{{ */
857 {
858   mb_host_t *host;
859   int status;
860
861   host = calloc(1, sizeof(*host));
862   if (host == NULL)
863     return (ENOMEM);
864   host->slaves = NULL;
865
866   status = cf_util_get_string_buffer(ci, host->host, sizeof(host->host));
867   if (status != 0) {
868     sfree(host);
869     return (status);
870   }
871   if (host->host[0] == 0) {
872     sfree(host);
873     return (EINVAL);
874   }
875
876   for (int i = 0; i < ci->children_num; i++) {
877     oconfig_item_t *child = ci->children + i;
878     status = 0;
879
880     if (strcasecmp("Address", child->key) == 0) {
881       char buffer[NI_MAXHOST];
882       status = cf_util_get_string_buffer(child, buffer, sizeof(buffer));
883       if (status == 0)
884         status = mb_config_set_host_address(host, buffer);
885       if (status == 0)
886         host->conntype = MBCONN_TCP;
887     } else if (strcasecmp("Port", child->key) == 0) {
888       host->port = cf_util_get_port_number(child);
889       if (host->port <= 0)
890         status = -1;
891     } else if (strcasecmp("Device", child->key) == 0) {
892       status = cf_util_get_string_buffer(child, host->node, sizeof(host->node));
893       if (status == 0)
894         host->conntype = MBCONN_RTU;
895     } else if (strcasecmp("Baudrate", child->key) == 0)
896       status = cf_util_get_int(child, &host->baudrate);
897     else if (strcasecmp("Interval", child->key) == 0)
898       status = cf_util_get_cdtime(child, &host->interval);
899     else if (strcasecmp("Slave", child->key) == 0)
900       /* Don't set status: Gracefully continue if a slave fails. */
901       mb_config_add_slave(host, child);
902     else {
903       ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
904       status = -1;
905     }
906
907     if (status != 0)
908       break;
909   } /* for (i = 0; i < ci->children_num; i++) */
910
911   assert(host->host[0] != 0);
912   if (host->node[0] == 0) {
913     ERROR("Modbus plugin: Data block \"%s\": No address or device has been "
914           "specified.",
915           host->host);
916     status = -1;
917   }
918   if (host->conntype == MBCONN_RTU && !host->baudrate) {
919     ERROR("Modbus plugin: Data block \"%s\": No serial baudrate has been "
920           "specified.",
921           host->host);
922     status = -1;
923   }
924   if ((host->conntype == MBCONN_TCP && host->baudrate) ||
925       (host->conntype == MBCONN_RTU && host->port)) {
926     ERROR("Modbus plugin: Data block \"%s\": You've mixed up RTU and TCP "
927           "options.",
928           host->host);
929     status = -1;
930   }
931
932   if (status == 0) {
933     user_data_t ud;
934     char name[1024];
935
936     ud.data = host;
937     ud.free_func = host_free;
938
939     ssnprintf(name, sizeof(name), "modbus-%s", host->host);
940
941     plugin_register_complex_read(/* group = */ NULL, name,
942                                  /* callback = */ mb_read,
943                                  /* interval = */ host->interval, &ud);
944   } else {
945     host_free(host);
946   }
947
948   return (status);
949 } /* }}} int mb_config_add_host */
950
951 static int mb_config(oconfig_item_t *ci) /* {{{ */
952 {
953   if (ci == NULL)
954     return (EINVAL);
955
956   for (int i = 0; i < ci->children_num; i++) {
957     oconfig_item_t *child = ci->children + i;
958
959     if (strcasecmp("Data", child->key) == 0)
960       mb_config_add_data(child);
961     else if (strcasecmp("Host", child->key) == 0)
962       mb_config_add_host(child);
963     else
964       ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
965   }
966
967   return (0);
968 } /* }}} int mb_config */
969
970 /* ========= */
971
972 static int mb_shutdown(void) /* {{{ */
973 {
974   data_free_all(data_definitions);
975   data_definitions = NULL;
976
977   return (0);
978 } /* }}} int mb_shutdown */
979
980 void module_register(void) {
981   plugin_register_complex_config("modbus", mb_config);
982   plugin_register_shutdown("modbus", mb_shutdown);
983 } /* void module_register */
984
985 /* vim: set sw=2 sts=2 et fdm=marker : */