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