]> sigrok.org Git - libsigrokdecode.git/blob - controller.c
6bb7748ef05eee8b9890a665289f867a08833389
[libsigrokdecode.git] / controller.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "sigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "sigrokdecode-internal.h"
23 #include "config.h"
24 #include <glib.h>
25 #include <inttypes.h>
26 #include <stdlib.h>
27
28
29 static GSList *di_list = NULL;
30 static GSList *callbacks = NULL;
31
32 /* lives in decoder.c */
33 extern GSList *pd_list;
34
35 /* lives in module_sigrokdecode.c */
36 extern PyMODINIT_FUNC PyInit_sigrokdecode(void);
37
38 /* lives in type_logic.c */
39 extern PyTypeObject srd_logic_type;
40
41
42 /**
43  * Initialize libsigrokdecode.
44  *
45  * This initializes the Python interpreter, and creates and initializes
46  * a "sigrok" Python module with a single put() method.
47  *
48  * Then, it searches for sigrok protocol decoder files (*.py) in the
49  * "decoders" subdirectory of the the sigrok installation directory.
50  * All decoders that are found are loaded into memory and added to an
51  * internal list of decoders, which can be queried via srd_list_decoders().
52  *
53  * The caller is responsible for calling the clean-up function srd_exit(),
54  * which will properly shut down libsigrokdecode and free its allocated memory.
55  *
56  * Multiple calls to srd_init(), without calling srd_exit() in between,
57  * are not allowed.
58  *
59  * @return SRD_OK upon success, a (negative) error code otherwise.
60  *         Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
61  *         directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
62  *         If not enough memory could be allocated, return SRD_ERR_MALLOC.
63  */
64 int srd_init(void)
65 {
66         int ret;
67
68         PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
69
70         /* Py_Initialize() returns void and usually cannot fail. */
71         Py_Initialize();
72
73         if ((ret = set_modulepath()) != SRD_OK) {
74                 Py_Finalize();
75                 return ret;
76         }
77
78         if ((ret = srd_load_all_decoders()) != SRD_OK) {
79                 Py_Finalize();
80                 return ret;
81         }
82
83         return SRD_OK;
84 }
85
86
87 /**
88  * Shutdown libsigrokdecode.
89  *
90  * This frees all the memory allocated for protocol decoders and shuts down
91  * the Python interpreter.
92  *
93  * This function should only be called if there was a (successful!) invocation
94  * of srd_init() before. Calling this function multiple times in a row, without
95  * any successful srd_init() calls in between, is not allowed.
96  *
97  * @return SRD_OK upon success, a (negative) error code otherwise.
98  */
99 int srd_exit(void)
100 {
101         /* Unload/free all decoders, and then the list of decoders itself. */
102         /* TODO: Error handling. */
103         srd_unload_all_decoders();
104         g_slist_free(pd_list);
105
106         /* Py_Finalize() returns void, any finalization errors are ignored. */
107         Py_Finalize();
108
109         return SRD_OK;
110 }
111
112
113 /**
114  * Add search directories for the protocol decoders.
115  *
116  * TODO: add path from env var SIGROKDECODE_PATH, config etc
117  */
118 int set_modulepath(void)
119 {
120         int ret;
121
122         PyRun_SimpleString("import sys");
123         ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
124
125         return ret;
126 }
127
128
129 /**
130  * Set options in a decoder instance.
131  *
132  * @param di Decoder instance.
133  * @param options A GHashTable of options to set.
134  *
135  * Handled options are removed from the hash.
136  *
137  * @return SRD_OK upon success, a (negative) error code otherwise.
138  */
139 int srd_instance_set_options(struct srd_decoder_instance *di,
140                 GHashTable *options)
141 {
142         PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
143         PyObject *py_optlist, *py_classval;
144         Py_UNICODE *py_ustr;
145         unsigned long long int val_ull;
146         int num_optkeys, ret, size, i;
147         char *key, *value;
148
149         if (g_hash_table_size(options) == 0)
150                 /* No options provided. */
151                 return SRD_OK;
152
153         if(!PyObject_HasAttrString(di->decoder->py_dec, "options"))
154                 /* Decoder has no options. */
155                 return SRD_OK;
156
157         ret = SRD_ERR_PYTHON;
158         key = NULL;
159         py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
160         py_optlist = py_classval = NULL;
161         py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");
162         if (!PyDict_Check(py_dec_options)) {
163                 srd_err("Protocol decoder %s options is not a dictionary.",
164                                 di->decoder->name);
165                 goto err_out;
166         }
167
168         /* All of these are synthesized objects, so they're good. */
169         py_dec_optkeys = PyDict_Keys(py_dec_options);
170         num_optkeys = PyList_Size(py_dec_optkeys);
171         if (!(py_di_options = PyObject_GetAttrString(di->py_instance, "options")))
172                 goto err_out;
173         for (i = 0; i < num_optkeys; i++) {
174                 /* Get the default class value for this option. */
175                 py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
176                 if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
177                         goto err_out;
178                 if (!(py_classval = PyList_GetItem(py_optlist, 1)))
179                         goto err_out;
180
181                 if ((value = g_hash_table_lookup(options, key))) {
182                         /* An override for this option was provided. */
183                         if (PyUnicode_Check(py_classval)) {
184                                 if (!(py_optval = PyUnicode_FromString(value))) {
185                                         /* Some UTF-8 encoding error. */
186                                         PyErr_Clear();
187                                         goto err_out;
188                                 }
189                         } else if (PyLong_Check(py_classval)) {
190                                 if (!(py_optval = PyLong_FromString(value, NULL, 0))) {
191                                         /* ValueError Exception */
192                                         PyErr_Clear();
193                                         srd_err("Option %s has invalid value %s: expected integer",
194                                                         key, value);
195                                         goto err_out;
196                                 }
197                         }
198                         g_hash_table_remove(options, key);
199                 } else {
200                         /* Use the class default for this option. */
201                         if (PyUnicode_Check(py_classval)) {
202                                 /* Make a brand new copy of the string. */
203                                 py_ustr = PyUnicode_AS_UNICODE(py_classval);
204                                 size = PyUnicode_GET_SIZE(py_classval);
205                                 py_optval = PyUnicode_FromUnicode(py_ustr, size);
206                         } else if (PyLong_Check(py_classval)) {
207                                 /* Make a brand new copy of the integer. */
208                                 val_ull = PyLong_AsUnsignedLongLong(py_classval);
209                                 if (val_ull == (unsigned long long)-1) {
210                                         /* OverFlowError exception */
211                                         PyErr_Clear();
212                                         srd_err("Invalid integer value for %s: expected integer", key);
213                                         goto err_out;
214                                 }
215                                 if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
216                                         goto err_out;
217                         }
218                 }
219
220                 /* If we got here, py_optval holds a known good new reference
221                  * to the instance option to set.
222                  */
223                 if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
224                         goto err_out;
225         }
226
227         ret = SRD_OK;
228
229 err_out:
230         Py_XDECREF(py_optlist);
231         Py_XDECREF(py_di_options);
232         Py_XDECREF(py_dec_optkeys);
233         Py_XDECREF(py_dec_options);
234         if (key)
235                 g_free(key);
236         if (PyErr_Occurred()) {
237                 srd_dbg("stray exception!");
238                 PyErr_Print();
239                 PyErr_Clear();
240         }
241
242         return ret;
243 }
244
245 /**
246  * Set probes in a decoder instance.
247  *
248  * @param di Decoder instance.
249  * @param probes A GHashTable of probes to set. Key is probe name, value is
250  * the probe number. Samples passed to this instance will be arranged in this
251  * order.
252  *
253  * Handled probes are removed from the hash.
254  *
255  * @return SRD_OK upon success, a (negative) error code otherwise.
256  */
257 int srd_instance_set_probes(struct srd_decoder_instance *di,
258                 GHashTable *probes)
259 {
260         int ret;
261
262         if (g_hash_table_size(probes) == 0)
263                 /* No probes provided. */
264                 return SRD_OK;
265
266         if(!PyObject_HasAttrString(di->decoder->py_dec, "probes"))
267                 /* Decoder has no probes. */
268                 return SRD_OK;
269
270         ret = SRD_ERR_PYTHON;
271
272         /* TODO */
273         if (g_hash_table_size(probes) > 0) {
274                 srd_err("Setting probes is not yet supported.");
275                 return SRD_ERR_PYTHON;
276         }
277
278         ret = SRD_OK;
279
280         return ret;
281 }
282
283 /**
284  * Create a new protocol decoder instance.
285  *
286  * @param id Decoder 'id' field.
287  * @param options GHashtable of options which override the defaults set in
288  *          the decoder class.
289  * @return Pointer to a newly allocated struct srd_decoder_instance, or
290  *              NULL in case of failure.
291  */
292 struct srd_decoder_instance *srd_instance_new(const char *decoder_id,
293                 GHashTable *options)
294 {
295         struct srd_decoder *dec;
296         struct srd_decoder_instance *di;
297         char *instance_id;
298
299         srd_dbg("%s: creating new %s instance", __func__, decoder_id);
300
301         if (!(dec = srd_get_decoder_by_id(decoder_id))) {
302                 srd_err("Protocol decoder %s not found.", decoder_id);
303                 return NULL;
304         }
305
306         if (!(di = g_try_malloc0(sizeof(*di)))) {
307                 srd_err("Failed to malloc instance.");
308                 return NULL;
309         }
310
311         instance_id = g_hash_table_lookup(options, "id");
312         di->decoder = dec;
313         di->instance_id = g_strdup(instance_id ? instance_id : decoder_id);
314         g_hash_table_remove(options, "id");
315
316         /* Create a new instance of this decoder class. */
317         if (!(di->py_instance = PyObject_CallObject(dec->py_dec, NULL))) {
318                 if (PyErr_Occurred())
319                         PyErr_Print();
320                 g_free(di);
321                 return NULL;
322         }
323
324         /* Instance takes input from a frontend by default. */
325         di_list = g_slist_append(di_list, di);
326
327         if (srd_instance_set_options(di, options) != SRD_OK) {
328                 di_list = g_slist_remove(di_list, di);
329                 g_free(di);
330                 return NULL;
331         }
332
333         return di;
334 }
335
336 int srd_instance_stack(struct srd_decoder_instance *di_from,
337                 struct srd_decoder_instance *di_to)
338 {
339
340         if (!di_from || !di_to) {
341                 srd_err("invalid from/to instance pair");
342                 return SRD_ERR_ARG;
343         }
344
345         if (!g_slist_find(di_list, di_from)) {
346                 srd_err("unstacked instance not found");
347                 return SRD_ERR_ARG;
348         }
349
350         /* Remove from the unstacked list. */
351         di_list = g_slist_remove(di_list, di_to);
352
353         /* Stack on top of source di. */
354         di_from->next_di = g_slist_append(di_from->next_di, di_to);
355
356         return SRD_OK;
357 }
358
359
360 /* TODO: this should go into the PD stack */
361 struct srd_decoder_instance *srd_instance_find(char *instance_id)
362 {
363         GSList *l;
364         struct srd_decoder_instance *tmp, *di;
365
366         di = NULL;
367         for (l = di_list; l; l = l->next) {
368                 tmp = l->data;
369                 if (!strcmp(tmp->instance_id, instance_id)) {
370                         di = tmp;
371                         break;
372                 }
373         }
374
375         return di;
376 }
377
378 int srd_instance_start(struct srd_decoder_instance *di, PyObject *args)
379 {
380         PyObject *py_name, *py_res;
381
382         srd_dbg("calling start() method on protocol decoder instance %s", di->instance_id);
383
384         if (!(py_name = PyUnicode_FromString("start"))) {
385                 srd_err("unable to build python object for 'start'");
386                 if (PyErr_Occurred())
387                         PyErr_Print();
388                 return SRD_ERR_PYTHON;
389         }
390
391         if (!(py_res = PyObject_CallMethodObjArgs(di->py_instance,
392                         py_name, args, NULL))) {
393                 if (PyErr_Occurred())
394                         PyErr_Print();
395                 return SRD_ERR_PYTHON;
396         }
397
398         Py_XDECREF(py_res);
399         Py_DECREF(py_name);
400
401         return SRD_OK;
402 }
403
404 /**
405  * Run the specified decoder function.
406  *
407  * @param dec TODO
408  * @param inbuf TODO
409  * @param inbuflen TODO
410  *
411  * @return SRD_OK upon success, a (negative) error code otherwise.
412  */
413 int srd_instance_decode(uint64_t start_samplenum,
414                 struct srd_decoder_instance *di, uint8_t *inbuf, uint64_t inbuflen)
415 {
416         PyObject *py_instance, *py_res;
417         srd_logic *logic;
418         uint64_t end_samplenum;
419
420         /* Return an error upon unusable input. */
421         if (di == NULL)
422                 return SRD_ERR_ARG; /* TODO: More specific error? */
423         if (inbuf == NULL)
424                 return SRD_ERR_ARG; /* TODO: More specific error? */
425         if (inbuflen == 0) /* No point in working on empty buffers. */
426                 return SRD_ERR_ARG; /* TODO: More specific error? */
427
428         /* TODO: Error handling. */
429         py_instance = di->py_instance;
430         Py_XINCREF(py_instance);
431
432         logic = PyObject_New(srd_logic, &srd_logic_type);
433         Py_INCREF(logic);
434         logic->di = di;
435         logic->start_samplenum = start_samplenum;
436         logic->itercnt = 0;
437         logic->inbuf = inbuf;
438         logic->inbuflen = inbuflen;
439         logic->sample = PyList_New(2);
440         Py_INCREF(logic->sample);
441
442         end_samplenum = start_samplenum + inbuflen / di->unitsize;
443         if (!(py_res = PyObject_CallMethod(py_instance, "decode",
444                         "KKO", logic->start_samplenum, end_samplenum, logic))) {
445                 if (PyErr_Occurred())
446                         PyErr_Print(); /* Returns void. */
447
448                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
449         }
450
451         Py_XDECREF(py_res);
452
453         return SRD_OK;
454 }
455
456
457 int srd_session_start(int num_probes, int unitsize, uint64_t samplerate)
458 {
459         PyObject *args;
460         GSList *d, *s;
461         struct srd_decoder_instance *di;
462         int ret;
463
464         if (!(args = Py_BuildValue("{s:l}", "samplerate", (long)samplerate))) {
465                 srd_err("unable to build python object for metadata");
466                 return SRD_ERR_PYTHON;
467         }
468
469         /* Run the start() method on all decoders receiving frontend data. */
470         for (d = di_list; d; d = d->next) {
471                 di = d->data;
472                 di->num_probes = num_probes;
473                 di->unitsize = unitsize;
474                 di->samplerate = samplerate;
475                 if ((ret = srd_instance_start(di, args) != SRD_OK))
476                         return ret;
477
478                 /* Run the start() method on all decoders up the stack from this one. */
479                 for (s = di->next_di; s; s = s->next) {
480                         /* These don't need probes, unitsize and samplerate. */
481                         di = s->data;
482                         if ((ret = srd_instance_start(di, args) != SRD_OK))
483                                 return ret;
484                 }
485         }
486
487         Py_DECREF(args);
488
489         return SRD_OK;
490 }
491
492 /* Feed logic samples to decoder session. */
493 int srd_session_feed(uint64_t start_samplenum, uint8_t *inbuf, uint64_t inbuflen)
494 {
495         GSList *d;
496         int ret;
497
498         for (d = di_list; d; d = d->next) {
499                 if ((ret = srd_instance_decode(start_samplenum, d->data, inbuf,
500                                 inbuflen)) != SRD_OK)
501                         return ret;
502         }
503
504         return SRD_OK;
505 }
506
507
508 int pd_add(struct srd_decoder_instance *di, int output_type,
509                 char *proto_id)
510 {
511         struct srd_pd_output *pdo;
512
513         if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
514                 return -1;
515
516         /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
517         pdo->pdo_id = g_slist_length(di->pd_output);
518         pdo->output_type = output_type;
519         pdo->decoder = di->decoder;
520         pdo->proto_id = g_strdup(proto_id);
521         di->pd_output = g_slist_append(di->pd_output, pdo);
522
523         return pdo->pdo_id;
524 }
525
526 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
527 {
528         GSList *l, *s;
529         struct srd_decoder_instance *di;
530
531         for (l = di_list; l; l = l->next) {
532                 di = l->data;
533                 if (decobject == di->py_instance)
534                         return di;
535                 /* Check decoders stacked on top of this one. */
536                 for (s = di->next_di; s; s = s->next) {
537                         di = s->data;
538                         if (decobject == di->py_instance)
539                                 return di;
540                 }
541         }
542
543         return NULL;
544 }
545
546 int srd_register_callback(int output_type, void *cb)
547 {
548         struct srd_pd_callback *pd_cb;
549
550         if (!(pd_cb = g_try_malloc(sizeof(struct srd_pd_callback))))
551                 return SRD_ERR_MALLOC;
552
553         pd_cb->output_type = output_type;
554         pd_cb->callback = cb;
555         callbacks = g_slist_append(callbacks, pd_cb);
556
557         return SRD_OK;
558 }
559
560 void *srd_find_callback(int output_type)
561 {
562         GSList *l;
563         struct srd_pd_callback *pd_cb;
564         void *(cb);
565
566         cb = NULL;
567         for (l = callbacks; l; l = l->next) {
568                 pd_cb = l->data;
569                 if (pd_cb->output_type == output_type) {
570                         cb = pd_cb->callback;
571                         break;
572                 }
573         }
574
575         return cb;
576 }
577