2 * collectd - src/modbus.c
3 * Copyright (C) 2010 noris network AG
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
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.
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
20 * Florian Forster <octo at noris.net>
26 #include "configfile.h"
30 #include <modbus/modbus.h>
32 #ifndef LIBMODBUS_VERSION_CHECK
33 /* Assume version 2.0.3 */
34 # define LEGACY_LIBMODBUS 1
36 /* Assume version 2.9.2 */
39 #ifndef MODBUS_TCP_DEFAULT_PORT
40 # ifdef MODBUS_TCP_PORT
41 # define MODBUS_TCP_DEFAULT_PORT MODBUS_TCP_PORT
43 # define MODBUS_TCP_DEFAULT_PORT 502
61 * Instance "foobar" # optional
70 enum mb_register_type_e /* {{{ */
76 typedef enum mb_register_type_e mb_register_type_t;
79 typedef struct mb_data_s mb_data_t;
80 struct mb_data_s /* {{{ */
84 mb_register_type_t register_type;
85 char type[DATA_MAX_NAME_LEN];
86 char instance[DATA_MAX_NAME_LEN];
92 typedef struct mb_dataset_s mb_dataset_t;
93 struct mb_dataset_s /* {{{ */
101 struct mb_slave_s /* {{{ */
104 char instance[DATA_MAX_NAME_LEN];
107 typedef struct mb_slave_s mb_slave_t;
109 struct mb_host_s /* {{{ */
111 char host[DATA_MAX_NAME_LEN];
112 char node[NI_MAXHOST];
113 /* char service[NI_MAXSERV]; */
121 modbus_param_t connection;
123 modbus_t *connection;
126 _Bool have_reconnected;
128 typedef struct mb_host_s mb_host_t;
130 struct mb_data_group_s;
131 typedef struct mb_data_group_s mb_data_group_t;
132 struct mb_data_group_s /* {{{ */
134 mb_data_t *registers;
135 size_t registers_num;
137 mb_data_group_t *next;
143 static mb_data_t *data_definitions = NULL;
144 static mb_dataset_t *data_sets = NULL;
149 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
157 for (ptr = src; ptr != NULL; ptr = ptr->next)
158 if (strcasecmp (ptr->name, name) == 0)
162 } /* }}} mb_data_t *data_get_by_name */
164 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
168 if ((dst == NULL) || (src == NULL))
179 while (ptr->next != NULL)
185 } /* }}} int data_append */
187 /* Copy a single mb_data_t and append it to another list. */
188 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
193 if ((dst == NULL) || (src == NULL))
196 tmp = malloc (sizeof (*tmp));
199 memcpy (tmp, src, sizeof (*tmp));
203 tmp->name = strdup (src->name);
204 if (tmp->name == NULL)
210 status = data_append (dst, tmp);
219 } /* }}} int data_copy */
221 /* Lookup a single mb_data_t instance, copy it and append the copy to another
223 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
228 if ((dst == NULL) || (src == NULL) || (name == NULL))
231 ptr = data_get_by_name (src, name);
235 return (data_copy (dst, ptr));
236 } /* }}} int data_copy_by_name */
238 static mb_dataset_t *dataset_get_by_name (mb_dataset_t *src, /* {{{ */
246 for (ptr = src; ptr != NULL; ptr = ptr->next)
247 if (strcasecmp (ptr->name, name) == 0)
251 } /* }}} mb_dataset_t *dataset_get_by_name */
253 static int dataset_append (mb_dataset_t **dst, mb_dataset_t *src) /* {{{ */
257 if ((dst == NULL) || (src == NULL))
268 while (ptr->next != NULL)
274 } /* }}} int dataset_append */
276 /* Copy a single mb_dataset_t and append it to another list. */
277 static int dataset_copy (mb_dataset_t **dst, const mb_dataset_t *src) /* {{{ */
282 if ((dst == NULL) || (src == NULL))
285 tmp = malloc (sizeof (*tmp));
288 memcpy (tmp, src, sizeof (*tmp));
292 tmp->name = strdup (src->name);
293 if (tmp->name == NULL)
299 status = dataset_append (dst, tmp);
308 } /* }}} int dataset_copy */
312 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
313 mb_data_t *data, value_t value)
315 value_list_t vl = VALUE_LIST_INIT;
317 if ((host == NULL) || (slave == NULL) || (data == NULL))
320 if (host->interval <= 0)
321 host->interval = interval_g;
323 if (slave->instance[0] == 0)
324 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
329 vl.interval = host->interval;
330 sstrncpy (vl.host, host->host, sizeof (vl.host));
331 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
332 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
333 sstrncpy (vl.type, data->type, sizeof (vl.type));
334 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
336 return (plugin_dispatch_values (&vl));
337 } /* }}} int mb_submit */
339 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
347 #if BYTE_ORDER == LITTLE_ENDIAN
349 conv.b[0] = lo & 0x00ff;
350 conv.b[1] = (lo >> 8) & 0x00ff;
351 conv.b[2] = hi & 0x00ff;
352 conv.b[3] = (hi >> 8) & 0x00ff;
354 conv.b[3] = lo & 0x00ff;
355 conv.b[2] = (lo >> 8) & 0x00ff;
356 conv.b[1] = hi & 0x00ff;
357 conv.b[0] = (hi >> 8) & 0x00ff;
361 } /* }}} float mb_register_to_float */
365 static int mb_init_connection (mb_host_t *host) /* {{{ */
372 if (host->is_connected)
375 /* Only reconnect once per interval. */
376 if (host->have_reconnected)
379 modbus_set_debug (&host->connection, 1);
381 /* We'll do the error handling ourselves. */
382 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
384 if ((host->port < 1) || (host->port > 65535))
385 host->port = MODBUS_TCP_DEFAULT_PORT;
387 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
388 host->node, host->port);
390 modbus_init_tcp (&host->connection,
391 /* host = */ host->node,
392 /* port = */ host->port);
394 status = modbus_connect (&host->connection);
397 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
398 host->node, host->port, status);
402 host->is_connected = 1;
403 host->have_reconnected = 1;
405 } /* }}} int mb_init_connection */
406 /* #endif LEGACY_LIBMODBUS */
408 #else /* if !LEGACY_LIBMODBUS */
410 static int mb_init_connection (mb_host_t *host) /* {{{ */
417 if (host->connection != NULL)
420 /* Only reconnect once per interval. */
421 if (host->have_reconnected)
424 if ((host->port < 1) || (host->port > 65535))
425 host->port = MODBUS_TCP_DEFAULT_PORT;
427 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
428 host->node, host->port);
430 host->connection = modbus_new_tcp (host->node, host->port);
431 if (host->connection == NULL)
433 host->have_reconnected = 1;
434 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
438 modbus_set_debug (host->connection, 1);
440 /* We'll do the error handling ourselves. */
441 modbus_set_error_recovery (host->connection, 0);
443 status = modbus_connect (host->connection);
446 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
447 host->node, host->port, status);
448 modbus_free (host->connection);
449 host->connection = NULL;
453 host->have_reconnected = 1;
455 } /* }}} int mb_init_connection */
456 #endif /* !LEGACY_LIBMODBUS */
458 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
459 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
460 (vt).counter = (counter_t) (raw); \
461 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
462 (vt).gauge = (gauge_t) (raw); \
463 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
464 (vt).derive = (derive_t) (raw); \
465 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
466 (vt).absolute = (absolute_t) (raw); \
469 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
474 const data_set_t *ds;
478 if ((host == NULL) || (slave == NULL) || (data == NULL))
481 ds = plugin_get_ds (data->type);
484 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
490 ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
491 "I can only handle data sets with only one data source.",
492 data->type, ds->ds_num);
496 if ((ds->ds[0].type != DS_TYPE_GAUGE)
497 && (data->register_type != REG_TYPE_UINT32))
499 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
500 "This will most likely result in problems, because the register type "
501 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
504 memset (values, 0, sizeof (values));
505 if ((data->register_type == REG_TYPE_UINT32)
506 || (data->register_type == REG_TYPE_FLOAT))
512 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
513 * id to each call of "read_holding_registers". */
514 # define modbus_read_registers(ctx, addr, nb, dest) \
515 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
516 #else /* if !LEGACY_LIBMODBUS */
517 /* Version 2.9.2: Set the slave id once before querying the registers. */
518 status = modbus_set_slave (host->connection, slave->id);
521 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
527 for (i = 0; i < 2; i++)
529 status = modbus_read_registers (host->connection,
530 /* start_addr = */ data->register_base,
531 /* num_registers = */ values_num, /* buffer = */ values);
535 if (host->is_connected)
538 modbus_close (&host->connection);
539 host->is_connected = 0;
541 modbus_close (host->connection);
542 modbus_free (host->connection);
543 host->connection = NULL;
547 /* If we already tried reconnecting this round, give up. */
548 if (host->have_reconnected)
550 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
551 "Reconnecting has already been tried. Giving up.", host->host);
555 /* Maybe the device closed the connection during the waiting interval.
556 * Try re-establishing the connection. */
557 status = mb_init_connection (host);
560 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
561 "While trying to reconnect, connecting to \"%s\" failed. "
563 host->host, host->node);
567 DEBUG ("Modbus plugin: Re-established connection to %s", host->host);
571 } /* for (i = 0, 1) */
573 DEBUG ("Modbus plugin: mb_read_data: Success! "
574 "modbus_read_registers returned with status %i.", status);
576 if (data->register_type == REG_TYPE_FLOAT)
581 float_value = mb_register_to_float (values[0], values[1]);
582 DEBUG ("Modbus plugin: mb_read_data: "
583 "Returned float value is %g", (double) float_value);
585 CAST_TO_VALUE_T (ds, vt, float_value);
586 mb_submit (host, slave, data, vt);
588 else if (data->register_type == REG_TYPE_UINT32)
593 v32 = (values[0] << 16) | values[1];
594 DEBUG ("Modbus plugin: mb_read_data: "
595 "Returned uint32 value is %"PRIu32, v32);
597 CAST_TO_VALUE_T (ds, vt, v32);
598 mb_submit (host, slave, data, vt);
600 else /* if (data->register_type == REG_TYPE_UINT16) */
604 DEBUG ("Modbus plugin: mb_read_data: "
605 "Returned uint16 value is %"PRIu16, values[0]);
607 CAST_TO_VALUE_T (ds, vt, values[0]);
608 mb_submit (host, slave, data, vt);
612 } /* }}} int mb_read_data */
614 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
620 if ((host == NULL) || (slave == NULL))
624 for (data = slave->collect; data != NULL; data = data->next)
626 status = mb_read_data (host, slave, data);
635 } /* }}} int mb_read_slave */
637 static int mb_read (user_data_t *user_data) /* {{{ */
644 if ((user_data == NULL) || (user_data->data == NULL))
647 host = user_data->data;
649 /* Clear the reconnect flag. */
650 host->have_reconnected = 0;
653 for (i = 0; i < host->slaves_num; i++)
655 status = mb_read_slave (host, host->slaves + i);
664 } /* }}} int mb_read */
668 static void data_free_one (mb_data_t *data) /* {{{ */
675 } /* }}} void data_free_one */
677 static void data_free_all (mb_data_t *data) /* {{{ */
685 data_free_one (data);
687 data_free_all (next);
688 } /* }}} void data_free_all */
690 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
697 for (i = 0; i < slaves_num; i++)
698 data_free_all (slaves[i].collect);
700 } /* }}} void slaves_free_all */
702 static void host_free (void *void_host) /* {{{ */
704 mb_host_t *host = void_host;
709 slaves_free_all (host->slaves, host->slaves_num);
711 } /* }}} void host_free */
713 /* Config functions */
715 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
721 memset (&data, 0, sizeof (data));
723 data.register_type = REG_TYPE_UINT16;
726 status = cf_util_get_string (ci, &data.name);
730 for (i = 0; i < ci->children_num; i++)
732 oconfig_item_t *child = ci->children + i;
735 if (strcasecmp ("Type", child->key) == 0)
736 status = cf_util_get_string_buffer (child,
737 data.type, sizeof (data.type));
738 else if (strcasecmp ("Instance", child->key) == 0)
739 status = cf_util_get_string_buffer (child,
740 data.instance, sizeof (data.instance));
741 else if (strcasecmp ("RegisterBase", child->key) == 0)
742 status = cf_util_get_int (child, &data.register_base);
743 else if (strcasecmp ("RegisterType", child->key) == 0)
746 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
749 else if (strcasecmp ("Uint16", tmp) == 0)
750 data.register_type = REG_TYPE_UINT16;
751 else if (strcasecmp ("Uint32", tmp) == 0)
752 data.register_type = REG_TYPE_UINT32;
753 else if (strcasecmp ("Float", tmp) == 0)
754 data.register_type = REG_TYPE_FLOAT;
757 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
763 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
769 } /* for (i = 0; i < ci->children_num; i++) */
771 assert (data.name != NULL);
772 if (data.type[0] == 0)
774 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
780 data_copy (&data_definitions, &data);
785 } /* }}} int mb_config_add_data */
787 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
790 struct addrinfo *ai_list;
791 struct addrinfo *ai_ptr;
792 struct addrinfo ai_hints;
795 if ((host == NULL) || (address == NULL))
798 memset (&ai_hints, 0, sizeof (ai_hints));
800 ai_hints.ai_flags |= AI_ADDRCONFIG;
802 /* XXX: libmodbus can only handle IPv4 addresses. */
803 ai_hints.ai_family = AF_INET;
804 ai_hints.ai_addr = NULL;
805 ai_hints.ai_canonname = NULL;
806 ai_hints.ai_next = NULL;
809 status = getaddrinfo (address, /* service = */ NULL,
810 &ai_hints, &ai_list);
814 ERROR ("Modbus plugin: getaddrinfo failed: %s",
815 (status == EAI_SYSTEM)
816 ? sstrerror (errno, errbuf, sizeof (errbuf))
817 : gai_strerror (status));
821 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
823 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
824 host->node, sizeof (host->node),
825 /* service = */ NULL, /* length = */ 0,
826 /* flags = */ NI_NUMERICHOST);
831 freeaddrinfo (ai_list);
834 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
835 else /* if (status == 0) */
837 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
838 address, host->node);
842 } /* }}} int mb_config_set_host_address */
844 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
850 if ((host == NULL) || (ci == NULL))
853 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
856 host->slaves = slave;
857 slave = host->slaves + host->slaves_num;
858 memset (slave, 0, sizeof (*slave));
859 slave->collect = NULL;
861 status = cf_util_get_int (ci, &slave->id);
865 for (i = 0; i < ci->children_num; i++)
867 oconfig_item_t *child = ci->children + i;
870 if (strcasecmp ("Instance", child->key) == 0)
871 status = cf_util_get_string_buffer (child,
872 slave->instance, sizeof (slave->instance));
873 else if (strcasecmp ("Collect", child->key) == 0)
876 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
878 data_copy_by_name (&slave->collect, data_definitions, buffer);
879 status = 0; /* continue after failure. */
881 else if (strcasecmp ("Dataset", child->key) == 0)
886 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
888 ds = dataset_get_by_name (data_sets, buffer);
891 for (data = ds->collect; data != NULL; data = data->next)
893 data_copy (&slave->collect, data);
897 status = 0; /* continue after failure. */
901 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
909 if ((status == 0) && (slave->collect == NULL))
917 else /* if (status != 0) */
918 data_free_all (slave->collect);
921 } /* }}} int mb_config_add_slave */
923 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
929 host = malloc (sizeof (*host));
932 memset (host, 0, sizeof (*host));
935 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
938 if (host->host[0] == 0)
941 for (i = 0; i < ci->children_num; i++)
943 oconfig_item_t *child = ci->children + i;
946 if (strcasecmp ("Address", child->key) == 0)
948 char buffer[NI_MAXHOST];
949 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
951 status = mb_config_set_host_address (host, buffer);
953 else if (strcasecmp ("Port", child->key) == 0)
955 host->port = cf_util_get_port_number (child);
959 else if (strcasecmp ("Interval", child->key) == 0)
960 status = cf_util_get_cdtime (child, &host->interval);
961 else if (strcasecmp ("Slave", child->key) == 0)
962 /* Don't set status: Gracefully continue if a slave fails. */
963 mb_config_add_slave (host, child);
966 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
972 } /* for (i = 0; i < ci->children_num; i++) */
974 assert (host->host[0] != 0);
975 if (host->host[0] == 0)
977 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
986 struct timespec interval = { 0, 0 };
989 ud.free_func = host_free;
991 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
993 CDTIME_T_TO_TIMESPEC (host->interval, &interval);
995 plugin_register_complex_read (/* group = */ NULL, name,
996 /* callback = */ mb_read,
997 /* interval = */ (host->interval > 0) ? &interval : NULL,
1006 } /* }}} int mb_config_add_host */
1009 static int mb_config_add_dataset (oconfig_item_t *ci) /* {{{ */
1011 mb_dataset_t dataset;
1015 memset (&dataset, 0, sizeof (dataset));
1016 dataset.name = NULL;
1017 dataset.collect = NULL;
1018 dataset.next = NULL;
1020 status = cf_util_get_string (ci, &dataset.name);
1022 for (i = 0; i < ci->children_num; i++)
1024 oconfig_item_t *child = ci->children + i;
1027 if (strcasecmp ("Collect", child->key) == 0)
1030 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
1032 data_copy_by_name (&dataset.collect, data_definitions, buffer);
1034 status = 0; /* continue after failure. */
1038 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1044 } /* for (i = 0; i < ci->children_num; i++) */
1046 if ((status == 0) && (dataset.collect == NULL))
1050 dataset_copy (&data_sets, &dataset);
1053 } /* }}} int mb_config_add_dataset */
1055 static int mb_config (oconfig_item_t *ci) /* {{{ */
1062 for (i = 0; i < ci->children_num; i++)
1064 oconfig_item_t *child = ci->children + i;
1066 if (strcasecmp ("Data", child->key) == 0)
1067 mb_config_add_data (child);
1068 else if (strcasecmp ("Host", child->key) == 0)
1069 mb_config_add_host (child);
1070 else if (strcasecmp ("Dataset", child->key) == 0)
1071 mb_config_add_dataset (child);
1073 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1077 } /* }}} int mb_config */
1081 static int mb_shutdown (void) /* {{{ */
1083 data_free_all (data_definitions);
1084 data_definitions = NULL;
1087 } /* }}} int mb_shutdown */
1089 void module_register (void)
1091 plugin_register_complex_config ("modbus", mb_config);
1092 plugin_register_shutdown ("modbus", mb_shutdown);
1093 } /* void module_register */
1095 /* vim: set sw=2 sts=2 et fdm=marker : */