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 /* getpeername() is used only to determine if the socket is connected, not
447 * because we're really interested in the peer's IP address. */
448 if (getpeername(modbus_get_socket(host->connection),
449 (void *)&(struct sockaddr_storage){0},
450 &(socklen_t){sizeof(struct sockaddr_storage)}) != 0)
454 if ((status == EBADF) || (status == ENOTSOCK) || (status == ENOTCONN)) {
455 status = mb_init_connection(host);
457 ERROR("Modbus plugin: mb_init_connection (%s/%s) failed. ", host->host,
459 host->is_connected = 0;
460 host->connection = NULL;
463 } else if (status != 0) {
465 modbus_close(&host->connection);
467 modbus_close(host->connection);
468 modbus_free(host->connection);
473 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
474 * id to each call of "read_holding_registers". */
475 #define modbus_read_registers(ctx, addr, nb, dest) \
476 read_holding_registers(&(ctx), slave->id, (addr), (nb), (dest))
477 #else /* if !LEGACY_LIBMODBUS */
478 /* Version 2.9.2: Set the slave id once before querying the registers. */
479 status = modbus_set_slave(host->connection, slave->id);
481 ERROR("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
486 if (data->modbus_register_type == MREG_INPUT) {
487 status = modbus_read_input_registers(host->connection,
488 /* start_addr = */ data->register_base,
489 /* num_registers = */ values_num,
490 /* buffer = */ values);
492 status = modbus_read_registers(host->connection,
493 /* start_addr = */ data->register_base,
494 /* num_registers = */ values_num,
495 /* buffer = */ values);
497 if (status != values_num) {
498 ERROR("Modbus plugin: modbus read function (%s/%s) failed. "
499 " status = %i, values_num = %i. Giving up.",
500 host->host, host->node, status, values_num);
502 modbus_close(&host->connection);
504 modbus_close(host->connection);
505 modbus_free(host->connection);
507 host->connection = NULL;
511 DEBUG("Modbus plugin: mb_read_data: Success! "
512 "modbus_read_registers returned with status %i.",
515 if (data->register_type == REG_TYPE_FLOAT) {
519 float_value = mb_register_to_float(values[0], values[1]);
520 DEBUG("Modbus plugin: mb_read_data: "
521 "Returned float value is %g",
522 (double)float_value);
524 CAST_TO_VALUE_T(ds, vt, float_value);
525 mb_submit(host, slave, data, vt);
526 } else if (data->register_type == REG_TYPE_INT32) {
533 v.u32 = (((uint32_t)values[0]) << 16) | ((uint32_t)values[1]);
534 DEBUG("Modbus plugin: mb_read_data: "
535 "Returned int32 value is %" PRIi32,
538 CAST_TO_VALUE_T(ds, vt, v.i32);
539 mb_submit(host, slave, data, vt);
540 } else if (data->register_type == REG_TYPE_INT16) {
549 DEBUG("Modbus plugin: mb_read_data: "
550 "Returned int16 value is %" PRIi16,
553 CAST_TO_VALUE_T(ds, vt, v.i16);
554 mb_submit(host, slave, data, vt);
555 } else if (data->register_type == REG_TYPE_UINT32) {
559 v32 = (((uint32_t)values[0]) << 16) | ((uint32_t)values[1]);
560 DEBUG("Modbus plugin: mb_read_data: "
561 "Returned uint32 value is %" PRIu32,
564 CAST_TO_VALUE_T(ds, vt, v32);
565 mb_submit(host, slave, data, vt);
566 } else /* if (data->register_type == REG_TYPE_UINT16) */
570 DEBUG("Modbus plugin: mb_read_data: "
571 "Returned uint16 value is %" PRIu16,
574 CAST_TO_VALUE_T(ds, vt, values[0]);
575 mb_submit(host, slave, data, vt);
579 } /* }}} int mb_read_data */
581 static int mb_read_slave(mb_host_t *host, mb_slave_t *slave) /* {{{ */
586 if ((host == NULL) || (slave == NULL))
590 for (mb_data_t *data = slave->collect; data != NULL; data = data->next) {
591 status = mb_read_data(host, slave, data);
600 } /* }}} int mb_read_slave */
602 static int mb_read(user_data_t *user_data) /* {{{ */
608 if ((user_data == NULL) || (user_data->data == NULL))
611 host = user_data->data;
614 for (size_t i = 0; i < host->slaves_num; i++) {
615 status = mb_read_slave(host, host->slaves + i);
624 } /* }}} int mb_read */
628 static void data_free_one(mb_data_t *data) /* {{{ */
635 } /* }}} void data_free_one */
637 static void data_free_all(mb_data_t *data) /* {{{ */
648 } /* }}} void data_free_all */
650 static void slaves_free_all(mb_slave_t *slaves, size_t slaves_num) /* {{{ */
655 for (size_t i = 0; i < slaves_num; i++)
656 data_free_all(slaves[i].collect);
658 } /* }}} void slaves_free_all */
660 static void host_free(void *void_host) /* {{{ */
662 mb_host_t *host = void_host;
667 slaves_free_all(host->slaves, host->slaves_num);
669 } /* }}} void host_free */
671 /* Config functions */
673 static int mb_config_add_data(oconfig_item_t *ci) /* {{{ */
675 mb_data_t data = {0};
679 data.register_type = REG_TYPE_UINT16;
682 status = cf_util_get_string(ci, &data.name);
686 for (int i = 0; i < ci->children_num; i++) {
687 oconfig_item_t *child = ci->children + i;
689 if (strcasecmp("Type", child->key) == 0)
690 status = cf_util_get_string_buffer(child, data.type, sizeof(data.type));
691 else if (strcasecmp("Instance", child->key) == 0)
692 status = cf_util_get_string_buffer(child, data.instance,
693 sizeof(data.instance));
694 else if (strcasecmp("RegisterBase", child->key) == 0)
695 status = cf_util_get_int(child, &data.register_base);
696 else if (strcasecmp("RegisterType", child->key) == 0) {
698 status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
701 else if (strcasecmp("Int16", tmp) == 0)
702 data.register_type = REG_TYPE_INT16;
703 else if (strcasecmp("Int32", tmp) == 0)
704 data.register_type = REG_TYPE_INT32;
705 else if (strcasecmp("Uint16", tmp) == 0)
706 data.register_type = REG_TYPE_UINT16;
707 else if (strcasecmp("Uint32", tmp) == 0)
708 data.register_type = REG_TYPE_UINT32;
709 else if (strcasecmp("Float", tmp) == 0)
710 data.register_type = REG_TYPE_FLOAT;
712 ERROR("Modbus plugin: The register type \"%s\" is unknown.", tmp);
715 } else if (strcasecmp("RegisterCmd", child->key) == 0) {
717 ERROR("Modbus plugin: RegisterCmd parameter can not be used "
718 "with your libmodbus version");
721 status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
724 else if (strcasecmp("ReadHolding", tmp) == 0)
725 data.modbus_register_type = MREG_HOLDING;
726 else if (strcasecmp("ReadInput", tmp) == 0)
727 data.modbus_register_type = MREG_INPUT;
729 ERROR("Modbus plugin: The modbus_register_type \"%s\" is unknown.",
735 ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
741 } /* for (i = 0; i < ci->children_num; i++) */
743 assert(data.name != NULL);
744 if (data.type[0] == 0) {
745 ERROR("Modbus plugin: Data block \"%s\": No type has been specified.",
751 data_copy(&data_definitions, &data);
756 } /* }}} int mb_config_add_data */
758 static int mb_config_set_host_address(mb_host_t *host, /* {{{ */
759 const char *address) {
760 struct addrinfo *ai_list;
763 if ((host == NULL) || (address == NULL))
766 struct addrinfo ai_hints = {
767 /* XXX: libmodbus can only handle IPv4 addresses. */
768 .ai_family = AF_INET,
769 .ai_flags = AI_ADDRCONFIG};
771 status = getaddrinfo(address, /* service = */ NULL, &ai_hints, &ai_list);
774 ERROR("Modbus plugin: getaddrinfo failed: %s",
775 (status == EAI_SYSTEM) ? sstrerror(errno, errbuf, sizeof(errbuf))
776 : gai_strerror(status));
780 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
781 ai_ptr = ai_ptr->ai_next) {
782 status = getnameinfo(ai_ptr->ai_addr, ai_ptr->ai_addrlen, host->node,
784 /* service = */ NULL, /* length = */ 0,
785 /* flags = */ NI_NUMERICHOST);
790 freeaddrinfo(ai_list);
793 ERROR("Modbus plugin: Unable to translate node name: \"%s\"", address);
794 else /* if (status == 0) */
796 DEBUG("Modbus plugin: mb_config_set_host_address: %s -> %s", address,
801 } /* }}} int mb_config_set_host_address */
803 static int mb_config_add_slave(mb_host_t *host, oconfig_item_t *ci) /* {{{ */
808 if ((host == NULL) || (ci == NULL))
811 slave = realloc(host->slaves, sizeof(*slave) * (host->slaves_num + 1));
814 host->slaves = slave;
815 slave = host->slaves + host->slaves_num;
816 memset(slave, 0, sizeof(*slave));
817 slave->collect = NULL;
819 status = cf_util_get_int(ci, &slave->id);
823 for (int i = 0; i < ci->children_num; i++) {
824 oconfig_item_t *child = ci->children + i;
826 if (strcasecmp("Instance", child->key) == 0)
827 status = cf_util_get_string_buffer(child, slave->instance,
828 sizeof(slave->instance));
829 else if (strcasecmp("Collect", child->key) == 0) {
831 status = cf_util_get_string_buffer(child, buffer, sizeof(buffer));
833 data_copy_by_name(&slave->collect, data_definitions, buffer);
834 status = 0; /* continue after failure. */
836 ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
844 if ((status == 0) && (slave->collect == NULL))
852 else /* if (status != 0) */
853 data_free_all(slave->collect);
856 } /* }}} int mb_config_add_slave */
858 static int mb_config_add_host(oconfig_item_t *ci) /* {{{ */
863 host = calloc(1, sizeof(*host));
868 status = cf_util_get_string_buffer(ci, host->host, sizeof(host->host));
873 if (host->host[0] == 0) {
878 for (int i = 0; i < ci->children_num; i++) {
879 oconfig_item_t *child = ci->children + i;
882 if (strcasecmp("Address", child->key) == 0) {
883 char buffer[NI_MAXHOST];
884 status = cf_util_get_string_buffer(child, buffer, sizeof(buffer));
886 status = mb_config_set_host_address(host, buffer);
888 host->conntype = MBCONN_TCP;
889 } else if (strcasecmp("Port", child->key) == 0) {
890 host->port = cf_util_get_port_number(child);
893 } else if (strcasecmp("Device", child->key) == 0) {
894 status = cf_util_get_string_buffer(child, host->node, sizeof(host->node));
896 host->conntype = MBCONN_RTU;
897 } else if (strcasecmp("Baudrate", child->key) == 0)
898 status = cf_util_get_int(child, &host->baudrate);
899 else if (strcasecmp("Interval", child->key) == 0)
900 status = cf_util_get_cdtime(child, &host->interval);
901 else if (strcasecmp("Slave", child->key) == 0)
902 /* Don't set status: Gracefully continue if a slave fails. */
903 mb_config_add_slave(host, child);
905 ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
911 } /* for (i = 0; i < ci->children_num; i++) */
913 assert(host->host[0] != 0);
914 if (host->node[0] == 0) {
915 ERROR("Modbus plugin: Data block \"%s\": No address or device has been "
920 if (host->conntype == MBCONN_RTU && !host->baudrate) {
921 ERROR("Modbus plugin: Data block \"%s\": No serial baudrate has been "
926 if ((host->conntype == MBCONN_TCP && host->baudrate) ||
927 (host->conntype == MBCONN_RTU && host->port)) {
928 ERROR("Modbus plugin: Data block \"%s\": You've mixed up RTU and TCP "
937 ssnprintf(name, sizeof(name), "modbus-%s", host->host);
939 plugin_register_complex_read(/* group = */ NULL, name,
940 /* callback = */ mb_read,
941 /* interval = */ host->interval,
943 .data = host, .free_func = host_free,
950 } /* }}} int mb_config_add_host */
952 static int mb_config(oconfig_item_t *ci) /* {{{ */
957 for (int i = 0; i < ci->children_num; i++) {
958 oconfig_item_t *child = ci->children + i;
960 if (strcasecmp("Data", child->key) == 0)
961 mb_config_add_data(child);
962 else if (strcasecmp("Host", child->key) == 0)
963 mb_config_add_host(child);
965 ERROR("Modbus plugin: Unknown configuration option: %s", child->key);
969 } /* }}} int mb_config */
973 static int mb_shutdown(void) /* {{{ */
975 data_free_all(data_definitions);
976 data_definitions = NULL;
979 } /* }}} int mb_shutdown */
981 void module_register(void) {
982 plugin_register_complex_config("modbus", mb_config);
983 plugin_register_shutdown("modbus", mb_shutdown);
984 } /* void module_register */