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 */
280 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
281 mb_data_t *data, value_t value)
283 value_list_t vl = VALUE_LIST_INIT;
285 if ((host == NULL) || (slave == NULL) || (data == NULL))
288 if (host->interval <= 0)
289 host->interval = interval_g;
291 if (slave->instance[0] == 0)
292 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
297 vl.interval = host->interval;
298 sstrncpy (vl.host, host->host, sizeof (vl.host));
299 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
300 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
301 sstrncpy (vl.type, data->type, sizeof (vl.type));
302 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
304 return (plugin_dispatch_values (&vl));
305 } /* }}} int mb_submit */
307 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
315 #if BYTE_ORDER == LITTLE_ENDIAN
317 conv.b[0] = lo & 0x00ff;
318 conv.b[1] = (lo >> 8) & 0x00ff;
319 conv.b[2] = hi & 0x00ff;
320 conv.b[3] = (hi >> 8) & 0x00ff;
322 conv.b[3] = lo & 0x00ff;
323 conv.b[2] = (lo >> 8) & 0x00ff;
324 conv.b[1] = hi & 0x00ff;
325 conv.b[0] = (hi >> 8) & 0x00ff;
329 } /* }}} float mb_register_to_float */
333 static int mb_init_connection (mb_host_t *host) /* {{{ */
340 if (host->is_connected)
343 /* Only reconnect once per interval. */
344 if (host->have_reconnected)
347 modbus_set_debug (&host->connection, 1);
349 /* We'll do the error handling ourselves. */
350 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
352 if ((host->port < 1) || (host->port > 65535))
353 host->port = MODBUS_TCP_DEFAULT_PORT;
355 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
356 host->node, host->port);
358 modbus_init_tcp (&host->connection,
359 /* host = */ host->node,
360 /* port = */ host->port);
362 status = modbus_connect (&host->connection);
365 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
366 host->node, host->port, status);
370 host->is_connected = 1;
371 host->have_reconnected = 1;
373 } /* }}} int mb_init_connection */
374 /* #endif LEGACY_LIBMODBUS */
376 #else /* if !LEGACY_LIBMODBUS */
378 static int mb_init_connection (mb_host_t *host) /* {{{ */
385 if (host->connection != NULL)
388 /* Only reconnect once per interval. */
389 if (host->have_reconnected)
392 if ((host->port < 1) || (host->port > 65535))
393 host->port = MODBUS_TCP_DEFAULT_PORT;
395 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
396 host->node, host->port);
398 host->connection = modbus_new_tcp (host->node, host->port);
399 if (host->connection == NULL)
401 host->have_reconnected = 1;
402 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
406 modbus_set_debug (host->connection, 1);
408 /* We'll do the error handling ourselves. */
409 modbus_set_error_recovery (host->connection, 0);
411 status = modbus_connect (host->connection);
414 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
415 host->node, host->port, status);
416 modbus_free (host->connection);
417 host->connection = NULL;
421 host->have_reconnected = 1;
423 } /* }}} int mb_init_connection */
424 #endif /* !LEGACY_LIBMODBUS */
426 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
427 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
428 (vt).counter = (counter_t) (raw); \
429 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
430 (vt).gauge = (gauge_t) (raw); \
431 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
432 (vt).derive = (derive_t) (raw); \
433 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
434 (vt).absolute = (absolute_t) (raw); \
437 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
442 const data_set_t *ds;
446 if ((host == NULL) || (slave == NULL) || (data == NULL))
449 ds = plugin_get_ds (data->type);
452 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
458 ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
459 "I can only handle data sets with only one data source.",
460 data->type, ds->ds_num);
464 if ((ds->ds[0].type != DS_TYPE_GAUGE)
465 && (data->register_type != REG_TYPE_UINT32))
467 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
468 "This will most likely result in problems, because the register type "
469 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
472 memset (values, 0, sizeof (values));
473 if ((data->register_type == REG_TYPE_UINT32)
474 || (data->register_type == REG_TYPE_FLOAT))
480 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
481 * id to each call of "read_holding_registers". */
482 # define modbus_read_registers(ctx, addr, nb, dest) \
483 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
484 #else /* if !LEGACY_LIBMODBUS */
485 /* Version 2.9.2: Set the slave id once before querying the registers. */
486 status = modbus_set_slave (host->connection, slave->id);
489 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
495 for (i = 0; i < 2; i++)
497 status = modbus_read_registers (host->connection,
498 /* start_addr = */ data->register_base,
499 /* num_registers = */ values_num, /* buffer = */ values);
503 if (host->is_connected)
506 modbus_close (&host->connection);
507 host->is_connected = 0;
509 modbus_close (host->connection);
510 modbus_free (host->connection);
511 host->connection = NULL;
515 /* If we already tried reconnecting this round, give up. */
516 if (host->have_reconnected)
518 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
519 "Reconnecting has already been tried. Giving up.", host->host);
523 /* Maybe the device closed the connection during the waiting interval.
524 * Try re-establishing the connection. */
525 status = mb_init_connection (host);
528 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
529 "While trying to reconnect, connecting to \"%s\" failed. "
531 host->host, host->node);
535 DEBUG ("Modbus plugin: Re-established connection to %s", host->host);
539 } /* for (i = 0, 1) */
541 DEBUG ("Modbus plugin: mb_read_data: Success! "
542 "modbus_read_registers returned with status %i.", status);
544 if (data->register_type == REG_TYPE_FLOAT)
549 float_value = mb_register_to_float (values[0], values[1]);
550 DEBUG ("Modbus plugin: mb_read_data: "
551 "Returned float value is %g", (double) float_value);
553 CAST_TO_VALUE_T (ds, vt, float_value);
554 mb_submit (host, slave, data, vt);
556 else if (data->register_type == REG_TYPE_UINT32)
561 v32 = (values[0] << 16) | values[1];
562 DEBUG ("Modbus plugin: mb_read_data: "
563 "Returned uint32 value is %"PRIu32, v32);
565 CAST_TO_VALUE_T (ds, vt, v32);
566 mb_submit (host, slave, data, vt);
568 else /* if (data->register_type == REG_TYPE_UINT16) */
572 DEBUG ("Modbus plugin: mb_read_data: "
573 "Returned uint16 value is %"PRIu16, values[0]);
575 CAST_TO_VALUE_T (ds, vt, values[0]);
576 mb_submit (host, slave, data, vt);
580 } /* }}} int mb_read_data */
582 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
588 if ((host == NULL) || (slave == NULL))
592 for (data = slave->collect; data != NULL; data = data->next)
594 status = mb_read_data (host, slave, data);
603 } /* }}} int mb_read_slave */
605 static int mb_read (user_data_t *user_data) /* {{{ */
612 if ((user_data == NULL) || (user_data->data == NULL))
615 host = user_data->data;
617 /* Clear the reconnect flag. */
618 host->have_reconnected = 0;
621 for (i = 0; i < host->slaves_num; i++)
623 status = mb_read_slave (host, host->slaves + i);
632 } /* }}} int mb_read */
636 static void data_free_one (mb_data_t *data) /* {{{ */
643 } /* }}} void data_free_one */
645 static void data_free_all (mb_data_t *data) /* {{{ */
653 data_free_one (data);
655 data_free_all (next);
656 } /* }}} void data_free_all */
658 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
665 for (i = 0; i < slaves_num; i++)
666 data_free_all (slaves[i].collect);
668 } /* }}} void slaves_free_all */
670 static void host_free (void *void_host) /* {{{ */
672 mb_host_t *host = void_host;
677 slaves_free_all (host->slaves, host->slaves_num);
679 } /* }}} void host_free */
681 /* Config functions */
683 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
689 memset (&data, 0, sizeof (data));
691 data.register_type = REG_TYPE_UINT16;
694 status = cf_util_get_string (ci, &data.name);
698 for (i = 0; i < ci->children_num; i++)
700 oconfig_item_t *child = ci->children + i;
703 if (strcasecmp ("Type", child->key) == 0)
704 status = cf_util_get_string_buffer (child,
705 data.type, sizeof (data.type));
706 else if (strcasecmp ("Instance", child->key) == 0)
707 status = cf_util_get_string_buffer (child,
708 data.instance, sizeof (data.instance));
709 else if (strcasecmp ("RegisterBase", child->key) == 0)
710 status = cf_util_get_int (child, &data.register_base);
711 else if (strcasecmp ("RegisterType", child->key) == 0)
714 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
717 else if (strcasecmp ("Uint16", tmp) == 0)
718 data.register_type = REG_TYPE_UINT16;
719 else if (strcasecmp ("Uint32", tmp) == 0)
720 data.register_type = REG_TYPE_UINT32;
721 else if (strcasecmp ("Float", tmp) == 0)
722 data.register_type = REG_TYPE_FLOAT;
725 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
731 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
737 } /* for (i = 0; i < ci->children_num; i++) */
739 assert (data.name != NULL);
740 if (data.type[0] == 0)
742 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
748 data_copy (&data_definitions, &data);
753 } /* }}} int mb_config_add_data */
755 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
758 struct addrinfo *ai_list;
759 struct addrinfo *ai_ptr;
760 struct addrinfo ai_hints;
763 if ((host == NULL) || (address == NULL))
766 memset (&ai_hints, 0, sizeof (ai_hints));
768 ai_hints.ai_flags |= AI_ADDRCONFIG;
770 /* XXX: libmodbus can only handle IPv4 addresses. */
771 ai_hints.ai_family = AF_INET;
772 ai_hints.ai_addr = NULL;
773 ai_hints.ai_canonname = NULL;
774 ai_hints.ai_next = NULL;
777 status = getaddrinfo (address, /* service = */ NULL,
778 &ai_hints, &ai_list);
782 ERROR ("Modbus plugin: getaddrinfo failed: %s",
783 (status == EAI_SYSTEM)
784 ? sstrerror (errno, errbuf, sizeof (errbuf))
785 : gai_strerror (status));
789 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
791 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
792 host->node, sizeof (host->node),
793 /* service = */ NULL, /* length = */ 0,
794 /* flags = */ NI_NUMERICHOST);
799 freeaddrinfo (ai_list);
802 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
803 else /* if (status == 0) */
805 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
806 address, host->node);
810 } /* }}} int mb_config_set_host_address */
812 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
818 if ((host == NULL) || (ci == NULL))
821 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
824 host->slaves = slave;
825 slave = host->slaves + host->slaves_num;
826 memset (slave, 0, sizeof (*slave));
827 slave->collect = NULL;
829 status = cf_util_get_int (ci, &slave->id);
833 for (i = 0; i < ci->children_num; i++)
835 oconfig_item_t *child = ci->children + i;
838 if (strcasecmp ("Instance", child->key) == 0)
839 status = cf_util_get_string_buffer (child,
840 slave->instance, sizeof (slave->instance));
841 else if (strcasecmp ("Collect", child->key) == 0)
844 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
846 data_copy_by_name (&slave->collect, data_definitions, buffer);
847 status = 0; /* continue after failure. */
849 else if (strcasecmp ("Datagroup", child->key) == 0)
854 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
856 ds = datagroup_get_by_name (data_groups, buffer);
859 for (data = ds->collect; data != NULL; data = data->next)
861 data_copy (&slave->collect, data);
865 status = 0; /* continue after failure. */
869 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
877 if ((status == 0) && (slave->collect == NULL))
885 else /* if (status != 0) */
886 data_free_all (slave->collect);
889 } /* }}} int mb_config_add_slave */
891 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
897 host = malloc (sizeof (*host));
900 memset (host, 0, sizeof (*host));
903 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
906 if (host->host[0] == 0)
909 for (i = 0; i < ci->children_num; i++)
911 oconfig_item_t *child = ci->children + i;
914 if (strcasecmp ("Address", child->key) == 0)
916 char buffer[NI_MAXHOST];
917 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
919 status = mb_config_set_host_address (host, buffer);
921 else if (strcasecmp ("Port", child->key) == 0)
923 host->port = cf_util_get_port_number (child);
927 else if (strcasecmp ("Interval", child->key) == 0)
928 status = cf_util_get_cdtime (child, &host->interval);
929 else if (strcasecmp ("Slave", child->key) == 0)
930 /* Don't set status: Gracefully continue if a slave fails. */
931 mb_config_add_slave (host, child);
934 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
940 } /* for (i = 0; i < ci->children_num; i++) */
942 assert (host->host[0] != 0);
943 if (host->host[0] == 0)
945 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
954 struct timespec interval = { 0, 0 };
957 ud.free_func = host_free;
959 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
961 CDTIME_T_TO_TIMESPEC (host->interval, &interval);
963 plugin_register_complex_read (/* group = */ NULL, name,
964 /* callback = */ mb_read,
965 /* interval = */ (host->interval > 0) ? &interval : NULL,
974 } /* }}} int mb_config_add_host */
977 static int mb_config_add_datagroup (oconfig_item_t *ci) /* {{{ */
979 mb_datagroup_t *datagroup;
983 datagroup = malloc (sizeof (*datagroup));
984 if (datagroup == NULL)
986 memset (datagroup, 0, sizeof (*datagroup));
987 datagroup->name = NULL;
988 datagroup->collect = NULL;
989 datagroup->next = NULL;
991 status = cf_util_get_string (ci, &datagroup->name);
993 for (i = 0; i < ci->children_num; i++)
995 oconfig_item_t *child = ci->children + i;
998 if (strcasecmp ("Collect", child->key) == 0)
1001 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
1003 data_copy_by_name (&datagroup->collect, data_definitions, buffer);
1005 status = 0; /* continue after failure. */
1009 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1015 } /* for (i = 0; i < ci->children_num; i++) */
1017 if ((status == 0) && (datagroup->collect == NULL))
1022 datagroup_append (&data_groups, datagroup);
1024 else /* if (status != 0) */
1026 sfree (datagroup->name);
1027 data_free_all (datagroup->collect);
1028 assert (datagroup->next == NULL);
1033 } /* }}} int mb_config_add_datagroup */
1035 static int mb_config (oconfig_item_t *ci) /* {{{ */
1042 for (i = 0; i < ci->children_num; i++)
1044 oconfig_item_t *child = ci->children + i;
1046 if (strcasecmp ("Data", child->key) == 0)
1047 mb_config_add_data (child);
1048 else if (strcasecmp ("Host", child->key) == 0)
1049 mb_config_add_host (child);
1050 else if (strcasecmp ("Datagroup", child->key) == 0)
1051 mb_config_add_datagroup (child);
1053 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1057 } /* }}} int mb_config */
1061 static int mb_shutdown (void) /* {{{ */
1063 data_free_all (data_definitions);
1064 data_definitions = NULL;
1067 } /* }}} int mb_shutdown */
1069 void module_register (void)
1071 plugin_register_complex_config ("modbus", mb_config);
1072 plugin_register_shutdown ("modbus", mb_shutdown);
1073 } /* void module_register */
1075 /* vim: set sw=2 sts=2 et fdm=marker : */