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
34 static GSList *pipelines = NULL;
36 /* lives in decoder.c */
37 extern GSList *list_pds;
38 extern GSList *decoders;
47 static PyObject *Decoder_init(PyObject *self, PyObject *args)
51 // printf("init object %x\n", self);
57 static PyObject *Decoder_put(PyObject *self, PyObject *args)
61 // printf("put object %x\n", self);
63 if (!PyArg_ParseTuple(args, "O:put", &arg))
66 // fprintf(stdout, "sigrok.put() called by decoder:\n");
67 PyObject_Print(arg, stdout, Py_PRINT_RAW);
73 static PyMethodDef no_methods[] = { {NULL, NULL, 0, NULL} };
74 static PyMethodDef Decoder_methods[] = {
75 {"__init__", Decoder_init, METH_VARARGS, ""},
76 {"put", Decoder_put, METH_VARARGS,
77 "Accepts a dictionary with the following keys: time, duration, data"},
82 // class Decoder(sigrok.Decoder):
85 } sigrok_Decoder_object;
87 static PyTypeObject sigrok_Decoder_type = {
88 PyObject_HEAD_INIT(NULL)
89 .tp_name = "sigrok.Decoder",
90 .tp_basicsize = sizeof(sigrok_Decoder_object),
91 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
92 .tp_doc = "Sigrok Decoder object",
93 .tp_methods = Decoder_methods,
96 PyMODINIT_FUNC init_sigrok_Decoder(void)
100 sigrok_Decoder_type.tp_new = PyType_GenericNew;
101 if (PyType_Ready(&sigrok_Decoder_type) < 0)
104 mod = Py_InitModule3("sigrok", no_methods, "sigrok base classes");
105 Py_INCREF(&sigrok_Decoder_type);
106 PyModule_AddObject(mod, "Decoder", (PyObject *)&sigrok_Decoder_type);
112 * Initialize libsigrokdecode.
114 * This initializes the Python interpreter, and creates and initializes
115 * a "sigrok" Python module with a single put() method.
117 * Then, it searches for sigrok protocol decoder files (*.py) in the
118 * "decoders" subdirectory of the the sigrok installation directory.
119 * All decoders that are found are loaded into memory and added to an
120 * internal list of decoders, which can be queried via srd_list_decoders().
122 * The caller is responsible for calling the clean-up function srd_exit(),
123 * which will properly shut down libsigrokdecode and free its allocated memory.
125 * Multiple calls to srd_init(), without calling srd_exit() inbetween,
128 * @return SRD_OK upon success, a (negative) error code otherwise.
129 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
130 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
131 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
137 /* Py_Initialize() returns void and usually cannot fail. */
140 init_sigrok_Decoder();
142 PyRun_SimpleString("import sys;");
143 if ((ret = set_modulepath()) != SRD_OK) {
148 if ((ret = srd_load_all_decoders()) != SRD_OK) {
158 * Shutdown libsigrokdecode.
160 * This frees all the memory allocated for protocol decoders and shuts down
161 * the Python interpreter.
163 * This function should only be called if there was a (successful!) invocation
164 * of srd_init() before. Calling this function multiple times in a row, without
165 * any successful srd_init() calls inbetween, is not allowed.
167 * @return SRD_OK upon success, a (negative) error code otherwise.
171 /* Unload/free all decoders, and then the list of decoders itself. */
172 /* TODO: Error handling. */
173 srd_unload_all_decoders();
174 g_slist_free(list_pds);
176 /* Py_Finalize() returns void, any finalization errors are ignored. */
184 * Add search directories for the protocol decoders.
186 * TODO: add path from env var SIGROKDECODE_PATH, config etc
188 int set_modulepath(void)
192 ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
198 struct srd_decoder_instance *srd_instance_new(const char *id)
200 struct srd_decoder *dec;
201 struct srd_decoder_instance *di;
204 fprintf(stdout, "%s: %s\n", __func__, id);
206 if (!(dec = srd_get_decoder_by_id(id)))
209 /* TODO: Error handling. Use g_try_malloc(). */
210 di = g_malloc(sizeof(*di));
212 di->pd_output = NULL;
214 /* Create an empty Python tuple. */
215 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
216 if (PyErr_Occurred())
217 PyErr_Print(); /* Returns void. */
219 return NULL; /* TODO: More specific error? */
222 /* Create an instance of the 'Decoder' class. */
223 di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
224 if (!di->py_instance) {
225 if (PyErr_Occurred())
226 PyErr_Print(); /* Returns void. */
228 return NULL; /* TODO: More specific error? */
230 decoders = g_slist_append(decoders, di);
238 int srd_instance_set_probe(struct srd_decoder_instance *di,
239 const char *probename, int num)
241 PyObject *probedict, *probenum;
243 probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
245 if (PyErr_Occurred())
246 PyErr_Print(); /* Returns void. */
248 return SRD_ERR_PYTHON; /* TODO: More specific error? */
251 probenum = PyInt_FromLong(num);
252 PyMapping_SetItemString(probedict, (char *)probename, probenum);
254 Py_XDECREF(probenum);
255 Py_XDECREF(probedict);
261 int srd_session_start(const char *driver, int unitsize, uint64_t starttime,
266 struct srd_decoder_instance *di;
268 fprintf(stdout, "%s: %s\n", __func__, driver);
270 for (d = decoders; d; d = d->next) {
272 if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
275 "unitsize", (long)unitsize,
276 "starttime", (long)starttime,
277 "samplerate", (long)samplerate))) {
278 if (PyErr_Occurred())
279 PyErr_Print(); /* Returns void. */
281 return SRD_ERR_PYTHON; /* TODO: More specific error? */
291 * Run the specified decoder function.
295 * @param inbuflen TODO
297 * @param outbuflen TODO
299 * @return SRD_OK upon success, a (negative) error code otherwise.
301 int srd_run_decoder(struct srd_decoder_instance *dec,
302 uint8_t *inbuf, uint64_t inbuflen)
304 PyObject *py_instance, *py_res;
305 /* FIXME: Don't have a timebase available here. Make one up. */
306 static int _timehack = 0;
308 _timehack += inbuflen;
310 // fprintf(stdout, "%s: %s\n", __func__, dec->decoder->name);
312 /* Return an error upon unusable input. */
314 return SRD_ERR_ARGS; /* TODO: More specific error? */
316 return SRD_ERR_ARGS; /* TODO: More specific error? */
317 if (inbuflen == 0) /* No point in working on empty buffers. */
318 return SRD_ERR_ARGS; /* TODO: More specific error? */
320 /* TODO: Error handling. */
321 py_instance = dec->py_instance;
322 Py_XINCREF(py_instance);
324 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
328 "data", inbuf, inbuflen))) { /* NEWREF */
329 if (PyErr_Occurred())
330 PyErr_Print(); /* Returns void. */
332 return SRD_ERR_PYTHON; /* TODO: More specific error? */
340 /* Feed logic samples to decoder session. */
341 int srd_session_feed(uint8_t *inbuf, uint64_t inbuflen)
346 // fprintf(stdout, "%s: %d bytes\n", __func__, inbuflen);
348 for (d = decoders; d; d = d->next) {
349 if ((ret = srd_run_decoder(d->data, inbuf, inbuflen)) != SRD_OK)
357 //int srd_pipeline_new(int plid)
364 //int pd_output_new(int output_type, char *output_id, char *description)