]> sigrok.org Git - libsigrokdecode.git/blob - controller.c
better python memory management
[libsigrokdecode.git] / controller.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2011 Bert Vermeulen <bert@biot.com>
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 #include "config.h"
22 #include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include <glib.h>
24 #include <inttypes.h>
25
26
27 /* TODO
28 static GSList *pipelines = NULL;
29 */
30
31 /* lives in decoder.c */
32 extern GSList *pd_list;
33 extern GSList *di_list;
34
35 struct srd_pipeline {
36         int id;
37         GSList *decoders;
38 };
39
40
41
42 static PyObject *Decoder_init(PyObject *self, PyObject *args)
43 {
44         (void)self;
45         (void)args;
46 //      printf("init object %x\n", self);
47
48         Py_RETURN_NONE;
49 }
50
51 struct srd_decoder_instance *get_di_by_decobject(void *decobject);
52
53 static PyObject *Decoder_put(PyObject *self, PyObject *args)
54 {
55         GSList *l;
56         PyObject *data;
57         struct srd_decoder_instance *di;
58         struct srd_pd_output *pdo;
59         uint64_t timeoffset, duration;
60         int output_id;
61
62         if (!(di = get_di_by_decobject(self)))
63                 return NULL;
64
65         if (!PyArg_ParseTuple(args, "KKiO", &timeoffset, &duration, &output_id, &data))
66                 return NULL;
67
68         printf("put: %s instance %p time %" PRIu64 " duration %" PRIu64 " ",
69                         di->decoder->name, di, timeoffset, duration);
70
71         if (!(l = g_slist_nth(di->pd_output, output_id)))
72                 /* PD supplied invalid output id */
73                 /* TODO: better error message */
74                 return NULL;
75         pdo = l->data;
76
77         printf("stream %d: ", pdo->output_type);
78         PyObject_Print(data, stdout, Py_PRINT_RAW);
79         puts("");
80
81         Py_RETURN_NONE;
82 }
83
84
85 static PyObject *Decoder_output_new(PyObject *self, PyObject *py_output_type)
86 {
87         PyObject *ret;
88         struct srd_decoder_instance *di;
89         char *protocol_id, *description;
90         int output_type, pdo_id;
91
92         if (!(di = get_di_by_decobject(self)))
93                 return NULL;
94
95         printf("output_new di %s\n", di->decoder->name);
96
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))
100                 return NULL;
101
102         protocol_id = "i2c";
103         description = "blah";
104         pdo_id = pd_output_new(di, output_type, protocol_id, description);
105         if (pdo_id < 0)
106                 Py_RETURN_NONE;
107         else
108                 ret = Py_BuildValue("i", pdo_id);
109
110         return ret;
111 }
112
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}
121 };
122
123
124 typedef struct {
125         PyObject_HEAD
126 } sigrok_Decoder_object;
127
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,
135 };
136
137 static struct PyModuleDef sigrok_Decoder_module = {
138         PyModuleDef_HEAD_INIT,
139         .m_name = "sigrok",
140         .m_doc = "sigrok base classes",
141         .m_size = -1,
142         .m_methods = no_methods,
143 };
144
145 PyMODINIT_FUNC PyInit_sigrok(void)
146 {
147         PyObject *mod;
148
149         /* assign this here, for compiler portability */
150         sigrok_Decoder_type.tp_new = PyType_GenericNew;
151         if (PyType_Ready(&sigrok_Decoder_type) < 0)
152                 return NULL;
153
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)
158                 return NULL;
159
160         return mod;
161 }
162
163
164 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
165 {
166         GSList *l;
167         struct srd_decoder_instance *di;
168
169         for (l = di_list; l; l = l->next) {
170                 di = l->data;
171                 if (decobject == di->py_instance)
172                         return di;
173         }
174
175         return NULL;
176 }
177
178 /**
179  * Initialize libsigrokdecode.
180  *
181  * This initializes the Python interpreter, and creates and initializes
182  * a "sigrok" Python module with a single put() method.
183  *
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().
188  *
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.
191  *
192  * Multiple calls to srd_init(), without calling srd_exit() inbetween,
193  * are not allowed.
194  *
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.
199  */
200 int srd_init(void)
201 {
202         int ret;
203
204         PyImport_AppendInittab("sigrok", PyInit_sigrok);
205
206         /* Py_Initialize() returns void and usually cannot fail. */
207         Py_Initialize();
208
209         PyInit_sigrok();
210
211         PyRun_SimpleString("import sys;");
212         if ((ret = set_modulepath()) != SRD_OK) {
213                 Py_Finalize();
214                 return ret;
215         }
216
217         if ((ret = srd_load_all_decoders()) != SRD_OK) {
218                 Py_Finalize();
219                 return ret;
220         }
221
222         return SRD_OK;
223 }
224
225
226 /**
227  * Shutdown libsigrokdecode.
228  *
229  * This frees all the memory allocated for protocol decoders and shuts down
230  * the Python interpreter.
231  *
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.
235  *
236  * @return SRD_OK upon success, a (negative) error code otherwise.
237  */
238 int srd_exit(void)
239 {
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);
244
245         /* Py_Finalize() returns void, any finalization errors are ignored. */
246         Py_Finalize();
247
248         return SRD_OK;
249 }
250
251
252 /**
253  * Add search directories for the protocol decoders.
254  *
255  * TODO: add path from env var SIGROKDECODE_PATH, config etc
256  */
257 int set_modulepath(void)
258 {
259         int ret;
260
261         ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
262
263         return ret;
264 }
265
266
267 struct srd_decoder_instance *srd_instance_new(const char *id)
268 {
269         struct srd_decoder *dec;
270         struct srd_decoder_instance *di;
271         PyObject *py_args;
272
273         fprintf(stdout, "%s: %s\n", __func__, id);
274
275         if (!(dec = srd_get_decoder_by_id(id)))
276                 return NULL;
277
278         /* TODO: Error handling. Use g_try_malloc(). */
279         di = g_malloc(sizeof(*di));
280         di->decoder = dec;
281         di->pd_output = NULL;
282
283         /* Create an empty Python tuple. */
284         if (!(py_args = PyTuple_New(0))) { /* NEWREF */
285                 if (PyErr_Occurred())
286                         PyErr_Print(); /* Returns void. */
287
288                 return NULL; /* TODO: More specific error? */
289         }
290
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. */
296                 Py_XDECREF(py_args);
297                 return NULL; /* TODO: More specific error? */
298         }
299         di_list = g_slist_append(di_list, di);
300
301         Py_XDECREF(py_args);
302
303         return di;
304 }
305
306
307 int srd_instance_set_probe(struct srd_decoder_instance *di,
308                            const char *probename, int num)
309 {
310         PyObject *probedict, *probenum;
311
312         probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
313         if (!probedict) {
314                 if (PyErr_Occurred())
315                         PyErr_Print(); /* Returns void. */
316
317                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
318         }
319
320         probenum = PyLong_FromLong(num);
321         PyMapping_SetItemString(probedict, (char *)probename, probenum);
322
323         Py_XDECREF(probenum);
324         Py_XDECREF(probedict);
325
326         return SRD_OK;
327 }
328
329
330 int srd_session_start(const char *driver, int unitsize, uint64_t starttime,
331                 uint64_t samplerate)
332 {
333         PyObject *py_res;
334         GSList *d;
335         struct srd_decoder_instance *di;
336
337         fprintf(stdout, "%s: %s\n", __func__, driver);
338
339         for (d = di_list; d; d = d->next) {
340                 di = d->data;
341                 if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
342                                         "{s:s,s:l,s:l,s:l}",
343                                         "driver", driver,
344                                         "unitsize", (long)unitsize,
345                                         "starttime", (long)starttime,
346                                         "samplerate", (long)samplerate))) {
347                         if (PyErr_Occurred())
348                                 PyErr_Print(); /* Returns void. */
349
350                         return SRD_ERR_PYTHON; /* TODO: More specific error? */
351                 }
352                 Py_XDECREF(py_res);
353         }
354
355         return SRD_OK;
356 }
357
358
359 /**
360  * Run the specified decoder function.
361  *
362  * @param dec TODO
363  * @param inbuf TODO
364  * @param inbuflen TODO
365  *
366  * @return SRD_OK upon success, a (negative) error code otherwise.
367  */
368 int srd_run_decoder(uint64_t timeoffset, uint64_t duration,
369                 struct srd_decoder_instance *dec, uint8_t *inbuf, uint64_t inbuflen)
370 {
371         PyObject *py_instance, *py_res;
372
373 //      fprintf(stdout, "%s: %s\n", __func__, dec->decoder->name);
374 //      printf("to %u du %u len %d\n", timeoffset, duration, inbuflen);
375
376         /* Return an error upon unusable input. */
377         if (dec == NULL)
378                 return SRD_ERR_ARG; /* TODO: More specific error? */
379         if (inbuf == NULL)
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? */
383
384         /* TODO: Error handling. */
385         py_instance = dec->py_instance;
386         Py_XINCREF(py_instance);
387
388         if (!(py_res = PyObject_CallMethod(py_instance, "decode",
389                         "KKs#", timeoffset, duration, inbuf, inbuflen))) {
390                 if (PyErr_Occurred())
391                         PyErr_Print(); /* Returns void. */
392
393                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
394         }
395
396         Py_XDECREF(py_res);
397         return SRD_OK;
398 }
399
400
401 /* Feed logic samples to decoder session. */
402 int srd_session_feed(uint64_t timeoffset, uint64_t duration, uint8_t *inbuf,
403                 uint64_t inbuflen)
404 {
405         GSList *d;
406         int ret;
407
408 //      fprintf(stdout, "%s: %d bytes\n", __func__, inbuflen);
409
410         for (d = di_list; d; d = d->next) {
411                 if ((ret = srd_run_decoder(timeoffset, duration, d->data, inbuf,
412                                 inbuflen)) != SRD_OK)
413                         return ret;
414         }
415
416         return SRD_OK;
417 }
418
419
420 int pd_output_new(struct srd_decoder_instance *di, int output_type,
421                 char *protocol_id, char *description)
422 {
423         GSList *l;
424         struct srd_pd_output *pdo;
425         int pdo_id;
426
427         fprintf(stdout, "%s: output type %d, protocol_id %s, description %s\n",
428                         __func__, output_type, protocol_id, description);
429
430         pdo_id = -1;
431         for (l = di->pd_output; l; l = l->next) {
432                 pdo = l->data;
433                 if (pdo->pdo_id > pdo_id)
434                         pdo_id = pdo->pdo_id;
435         }
436         pdo_id++;
437
438         if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
439                 return -1;
440
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);
446
447         return pdo_id;
448 }
449
450
451 //int srd_pipeline_new(int plid)
452 //{
453 //
454 //
455 //}
456
457
458
459