2 * This file is part of the sigrok project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2011 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/>.
22 #include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
26 /* TODO: this should probably be in sigrokdecode.h */
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
36 static GSList *pipelines = NULL;
39 /* lives in decoder.c */
40 extern GSList *pd_list;
41 extern GSList *di_list;
50 static PyObject *Decoder_init(PyObject *self, PyObject *args)
54 // printf("init object %x\n", self);
59 struct srd_decoder_instance *get_di_by_decobject(void *decobject);
61 static PyObject *Decoder_put(PyObject *self, PyObject *args)
65 struct srd_decoder_instance *di;
66 struct srd_pd_output *pdo;
67 uint64_t timeoffset, duration;
70 if (!(di = get_di_by_decobject(self)))
73 if (!PyArg_ParseTuple(args, "KKiO", &timeoffset, &duration, &output_id, &data))
76 printf("put: %s instance %p time %" PRIu64 " duration %" PRIu64 " ",
77 di->decoder->name, di, timeoffset, duration);
79 if (!(l = g_slist_nth(di->pd_output, output_id)))
80 /* PD supplied invalid output id */
81 /* TODO: better error message */
85 printf("stream %d: ", pdo->output_type);
86 PyObject_Print(data, stdout, Py_PRINT_RAW);
93 static PyObject *Decoder_output_new(PyObject *self, PyObject *py_output_type)
96 struct srd_decoder_instance *di;
97 char *protocol_id, *description;
98 int output_type, pdo_id;
100 if (!(di = get_di_by_decobject(self)))
103 printf("output_new di %s\n", di->decoder->name);
105 // if (!PyArg_ParseTuple(args, "i:output_type,s:protocol_id,s:description",
106 // &output_type, &protocol_id, &description))
107 if (!PyArg_ParseTuple(py_output_type, "i:output_type", &output_type))
111 description = "blah";
112 pdo_id = pd_output_new(di, output_type, protocol_id, description);
116 ret = Py_BuildValue("i", pdo_id);
121 static PyMethodDef no_methods[] = { {NULL, NULL, 0, NULL} };
122 static PyMethodDef Decoder_methods[] = {
123 {"__init__", Decoder_init, METH_VARARGS, ""},
124 {"put", Decoder_put, METH_VARARGS,
125 "Accepts a dictionary with the following keys: time, duration, data"},
126 {"output_new", Decoder_output_new, METH_VARARGS,
127 "Create a new output stream"},
128 {NULL, NULL, 0, NULL}
134 } sigrok_Decoder_object;
136 static PyTypeObject sigrok_Decoder_type = {
137 PyObject_HEAD_INIT(NULL)
138 .tp_name = "sigrok.Decoder",
139 .tp_basicsize = sizeof(sigrok_Decoder_object),
140 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
141 .tp_doc = "Sigrok Decoder object",
142 .tp_methods = Decoder_methods,
145 PyMODINIT_FUNC init_sigrok_Decoder(void)
149 /* assign this here, for compiler portability */
150 sigrok_Decoder_type.tp_new = PyType_GenericNew;
151 if (PyType_Ready(&sigrok_Decoder_type) < 0)
154 mod = Py_InitModule3("sigrok", no_methods, "sigrok base classes");
155 Py_INCREF(&sigrok_Decoder_type);
156 PyModule_AddObject(mod, "Decoder", (PyObject *)&sigrok_Decoder_type);
161 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
164 struct srd_decoder_instance *di;
166 for (l = di_list; l; l = l->next) {
168 if (decobject == di->py_instance)
176 * Initialize libsigrokdecode.
178 * This initializes the Python interpreter, and creates and initializes
179 * a "sigrok" Python module with a single put() method.
181 * Then, it searches for sigrok protocol decoder files (*.py) in the
182 * "decoders" subdirectory of the the sigrok installation directory.
183 * All decoders that are found are loaded into memory and added to an
184 * internal list of decoders, which can be queried via srd_list_decoders().
186 * The caller is responsible for calling the clean-up function srd_exit(),
187 * which will properly shut down libsigrokdecode and free its allocated memory.
189 * Multiple calls to srd_init(), without calling srd_exit() inbetween,
192 * @return SRD_OK upon success, a (negative) error code otherwise.
193 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
194 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
195 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
201 /* Py_Initialize() returns void and usually cannot fail. */
204 init_sigrok_Decoder();
206 PyRun_SimpleString("import sys;");
207 if ((ret = set_modulepath()) != SRD_OK) {
212 if ((ret = srd_load_all_decoders()) != SRD_OK) {
222 * Shutdown libsigrokdecode.
224 * This frees all the memory allocated for protocol decoders and shuts down
225 * the Python interpreter.
227 * This function should only be called if there was a (successful!) invocation
228 * of srd_init() before. Calling this function multiple times in a row, without
229 * any successful srd_init() calls inbetween, is not allowed.
231 * @return SRD_OK upon success, a (negative) error code otherwise.
235 /* Unload/free all decoders, and then the list of decoders itself. */
236 /* TODO: Error handling. */
237 srd_unload_all_decoders();
238 g_slist_free(pd_list);
240 /* Py_Finalize() returns void, any finalization errors are ignored. */
248 * Add search directories for the protocol decoders.
250 * TODO: add path from env var SIGROKDECODE_PATH, config etc
252 int set_modulepath(void)
256 ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
262 struct srd_decoder_instance *srd_instance_new(const char *id)
264 struct srd_decoder *dec;
265 struct srd_decoder_instance *di;
268 fprintf(stdout, "%s: %s\n", __func__, id);
270 if (!(dec = srd_get_decoder_by_id(id)))
273 /* TODO: Error handling. Use g_try_malloc(). */
274 di = g_malloc(sizeof(*di));
276 di->pd_output = NULL;
278 /* Create an empty Python tuple. */
279 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
280 if (PyErr_Occurred())
281 PyErr_Print(); /* Returns void. */
283 return NULL; /* TODO: More specific error? */
286 /* Create an instance of the 'Decoder' class. */
287 di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
288 if (!di->py_instance) {
289 if (PyErr_Occurred())
290 PyErr_Print(); /* Returns void. */
292 return NULL; /* TODO: More specific error? */
294 di_list = g_slist_append(di_list, di);
302 int srd_instance_set_probe(struct srd_decoder_instance *di,
303 const char *probename, int num)
305 PyObject *probedict, *probenum;
307 probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
309 if (PyErr_Occurred())
310 PyErr_Print(); /* Returns void. */
312 return SRD_ERR_PYTHON; /* TODO: More specific error? */
315 probenum = PyInt_FromLong(num);
316 PyMapping_SetItemString(probedict, (char *)probename, probenum);
318 Py_XDECREF(probenum);
319 Py_XDECREF(probedict);
325 int srd_session_start(const char *driver, int unitsize, uint64_t starttime,
330 struct srd_decoder_instance *di;
332 fprintf(stdout, "%s: %s\n", __func__, driver);
334 for (d = di_list; d; d = d->next) {
336 if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
339 "unitsize", (long)unitsize,
340 "starttime", (long)starttime,
341 "samplerate", (long)samplerate))) {
342 if (PyErr_Occurred())
343 PyErr_Print(); /* Returns void. */
345 return SRD_ERR_PYTHON; /* TODO: More specific error? */
355 * Run the specified decoder function.
359 * @param inbuflen TODO
361 * @return SRD_OK upon success, a (negative) error code otherwise.
363 int srd_run_decoder(uint64_t timeoffset, uint64_t duration,
364 struct srd_decoder_instance *dec, uint8_t *inbuf, uint64_t inbuflen)
366 PyObject *py_instance, *py_res;
368 // fprintf(stdout, "%s: %s\n", __func__, dec->decoder->name);
369 // printf("to %u du %u len %d\n", timeoffset, duration, inbuflen);
371 /* Return an error upon unusable input. */
373 return SRD_ERR_ARG; /* TODO: More specific error? */
375 return SRD_ERR_ARG; /* TODO: More specific error? */
376 if (inbuflen == 0) /* No point in working on empty buffers. */
377 return SRD_ERR_ARG; /* TODO: More specific error? */
379 /* TODO: Error handling. */
380 py_instance = dec->py_instance;
381 Py_XINCREF(py_instance);
383 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
384 "KKs#", timeoffset, duration, inbuf, inbuflen))) {
385 if (PyErr_Occurred())
386 PyErr_Print(); /* Returns void. */
388 return SRD_ERR_PYTHON; /* TODO: More specific error? */
396 /* Feed logic samples to decoder session. */
397 int srd_session_feed(uint64_t timeoffset, uint64_t duration, uint8_t *inbuf,
403 // fprintf(stdout, "%s: %d bytes\n", __func__, inbuflen);
405 for (d = di_list; d; d = d->next) {
406 if ((ret = srd_run_decoder(timeoffset, duration, d->data, inbuf,
407 inbuflen)) != SRD_OK)
415 int pd_output_new(struct srd_decoder_instance *di, int output_type,
416 char *protocol_id, char *description)
419 struct srd_pd_output *pdo;
422 fprintf(stdout, "%s: output type %d, protocol_id %s, description %s\n",
423 __func__, output_type, protocol_id, description);
426 for (l = di->pd_output; l; l = l->next) {
428 if (pdo->pdo_id > pdo_id)
429 pdo_id = pdo->pdo_id;
433 if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
436 pdo->pdo_id = pdo_id;
437 pdo->output_type = output_type;
438 pdo->protocol_id = g_strdup(protocol_id);
439 pdo->description = g_strdup(description);
440 di->pd_output = g_slist_append(di->pd_output, pdo);
446 //int srd_pipeline_new(int plid)