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 General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian Forster <octo at noris.net>
25 #include "configfile.h"
29 #include <modbus/modbus.h>
31 #ifndef LIBMODBUS_VERSION_CHECK
32 /* Assume version 2.0.3 */
33 # define LEGACY_LIBMODBUS 1
35 /* Assume version 2.9.2 */
38 #ifndef MODBUS_TCP_DEFAULT_PORT
39 # ifdef MODBUS_TCP_PORT
40 # define MODBUS_TCP_DEFAULT_PORT MODBUS_TCP_PORT
42 # define MODBUS_TCP_DEFAULT_PORT 502
60 * Instance "foobar" # optional
69 enum mb_register_type_e /* {{{ */
75 typedef enum mb_register_type_e mb_register_type_t;
78 typedef struct mb_data_s mb_data_t;
79 struct mb_data_s /* {{{ */
83 mb_register_type_t register_type;
84 char type[DATA_MAX_NAME_LEN];
85 char instance[DATA_MAX_NAME_LEN];
90 struct mb_slave_s /* {{{ */
93 char instance[DATA_MAX_NAME_LEN];
96 typedef struct mb_slave_s mb_slave_t;
98 struct mb_host_s /* {{{ */
100 char host[DATA_MAX_NAME_LEN];
101 char node[NI_MAXHOST];
102 /* char service[NI_MAXSERV]; */
110 modbus_param_t connection;
112 modbus_t *connection;
115 _Bool have_reconnected;
117 typedef struct mb_host_s mb_host_t;
119 struct mb_data_group_s;
120 typedef struct mb_data_group_s mb_data_group_t;
121 struct mb_data_group_s /* {{{ */
123 mb_data_t *registers;
124 size_t registers_num;
126 mb_data_group_t *next;
132 static mb_data_t *data_definitions = NULL;
137 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
145 for (ptr = src; ptr != NULL; ptr = ptr->next)
146 if (strcasecmp (ptr->name, name) == 0)
150 } /* }}} mb_data_t *data_get_by_name */
152 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
156 if ((dst == NULL) || (src == NULL))
167 while (ptr->next != NULL)
173 } /* }}} int data_append */
175 /* Copy a single mb_data_t and append it to another list. */
176 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
181 if ((dst == NULL) || (src == NULL))
184 tmp = malloc (sizeof (*tmp));
187 memcpy (tmp, src, sizeof (*tmp));
191 tmp->name = strdup (src->name);
192 if (tmp->name == NULL)
198 status = data_append (dst, tmp);
207 } /* }}} int data_copy */
209 /* Lookup a single mb_data_t instance, copy it and append the copy to another
211 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
216 if ((dst == NULL) || (src == NULL) || (name == NULL))
219 ptr = data_get_by_name (src, name);
223 return (data_copy (dst, ptr));
224 } /* }}} int data_copy_by_name */
228 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
229 mb_data_t *data, value_t value)
231 value_list_t vl = VALUE_LIST_INIT;
233 if ((host == NULL) || (slave == NULL) || (data == NULL))
236 if (host->interval <= 0)
237 host->interval = interval_g;
239 if (slave->instance[0] == 0)
240 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
245 vl.interval = host->interval;
246 sstrncpy (vl.host, host->host, sizeof (vl.host));
247 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
248 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
249 sstrncpy (vl.type, data->type, sizeof (vl.type));
250 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
252 return (plugin_dispatch_values (&vl));
253 } /* }}} int mb_submit */
255 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
263 #if BYTE_ORDER == LITTLE_ENDIAN
265 conv.b[0] = lo & 0x00ff;
266 conv.b[1] = (lo >> 8) & 0x00ff;
267 conv.b[2] = hi & 0x00ff;
268 conv.b[3] = (hi >> 8) & 0x00ff;
270 conv.b[3] = lo & 0x00ff;
271 conv.b[2] = (lo >> 8) & 0x00ff;
272 conv.b[1] = hi & 0x00ff;
273 conv.b[0] = (hi >> 8) & 0x00ff;
277 } /* }}} float mb_register_to_float */
281 static int mb_init_connection (mb_host_t *host) /* {{{ */
288 if (host->is_connected)
291 /* Only reconnect once per interval. */
292 if (host->have_reconnected)
295 modbus_set_debug (&host->connection, 1);
297 /* We'll do the error handling ourselves. */
298 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
300 if ((host->port < 1) || (host->port > 65535))
301 host->port = MODBUS_TCP_DEFAULT_PORT;
303 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
304 host->node, host->port);
306 modbus_init_tcp (&host->connection,
307 /* host = */ host->node,
308 /* port = */ host->port);
310 status = modbus_connect (&host->connection);
313 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
314 host->node, host->port, status);
318 host->is_connected = 1;
319 host->have_reconnected = 1;
321 } /* }}} int mb_init_connection */
322 /* #endif LEGACY_LIBMODBUS */
324 #else /* if !LEGACY_LIBMODBUS */
326 static int mb_init_connection (mb_host_t *host) /* {{{ */
333 if (host->connection != NULL)
336 /* Only reconnect once per interval. */
337 if (host->have_reconnected)
340 if ((host->port < 1) || (host->port > 65535))
341 host->port = MODBUS_TCP_DEFAULT_PORT;
343 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
344 host->node, host->port);
346 host->connection = modbus_new_tcp (host->node, host->port);
347 if (host->connection == NULL)
349 host->have_reconnected = 1;
350 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
354 modbus_set_debug (host->connection, 1);
356 /* We'll do the error handling ourselves. */
357 modbus_set_error_recovery (host->connection, 0);
359 status = modbus_connect (host->connection);
362 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
363 host->node, host->port, status);
364 modbus_free (host->connection);
365 host->connection = NULL;
369 host->have_reconnected = 1;
371 } /* }}} int mb_init_connection */
372 #endif /* !LEGACY_LIBMODBUS */
374 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
375 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
376 (vt).counter = (counter_t) (raw); \
377 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
378 (vt).gauge = (gauge_t) (raw); \
379 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
380 (vt).derive = (derive_t) (raw); \
381 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
382 (vt).absolute = (absolute_t) (raw); \
385 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
390 const data_set_t *ds;
394 if ((host == NULL) || (slave == NULL) || (data == NULL))
397 ds = plugin_get_ds (data->type);
400 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
406 ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
407 "I can only handle data sets with only one data source.",
408 data->type, ds->ds_num);
412 if ((ds->ds[0].type != DS_TYPE_GAUGE)
413 && (data->register_type != REG_TYPE_UINT32))
415 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
416 "This will most likely result in problems, because the register type "
417 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
420 memset (values, 0, sizeof (values));
421 if ((data->register_type == REG_TYPE_UINT32)
422 || (data->register_type == REG_TYPE_FLOAT))
428 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
429 * id to each call of "read_holding_registers". */
430 # define modbus_read_registers(ctx, addr, nb, dest) \
431 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
432 #else /* if !LEGACY_LIBMODBUS */
433 /* Version 2.9.2: Set the slave id once before querying the registers. */
434 status = modbus_set_slave (host->connection, slave->id);
437 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
443 for (i = 0; i < 2; i++)
445 status = modbus_read_registers (host->connection,
446 /* start_addr = */ data->register_base,
447 /* num_registers = */ values_num, /* buffer = */ values);
451 if (host->is_connected)
454 modbus_close (&host->connection);
455 host->is_connected = 0;
457 modbus_close (host->connection);
458 modbus_free (host->connection);
459 host->connection = NULL;
463 /* If we already tried reconnecting this round, give up. */
464 if (host->have_reconnected)
466 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
467 "Reconnecting has already been tried. Giving up.", host->host);
471 /* Maybe the device closed the connection during the waiting interval.
472 * Try re-establishing the connection. */
473 status = mb_init_connection (host);
476 ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
477 "While trying to reconnect, connecting to \"%s\" failed. "
479 host->host, host->node);
483 DEBUG ("Modbus plugin: Re-established connection to %s", host->host);
487 } /* for (i = 0, 1) */
489 DEBUG ("Modbus plugin: mb_read_data: Success! "
490 "modbus_read_registers returned with status %i.", status);
492 if (data->register_type == REG_TYPE_FLOAT)
497 float_value = mb_register_to_float (values[0], values[1]);
498 DEBUG ("Modbus plugin: mb_read_data: "
499 "Returned float value is %g", (double) float_value);
501 CAST_TO_VALUE_T (ds, vt, float_value);
502 mb_submit (host, slave, data, vt);
504 else if (data->register_type == REG_TYPE_UINT32)
509 v32 = (values[0] << 16) | values[1];
510 DEBUG ("Modbus plugin: mb_read_data: "
511 "Returned uint32 value is %"PRIu32, v32);
513 CAST_TO_VALUE_T (ds, vt, v32);
514 mb_submit (host, slave, data, vt);
516 else /* if (data->register_type == REG_TYPE_UINT16) */
520 DEBUG ("Modbus plugin: mb_read_data: "
521 "Returned uint16 value is %"PRIu16, values[0]);
523 CAST_TO_VALUE_T (ds, vt, values[0]);
524 mb_submit (host, slave, data, vt);
528 } /* }}} int mb_read_data */
530 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
536 if ((host == NULL) || (slave == NULL))
540 for (data = slave->collect; data != NULL; data = data->next)
542 status = mb_read_data (host, slave, data);
551 } /* }}} int mb_read_slave */
553 static int mb_read (user_data_t *user_data) /* {{{ */
560 if ((user_data == NULL) || (user_data->data == NULL))
563 host = user_data->data;
565 /* Clear the reconnect flag. */
566 host->have_reconnected = 0;
569 for (i = 0; i < host->slaves_num; i++)
571 status = mb_read_slave (host, host->slaves + i);
580 } /* }}} int mb_read */
584 static void data_free_one (mb_data_t *data) /* {{{ */
591 } /* }}} void data_free_one */
593 static void data_free_all (mb_data_t *data) /* {{{ */
601 data_free_one (data);
603 data_free_all (next);
604 } /* }}} void data_free_all */
606 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
613 for (i = 0; i < slaves_num; i++)
614 data_free_all (slaves[i].collect);
616 } /* }}} void slaves_free_all */
618 static void host_free (void *void_host) /* {{{ */
620 mb_host_t *host = void_host;
625 slaves_free_all (host->slaves, host->slaves_num);
627 } /* }}} void host_free */
629 /* Config functions */
631 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
637 memset (&data, 0, sizeof (data));
639 data.register_type = REG_TYPE_UINT16;
642 status = cf_util_get_string (ci, &data.name);
646 for (i = 0; i < ci->children_num; i++)
648 oconfig_item_t *child = ci->children + i;
651 if (strcasecmp ("Type", child->key) == 0)
652 status = cf_util_get_string_buffer (child,
653 data.type, sizeof (data.type));
654 else if (strcasecmp ("Instance", child->key) == 0)
655 status = cf_util_get_string_buffer (child,
656 data.instance, sizeof (data.instance));
657 else if (strcasecmp ("RegisterBase", child->key) == 0)
658 status = cf_util_get_int (child, &data.register_base);
659 else if (strcasecmp ("RegisterType", child->key) == 0)
662 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
665 else if (strcasecmp ("Uint16", tmp) == 0)
666 data.register_type = REG_TYPE_UINT16;
667 else if (strcasecmp ("Uint32", tmp) == 0)
668 data.register_type = REG_TYPE_UINT32;
669 else if (strcasecmp ("Float", tmp) == 0)
670 data.register_type = REG_TYPE_FLOAT;
673 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
679 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
685 } /* for (i = 0; i < ci->children_num; i++) */
687 assert (data.name != NULL);
688 if (data.type[0] == 0)
690 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
696 data_copy (&data_definitions, &data);
701 } /* }}} int mb_config_add_data */
703 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
706 struct addrinfo *ai_list;
707 struct addrinfo *ai_ptr;
708 struct addrinfo ai_hints;
711 if ((host == NULL) || (address == NULL))
714 memset (&ai_hints, 0, sizeof (ai_hints));
716 ai_hints.ai_flags |= AI_ADDRCONFIG;
718 /* XXX: libmodbus can only handle IPv4 addresses. */
719 ai_hints.ai_family = AF_INET;
720 ai_hints.ai_addr = NULL;
721 ai_hints.ai_canonname = NULL;
722 ai_hints.ai_next = NULL;
725 status = getaddrinfo (address, /* service = */ NULL,
726 &ai_hints, &ai_list);
730 ERROR ("Modbus plugin: getaddrinfo failed: %s",
731 (status == EAI_SYSTEM)
732 ? sstrerror (errno, errbuf, sizeof (errbuf))
733 : gai_strerror (status));
737 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
739 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
740 host->node, sizeof (host->node),
741 /* service = */ NULL, /* length = */ 0,
742 /* flags = */ NI_NUMERICHOST);
747 freeaddrinfo (ai_list);
750 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
751 else /* if (status == 0) */
753 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
754 address, host->node);
758 } /* }}} int mb_config_set_host_address */
760 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
766 if ((host == NULL) || (ci == NULL))
769 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
772 host->slaves = slave;
773 slave = host->slaves + host->slaves_num;
774 memset (slave, 0, sizeof (*slave));
775 slave->collect = NULL;
777 status = cf_util_get_int (ci, &slave->id);
781 for (i = 0; i < ci->children_num; i++)
783 oconfig_item_t *child = ci->children + i;
786 if (strcasecmp ("Instance", child->key) == 0)
787 status = cf_util_get_string_buffer (child,
788 slave->instance, sizeof (slave->instance));
789 else if (strcasecmp ("Collect", child->key) == 0)
792 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
794 data_copy_by_name (&slave->collect, data_definitions, buffer);
795 status = 0; /* continue after failure. */
799 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
807 if ((status == 0) && (slave->collect == NULL))
815 else /* if (status != 0) */
816 data_free_all (slave->collect);
819 } /* }}} int mb_config_add_slave */
821 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
827 host = malloc (sizeof (*host));
830 memset (host, 0, sizeof (*host));
833 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
836 if (host->host[0] == 0)
839 for (i = 0; i < ci->children_num; i++)
841 oconfig_item_t *child = ci->children + i;
844 if (strcasecmp ("Address", child->key) == 0)
846 char buffer[NI_MAXHOST];
847 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
849 status = mb_config_set_host_address (host, buffer);
851 else if (strcasecmp ("Port", child->key) == 0)
853 host->port = cf_util_get_port_number (child);
857 else if (strcasecmp ("Interval", child->key) == 0)
858 status = cf_util_get_cdtime (child, &host->interval);
859 else if (strcasecmp ("Slave", child->key) == 0)
860 /* Don't set status: Gracefully continue if a slave fails. */
861 mb_config_add_slave (host, child);
864 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
870 } /* for (i = 0; i < ci->children_num; i++) */
872 assert (host->host[0] != 0);
873 if (host->host[0] == 0)
875 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
884 struct timespec interval = { 0, 0 };
887 ud.free_func = host_free;
889 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
891 CDTIME_T_TO_TIMESPEC (host->interval, &interval);
893 plugin_register_complex_read (/* group = */ NULL, name,
894 /* callback = */ mb_read,
895 /* interval = */ (host->interval > 0) ? &interval : NULL,
904 } /* }}} int mb_config_add_host */
906 static int mb_config (oconfig_item_t *ci) /* {{{ */
913 for (i = 0; i < ci->children_num; i++)
915 oconfig_item_t *child = ci->children + i;
917 if (strcasecmp ("Data", child->key) == 0)
918 mb_config_add_data (child);
919 else if (strcasecmp ("Host", child->key) == 0)
920 mb_config_add_host (child);
922 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
926 } /* }}} int mb_config */
930 static int mb_shutdown (void) /* {{{ */
932 data_free_all (data_definitions);
933 data_definitions = NULL;
936 } /* }}} int mb_shutdown */
938 void module_register (void)
940 plugin_register_complex_config ("modbus", mb_config);
941 plugin_register_shutdown ("modbus", mb_shutdown);
942 } /* void module_register */
944 /* vim: set sw=2 sts=2 et fdm=marker : */