2 * collectd - src/modbus.c
3 * Copyright (C) 2010 noris network AG
4 * Copyright (C) 2011 Universiteit Gent
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation; only version 2.1 of the License is
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 * Florian Forster <octo at noris.net>
22 * Ivo De Decker <ivo.dedecker at ugent.be>
28 #include "configfile.h"
32 #include <modbus/modbus.h>
34 #ifndef LIBMODBUS_VERSION_CHECK
35 /* Assume version 2.0.3 */
36 # define LEGACY_LIBMODBUS 1
38 /* Assume version 2.9.2 */
41 #ifndef MODBUS_TCP_DEFAULT_PORT
42 # ifdef MODBUS_TCP_PORT
43 # define MODBUS_TCP_DEFAULT_PORT MODBUS_TCP_PORT
45 # define MODBUS_TCP_DEFAULT_PORT 502
63 * Instance "foobar" # optional
72 enum mb_register_type_e /* {{{ */
78 typedef enum mb_register_type_e mb_register_type_t;
81 typedef struct mb_data_s mb_data_t;
82 struct mb_data_s /* {{{ */
86 mb_register_type_t register_type;
87 char type[DATA_MAX_NAME_LEN];
88 char instance[DATA_MAX_NAME_LEN];
93 struct mb_datagroup_s;
94 typedef struct mb_datagroup_s mb_datagroup_t;
95 struct mb_datagroup_s /* {{{ */
100 mb_datagroup_t *next;
103 struct mb_slave_s /* {{{ */
106 char instance[DATA_MAX_NAME_LEN];
109 typedef struct mb_slave_s mb_slave_t;
111 struct mb_host_s /* {{{ */
113 char host[DATA_MAX_NAME_LEN];
114 char node[NI_MAXHOST];
115 /* char service[NI_MAXSERV]; */
123 modbus_param_t connection;
125 modbus_t *connection;
128 _Bool have_reconnected;
130 typedef struct mb_host_s mb_host_t;
132 struct mb_data_group_s;
133 typedef struct mb_data_group_s mb_data_group_t;
134 struct mb_data_group_s /* {{{ */
136 mb_data_t *registers;
137 size_t registers_num;
139 mb_data_group_t *next;
145 static mb_data_t *data_definitions = NULL;
146 static mb_datagroup_t *data_groups = NULL;
151 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
159 for (ptr = src; ptr != NULL; ptr = ptr->next)
160 if (strcasecmp (ptr->name, name) == 0)
164 } /* }}} mb_data_t *data_get_by_name */
166 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
170 if ((dst == NULL) || (src == NULL))
181 while (ptr->next != NULL)
187 } /* }}} int data_append */
189 /* Copy a single mb_data_t and append it to another list. */
190 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
195 if ((dst == NULL) || (src == NULL))
198 tmp = malloc (sizeof (*tmp));
201 memcpy (tmp, src, sizeof (*tmp));
205 tmp->name = strdup (src->name);
206 if (tmp->name == NULL)
212 status = data_append (dst, tmp);
221 } /* }}} int data_copy */
223 /* Lookup a single mb_data_t instance, copy it and append the copy to another
225 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
230 if ((dst == NULL) || (src == NULL) || (name == NULL))
233 ptr = data_get_by_name (src, name);
237 return (data_copy (dst, ptr));
238 } /* }}} int data_copy_by_name */
240 static mb_datagroup_t *datagroup_get_by_name (mb_datagroup_t *src, /* {{{ */
248 for (ptr = src; ptr != NULL; ptr = ptr->next)
249 if (strcasecmp (ptr->name, name) == 0)
253 } /* }}} mb_datagroup_t *datagroup_get_by_name */
255 static int datagroup_append (mb_datagroup_t **dst, mb_datagroup_t *src) /* {{{ */
259 if ((dst == NULL) || (src == NULL))
270 while (ptr->next != NULL)
276 } /* }}} int datagroup_append */
278 /* Copy a single mb_datagroup_t and append it to another list. */
279 static int datagroup_copy (mb_datagroup_t **dst, const mb_datagroup_t *src) /* {{{ */
284 if ((dst == NULL) || (src == NULL))
287 tmp = malloc (sizeof (*tmp));
290 memcpy (tmp, src, sizeof (*tmp));
294 tmp->name = strdup (src->name);
295 if (tmp->name == NULL)
301 status = datagroup_append (dst, tmp);
310 } /* }}} int datagroup_copy */
314 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
315 mb_data_t *data, value_t value)
317 value_list_t vl = VALUE_LIST_INIT;
319 if ((host == NULL) || (slave == NULL) || (data == NULL))
322 if (host->interval <= 0)
323 host->interval = interval_g;
325 if (slave->instance[0] == 0)
326 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
331 vl.interval = host->interval;
332 sstrncpy (vl.host, host->host, sizeof (vl.host));
333 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
334 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
335 sstrncpy (vl.type, data->type, sizeof (vl.type));
336 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
338 return (plugin_dispatch_values (&vl));
339 } /* }}} int mb_submit */
341 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
349 #if BYTE_ORDER == LITTLE_ENDIAN
351 conv.b[0] = lo & 0x00ff;
352 conv.b[1] = (lo >> 8) & 0x00ff;
353 conv.b[2] = hi & 0x00ff;
354 conv.b[3] = (hi >> 8) & 0x00ff;
356 conv.b[3] = lo & 0x00ff;
357 conv.b[2] = (lo >> 8) & 0x00ff;
358 conv.b[1] = hi & 0x00ff;
359 conv.b[0] = (hi >> 8) & 0x00ff;
363 } /* }}} float mb_register_to_float */
367 static int mb_init_connection (mb_host_t *host) /* {{{ */
374 if (host->is_connected)
377 /* Only reconnect once per interval. */
378 if (host->have_reconnected)
381 modbus_set_debug (&host->connection, 1);
383 /* We'll do the error handling ourselves. */
384 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
386 if ((host->port < 1) || (host->port > 65535))
387 host->port = MODBUS_TCP_DEFAULT_PORT;
389 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
390 host->node, host->port);
392 modbus_init_tcp (&host->connection,
393 /* host = */ host->node,
394 /* port = */ host->port);
396 status = modbus_connect (&host->connection);
399 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
400 host->node, host->port, status);
404 host->is_connected = 1;
405 host->have_reconnected = 1;
407 } /* }}} int mb_init_connection */
408 /* #endif LEGACY_LIBMODBUS */
410 #else /* if !LEGACY_LIBMODBUS */
412 static int mb_init_connection (mb_host_t *host) /* {{{ */
419 if (host->connection != NULL)
422 /* Only reconnect once per interval. */
423 if (host->have_reconnected)
426 if ((host->port < 1) || (host->port > 65535))
427 host->port = MODBUS_TCP_DEFAULT_PORT;
429 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
430 host->node, host->port);
432 host->connection = modbus_new_tcp (host->node, host->port);
433 if (host->connection == NULL)
435 host->have_reconnected = 1;
436 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
440 modbus_set_debug (host->connection, 1);
442 /* We'll do the error handling ourselves. */
443 modbus_set_error_recovery (host->connection, 0);
445 status = modbus_connect (host->connection);
448 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
449 host->node, host->port, status);
450 modbus_free (host->connection);
451 host->connection = NULL;
455 host->have_reconnected = 1;
457 } /* }}} int mb_init_connection */
458 #endif /* !LEGACY_LIBMODBUS */
460 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
461 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
462 (vt).counter = (counter_t) (raw); \
463 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
464 (vt).gauge = (gauge_t) (raw); \
465 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
466 (vt).derive = (derive_t) (raw); \
467 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
468 (vt).absolute = (absolute_t) (raw); \
471 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
476 const data_set_t *ds;
480 if ((host == NULL) || (slave == NULL) || (data == NULL))
483 ds = plugin_get_ds (data->type);
486 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
492 ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
493 "I can only handle data sets with only one data source.",
494 data->type, ds->ds_num);
498 if ((ds->ds[0].type != DS_TYPE_GAUGE)
499 && (data->register_type != REG_TYPE_UINT32))
501 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
502 "This will most likely result in problems, because the register type "
503 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
506 memset (values, 0, sizeof (values));
507 if ((data->register_type == REG_TYPE_UINT32)
508 || (data->register_type == REG_TYPE_FLOAT))
514 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
515 * id to each call of "read_holding_registers". */
516 # define modbus_read_registers(ctx, addr, nb, dest) \
517 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
518 #else /* if !LEGACY_LIBMODBUS */
519 /* Version 2.9.2: Set the slave id once before querying the registers. */
520 status = modbus_set_slave (host->connection, slave->id);
523 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
529 for (i = 0; i < 2; i++)
531 status = modbus_read_registers (host->connection,
532 /* start_addr = */ data->register_base,
533 /* num_registers = */ values_num, /* buffer = */ values);
537 if (host->is_connected)
540 modbus_close (&host->connection);
541 host->is_connected = 0;
543 modbus_close (host->connection);
544 modbus_free (host->connection);
545 host->connection = NULL;
549 /* If we already tried reconnecting this round, give up. */
550 if (host->have_reconnected)
552 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
553 "Reconnecting has already been tried. Giving up.", host->host);
557 /* Maybe the device closed the connection during the waiting interval.
558 * Try re-establishing the connection. */
559 status = mb_init_connection (host);
562 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
563 "While trying to reconnect, connecting to \"%s\" failed. "
565 host->host, host->node);
569 DEBUG ("Modbus plugin: Re-established connection to %s", host->host);
573 } /* for (i = 0, 1) */
575 DEBUG ("Modbus plugin: mb_read_data: Success! "
576 "modbus_read_registers returned with status %i.", status);
578 if (data->register_type == REG_TYPE_FLOAT)
583 float_value = mb_register_to_float (values[0], values[1]);
584 DEBUG ("Modbus plugin: mb_read_data: "
585 "Returned float value is %g", (double) float_value);
587 CAST_TO_VALUE_T (ds, vt, float_value);
588 mb_submit (host, slave, data, vt);
590 else if (data->register_type == REG_TYPE_UINT32)
595 v32 = (values[0] << 16) | values[1];
596 DEBUG ("Modbus plugin: mb_read_data: "
597 "Returned uint32 value is %"PRIu32, v32);
599 CAST_TO_VALUE_T (ds, vt, v32);
600 mb_submit (host, slave, data, vt);
602 else /* if (data->register_type == REG_TYPE_UINT16) */
606 DEBUG ("Modbus plugin: mb_read_data: "
607 "Returned uint16 value is %"PRIu16, values[0]);
609 CAST_TO_VALUE_T (ds, vt, values[0]);
610 mb_submit (host, slave, data, vt);
614 } /* }}} int mb_read_data */
616 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
622 if ((host == NULL) || (slave == NULL))
626 for (data = slave->collect; data != NULL; data = data->next)
628 status = mb_read_data (host, slave, data);
637 } /* }}} int mb_read_slave */
639 static int mb_read (user_data_t *user_data) /* {{{ */
646 if ((user_data == NULL) || (user_data->data == NULL))
649 host = user_data->data;
651 /* Clear the reconnect flag. */
652 host->have_reconnected = 0;
655 for (i = 0; i < host->slaves_num; i++)
657 status = mb_read_slave (host, host->slaves + i);
666 } /* }}} int mb_read */
670 static void data_free_one (mb_data_t *data) /* {{{ */
677 } /* }}} void data_free_one */
679 static void data_free_all (mb_data_t *data) /* {{{ */
687 data_free_one (data);
689 data_free_all (next);
690 } /* }}} void data_free_all */
692 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
699 for (i = 0; i < slaves_num; i++)
700 data_free_all (slaves[i].collect);
702 } /* }}} void slaves_free_all */
704 static void host_free (void *void_host) /* {{{ */
706 mb_host_t *host = void_host;
711 slaves_free_all (host->slaves, host->slaves_num);
713 } /* }}} void host_free */
715 /* Config functions */
717 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
723 memset (&data, 0, sizeof (data));
725 data.register_type = REG_TYPE_UINT16;
728 status = cf_util_get_string (ci, &data.name);
732 for (i = 0; i < ci->children_num; i++)
734 oconfig_item_t *child = ci->children + i;
737 if (strcasecmp ("Type", child->key) == 0)
738 status = cf_util_get_string_buffer (child,
739 data.type, sizeof (data.type));
740 else if (strcasecmp ("Instance", child->key) == 0)
741 status = cf_util_get_string_buffer (child,
742 data.instance, sizeof (data.instance));
743 else if (strcasecmp ("RegisterBase", child->key) == 0)
744 status = cf_util_get_int (child, &data.register_base);
745 else if (strcasecmp ("RegisterType", child->key) == 0)
748 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
751 else if (strcasecmp ("Uint16", tmp) == 0)
752 data.register_type = REG_TYPE_UINT16;
753 else if (strcasecmp ("Uint32", tmp) == 0)
754 data.register_type = REG_TYPE_UINT32;
755 else if (strcasecmp ("Float", tmp) == 0)
756 data.register_type = REG_TYPE_FLOAT;
759 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
765 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
771 } /* for (i = 0; i < ci->children_num; i++) */
773 assert (data.name != NULL);
774 if (data.type[0] == 0)
776 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
782 data_copy (&data_definitions, &data);
787 } /* }}} int mb_config_add_data */
789 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
792 struct addrinfo *ai_list;
793 struct addrinfo *ai_ptr;
794 struct addrinfo ai_hints;
797 if ((host == NULL) || (address == NULL))
800 memset (&ai_hints, 0, sizeof (ai_hints));
802 ai_hints.ai_flags |= AI_ADDRCONFIG;
804 /* XXX: libmodbus can only handle IPv4 addresses. */
805 ai_hints.ai_family = AF_INET;
806 ai_hints.ai_addr = NULL;
807 ai_hints.ai_canonname = NULL;
808 ai_hints.ai_next = NULL;
811 status = getaddrinfo (address, /* service = */ NULL,
812 &ai_hints, &ai_list);
816 ERROR ("Modbus plugin: getaddrinfo failed: %s",
817 (status == EAI_SYSTEM)
818 ? sstrerror (errno, errbuf, sizeof (errbuf))
819 : gai_strerror (status));
823 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
825 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
826 host->node, sizeof (host->node),
827 /* service = */ NULL, /* length = */ 0,
828 /* flags = */ NI_NUMERICHOST);
833 freeaddrinfo (ai_list);
836 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
837 else /* if (status == 0) */
839 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
840 address, host->node);
844 } /* }}} int mb_config_set_host_address */
846 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
852 if ((host == NULL) || (ci == NULL))
855 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
858 host->slaves = slave;
859 slave = host->slaves + host->slaves_num;
860 memset (slave, 0, sizeof (*slave));
861 slave->collect = NULL;
863 status = cf_util_get_int (ci, &slave->id);
867 for (i = 0; i < ci->children_num; i++)
869 oconfig_item_t *child = ci->children + i;
872 if (strcasecmp ("Instance", child->key) == 0)
873 status = cf_util_get_string_buffer (child,
874 slave->instance, sizeof (slave->instance));
875 else if (strcasecmp ("Collect", child->key) == 0)
878 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
880 data_copy_by_name (&slave->collect, data_definitions, buffer);
881 status = 0; /* continue after failure. */
883 else if (strcasecmp ("Datagroup", child->key) == 0)
888 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
890 ds = datagroup_get_by_name (data_groups, buffer);
893 for (data = ds->collect; data != NULL; data = data->next)
895 data_copy (&slave->collect, data);
899 status = 0; /* continue after failure. */
903 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
911 if ((status == 0) && (slave->collect == NULL))
919 else /* if (status != 0) */
920 data_free_all (slave->collect);
923 } /* }}} int mb_config_add_slave */
925 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
931 host = malloc (sizeof (*host));
934 memset (host, 0, sizeof (*host));
937 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
940 if (host->host[0] == 0)
943 for (i = 0; i < ci->children_num; i++)
945 oconfig_item_t *child = ci->children + i;
948 if (strcasecmp ("Address", child->key) == 0)
950 char buffer[NI_MAXHOST];
951 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
953 status = mb_config_set_host_address (host, buffer);
955 else if (strcasecmp ("Port", child->key) == 0)
957 host->port = cf_util_get_port_number (child);
961 else if (strcasecmp ("Interval", child->key) == 0)
962 status = cf_util_get_cdtime (child, &host->interval);
963 else if (strcasecmp ("Slave", child->key) == 0)
964 /* Don't set status: Gracefully continue if a slave fails. */
965 mb_config_add_slave (host, child);
968 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
974 } /* for (i = 0; i < ci->children_num; i++) */
976 assert (host->host[0] != 0);
977 if (host->host[0] == 0)
979 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
988 struct timespec interval = { 0, 0 };
991 ud.free_func = host_free;
993 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
995 CDTIME_T_TO_TIMESPEC (host->interval, &interval);
997 plugin_register_complex_read (/* group = */ NULL, name,
998 /* callback = */ mb_read,
999 /* interval = */ (host->interval > 0) ? &interval : NULL,
1008 } /* }}} int mb_config_add_host */
1011 static int mb_config_add_datagroup (oconfig_item_t *ci) /* {{{ */
1013 mb_datagroup_t datagroup;
1017 memset (&datagroup, 0, sizeof (datagroup));
1018 datagroup.name = NULL;
1019 datagroup.collect = NULL;
1020 datagroup.next = NULL;
1022 status = cf_util_get_string (ci, &datagroup.name);
1024 for (i = 0; i < ci->children_num; i++)
1026 oconfig_item_t *child = ci->children + i;
1029 if (strcasecmp ("Collect", child->key) == 0)
1032 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
1034 data_copy_by_name (&datagroup.collect, data_definitions, buffer);
1036 status = 0; /* continue after failure. */
1040 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1046 } /* for (i = 0; i < ci->children_num; i++) */
1048 if ((status == 0) && (datagroup.collect == NULL))
1052 datagroup_copy (&data_groups, &datagroup);
1055 } /* }}} int mb_config_add_datagroup */
1057 static int mb_config (oconfig_item_t *ci) /* {{{ */
1064 for (i = 0; i < ci->children_num; i++)
1066 oconfig_item_t *child = ci->children + i;
1068 if (strcasecmp ("Data", child->key) == 0)
1069 mb_config_add_data (child);
1070 else if (strcasecmp ("Host", child->key) == 0)
1071 mb_config_add_host (child);
1072 else if (strcasecmp ("Datagroup", child->key) == 0)
1073 mb_config_add_datagroup (child);
1075 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1079 } /* }}} int mb_config */
1083 static int mb_shutdown (void) /* {{{ */
1085 data_free_all (data_definitions);
1086 data_definitions = NULL;
1089 } /* }}} int mb_shutdown */
1091 void module_register (void)
1093 plugin_register_complex_config ("modbus", mb_config);
1094 plugin_register_shutdown ("modbus", mb_shutdown);
1095 } /* void module_register */
1097 /* vim: set sw=2 sts=2 et fdm=marker : */