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 /* {{{ */
81 REG_TYPE_FLOAT }; /* }}} */
82 enum mb_mreg_type_e /* {{{ */
84 MREG_INPUT }; /* }}} */
85 typedef enum mb_register_type_e mb_register_type_t;
86 typedef enum mb_mreg_type_e mb_mreg_type_t;
88 /* TCP or RTU depending on what is specified in host config block */
89 enum mb_conntype_e /* {{{ */
91 MBCONN_RTU }; /* }}} */
92 typedef enum mb_conntype_e mb_conntype_t;
95 typedef struct mb_data_s mb_data_t;
96 struct mb_data_s /* {{{ */
100 mb_register_type_t register_type;
101 mb_mreg_type_t modbus_register_type;
102 char type[DATA_MAX_NAME_LEN];
103 char instance[DATA_MAX_NAME_LEN];
108 struct mb_slave_s /* {{{ */
111 char instance[DATA_MAX_NAME_LEN];
114 typedef struct mb_slave_s mb_slave_t;
116 struct mb_host_s /* {{{ */
118 char host[DATA_MAX_NAME_LEN];
119 char node[NI_MAXHOST]; /* TCP hostname or RTU serial device */
120 /* char service[NI_MAXSERV]; */
121 int port; /* for Modbus/TCP */
122 int baudrate; /* for Modbus/RTU */
123 mb_conntype_t conntype;
130 modbus_param_t connection;
132 modbus_t *connection;
136 typedef struct mb_host_s mb_host_t;
138 struct mb_data_group_s;
139 typedef struct mb_data_group_s mb_data_group_t;
140 struct mb_data_group_s /* {{{ */
142 mb_data_t *registers;
143 size_t registers_num;
145 mb_data_group_t *next;
151 static mb_data_t *data_definitions = NULL;
156 static mb_data_t *data_get_by_name(mb_data_t *src, /* {{{ */
161 for (mb_data_t *ptr = src; ptr != NULL; ptr = ptr->next)
162 if (strcasecmp(ptr->name, name) == 0)
166 } /* }}} mb_data_t *data_get_by_name */
168 static int data_append(mb_data_t **dst, mb_data_t *src) /* {{{ */
172 if ((dst == NULL) || (src == NULL))
182 while (ptr->next != NULL)
188 } /* }}} int data_append */
190 /* Copy a single mb_data_t and append it to another list. */
191 static int data_copy(mb_data_t **dst, const mb_data_t *src) /* {{{ */
196 if ((dst == NULL) || (src == NULL))
199 tmp = malloc(sizeof(*tmp));
202 memcpy(tmp, src, sizeof(*tmp));
206 tmp->name = strdup(src->name);
207 if (tmp->name == NULL) {
212 status = data_append(dst, tmp);
220 } /* }}} int data_copy */
222 /* Lookup a single mb_data_t instance, copy it and append the copy to another
224 static int data_copy_by_name(mb_data_t **dst, mb_data_t *src, /* {{{ */
228 if ((dst == NULL) || (src == NULL) || (name == NULL))
231 ptr = data_get_by_name(src, name);
235 return (data_copy(dst, ptr));
236 } /* }}} int data_copy_by_name */
240 static int mb_submit(mb_host_t *host, mb_slave_t *slave, /* {{{ */
241 mb_data_t *data, value_t value) {
242 value_list_t vl = VALUE_LIST_INIT;
244 if ((host == NULL) || (slave == NULL) || (data == NULL))
247 if (host->interval == 0)
248 host->interval = plugin_get_interval();
250 if (slave->instance[0] == 0)
251 ssnprintf(slave->instance, sizeof(slave->instance), "slave_%i", slave->id);
255 vl.interval = host->interval;
256 sstrncpy(vl.host, host->host, sizeof(vl.host));
257 sstrncpy(vl.plugin, "modbus", sizeof(vl.plugin));
258 sstrncpy(vl.plugin_instance, slave->instance, sizeof(vl.plugin_instance));
259 sstrncpy(vl.type, data->type, sizeof(vl.type));
260 sstrncpy(vl.type_instance, data->instance, sizeof(vl.type_instance));
262 return (plugin_dispatch_values(&vl));
263 } /* }}} int mb_submit */
265 static float mb_register_to_float(uint16_t hi, uint16_t lo) /* {{{ */
273 #if BYTE_ORDER == LITTLE_ENDIAN
275 conv.b[0] = lo & 0x00ff;
276 conv.b[1] = (lo >> 8) & 0x00ff;
277 conv.b[2] = hi & 0x00ff;
278 conv.b[3] = (hi >> 8) & 0x00ff;
280 conv.b[3] = lo & 0x00ff;
281 conv.b[2] = (lo >> 8) & 0x00ff;
282 conv.b[1] = hi & 0x00ff;
283 conv.b[0] = (hi >> 8) & 0x00ff;
287 } /* }}} float mb_register_to_float */
291 static int mb_init_connection(mb_host_t *host) /* {{{ */
299 modbus_set_debug(&host->connection, 1);
302 /* We'll do the error handling ourselves. */
303 modbus_set_error_handling(&host->connection, NOP_ON_ERROR);
305 if (host->conntype == MBCONN_TCP) {
306 if ((host->port < 1) || (host->port > 65535))
307 host->port = MODBUS_TCP_DEFAULT_PORT;
309 DEBUG("Modbus plugin: Trying to connect to \"%s\", port %i.", host->node,
312 modbus_init_tcp(&host->connection,
313 /* host = */ host->node,
314 /* port = */ host->port);
315 } else /* MBCONN_RTU */
317 DEBUG("Modbus plugin: Trying to connect to \"%s\".", host->node);
319 modbus_init_rtu(&host->connection,
320 /* device = */ host->node,
321 /* baudrate = */ host->baudrate, 'N', 8, 1, 0);
324 status = modbus_connect(&host->connection);
326 ERROR("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
327 host->node, host->port ? host->port : host->baudrate, status);
331 host->is_connected = 1;
333 } /* }}} int mb_init_connection */
334 /* #endif LEGACY_LIBMODBUS */
336 #else /* if !LEGACY_LIBMODBUS */
338 static int mb_init_connection(mb_host_t *host) /* {{{ */
345 if (host->connection != NULL)
348 if (host->conntype == MBCONN_TCP) {
349 if ((host->port < 1) || (host->port > 65535))
350 host->port = MODBUS_TCP_DEFAULT_PORT;
352 DEBUG("Modbus plugin: Trying to connect to \"%s\", port %i.", host->node,
355 host->connection = modbus_new_tcp(host->node, host->port);
356 if (host->connection == NULL) {
357 ERROR("Modbus plugin: Creating new Modbus/TCP object failed.");
361 DEBUG("Modbus plugin: Trying to connect to \"%s\", baudrate %i.",
362 host->node, host->baudrate);
364 host->connection = modbus_new_rtu(host->node, host->baudrate, 'N', 8, 1);
365 if (host->connection == NULL) {
366 ERROR("Modbus plugin: Creating new Modbus/RTU object failed.");
372 modbus_set_debug(host->connection, 1);
375 /* We'll do the error handling ourselves. */
376 modbus_set_error_recovery(host->connection, 0);
378 status = modbus_connect(host->connection);
380 ERROR("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
381 host->node, host->port ? host->port : host->baudrate, status);
382 modbus_free(host->connection);
383 host->connection = NULL;
388 } /* }}} int mb_init_connection */
389 #endif /* !LEGACY_LIBMODBUS */
391 #define CAST_TO_VALUE_T(ds, vt, raw) \
393 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
394 (vt).counter = (counter_t)(raw); \
395 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
396 (vt).gauge = (gauge_t)(raw); \
397 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
398 (vt).derive = (derive_t)(raw); \
399 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
400 (vt).absolute = (absolute_t)(raw); \
403 static int mb_read_data(mb_host_t *host, mb_slave_t *slave, /* {{{ */
405 uint16_t values[2] = {0};
407 const data_set_t *ds;
410 if ((host == NULL) || (slave == NULL) || (data == NULL))
413 ds = plugin_get_ds(data->type);
415 ERROR("Modbus plugin: Type \"%s\" is not defined.", data->type);
419 if (ds->ds_num != 1) {
420 ERROR("Modbus plugin: The type \"%s\" has %zu data sources. "
421 "I can only handle data sets with only one data source.",
422 data->type, ds->ds_num);
426 if ((ds->ds[0].type != DS_TYPE_GAUGE) &&
427 (data->register_type != REG_TYPE_INT32) &&
428 (data->register_type != REG_TYPE_UINT32)) {
430 "Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
431 "This will most likely result in problems, because the register type "
433 data->type, DS_TYPE_TO_STRING(ds->ds[0].type));
436 if ((data->register_type == REG_TYPE_INT32) ||
437 (data->register_type == REG_TYPE_UINT32) ||
438 (data->register_type == REG_TYPE_FLOAT))
443 if (host->connection == NULL) {
445 } else if (host->conntype == MBCONN_TCP) {
446 if (getpeername(modbus_get_socket(host->connection),
447 (void *)&(struct sockaddr_storage){0},
448 &(socklen_t){sizeof(struct sockaddr_storage)}) != 0)
452 if ((status == EBADF) || (status == ENOTSOCK) || (status == ENOTCONN)) {
453 status = mb_init_connection(host);
455 ERROR("Modbus plugin: mb_init_connection (%s/%s) failed. ", host->host,
457 host->is_connected = 0;
458 host->connection = NULL;
461 } else if (status != 0) {
463 modbus_close(&host->connection);
465 modbus_close(host->connection);
466 modbus_free(host->connection);
471 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
472 * id to each call of "read_holding_registers". */
473 #define modbus_read_registers(ctx, addr, nb, dest) \
474 read_holding_registers(&(ctx), slave->id, (addr), (nb), (dest))
475 #else /* if !LEGACY_LIBMODBUS */
476 /* Version 2.9.2: Set the slave id once before querying the registers. */
477 status = modbus_set_slave(host->connection, slave->id);
479 ERROR("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
484 if (data->modbus_register_type == MREG_INPUT) {
485 status = modbus_read_input_registers(host->connection,
486 /* start_addr = */ data->register_base,
487 /* num_registers = */ values_num,
488 /* buffer = */ values);
490 status = modbus_read_registers(host->connection,
491 /* start_addr = */ data->register_base,
492 /* num_registers = */ values_num,
493 /* buffer = */ values);
495 if (status != values_num) {
496 ERROR("Modbus plugin: modbus read function (%s/%s) failed. "
497 " status = %i, values_num = %i. Giving up.",
498 host->host, host->node, status, values_num);
500 modbus_close(&host->connection);
502 modbus_close(host->connection);
503 modbus_free(host->connection);
505 host->connection = NULL;
509 DEBUG("Modbus plugin: mb_read_data: Success! "
510 "modbus_read_registers returned with status %i.",
513 if (data->register_type == REG_TYPE_FLOAT) {
517 float_value = mb_register_to_float(values[0], values[1]);
518 DEBUG("Modbus plugin: mb_read_data: "
519 "Returned float value is %g",
520 (double)float_value);
522 CAST_TO_VALUE_T(ds, vt, float_value);
523 mb_submit(host, slave, data, vt);
524 } else if (data->register_type == REG_TYPE_INT32) {
531 v.u32 = (((uint32_t)values[0]) << 16) | ((uint32_t)values[1]);
532 DEBUG("Modbus plugin: mb_read_data: "
533 "Returned int32 value is %" PRIi32,
536 CAST_TO_VALUE_T(ds, vt, v.i32);
537 mb_submit(host, slave, data, vt);
538 } else if (data->register_type == REG_TYPE_INT16) {
547 DEBUG("Modbus plugin: mb_read_data: "
548 "Returned int16 value is %" PRIi16,
551 CAST_TO_VALUE_T(ds, vt, v.i16);
552 mb_submit(host, slave, data, vt);
553 } else if (data->register_type == REG_TYPE_UINT32) {
557 v32 = (((uint32_t)values[0]) << 16) | ((uint32_t)values[1]);
558 DEBUG("Modbus plugin: mb_read_data: "
559 "Returned uint32 value is %" PRIu32,
562 CAST_TO_VALUE_T(ds, vt, v32);
563 mb_submit(host, slave, data, vt);
564 } else /* if (data->register_type == REG_TYPE_UINT16) */
568 DEBUG("Modbus plugin: mb_read_data: "
569 "Returned uint16 value is %" PRIu16,
572 CAST_TO_VALUE_T(ds, vt, values[0]);
573 mb_submit(host, slave, data, vt);
577 } /* }}} int mb_read_data */
579 static int mb_read_slave(mb_host_t *host, mb_slave_t *slave) /* {{{ */
584 if ((host == NULL) || (slave == NULL))
588 for (mb_data_t *data = slave->collect; data != NULL; data = data->next) {
589 status = mb_read_data(host, slave, data);
598 } /* }}} int mb_read_slave */
600 static int mb_read(user_data_t *user_data) /* {{{ */
606 if ((user_data == NULL) || (user_data->data == NULL))
609 host = user_data->data;
612 for (size_t i = 0; i < host->slaves_num; i++) {
613 status = mb_read_slave(host, host->slaves + i);
622 } /* }}} int mb_read */
626 static void data_free_one(mb_data_t *data) /* {{{ */
633 } /* }}} void data_free_one */
635 static void data_free_all(mb_data_t *data) /* {{{ */
646 } /* }}} void data_free_all */
648 static void slaves_free_all(mb_slave_t *slaves, size_t slaves_num) /* {{{ */
653 for (size_t 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) /* {{{ */
673 mb_data_t data = {0};
677 data.register_type = REG_TYPE_UINT16;
680 status = cf_util_get_string(ci, &data.name);
684 for (int i = 0; i < ci->children_num; i++) {
685 oconfig_item_t *child = ci->children + i;
687 if (strcasecmp("Type", child->key) == 0)
688 status = cf_util_get_string_buffer(child, data.type, sizeof(data.type));
689 else if (strcasecmp("Instance", child->key) == 0)
690 status = cf_util_get_string_buffer(child, data.instance,
691 sizeof(data.instance));
692 else if (strcasecmp("RegisterBase", child->key) == 0)
693 status = cf_util_get_int(child, &data.register_base);
694 else if (strcasecmp("RegisterType", child->key) == 0) {
696 status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
699 else if (strcasecmp("Int16", tmp) == 0)
700 data.register_type = REG_TYPE_INT16;
701 else if (strcasecmp("Int32", tmp) == 0)
702 data.register_type = REG_TYPE_INT32;
703 else if (strcasecmp("Uint16", tmp) == 0)
704 data.register_type = REG_TYPE_UINT16;
705 else if (strcasecmp("Uint32", tmp) == 0)
706 data.register_type = REG_TYPE_UINT32;
707 else if (strcasecmp("Float", tmp) == 0)
708 data.register_type = REG_TYPE_FLOAT;
710 ERROR("Modbus plugin: The register type \"%s\" is unknown.", tmp);
713 } else if (strcasecmp("RegisterCmd", child->key) == 0) {
715 ERROR("Modbus plugin: RegisterCmd parameter can not be used "
716 "with your libmodbus version");
719 status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
722 else if (strcasecmp("ReadHolding", tmp) == 0)
723 data.modbus_register_type = MREG_HOLDING;
724 else if (strcasecmp("ReadInput", tmp) == 0)
725 data.modbus_register_type = MREG_INPUT;
727 ERROR("Modbus plugin: The modbus_register_type \"%s\" is unknown.",
733 ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
739 } /* for (i = 0; i < ci->children_num; i++) */
741 assert(data.name != NULL);
742 if (data.type[0] == 0) {
743 ERROR("Modbus plugin: Data block \"%s\": No type has been specified.",
749 data_copy(&data_definitions, &data);
754 } /* }}} int mb_config_add_data */
756 static int mb_config_set_host_address(mb_host_t *host, /* {{{ */
757 const char *address) {
758 struct addrinfo *ai_list;
761 if ((host == NULL) || (address == NULL))
764 struct addrinfo ai_hints = {
765 /* XXX: libmodbus can only handle IPv4 addresses. */
766 .ai_family = AF_INET,
767 .ai_flags = AI_ADDRCONFIG};
769 status = getaddrinfo(address, /* service = */ NULL, &ai_hints, &ai_list);
772 ERROR("Modbus plugin: getaddrinfo failed: %s",
773 (status == EAI_SYSTEM) ? sstrerror(errno, errbuf, sizeof(errbuf))
774 : gai_strerror(status));
778 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
779 ai_ptr = ai_ptr->ai_next) {
780 status = getnameinfo(ai_ptr->ai_addr, ai_ptr->ai_addrlen, host->node,
782 /* service = */ NULL, /* length = */ 0,
783 /* flags = */ NI_NUMERICHOST);
788 freeaddrinfo(ai_list);
791 ERROR("Modbus plugin: Unable to translate node name: \"%s\"", address);
792 else /* if (status == 0) */
794 DEBUG("Modbus plugin: mb_config_set_host_address: %s -> %s", address,
799 } /* }}} int mb_config_set_host_address */
801 static int mb_config_add_slave(mb_host_t *host, oconfig_item_t *ci) /* {{{ */
806 if ((host == NULL) || (ci == NULL))
809 slave = realloc(host->slaves, sizeof(*slave) * (host->slaves_num + 1));
812 host->slaves = slave;
813 slave = host->slaves + host->slaves_num;
814 memset(slave, 0, sizeof(*slave));
815 slave->collect = NULL;
817 status = cf_util_get_int(ci, &slave->id);
821 for (int i = 0; i < ci->children_num; i++) {
822 oconfig_item_t *child = ci->children + i;
824 if (strcasecmp("Instance", child->key) == 0)
825 status = cf_util_get_string_buffer(child, slave->instance,
826 sizeof(slave->instance));
827 else if (strcasecmp("Collect", child->key) == 0) {
829 status = cf_util_get_string_buffer(child, buffer, sizeof(buffer));
831 data_copy_by_name(&slave->collect, data_definitions, buffer);
832 status = 0; /* continue after failure. */
834 ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
842 if ((status == 0) && (slave->collect == NULL))
850 else /* if (status != 0) */
851 data_free_all(slave->collect);
854 } /* }}} int mb_config_add_slave */
856 static int mb_config_add_host(oconfig_item_t *ci) /* {{{ */
861 host = calloc(1, sizeof(*host));
866 status = cf_util_get_string_buffer(ci, host->host, sizeof(host->host));
871 if (host->host[0] == 0) {
876 for (int i = 0; i < ci->children_num; i++) {
877 oconfig_item_t *child = ci->children + i;
880 if (strcasecmp("Address", child->key) == 0) {
881 char buffer[NI_MAXHOST];
882 status = cf_util_get_string_buffer(child, buffer, sizeof(buffer));
884 status = mb_config_set_host_address(host, buffer);
886 host->conntype = MBCONN_TCP;
887 } else if (strcasecmp("Port", child->key) == 0) {
888 host->port = cf_util_get_port_number(child);
891 } else if (strcasecmp("Device", child->key) == 0) {
892 status = cf_util_get_string_buffer(child, host->node, sizeof(host->node));
894 host->conntype = MBCONN_RTU;
895 } else if (strcasecmp("Baudrate", child->key) == 0)
896 status = cf_util_get_int(child, &host->baudrate);
897 else if (strcasecmp("Interval", child->key) == 0)
898 status = cf_util_get_cdtime(child, &host->interval);
899 else if (strcasecmp("Slave", child->key) == 0)
900 /* Don't set status: Gracefully continue if a slave fails. */
901 mb_config_add_slave(host, child);
903 ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
909 } /* for (i = 0; i < ci->children_num; i++) */
911 assert(host->host[0] != 0);
912 if (host->node[0] == 0) {
913 ERROR("Modbus plugin: Data block \"%s\": No address or device has been "
918 if (host->conntype == MBCONN_RTU && !host->baudrate) {
919 ERROR("Modbus plugin: Data block \"%s\": No serial baudrate has been "
924 if ((host->conntype == MBCONN_TCP && host->baudrate) ||
925 (host->conntype == MBCONN_RTU && host->port)) {
926 ERROR("Modbus plugin: Data block \"%s\": You've mixed up RTU and TCP "
937 ud.free_func = host_free;
939 ssnprintf(name, sizeof(name), "modbus-%s", host->host);
941 plugin_register_complex_read(/* group = */ NULL, name,
942 /* callback = */ mb_read,
943 /* interval = */ host->interval, &ud);
949 } /* }}} int mb_config_add_host */
951 static int mb_config(oconfig_item_t *ci) /* {{{ */
956 for (int i = 0; i < ci->children_num; i++) {
957 oconfig_item_t *child = ci->children + i;
959 if (strcasecmp("Data", child->key) == 0)
960 mb_config_add_data(child);
961 else if (strcasecmp("Host", child->key) == 0)
962 mb_config_add_host(child);
964 ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
968 } /* }}} int mb_config */
972 static int mb_shutdown(void) /* {{{ */
974 data_free_all(data_definitions);
975 data_definitions = NULL;
978 } /* }}} int mb_shutdown */
980 void module_register(void) {
981 plugin_register_complex_config("modbus", mb_config);
982 plugin_register_shutdown("modbus", mb_shutdown);
983 } /* void module_register */
985 /* vim: set sw=2 sts=2 et fdm=marker : */