]> sigrok.org Git - libsigrokdecode.git/blob - controller.c
140f664f1a2166992095a23459195993e939308b
[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 /* TODO: this should probably be in sigrokdecode.h */
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
32 #endif
33
34
35 /* TODO
36 static GSList *pipelines = NULL;
37 */
38
39 /* lives in decoder.c */
40 extern GSList *pd_list;
41 extern GSList *di_list;
42
43 struct srd_pipeline {
44         int id;
45         GSList *decoders;
46 };
47
48
49
50 static PyObject *Decoder_init(PyObject *self, PyObject *args)
51 {
52         (void)self;
53         (void)args;
54 //      printf("init object %x\n", self);
55
56         Py_RETURN_NONE;
57 }
58
59 struct srd_decoder_instance *get_di_by_decobject(void *decobject);
60
61 static PyObject *Decoder_put(PyObject *self, PyObject *args)
62 {
63         GSList *l;
64         PyObject *data;
65         struct srd_decoder_instance *di;
66         struct srd_pd_output *pdo;
67         uint64_t timeoffset, duration;
68         int output_id;
69
70         if (!(di = get_di_by_decobject(self)))
71                 return NULL;
72
73         if (!PyArg_ParseTuple(args, "KKiO", &timeoffset, &duration, &output_id, &data))
74                 return NULL;
75
76         printf("put: %s instance %p time %" PRIu64 " duration %" PRIu64 " ",
77                         di->decoder->name, di, timeoffset, duration);
78
79         if (!(l = g_slist_nth(di->pd_output, output_id)))
80                 /* PD supplied invalid output id */
81                 /* TODO: better error message */
82                 return NULL;
83         pdo = l->data;
84
85         printf("stream %d: ", pdo->output_type);
86         PyObject_Print(data, stdout, Py_PRINT_RAW);
87         puts("");
88
89         Py_RETURN_NONE;
90 }
91
92
93 static PyObject *Decoder_output_new(PyObject *self, PyObject *py_output_type)
94 {
95         PyObject *ret;
96         struct srd_decoder_instance *di;
97         char *protocol_id, *description;
98         int output_type, pdo_id;
99
100         if (!(di = get_di_by_decobject(self)))
101                 return NULL;
102
103         printf("output_new di %s\n", di->decoder->name);
104
105 //      if (!PyArg_ParseTuple(args, "i:output_type,s:protocol_id,s:description",
106 //                      &output_type, &protocol_id, &description))
107         if (!PyArg_ParseTuple(py_output_type, "i:output_type", &output_type))
108                 return NULL;
109
110         protocol_id = "i2c";
111         description = "blah";
112         pdo_id = pd_output_new(di, output_type, protocol_id, description);
113         if (pdo_id < 0)
114                 Py_RETURN_NONE;
115         else
116                 ret = Py_BuildValue("i", pdo_id);
117
118         return ret;
119 }
120
121 static PyMethodDef no_methods[] = { {NULL, NULL, 0, NULL} };
122 static PyMethodDef Decoder_methods[] = {
123         {"__init__", Decoder_init, METH_VARARGS, ""},
124         {"put", Decoder_put, METH_VARARGS,
125          "Accepts a dictionary with the following keys: time, duration, data"},
126         {"output_new", Decoder_output_new, METH_VARARGS,
127          "Create a new output stream"},
128         {NULL, NULL, 0, NULL}
129 };
130
131
132 typedef struct {
133         PyObject_HEAD
134 } sigrok_Decoder_object;
135
136 static PyTypeObject sigrok_Decoder_type = {
137         PyObject_HEAD_INIT(NULL)
138         .tp_name = "sigrok.Decoder",
139         .tp_basicsize = sizeof(sigrok_Decoder_object),
140         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
141         .tp_doc = "Sigrok Decoder object",
142         .tp_methods = Decoder_methods,
143 };
144
145 PyMODINIT_FUNC init_sigrok_Decoder(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;
153
154         mod = Py_InitModule3("sigrok", no_methods, "sigrok base classes");
155         Py_INCREF(&sigrok_Decoder_type);
156         PyModule_AddObject(mod, "Decoder", (PyObject *)&sigrok_Decoder_type);
157
158 }
159
160
161 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
162 {
163         GSList *l;
164         struct srd_decoder_instance *di;
165
166         for (l = di_list; l; l = l->next) {
167                 di = l->data;
168                 if (decobject == di->py_instance)
169                         return di;
170         }
171
172         return NULL;
173 }
174
175 /**
176  * Initialize libsigrokdecode.
177  *
178  * This initializes the Python interpreter, and creates and initializes
179  * a "sigrok" Python module with a single put() method.
180  *
181  * Then, it searches for sigrok protocol decoder files (*.py) in the
182  * "decoders" subdirectory of the the sigrok installation directory.
183  * All decoders that are found are loaded into memory and added to an
184  * internal list of decoders, which can be queried via srd_list_decoders().
185  *
186  * The caller is responsible for calling the clean-up function srd_exit(),
187  * which will properly shut down libsigrokdecode and free its allocated memory.
188  *
189  * Multiple calls to srd_init(), without calling srd_exit() inbetween,
190  * are not allowed.
191  *
192  * @return SRD_OK upon success, a (negative) error code otherwise.
193  *         Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
194  *         directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
195  *         If not enough memory could be allocated, return SRD_ERR_MALLOC.
196  */
197 int srd_init(void)
198 {
199         int ret;
200
201         /* Py_Initialize() returns void and usually cannot fail. */
202         Py_Initialize();
203
204         init_sigrok_Decoder();
205
206         PyRun_SimpleString("import sys;");
207         if ((ret = set_modulepath()) != SRD_OK) {
208                 Py_Finalize();
209                 return ret;
210         }
211
212         if ((ret = srd_load_all_decoders()) != SRD_OK) {
213                 Py_Finalize();
214                 return ret;
215         }
216
217         return SRD_OK;
218 }
219
220
221 /**
222  * Shutdown libsigrokdecode.
223  *
224  * This frees all the memory allocated for protocol decoders and shuts down
225  * the Python interpreter.
226  *
227  * This function should only be called if there was a (successful!) invocation
228  * of srd_init() before. Calling this function multiple times in a row, without
229  * any successful srd_init() calls inbetween, is not allowed.
230  *
231  * @return SRD_OK upon success, a (negative) error code otherwise.
232  */
233 int srd_exit(void)
234 {
235         /* Unload/free all decoders, and then the list of decoders itself. */
236         /* TODO: Error handling. */
237         srd_unload_all_decoders();
238         g_slist_free(pd_list);
239
240         /* Py_Finalize() returns void, any finalization errors are ignored. */
241         Py_Finalize();
242
243         return SRD_OK;
244 }
245
246
247 /**
248  * Add search directories for the protocol decoders.
249  *
250  * TODO: add path from env var SIGROKDECODE_PATH, config etc
251  */
252 int set_modulepath(void)
253 {
254         int ret;
255
256         ret = PyRun_SimpleString("sys.path.append(r'" DECODERS_DIR "');");
257
258         return ret;
259 }
260
261
262 struct srd_decoder_instance *srd_instance_new(const char *id)
263 {
264         struct srd_decoder *dec;
265         struct srd_decoder_instance *di;
266         PyObject *py_args;
267
268         fprintf(stdout, "%s: %s\n", __func__, id);
269
270         if (!(dec = srd_get_decoder_by_id(id)))
271                 return NULL;
272
273         /* TODO: Error handling. Use g_try_malloc(). */
274         di = g_malloc(sizeof(*di));
275         di->decoder = dec;
276         di->pd_output = NULL;
277
278         /* Create an empty Python tuple. */
279         if (!(py_args = PyTuple_New(0))) { /* NEWREF */
280                 if (PyErr_Occurred())
281                         PyErr_Print(); /* Returns void. */
282
283                 return NULL; /* TODO: More specific error? */
284         }
285
286         /* Create an instance of the 'Decoder' class. */
287         di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
288         if (!di->py_instance) {
289                 if (PyErr_Occurred())
290                         PyErr_Print(); /* Returns void. */
291                 Py_XDECREF(py_args);
292                 return NULL; /* TODO: More specific error? */
293         }
294         di_list = g_slist_append(di_list, di);
295
296         Py_XDECREF(py_args);
297
298         return di;
299 }
300
301
302 int srd_instance_set_probe(struct srd_decoder_instance *di,
303                            const char *probename, int num)
304 {
305         PyObject *probedict, *probenum;
306
307         probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
308         if (!probedict) {
309                 if (PyErr_Occurred())
310                         PyErr_Print(); /* Returns void. */
311
312                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
313         }
314
315         probenum = PyInt_FromLong(num);
316         PyMapping_SetItemString(probedict, (char *)probename, probenum);
317
318         Py_XDECREF(probenum);
319         Py_XDECREF(probedict);
320
321         return SRD_OK;
322 }
323
324
325 int srd_session_start(const char *driver, int unitsize, uint64_t starttime,
326                 uint64_t samplerate)
327 {
328         PyObject *py_res;
329         GSList *d;
330         struct srd_decoder_instance *di;
331
332         fprintf(stdout, "%s: %s\n", __func__, driver);
333
334         for (d = di_list; d; d = d->next) {
335                 di = d->data;
336                 if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
337                                         "{s:s,s:l,s:l,s:l}",
338                                         "driver", driver,
339                                         "unitsize", (long)unitsize,
340                                         "starttime", (long)starttime,
341                                         "samplerate", (long)samplerate))) {
342                         if (PyErr_Occurred())
343                                 PyErr_Print(); /* Returns void. */
344
345                         return SRD_ERR_PYTHON; /* TODO: More specific error? */
346                 }
347                 Py_XDECREF(py_res);
348         }
349
350         return SRD_OK;
351 }
352
353
354 /**
355  * Run the specified decoder function.
356  *
357  * @param dec TODO
358  * @param inbuf TODO
359  * @param inbuflen TODO
360  *
361  * @return SRD_OK upon success, a (negative) error code otherwise.
362  */
363 int srd_run_decoder(uint64_t timeoffset, uint64_t duration,
364                 struct srd_decoder_instance *dec, uint8_t *inbuf, uint64_t inbuflen)
365 {
366         PyObject *py_instance, *py_res;
367
368 //      fprintf(stdout, "%s: %s\n", __func__, dec->decoder->name);
369 //      printf("to %u du %u len %d\n", timeoffset, duration, inbuflen);
370
371         /* Return an error upon unusable input. */
372         if (dec == NULL)
373                 return SRD_ERR_ARG; /* TODO: More specific error? */
374         if (inbuf == NULL)
375                 return SRD_ERR_ARG; /* TODO: More specific error? */
376         if (inbuflen == 0) /* No point in working on empty buffers. */
377                 return SRD_ERR_ARG; /* TODO: More specific error? */
378
379         /* TODO: Error handling. */
380         py_instance = dec->py_instance;
381         Py_XINCREF(py_instance);
382
383         if (!(py_res = PyObject_CallMethod(py_instance, "decode",
384                         "KKs#", timeoffset, duration, inbuf, inbuflen))) {
385                 if (PyErr_Occurred())
386                         PyErr_Print(); /* Returns void. */
387
388                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
389         }
390
391         Py_XDECREF(py_res);
392         return SRD_OK;
393 }
394
395
396 /* Feed logic samples to decoder session. */
397 int srd_session_feed(uint64_t timeoffset, uint64_t duration, uint8_t *inbuf,
398                 uint64_t inbuflen)
399 {
400         GSList *d;
401         int ret;
402
403 //      fprintf(stdout, "%s: %d bytes\n", __func__, inbuflen);
404
405         for (d = di_list; d; d = d->next) {
406                 if ((ret = srd_run_decoder(timeoffset, duration, d->data, inbuf,
407                                 inbuflen)) != SRD_OK)
408                         return ret;
409         }
410
411         return SRD_OK;
412 }
413
414
415 int pd_output_new(struct srd_decoder_instance *di, int output_type,
416                 char *protocol_id, char *description)
417 {
418         GSList *l;
419         struct srd_pd_output *pdo;
420         int pdo_id;
421
422         fprintf(stdout, "%s: output type %d, protocol_id %s, description %s\n",
423                         __func__, output_type, protocol_id, description);
424
425         pdo_id = -1;
426         for (l = di->pd_output; l; l = l->next) {
427                 pdo = l->data;
428                 if (pdo->pdo_id > pdo_id)
429                         pdo_id = pdo->pdo_id;
430         }
431         pdo_id++;
432
433         if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
434                 return -1;
435
436         pdo->pdo_id = pdo_id;
437         pdo->output_type = output_type;
438         pdo->protocol_id = g_strdup(protocol_id);
439         pdo->description = g_strdup(description);
440         di->pd_output = g_slist_append(di->pd_output, pdo);
441
442         return pdo_id;
443 }
444
445
446 //int srd_pipeline_new(int plid)
447 //{
448 //
449 //
450 //}
451
452
453
454