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"
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
50 * RegisterCmd ReadHolding
60 * # Device "/dev/ttyUSB0"
66 * Instance "foobar" # optional
75 enum mb_register_type_e /* {{{ */
83 enum mb_mreg_type_e /* {{{ */
88 typedef enum mb_register_type_e mb_register_type_t;
89 typedef enum mb_mreg_type_e mb_mreg_type_t;
91 /* TCP or RTU depending on what is specified in host config block */
92 enum mb_conntype_e /* {{{ */
97 typedef enum mb_conntype_e mb_conntype_t;
100 typedef struct mb_data_s mb_data_t;
101 struct mb_data_s /* {{{ */
105 mb_register_type_t register_type;
106 mb_mreg_type_t modbus_register_type;
107 char type[DATA_MAX_NAME_LEN];
108 char instance[DATA_MAX_NAME_LEN];
113 struct mb_slave_s /* {{{ */
116 char instance[DATA_MAX_NAME_LEN];
119 typedef struct mb_slave_s mb_slave_t;
121 struct mb_host_s /* {{{ */
123 char host[DATA_MAX_NAME_LEN];
124 char node[NI_MAXHOST]; /* TCP hostname or RTU serial device */
125 /* char service[NI_MAXSERV]; */
126 int port; /* for Modbus/TCP */
127 int baudrate; /* for Modbus/RTU */
128 mb_conntype_t conntype;
135 modbus_param_t connection;
137 modbus_t *connection;
141 typedef struct mb_host_s mb_host_t;
143 struct mb_data_group_s;
144 typedef struct mb_data_group_s mb_data_group_t;
145 struct mb_data_group_s /* {{{ */
147 mb_data_t *registers;
148 size_t registers_num;
150 mb_data_group_t *next;
156 static mb_data_t *data_definitions = NULL;
161 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
169 for (ptr = src; ptr != NULL; ptr = ptr->next)
170 if (strcasecmp (ptr->name, name) == 0)
174 } /* }}} mb_data_t *data_get_by_name */
176 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
180 if ((dst == NULL) || (src == NULL))
191 while (ptr->next != NULL)
197 } /* }}} int data_append */
199 /* Copy a single mb_data_t and append it to another list. */
200 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
205 if ((dst == NULL) || (src == NULL))
208 tmp = malloc (sizeof (*tmp));
211 memcpy (tmp, src, sizeof (*tmp));
215 tmp->name = strdup (src->name);
216 if (tmp->name == NULL)
222 status = data_append (dst, tmp);
231 } /* }}} int data_copy */
233 /* Lookup a single mb_data_t instance, copy it and append the copy to another
235 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
240 if ((dst == NULL) || (src == NULL) || (name == NULL))
243 ptr = data_get_by_name (src, name);
247 return (data_copy (dst, ptr));
248 } /* }}} int data_copy_by_name */
252 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
253 mb_data_t *data, value_t value)
255 value_list_t vl = VALUE_LIST_INIT;
257 if ((host == NULL) || (slave == NULL) || (data == NULL))
260 if (host->interval <= 0)
261 host->interval = plugin_get_interval ();
263 if (slave->instance[0] == 0)
264 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
269 vl.interval = host->interval;
270 sstrncpy (vl.host, host->host, sizeof (vl.host));
271 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
272 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
273 sstrncpy (vl.type, data->type, sizeof (vl.type));
274 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
276 return (plugin_dispatch_values (&vl));
277 } /* }}} int mb_submit */
279 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
288 #if BYTE_ORDER == LITTLE_ENDIAN
290 conv.b[0] = lo & 0x00ff;
291 conv.b[1] = (lo >> 8) & 0x00ff;
292 conv.b[2] = hi & 0x00ff;
293 conv.b[3] = (hi >> 8) & 0x00ff;
295 conv.b[3] = lo & 0x00ff;
296 conv.b[2] = (lo >> 8) & 0x00ff;
297 conv.b[1] = hi & 0x00ff;
298 conv.b[0] = (hi >> 8) & 0x00ff;
302 } /* }}} float mb_register_to_float */
306 static int mb_init_connection (mb_host_t *host) /* {{{ */
314 modbus_set_debug (&host->connection, 1);
317 /* We'll do the error handling ourselves. */
318 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
320 if (host->conntype == MBCONN_TCP)
322 if ((host->port < 1) || (host->port > 65535))
323 host->port = MODBUS_TCP_DEFAULT_PORT;
325 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
326 host->node, host->port);
328 modbus_init_tcp (&host->connection,
329 /* host = */ host->node,
330 /* port = */ host->port);
332 else /* MBCONN_RTU */
334 DEBUG ("Modbus plugin: Trying to connect to \"%s\".", host->node);
336 modbus_init_rtu (&host->connection,
337 /* device = */ host->node,
338 /* baudrate = */ host->baudrate,
342 status = modbus_connect (&host->connection);
345 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
346 host->node, host->port ? host->port : host->baudrate, status);
350 host->is_connected = 1;
352 } /* }}} int mb_init_connection */
353 /* #endif LEGACY_LIBMODBUS */
355 #else /* if !LEGACY_LIBMODBUS */
357 static int mb_init_connection (mb_host_t *host) /* {{{ */
364 if (host->connection != NULL)
367 if (host->conntype == MBCONN_TCP)
369 if ((host->port < 1) || (host->port > 65535))
370 host->port = MODBUS_TCP_DEFAULT_PORT;
372 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
373 host->node, host->port);
375 host->connection = modbus_new_tcp (host->node, host->port);
376 if (host->connection == NULL)
378 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
384 DEBUG ("Modbus plugin: Trying to connect to \"%s\", baudrate %i.",
385 host->node, host->baudrate);
387 host->connection = modbus_new_rtu (host->node, host->baudrate, 'N', 8, 1);
388 if (host->connection == NULL)
390 ERROR ("Modbus plugin: Creating new Modbus/RTU object failed.");
396 modbus_set_debug (host->connection, 1);
399 /* We'll do the error handling ourselves. */
400 modbus_set_error_recovery (host->connection, 0);
402 status = modbus_connect (host->connection);
405 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
406 host->node, host->port ? host->port : host->baudrate, status);
407 modbus_free (host->connection);
408 host->connection = NULL;
413 } /* }}} int mb_init_connection */
414 #endif /* !LEGACY_LIBMODBUS */
416 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
417 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
418 (vt).counter = (counter_t) (raw); \
419 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
420 (vt).gauge = (gauge_t) (raw); \
421 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
422 (vt).derive = (derive_t) (raw); \
423 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
424 (vt).absolute = (absolute_t) (raw); \
427 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
432 const data_set_t *ds;
435 if ((host == NULL) || (slave == NULL) || (data == NULL))
438 ds = plugin_get_ds (data->type);
441 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
447 ERROR ("Modbus plugin: The type \"%s\" has %zu data sources. "
448 "I can only handle data sets with only one data source.",
449 data->type, ds->ds_num);
453 if ((ds->ds[0].type != DS_TYPE_GAUGE)
454 && (data->register_type != REG_TYPE_INT32)
455 && (data->register_type != REG_TYPE_UINT32))
457 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
458 "This will most likely result in problems, because the register type "
459 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
462 memset (values, 0, sizeof (values));
463 if ((data->register_type == REG_TYPE_INT32)
464 || (data->register_type == REG_TYPE_UINT32)
465 || (data->register_type == REG_TYPE_FLOAT))
470 if (host->connection == NULL)
474 else if (host->conntype == MBCONN_TCP)
476 struct sockaddr sockaddr;
477 socklen_t saddrlen = sizeof (sockaddr);
479 status = getpeername (modbus_get_socket (host->connection),
480 &sockaddr, &saddrlen);
485 if ((status == EBADF) || (status == ENOTSOCK) || (status == ENOTCONN))
487 status = mb_init_connection (host);
490 ERROR ("Modbus plugin: mb_init_connection (%s/%s) failed. ",
491 host->host, host->node);
492 host->is_connected = 0;
493 host->connection = NULL;
497 else if (status != 0)
500 modbus_close (&host->connection);
502 modbus_close (host->connection);
503 modbus_free (host->connection);
508 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
509 * id to each call of "read_holding_registers". */
510 # define modbus_read_registers(ctx, addr, nb, dest) \
511 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
512 #else /* if !LEGACY_LIBMODBUS */
513 /* Version 2.9.2: Set the slave id once before querying the registers. */
514 status = modbus_set_slave (host->connection, slave->id);
517 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
522 if (data->modbus_register_type == MREG_INPUT){
523 status = modbus_read_input_registers (host->connection,
524 /* start_addr = */ data->register_base,
525 /* num_registers = */ values_num, /* buffer = */ values);
528 status = modbus_read_registers (host->connection,
529 /* start_addr = */ data->register_base,
530 /* num_registers = */ values_num, /* buffer = */ values);
532 if (status != values_num)
534 ERROR ("Modbus plugin: modbus read function (%s/%s) failed. "
535 " status = %i, values_num = %i. Giving up.",
536 host->host, host->node, status, values_num);
538 modbus_close (&host->connection);
540 modbus_close (host->connection);
541 modbus_free (host->connection);
543 host->connection = NULL;
547 DEBUG ("Modbus plugin: mb_read_data: Success! "
548 "modbus_read_registers returned with status %i.", status);
550 if (data->register_type == REG_TYPE_FLOAT)
555 float_value = mb_register_to_float (values[0], values[1]);
556 DEBUG ("Modbus plugin: mb_read_data: "
557 "Returned float value is %g", (double) float_value);
559 CAST_TO_VALUE_T (ds, vt, float_value);
560 mb_submit (host, slave, data, vt);
562 else if (data->register_type == REG_TYPE_INT32)
571 v.u32 = (((uint32_t) values[0]) << 16)
572 | ((uint32_t) values[1]);
573 DEBUG ("Modbus plugin: mb_read_data: "
574 "Returned int32 value is %"PRIi32, v.i32);
576 CAST_TO_VALUE_T (ds, vt, v.i32);
577 mb_submit (host, slave, data, vt);
579 else if (data->register_type == REG_TYPE_INT16)
590 DEBUG ("Modbus plugin: mb_read_data: "
591 "Returned int16 value is %"PRIi16, v.i16);
593 CAST_TO_VALUE_T (ds, vt, v.i16);
594 mb_submit (host, slave, data, vt);
596 else if (data->register_type == REG_TYPE_UINT32)
601 v32 = (((uint32_t) values[0]) << 16)
602 | ((uint32_t) values[1]);
603 DEBUG ("Modbus plugin: mb_read_data: "
604 "Returned uint32 value is %"PRIu32, v32);
606 CAST_TO_VALUE_T (ds, vt, v32);
607 mb_submit (host, slave, data, vt);
609 else /* if (data->register_type == REG_TYPE_UINT16) */
613 DEBUG ("Modbus plugin: mb_read_data: "
614 "Returned uint16 value is %"PRIu16, values[0]);
616 CAST_TO_VALUE_T (ds, vt, values[0]);
617 mb_submit (host, slave, data, vt);
621 } /* }}} int mb_read_data */
623 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
629 if ((host == NULL) || (slave == NULL))
633 for (data = slave->collect; data != NULL; data = data->next)
635 status = mb_read_data (host, slave, data);
644 } /* }}} int mb_read_slave */
646 static int mb_read (user_data_t *user_data) /* {{{ */
653 if ((user_data == NULL) || (user_data->data == NULL))
656 host = user_data->data;
659 for (i = 0; i < host->slaves_num; i++)
661 status = mb_read_slave (host, host->slaves + i);
670 } /* }}} int mb_read */
674 static void data_free_one (mb_data_t *data) /* {{{ */
681 } /* }}} void data_free_one */
683 static void data_free_all (mb_data_t *data) /* {{{ */
691 data_free_one (data);
693 data_free_all (next);
694 } /* }}} void data_free_all */
696 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
703 for (i = 0; i < slaves_num; i++)
704 data_free_all (slaves[i].collect);
706 } /* }}} void slaves_free_all */
708 static void host_free (void *void_host) /* {{{ */
710 mb_host_t *host = void_host;
715 slaves_free_all (host->slaves, host->slaves_num);
717 } /* }}} void host_free */
719 /* Config functions */
721 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
727 memset (&data, 0, sizeof (data));
729 data.register_type = REG_TYPE_UINT16;
732 status = cf_util_get_string (ci, &data.name);
736 for (i = 0; i < ci->children_num; i++)
738 oconfig_item_t *child = ci->children + i;
740 if (strcasecmp ("Type", child->key) == 0)
741 status = cf_util_get_string_buffer (child,
742 data.type, sizeof (data.type));
743 else if (strcasecmp ("Instance", child->key) == 0)
744 status = cf_util_get_string_buffer (child,
745 data.instance, sizeof (data.instance));
746 else if (strcasecmp ("RegisterBase", child->key) == 0)
747 status = cf_util_get_int (child, &data.register_base);
748 else if (strcasecmp ("RegisterType", child->key) == 0)
751 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
754 else if (strcasecmp ("Int16", tmp) == 0)
755 data.register_type = REG_TYPE_INT16;
756 else if (strcasecmp ("Int32", tmp) == 0)
757 data.register_type = REG_TYPE_INT32;
758 else if (strcasecmp ("Uint16", tmp) == 0)
759 data.register_type = REG_TYPE_UINT16;
760 else if (strcasecmp ("Uint32", tmp) == 0)
761 data.register_type = REG_TYPE_UINT32;
762 else if (strcasecmp ("Float", tmp) == 0)
763 data.register_type = REG_TYPE_FLOAT;
766 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
770 else if (strcasecmp ("RegisterCmd", child->key) == 0)
773 ERROR("Modbus plugin: RegisterCmd parameter can not be used "
774 "with your libmodbus version");
777 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
780 else if (strcasecmp ("ReadHolding", tmp) == 0)
781 data.modbus_register_type = MREG_HOLDING;
782 else if (strcasecmp ("ReadInput", tmp) == 0)
783 data.modbus_register_type = MREG_INPUT;
786 ERROR ("Modbus plugin: The modbus_register_type \"%s\" is unknown.",
794 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
800 } /* for (i = 0; i < ci->children_num; i++) */
802 assert (data.name != NULL);
803 if (data.type[0] == 0)
805 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
811 data_copy (&data_definitions, &data);
816 } /* }}} int mb_config_add_data */
818 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
821 struct addrinfo *ai_list;
822 struct addrinfo *ai_ptr;
823 struct addrinfo ai_hints;
826 if ((host == NULL) || (address == NULL))
829 memset (&ai_hints, 0, sizeof (ai_hints));
831 ai_hints.ai_flags |= AI_ADDRCONFIG;
833 /* XXX: libmodbus can only handle IPv4 addresses. */
834 ai_hints.ai_family = AF_INET;
835 ai_hints.ai_addr = NULL;
836 ai_hints.ai_canonname = NULL;
837 ai_hints.ai_next = NULL;
840 status = getaddrinfo (address, /* service = */ NULL,
841 &ai_hints, &ai_list);
845 ERROR ("Modbus plugin: getaddrinfo failed: %s",
846 (status == EAI_SYSTEM)
847 ? sstrerror (errno, errbuf, sizeof (errbuf))
848 : gai_strerror (status));
852 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
854 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
855 host->node, sizeof (host->node),
856 /* service = */ NULL, /* length = */ 0,
857 /* flags = */ NI_NUMERICHOST);
862 freeaddrinfo (ai_list);
865 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
866 else /* if (status == 0) */
868 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
869 address, host->node);
873 } /* }}} int mb_config_set_host_address */
875 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
881 if ((host == NULL) || (ci == NULL))
884 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
887 host->slaves = slave;
888 slave = host->slaves + host->slaves_num;
889 memset (slave, 0, sizeof (*slave));
890 slave->collect = NULL;
892 status = cf_util_get_int (ci, &slave->id);
896 for (i = 0; i < ci->children_num; i++)
898 oconfig_item_t *child = ci->children + i;
900 if (strcasecmp ("Instance", child->key) == 0)
901 status = cf_util_get_string_buffer (child,
902 slave->instance, sizeof (slave->instance));
903 else if (strcasecmp ("Collect", child->key) == 0)
906 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
908 data_copy_by_name (&slave->collect, data_definitions, buffer);
909 status = 0; /* continue after failure. */
913 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
921 if ((status == 0) && (slave->collect == NULL))
929 else /* if (status != 0) */
930 data_free_all (slave->collect);
933 } /* }}} int mb_config_add_slave */
935 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
941 host = calloc (1, sizeof (*host));
946 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
952 if (host->host[0] == 0)
958 for (i = 0; i < ci->children_num; i++)
960 oconfig_item_t *child = ci->children + i;
963 if (strcasecmp ("Address", child->key) == 0)
965 char buffer[NI_MAXHOST];
966 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
968 status = mb_config_set_host_address (host, buffer);
970 host->conntype = MBCONN_TCP;
972 else if (strcasecmp ("Port", child->key) == 0)
974 host->port = cf_util_get_port_number (child);
978 else if (strcasecmp ("Device", child->key) == 0)
980 status = cf_util_get_string_buffer (child, host->node, sizeof (host->node));
982 host->conntype = MBCONN_RTU;
984 else if (strcasecmp ("Baudrate", child->key) == 0)
985 status = cf_util_get_int(child, &host->baudrate);
986 else if (strcasecmp ("Interval", child->key) == 0)
987 status = cf_util_get_cdtime (child, &host->interval);
988 else if (strcasecmp ("Slave", child->key) == 0)
989 /* Don't set status: Gracefully continue if a slave fails. */
990 mb_config_add_slave (host, child);
993 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
999 } /* for (i = 0; i < ci->children_num; i++) */
1001 assert (host->host[0] != 0);
1002 if (host->node[0] == 0)
1004 ERROR ("Modbus plugin: Data block \"%s\": No address or device has been specified.",
1008 if (host->conntype == MBCONN_RTU && !host->baudrate)
1010 ERROR ("Modbus plugin: Data block \"%s\": No serial baudrate has been specified.",
1014 if ((host->conntype == MBCONN_TCP && host->baudrate) ||
1015 (host->conntype == MBCONN_RTU && host->port))
1017 ERROR ("Modbus plugin: Data block \"%s\": You've mixed up RTU and TCP options.",
1028 ud.free_func = host_free;
1030 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
1032 plugin_register_complex_read (/* group = */ NULL, name,
1033 /* callback = */ mb_read,
1034 /* interval = */ host->interval,
1043 } /* }}} int mb_config_add_host */
1045 static int mb_config (oconfig_item_t *ci) /* {{{ */
1052 for (i = 0; i < ci->children_num; i++)
1054 oconfig_item_t *child = ci->children + i;
1056 if (strcasecmp ("Data", child->key) == 0)
1057 mb_config_add_data (child);
1058 else if (strcasecmp ("Host", child->key) == 0)
1059 mb_config_add_host (child);
1061 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1065 } /* }}} int mb_config */
1069 static int mb_shutdown (void) /* {{{ */
1071 data_free_all (data_definitions);
1072 data_definitions = NULL;
1075 } /* }}} int mb_shutdown */
1077 void module_register (void)
1079 plugin_register_complex_config ("modbus", mb_config);
1080 plugin_register_shutdown ("modbus", mb_shutdown);
1081 } /* void module_register */
1083 /* vim: set sw=2 sts=2 et fdm=marker : */