Merge branch 'collectd-5.7' into collectd-5.8
[collectd.git] / src / sigrok.c
1 /*
2  * collectd - src/sigrok.c
3  * Copyright (C) 2013 Bert Vermeulen
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  * Authors:
19  *   Bert Vermeulen <bert at biot.com>
20  */
21
22 #include "collectd.h"
23
24 #include "common.h"
25 #include "plugin.h"
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <time.h>
31
32 #include <glib.h>
33 #include <libsigrok/libsigrok.h>
34
35 /* Minimum interval between dispatches coming from this plugin. The RRD
36  * plugin, at least, complains when written to with sub-second intervals.*/
37 #define DEFAULT_MIN_DISPATCH_INTERVAL TIME_T_TO_CDTIME_T(0)
38
39 static pthread_t sr_thread;
40 static int sr_thread_running = FALSE;
41 GSList *config_devices;
42 static int num_devices;
43 static int loglevel = SR_LOG_WARN;
44 static struct sr_context *sr_ctx;
45
46 struct config_device {
47   char *name;
48   char *driver;
49   char *conn;
50   char *serialcomm;
51   struct sr_dev_inst *sdi;
52   cdtime_t min_dispatch_interval;
53   cdtime_t last_dispatch;
54 };
55
56 static int sigrok_log_callback(void *cb_data __attribute__((unused)),
57                                int msg_loglevel, const char *format,
58                                va_list args) {
59   char s[512];
60
61   if (msg_loglevel <= loglevel) {
62     vsnprintf(s, 512, format, args);
63     plugin_log(LOG_INFO, "sigrok plugin: %s", s);
64   }
65
66   return 0;
67 }
68
69 static int sigrok_config_device(oconfig_item_t *ci) {
70   struct config_device *cfdev;
71
72   if (!(cfdev = calloc(1, sizeof(*cfdev)))) {
73     ERROR("sigrok plugin: calloc failed.");
74     return -1;
75   }
76   if (cf_util_get_string(ci, &cfdev->name)) {
77     free(cfdev);
78     WARNING("sigrok plugin: Invalid device name.");
79     return -1;
80   }
81   cfdev->min_dispatch_interval = DEFAULT_MIN_DISPATCH_INTERVAL;
82
83   for (int i = 0; i < ci->children_num; i++) {
84     oconfig_item_t *item = ci->children + i;
85     if (!strcasecmp(item->key, "driver"))
86       cf_util_get_string(item, &cfdev->driver);
87     else if (!strcasecmp(item->key, "conn"))
88       cf_util_get_string(item, &cfdev->conn);
89     else if (!strcasecmp(item->key, "serialcomm"))
90       cf_util_get_string(item, &cfdev->serialcomm);
91     else if (!strcasecmp(item->key, "minimuminterval"))
92       cf_util_get_cdtime(item, &cfdev->min_dispatch_interval);
93     else
94       WARNING("sigrok plugin: Invalid keyword \"%s\".", item->key);
95   }
96
97   config_devices = g_slist_append(config_devices, cfdev);
98
99   return 0;
100 }
101
102 static int sigrok_config(oconfig_item_t *ci) {
103   for (int i = 0; i < ci->children_num; i++) {
104     oconfig_item_t *item = ci->children + i;
105     if (strcasecmp("LogLevel", item->key) == 0) {
106       int status;
107       int tmp = -1;
108
109       status = cf_util_get_int(item, &tmp);
110       if (status != 0)
111         continue;
112       else if ((tmp < 0) || (tmp > 5)) {
113         ERROR("sigrok plugin: The \"LogLevel\" "
114               "configuration option expects "
115               "an integer between 0 and 5 "
116               "(inclusive); you provided %i.",
117               tmp);
118         continue;
119       }
120       loglevel = tmp;
121     } else if (!strcasecmp(item->key, "Device"))
122       sigrok_config_device(item);
123     else
124       WARNING("sigrok plugin: Invalid keyword \"%s\".", item->key);
125   }
126
127   return 0;
128 }
129
130 static const char *sigrok_value_type(const struct sr_datafeed_analog *analog) {
131   const char *s;
132
133   if (analog->mq == SR_MQ_VOLTAGE)
134     s = "voltage";
135   else if (analog->mq == SR_MQ_CURRENT)
136     s = "current";
137   else if (analog->mq == SR_MQ_FREQUENCY)
138     s = "frequency";
139   else if (analog->mq == SR_MQ_POWER)
140     s = "power";
141   else if (analog->mq == SR_MQ_TEMPERATURE)
142     s = "temperature";
143   else if (analog->mq == SR_MQ_RELATIVE_HUMIDITY)
144     s = "humidity";
145   else if (analog->mq == SR_MQ_SOUND_PRESSURE_LEVEL)
146     s = "spl";
147   else
148     s = "gauge";
149
150   return s;
151 }
152
153 static void sigrok_feed_callback(const struct sr_dev_inst *sdi,
154                                  const struct sr_datafeed_packet *packet,
155                                  void *cb_data) {
156   const struct sr_datafeed_analog *analog;
157   struct config_device *cfdev;
158   value_list_t vl = VALUE_LIST_INIT;
159
160   /* Find this device's configuration. */
161   cfdev = NULL;
162   for (GSList *l = config_devices; l; l = l->next) {
163     cfdev = l->data;
164     if (cfdev->sdi == sdi) {
165       /* Found it. */
166       break;
167     }
168     cfdev = NULL;
169   }
170
171   if (!cfdev) {
172     ERROR("sigrok plugin: Received data from driver \"%s\" but "
173           "can't find a configuration / device matching "
174           "it.",
175           sdi->driver->name);
176     return;
177   }
178
179   if (packet->type == SR_DF_END) {
180     /* TODO: try to restart acquisition after a delay? */
181     WARNING("sigrok plugin: acquisition for \"%s\" ended.", cfdev->name);
182     return;
183   }
184
185   if (packet->type != SR_DF_ANALOG)
186     return;
187
188   if ((cfdev->min_dispatch_interval != 0) &&
189       ((cdtime() - cfdev->last_dispatch) < cfdev->min_dispatch_interval))
190     return;
191
192   /* Ignore all but the first sample on the first probe. */
193   analog = packet->payload;
194   vl.values = &(value_t){.gauge = analog->data[0]};
195   vl.values_len = 1;
196   sstrncpy(vl.plugin, "sigrok", sizeof(vl.plugin));
197   sstrncpy(vl.plugin_instance, cfdev->name, sizeof(vl.plugin_instance));
198   sstrncpy(vl.type, sigrok_value_type(analog), sizeof(vl.type));
199
200   plugin_dispatch_values(&vl);
201   cfdev->last_dispatch = cdtime();
202 }
203
204 static void sigrok_free_drvopts(struct sr_config *src) {
205   g_variant_unref(src->data);
206   g_free(src);
207 }
208
209 static int sigrok_init_driver(struct config_device *cfdev,
210                               struct sr_dev_driver *drv) {
211   struct sr_config *src;
212   GSList *devlist, *drvopts;
213   char hwident[512];
214
215   if (sr_driver_init(sr_ctx, drv) != SR_OK)
216     /* Error was logged by libsigrok. */
217     return -1;
218
219   drvopts = NULL;
220   if (cfdev->conn) {
221     if (!(src = malloc(sizeof(*src))))
222       return -1;
223     src->key = SR_CONF_CONN;
224     src->data = g_variant_new_string(cfdev->conn);
225     drvopts = g_slist_append(drvopts, src);
226   }
227   if (cfdev->serialcomm) {
228     if (!(src = malloc(sizeof(*src))))
229       return -1;
230     src->key = SR_CONF_SERIALCOMM;
231     src->data = g_variant_new_string(cfdev->serialcomm);
232     drvopts = g_slist_append(drvopts, src);
233   }
234   devlist = sr_driver_scan(drv, drvopts);
235   g_slist_free_full(drvopts, (GDestroyNotify)sigrok_free_drvopts);
236   if (!devlist) {
237     /* Not an error, but the user should know about it. */
238     WARNING("sigrok plugin: No device found for \"%s\".", cfdev->name);
239     return 0;
240   }
241
242   if (g_slist_length(devlist) > 1) {
243     INFO("sigrok plugin: %d sigrok devices for device entry "
244          "\"%s\": must be 1.",
245          g_slist_length(devlist), cfdev->name);
246     return -1;
247   }
248   cfdev->sdi = devlist->data;
249   g_slist_free(devlist);
250   snprintf(hwident, sizeof(hwident), "%s %s %s",
251            cfdev->sdi->vendor ? cfdev->sdi->vendor : "",
252            cfdev->sdi->model ? cfdev->sdi->model : "",
253            cfdev->sdi->version ? cfdev->sdi->version : "");
254   INFO("sigrok plugin: Device \"%s\" is a %s", cfdev->name, hwident);
255
256   if (sr_dev_open(cfdev->sdi) != SR_OK)
257     return -1;
258
259   if (sr_session_dev_add(cfdev->sdi) != SR_OK)
260     return -1;
261
262   return 1;
263 }
264
265 static void *sigrok_read_thread(void *arg __attribute__((unused))) {
266   struct sr_dev_driver *drv, **drvlist;
267   GSList *l;
268   struct config_device *cfdev;
269   int ret, i;
270
271   sr_log_callback_set(sigrok_log_callback, NULL);
272   sr_log_loglevel_set(loglevel);
273
274   if ((ret = sr_init(&sr_ctx)) != SR_OK) {
275     ERROR("sigrok plugin: Failed to initialize libsigrok: %s.",
276           sr_strerror(ret));
277     return NULL;
278   }
279
280   if (!sr_session_new())
281     return NULL;
282
283   num_devices = 0;
284   drvlist = sr_driver_list();
285   for (l = config_devices; l; l = l->next) {
286     cfdev = l->data;
287     drv = NULL;
288     for (i = 0; drvlist[i]; i++) {
289       if (!strcmp(drvlist[i]->name, cfdev->driver)) {
290         drv = drvlist[i];
291         break;
292       }
293     }
294     if (!drv) {
295       ERROR("sigrok plugin: Unknown driver \"%s\".", cfdev->driver);
296       return NULL;
297     }
298
299     if ((ret = sigrok_init_driver(cfdev, drv)) < 0)
300       /* Error was already logged. */
301       return NULL;
302
303     num_devices += ret;
304   }
305
306   if (num_devices > 0) {
307     /* Do this only when we're sure there's hardware to talk to. */
308     if (sr_session_datafeed_callback_add(sigrok_feed_callback, NULL) != SR_OK)
309       return NULL;
310
311     /* Start acquisition on all devices. */
312     if (sr_session_start() != SR_OK)
313       return NULL;
314
315     /* Main loop, runs forever. */
316     sr_session_run();
317
318     sr_session_stop();
319     sr_session_dev_remove_all();
320   }
321
322   sr_session_destroy();
323
324   sr_exit(sr_ctx);
325
326   pthread_exit(NULL);
327   sr_thread_running = FALSE;
328
329   return NULL;
330 }
331
332 static int sigrok_init(void) {
333   int status;
334
335   if (sr_thread_running) {
336     ERROR("sigrok plugin: Thread already running.");
337     return -1;
338   }
339
340   status = plugin_thread_create(&sr_thread, NULL, sigrok_read_thread, NULL,
341                                 "sigrok read");
342   if (status != 0) {
343     char errbuf[1024];
344     ERROR("sigrok plugin: Failed to create thread: %s.",
345           sstrerror(errno, errbuf, sizeof(errbuf)));
346     return -1;
347   }
348   sr_thread_running = TRUE;
349
350   return 0;
351 }
352
353 static int sigrok_shutdown(void) {
354   struct config_device *cfdev;
355   GSList *l;
356
357   if (sr_thread_running) {
358     pthread_cancel(sr_thread);
359     pthread_join(sr_thread, NULL);
360   }
361
362   for (l = config_devices; l; l = l->next) {
363     cfdev = l->data;
364     free(cfdev->name);
365     free(cfdev->driver);
366     free(cfdev->conn);
367     free(cfdev->serialcomm);
368     free(cfdev);
369   }
370   g_slist_free(config_devices);
371
372   return 0;
373 }
374
375 void module_register(void) {
376   plugin_register_complex_config("sigrok", sigrok_config);
377   plugin_register_init("sigrok", sigrok_init);
378   plugin_register_shutdown("sigrok", sigrok_shutdown);
379 }