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