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"
31 #include <sys/socket.h>
33 #ifndef LIBMODBUS_VERSION_CHECK
34 /* Assume version 2.0.3 */
35 # define LEGACY_LIBMODBUS 1
37 /* Assume version 2.9.2 */
40 #ifndef MODBUS_TCP_DEFAULT_PORT
41 # ifdef MODBUS_TCP_PORT
42 # define MODBUS_TCP_DEFAULT_PORT MODBUS_TCP_PORT
44 # define MODBUS_TCP_DEFAULT_PORT 502
51 * RegisterCmd ReadHolding
61 * # Device "/dev/ttyUSB0"
67 * Instance "foobar" # optional
76 enum mb_register_type_e /* {{{ */
84 enum mb_mreg_type_e /* {{{ */
89 typedef enum mb_register_type_e mb_register_type_t;
90 typedef enum mb_mreg_type_e mb_mreg_type_t;
92 /* TCP or RTU depending on what is specified in host config block */
93 enum mb_conntype_e /* {{{ */
98 typedef enum mb_conntype_e mb_conntype_t;
101 typedef struct mb_data_s mb_data_t;
102 struct mb_data_s /* {{{ */
106 mb_register_type_t register_type;
107 mb_mreg_type_t modbus_register_type;
108 char type[DATA_MAX_NAME_LEN];
109 char instance[DATA_MAX_NAME_LEN];
114 struct mb_slave_s /* {{{ */
117 char instance[DATA_MAX_NAME_LEN];
120 typedef struct mb_slave_s mb_slave_t;
122 struct mb_host_s /* {{{ */
124 char host[DATA_MAX_NAME_LEN];
125 char node[NI_MAXHOST]; /* TCP hostname or RTU serial device */
126 /* char service[NI_MAXSERV]; */
127 int port; /* for Modbus/TCP */
128 int baudrate; /* for Modbus/RTU */
129 mb_conntype_t conntype;
136 modbus_param_t connection;
138 modbus_t *connection;
142 typedef struct mb_host_s mb_host_t;
144 struct mb_data_group_s;
145 typedef struct mb_data_group_s mb_data_group_t;
146 struct mb_data_group_s /* {{{ */
148 mb_data_t *registers;
149 size_t registers_num;
151 mb_data_group_t *next;
157 static mb_data_t *data_definitions = NULL;
162 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
170 for (ptr = src; ptr != NULL; ptr = ptr->next)
171 if (strcasecmp (ptr->name, name) == 0)
175 } /* }}} mb_data_t *data_get_by_name */
177 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
181 if ((dst == NULL) || (src == NULL))
192 while (ptr->next != NULL)
198 } /* }}} int data_append */
200 /* Copy a single mb_data_t and append it to another list. */
201 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
206 if ((dst == NULL) || (src == NULL))
209 tmp = malloc (sizeof (*tmp));
212 memcpy (tmp, src, sizeof (*tmp));
216 tmp->name = strdup (src->name);
217 if (tmp->name == NULL)
223 status = data_append (dst, tmp);
232 } /* }}} int data_copy */
234 /* Lookup a single mb_data_t instance, copy it and append the copy to another
236 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
241 if ((dst == NULL) || (src == NULL) || (name == NULL))
244 ptr = data_get_by_name (src, name);
248 return (data_copy (dst, ptr));
249 } /* }}} int data_copy_by_name */
253 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
254 mb_data_t *data, value_t value)
256 value_list_t vl = VALUE_LIST_INIT;
258 if ((host == NULL) || (slave == NULL) || (data == NULL))
261 if (host->interval <= 0)
262 host->interval = plugin_get_interval ();
264 if (slave->instance[0] == 0)
265 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
270 vl.interval = host->interval;
271 sstrncpy (vl.host, host->host, sizeof (vl.host));
272 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
273 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
274 sstrncpy (vl.type, data->type, sizeof (vl.type));
275 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
277 return (plugin_dispatch_values (&vl));
278 } /* }}} int mb_submit */
280 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
289 #if BYTE_ORDER == LITTLE_ENDIAN
291 conv.b[0] = lo & 0x00ff;
292 conv.b[1] = (lo >> 8) & 0x00ff;
293 conv.b[2] = hi & 0x00ff;
294 conv.b[3] = (hi >> 8) & 0x00ff;
296 conv.b[3] = lo & 0x00ff;
297 conv.b[2] = (lo >> 8) & 0x00ff;
298 conv.b[1] = hi & 0x00ff;
299 conv.b[0] = (hi >> 8) & 0x00ff;
303 } /* }}} float mb_register_to_float */
307 static int mb_init_connection (mb_host_t *host) /* {{{ */
315 modbus_set_debug (&host->connection, 1);
318 /* We'll do the error handling ourselves. */
319 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
321 if (host->conntype == MBCONN_TCP)
323 if ((host->port < 1) || (host->port > 65535))
324 host->port = MODBUS_TCP_DEFAULT_PORT;
326 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
327 host->node, host->port);
329 modbus_init_tcp (&host->connection,
330 /* host = */ host->node,
331 /* port = */ host->port);
333 else /* MBCONN_RTU */
335 DEBUG ("Modbus plugin: Trying to connect to \"%s\".", host->node);
337 modbus_init_rtu (&host->connection,
338 /* device = */ host->node,
339 /* baudrate = */ host->baudrate,
343 status = modbus_connect (&host->connection);
346 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
347 host->node, host->port ? host->port : host->baudrate, status);
351 host->is_connected = 1;
353 } /* }}} int mb_init_connection */
354 /* #endif LEGACY_LIBMODBUS */
356 #else /* if !LEGACY_LIBMODBUS */
358 static int mb_init_connection (mb_host_t *host) /* {{{ */
365 if (host->connection != NULL)
368 if (host->conntype == MBCONN_TCP)
370 if ((host->port < 1) || (host->port > 65535))
371 host->port = MODBUS_TCP_DEFAULT_PORT;
373 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
374 host->node, host->port);
376 host->connection = modbus_new_tcp (host->node, host->port);
377 if (host->connection == NULL)
379 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
385 DEBUG ("Modbus plugin: Trying to connect to \"%s\", baudrate %i.",
386 host->node, host->baudrate);
388 host->connection = modbus_new_rtu (host->node, host->baudrate, 'N', 8, 1);
389 if (host->connection == NULL)
391 ERROR ("Modbus plugin: Creating new Modbus/RTU object failed.");
397 modbus_set_debug (host->connection, 1);
400 /* We'll do the error handling ourselves. */
401 modbus_set_error_recovery (host->connection, 0);
403 status = modbus_connect (host->connection);
406 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
407 host->node, host->port ? host->port : host->baudrate, status);
408 modbus_free (host->connection);
409 host->connection = NULL;
414 } /* }}} int mb_init_connection */
415 #endif /* !LEGACY_LIBMODBUS */
417 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
418 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
419 (vt).counter = (counter_t) (raw); \
420 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
421 (vt).gauge = (gauge_t) (raw); \
422 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
423 (vt).derive = (derive_t) (raw); \
424 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
425 (vt).absolute = (absolute_t) (raw); \
428 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
433 const data_set_t *ds;
436 if ((host == NULL) || (slave == NULL) || (data == NULL))
439 ds = plugin_get_ds (data->type);
442 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
448 ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
449 "I can only handle data sets with only one data source.",
450 data->type, ds->ds_num);
454 if ((ds->ds[0].type != DS_TYPE_GAUGE)
455 && (data->register_type != REG_TYPE_INT32)
456 && (data->register_type != REG_TYPE_UINT32))
458 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
459 "This will most likely result in problems, because the register type "
460 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
463 memset (values, 0, sizeof (values));
464 if ((data->register_type == REG_TYPE_INT32)
465 || (data->register_type == REG_TYPE_UINT32)
466 || (data->register_type == REG_TYPE_FLOAT))
471 if (host->connection == NULL)
475 else if (host->conntype == MBCONN_TCP)
477 if (getpeername (modbus_get_socket (host->connection),
478 (void *) &(struct sockaddr_storage) {0},
479 &(socklen_t) {sizeof(struct sockaddr_storage)}) != 0)
483 if ((status == EBADF) || (status == ENOTSOCK) || (status == ENOTCONN))
485 status = mb_init_connection (host);
488 ERROR ("Modbus plugin: mb_init_connection (%s/%s) failed. ",
489 host->host, host->node);
490 host->is_connected = 0;
491 host->connection = NULL;
495 else if (status != 0)
498 modbus_close (&host->connection);
500 modbus_close (host->connection);
501 modbus_free (host->connection);
506 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
507 * id to each call of "read_holding_registers". */
508 # define modbus_read_registers(ctx, addr, nb, dest) \
509 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
510 #else /* if !LEGACY_LIBMODBUS */
511 /* Version 2.9.2: Set the slave id once before querying the registers. */
512 status = modbus_set_slave (host->connection, slave->id);
515 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
520 if (data->modbus_register_type == MREG_INPUT){
521 status = modbus_read_input_registers (host->connection,
522 /* start_addr = */ data->register_base,
523 /* num_registers = */ values_num, /* buffer = */ values);
526 status = modbus_read_registers (host->connection,
527 /* start_addr = */ data->register_base,
528 /* num_registers = */ values_num, /* buffer = */ values);
530 if (status != values_num)
532 ERROR ("Modbus plugin: modbus read function (%s/%s) failed. "
533 " status = %i, values_num = %i. Giving up.",
534 host->host, host->node, status, values_num);
536 modbus_close (&host->connection);
538 modbus_close (host->connection);
539 modbus_free (host->connection);
541 host->connection = NULL;
545 DEBUG ("Modbus plugin: mb_read_data: Success! "
546 "modbus_read_registers returned with status %i.", status);
548 if (data->register_type == REG_TYPE_FLOAT)
553 float_value = mb_register_to_float (values[0], values[1]);
554 DEBUG ("Modbus plugin: mb_read_data: "
555 "Returned float value is %g", (double) float_value);
557 CAST_TO_VALUE_T (ds, vt, float_value);
558 mb_submit (host, slave, data, vt);
560 else if (data->register_type == REG_TYPE_INT32)
569 v.u32 = (((uint32_t) values[0]) << 16)
570 | ((uint32_t) values[1]);
571 DEBUG ("Modbus plugin: mb_read_data: "
572 "Returned int32 value is %"PRIi32, v.i32);
574 CAST_TO_VALUE_T (ds, vt, v.i32);
575 mb_submit (host, slave, data, vt);
577 else if (data->register_type == REG_TYPE_INT16)
588 DEBUG ("Modbus plugin: mb_read_data: "
589 "Returned int16 value is %"PRIi16, v.i16);
591 CAST_TO_VALUE_T (ds, vt, v.i16);
592 mb_submit (host, slave, data, vt);
594 else if (data->register_type == REG_TYPE_UINT32)
599 v32 = (((uint32_t) values[0]) << 16)
600 | ((uint32_t) values[1]);
601 DEBUG ("Modbus plugin: mb_read_data: "
602 "Returned uint32 value is %"PRIu32, v32);
604 CAST_TO_VALUE_T (ds, vt, v32);
605 mb_submit (host, slave, data, vt);
607 else /* if (data->register_type == REG_TYPE_UINT16) */
611 DEBUG ("Modbus plugin: mb_read_data: "
612 "Returned uint16 value is %"PRIu16, values[0]);
614 CAST_TO_VALUE_T (ds, vt, values[0]);
615 mb_submit (host, slave, data, vt);
619 } /* }}} int mb_read_data */
621 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
627 if ((host == NULL) || (slave == NULL))
631 for (data = slave->collect; data != NULL; data = data->next)
633 status = mb_read_data (host, slave, data);
642 } /* }}} int mb_read_slave */
644 static int mb_read (user_data_t *user_data) /* {{{ */
651 if ((user_data == NULL) || (user_data->data == NULL))
654 host = user_data->data;
657 for (i = 0; i < host->slaves_num; i++)
659 status = mb_read_slave (host, host->slaves + i);
668 } /* }}} int mb_read */
672 static void data_free_one (mb_data_t *data) /* {{{ */
679 } /* }}} void data_free_one */
681 static void data_free_all (mb_data_t *data) /* {{{ */
689 data_free_one (data);
691 data_free_all (next);
692 } /* }}} void data_free_all */
694 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
701 for (i = 0; i < slaves_num; i++)
702 data_free_all (slaves[i].collect);
704 } /* }}} void slaves_free_all */
706 static void host_free (void *void_host) /* {{{ */
708 mb_host_t *host = void_host;
713 slaves_free_all (host->slaves, host->slaves_num);
715 } /* }}} void host_free */
717 /* Config functions */
719 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
725 memset (&data, 0, sizeof (data));
727 data.register_type = REG_TYPE_UINT16;
730 status = cf_util_get_string (ci, &data.name);
734 for (i = 0; i < ci->children_num; i++)
736 oconfig_item_t *child = ci->children + i;
738 if (strcasecmp ("Type", child->key) == 0)
739 status = cf_util_get_string_buffer (child,
740 data.type, sizeof (data.type));
741 else if (strcasecmp ("Instance", child->key) == 0)
742 status = cf_util_get_string_buffer (child,
743 data.instance, sizeof (data.instance));
744 else if (strcasecmp ("RegisterBase", child->key) == 0)
745 status = cf_util_get_int (child, &data.register_base);
746 else if (strcasecmp ("RegisterType", child->key) == 0)
749 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
752 else if (strcasecmp ("Int16", tmp) == 0)
753 data.register_type = REG_TYPE_INT16;
754 else if (strcasecmp ("Int32", tmp) == 0)
755 data.register_type = REG_TYPE_INT32;
756 else if (strcasecmp ("Uint16", tmp) == 0)
757 data.register_type = REG_TYPE_UINT16;
758 else if (strcasecmp ("Uint32", tmp) == 0)
759 data.register_type = REG_TYPE_UINT32;
760 else if (strcasecmp ("Float", tmp) == 0)
761 data.register_type = REG_TYPE_FLOAT;
764 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
768 else if (strcasecmp ("RegisterCmd", child->key) == 0)
771 ERROR("Modbus plugin: RegisterCmd parameter can not be used "
772 "with your libmodbus version");
775 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
778 else if (strcasecmp ("ReadHolding", tmp) == 0)
779 data.modbus_register_type = MREG_HOLDING;
780 else if (strcasecmp ("ReadInput", tmp) == 0)
781 data.modbus_register_type = MREG_INPUT;
784 ERROR ("Modbus plugin: The modbus_register_type \"%s\" is unknown.",
792 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
798 } /* for (i = 0; i < ci->children_num; i++) */
800 assert (data.name != NULL);
801 if (data.type[0] == 0)
803 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
809 data_copy (&data_definitions, &data);
814 } /* }}} int mb_config_add_data */
816 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
819 struct addrinfo *ai_list;
820 struct addrinfo *ai_ptr;
821 struct addrinfo ai_hints;
824 if ((host == NULL) || (address == NULL))
827 memset (&ai_hints, 0, sizeof (ai_hints));
829 ai_hints.ai_flags |= AI_ADDRCONFIG;
831 /* XXX: libmodbus can only handle IPv4 addresses. */
832 ai_hints.ai_family = AF_INET;
833 ai_hints.ai_addr = NULL;
834 ai_hints.ai_canonname = NULL;
835 ai_hints.ai_next = NULL;
838 status = getaddrinfo (address, /* service = */ NULL,
839 &ai_hints, &ai_list);
843 ERROR ("Modbus plugin: getaddrinfo failed: %s",
844 (status == EAI_SYSTEM)
845 ? sstrerror (errno, errbuf, sizeof (errbuf))
846 : gai_strerror (status));
850 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
852 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
853 host->node, sizeof (host->node),
854 /* service = */ NULL, /* length = */ 0,
855 /* flags = */ NI_NUMERICHOST);
860 freeaddrinfo (ai_list);
863 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
864 else /* if (status == 0) */
866 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
867 address, host->node);
871 } /* }}} int mb_config_set_host_address */
873 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
879 if ((host == NULL) || (ci == NULL))
882 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
885 host->slaves = slave;
886 slave = host->slaves + host->slaves_num;
887 memset (slave, 0, sizeof (*slave));
888 slave->collect = NULL;
890 status = cf_util_get_int (ci, &slave->id);
894 for (i = 0; i < ci->children_num; i++)
896 oconfig_item_t *child = ci->children + i;
898 if (strcasecmp ("Instance", child->key) == 0)
899 status = cf_util_get_string_buffer (child,
900 slave->instance, sizeof (slave->instance));
901 else if (strcasecmp ("Collect", child->key) == 0)
904 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
906 data_copy_by_name (&slave->collect, data_definitions, buffer);
907 status = 0; /* continue after failure. */
911 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
919 if ((status == 0) && (slave->collect == NULL))
927 else /* if (status != 0) */
928 data_free_all (slave->collect);
931 } /* }}} int mb_config_add_slave */
933 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
939 host = malloc (sizeof (*host));
942 memset (host, 0, sizeof (*host));
945 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
951 if (host->host[0] == 0)
957 for (i = 0; i < ci->children_num; i++)
959 oconfig_item_t *child = ci->children + i;
962 if (strcasecmp ("Address", child->key) == 0)
964 char buffer[NI_MAXHOST];
965 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
967 status = mb_config_set_host_address (host, buffer);
969 host->conntype = MBCONN_TCP;
971 else if (strcasecmp ("Port", child->key) == 0)
973 host->port = cf_util_get_port_number (child);
977 else if (strcasecmp ("Device", child->key) == 0)
979 status = cf_util_get_string_buffer (child, host->node, sizeof (host->node));
981 host->conntype = MBCONN_RTU;
983 else if (strcasecmp ("Baudrate", child->key) == 0)
984 status = cf_util_get_int(child, &host->baudrate);
985 else if (strcasecmp ("Interval", child->key) == 0)
986 status = cf_util_get_cdtime (child, &host->interval);
987 else if (strcasecmp ("Slave", child->key) == 0)
988 /* Don't set status: Gracefully continue if a slave fails. */
989 mb_config_add_slave (host, child);
992 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
998 } /* for (i = 0; i < ci->children_num; i++) */
1000 assert (host->host[0] != 0);
1001 if (host->node[0] == 0)
1003 ERROR ("Modbus plugin: Data block \"%s\": No address or device has been specified.",
1007 if (host->conntype == MBCONN_RTU && !host->baudrate)
1009 ERROR ("Modbus plugin: Data block \"%s\": No serial baudrate has been specified.",
1013 if ((host->conntype == MBCONN_TCP && host->baudrate) ||
1014 (host->conntype == MBCONN_RTU && host->port))
1016 ERROR ("Modbus plugin: Data block \"%s\": You've mixed up RTU and TCP options.",
1025 struct timespec interval = { 0, 0 };
1028 ud.free_func = host_free;
1030 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
1032 CDTIME_T_TO_TIMESPEC (host->interval, &interval);
1034 plugin_register_complex_read (/* group = */ NULL, name,
1035 /* callback = */ mb_read,
1036 /* interval = */ (host->interval > 0) ? &interval : NULL,
1045 } /* }}} int mb_config_add_host */
1047 static int mb_config (oconfig_item_t *ci) /* {{{ */
1054 for (i = 0; i < ci->children_num; i++)
1056 oconfig_item_t *child = ci->children + i;
1058 if (strcasecmp ("Data", child->key) == 0)
1059 mb_config_add_data (child);
1060 else if (strcasecmp ("Host", child->key) == 0)
1061 mb_config_add_host (child);
1063 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1067 } /* }}} int mb_config */
1071 static int mb_shutdown (void) /* {{{ */
1073 data_free_all (data_definitions);
1074 data_definitions = NULL;
1077 } /* }}} int mb_shutdown */
1079 void module_register (void)
1081 plugin_register_complex_config ("modbus", mb_config);
1082 plugin_register_shutdown ("modbus", mb_shutdown);
1083 } /* void module_register */
1085 /* vim: set sw=2 sts=2 et fdm=marker : */