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)
91 sizeof(sigrok_Decoder_object),
108 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
109 "Sigrok Decoder object",
119 PyMODINIT_FUNC init_sigrok_Decoder(void)
123 sigrok_Decoder_type.tp_new = PyType_GenericNew;
124 if (PyType_Ready(&sigrok_Decoder_type) < 0)
127 mod = Py_InitModule3("sigrok", no_methods, "sigrok base classes");
128 Py_INCREF(&sigrok_Decoder_type);
129 PyModule_AddObject(mod, "Decoder", (PyObject *)&sigrok_Decoder_type);
135 * Initialize libsigrokdecode.
137 * This initializes the Python interpreter, and creates and initializes
138 * a "sigrok" Python module with a single put() method.
140 * Then, it searches for sigrok protocol decoder files (*.py) in the
141 * "decoders" subdirectory of the the sigrok installation directory.
142 * All decoders that are found are loaded into memory and added to an
143 * internal list of decoders, which can be queried via srd_list_decoders().
145 * The caller is responsible for calling the clean-up function srd_exit(),
146 * which will properly shut down libsigrokdecode and free its allocated memory.
148 * Multiple calls to srd_init(), without calling srd_exit() inbetween,
151 * @return SRD_OK upon success, a (negative) error code otherwise.
152 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
153 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
154 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
160 /* Py_Initialize() returns void and usually cannot fail. */
163 init_sigrok_Decoder();
165 PyRun_SimpleString("import sys;");
166 if ((ret = set_modulepath()) != SRD_OK) {
171 if ((ret = srd_load_all_decoders()) != SRD_OK) {
181 * Shutdown libsigrokdecode.
183 * This frees all the memory allocated for protocol decoders and shuts down
184 * the Python interpreter.
186 * This function should only be called if there was a (successful!) invocation
187 * of srd_init() before. Calling this function multiple times in a row, without
188 * any successful srd_init() calls inbetween, is not allowed.
190 * @return SRD_OK upon success, a (negative) error code otherwise.
194 /* Unload/free all decoders, and then the list of decoders itself. */
195 /* TODO: Error handling. */
196 srd_unload_all_decoders();
197 g_slist_free(list_pds);
199 /* Py_Finalize() returns void, any finalization errors are ignored. */
207 * Add search directories for the protocol decoders.
209 * TODO: add path from env var SIGROKDECODE_PATH, config etc
211 int set_modulepath(void)
215 ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
221 struct srd_decoder_instance *srd_instance_new(const char *id)
223 struct srd_decoder *dec;
224 struct srd_decoder_instance *di;
227 fprintf(stdout, "%s: %s\n", __func__, id);
229 if (!(dec = srd_get_decoder_by_id(id)))
232 /* TODO: Error handling. Use g_try_malloc(). */
233 di = g_malloc(sizeof(*di));
235 di->pd_output = NULL;
237 /* Create an empty Python tuple. */
238 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
239 if (PyErr_Occurred())
240 PyErr_Print(); /* Returns void. */
242 return NULL; /* TODO: More specific error? */
245 /* Create an instance of the 'Decoder' class. */
246 di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
247 if (!di->py_instance) {
248 if (PyErr_Occurred())
249 PyErr_Print(); /* Returns void. */
251 return NULL; /* TODO: More specific error? */
253 decoders = g_slist_append(decoders, di);
261 int srd_instance_set_probe(struct srd_decoder_instance *di,
262 const char *probename, int num)
264 PyObject *probedict, *probenum;
266 probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
268 if (PyErr_Occurred())
269 PyErr_Print(); /* Returns void. */
271 return SRD_ERR_PYTHON; /* TODO: More specific error? */
274 probenum = PyInt_FromLong(num);
275 PyMapping_SetItemString(probedict, (char *)probename, probenum);
277 Py_XDECREF(probenum);
278 Py_XDECREF(probedict);
284 int srd_session_start(const char *driver, int unitsize, uint64_t starttime,
289 struct srd_decoder_instance *di;
291 fprintf(stdout, "%s: %s\n", __func__, driver);
293 for (d = decoders; d; d = d->next) {
295 if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
298 "unitsize", unitsize,
299 "starttime", starttime))) {
300 if (PyErr_Occurred())
301 PyErr_Print(); /* Returns void. */
303 return SRD_ERR_PYTHON; /* TODO: More specific error? */
313 * Run the specified decoder function.
317 * @param inbuflen TODO
319 * @param outbuflen TODO
321 * @return SRD_OK upon success, a (negative) error code otherwise.
323 int srd_run_decoder(struct srd_decoder_instance *dec,
324 uint8_t *inbuf, uint64_t inbuflen)
326 PyObject *py_instance, *py_res;
327 /* FIXME: Don't have a timebase available here. Make one up. */
328 static int _timehack = 0;
330 _timehack += inbuflen;
332 // fprintf(stdout, "%s: %s\n", __func__, dec->decoder->name);
334 /* Return an error upon unusable input. */
336 return SRD_ERR_ARGS; /* TODO: More specific error? */
338 return SRD_ERR_ARGS; /* TODO: More specific error? */
339 if (inbuflen == 0) /* No point in working on empty buffers. */
340 return SRD_ERR_ARGS; /* TODO: More specific error? */
342 /* TODO: Error handling. */
343 py_instance = dec->py_instance;
344 Py_XINCREF(py_instance);
346 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
350 "data", inbuf, inbuflen))) { /* NEWREF */
351 if (PyErr_Occurred())
352 PyErr_Print(); /* Returns void. */
354 return SRD_ERR_PYTHON; /* TODO: More specific error? */
362 /* Feed logic samples to decoder session. */
363 int srd_session_feed(uint8_t *inbuf, uint64_t inbuflen)
368 // fprintf(stdout, "%s: %d bytes\n", __func__, inbuflen);
370 for (d = decoders; d; d = d->next) {
371 if ((ret = srd_run_decoder(d->data, inbuf, inbuflen)) != SRD_OK)
379 //int srd_pipeline_new(int plid)
386 //int pd_output_new(int output_type, char *output_id, char *description)