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