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. */
25 /* TODO: this should probably be in sigrokdecode.h */
26 /* Re-define some string functions for Python >= 3.0. */
27 #if PY_VERSION_HEX >= 0x03000000
28 #define PyString_AsString PyBytes_AsString
29 #define PyString_FromString PyBytes_FromString
30 #define PyString_Check PyBytes_Check
35 static GSList *pipelines = NULL;
38 /* lives in decoder.c */
39 extern GSList *pd_list;
40 extern GSList *di_list;
49 static PyObject *Decoder_init(PyObject *self, PyObject *args)
53 // printf("init object %x\n", self);
58 struct srd_decoder_instance *get_di_by_decobject(void *decobject);
60 static PyObject *Decoder_put(PyObject *self, PyObject *args)
64 struct srd_decoder_instance *di;
65 struct srd_pd_output *pdo;
68 if (!(di = get_di_by_decobject(self)))
71 printf("put: %s instance %x: ", di->decoder->name, (unsigned int) di);
73 if (!PyArg_ParseTuple(args, "iO", &output_id, &data))
76 if (!(l = g_slist_nth(di->pd_output, output_id)))
77 /* PD supplied invalid output id */
78 /* TODO: better error message */
82 printf("output type %d: ", pdo->output_type);
83 PyObject_Print(data, stdout, Py_PRINT_RAW);
90 static PyObject *Decoder_output_new(PyObject *self, PyObject *py_output_type)
93 struct srd_decoder_instance *di;
94 char *protocol_id, *description;
95 int output_type, pdo_id;
97 if (!(di = get_di_by_decobject(self)))
100 printf("output_new di %s\n", di->decoder->name);
102 // if (!PyArg_ParseTuple(args, "i:output_type,s:protocol_id,s:description",
103 // &output_type, &protocol_id, &description))
104 if (!PyArg_ParseTuple(py_output_type, "i:output_type", &output_type))
108 description = "blah";
109 pdo_id = pd_output_new(di, output_type, protocol_id, description);
113 ret = Py_BuildValue("i", pdo_id);
118 static PyMethodDef no_methods[] = { {NULL, NULL, 0, NULL} };
119 static PyMethodDef Decoder_methods[] = {
120 {"__init__", Decoder_init, METH_VARARGS, ""},
121 {"put", Decoder_put, METH_VARARGS,
122 "Accepts a dictionary with the following keys: time, duration, data"},
123 {"output_new", Decoder_output_new, METH_VARARGS,
124 "Create a new output stream"},
125 {NULL, NULL, 0, NULL}
131 } sigrok_Decoder_object;
133 static PyTypeObject sigrok_Decoder_type = {
134 PyObject_HEAD_INIT(NULL)
135 .tp_name = "sigrok.Decoder",
136 .tp_basicsize = sizeof(sigrok_Decoder_object),
137 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
138 .tp_doc = "Sigrok Decoder object",
139 .tp_methods = Decoder_methods,
142 PyMODINIT_FUNC init_sigrok_Decoder(void)
146 /* assign this here, for compiler portability */
147 sigrok_Decoder_type.tp_new = PyType_GenericNew;
148 if (PyType_Ready(&sigrok_Decoder_type) < 0)
151 mod = Py_InitModule3("sigrok", no_methods, "sigrok base classes");
152 Py_INCREF(&sigrok_Decoder_type);
153 PyModule_AddObject(mod, "Decoder", (PyObject *)&sigrok_Decoder_type);
158 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
161 struct srd_decoder_instance *di;
163 for (l = di_list; l; l = l->next) {
165 if (decobject == di->py_instance)
173 * Initialize libsigrokdecode.
175 * This initializes the Python interpreter, and creates and initializes
176 * a "sigrok" Python module with a single put() method.
178 * Then, it searches for sigrok protocol decoder files (*.py) in the
179 * "decoders" subdirectory of the the sigrok installation directory.
180 * All decoders that are found are loaded into memory and added to an
181 * internal list of decoders, which can be queried via srd_list_decoders().
183 * The caller is responsible for calling the clean-up function srd_exit(),
184 * which will properly shut down libsigrokdecode and free its allocated memory.
186 * Multiple calls to srd_init(), without calling srd_exit() inbetween,
189 * @return SRD_OK upon success, a (negative) error code otherwise.
190 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
191 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
192 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
198 /* Py_Initialize() returns void and usually cannot fail. */
201 init_sigrok_Decoder();
203 PyRun_SimpleString("import sys;");
204 if ((ret = set_modulepath()) != SRD_OK) {
209 if ((ret = srd_load_all_decoders()) != SRD_OK) {
219 * Shutdown libsigrokdecode.
221 * This frees all the memory allocated for protocol decoders and shuts down
222 * the Python interpreter.
224 * This function should only be called if there was a (successful!) invocation
225 * of srd_init() before. Calling this function multiple times in a row, without
226 * any successful srd_init() calls inbetween, is not allowed.
228 * @return SRD_OK upon success, a (negative) error code otherwise.
232 /* Unload/free all decoders, and then the list of decoders itself. */
233 /* TODO: Error handling. */
234 srd_unload_all_decoders();
235 g_slist_free(pd_list);
237 /* Py_Finalize() returns void, any finalization errors are ignored. */
245 * Add search directories for the protocol decoders.
247 * TODO: add path from env var SIGROKDECODE_PATH, config etc
249 int set_modulepath(void)
253 ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
259 struct srd_decoder_instance *srd_instance_new(const char *id)
261 struct srd_decoder *dec;
262 struct srd_decoder_instance *di;
265 fprintf(stdout, "%s: %s\n", __func__, id);
267 if (!(dec = srd_get_decoder_by_id(id)))
270 /* TODO: Error handling. Use g_try_malloc(). */
271 di = g_malloc(sizeof(*di));
273 di->pd_output = NULL;
275 /* Create an empty Python tuple. */
276 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
277 if (PyErr_Occurred())
278 PyErr_Print(); /* Returns void. */
280 return NULL; /* TODO: More specific error? */
283 /* Create an instance of the 'Decoder' class. */
284 di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
285 if (!di->py_instance) {
286 if (PyErr_Occurred())
287 PyErr_Print(); /* Returns void. */
289 return NULL; /* TODO: More specific error? */
291 di_list = g_slist_append(di_list, di);
299 int srd_instance_set_probe(struct srd_decoder_instance *di,
300 const char *probename, int num)
302 PyObject *probedict, *probenum;
304 probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
306 if (PyErr_Occurred())
307 PyErr_Print(); /* Returns void. */
309 return SRD_ERR_PYTHON; /* TODO: More specific error? */
312 probenum = PyInt_FromLong(num);
313 PyMapping_SetItemString(probedict, (char *)probename, probenum);
315 Py_XDECREF(probenum);
316 Py_XDECREF(probedict);
322 int srd_session_start(const char *driver, int unitsize, uint64_t starttime,
327 struct srd_decoder_instance *di;
329 fprintf(stdout, "%s: %s\n", __func__, driver);
331 for (d = di_list; d; d = d->next) {
333 if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
336 "unitsize", (long)unitsize,
337 "starttime", (long)starttime,
338 "samplerate", (long)samplerate))) {
339 if (PyErr_Occurred())
340 PyErr_Print(); /* Returns void. */
342 return SRD_ERR_PYTHON; /* TODO: More specific error? */
352 * Run the specified decoder function.
356 * @param inbuflen TODO
358 * @return SRD_OK upon success, a (negative) error code otherwise.
360 int srd_run_decoder(struct srd_decoder_instance *dec,
361 uint8_t *inbuf, uint64_t inbuflen)
363 PyObject *py_instance, *py_res;
364 /* FIXME: Don't have a timebase available here. Make one up. */
365 static int _timehack = 0;
367 _timehack += inbuflen;
369 // fprintf(stdout, "%s: %s\n", __func__, dec->decoder->name);
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",
387 "data", inbuf, inbuflen))) { /* NEWREF */
388 if (PyErr_Occurred())
389 PyErr_Print(); /* Returns void. */
391 return SRD_ERR_PYTHON; /* TODO: More specific error? */
399 /* Feed logic samples to decoder session. */
400 int srd_session_feed(uint8_t *inbuf, uint64_t inbuflen)
405 // fprintf(stdout, "%s: %d bytes\n", __func__, inbuflen);
407 for (d = di_list; d; d = d->next) {
408 if ((ret = srd_run_decoder(d->data, inbuf, inbuflen)) != SRD_OK)
416 int pd_output_new(struct srd_decoder_instance *di, int output_type,
417 char *protocol_id, char *description)
420 struct srd_pd_output *pdo;
423 fprintf(stdout, "%s: output type %d, protocol_id %s, description %s\n",
424 __func__, output_type, protocol_id, description);
427 for (l = di->pd_output; l; l = l->next) {
429 if (pdo->pdo_id > pdo_id)
430 pdo_id = pdo->pdo_id;
434 if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
437 pdo->pdo_id = pdo_id;
438 pdo->output_type = output_type;
439 pdo->protocol_id = g_strdup(protocol_id);
440 pdo->description = g_strdup(description);
441 di->pd_output = g_slist_append(di->pd_output, pdo);
447 //int srd_pipeline_new(int plid)