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 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 /* {{{ */
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_slave_s /* {{{ */
96 char instance[DATA_MAX_NAME_LEN];
99 typedef struct mb_slave_s mb_slave_t;
101 struct mb_host_s /* {{{ */
103 char host[DATA_MAX_NAME_LEN];
104 char node[NI_MAXHOST];
105 /* char service[NI_MAXSERV]; */
113 modbus_param_t connection;
115 modbus_t *connection;
118 _Bool have_reconnected;
120 typedef struct mb_host_s mb_host_t;
122 struct mb_data_group_s;
123 typedef struct mb_data_group_s mb_data_group_t;
124 struct mb_data_group_s /* {{{ */
126 mb_data_t *registers;
127 size_t registers_num;
129 mb_data_group_t *next;
135 static mb_data_t *data_definitions = NULL;
140 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
148 for (ptr = src; ptr != NULL; ptr = ptr->next)
149 if (strcasecmp (ptr->name, name) == 0)
153 } /* }}} mb_data_t *data_get_by_name */
155 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
159 if ((dst == NULL) || (src == NULL))
170 while (ptr->next != NULL)
176 } /* }}} int data_append */
178 /* Copy a single mb_data_t and append it to another list. */
179 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
184 if ((dst == NULL) || (src == NULL))
187 tmp = malloc (sizeof (*tmp));
190 memcpy (tmp, src, sizeof (*tmp));
194 tmp->name = strdup (src->name);
195 if (tmp->name == NULL)
201 status = data_append (dst, tmp);
210 } /* }}} int data_copy */
212 /* Lookup a single mb_data_t instance, copy it and append the copy to another
214 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
219 if ((dst == NULL) || (src == NULL) || (name == NULL))
222 ptr = data_get_by_name (src, name);
226 return (data_copy (dst, ptr));
227 } /* }}} int data_copy_by_name */
231 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
232 mb_data_t *data, value_t value)
234 value_list_t vl = VALUE_LIST_INIT;
236 if ((host == NULL) || (slave == NULL) || (data == NULL))
239 if (host->interval <= 0)
240 host->interval = interval_g;
242 if (slave->instance[0] == 0)
243 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
248 vl.interval = host->interval;
249 sstrncpy (vl.host, host->host, sizeof (vl.host));
250 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
251 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
252 sstrncpy (vl.type, data->type, sizeof (vl.type));
253 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
255 return (plugin_dispatch_values (&vl));
256 } /* }}} int mb_submit */
258 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
266 #if BYTE_ORDER == LITTLE_ENDIAN
268 conv.b[0] = lo & 0x00ff;
269 conv.b[1] = (lo >> 8) & 0x00ff;
270 conv.b[2] = hi & 0x00ff;
271 conv.b[3] = (hi >> 8) & 0x00ff;
273 conv.b[3] = lo & 0x00ff;
274 conv.b[2] = (lo >> 8) & 0x00ff;
275 conv.b[1] = hi & 0x00ff;
276 conv.b[0] = (hi >> 8) & 0x00ff;
280 } /* }}} float mb_register_to_float */
284 static int mb_init_connection (mb_host_t *host) /* {{{ */
291 if (host->is_connected)
294 /* Only reconnect once per interval. */
295 if (host->have_reconnected)
298 modbus_set_debug (&host->connection, 1);
300 /* We'll do the error handling ourselves. */
301 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
303 if ((host->port < 1) || (host->port > 65535))
304 host->port = MODBUS_TCP_DEFAULT_PORT;
306 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
307 host->node, host->port);
309 modbus_init_tcp (&host->connection,
310 /* host = */ host->node,
311 /* port = */ host->port);
313 status = modbus_connect (&host->connection);
316 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
317 host->node, host->port, status);
321 host->is_connected = 1;
322 host->have_reconnected = 1;
324 } /* }}} int mb_init_connection */
325 /* #endif LEGACY_LIBMODBUS */
327 #else /* if !LEGACY_LIBMODBUS */
329 static int mb_init_connection (mb_host_t *host) /* {{{ */
336 if (host->connection != NULL)
339 /* Only reconnect once per interval. */
340 if (host->have_reconnected)
343 if ((host->port < 1) || (host->port > 65535))
344 host->port = MODBUS_TCP_DEFAULT_PORT;
346 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
347 host->node, host->port);
349 host->connection = modbus_new_tcp (host->node, host->port);
350 if (host->connection == NULL)
352 host->have_reconnected = 1;
353 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
357 modbus_set_debug (host->connection, 1);
359 /* We'll do the error handling ourselves. */
360 modbus_set_error_recovery (host->connection, 0);
362 status = modbus_connect (host->connection);
365 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
366 host->node, host->port, status);
367 modbus_free (host->connection);
368 host->connection = NULL;
372 host->have_reconnected = 1;
374 } /* }}} int mb_init_connection */
375 #endif /* !LEGACY_LIBMODBUS */
377 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
378 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
379 (vt).counter = (counter_t) (raw); \
380 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
381 (vt).gauge = (gauge_t) (raw); \
382 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
383 (vt).derive = (derive_t) (raw); \
384 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
385 (vt).absolute = (absolute_t) (raw); \
388 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
393 const data_set_t *ds;
397 if ((host == NULL) || (slave == NULL) || (data == NULL))
400 ds = plugin_get_ds (data->type);
403 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
409 ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
410 "I can only handle data sets with only one data source.",
411 data->type, ds->ds_num);
415 if ((ds->ds[0].type != DS_TYPE_GAUGE)
416 && (data->register_type != REG_TYPE_INT32)
417 && (data->register_type != REG_TYPE_UINT32))
419 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
420 "This will most likely result in problems, because the register type "
421 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
424 memset (values, 0, sizeof (values));
425 if ((data->register_type == REG_TYPE_INT32)
426 || (data->register_type == REG_TYPE_UINT32)
427 || (data->register_type == REG_TYPE_FLOAT))
433 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
434 * id to each call of "read_holding_registers". */
435 # define modbus_read_registers(ctx, addr, nb, dest) \
436 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
437 #else /* if !LEGACY_LIBMODBUS */
438 /* Version 2.9.2: Set the slave id once before querying the registers. */
439 status = modbus_set_slave (host->connection, slave->id);
442 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
448 for (i = 0; i < 2; i++)
450 status = modbus_read_registers (host->connection,
451 /* start_addr = */ data->register_base,
452 /* num_registers = */ values_num, /* buffer = */ values);
456 if (host->is_connected)
459 modbus_close (&host->connection);
460 host->is_connected = 0;
462 modbus_close (host->connection);
463 modbus_free (host->connection);
464 host->connection = NULL;
468 /* If we already tried reconnecting this round, give up. */
469 if (host->have_reconnected)
471 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
472 "Reconnecting has already been tried. Giving up.", host->host);
476 /* Maybe the device closed the connection during the waiting interval.
477 * Try re-establishing the connection. */
478 status = mb_init_connection (host);
481 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
482 "While trying to reconnect, connecting to \"%s\" failed. "
484 host->host, host->node);
488 DEBUG ("Modbus plugin: Re-established connection to %s", host->host);
492 } /* for (i = 0, 1) */
494 DEBUG ("Modbus plugin: mb_read_data: Success! "
495 "modbus_read_registers returned with status %i.", status);
497 if (data->register_type == REG_TYPE_FLOAT)
502 float_value = mb_register_to_float (values[0], values[1]);
503 DEBUG ("Modbus plugin: mb_read_data: "
504 "Returned float value is %g", (double) float_value);
506 CAST_TO_VALUE_T (ds, vt, float_value);
507 mb_submit (host, slave, data, vt);
509 else if (data->register_type == REG_TYPE_INT32)
518 v.u32 = (((uint32_t) values[0]) << 16)
519 | ((uint32_t) values[1]);
520 DEBUG ("Modbus plugin: mb_read_data: "
521 "Returned int32 value is %"PRIi32, v.i32);
523 CAST_TO_VALUE_T (ds, vt, v.i32);
524 mb_submit (host, slave, data, vt);
526 else if (data->register_type == REG_TYPE_INT16)
537 DEBUG ("Modbus plugin: mb_read_data: "
538 "Returned int16 value is %"PRIi16, v.i16);
540 CAST_TO_VALUE_T (ds, vt, v.i16);
541 mb_submit (host, slave, data, vt);
543 else if (data->register_type == REG_TYPE_UINT32)
548 v32 = (((uint32_t) values[0]) << 16)
549 | ((uint32_t) values[1]);
550 DEBUG ("Modbus plugin: mb_read_data: "
551 "Returned uint32 value is %"PRIu32, v32);
553 CAST_TO_VALUE_T (ds, vt, v32);
554 mb_submit (host, slave, data, vt);
556 else /* if (data->register_type == REG_TYPE_UINT16) */
560 DEBUG ("Modbus plugin: mb_read_data: "
561 "Returned uint16 value is %"PRIu16, values[0]);
563 CAST_TO_VALUE_T (ds, vt, values[0]);
564 mb_submit (host, slave, data, vt);
568 } /* }}} int mb_read_data */
570 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
576 if ((host == NULL) || (slave == NULL))
580 for (data = slave->collect; data != NULL; data = data->next)
582 status = mb_read_data (host, slave, data);
591 } /* }}} int mb_read_slave */
593 static int mb_read (user_data_t *user_data) /* {{{ */
600 if ((user_data == NULL) || (user_data->data == NULL))
603 host = user_data->data;
605 /* Clear the reconnect flag. */
606 host->have_reconnected = 0;
609 for (i = 0; i < host->slaves_num; i++)
611 status = mb_read_slave (host, host->slaves + i);
620 } /* }}} int mb_read */
624 static void data_free_one (mb_data_t *data) /* {{{ */
631 } /* }}} void data_free_one */
633 static void data_free_all (mb_data_t *data) /* {{{ */
641 data_free_one (data);
643 data_free_all (next);
644 } /* }}} void data_free_all */
646 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
653 for (i = 0; i < slaves_num; i++)
654 data_free_all (slaves[i].collect);
656 } /* }}} void slaves_free_all */
658 static void host_free (void *void_host) /* {{{ */
660 mb_host_t *host = void_host;
665 slaves_free_all (host->slaves, host->slaves_num);
667 } /* }}} void host_free */
669 /* Config functions */
671 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
677 memset (&data, 0, sizeof (data));
679 data.register_type = REG_TYPE_UINT16;
682 status = cf_util_get_string (ci, &data.name);
686 for (i = 0; i < ci->children_num; i++)
688 oconfig_item_t *child = ci->children + i;
691 if (strcasecmp ("Type", child->key) == 0)
692 status = cf_util_get_string_buffer (child,
693 data.type, sizeof (data.type));
694 else if (strcasecmp ("Instance", child->key) == 0)
695 status = cf_util_get_string_buffer (child,
696 data.instance, sizeof (data.instance));
697 else if (strcasecmp ("RegisterBase", child->key) == 0)
698 status = cf_util_get_int (child, &data.register_base);
699 else if (strcasecmp ("RegisterType", child->key) == 0)
702 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
705 else if (strcasecmp ("Int16", tmp) == 0)
706 data.register_type = REG_TYPE_INT16;
707 else if (strcasecmp ("Int32", tmp) == 0)
708 data.register_type = REG_TYPE_INT32;
709 else if (strcasecmp ("Uint16", tmp) == 0)
710 data.register_type = REG_TYPE_UINT16;
711 else if (strcasecmp ("Uint32", tmp) == 0)
712 data.register_type = REG_TYPE_UINT32;
713 else if (strcasecmp ("Float", tmp) == 0)
714 data.register_type = REG_TYPE_FLOAT;
717 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
723 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
729 } /* for (i = 0; i < ci->children_num; i++) */
731 assert (data.name != NULL);
732 if (data.type[0] == 0)
734 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
740 data_copy (&data_definitions, &data);
745 } /* }}} int mb_config_add_data */
747 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
750 struct addrinfo *ai_list;
751 struct addrinfo *ai_ptr;
752 struct addrinfo ai_hints;
755 if ((host == NULL) || (address == NULL))
758 memset (&ai_hints, 0, sizeof (ai_hints));
760 ai_hints.ai_flags |= AI_ADDRCONFIG;
762 /* XXX: libmodbus can only handle IPv4 addresses. */
763 ai_hints.ai_family = AF_INET;
764 ai_hints.ai_addr = NULL;
765 ai_hints.ai_canonname = NULL;
766 ai_hints.ai_next = NULL;
769 status = getaddrinfo (address, /* service = */ NULL,
770 &ai_hints, &ai_list);
774 ERROR ("Modbus plugin: getaddrinfo failed: %s",
775 (status == EAI_SYSTEM)
776 ? sstrerror (errno, errbuf, sizeof (errbuf))
777 : gai_strerror (status));
781 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
783 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
784 host->node, sizeof (host->node),
785 /* service = */ NULL, /* length = */ 0,
786 /* flags = */ NI_NUMERICHOST);
791 freeaddrinfo (ai_list);
794 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
795 else /* if (status == 0) */
797 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
798 address, host->node);
802 } /* }}} int mb_config_set_host_address */
804 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
810 if ((host == NULL) || (ci == NULL))
813 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
816 host->slaves = slave;
817 slave = host->slaves + host->slaves_num;
818 memset (slave, 0, sizeof (*slave));
819 slave->collect = NULL;
821 status = cf_util_get_int (ci, &slave->id);
825 for (i = 0; i < ci->children_num; i++)
827 oconfig_item_t *child = ci->children + i;
830 if (strcasecmp ("Instance", child->key) == 0)
831 status = cf_util_get_string_buffer (child,
832 slave->instance, sizeof (slave->instance));
833 else if (strcasecmp ("Collect", child->key) == 0)
836 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
838 data_copy_by_name (&slave->collect, data_definitions, buffer);
839 status = 0; /* continue after failure. */
843 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
851 if ((status == 0) && (slave->collect == NULL))
859 else /* if (status != 0) */
860 data_free_all (slave->collect);
863 } /* }}} int mb_config_add_slave */
865 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
871 host = malloc (sizeof (*host));
874 memset (host, 0, sizeof (*host));
877 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
880 if (host->host[0] == 0)
883 for (i = 0; i < ci->children_num; i++)
885 oconfig_item_t *child = ci->children + i;
888 if (strcasecmp ("Address", child->key) == 0)
890 char buffer[NI_MAXHOST];
891 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
893 status = mb_config_set_host_address (host, buffer);
895 else if (strcasecmp ("Port", child->key) == 0)
897 host->port = cf_util_get_port_number (child);
901 else if (strcasecmp ("Interval", child->key) == 0)
902 status = cf_util_get_cdtime (child, &host->interval);
903 else if (strcasecmp ("Slave", child->key) == 0)
904 /* Don't set status: Gracefully continue if a slave fails. */
905 mb_config_add_slave (host, child);
908 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
914 } /* for (i = 0; i < ci->children_num; i++) */
916 assert (host->host[0] != 0);
917 if (host->host[0] == 0)
919 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
928 struct timespec interval = { 0, 0 };
931 ud.free_func = host_free;
933 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
935 CDTIME_T_TO_TIMESPEC (host->interval, &interval);
937 plugin_register_complex_read (/* group = */ NULL, name,
938 /* callback = */ mb_read,
939 /* interval = */ (host->interval > 0) ? &interval : NULL,
948 } /* }}} int mb_config_add_host */
950 static int mb_config (oconfig_item_t *ci) /* {{{ */
957 for (i = 0; i < ci->children_num; i++)
959 oconfig_item_t *child = ci->children + i;
961 if (strcasecmp ("Data", child->key) == 0)
962 mb_config_add_data (child);
963 else if (strcasecmp ("Host", child->key) == 0)
964 mb_config_add_host (child);
966 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
970 } /* }}} int mb_config */
974 static int mb_shutdown (void) /* {{{ */
976 data_free_all (data_definitions);
977 data_definitions = NULL;
980 } /* }}} int mb_shutdown */
982 void module_register (void)
984 plugin_register_complex_config ("modbus", mb_config);
985 plugin_register_shutdown ("modbus", mb_shutdown);
986 } /* void module_register */
988 /* vim: set sw=2 sts=2 et fdm=marker : */