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, /* {{{ */
168 for (mb_data_t *ptr = src; ptr != NULL; ptr = ptr->next)
169 if (strcasecmp (ptr->name, name) == 0)
173 } /* }}} mb_data_t *data_get_by_name */
175 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
179 if ((dst == NULL) || (src == NULL))
190 while (ptr->next != NULL)
196 } /* }}} int data_append */
198 /* Copy a single mb_data_t and append it to another list. */
199 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
204 if ((dst == NULL) || (src == NULL))
207 tmp = malloc (sizeof (*tmp));
210 memcpy (tmp, src, sizeof (*tmp));
214 tmp->name = strdup (src->name);
215 if (tmp->name == NULL)
221 status = data_append (dst, tmp);
230 } /* }}} int data_copy */
232 /* Lookup a single mb_data_t instance, copy it and append the copy to another
234 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
239 if ((dst == NULL) || (src == NULL) || (name == NULL))
242 ptr = data_get_by_name (src, name);
246 return (data_copy (dst, ptr));
247 } /* }}} int data_copy_by_name */
251 static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
252 mb_data_t *data, value_t value)
254 value_list_t vl = VALUE_LIST_INIT;
256 if ((host == NULL) || (slave == NULL) || (data == NULL))
259 if (host->interval == 0)
260 host->interval = plugin_get_interval ();
262 if (slave->instance[0] == 0)
263 ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
268 vl.interval = host->interval;
269 sstrncpy (vl.host, host->host, sizeof (vl.host));
270 sstrncpy (vl.plugin, "modbus", sizeof (vl.plugin));
271 sstrncpy (vl.plugin_instance, slave->instance, sizeof (vl.plugin_instance));
272 sstrncpy (vl.type, data->type, sizeof (vl.type));
273 sstrncpy (vl.type_instance, data->instance, sizeof (vl.type_instance));
275 return (plugin_dispatch_values (&vl));
276 } /* }}} int mb_submit */
278 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
287 #if BYTE_ORDER == LITTLE_ENDIAN
289 conv.b[0] = lo & 0x00ff;
290 conv.b[1] = (lo >> 8) & 0x00ff;
291 conv.b[2] = hi & 0x00ff;
292 conv.b[3] = (hi >> 8) & 0x00ff;
294 conv.b[3] = lo & 0x00ff;
295 conv.b[2] = (lo >> 8) & 0x00ff;
296 conv.b[1] = hi & 0x00ff;
297 conv.b[0] = (hi >> 8) & 0x00ff;
301 } /* }}} float mb_register_to_float */
305 static int mb_init_connection (mb_host_t *host) /* {{{ */
313 modbus_set_debug (&host->connection, 1);
316 /* We'll do the error handling ourselves. */
317 modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
319 if (host->conntype == MBCONN_TCP)
321 if ((host->port < 1) || (host->port > 65535))
322 host->port = MODBUS_TCP_DEFAULT_PORT;
324 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
325 host->node, host->port);
327 modbus_init_tcp (&host->connection,
328 /* host = */ host->node,
329 /* port = */ host->port);
331 else /* MBCONN_RTU */
333 DEBUG ("Modbus plugin: Trying to connect to \"%s\".", host->node);
335 modbus_init_rtu (&host->connection,
336 /* device = */ host->node,
337 /* baudrate = */ host->baudrate,
341 status = modbus_connect (&host->connection);
344 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
345 host->node, host->port ? host->port : host->baudrate, status);
349 host->is_connected = 1;
351 } /* }}} int mb_init_connection */
352 /* #endif LEGACY_LIBMODBUS */
354 #else /* if !LEGACY_LIBMODBUS */
356 static int mb_init_connection (mb_host_t *host) /* {{{ */
363 if (host->connection != NULL)
366 if (host->conntype == MBCONN_TCP)
368 if ((host->port < 1) || (host->port > 65535))
369 host->port = MODBUS_TCP_DEFAULT_PORT;
371 DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
372 host->node, host->port);
374 host->connection = modbus_new_tcp (host->node, host->port);
375 if (host->connection == NULL)
377 ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
383 DEBUG ("Modbus plugin: Trying to connect to \"%s\", baudrate %i.",
384 host->node, host->baudrate);
386 host->connection = modbus_new_rtu (host->node, host->baudrate, 'N', 8, 1);
387 if (host->connection == NULL)
389 ERROR ("Modbus plugin: Creating new Modbus/RTU object failed.");
395 modbus_set_debug (host->connection, 1);
398 /* We'll do the error handling ourselves. */
399 modbus_set_error_recovery (host->connection, 0);
401 status = modbus_connect (host->connection);
404 ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
405 host->node, host->port ? host->port : host->baudrate, status);
406 modbus_free (host->connection);
407 host->connection = NULL;
412 } /* }}} int mb_init_connection */
413 #endif /* !LEGACY_LIBMODBUS */
415 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
416 if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
417 (vt).counter = (counter_t) (raw); \
418 else if ((ds)->ds[0].type == DS_TYPE_GAUGE) \
419 (vt).gauge = (gauge_t) (raw); \
420 else if ((ds)->ds[0].type == DS_TYPE_DERIVE) \
421 (vt).derive = (derive_t) (raw); \
422 else /* if (ds->ds[0].type == DS_TYPE_ABSOLUTE) */ \
423 (vt).absolute = (absolute_t) (raw); \
426 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
429 uint16_t values[2] = { 0 };
431 const data_set_t *ds;
434 if ((host == NULL) || (slave == NULL) || (data == NULL))
437 ds = plugin_get_ds (data->type);
440 ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
446 ERROR ("Modbus plugin: The type \"%s\" has %zu data sources. "
447 "I can only handle data sets with only one data source.",
448 data->type, ds->ds_num);
452 if ((ds->ds[0].type != DS_TYPE_GAUGE)
453 && (data->register_type != REG_TYPE_INT32)
454 && (data->register_type != REG_TYPE_UINT32))
456 NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
457 "This will most likely result in problems, because the register type "
458 "is not UINT32.", data->type, DS_TYPE_TO_STRING (ds->ds[0].type));
461 if ((data->register_type == REG_TYPE_INT32)
462 || (data->register_type == REG_TYPE_UINT32)
463 || (data->register_type == REG_TYPE_FLOAT))
468 if (host->connection == NULL)
472 else if (host->conntype == MBCONN_TCP)
474 /* getpeername() is used only to determine if the socket is connected, not
475 * because we're really interested in the peer's IP address. */
476 if (getpeername (modbus_get_socket (host->connection),
477 (void *) &(struct sockaddr_storage) {0},
478 &(socklen_t) {sizeof(struct sockaddr_storage)}) != 0)
482 if ((status == EBADF) || (status == ENOTSOCK) || (status == ENOTCONN))
484 status = mb_init_connection (host);
487 ERROR ("Modbus plugin: mb_init_connection (%s/%s) failed. ",
488 host->host, host->node);
489 host->is_connected = 0;
490 host->connection = NULL;
494 else if (status != 0)
497 modbus_close (&host->connection);
499 modbus_close (host->connection);
500 modbus_free (host->connection);
505 /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
506 * id to each call of "read_holding_registers". */
507 # define modbus_read_registers(ctx, addr, nb, dest) \
508 read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
509 #else /* if !LEGACY_LIBMODBUS */
510 /* Version 2.9.2: Set the slave id once before querying the registers. */
511 status = modbus_set_slave (host->connection, slave->id);
514 ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
519 if (data->modbus_register_type == MREG_INPUT){
520 status = modbus_read_input_registers (host->connection,
521 /* start_addr = */ data->register_base,
522 /* num_registers = */ values_num, /* buffer = */ values);
525 status = modbus_read_registers (host->connection,
526 /* start_addr = */ data->register_base,
527 /* num_registers = */ values_num, /* buffer = */ values);
529 if (status != values_num)
531 ERROR ("Modbus plugin: modbus read function (%s/%s) failed. "
532 " status = %i, values_num = %i. Giving up.",
533 host->host, host->node, status, values_num);
535 modbus_close (&host->connection);
537 modbus_close (host->connection);
538 modbus_free (host->connection);
540 host->connection = NULL;
544 DEBUG ("Modbus plugin: mb_read_data: Success! "
545 "modbus_read_registers returned with status %i.", status);
547 if (data->register_type == REG_TYPE_FLOAT)
552 float_value = mb_register_to_float (values[0], values[1]);
553 DEBUG ("Modbus plugin: mb_read_data: "
554 "Returned float value is %g", (double) float_value);
556 CAST_TO_VALUE_T (ds, vt, float_value);
557 mb_submit (host, slave, data, vt);
559 else if (data->register_type == REG_TYPE_INT32)
568 v.u32 = (((uint32_t) values[0]) << 16)
569 | ((uint32_t) values[1]);
570 DEBUG ("Modbus plugin: mb_read_data: "
571 "Returned int32 value is %"PRIi32, v.i32);
573 CAST_TO_VALUE_T (ds, vt, v.i32);
574 mb_submit (host, slave, data, vt);
576 else if (data->register_type == REG_TYPE_INT16)
587 DEBUG ("Modbus plugin: mb_read_data: "
588 "Returned int16 value is %"PRIi16, v.i16);
590 CAST_TO_VALUE_T (ds, vt, v.i16);
591 mb_submit (host, slave, data, vt);
593 else if (data->register_type == REG_TYPE_UINT32)
598 v32 = (((uint32_t) values[0]) << 16)
599 | ((uint32_t) values[1]);
600 DEBUG ("Modbus plugin: mb_read_data: "
601 "Returned uint32 value is %"PRIu32, v32);
603 CAST_TO_VALUE_T (ds, vt, v32);
604 mb_submit (host, slave, data, vt);
606 else /* if (data->register_type == REG_TYPE_UINT16) */
610 DEBUG ("Modbus plugin: mb_read_data: "
611 "Returned uint16 value is %"PRIu16, values[0]);
613 CAST_TO_VALUE_T (ds, vt, values[0]);
614 mb_submit (host, slave, data, vt);
618 } /* }}} int mb_read_data */
620 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
625 if ((host == NULL) || (slave == NULL))
629 for (mb_data_t *data = slave->collect; data != NULL; data = data->next)
631 status = mb_read_data (host, slave, data);
640 } /* }}} int mb_read_slave */
642 static int mb_read (user_data_t *user_data) /* {{{ */
648 if ((user_data == NULL) || (user_data->data == NULL))
651 host = user_data->data;
654 for (size_t i = 0; i < host->slaves_num; i++)
656 status = mb_read_slave (host, host->slaves + i);
665 } /* }}} int mb_read */
669 static void data_free_one (mb_data_t *data) /* {{{ */
676 } /* }}} void data_free_one */
678 static void data_free_all (mb_data_t *data) /* {{{ */
686 data_free_one (data);
688 data_free_all (next);
689 } /* }}} void data_free_all */
691 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
696 for (size_t i = 0; i < slaves_num; i++)
697 data_free_all (slaves[i].collect);
699 } /* }}} void slaves_free_all */
701 static void host_free (void *void_host) /* {{{ */
703 mb_host_t *host = void_host;
708 slaves_free_all (host->slaves, host->slaves_num);
710 } /* }}} void host_free */
712 /* Config functions */
714 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
716 mb_data_t data = { 0 };
720 data.register_type = REG_TYPE_UINT16;
723 status = cf_util_get_string (ci, &data.name);
727 for (int i = 0; i < ci->children_num; i++)
729 oconfig_item_t *child = ci->children + i;
731 if (strcasecmp ("Type", child->key) == 0)
732 status = cf_util_get_string_buffer (child,
733 data.type, sizeof (data.type));
734 else if (strcasecmp ("Instance", child->key) == 0)
735 status = cf_util_get_string_buffer (child,
736 data.instance, sizeof (data.instance));
737 else if (strcasecmp ("RegisterBase", child->key) == 0)
738 status = cf_util_get_int (child, &data.register_base);
739 else if (strcasecmp ("RegisterType", child->key) == 0)
742 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
745 else if (strcasecmp ("Int16", tmp) == 0)
746 data.register_type = REG_TYPE_INT16;
747 else if (strcasecmp ("Int32", tmp) == 0)
748 data.register_type = REG_TYPE_INT32;
749 else if (strcasecmp ("Uint16", tmp) == 0)
750 data.register_type = REG_TYPE_UINT16;
751 else if (strcasecmp ("Uint32", tmp) == 0)
752 data.register_type = REG_TYPE_UINT32;
753 else if (strcasecmp ("Float", tmp) == 0)
754 data.register_type = REG_TYPE_FLOAT;
757 ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
761 else if (strcasecmp ("RegisterCmd", child->key) == 0)
764 ERROR("Modbus plugin: RegisterCmd parameter can not be used "
765 "with your libmodbus version");
768 status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
771 else if (strcasecmp ("ReadHolding", tmp) == 0)
772 data.modbus_register_type = MREG_HOLDING;
773 else if (strcasecmp ("ReadInput", tmp) == 0)
774 data.modbus_register_type = MREG_INPUT;
777 ERROR ("Modbus plugin: The modbus_register_type \"%s\" is unknown.",
785 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
791 } /* for (i = 0; i < ci->children_num; i++) */
793 assert (data.name != NULL);
794 if (data.type[0] == 0)
796 ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
802 data_copy (&data_definitions, &data);
807 } /* }}} int mb_config_add_data */
809 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
812 struct addrinfo *ai_list;
815 if ((host == NULL) || (address == NULL))
818 struct addrinfo ai_hints = {
819 /* XXX: libmodbus can only handle IPv4 addresses. */
820 .ai_family = AF_INET,
821 .ai_flags = AI_ADDRCONFIG
824 status = getaddrinfo (address, /* service = */ NULL,
825 &ai_hints, &ai_list);
829 ERROR ("Modbus plugin: getaddrinfo failed: %s",
830 (status == EAI_SYSTEM)
831 ? sstrerror (errno, errbuf, sizeof (errbuf))
832 : gai_strerror (status));
836 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
838 status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
839 host->node, sizeof (host->node),
840 /* service = */ NULL, /* length = */ 0,
841 /* flags = */ NI_NUMERICHOST);
846 freeaddrinfo (ai_list);
849 ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
850 else /* if (status == 0) */
852 DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
853 address, host->node);
857 } /* }}} int mb_config_set_host_address */
859 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
864 if ((host == NULL) || (ci == NULL))
867 slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
870 host->slaves = slave;
871 slave = host->slaves + host->slaves_num;
872 memset (slave, 0, sizeof (*slave));
873 slave->collect = NULL;
875 status = cf_util_get_int (ci, &slave->id);
879 for (int i = 0; i < ci->children_num; i++)
881 oconfig_item_t *child = ci->children + i;
883 if (strcasecmp ("Instance", child->key) == 0)
884 status = cf_util_get_string_buffer (child,
885 slave->instance, sizeof (slave->instance));
886 else if (strcasecmp ("Collect", child->key) == 0)
889 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
891 data_copy_by_name (&slave->collect, data_definitions, buffer);
892 status = 0; /* continue after failure. */
896 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
904 if ((status == 0) && (slave->collect == NULL))
912 else /* if (status != 0) */
913 data_free_all (slave->collect);
916 } /* }}} int mb_config_add_slave */
918 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
923 host = calloc (1, sizeof (*host));
928 status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
934 if (host->host[0] == 0)
940 for (int i = 0; i < ci->children_num; i++)
942 oconfig_item_t *child = ci->children + i;
945 if (strcasecmp ("Address", child->key) == 0)
947 char buffer[NI_MAXHOST];
948 status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
950 status = mb_config_set_host_address (host, buffer);
952 host->conntype = MBCONN_TCP;
954 else if (strcasecmp ("Port", child->key) == 0)
956 host->port = cf_util_get_port_number (child);
960 else if (strcasecmp ("Device", child->key) == 0)
962 status = cf_util_get_string_buffer (child, host->node, sizeof (host->node));
964 host->conntype = MBCONN_RTU;
966 else if (strcasecmp ("Baudrate", child->key) == 0)
967 status = cf_util_get_int(child, &host->baudrate);
968 else if (strcasecmp ("Interval", child->key) == 0)
969 status = cf_util_get_cdtime (child, &host->interval);
970 else if (strcasecmp ("Slave", child->key) == 0)
971 /* Don't set status: Gracefully continue if a slave fails. */
972 mb_config_add_slave (host, child);
975 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
981 } /* for (i = 0; i < ci->children_num; i++) */
983 assert (host->host[0] != 0);
984 if (host->node[0] == 0)
986 ERROR ("Modbus plugin: Data block \"%s\": No address or device has been specified.",
990 if (host->conntype == MBCONN_RTU && !host->baudrate)
992 ERROR ("Modbus plugin: Data block \"%s\": No serial baudrate has been specified.",
996 if ((host->conntype == MBCONN_TCP && host->baudrate) ||
997 (host->conntype == MBCONN_RTU && host->port))
999 ERROR ("Modbus plugin: Data block \"%s\": You've mixed up RTU and TCP options.",
1008 ssnprintf (name, sizeof (name), "modbus-%s", host->host);
1010 plugin_register_complex_read (/* group = */ NULL, name,
1011 /* callback = */ mb_read,
1012 /* interval = */ host->interval,
1015 .free_func = host_free,
1024 } /* }}} int mb_config_add_host */
1026 static int mb_config (oconfig_item_t *ci) /* {{{ */
1031 for (int i = 0; i < ci->children_num; i++)
1033 oconfig_item_t *child = ci->children + i;
1035 if (strcasecmp ("Data", child->key) == 0)
1036 mb_config_add_data (child);
1037 else if (strcasecmp ("Host", child->key) == 0)
1038 mb_config_add_host (child);
1040 ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
1044 } /* }}} int mb_config */
1048 static int mb_shutdown (void) /* {{{ */
1050 data_free_all (data_definitions);
1051 data_definitions = NULL;
1054 } /* }}} int mb_shutdown */
1056 void module_register (void)
1058 plugin_register_complex_config ("modbus", mb_config);
1059 plugin_register_shutdown ("modbus", mb_shutdown);
1060 } /* void module_register */
1062 /* vim: set sw=2 sts=2 et fdm=marker : */