2 * This file is part of the sigrok project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
21 #include "sigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "sigrokdecode-internal.h"
28 static GSList *di_list = NULL;
29 static GSList *callbacks = NULL;
31 /* lives in decoder.c */
32 extern GSList *pd_list;
34 /* lives in module_sigrokdecode.c */
35 extern PyMODINIT_FUNC PyInit_sigrokdecode(void);
37 /* lives in type_logic.c */
38 extern PyTypeObject srd_logic_type;
42 * Initialize libsigrokdecode.
44 * This initializes the Python interpreter, and creates and initializes
45 * a "sigrok" Python module with a single put() method.
47 * Then, it searches for sigrok protocol decoder files (*.py) in the
48 * "decoders" subdirectory of the the sigrok installation directory.
49 * All decoders that are found are loaded into memory and added to an
50 * internal list of decoders, which can be queried via srd_list_decoders().
52 * The caller is responsible for calling the clean-up function srd_exit(),
53 * which will properly shut down libsigrokdecode and free its allocated memory.
55 * Multiple calls to srd_init(), without calling srd_exit() in between,
58 * @return SRD_OK upon success, a (negative) error code otherwise.
59 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
60 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
61 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
67 PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
69 /* Py_Initialize() returns void and usually cannot fail. */
72 if ((ret = set_modulepath()) != SRD_OK) {
77 if ((ret = srd_load_all_decoders()) != SRD_OK) {
87 * Shutdown libsigrokdecode.
89 * This frees all the memory allocated for protocol decoders and shuts down
90 * the Python interpreter.
92 * This function should only be called if there was a (successful!) invocation
93 * of srd_init() before. Calling this function multiple times in a row, without
94 * any successful srd_init() calls in between, is not allowed.
96 * @return SRD_OK upon success, a (negative) error code otherwise.
100 /* Unload/free all decoders, and then the list of decoders itself. */
101 /* TODO: Error handling. */
102 srd_unload_all_decoders();
103 g_slist_free(pd_list);
105 /* Py_Finalize() returns void, any finalization errors are ignored. */
113 * Add search directories for the protocol decoders.
115 * TODO: add path from env var SIGROKDECODE_PATH, config etc
117 int set_modulepath(void)
121 PyRun_SimpleString("import sys");
122 ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
129 * Create a new protocol decoder instance.
131 * TODO: this should be a decoder name, as decoder ids will disappear.
133 * @param id Decoder 'id' field.
134 * @param instance_id Optional unique identifier for this instance. If NULL,
135 * the 'id' parameter is used.
136 * @return Pointer to a newly allocated struct srd_decoder_instance, or
137 * NULL in case of failure.
139 struct srd_decoder_instance *srd_instance_new(const char *id,
140 const char *instance_id)
142 struct srd_decoder *dec;
143 struct srd_decoder_instance *di;
146 srd_dbg("%s: creating new %s instance", __func__, id);
148 if (!(dec = srd_get_decoder_by_id(id)))
151 if (!(di = g_try_malloc(sizeof(*di)))) {
152 srd_err("failed to malloc instance");
156 di->instance_id = g_strdup(instance_id ? instance_id : id);
157 di->pd_output = NULL;
163 /* Create an empty Python tuple. */
164 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
165 if (PyErr_Occurred())
170 /* Create an instance of the 'Decoder' class. */
171 di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
172 if (!di->py_instance) {
173 if (PyErr_Occurred())
179 /* Instance takes input from a frontend by default. */
180 di_list = g_slist_append(di_list, di);
187 int srd_instance_stack(struct srd_decoder_instance *di_from,
188 struct srd_decoder_instance *di_to)
191 if (!di_from || !di_to) {
192 srd_err("invalid from/to instance pair");
196 if (!g_slist_find(di_list, di_from)) {
197 srd_err("unstacked instance not found");
201 /* Remove from the unstacked list. */
202 di_list = g_slist_remove(di_list, di_to);
204 /* Stack on top of source di. */
205 di_from->next_di = g_slist_append(di_from->next_di, di_to);
211 int srd_instance_set_probe(struct srd_decoder_instance *di,
212 const char *probename, int num)
214 PyObject *probedict, *probenum;
216 probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
218 if (PyErr_Occurred())
219 PyErr_Print(); /* Returns void. */
221 return SRD_ERR_PYTHON; /* TODO: More specific error? */
224 probenum = PyLong_FromLong(num);
225 PyMapping_SetItemString(probedict, (char *)probename, probenum);
227 Py_XDECREF(probenum);
228 Py_XDECREF(probedict);
233 struct srd_decoder_instance *srd_instance_find(char *instance_id)
236 struct srd_decoder_instance *tmp, *di;
239 for (l = di_list; l; l = l->next) {
241 if (!strcmp(tmp->instance_id, instance_id)) {
250 int srd_instance_start(struct srd_decoder_instance *di, PyObject *args)
252 PyObject *py_name, *py_res;
254 srd_dbg("calling start() method on protocol decoder instance %s", di->instance_id);
256 if (!(py_name = PyUnicode_FromString("start"))) {
257 srd_err("unable to build python object for 'start'");
258 if (PyErr_Occurred())
260 return SRD_ERR_PYTHON;
263 if (!(py_res = PyObject_CallMethodObjArgs(di->py_instance,
264 py_name, args, NULL))) {
265 if (PyErr_Occurred())
267 return SRD_ERR_PYTHON;
277 * Run the specified decoder function.
281 * @param inbuflen TODO
283 * @return SRD_OK upon success, a (negative) error code otherwise.
285 int srd_instance_decode(uint64_t timeoffset, uint64_t duration,
286 struct srd_decoder_instance *di, uint8_t *inbuf, uint64_t inbuflen)
288 PyObject *py_instance, *py_res;
291 /* Return an error upon unusable input. */
293 return SRD_ERR_ARG; /* TODO: More specific error? */
295 return SRD_ERR_ARG; /* TODO: More specific error? */
296 if (inbuflen == 0) /* No point in working on empty buffers. */
297 return SRD_ERR_ARG; /* TODO: More specific error? */
299 /* TODO: Error handling. */
300 py_instance = di->py_instance;
301 Py_XINCREF(py_instance);
303 logic = PyObject_New(srd_logic, &srd_logic_type);
307 logic->inbuf = inbuf;
308 logic->inbuflen = inbuflen;
309 logic->sample = PyList_New(2);
310 Py_INCREF(logic->sample);
312 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
313 "KKO", timeoffset, duration, logic))) {
314 if (PyErr_Occurred())
315 PyErr_Print(); /* Returns void. */
317 return SRD_ERR_PYTHON; /* TODO: More specific error? */
326 int srd_session_start(int num_probes, int unitsize, uint64_t samplerate)
330 struct srd_decoder_instance *di;
333 if (!(args = Py_BuildValue("{s:l}", "samplerate", (long)samplerate))) {
334 srd_err("unable to build python object for metadata");
335 return SRD_ERR_PYTHON;
338 /* Run the start() method on all decoders receiving frontend data. */
339 for (d = di_list; d; d = d->next) {
341 di->num_probes = num_probes;
342 di->unitsize = unitsize;
343 di->samplerate = samplerate;
344 if ((ret = srd_instance_start(di, args) != SRD_OK))
347 /* Run the start() method on all decoders up the stack from this one. */
348 for (s = di->next_di; s; s = s->next) {
349 /* These don't need probes, unitsize and samplerate. */
351 if ((ret = srd_instance_start(di, args) != SRD_OK))
361 /* Feed logic samples to decoder session. */
362 int srd_session_feed(uint64_t timeoffset, uint64_t duration, uint8_t *inbuf,
368 for (d = di_list; d; d = d->next) {
369 if ((ret = srd_instance_decode(timeoffset, duration, d->data, inbuf,
370 inbuflen)) != SRD_OK)
378 int pd_add(struct srd_decoder_instance *di, int output_type,
381 struct srd_pd_output *pdo;
383 if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
386 /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
387 pdo->pdo_id = g_slist_length(di->pd_output);
388 pdo->output_type = output_type;
389 pdo->decoder = di->decoder;
390 pdo->proto_id = g_strdup(proto_id);
391 di->pd_output = g_slist_append(di->pd_output, pdo);
396 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
399 struct srd_decoder_instance *di;
401 for (l = di_list; l; l = l->next) {
403 if (decobject == di->py_instance)
405 /* Check decoders stacked on top of this one. */
406 for (s = di->next_di; s; s = s->next) {
408 if (decobject == di->py_instance)
416 int srd_register_callback(int output_type, void *cb)
418 struct srd_pd_callback *pd_cb;
420 if (!(pd_cb = g_try_malloc(sizeof(struct srd_pd_callback))))
421 return SRD_ERR_MALLOC;
423 pd_cb->output_type = output_type;
424 pd_cb->callback = cb;
425 callbacks = g_slist_append(callbacks, pd_cb);
430 void *srd_find_callback(int output_type)
433 struct srd_pd_callback *pd_cb;
437 for (l = callbacks; l; l = l->next) {
439 if (pd_cb->output_type == output_type) {
440 cb = pd_cb->callback;