2 * This file is part of the sigrok project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 #include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
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
34 /* The list of protocol decoders. */
35 static GSList *list_pds = NULL;
38 * Here's a quick overview of Python/C API reference counting.
40 * Check the Python/C API docs for what type of reference a function returns.
42 * - If it returns a "new reference", you're responsible to Py_XDECREF() it.
44 * - If it returns a "borrowed reference", you MUST NOT Py_XDECREF() it.
46 * - If a function "steals" a reference, you no longer are responsible for
47 * Py_XDECREF()ing it (someone else will do it for you at some point).
50 static int srd_load_decoder(const char *name, struct srd_decoder **dec);
52 static int _unitsize = 1;
55 emb_getmeta(PyObject *self, PyObject *args)
57 if (!PyArg_ParseTuple(args, ":get"))
60 return Py_BuildValue("{sssisd}",
62 "unitsize", _unitsize,
63 "starttime", 129318231823.0 //TODO: Fill with something reasonable.
69 emb_get(PyObject *self, PyObject *args)
72 if (!PyArg_ParseTuple(args, ":get"))
75 fprintf(stderr, "get called, returns %d\n", _bufoffset);
76 if ((_bufoffset + _unitsize) <= _buflen) {
77 r = Py_BuildValue("{sisiss#}",
78 "time", _bufoffset / _unitsize,
80 "data", &_buf[_bufoffset], _unitsize
82 _bufoffset += _unitsize;
90 emb_put(PyObject *self, PyObject *args)
94 if (!PyArg_ParseTuple(args, "O:put", &arg))
97 fprintf(stderr, "put called, got passed %d\n", arg);
101 static PyMethodDef EmbMethods[] = {
102 {"get_meta", emb_getmeta, METH_VARARGS,
103 "Returns information about the stream."},
104 /*{"get", emb_get, METH_VARARGS,
105 "Returns a dictionary with the following keys: time, duration, data"},*/
106 {"put", emb_put, METH_VARARGS,
107 "Accepts a dictionary with the following keys: time, duration, data"},
108 {NULL, NULL, 0, NULL}
112 * Initialize libsigrokdecode.
114 * @return SRD_OK upon success, a (negative) error code otherwise.
121 struct srd_decoder *dec;
124 /* Py_Initialize() returns void and usually cannot fail. */
127 Py_InitModule("sigrok", EmbMethods);
129 /* Add search directory for the protocol decoders. */
130 /* FIXME: Check error code. */
131 /* FIXME: What happens if this function is called multiple times? */
132 PyRun_SimpleString("import sys;"
133 "sys.path.append(r'" DECODERS_DIR "');");
135 if (!(dir = opendir(DECODERS_DIR)))
136 return SRD_ERR_DECODERS_DIR;
138 while ((dp = readdir(dir)) != NULL) {
139 if (!g_str_has_suffix(dp->d_name, ".py"))
142 /* Decoder name == filename (without .py suffix). */
143 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
145 /* TODO: Error handling. */
146 dec = malloc(sizeof(struct srd_decoder));
148 /* Load the decoder. */
149 ret = srd_load_decoder(decodername, &dec);
151 /* Append it to the list of supported/loaded decoders. */
152 list_pds = g_slist_append(list_pds, dec);
160 * Returns the list of supported/loaded protocol decoders.
162 * This is a GSList containing the names of the decoders as strings.
164 * @return List of decoders, NULL if none are supported or loaded.
166 GSList *srd_list_decoders(void)
172 * Get the decoder with the specified ID.
174 * @param id The ID string of the decoder to return.
175 * @return The decoder with the specified ID, or NULL if not found.
177 struct srd_decoder *srd_get_decoder_by_id(const char *id)
180 struct srd_decoder *dec;
182 for (l = srd_list_decoders(); l; l = l->next) {
184 if (!strcmp(dec->id, id))
192 * Helper function to handle Python strings.
194 * TODO: @param entries.
196 * @return SRD_OK upon success, a (negative) error code otherwise.
197 * The 'outstr' argument points to a malloc()ed string upon success.
199 static int h_str(PyObject *py_res, PyObject *py_mod,
200 const char *key, char **outstr)
206 py_str = PyMapping_GetItemString(py_res, (char *)key);
207 if (!py_str || !PyString_Check(py_str)) {
208 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
209 goto err_h_decref_mod;
213 * PyString_AsString()'s returned string refers to an internal buffer
214 * (not a copy), i.e. the data must not be modified, and the memory
215 * must not be free()'d.
217 if (!(str = PyString_AsString(py_str))) {
218 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
219 goto err_h_decref_str;
222 if (!(*outstr = g_strdup(str))) {
223 ret = SRD_ERR_MALLOC;
224 goto err_h_decref_str;
236 if (PyErr_Occurred())
237 PyErr_Print(); /* Returns void. */
247 * @return SRD_OK upon success, a (negative) error code otherwise.
249 static int srd_load_decoder(const char *name,
250 struct srd_decoder **dec)
252 struct srd_decoder *d;
253 PyObject *py_mod, *py_func, *py_res /* , *py_tuple */;
256 /* "Import" the Python module. */
257 if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
258 PyErr_Print(); /* Returns void. */
259 return SRD_ERR_PYTHON; /* TODO: More specific error? */
262 /* Get the 'register' dictionary as Python object. */
263 py_res = PyObject_GetAttrString(py_mod, "register"); /* NEWREF */
264 if (!py_res || PyCallable_Check(py_res)) {
265 if (PyErr_Occurred())
266 PyErr_Print(); /* Returns void. */
268 fprintf(stderr, "register dictionary was not found or is declared a function.\n");
269 return SRD_ERR_PYTHON; /* TODO: More specific error? */
273 if (!(d = malloc(sizeof(struct srd_decoder))))
274 return SRD_ERR_MALLOC;
276 if ((r = h_str(py_res, py_mod, "id", &(d->id))) < 0)
279 if ((r = h_str(py_res, py_mod, "name", &(d->name))) < 0)
282 if ((r = h_str(py_res, py_mod, "longname",
283 &(d->longname))) < 0)
286 if ((r = h_str(py_res, py_mod, "desc", &(d->desc))) < 0)
289 if ((r = h_str(py_res, py_mod, "longdesc",
290 &(d->longdesc))) < 0)
293 if ((r = h_str(py_res, py_mod, "author", &(d->author))) < 0)
296 if ((r = h_str(py_res, py_mod, "email", &(d->email))) < 0)
299 if ((r = h_str(py_res, py_mod, "license", &(d->license))) < 0)
307 /* Get the 'decode' function name as Python callable object. */
308 py_func = PyObject_GetAttrString(py_mod, "decode"); /* NEWREF */
309 if (!py_func || !PyCallable_Check(py_func)) {
310 if (PyErr_Occurred())
311 PyErr_Print(); /* Returns void. */
313 return SRD_ERR_PYTHON; /* TODO: More specific error? */
316 d->py_decodefunc = py_func;
318 /* TODO: Handle func, inputformats, outputformats. */
319 /* Note: They must at least be set to NULL, will segfault otherwise. */
321 d->inputformats = NULL;
322 d->outputformats = NULL;
330 * Run the specified decoder function.
334 * @param inbuflen TODO
336 * @param outbuflen TODO
338 * @return SRD_OK upon success, a (negative) error code otherwise.
340 int srd_run_decoder(struct srd_decoder *dec,
341 uint8_t *inbuf, uint64_t inbuflen,
342 uint8_t **outbuf, uint64_t *outbuflen)
344 PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
347 /* FIXME: Don't have a timebase available here. Make one up. */
348 static int _timehack = 0;
349 _timehack += inbuflen;
351 /* TODO: Use #defines for the return codes. */
353 /* Return an error upon unusable input. */
355 return SRD_ERR_ARGS; /* TODO: More specific error? */
357 return SRD_ERR_ARGS; /* TODO: More specific error? */
358 if (inbuflen == 0) /* No point in working on empty buffers. */
359 return SRD_ERR_ARGS; /* TODO: More specific error? */
361 return SRD_ERR_ARGS; /* TODO: More specific error? */
362 if (outbuflen == NULL)
363 return SRD_ERR_ARGS; /* TODO: More specific error? */
365 /* TODO: Error handling. */
366 py_mod = dec->py_mod;
368 py_func = dec->py_decodefunc;
371 /* Create a Python tuple of size 1. */
372 if (!(py_args = PyTuple_New(1))) { /* NEWREF */
373 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
374 goto err_run_decref_func;
377 /* Get the input buffer as Python "string" (byte array). */
378 /* TODO: int vs. uint64_t for 'inbuflen'? */
380 py_value = Py_BuildValue("{sisiss#}",
383 "data", inbuf, inbuflen / _unitsize
387 * IMPORTANT: PyTuple_SetItem() "steals" a reference to py_value!
388 * That means we are no longer responsible for Py_XDECREF()'ing it.
389 * It will automatically be free'd when the 'py_args' tuple is free'd.
391 if (PyTuple_SetItem(py_args, 0, py_value) != 0) { /* STEAL */
392 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
393 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
394 goto err_run_decref_args;
397 if (!(py_res = PyObject_CallObject(py_func, py_args))) { /* NEWREF */
398 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
399 goto err_run_decref_args;
413 if (PyErr_Occurred())
414 PyErr_Print(); /* Returns void. */
422 static int srd_unload_decoder(struct srd_decoder *dec)
429 /* TODO: Free everything in inputformats and outputformats. */
431 if (dec->inputformats != NULL)
432 g_slist_free(dec->inputformats);
433 if (dec->outputformats != NULL)
434 g_slist_free(dec->outputformats);
436 Py_XDECREF(dec->py_decodefunc);
437 Py_XDECREF(dec->py_mod);
445 static int srd_unload_all_decoders(void)
448 struct srd_decoder *dec;
450 for (l = srd_list_decoders(); l; l = l->next) {
452 /* TODO: Error handling. */
453 srd_unload_decoder(dec);
460 * Shutdown libsigrokdecode.
462 * @return SRD_OK upon success, a (negative) error code otherwise.
466 /* Unload/free all decoders, and then the list of decoders itself. */
467 /* TODO: Error handling. */
468 srd_unload_all_decoders();
469 g_slist_free(list_pds);
471 /* Py_Finalize() returns void, any finalization errors are ignored. */