]> sigrok.org Git - libsigrokdecode.git/blame - decode.c
srd: Changed nunchuk and transitioncounter to new registraion api.
[libsigrokdecode.git] / decode.c
CommitLineData
1c6fa20f
UH
1/*
2 * This file is part of the sigrok project.
3 *
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
17830fe1 21#include "config.h"
1c6fa20f
UH
22#include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
23#include <stdio.h>
5c55017c 24#include <string.h>
7c24d086 25#include <dirent.h>
1c6fa20f 26
e6c7a826
UH
27/* Re-define some string functions for Python >= 3.0. */
28#if PY_VERSION_HEX >= 0x03000000
29#define PyString_AsString PyBytes_AsString
30#define PyString_FromString PyBytes_FromString
31#define PyString_Check PyBytes_Check
32#endif
33
7c24d086 34/* The list of protocol decoders. */
a0d48257 35static GSList *list_pds = NULL;
60b928b2
GM
36/* The list of protocol decoder instances: struct srd_decoder_instance */
37static GSList *decoders;
7c24d086 38
f800adc4
UH
39/*
40 * Here's a quick overview of Python/C API reference counting.
41 *
42 * Check the Python/C API docs for what type of reference a function returns.
43 *
2557ad9d 44 * - If it returns a "new reference", you're responsible to Py_XDECREF() it.
f800adc4 45 *
2557ad9d 46 * - If it returns a "borrowed reference", you MUST NOT Py_XDECREF() it.
f800adc4
UH
47 *
48 * - If a function "steals" a reference, you no longer are responsible for
2557ad9d 49 * Py_XDECREF()ing it (someone else will do it for you at some point).
f800adc4
UH
50 */
51
67e847fd
GM
52static int srd_load_decoder(PyObject *py_res);
53
54static PyObject *emb_register(PyObject *self, PyObject *args)
55{
56 PyObject *arg;
57
58 (void)self;
59
60 if (!PyArg_ParseTuple(args, "O:decoder", &arg))
61 return NULL;
62
63 srd_load_decoder(arg);
64
65 Py_RETURN_NONE;
66}
53bec0cf 67
261d6532 68static PyObject *emb_put(PyObject *self, PyObject *args)
922763ab
KS
69{
70 PyObject *arg;
261d6532 71
6eb87578
GM
72 (void)self;
73
922763ab
KS
74 if (!PyArg_ParseTuple(args, "O:put", &arg))
75 return NULL;
76
3b24e378 77 PyObject_Print(arg, stdout, Py_PRINT_RAW);
74911b4c 78 puts("");
3b24e378 79
922763ab
KS
80 Py_RETURN_NONE;
81}
82
83static PyMethodDef EmbMethods[] = {
67e847fd
GM
84 {"register", emb_register, METH_VARARGS,
85 "Register a protocol decoder object with libsigrokdecode."},
922763ab 86 {"put", emb_put, METH_VARARGS,
261d6532 87 "Accepts a dictionary with the following keys: time, duration, data"},
922763ab
KS
88 {NULL, NULL, 0, NULL}
89};
90
1c6fa20f
UH
91/**
92 * Initialize libsigrokdecode.
93 *
c75080f0
UH
94 * This initializes the Python interpreter, and creates and initializes
95 * a "sigrok" Python module with a single put() method.
96 *
97 * Then, it searches for sigrok protocol decoder files (*.py) in the
98 * "decoders" subdirectory of the the sigrok installation directory.
99 * All decoders that are found are loaded into memory and added to an
100 * internal list of decoders, which can be queried via srd_list_decoders().
101 *
102 * The caller is responsible for calling the clean-up function srd_exit(),
103 * which will properly shut down libsigrokdecode and free its allocated memory.
104 *
105 * Multiple calls to srd_init(), without calling srd_exit() inbetween,
106 * are not allowed.
107 *
d752b12b 108 * @return SRD_OK upon success, a (negative) error code otherwise.
c75080f0
UH
109 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
110 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
111 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
1c6fa20f 112 */
d752b12b 113int srd_init(void)
1c6fa20f 114{
7c24d086
UH
115 DIR *dir;
116 struct dirent *dp;
53bec0cf 117 char *decodername;
d752b12b 118 struct srd_decoder *dec;
53bec0cf 119 int ret;
7c24d086 120
1c6fa20f
UH
121 /* Py_Initialize() returns void and usually cannot fail. */
122 Py_Initialize();
123
0d1cf0f8
UH
124 /* TODO: Use Py_InitModule3() to add a docstring? */
125 if (!Py_InitModule("sigrok", EmbMethods)) {
126 Py_Finalize(); /* Returns void. */
127 return SRD_ERR_PYTHON;
128 }
922763ab 129
0895f56a 130 /* Add search directory for the protocol decoders. */
70e44845 131 /* FIXME: What happens if this function is called multiple times? */
0d1cf0f8
UH
132 ret = PyRun_SimpleString("import sys;"
133 "sys.path.append(r'" DECODERS_DIR "');");
134 if (ret != 0) {
135 Py_Finalize(); /* Returns void. */
136 return SRD_ERR_PYTHON;
137 }
1c6fa20f 138
0d1cf0f8
UH
139 if (!(dir = opendir(DECODERS_DIR))) {
140 Py_Finalize(); /* Returns void. */
d752b12b 141 return SRD_ERR_DECODERS_DIR;
0d1cf0f8 142 }
7c24d086
UH
143
144 while ((dp = readdir(dir)) != NULL) {
261d6532 145 /* Ignore filenames which don't end with ".py". */
276b55eb 146 if (!g_str_has_suffix(dp->d_name, ".py"))
7c24d086 147 continue;
53bec0cf
UH
148
149 /* Decoder name == filename (without .py suffix). */
150 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
151
261d6532 152 /* TODO: Error handling. Use g_try_malloc(). */
0d1cf0f8
UH
153 if (!(dec = malloc(sizeof(struct srd_decoder)))) {
154 Py_Finalize(); /* Returns void. */
155 return SRD_ERR_MALLOC;
156 }
53bec0cf
UH
157
158 /* Load the decoder. */
67e847fd
GM
159 /* "Import" the Python module. */
160 PyObject *py_mod;
161 if (!(py_mod = PyImport_ImportModule(decodername))) { /* NEWREF */
162 PyErr_Print(); /* Returns void. */
163 return SRD_ERR_PYTHON; /* TODO: More specific error? */
3b24e378 164 }
67e847fd
GM
165 /* We release here. If any decoders were registered they
166 * will hold references. */
167 Py_XDECREF(py_mod);
7c24d086
UH
168 }
169 closedir(dir);
170
d752b12b 171 return SRD_OK;
1c6fa20f
UH
172}
173
871d21e2
UH
174/**
175 * Returns the list of supported/loaded protocol decoders.
176 *
177 * This is a GSList containing the names of the decoders as strings.
178 *
179 * @return List of decoders, NULL if none are supported or loaded.
180 */
d752b12b 181GSList *srd_list_decoders(void)
871d21e2
UH
182{
183 return list_pds;
184}
185
53bec0cf
UH
186/**
187 * Get the decoder with the specified ID.
188 *
189 * @param id The ID string of the decoder to return.
190 * @return The decoder with the specified ID, or NULL if not found.
191 */
d752b12b 192struct srd_decoder *srd_get_decoder_by_id(const char *id)
53bec0cf
UH
193{
194 GSList *l;
d752b12b 195 struct srd_decoder *dec;
53bec0cf 196
d752b12b 197 for (l = srd_list_decoders(); l; l = l->next) {
53bec0cf
UH
198 dec = l->data;
199 if (!strcmp(dec->id, id))
200 return dec;
201 }
202
203 return NULL;
204}
205
5c55017c
UH
206/**
207 * Helper function to handle Python strings.
208 *
209 * TODO: @param entries.
210 *
d752b12b 211 * @return SRD_OK upon success, a (negative) error code otherwise.
70e44845 212 * The 'outstr' argument points to a malloc()ed string upon success.
5c55017c 213 */
67e847fd 214static int h_str(PyObject *py_res, const char *key, char **outstr)
5c55017c
UH
215{
216 PyObject *py_str;
217 char *str;
f7313eea 218 int ret;
5c55017c 219
6eb87578 220 py_str = PyObject_GetAttrString(py_res, (char *)key); /* NEWREF */
5c55017c 221 if (!py_str || !PyString_Check(py_str)) {
d752b12b 222 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
922763ab 223 goto err_h_decref_mod;
5c55017c
UH
224 }
225
6b08da24
UH
226 /*
227 * PyString_AsString()'s returned string refers to an internal buffer
228 * (not a copy), i.e. the data must not be modified, and the memory
229 * must not be free()'d.
230 */
5c55017c 231 if (!(str = PyString_AsString(py_str))) {
d752b12b 232 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
f7313eea 233 goto err_h_decref_str;
5c55017c
UH
234 }
235
f9b54a6c 236 if (!(*outstr = g_strdup(str))) {
d752b12b 237 ret = SRD_ERR_MALLOC;
f7313eea 238 goto err_h_decref_str;
5c55017c
UH
239 }
240
2557ad9d 241 Py_XDECREF(py_str);
5c55017c 242
d752b12b 243 return SRD_OK;
f7313eea
UH
244
245err_h_decref_str:
246 Py_XDECREF(py_str);
922763ab 247err_h_decref_mod:
f7313eea
UH
248
249 if (PyErr_Occurred())
250 PyErr_Print(); /* Returns void. */
251
252 return ret;
5c55017c
UH
253}
254
1c6fa20f
UH
255/**
256 * TODO
257 *
258 * @param name TODO
70e44845 259 *
d752b12b 260 * @return SRD_OK upon success, a (negative) error code otherwise.
1c6fa20f 261 */
67e847fd 262static int srd_load_decoder(PyObject *py_res)
1c6fa20f 263{
d752b12b 264 struct srd_decoder *d;
5c55017c 265 int r;
261d6532 266
d752b12b
UH
267 if (!(d = malloc(sizeof(struct srd_decoder))))
268 return SRD_ERR_MALLOC;
5c55017c 269
67e847fd
GM
270 if ((r = h_str(py_res, "id", &(d->id))) < 0)
271 return r;
5c55017c 272
67e847fd 273 if ((r = h_str(py_res, "name", &(d->name))) < 0)
5c55017c
UH
274 return r;
275
67e847fd 276 if ((r = h_str(py_res, "longname",
75a282e5
UH
277 &(d->longname))) < 0)
278 return r;
279
67e847fd 280 if ((r = h_str(py_res, "desc", &(d->desc))) < 0)
5c55017c
UH
281 return r;
282
67e847fd 283 if ((r = h_str(py_res, "longdesc",
75a282e5
UH
284 &(d->longdesc))) < 0)
285 return r;
286
67e847fd 287 if ((r = h_str(py_res, "author", &(d->author))) < 0)
75a282e5
UH
288 return r;
289
67e847fd 290 if ((r = h_str(py_res, "email", &(d->email))) < 0)
75a282e5
UH
291 return r;
292
67e847fd 293 if ((r = h_str(py_res, "license", &(d->license))) < 0)
75a282e5
UH
294 return r;
295
6eb87578 296 d->py_decobj = py_res;
5c55017c 297
74911b4c
GM
298 /* TODO: Handle func, inputformats, outputformats. */
299 /* Note: They must at least be set to NULL, will segfault otherwise. */
300 d->func = NULL;
301 d->inputformats = NULL;
302 d->outputformats = NULL;
303
67e847fd
GM
304 Py_INCREF(py_res);
305 fprintf(stderr, "srd: registered '%s'\n", d->id);
306 list_pds = g_slist_append(list_pds, d);
74911b4c
GM
307
308 return SRD_OK;
309}
310
60b928b2 311/** Create a new decoder instance and add to session. */
74911b4c
GM
312struct srd_decoder_instance *srd_instance_new(const char *id)
313{
261d6532
UH
314 struct srd_decoder *dec;
315 struct srd_decoder_instance *di;
3643fc3f 316 PyObject *py_args;
74911b4c 317
261d6532
UH
318 if (!(dec = srd_get_decoder_by_id(id)))
319 return NULL;
320
321 /* TODO: Error handling. Use g_try_malloc(). */
322 di = g_malloc(sizeof(*di));
323
324 /* Create an empty Python tuple. */
6eb87578 325 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
5c55017c 326 if (PyErr_Occurred())
6b08da24 327 PyErr_Print(); /* Returns void. */
261d6532 328
74911b4c 329 return NULL; /* TODO: More specific error? */
5c55017c 330 }
74911b4c 331
261d6532 332 /* Create an instance of the 'Decoder' class. */
3643fc3f 333 di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
74911b4c 334 if (!di->py_instance) {
6eb87578
GM
335 if (PyErr_Occurred())
336 PyErr_Print(); /* Returns void. */
74911b4c 337 Py_XDECREF(py_args);
74911b4c 338 return NULL; /* TODO: More specific error? */
261d6532 339 }
5c55017c 340
60b928b2
GM
341 /* Append to list of PD instances */
342 decoders = g_slist_append(decoders, di);
343
74911b4c 344 Py_XDECREF(py_args);
910e5fd8 345
74911b4c 346 return di;
1c6fa20f
UH
347}
348
f97f531c 349int srd_instance_set_probe(struct srd_decoder_instance *di,
261d6532 350 const char *probename, int num)
f97f531c
GM
351{
352 PyObject *probedict, *probenum;
261d6532 353
f97f531c
GM
354 probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
355 if (!probedict) {
356 if (PyErr_Occurred())
357 PyErr_Print(); /* Returns void. */
261d6532 358
f97f531c
GM
359 return SRD_ERR_PYTHON; /* TODO: More specific error? */
360 }
361
362 probenum = PyInt_FromLong(num);
261d6532 363 PyMapping_SetItemString(probedict, (char *)probename, probenum);
f97f531c
GM
364
365 Py_XDECREF(probenum);
366 Py_XDECREF(probedict);
261d6532 367
f97f531c
GM
368 return SRD_OK;
369}
370
60b928b2
GM
371/** Start decoding session. Feed metadata to decoder instances. */
372int srd_session_start(const char *driver, int unitsize, uint64_t starttime,
73e542a4 373 uint64_t samplerate)
3643fc3f
GM
374{
375 PyObject *py_res;
60b928b2
GM
376 GSList *d;
377 for (d = decoders; d; d = d->next) {
378 struct srd_decoder_instance *di = d->data;
379 /* TODO: Error handling. */
380 if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
381 "{s:s,s:l,s:l,s:l}",
382 "driver", driver,
383 "unitsize", (long)unitsize,
384 "starttime", (long)starttime,
385 "samplerate", (long)samplerate))) {
386 if (PyErr_Occurred())
387 PyErr_Print(); /* Returns void. */
388
389 return SRD_ERR_PYTHON; /* TODO: More specific error? */
390 }
391 Py_XDECREF(py_res);
3643fc3f 392 }
60b928b2 393
3643fc3f
GM
394 return SRD_OK;
395}
396
1c6fa20f
UH
397/**
398 * Run the specified decoder function.
399 *
5c55017c 400 * @param dec TODO
1c6fa20f
UH
401 * @param inbuf TODO
402 * @param inbuflen TODO
403 * @param outbuf TODO
404 * @param outbuflen TODO
70e44845 405 *
d752b12b 406 * @return SRD_OK upon success, a (negative) error code otherwise.
1c6fa20f 407 */
60b928b2
GM
408static int srd_run_decoder(struct srd_decoder_instance *dec,
409 uint8_t *inbuf, uint64_t inbuflen)
1c6fa20f 410{
3643fc3f 411 PyObject *py_instance, *py_res;
9d29ffad
KS
412 /* FIXME: Don't have a timebase available here. Make one up. */
413 static int _timehack = 0;
261d6532 414
9d29ffad 415 _timehack += inbuflen;
1c6fa20f
UH
416
417 /* TODO: Use #defines for the return codes. */
418
419 /* Return an error upon unusable input. */
5c55017c 420 if (dec == NULL)
d752b12b 421 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 422 if (inbuf == NULL)
d752b12b 423 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 424 if (inbuflen == 0) /* No point in working on empty buffers. */
d752b12b 425 return SRD_ERR_ARGS; /* TODO: More specific error? */
261d6532 426
5c55017c 427 /* TODO: Error handling. */
052f32ee
GM
428 py_instance = dec->py_instance;
429 Py_XINCREF(py_instance);
1c6fa20f 430
261d6532 431 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
3643fc3f
GM
432 "{s:i,s:i,s:s#}",
433 "time", _timehack,
434 "duration", 10,
435 "data", inbuf, inbuflen))) { /* NEWREF */
436 if (PyErr_Occurred())
437 PyErr_Print(); /* Returns void. */
9d29ffad 438
3643fc3f
GM
439 return SRD_ERR_PYTHON; /* TODO: More specific error? */
440 }
036e6f67 441
2557ad9d 442 Py_XDECREF(py_res);
3643fc3f 443 return SRD_OK;
1c6fa20f
UH
444}
445
60b928b2
GM
446/* Feed logic samples to decoder session. */
447int srd_session_feed(uint8_t *inbuf, uint64_t inbuflen)
448{
449 GSList *d;
450 for (d = decoders; d; d = d->next) {
451 /* TODO: Error handling. */
452
453 int ret = srd_run_decoder(d->data, inbuf, inbuflen);
454
455 if (ret != SRD_OK) {
67e847fd 456 /* This probably shouldn't fail catastrophically. */
60b928b2
GM
457 fprintf(stderr, "Decoder runtime error (%d)\n", ret);
458 exit(1);
459 }
460 }
67e847fd 461 return SRD_OK;
60b928b2
GM
462}
463
f9b54a6c
UH
464/**
465 * TODO
466 */
d752b12b 467static int srd_unload_decoder(struct srd_decoder *dec)
f9b54a6c
UH
468{
469 g_free(dec->id);
470 g_free(dec->name);
471 g_free(dec->desc);
472 g_free(dec->func);
473
474 /* TODO: Free everything in inputformats and outputformats. */
475
476 if (dec->inputformats != NULL)
477 g_slist_free(dec->inputformats);
478 if (dec->outputformats != NULL)
479 g_slist_free(dec->outputformats);
480
74911b4c 481 Py_XDECREF(dec->py_decobj);
f9b54a6c 482
0d1cf0f8
UH
483 /* TODO: (g_)free dec itself? */
484
d752b12b 485 return SRD_OK;
f9b54a6c
UH
486}
487
488/**
489 * TODO
490 */
d752b12b 491static int srd_unload_all_decoders(void)
f9b54a6c
UH
492{
493 GSList *l;
d752b12b 494 struct srd_decoder *dec;
f9b54a6c 495
d752b12b 496 for (l = srd_list_decoders(); l; l = l->next) {
f9b54a6c
UH
497 dec = l->data;
498 /* TODO: Error handling. */
d752b12b 499 srd_unload_decoder(dec);
f9b54a6c
UH
500 }
501
d752b12b 502 return SRD_OK;
f9b54a6c
UH
503}
504
1c6fa20f
UH
505/**
506 * Shutdown libsigrokdecode.
507 *
c75080f0
UH
508 * This frees all the memory allocated for protocol decoders and shuts down
509 * the Python interpreter.
510 *
511 * This function should only be called if there was a (successful!) invocation
512 * of srd_init() before. Calling this function multiple times in a row, without
513 * any successful srd_init() calls inbetween, is not allowed.
514 *
d752b12b 515 * @return SRD_OK upon success, a (negative) error code otherwise.
1c6fa20f 516 */
7ea73e33 517int srd_exit(void)
1c6fa20f 518{
f9b54a6c
UH
519 /* Unload/free all decoders, and then the list of decoders itself. */
520 /* TODO: Error handling. */
d752b12b 521 srd_unload_all_decoders();
f9b54a6c
UH
522 g_slist_free(list_pds);
523
1c6fa20f
UH
524 /* Py_Finalize() returns void, any finalization errors are ignored. */
525 Py_Finalize();
526
d752b12b 527 return SRD_OK;
1c6fa20f 528}