modbus plugin: Actually get into a working state.
[collectd.git] / src / modbus.c
1 /**
2  * collectd - src/modbus.c
3  * Copyright (C) 2010  noris network AG
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian Forster <octo at noris.net>
20  **/
21
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "configfile.h"
26
27 #include <modbus/modbus.h>
28
29 /*
30  * <Data "data_name">
31  *   RegisterBase 1234
32  *   RegisterType float
33  *   Type gauge
34  *   Instance "..."
35  * </Data>
36  *
37  * <Host "name">
38  *   Address "addr"
39  *   Port "1234"
40  *   Interval 60
41  *
42  *   <Slave 1>
43  *     Instance "foobar" # optional
44  *     Collect "data_name"
45  *   </Slave>
46  * </Host>
47  */
48
49 /*
50  * Data structures
51  */
52 enum mb_register_type_e
53 {
54   REG_TYPE_UINT16,
55   REG_TYPE_UINT32,
56   REG_TYPE_FLOAT
57 };
58 typedef enum mb_register_type_e mb_register_type_t;
59
60 struct mb_data_s;
61 typedef struct mb_data_s mb_data_t;
62 struct mb_data_s
63 {
64   char *name;
65   int register_base;
66   mb_register_type_t register_type;
67   char type[DATA_MAX_NAME_LEN];
68   char instance[DATA_MAX_NAME_LEN];
69
70   mb_data_t *next;
71 };
72
73 struct mb_slave_s
74 {
75   int id;
76   char instance[DATA_MAX_NAME_LEN];
77   mb_data_t *collect;
78 };
79 typedef struct mb_slave_s mb_slave_t;
80
81 struct mb_host_s
82 {
83   char host[DATA_MAX_NAME_LEN];
84   char node[NI_MAXHOST];
85   /* char service[NI_MAXSERV]; */
86   int port;
87   int interval;
88
89   mb_slave_t *slaves;
90   size_t slaves_num;
91
92   modbus_param_t connection;
93   _Bool is_connected;
94   _Bool have_reconnected;
95 };
96 typedef struct mb_host_s mb_host_t;
97
98 struct mb_data_group_s;
99 typedef struct mb_data_group_s mb_data_group_t;
100 struct mb_data_group_s
101 {
102   mb_data_t *registers;
103   size_t registers_num;
104
105   mb_data_group_t *next;
106 };
107
108 /*
109  * Global variables
110  */
111 static mb_data_t *data_definitions = NULL;
112
113 /*
114  * Functions
115  */
116 static mb_data_t *data_get_by_name (mb_data_t *src, /* {{{ */
117     const char *name)
118 {
119   mb_data_t *ptr;
120
121   if (name == NULL)
122     return (NULL);
123
124   for (ptr = src; ptr != NULL; ptr = ptr->next)
125     if (strcasecmp (ptr->name, name) == 0)
126       return (ptr);
127
128   return (NULL);
129 } /* }}} mb_data_t *data_get_by_name */
130
131 static int data_append (mb_data_t **dst, mb_data_t *src) /* {{{ */
132 {
133   mb_data_t *ptr;
134
135   if ((dst == NULL) || (src == NULL))
136     return (EINVAL);
137
138   ptr = *dst;
139
140   if (ptr == NULL)
141   {
142     *dst = src;
143     return (0);
144   }
145
146   while (ptr->next != NULL)
147     ptr = ptr->next;
148
149   ptr->next = src;
150
151   return (0);
152 } /* }}} int data_append */
153
154 /* Copy a single mb_data_t and append it to another list. */
155 static int data_copy (mb_data_t **dst, const mb_data_t *src) /* {{{ */
156 {
157   mb_data_t *tmp;
158   int status;
159
160   if ((dst == NULL) || (src == NULL))
161     return (EINVAL);
162
163   tmp = malloc (sizeof (*tmp));
164   if (tmp == NULL)
165     return (ENOMEM);
166   memcpy (tmp, src, sizeof (*tmp));
167   tmp->name = NULL;
168   tmp->next = NULL;
169
170   tmp->name = strdup (src->name);
171   if (tmp->name == NULL)
172   {
173     sfree (tmp);
174     return (ENOMEM);
175   }
176
177   status = data_append (dst, tmp);
178   if (status != 0)
179   {
180     sfree (tmp->name);
181     sfree (tmp);
182     return (status);
183   }
184
185   return (0);
186 } /* }}} int data_copy */
187
188 /* Lookup a single mb_data_t instance, copy it and append the copy to another
189  * list. */
190 static int data_copy_by_name (mb_data_t **dst, mb_data_t *src, /* {{{ */
191     const char *name)
192 {
193   mb_data_t *ptr;
194
195   if ((dst == NULL) || (src == NULL) || (name == NULL))
196     return (EINVAL);
197
198   ptr = data_get_by_name (src, name);
199   if (ptr == NULL)
200     return (ENOENT);
201
202   return (data_copy (dst, ptr));
203 } /* }}} int data_copy_by_name */
204
205 /* Read functions */
206
207 static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
208 {
209   union
210   {
211     uint8_t b[4];
212     float f;
213   } conv;
214
215 #if BYTE_ORDER == LITTLE_ENDIAN
216   /* little endian */
217   conv.b[0] = lo & 0x00ff;
218   conv.b[1] = (lo >> 8) & 0x00ff;
219   conv.b[2] = hi & 0x00ff;
220   conv.b[3] = (hi >> 8) & 0x00ff;
221 #else
222   conv.b[3] = lo & 0x00ff;
223   conv.b[2] = (lo >> 8) & 0x00ff;
224   conv.b[1] = hi & 0x00ff;
225   conv.b[0] = (hi >> 8) & 0x00ff;
226 #endif
227
228   return (conv.f);
229 } /* }}} float mb_register_to_float */
230
231 static int mb_init_connection (mb_host_t *host) /* {{{ */
232 {
233   int status;
234
235   if (host == NULL)
236     return (EINVAL);
237
238   if (host->is_connected)
239     return (0);
240
241   /* Only reconnect once per interval. */
242   if (host->have_reconnected)
243     return (-1);
244
245   modbus_set_debug (&host->connection, 1);
246
247   /* We'll do the error handling ourselves. */
248   modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
249
250   if ((host->port < 1) || (host->port > 65535))
251     host->port = MODBUS_TCP_DEFAULT_PORT;
252
253   DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
254       host->node, host->port);
255
256   modbus_init_tcp (&host->connection,
257       /* host = */ host->node,
258       /* port = */ host->port);
259
260   status = modbus_connect (&host->connection);
261   if (status != 0)
262   {
263     ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
264         host->node, host->port, status);
265     return (status);
266   }
267
268   host->is_connected = 1;
269   host->have_reconnected = 1;
270   return (0);
271 } /* }}} int mb_init_connection */
272
273 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
274     mb_data_t *data)
275 {
276   uint16_t values[2];
277   int values_num;
278   const data_set_t *ds;
279   int status;
280   int i;
281
282   if ((host == NULL) || (slave == NULL) || (data == NULL))
283     return (EINVAL);
284
285   ds = plugin_get_ds (data->type);
286   if (ds == NULL)
287   {
288     ERROR ("Modbus plugin: Type \"%s\" is not defined.", data->type);
289     return (-1);
290   }
291
292   if (ds->ds_num != 1)
293   {
294     ERROR ("Modbus plugin: The type \"%s\" has %i data sources. "
295         "I can only handle data sets with only one data source.",
296         data->type, ds->ds_num);
297     return (-1);
298   }
299
300   memset (values, 0, sizeof (values));
301   if ((data->register_type == REG_TYPE_UINT32)
302       || (data->register_type == REG_TYPE_FLOAT))
303     values_num = 2;
304   else
305     values_num = 1;
306
307   for (i = 0; i < 2; i++)
308   {
309     status = read_holding_registers (&host->connection,
310         /* slave = */ slave->id, /* start_addr = */ data->register_base,
311         /* num_registers = */ values_num, /* buffer = */ values);
312     if (status > 0)
313       break;
314
315     if (host->is_connected)
316       modbus_close (&host->connection);
317     host->is_connected = 0;
318
319     /* If we already tried reconnecting this round, give up. */
320     if (host->have_reconnected)
321     {
322       ERROR ("Modbus plugin: read_holding_registers (%s) failed. "
323           "Reconnecting has already been tried. Giving up.", host->host);
324       return (-1);
325     }
326
327     /* Maybe the device closed the connection during the waiting interval.
328      * Try re-establishing the connection. */
329     status = mb_init_connection (host);
330     if (status != 0)
331     {
332       ERROR ("Modbus plugin: read_holding_registers (%s) failed. "
333           "While trying to reconnect, connecting to \"%s\" failed. "
334           "Giving up.",
335           host->host, host->node);
336       return (-1);
337     }
338
339     DEBUG ("Modbus plugin: Re-established connection to %s", host->host);
340
341     /* try again */
342     continue;
343   } /* for (i = 0, 1) */
344
345   DEBUG ("Modbus plugin: mb_read_data: Success! "
346       "read_holding_registers returned with status %i.", status);
347
348   if (data->register_type == REG_TYPE_FLOAT)
349   {
350     float value;
351
352     value = mb_register_to_float (values[0], values[1]);
353     DEBUG ("Modbus plugin: mb_read_data: "
354         "Returned float value is %g", (double) value);
355   }
356
357   return (0);
358 } /* }}} int mb_read_data */
359
360 static int mb_read_slave (mb_host_t *host, mb_slave_t *slave) /* {{{ */
361 {
362   mb_data_t *data;
363   int success;
364   int status;
365
366   if ((host == NULL) || (slave == NULL))
367     return (EINVAL);
368
369   success = 0;
370   for (data = slave->collect; data != NULL; data = data->next)
371   {
372     status = mb_read_data (host, slave, data);
373     if (status == 0)
374       success++;
375   }
376
377   if (success == 0)
378     return (-1);
379   else
380     return (0);
381 } /* }}} int mb_read_slave */
382
383 static int mb_read (user_data_t *user_data) /* {{{ */
384 {
385   mb_host_t *host;
386   size_t i;
387   int success;
388   int status;
389
390   if ((user_data == NULL) || (user_data->data == NULL))
391     return (EINVAL);
392
393   host = user_data->data;
394
395   /* Clear the reconnect flag. */
396   host->have_reconnected = 0;
397
398   success = 0;
399   for (i = 0; i < host->slaves_num; i++)
400   {
401     status = mb_read_slave (host, host->slaves + i);
402     if (status == 0)
403       success++;
404   }
405
406   if (success == 0)
407     return (-1);
408   else
409     return (0);
410 } /* }}} int mb_read */
411
412 /* Free functions */
413
414 static void data_free_one (mb_data_t *data) /* {{{ */
415 {
416   if (data == NULL)
417     return;
418
419   sfree (data->name);
420   sfree (data);
421 } /* }}} void data_free_one */
422
423 static void data_free_all (mb_data_t *data) /* {{{ */
424 {
425   mb_data_t *next;
426
427   if (data == NULL)
428     return;
429
430   next = data->next;
431   data_free_one (data);
432
433   data_free_all (next);
434 } /* }}} void data_free_all */
435
436 static void slaves_free_all (mb_slave_t *slaves, size_t slaves_num) /* {{{ */
437 {
438   size_t i;
439
440   if (slaves == NULL)
441     return;
442
443   for (i = 0; i < slaves_num; i++)
444     data_free_all (slaves[i].collect);
445   sfree (slaves);
446 } /* }}} void slaves_free_all */
447
448 static void host_free (void *void_host) /* {{{ */
449 {
450   mb_host_t *host = void_host;
451
452   if (host == NULL)
453     return;
454
455   slaves_free_all (host->slaves, host->slaves_num);
456   sfree (host);
457 } /* }}} void host_free */
458
459 /* Config functions */
460
461 static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
462 {
463   mb_data_t data;
464   int status;
465   int i;
466
467   memset (&data, 0, sizeof (data));
468   data.name = NULL;
469   data.register_type = REG_TYPE_UINT16;
470   data.next = NULL;
471
472   status = cf_util_get_string (ci, &data.name);
473   if (status != 0)
474     return (status);
475
476   for (i = 0; i < ci->children_num; i++)
477   {
478     oconfig_item_t *child = ci->children + i;
479     status = 0;
480
481     if (strcasecmp ("Type", child->key) == 0)
482       status = cf_util_get_string_buffer (child,
483           data.type, sizeof (data.type));
484     else if (strcasecmp ("Instance", child->key) == 0)
485       status = cf_util_get_string_buffer (child,
486           data.instance, sizeof (data.instance));
487     else if (strcasecmp ("RegisterBase", child->key) == 0)
488       status = cf_util_get_int (child, &data.register_base);
489     else if (strcasecmp ("RegisterType", child->key) == 0)
490     {
491       char tmp[16];
492       status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
493       if (status != 0)
494         /* do nothing */;
495       else if (strcasecmp ("Uint16", tmp) == 0)
496         data.register_type = REG_TYPE_UINT16;
497       else if (strcasecmp ("Uint32", tmp) == 0)
498         data.register_type = REG_TYPE_UINT32;
499       else if (strcasecmp ("Float", tmp) == 0)
500         data.register_type = REG_TYPE_FLOAT;
501       else
502       {
503         ERROR ("Modbus plugin: The register type \"%s\" is unknown.", tmp);
504         status = -1;
505       }
506     }
507     else
508     {
509       ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
510       status = -1;
511     }
512
513     if (status != 0)
514       break;
515   } /* for (i = 0; i < ci->children_num; i++) */
516
517   assert (data.name != NULL);
518   if (data.type[0] == 0)
519   {
520     ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
521         data.name);
522     status = -1;
523   }
524
525   if (status == 0)
526     data_copy (&data_definitions, &data);
527
528   sfree (data.name);
529
530   return (status);
531 } /* }}} int mb_config_add_data */
532
533 static int mb_config_set_host_address (mb_host_t *host, /* {{{ */
534     const char *address)
535 {
536   struct addrinfo *ai_list;
537   struct addrinfo *ai_ptr;
538   struct addrinfo  ai_hints;
539   int status;
540
541   if ((host == NULL) || (address == NULL))
542     return (EINVAL);
543
544   memset (&ai_hints, 0, sizeof (ai_hints));
545 #if AI_ADDRCONFIG
546   ai_hints.ai_flags |= AI_ADDRCONFIG;
547 #endif
548   /* XXX: libmodbus can only handle IPv4 addresses. */
549   ai_hints.ai_family = AF_INET;
550   ai_hints.ai_addr = NULL;
551   ai_hints.ai_canonname = NULL;
552   ai_hints.ai_next = NULL;
553
554   ai_list = NULL;
555   status = getaddrinfo (address, /* service = */ NULL,
556       &ai_hints, &ai_list);
557   if (status != 0)
558   {
559     char errbuf[1024];
560     ERROR ("Modbus plugin: getaddrinfo failed: %s",
561         (status == EAI_SYSTEM)
562         ? sstrerror (errno, errbuf, sizeof (errbuf))
563         : gai_strerror (status));
564     return (status);
565   }
566
567   for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
568   {
569     status = getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
570         host->node, sizeof (host->node),
571         /* service = */ NULL, /* length = */ 0,
572         /* flags = */ NI_NUMERICHOST);
573     if (status == 0)
574       break;
575   } /* for (ai_ptr) */
576
577   freeaddrinfo (ai_list);
578
579   if (status != 0)
580     ERROR ("Modbus plugin: Unable to translate node name: \"%s\"", address);
581   else /* if (status == 0) */
582   {
583     DEBUG ("Modbus plugin: mb_config_set_host_address: %s -> %s",
584         address, host->node);
585   }
586
587   return (status);
588 } /* }}} int mb_config_set_host_address */
589
590 static int mb_config_add_slave (mb_host_t *host, oconfig_item_t *ci) /* {{{ */
591 {
592   mb_slave_t *slave;
593   int status;
594   int i;
595
596   if ((host == NULL) || (ci == NULL))
597     return (EINVAL);
598
599   slave = realloc (host->slaves, sizeof (*slave) * (host->slaves_num + 1));
600   if (slave == NULL)
601     return (ENOMEM);
602   host->slaves = slave;
603   slave = host->slaves + host->slaves_num;
604   memset (slave, 0, sizeof (*slave));
605   slave->collect = NULL;
606
607   status = cf_util_get_int (ci, &slave->id);
608   if (status != 0)
609     return (status);
610
611   for (i = 0; i < ci->children_num; i++)
612   {
613     oconfig_item_t *child = ci->children + i;
614     status = 0;
615
616     if (strcasecmp ("Instance", child->key) == 0)
617       status = cf_util_get_string_buffer (child,
618           slave->instance, sizeof (slave->instance));
619     else if (strcasecmp ("Collect", child->key) == 0)
620     {
621       char buffer[1024];
622       status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
623       if (status == 0)
624         data_copy_by_name (&slave->collect, data_definitions, buffer);
625       status = 0; /* continue after failure. */
626     }
627     else
628     {
629       ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
630       status = -1;
631     }
632
633     if (status != 0)
634       break;
635   }
636
637   if ((status == 0) && (slave->collect == NULL))
638     status = EINVAL;
639
640   if (slave->id < 0)
641     status = EINVAL;
642
643   if (status == 0)
644     host->slaves_num++;
645   else /* if (status != 0) */
646     data_free_all (slave->collect);
647
648   return (status);
649 } /* }}} int mb_config_add_slave */
650
651 static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
652 {
653   mb_host_t *host;
654   int status;
655   int i;
656
657   host = malloc (sizeof (*host));
658   if (host == NULL)
659     return (ENOMEM);
660   memset (host, 0, sizeof (*host));
661   host->slaves = NULL;
662
663   status = cf_util_get_string_buffer (ci, host->host, sizeof (host->host));
664   if (status != 0)
665     return (status);
666   if (host->host[0] == 0)
667     return (EINVAL);
668
669   for (i = 0; i < ci->children_num; i++)
670   {
671     oconfig_item_t *child = ci->children + i;
672     status = 0;
673
674     if (strcasecmp ("Address", child->key) == 0)
675     {
676       char buffer[NI_MAXHOST];
677       status = cf_util_get_string_buffer (child, buffer, sizeof (buffer));
678       if (status == 0)
679         status = mb_config_set_host_address (host, buffer);
680     }
681     else if (strcasecmp ("Port", child->key) == 0)
682     {
683       host->port = cf_util_get_port_number (child);
684       if (host->port <= 0)
685         status = -1;
686     }
687     else if (strcasecmp ("Interval", child->key) == 0)
688       status = cf_util_get_int (child, &host->interval);
689     else if (strcasecmp ("Slave", child->key) == 0)
690       /* Don't set status: Gracefully continue if a slave fails. */
691       mb_config_add_slave (host, child);
692     else
693     {
694       ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
695       status = -1;
696     }
697
698     if (status != 0)
699       break;
700   } /* for (i = 0; i < ci->children_num; i++) */
701
702   assert (host->host[0] != 0);
703   if (host->host[0] == 0)
704   {
705     ERROR ("Modbus plugin: Data block \"%s\": No type has been specified.",
706         host->host);
707     status = -1;
708   }
709
710   if (status == 0)
711   {
712     user_data_t ud;
713     char name[1024];
714     struct timespec interval;
715
716     ud.data = host;
717     ud.free_func = host_free;
718
719     ssnprintf (name, sizeof (name), "modbus-%s", host->host);
720
721     interval.tv_nsec = 0;
722     if (host->interval > 0)
723       interval.tv_sec = host->interval;
724     else
725       interval.tv_sec = 0;
726
727     plugin_register_complex_read (name, mb_read,
728         (interval.tv_sec > 0) ? &interval : NULL,
729         &ud);
730   }
731   else
732   {
733     host_free (host);
734   }
735
736   return (status);
737 } /* }}} int mb_config_add_host */
738
739 static int mb_config (oconfig_item_t *ci) /* {{{ */
740 {
741   int i;
742
743   if (ci == NULL)
744     return (EINVAL);
745
746   for (i = 0; i < ci->children_num; i++)
747   {
748     oconfig_item_t *child = ci->children + i;
749
750     if (strcasecmp ("Data", child->key) == 0)
751       mb_config_add_data (child);
752     else if (strcasecmp ("Host", child->key) == 0)
753       mb_config_add_host (child);
754     else
755       ERROR ("Modbus plugin: Unknown configuration option: %s", child->key);
756   }
757
758   return (0);
759 } /* }}} int mb_config */
760
761 /* ========= */
762
763 #if 0
764 static int foo (void) /* {{{ */
765 {
766   int status;
767   uint16_t values[2];
768   int values_num;
769
770   if (dev == NULL)
771     return (EINVAL);
772
773   printf ("mb_read (addr = %i, float = %s);\n", register_addr,
774       is_float ? "true" : "false");
775
776   memset (values, 0, sizeof (values));
777   if (is_float)
778     values_num = 2;
779   else
780     values_num = 1;
781
782   status = read_holding_registers (dev->connection,
783       /* slave = */ 1, /* start_addr = */ register_addr,
784       /* num_registers = */ values_num, /* buffer = */ values);
785   printf ("read_coil_status returned with status %i\n", status);
786   if (status <= 0)
787     return (EAGAIN);
788
789   if (is_float)
790   {
791     float value = mb_register_to_float (values[0], values[1]);
792     printf ("read_coil_status returned value %g (hi %#"PRIx16", lo %#"PRIx16")\n",
793         value, values[0], values[1]);
794   }
795   else
796   {
797     printf ("read_coil_status returned value %"PRIu16"\n", values[0]);
798   }
799
800   return (0);
801 } /* }}} int foo */
802 #endif
803
804 static int mb_shutdown (void) /* {{{ */
805 {
806   data_free_all (data_definitions);
807   data_definitions = NULL;
808
809   return (0);
810 } /* }}} int mb_shutdown */
811
812 void module_register (void)
813 {
814   plugin_register_complex_config ("modbus", mb_config);
815   plugin_register_shutdown ("modbus", mb_shutdown);
816 } /* void module_register */
817
818 /* vim: set sw=2 sts=2 et fdm=marker : */