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];
91 struct mb_slave_s /* {{{ */
94 char instance[DATA_MAX_NAME_LEN];
97 typedef struct mb_slave_s mb_slave_t;
99 struct mb_host_s /* {{{ */
101 char host[DATA_MAX_NAME_LEN];
102 char node[NI_MAXHOST];
103 /* char service[NI_MAXSERV]; */
111 modbus_param_t connection;
113 modbus_t *connection;
116 _Bool have_reconnected;
118 typedef struct mb_host_s mb_host_t;
120 struct mb_data_group_s;
121 typedef struct mb_data_group_s mb_data_group_t;
122 struct mb_data_group_s /* {{{ */
124 mb_data_t *registers;
125 size_t registers_num;
127 mb_data_group_t *next;
133 static mb_data_t *data_definitions = NULL;
138 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
146 for (ptr = src; ptr != NULL; ptr = ptr->next)
147 if (strcasecmp (ptr->name, name) == 0)
151 } /* }}} mb_data_t *data_get_by_name */
153 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
157 if ((dst == NULL) || (src == NULL))
168 while (ptr->next != NULL)
174 } /* }}} int data_append */
176 /* Copy a single mb_data_t and append it to another list. */
177 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
182 if ((dst == NULL) || (src == NULL))
185 tmp = malloc (sizeof (*tmp));
188 memcpy (tmp, src, sizeof (*tmp));
192 tmp->name = strdup (src->name);
193 if (tmp->name == NULL)
199 status = data_append (dst, tmp);
208 } /* }}} int data_copy */
210 /* Lookup a single mb_data_t instance, copy it and append the copy to another
212 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
217 if ((dst == NULL) || (src == NULL) || (name == NULL))
220 ptr = data_get_by_name (src, name);
224 return (data_copy (dst, ptr));
225 } /* }}} int data_copy_by_name */
229 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
230 mb_data_t *data, value_t value)
232 value_list_t vl = VALUE_LIST_INIT;
234 if ((host == NULL) || (slave == NULL) || (data == NULL))
237 if (host->interval <= 0)
238 host->interval = interval_g;
240 if (slave->instance[0] == 0)
241 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
246 vl.interval = host->interval;
247 sstrncpy (vl.host, host->host, sizeof (vl.host));
248 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
249 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
250 sstrncpy (vl.type, data->type, sizeof (vl.type));
251 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
253 return (plugin_dispatch_values (&vl));
254 } /* }}} int mb_submit */
256 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
264 #if BYTE_ORDER == LITTLE_ENDIAN
266 conv.b[0] = lo & 0x00ff;
267 conv.b[1] = (lo >> 8) & 0x00ff;
268 conv.b[2] = hi & 0x00ff;
269 conv.b[3] = (hi >> 8) & 0x00ff;
271 conv.b[3] = lo & 0x00ff;
272 conv.b[2] = (lo >> 8) & 0x00ff;
273 conv.b[1] = hi & 0x00ff;
274 conv.b[0] = (hi >> 8) & 0x00ff;
278 } /* }}} float mb_register_to_float */
282 static int mb_init_connection (mb_host_t *host) /* {{{ */
289 if (host->is_connected)
292 /* Only reconnect once per interval. */
293 if (host->have_reconnected)
296 modbus_set_debug (&host->connection, 1);
298 /* We'll do the error handling ourselves. */
299 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
301 if ((host->port < 1) || (host->port > 65535))
302 host->port = MODBUS_TCP_DEFAULT_PORT;
304 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
305 host->node, host->port);
307 modbus_init_tcp (&host->connection,
308 /* host = */ host->node,
309 /* port = */ host->port);
311 status = modbus_connect (&host->connection);
314 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
315 host->node, host->port, status);
319 host->is_connected = 1;
320 host->have_reconnected = 1;
322 } /* }}} int mb_init_connection */
323 /* #endif LEGACY_LIBMODBUS */
325 #else /* if !LEGACY_LIBMODBUS */
327 static int mb_init_connection (mb_host_t *host) /* {{{ */
334 if (host->connection != NULL)
337 /* Only reconnect once per interval. */
338 if (host->have_reconnected)
341 if ((host->port < 1) || (host->port > 65535))
342 host->port = MODBUS_TCP_DEFAULT_PORT;
344 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
345 host->node, host->port);
347 host->connection = modbus_new_tcp (host->node, host->port);
348 if (host->connection == NULL)
350 host->have_reconnected = 1;
351 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
355 modbus_set_debug (host->connection, 1);
357 /* We'll do the error handling ourselves. */
358 modbus_set_error_recovery (host->connection, 0);
360 status = modbus_connect (host->connection);
363 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
364 host->node, host->port, status);
365 modbus_free (host->connection);
366 host->connection = NULL;
370 host->have_reconnected = 1;
372 } /* }}} int mb_init_connection */
373 #endif /* !LEGACY_LIBMODBUS */
375 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
376 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
377 (vt).counter = (counter_t) (raw); \
378 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
379 (vt).gauge = (gauge_t) (raw); \
380 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
381 (vt).derive = (derive_t) (raw); \
382 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
383 (vt).absolute = (absolute_t) (raw); \
386 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
391 const data_set_t *ds;
395 if ((host == NULL) || (slave == NULL) || (data == NULL))
398 ds = plugin_get_ds (data->type);
401 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
407 ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
408 "I can only handle data sets with only one data source.",
409 data->type, ds->ds_num);
413 if ((ds->ds[0].type != DS_TYPE_GAUGE)
414 && (data->register_type != REG_TYPE_UINT32))
416 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
417 "This will most likely result in problems, because the register type "
418 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
421 memset (values, 0, sizeof (values));
422 if ((data->register_type == REG_TYPE_UINT32)
423 || (data->register_type == REG_TYPE_FLOAT))
429 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
430 * id to each call of "read_holding_registers". */
431 # define modbus_read_registers(ctx, addr, nb, dest) \
432 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
433 #else /* if !LEGACY_LIBMODBUS */
434 /* Version 2.9.2: Set the slave id once before querying the registers. */
435 status = modbus_set_slave (host->connection, slave->id);
438 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
444 for (i = 0; i < 2; i++)
446 status = modbus_read_registers (host->connection,
447 /* start_addr = */ data->register_base,
448 /* num_registers = */ values_num, /* buffer = */ values);
452 if (host->is_connected)
455 modbus_close (&host->connection);
456 host->is_connected = 0;
458 modbus_close (host->connection);
459 modbus_free (host->connection);
460 host->connection = NULL;
464 /* If we already tried reconnecting this round, give up. */
465 if (host->have_reconnected)
467 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
468 "Reconnecting has already been tried. Giving up.", host->host);
472 /* Maybe the device closed the connection during the waiting interval.
473 * Try re-establishing the connection. */
474 status = mb_init_connection (host);
477 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
478 "While trying to reconnect, connecting to \"%s\" failed. "
480 host->host, host->node);
484 DEBUG ("Modbus plugin: Re-established connection to %s", host->host);
488 } /* for (i = 0, 1) */
490 DEBUG ("Modbus plugin: mb_read_data: Success! "
491 "modbus_read_registers returned with status %i.", status);
493 if (data->register_type == REG_TYPE_FLOAT)
498 float_value = mb_register_to_float (values[0], values[1]);
499 DEBUG ("Modbus plugin: mb_read_data: "
500 "Returned float value is %g", (double) float_value);
502 CAST_TO_VALUE_T (ds, vt, float_value);
503 mb_submit (host, slave, data, vt);
505 else if (data->register_type == REG_TYPE_UINT32)
510 v32 = (values[0] << 16) | values[1];
511 DEBUG ("Modbus plugin: mb_read_data: "
512 "Returned uint32 value is %"PRIu32, v32);
514 CAST_TO_VALUE_T (ds, vt, v32);
515 mb_submit (host, slave, data, vt);
517 else /* if (data->register_type == REG_TYPE_UINT16) */
521 DEBUG ("Modbus plugin: mb_read_data: "
522 "Returned uint16 value is %"PRIu16, values[0]);
524 CAST_TO_VALUE_T (ds, vt, values[0]);
525 mb_submit (host, slave, data, vt);
529 } /* }}} int mb_read_data */
531 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
537 if ((host == NULL) || (slave == NULL))
541 for (data = slave->collect; data != NULL; data = data->next)
543 status = mb_read_data (host, slave, data);
552 } /* }}} int mb_read_slave */
554 static int mb_read (user_data_t *user_data) /* {{{ */
561 if ((user_data == NULL) || (user_data->data == NULL))
564 host = user_data->data;
566 /* Clear the reconnect flag. */
567 host->have_reconnected = 0;
570 for (i = 0; i < host->slaves_num; i++)
572 status = mb_read_slave (host, host->slaves + i);
581 } /* }}} int mb_read */
585 static void data_free_one (mb_data_t *data) /* {{{ */
592 } /* }}} void data_free_one */
594 static void data_free_all (mb_data_t *data) /* {{{ */
602 data_free_one (data);
604 data_free_all (next);
605 } /* }}} void data_free_all */
607 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
614 for (i = 0; i < slaves_num; i++)
615 data_free_all (slaves[i].collect);
617 } /* }}} void slaves_free_all */
619 static void host_free (void *void_host) /* {{{ */
621 mb_host_t *host = void_host;
626 slaves_free_all (host->slaves, host->slaves_num);
628 } /* }}} void host_free */
630 /* Config functions */
632 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
638 memset (&data, 0, sizeof (data));
640 data.register_type = REG_TYPE_UINT16;
643 status = cf_util_get_string (ci, &data.name);
647 for (i = 0; i < ci->children_num; i++)
649 oconfig_item_t *child = ci->children + i;
652 if (strcasecmp ("Type", child->key) == 0)
653 status = cf_util_get_string_buffer (child,
654 data.type, sizeof (data.type));
655 else if (strcasecmp ("Instance", child->key) == 0)
656 status = cf_util_get_string_buffer (child,
657 data.instance, sizeof (data.instance));
658 else if (strcasecmp ("RegisterBase", child->key) == 0)
659 status = cf_util_get_int (child, &data.register_base);
660 else if (strcasecmp ("RegisterType", child->key) == 0)
663 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
666 else if (strcasecmp ("Uint16", tmp) == 0)
667 data.register_type = REG_TYPE_UINT16;
668 else if (strcasecmp ("Uint32", tmp) == 0)
669 data.register_type = REG_TYPE_UINT32;
670 else if (strcasecmp ("Float", tmp) == 0)
671 data.register_type = REG_TYPE_FLOAT;
674 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
680 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
686 } /* for (i = 0; i < ci->children_num; i++) */
688 assert (data.name != NULL);
689 if (data.type[0] == 0)
691 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
697 data_copy (&data_definitions, &data);
702 } /* }}} int mb_config_add_data */
704 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
707 struct addrinfo *ai_list;
708 struct addrinfo *ai_ptr;
709 struct addrinfo ai_hints;
712 if ((host == NULL) || (address == NULL))
715 memset (&ai_hints, 0, sizeof (ai_hints));
717 ai_hints.ai_flags |= AI_ADDRCONFIG;
719 /* XXX: libmodbus can only handle IPv4 addresses. */
720 ai_hints.ai_family = AF_INET;
721 ai_hints.ai_addr = NULL;
722 ai_hints.ai_canonname = NULL;
723 ai_hints.ai_next = NULL;
726 status = getaddrinfo (address, /* service = */ NULL,
727 &ai_hints, &ai_list);
731 ERROR ("Modbus plugin: getaddrinfo failed: %s",
732 (status == EAI_SYSTEM)
733 ? sstrerror (errno, errbuf, sizeof (errbuf))
734 : gai_strerror (status));
738 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
740 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
741 host->node, sizeof (host->node),
742 /* service = */ NULL, /* length = */ 0,
743 /* flags = */ NI_NUMERICHOST);
748 freeaddrinfo (ai_list);
751 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
752 else /* if (status == 0) */
754 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
755 address, host->node);
759 } /* }}} int mb_config_set_host_address */
761 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
767 if ((host == NULL) || (ci == NULL))
770 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
773 host->slaves = slave;
774 slave = host->slaves + host->slaves_num;
775 memset (slave, 0, sizeof (*slave));
776 slave->collect = NULL;
778 status = cf_util_get_int (ci, &slave->id);
782 for (i = 0; i < ci->children_num; i++)
784 oconfig_item_t *child = ci->children + i;
787 if (strcasecmp ("Instance", child->key) == 0)
788 status = cf_util_get_string_buffer (child,
789 slave->instance, sizeof (slave->instance));
790 else if (strcasecmp ("Collect", child->key) == 0)
793 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
795 data_copy_by_name (&slave->collect, data_definitions, buffer);
796 status = 0; /* continue after failure. */
800 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
808 if ((status == 0) && (slave->collect == NULL))
816 else /* if (status != 0) */
817 data_free_all (slave->collect);
820 } /* }}} int mb_config_add_slave */
822 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
828 host = malloc (sizeof (*host));
831 memset (host, 0, sizeof (*host));
834 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
837 if (host->host[0] == 0)
840 for (i = 0; i < ci->children_num; i++)
842 oconfig_item_t *child = ci->children + i;
845 if (strcasecmp ("Address", child->key) == 0)
847 char buffer[NI_MAXHOST];
848 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
850 status = mb_config_set_host_address (host, buffer);
852 else if (strcasecmp ("Port", child->key) == 0)
854 host->port = cf_util_get_port_number (child);
858 else if (strcasecmp ("Interval", child->key) == 0)
859 status = cf_util_get_cdtime (child, &host->interval);
860 else if (strcasecmp ("Slave", child->key) == 0)
861 /* Don't set status: Gracefully continue if a slave fails. */
862 mb_config_add_slave (host, child);
865 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
871 } /* for (i = 0; i < ci->children_num; i++) */
873 assert (host->host[0] != 0);
874 if (host->host[0] == 0)
876 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
885 struct timespec interval = { 0, 0 };
888 ud.free_func = host_free;
890 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
892 CDTIME_T_TO_TIMESPEC (host->interval, &interval);
894 plugin_register_complex_read (/* group = */ NULL, name,
895 /* callback = */ mb_read,
896 /* interval = */ (host->interval > 0) ? &interval : NULL,
905 } /* }}} int mb_config_add_host */
907 static int mb_config (oconfig_item_t *ci) /* {{{ */
914 for (i = 0; i < ci->children_num; i++)
916 oconfig_item_t *child = ci->children + i;
918 if (strcasecmp ("Data", child->key) == 0)
919 mb_config_add_data (child);
920 else if (strcasecmp ("Host", child->key) == 0)
921 mb_config_add_host (child);
923 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
927 } /* }}} int mb_config */
931 static int mb_shutdown (void) /* {{{ */
933 data_free_all (data_definitions);
934 data_definitions = NULL;
937 } /* }}} int mb_shutdown */
939 void module_register (void)
941 plugin_register_complex_config ("modbus", mb_config);
942 plugin_register_shutdown ("modbus", mb_shutdown);
943 } /* void module_register */
945 /* vim: set sw=2 sts=2 et fdm=marker : */