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