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. */
28 static GSList *pipelines = NULL;
31 /* lives in decoder.c */
32 extern GSList *pd_list;
33 extern GSList *di_list;
42 static PyObject *Decoder_init(PyObject *self, PyObject *args)
46 // printf("init object %x\n", self);
51 struct srd_decoder_instance *get_di_by_decobject(void *decobject);
53 static PyObject *Decoder_put(PyObject *self, PyObject *args)
57 struct srd_decoder_instance *di;
58 struct srd_pd_output *pdo;
59 uint64_t timeoffset, duration;
62 if (!(di = get_di_by_decobject(self)))
65 if (!PyArg_ParseTuple(args, "KKiO", &timeoffset, &duration, &output_id, &data))
68 printf("put: %s instance %p time %" PRIu64 " duration %" PRIu64 " ",
69 di->decoder->name, di, timeoffset, duration);
71 if (!(l = g_slist_nth(di->pd_output, output_id)))
72 /* PD supplied invalid output id */
73 /* TODO: better error message */
77 printf("stream %d: ", pdo->output_type);
78 PyObject_Print(data, stdout, Py_PRINT_RAW);
85 static PyObject *Decoder_output_new(PyObject *self, PyObject *py_output_type)
88 struct srd_decoder_instance *di;
89 char *protocol_id, *description;
90 int output_type, pdo_id;
92 if (!(di = get_di_by_decobject(self)))
95 printf("output_new di %s\n", di->decoder->name);
97 // if (!PyArg_ParseTuple(args, "i:output_type,s:protocol_id,s:description",
98 // &output_type, &protocol_id, &description))
99 if (!PyArg_ParseTuple(py_output_type, "i:output_type", &output_type))
103 description = "blah";
104 pdo_id = pd_output_new(di, output_type, protocol_id, description);
108 ret = Py_BuildValue("i", pdo_id);
113 static PyMethodDef no_methods[] = { {NULL, NULL, 0, NULL} };
114 static PyMethodDef Decoder_methods[] = {
115 {"__init__", Decoder_init, METH_VARARGS, ""},
116 {"put", Decoder_put, METH_VARARGS,
117 "Accepts a dictionary with the following keys: time, duration, data"},
118 {"output_new", Decoder_output_new, METH_VARARGS,
119 "Create a new output stream"},
120 {NULL, NULL, 0, NULL}
126 } sigrok_Decoder_object;
128 static PyTypeObject sigrok_Decoder_type = {
129 PyVarObject_HEAD_INIT(NULL, 0)
130 .tp_name = "sigrok.Decoder",
131 .tp_basicsize = sizeof(sigrok_Decoder_object),
132 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
133 .tp_doc = "Sigrok Decoder object",
134 .tp_methods = Decoder_methods,
137 static struct PyModuleDef sigrok_Decoder_module = {
138 PyModuleDef_HEAD_INIT,
140 .m_doc = "sigrok base classes",
142 .m_methods = no_methods,
145 PyMODINIT_FUNC PyInit_sigrok(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 mod = PyModule_Create(&sigrok_Decoder_module);
156 Py_INCREF(&sigrok_Decoder_type);
157 if (PyModule_AddObject(mod, "Decoder", (PyObject *)&sigrok_Decoder_type) == -1)
164 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
167 struct srd_decoder_instance *di;
169 for (l = di_list; l; l = l->next) {
171 if (decobject == di->py_instance)
179 * Initialize libsigrokdecode.
181 * This initializes the Python interpreter, and creates and initializes
182 * a "sigrok" Python module with a single put() method.
184 * Then, it searches for sigrok protocol decoder files (*.py) in the
185 * "decoders" subdirectory of the the sigrok installation directory.
186 * All decoders that are found are loaded into memory and added to an
187 * internal list of decoders, which can be queried via srd_list_decoders().
189 * The caller is responsible for calling the clean-up function srd_exit(),
190 * which will properly shut down libsigrokdecode and free its allocated memory.
192 * Multiple calls to srd_init(), without calling srd_exit() inbetween,
195 * @return SRD_OK upon success, a (negative) error code otherwise.
196 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
197 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
198 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
204 PyImport_AppendInittab("sigrok", PyInit_sigrok);
206 /* Py_Initialize() returns void and usually cannot fail. */
211 PyRun_SimpleString("import sys;");
212 if ((ret = set_modulepath()) != SRD_OK) {
217 if ((ret = srd_load_all_decoders()) != SRD_OK) {
227 * Shutdown libsigrokdecode.
229 * This frees all the memory allocated for protocol decoders and shuts down
230 * the Python interpreter.
232 * This function should only be called if there was a (successful!) invocation
233 * of srd_init() before. Calling this function multiple times in a row, without
234 * any successful srd_init() calls inbetween, is not allowed.
236 * @return SRD_OK upon success, a (negative) error code otherwise.
240 /* Unload/free all decoders, and then the list of decoders itself. */
241 /* TODO: Error handling. */
242 srd_unload_all_decoders();
243 g_slist_free(pd_list);
245 /* Py_Finalize() returns void, any finalization errors are ignored. */
253 * Add search directories for the protocol decoders.
255 * TODO: add path from env var SIGROKDECODE_PATH, config etc
257 int set_modulepath(void)
261 ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
267 struct srd_decoder_instance *srd_instance_new(const char *id)
269 struct srd_decoder *dec;
270 struct srd_decoder_instance *di;
273 fprintf(stdout, "%s: %s\n", __func__, id);
275 if (!(dec = srd_get_decoder_by_id(id)))
278 /* TODO: Error handling. Use g_try_malloc(). */
279 di = g_malloc(sizeof(*di));
281 di->pd_output = NULL;
283 /* Create an empty Python tuple. */
284 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
285 if (PyErr_Occurred())
286 PyErr_Print(); /* Returns void. */
288 return NULL; /* TODO: More specific error? */
291 /* Create an instance of the 'Decoder' class. */
292 di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
293 if (!di->py_instance) {
294 if (PyErr_Occurred())
295 PyErr_Print(); /* Returns void. */
297 return NULL; /* TODO: More specific error? */
299 di_list = g_slist_append(di_list, di);
307 int srd_instance_set_probe(struct srd_decoder_instance *di,
308 const char *probename, int num)
310 PyObject *probedict, *probenum;
312 probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
314 if (PyErr_Occurred())
315 PyErr_Print(); /* Returns void. */
317 return SRD_ERR_PYTHON; /* TODO: More specific error? */
320 probenum = PyLong_FromLong(num);
321 PyMapping_SetItemString(probedict, (char *)probename, probenum);
323 Py_XDECREF(probenum);
324 Py_XDECREF(probedict);
330 int srd_session_start(const char *driver, int unitsize, uint64_t starttime,
335 struct srd_decoder_instance *di;
337 fprintf(stdout, "%s: %s\n", __func__, driver);
339 for (d = di_list; d; d = d->next) {
341 if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
344 "unitsize", (long)unitsize,
345 "starttime", (long)starttime,
346 "samplerate", (long)samplerate))) {
347 if (PyErr_Occurred())
348 PyErr_Print(); /* Returns void. */
350 return SRD_ERR_PYTHON; /* TODO: More specific error? */
360 * Run the specified decoder function.
364 * @param inbuflen TODO
366 * @return SRD_OK upon success, a (negative) error code otherwise.
368 int srd_run_decoder(uint64_t timeoffset, uint64_t duration,
369 struct srd_decoder_instance *dec, uint8_t *inbuf, uint64_t inbuflen)
371 PyObject *py_instance, *py_res;
373 // fprintf(stdout, "%s: %s\n", __func__, dec->decoder->name);
374 // printf("to %u du %u len %d\n", timeoffset, duration, inbuflen);
376 /* Return an error upon unusable input. */
378 return SRD_ERR_ARG; /* TODO: More specific error? */
380 return SRD_ERR_ARG; /* TODO: More specific error? */
381 if (inbuflen == 0) /* No point in working on empty buffers. */
382 return SRD_ERR_ARG; /* TODO: More specific error? */
384 /* TODO: Error handling. */
385 py_instance = dec->py_instance;
386 Py_XINCREF(py_instance);
388 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
389 "KKs#", timeoffset, duration, inbuf, inbuflen))) {
390 if (PyErr_Occurred())
391 PyErr_Print(); /* Returns void. */
393 return SRD_ERR_PYTHON; /* TODO: More specific error? */
401 /* Feed logic samples to decoder session. */
402 int srd_session_feed(uint64_t timeoffset, uint64_t duration, uint8_t *inbuf,
408 // fprintf(stdout, "%s: %d bytes\n", __func__, inbuflen);
410 for (d = di_list; d; d = d->next) {
411 if ((ret = srd_run_decoder(timeoffset, duration, d->data, inbuf,
412 inbuflen)) != SRD_OK)
420 int pd_output_new(struct srd_decoder_instance *di, int output_type,
421 char *protocol_id, char *description)
424 struct srd_pd_output *pdo;
427 fprintf(stdout, "%s: output type %d, protocol_id %s, description %s\n",
428 __func__, output_type, protocol_id, description);
431 for (l = di->pd_output; l; l = l->next) {
433 if (pdo->pdo_id > pdo_id)
434 pdo_id = pdo->pdo_id;
438 if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
441 pdo->pdo_id = pdo_id;
442 pdo->output_type = output_type;
443 pdo->protocol_id = g_strdup(protocol_id);
444 pdo->description = g_strdup(description);
445 di->pd_output = g_slist_append(di->pd_output, pdo);
451 //int srd_pipeline_new(int plid)