Add missing kstat definitions
[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 #include "common.h"
24 #include "plugin.h"
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <time.h>
30 #include <pthread.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
57 static int sigrok_log_callback(void*cb_data __attribute__((unused)),
58                 int msg_loglevel, const char *format, va_list args)
59 {
60         char s[512];
61
62         if (msg_loglevel <= loglevel) {
63                 vsnprintf(s, 512, format, args);
64                 plugin_log(LOG_INFO, "sigrok plugin: %s", s);
65         }
66
67         return 0;
68 }
69
70 static int sigrok_config_device(oconfig_item_t *ci)
71 {
72         struct config_device *cfdev;
73         int i;
74
75         if (!(cfdev = malloc(sizeof(struct config_device)))) {
76                 ERROR("sigrok plugin: malloc() failed.");
77                 return -1;
78         }
79         memset(cfdev, 0, sizeof(*cfdev));
80         if (cf_util_get_string(ci, &cfdev->name)) {
81                 free(cfdev);
82                 WARNING("sigrok plugin: Invalid device name.");
83                 return -1;
84         }
85         cfdev->min_dispatch_interval = DEFAULT_MIN_DISPATCH_INTERVAL;
86
87         for (i = 0; i < ci->children_num; i++) {
88                 oconfig_item_t *item = ci->children + i;
89                 if (!strcasecmp(item->key, "driver"))
90                         cf_util_get_string(item, &cfdev->driver);
91                 else if (!strcasecmp(item->key, "conn"))
92                         cf_util_get_string(item, &cfdev->conn);
93                 else if (!strcasecmp(item->key, "serialcomm"))
94                         cf_util_get_string(item, &cfdev->serialcomm);
95                 else if (!strcasecmp(item->key, "minimuminterval"))
96                         cf_util_get_cdtime(item, &cfdev->min_dispatch_interval);
97                 else
98                         WARNING("sigrok plugin: Invalid keyword \"%s\".",
99                                         item->key);
100         }
101
102         config_devices = g_slist_append(config_devices, cfdev);
103
104         return 0;
105 }
106
107 static int sigrok_config(oconfig_item_t *ci)
108 {
109         int i;
110
111         for (i = 0; i < ci->children_num; i++) {
112                 oconfig_item_t *item = ci->children + i;
113                 if (strcasecmp("LogLevel", item->key) == 0) {
114                         int status;
115                         int tmp = -1;
116
117                         status = cf_util_get_int (item, &tmp);
118                         if (status != 0)
119                                 continue;
120                         else if ((tmp < 0) || (tmp > 5)) {
121                                 ERROR ("sigrok plugin: The \"LogLevel\" "
122                                                 "configuration option expects "
123                                                 "an integer between 0 and 5 "
124                                                 "(inclusive); you provided %i.",
125                                                 tmp);
126                                 continue;
127                         }
128                         loglevel = tmp;
129                 } else if (!strcasecmp(item->key, "Device"))
130                         sigrok_config_device(item);
131                 else
132                         WARNING("sigrok plugin: Invalid keyword \"%s\".",
133                                         item->key);
134         }
135
136         return 0;
137 }
138
139 static char *sigrok_value_type(const struct sr_datafeed_analog *analog)
140 {
141         char *s;
142
143         if (analog->mq == SR_MQ_VOLTAGE)
144                 s = "voltage";
145         else if (analog->mq == SR_MQ_CURRENT)
146                 s = "current";
147         else if (analog->mq == SR_MQ_FREQUENCY)
148                 s = "frequency";
149         else if (analog->mq == SR_MQ_POWER)
150                 s = "power";
151         else if (analog->mq == SR_MQ_TEMPERATURE)
152                 s = "temperature";
153         else if (analog->mq == SR_MQ_RELATIVE_HUMIDITY)
154                 s = "humidity";
155         else if (analog->mq == SR_MQ_SOUND_PRESSURE_LEVEL)
156                 s = "spl";
157         else
158                 s = "gauge";
159
160         return s;
161 }
162
163 static void sigrok_feed_callback(const struct sr_dev_inst *sdi,
164                 const struct sr_datafeed_packet *packet, void *cb_data)
165 {
166         const struct sr_datafeed_analog *analog;
167         struct config_device *cfdev;
168         GSList *l;
169         value_t value;
170         value_list_t vl = VALUE_LIST_INIT;
171
172         /* Find this device's configuration. */
173         cfdev = NULL;
174         for (l = config_devices; l; l = l->next) {
175                 cfdev = l->data;
176                 if (cfdev->sdi == sdi) {
177                         /* Found it. */
178                         break;
179                 }
180                 cfdev = NULL;
181         }
182
183         if (!cfdev) {
184                 ERROR("sigrok plugin: Received data from driver \"%s\" but "
185                                 "can't find a configuration / device matching "
186                                 "it.", sdi->driver->name);
187                 return;
188         }
189
190         if (packet->type == SR_DF_END) {
191                 /* TODO: try to restart acquisition after a delay? */
192                 WARNING("sigrok plugin: acquisition for \"%s\" ended.",
193                                 cfdev->name);
194                 return;
195         }
196
197         if (packet->type != SR_DF_ANALOG)
198                 return;
199
200         if ((cfdev->min_dispatch_interval != 0)
201                         && ((cdtime() - cfdev->last_dispatch)
202                                 < cfdev->min_dispatch_interval))
203                 return;
204
205         /* Ignore all but the first sample on the first probe. */
206         analog = packet->payload;
207         value.gauge = analog->data[0];
208         vl.values = &value;
209         vl.values_len = 1;
210         sstrncpy(vl.host, hostname_g, sizeof(vl.host));
211         sstrncpy(vl.plugin, "sigrok", sizeof(vl.plugin));
212         ssnprintf(vl.plugin_instance, sizeof(vl.plugin_instance),
213                         "%s", cfdev->name);
214         sstrncpy(vl.type, sigrok_value_type(analog), sizeof(vl.type));
215
216         plugin_dispatch_values(&vl);
217         cfdev->last_dispatch = cdtime();
218 }
219
220 static void sigrok_free_drvopts(struct sr_config *src)
221 {
222         g_variant_unref(src->data);
223         g_free(src);
224 }
225
226 static int sigrok_init_driver(struct config_device *cfdev,
227                 struct sr_dev_driver *drv)
228 {
229         struct sr_config *src;
230         GSList *devlist, *drvopts;
231         char hwident[512];
232
233         if (sr_driver_init(sr_ctx, drv) != SR_OK)
234                 /* Error was logged by libsigrok. */
235                 return -1;
236
237         drvopts = NULL;
238         if (cfdev->conn) {
239                 if (!(src = malloc(sizeof(struct sr_config))))
240                         return -1;
241                 src->key = SR_CONF_CONN;
242                 src->data = g_variant_new_string(cfdev->conn);
243                 drvopts = g_slist_append(drvopts, src);
244         }
245         if (cfdev->serialcomm) {
246                 if (!(src = malloc(sizeof(struct sr_config))))
247                         return -1;
248                 src->key = SR_CONF_SERIALCOMM;
249                 src->data = g_variant_new_string(cfdev->serialcomm);
250                 drvopts = g_slist_append(drvopts, src);
251         }
252         devlist = sr_driver_scan(drv, drvopts);
253         g_slist_free_full(drvopts, (GDestroyNotify)sigrok_free_drvopts);
254         if (!devlist) {
255                 /* Not an error, but the user should know about it. */
256                 WARNING("sigrok plugin: No device found for \"%s\".",
257                                 cfdev->name);
258                 return 0;
259         }
260
261         if (g_slist_length(devlist) > 1) {
262                 INFO("sigrok plugin: %d sigrok devices for device entry "
263                                 "\"%s\": must be 1.",
264                                 g_slist_length(devlist), cfdev->name);
265                 return -1;
266         }
267         cfdev->sdi = devlist->data;
268         g_slist_free(devlist);
269         ssnprintf(hwident, sizeof(hwident), "%s %s %s",
270                         cfdev->sdi->vendor ? cfdev->sdi->vendor : "",
271                         cfdev->sdi->model ? cfdev->sdi->model : "",
272                         cfdev->sdi->version ? cfdev->sdi->version : "");
273         INFO("sigrok plugin: Device \"%s\" is a %s", cfdev->name, hwident);
274
275         if (sr_dev_open(cfdev->sdi) != SR_OK)
276                 return -1;
277
278         if (sr_session_dev_add(cfdev->sdi) != SR_OK)
279                 return -1;
280
281         return 1;
282 }
283
284 static void *sigrok_read_thread(void *arg __attribute__((unused)))
285 {
286         struct sr_dev_driver *drv, **drvlist;
287         GSList *l;
288         struct config_device *cfdev;
289         int ret, i;
290
291         sr_log_callback_set(sigrok_log_callback, NULL);
292         sr_log_loglevel_set(loglevel);
293
294         if ((ret = sr_init(&sr_ctx)) != SR_OK) {
295                 ERROR("sigrok plugin: Failed to initialize libsigrok: %s.",
296                                 sr_strerror(ret));
297                 return NULL;
298         }
299
300         if (!sr_session_new())
301                 return NULL;
302
303         num_devices = 0;
304         drvlist = sr_driver_list();
305         for (l = config_devices; l; l = l->next) {
306                 cfdev = l->data;
307                 drv = NULL;
308                 for (i = 0; drvlist[i]; i++) {
309                         if (!strcmp(drvlist[i]->name, cfdev->driver)) {
310                                 drv = drvlist[i];
311                                 break;
312                         }
313                 }
314                 if (!drv) {
315                         ERROR("sigrok plugin: Unknown driver \"%s\".",
316                                         cfdev->driver);
317                         return NULL;
318                 }
319
320                 if ((ret = sigrok_init_driver(cfdev, drv)) < 0)
321                         /* Error was already logged. */
322                         return NULL;
323
324                 num_devices += ret;
325         }
326
327         if (num_devices > 0) {
328                 /* Do this only when we're sure there's hardware to talk to. */
329                 if (sr_session_datafeed_callback_add(sigrok_feed_callback, NULL)
330                                 != SR_OK)
331                         return NULL;
332
333                 /* Start acquisition on all devices. */
334                 if (sr_session_start() != SR_OK)
335                         return NULL;
336
337                 /* Main loop, runs forever. */
338                 sr_session_run();
339
340                 sr_session_stop();
341                 sr_session_dev_remove_all();
342         }
343
344         sr_session_destroy();
345
346         sr_exit(sr_ctx);
347
348         pthread_exit(NULL);
349         sr_thread_running = FALSE;
350
351         return NULL;
352 }
353
354 static int sigrok_init(void)
355 {
356         int status;
357
358         if (sr_thread_running) {
359                 ERROR("sigrok plugin: Thread already running.");
360                 return -1;
361         }
362
363         if ((status = plugin_thread_create(&sr_thread, NULL, sigrok_read_thread,
364                         NULL)) != 0) {
365                 ERROR("sigrok plugin: Failed to create thread: %s.",
366                                 strerror(status));
367                 return -1;
368         }
369         sr_thread_running = TRUE;
370
371         return 0;
372 }
373
374 static int sigrok_shutdown(void)
375 {
376         struct config_device *cfdev;
377         GSList *l;
378
379         if (sr_thread_running) {
380                 pthread_cancel(sr_thread);
381                 pthread_join(sr_thread, NULL);
382         }
383
384         for (l = config_devices; l; l = l->next) {
385                 cfdev = l->data;
386                 free(cfdev->name);
387                 free(cfdev->driver);
388                 free(cfdev->conn);
389                 free(cfdev->serialcomm);
390                 free(cfdev);
391         }
392         g_slist_free(config_devices);
393
394         return 0;
395 }
396
397 void module_register(void)
398 {
399         plugin_register_complex_config("sigrok", sigrok_config);
400         plugin_register_init("sigrok", sigrok_init);
401         plugin_register_shutdown("sigrok", sigrok_shutdown);
402 }