2 * collectd - src/modbus.c
3 * Copyright (C) 2010,2011 noris network AG
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian Forster <octo at noris.net>
25 #include "configfile.h"
29 #include <modbus/modbus.h>
31 #ifndef LIBMODBUS_VERSION_CHECK
32 /* Assume version 2.0.3 */
33 # define LEGACY_LIBMODBUS 1
35 /* Assume version 2.9.2 */
38 #ifndef MODBUS_TCP_DEFAULT_PORT
39 # ifdef MODBUS_TCP_PORT
40 # define MODBUS_TCP_DEFAULT_PORT MODBUS_TCP_PORT
42 # define MODBUS_TCP_DEFAULT_PORT 502
60 * Instance "foobar" # optional
69 enum mb_register_type_e /* {{{ */
77 typedef enum mb_register_type_e mb_register_type_t;
80 typedef struct mb_data_s mb_data_t;
81 struct mb_data_s /* {{{ */
85 mb_register_type_t register_type;
86 char type[DATA_MAX_NAME_LEN];
87 char instance[DATA_MAX_NAME_LEN];
92 struct mb_slave_s /* {{{ */
95 char instance[DATA_MAX_NAME_LEN];
98 typedef struct mb_slave_s mb_slave_t;
100 struct mb_host_s /* {{{ */
102 char host[DATA_MAX_NAME_LEN];
103 char node[NI_MAXHOST];
104 /* char service[NI_MAXSERV]; */
112 modbus_param_t connection;
114 modbus_t *connection;
117 _Bool have_reconnected;
119 typedef struct mb_host_s mb_host_t;
121 struct mb_data_group_s;
122 typedef struct mb_data_group_s mb_data_group_t;
123 struct mb_data_group_s /* {{{ */
125 mb_data_t *registers;
126 size_t registers_num;
128 mb_data_group_t *next;
134 static mb_data_t *data_definitions = NULL;
139 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
147 for (ptr = src; ptr != NULL; ptr = ptr->next)
148 if (strcasecmp (ptr->name, name) == 0)
152 } /* }}} mb_data_t *data_get_by_name */
154 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
158 if ((dst == NULL) || (src == NULL))
169 while (ptr->next != NULL)
175 } /* }}} int data_append */
177 /* Copy a single mb_data_t and append it to another list. */
178 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
183 if ((dst == NULL) || (src == NULL))
186 tmp = malloc (sizeof (*tmp));
189 memcpy (tmp, src, sizeof (*tmp));
193 tmp->name = strdup (src->name);
194 if (tmp->name == NULL)
200 status = data_append (dst, tmp);
209 } /* }}} int data_copy */
211 /* Lookup a single mb_data_t instance, copy it and append the copy to another
213 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
218 if ((dst == NULL) || (src == NULL) || (name == NULL))
221 ptr = data_get_by_name (src, name);
225 return (data_copy (dst, ptr));
226 } /* }}} int data_copy_by_name */
230 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
231 mb_data_t *data, value_t value)
233 value_list_t vl = VALUE_LIST_INIT;
235 if ((host == NULL) || (slave == NULL) || (data == NULL))
238 if (host->interval <= 0)
239 host->interval = interval_g;
241 if (slave->instance[0] == 0)
242 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
247 vl.interval = host->interval;
248 sstrncpy (vl.host, host->host, sizeof (vl.host));
249 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
250 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
251 sstrncpy (vl.type, data->type, sizeof (vl.type));
252 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
254 return (plugin_dispatch_values (&vl));
255 } /* }}} int mb_submit */
257 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
265 #if BYTE_ORDER == LITTLE_ENDIAN
267 conv.b[0] = lo & 0x00ff;
268 conv.b[1] = (lo >> 8) & 0x00ff;
269 conv.b[2] = hi & 0x00ff;
270 conv.b[3] = (hi >> 8) & 0x00ff;
272 conv.b[3] = lo & 0x00ff;
273 conv.b[2] = (lo >> 8) & 0x00ff;
274 conv.b[1] = hi & 0x00ff;
275 conv.b[0] = (hi >> 8) & 0x00ff;
279 } /* }}} float mb_register_to_float */
283 static int mb_init_connection (mb_host_t *host) /* {{{ */
290 if (host->is_connected)
293 /* Only reconnect once per interval. */
294 if (host->have_reconnected)
297 modbus_set_debug (&host->connection, 1);
299 /* We'll do the error handling ourselves. */
300 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
302 if ((host->port < 1) || (host->port > 65535))
303 host->port = MODBUS_TCP_DEFAULT_PORT;
305 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
306 host->node, host->port);
308 modbus_init_tcp (&host->connection,
309 /* host = */ host->node,
310 /* port = */ host->port);
312 status = modbus_connect (&host->connection);
315 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
316 host->node, host->port, status);
320 host->is_connected = 1;
321 host->have_reconnected = 1;
323 } /* }}} int mb_init_connection */
324 /* #endif LEGACY_LIBMODBUS */
326 #else /* if !LEGACY_LIBMODBUS */
328 static int mb_init_connection (mb_host_t *host) /* {{{ */
335 if (host->connection != NULL)
338 /* Only reconnect once per interval. */
339 if (host->have_reconnected)
342 if ((host->port < 1) || (host->port > 65535))
343 host->port = MODBUS_TCP_DEFAULT_PORT;
345 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
346 host->node, host->port);
348 host->connection = modbus_new_tcp (host->node, host->port);
349 if (host->connection == NULL)
351 host->have_reconnected = 1;
352 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
356 modbus_set_debug (host->connection, 1);
358 /* We'll do the error handling ourselves. */
359 modbus_set_error_recovery (host->connection, 0);
361 status = modbus_connect (host->connection);
364 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
365 host->node, host->port, status);
366 modbus_free (host->connection);
367 host->connection = NULL;
371 host->have_reconnected = 1;
373 } /* }}} int mb_init_connection */
374 #endif /* !LEGACY_LIBMODBUS */
376 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
377 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
378 (vt).counter = (counter_t) (raw); \
379 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
380 (vt).gauge = (gauge_t) (raw); \
381 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
382 (vt).derive = (derive_t) (raw); \
383 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
384 (vt).absolute = (absolute_t) (raw); \
387 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
392 const data_set_t *ds;
396 if ((host == NULL) || (slave == NULL) || (data == NULL))
399 ds = plugin_get_ds (data->type);
402 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
408 ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
409 "I can only handle data sets with only one data source.",
410 data->type, ds->ds_num);
414 if ((ds->ds[0].type != DS_TYPE_GAUGE)
415 && (data->register_type != REG_TYPE_INT32)
416 && (data->register_type != REG_TYPE_UINT32))
418 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
419 "This will most likely result in problems, because the register type "
420 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
423 memset (values, 0, sizeof (values));
424 if ((data->register_type == REG_TYPE_INT32)
425 || (data->register_type == REG_TYPE_UINT32)
426 || (data->register_type == REG_TYPE_FLOAT))
432 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
433 * id to each call of "read_holding_registers". */
434 # define modbus_read_registers(ctx, addr, nb, dest) \
435 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
436 #else /* if !LEGACY_LIBMODBUS */
437 /* Version 2.9.2: Set the slave id once before querying the registers. */
438 status = modbus_set_slave (host->connection, slave->id);
441 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
447 for (i = 0; i < 2; i++)
449 status = modbus_read_registers (host->connection,
450 /* start_addr = */ data->register_base,
451 /* num_registers = */ values_num, /* buffer = */ values);
455 if (host->is_connected)
458 modbus_close (&host->connection);
459 host->is_connected = 0;
461 modbus_close (host->connection);
462 modbus_free (host->connection);
463 host->connection = NULL;
467 /* If we already tried reconnecting this round, give up. */
468 if (host->have_reconnected)
470 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
471 "Reconnecting has already been tried. Giving up.", host->host);
475 /* Maybe the device closed the connection during the waiting interval.
476 * Try re-establishing the connection. */
477 status = mb_init_connection (host);
480 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
481 "While trying to reconnect, connecting to \"%s\" failed. "
483 host->host, host->node);
487 DEBUG ("Modbus plugin: Re-established connection to %s", host->host);
491 } /* for (i = 0, 1) */
493 DEBUG ("Modbus plugin: mb_read_data: Success! "
494 "modbus_read_registers returned with status %i.", status);
496 if (data->register_type == REG_TYPE_FLOAT)
501 float_value = mb_register_to_float (values[0], values[1]);
502 DEBUG ("Modbus plugin: mb_read_data: "
503 "Returned float value is %g", (double) float_value);
505 CAST_TO_VALUE_T (ds, vt, float_value);
506 mb_submit (host, slave, data, vt);
508 else if (data->register_type == REG_TYPE_INT32)
517 v.u32 = (((uint32_t) values[0]) << 16)
518 | ((uint32_t) values[1]);
519 DEBUG ("Modbus plugin: mb_read_data: "
520 "Returned int32 value is %"PRIi32, v.i32);
522 CAST_TO_VALUE_T (ds, vt, v.i32);
523 mb_submit (host, slave, data, vt);
525 else if (data->register_type == REG_TYPE_INT16)
536 DEBUG ("Modbus plugin: mb_read_data: "
537 "Returned int16 value is %"PRIi16, v.i16);
539 CAST_TO_VALUE_T (ds, vt, v.i16);
540 mb_submit (host, slave, data, vt);
542 else if (data->register_type == REG_TYPE_UINT32)
547 v32 = (((uint32_t) values[0]) << 16)
548 | ((uint32_t) values[1]);
549 DEBUG ("Modbus plugin: mb_read_data: "
550 "Returned uint32 value is %"PRIu32, v32);
552 CAST_TO_VALUE_T (ds, vt, v32);
553 mb_submit (host, slave, data, vt);
555 else /* if (data->register_type == REG_TYPE_UINT16) */
559 DEBUG ("Modbus plugin: mb_read_data: "
560 "Returned uint16 value is %"PRIu16, values[0]);
562 CAST_TO_VALUE_T (ds, vt, values[0]);
563 mb_submit (host, slave, data, vt);
567 } /* }}} int mb_read_data */
569 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
575 if ((host == NULL) || (slave == NULL))
579 for (data = slave->collect; data != NULL; data = data->next)
581 status = mb_read_data (host, slave, data);
590 } /* }}} int mb_read_slave */
592 static int mb_read (user_data_t *user_data) /* {{{ */
599 if ((user_data == NULL) || (user_data->data == NULL))
602 host = user_data->data;
604 /* Clear the reconnect flag. */
605 host->have_reconnected = 0;
608 for (i = 0; i < host->slaves_num; i++)
610 status = mb_read_slave (host, host->slaves + i);
619 } /* }}} int mb_read */
623 static void data_free_one (mb_data_t *data) /* {{{ */
630 } /* }}} void data_free_one */
632 static void data_free_all (mb_data_t *data) /* {{{ */
640 data_free_one (data);
642 data_free_all (next);
643 } /* }}} void data_free_all */
645 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
652 for (i = 0; i < slaves_num; i++)
653 data_free_all (slaves[i].collect);
655 } /* }}} void slaves_free_all */
657 static void host_free (void *void_host) /* {{{ */
659 mb_host_t *host = void_host;
664 slaves_free_all (host->slaves, host->slaves_num);
666 } /* }}} void host_free */
668 /* Config functions */
670 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
676 memset (&data, 0, sizeof (data));
678 data.register_type = REG_TYPE_UINT16;
681 status = cf_util_get_string (ci, &data.name);
685 for (i = 0; i < ci->children_num; i++)
687 oconfig_item_t *child = ci->children + i;
690 if (strcasecmp ("Type", child->key) == 0)
691 status = cf_util_get_string_buffer (child,
692 data.type, sizeof (data.type));
693 else if (strcasecmp ("Instance", child->key) == 0)
694 status = cf_util_get_string_buffer (child,
695 data.instance, sizeof (data.instance));
696 else if (strcasecmp ("RegisterBase", child->key) == 0)
697 status = cf_util_get_int (child, &data.register_base);
698 else if (strcasecmp ("RegisterType", child->key) == 0)
701 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
704 else if (strcasecmp ("Int16", tmp) == 0)
705 data.register_type = REG_TYPE_INT16;
706 else if (strcasecmp ("Int32", tmp) == 0)
707 data.register_type = REG_TYPE_INT32;
708 else if (strcasecmp ("Uint16", tmp) == 0)
709 data.register_type = REG_TYPE_UINT16;
710 else if (strcasecmp ("Uint32", tmp) == 0)
711 data.register_type = REG_TYPE_UINT32;
712 else if (strcasecmp ("Float", tmp) == 0)
713 data.register_type = REG_TYPE_FLOAT;
716 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
722 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
728 } /* for (i = 0; i < ci->children_num; i++) */
730 assert (data.name != NULL);
731 if (data.type[0] == 0)
733 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
739 data_copy (&data_definitions, &data);
744 } /* }}} int mb_config_add_data */
746 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
749 struct addrinfo *ai_list;
750 struct addrinfo *ai_ptr;
751 struct addrinfo ai_hints;
754 if ((host == NULL) || (address == NULL))
757 memset (&ai_hints, 0, sizeof (ai_hints));
759 ai_hints.ai_flags |= AI_ADDRCONFIG;
761 /* XXX: libmodbus can only handle IPv4 addresses. */
762 ai_hints.ai_family = AF_INET;
763 ai_hints.ai_addr = NULL;
764 ai_hints.ai_canonname = NULL;
765 ai_hints.ai_next = NULL;
768 status = getaddrinfo (address, /* service = */ NULL,
769 &ai_hints, &ai_list);
773 ERROR ("Modbus plugin: getaddrinfo failed: %s",
774 (status == EAI_SYSTEM)
775 ? sstrerror (errno, errbuf, sizeof (errbuf))
776 : gai_strerror (status));
780 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
782 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
783 host->node, sizeof (host->node),
784 /* service = */ NULL, /* length = */ 0,
785 /* flags = */ NI_NUMERICHOST);
790 freeaddrinfo (ai_list);
793 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
794 else /* if (status == 0) */
796 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
797 address, host->node);
801 } /* }}} int mb_config_set_host_address */
803 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
809 if ((host == NULL) || (ci == NULL))
812 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
815 host->slaves = slave;
816 slave = host->slaves + host->slaves_num;
817 memset (slave, 0, sizeof (*slave));
818 slave->collect = NULL;
820 status = cf_util_get_int (ci, &slave->id);
824 for (i = 0; i < ci->children_num; i++)
826 oconfig_item_t *child = ci->children + i;
829 if (strcasecmp ("Instance", child->key) == 0)
830 status = cf_util_get_string_buffer (child,
831 slave->instance, sizeof (slave->instance));
832 else if (strcasecmp ("Collect", child->key) == 0)
835 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
837 data_copy_by_name (&slave->collect, data_definitions, buffer);
838 status = 0; /* continue after failure. */
842 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
850 if ((status == 0) && (slave->collect == NULL))
858 else /* if (status != 0) */
859 data_free_all (slave->collect);
862 } /* }}} int mb_config_add_slave */
864 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
870 host = malloc (sizeof (*host));
873 memset (host, 0, sizeof (*host));
876 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
879 if (host->host[0] == 0)
882 for (i = 0; i < ci->children_num; i++)
884 oconfig_item_t *child = ci->children + i;
887 if (strcasecmp ("Address", child->key) == 0)
889 char buffer[NI_MAXHOST];
890 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
892 status = mb_config_set_host_address (host, buffer);
894 else if (strcasecmp ("Port", child->key) == 0)
896 host->port = cf_util_get_port_number (child);
900 else if (strcasecmp ("Interval", child->key) == 0)
901 status = cf_util_get_cdtime (child, &host->interval);
902 else if (strcasecmp ("Slave", child->key) == 0)
903 /* Don't set status: Gracefully continue if a slave fails. */
904 mb_config_add_slave (host, child);
907 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
913 } /* for (i = 0; i < ci->children_num; i++) */
915 assert (host->host[0] != 0);
916 if (host->host[0] == 0)
918 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
927 struct timespec interval = { 0, 0 };
930 ud.free_func = host_free;
932 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
934 CDTIME_T_TO_TIMESPEC (host->interval, &interval);
936 plugin_register_complex_read (/* group = */ NULL, name,
937 /* callback = */ mb_read,
938 /* interval = */ (host->interval > 0) ? &interval : NULL,
947 } /* }}} int mb_config_add_host */
949 static int mb_config (oconfig_item_t *ci) /* {{{ */
956 for (i = 0; i < ci->children_num; i++)
958 oconfig_item_t *child = ci->children + i;
960 if (strcasecmp ("Data", child->key) == 0)
961 mb_config_add_data (child);
962 else if (strcasecmp ("Host", child->key) == 0)
963 mb_config_add_host (child);
965 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
969 } /* }}} int mb_config */
973 static int mb_shutdown (void) /* {{{ */
975 data_free_all (data_definitions);
976 data_definitions = NULL;
979 } /* }}} int mb_shutdown */
981 void module_register (void)
983 plugin_register_complex_config ("modbus", mb_config);
984 plugin_register_shutdown ("modbus", mb_shutdown);
985 } /* void module_register */
987 /* vim: set sw=2 sts=2 et fdm=marker : */