2 * This file is part of the libsigrokdecode project.
4 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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 3 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, see <http://www.gnu.org/licenses/>.
21 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode.h"
29 /* This is only used for nicer srd_dbg() output.
31 static const char *output_type_name(unsigned int idx)
33 static const char names[][16] = {
40 return names[MIN(idx, G_N_ELEMENTS(names) - 1)];
43 static void release_annotation(struct srd_proto_data_annotation *pda)
48 g_strfreev(pda->ann_text);
52 static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
53 struct srd_proto_data *pdata)
56 struct srd_pd_output *pdo;
57 struct srd_proto_data_annotation *pda;
60 PyGILState_STATE gstate;
62 gstate = PyGILState_Ensure();
64 /* Should be a list of [annotation class, [string, ...]]. */
65 if (!PyList_Check(obj)) {
66 srd_err("Protocol decoder %s submitted an annotation that"
67 " is not a list", di->decoder->name);
71 /* Should have 2 elements. */
72 if (PyList_Size(obj) != 2) {
73 srd_err("Protocol decoder %s submitted annotation list with "
74 "%zd elements instead of 2", di->decoder->name,
80 * The first element should be an integer matching a previously
81 * registered annotation class.
83 py_tmp = PyList_GetItem(obj, 0);
84 if (!PyLong_Check(py_tmp)) {
85 srd_err("Protocol decoder %s submitted annotation list, but "
86 "first element was not an integer.", di->decoder->name);
89 ann_class = PyLong_AsLong(py_tmp);
90 if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_class))) {
91 srd_err("Protocol decoder %s submitted data to unregistered "
92 "annotation class %d.", di->decoder->name, ann_class);
96 /* Second element must be a list. */
97 py_tmp = PyList_GetItem(obj, 1);
98 if (!PyList_Check(py_tmp)) {
99 srd_err("Protocol decoder %s submitted annotation list, but "
100 "second element was not a list.", di->decoder->name);
103 if (py_strseq_to_char(py_tmp, &ann_text) != SRD_OK) {
104 srd_err("Protocol decoder %s submitted annotation list, but "
105 "second element was malformed.", di->decoder->name);
109 pda = g_malloc(sizeof(struct srd_proto_data_annotation));
110 pda->ann_class = ann_class;
111 pda->ann_text = ann_text;
114 PyGILState_Release(gstate);
119 PyGILState_Release(gstate);
121 return SRD_ERR_PYTHON;
124 static void release_binary(struct srd_proto_data_binary *pdb)
128 g_free((void *)pdb->data);
132 static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
133 struct srd_proto_data *pdata)
135 struct srd_proto_data_binary *pdb;
139 char *class_name, *buf;
140 PyGILState_STATE gstate;
142 gstate = PyGILState_Ensure();
144 /* Should be a list of [binary class, bytes]. */
145 if (!PyList_Check(obj)) {
146 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_BINARY.",
151 /* Should have 2 elements. */
152 if (PyList_Size(obj) != 2) {
153 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list "
154 "with %zd elements instead of 2", di->decoder->name,
159 /* The first element should be an integer. */
160 py_tmp = PyList_GetItem(obj, 0);
161 if (!PyLong_Check(py_tmp)) {
162 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
163 "but first element was not an integer.", di->decoder->name);
166 bin_class = PyLong_AsLong(py_tmp);
167 if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
168 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
169 "unregistered binary class %d.", di->decoder->name, bin_class);
173 /* Second element should be bytes. */
174 py_tmp = PyList_GetItem(obj, 1);
175 if (!PyBytes_Check(py_tmp)) {
176 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
177 "but second element was not bytes.", di->decoder->name);
181 /* Consider an empty set of bytes a bug. */
182 if (PyBytes_Size(py_tmp) == 0) {
183 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
184 "with empty data set.", di->decoder->name);
188 if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
191 PyGILState_Release(gstate);
193 pdb = g_malloc(sizeof(struct srd_proto_data_binary));
194 pdb->bin_class = bin_class;
196 if (!(pdb->data = g_try_malloc(pdb->size))) {
198 return SRD_ERR_MALLOC;
200 memcpy((void *)pdb->data, (const void *)buf, pdb->size);
206 PyGILState_Release(gstate);
208 return SRD_ERR_PYTHON;
211 static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
215 PyGILState_STATE gstate;
217 gstate = PyGILState_Ensure();
219 if (pdata->pdo->meta_type == G_VARIANT_TYPE_INT64) {
220 if (!PyLong_Check(obj)) {
221 PyErr_Format(PyExc_TypeError, "This output was registered "
222 "as 'int', but something else was passed.");
225 intvalue = PyLong_AsLongLong(obj);
226 if (PyErr_Occurred())
228 pdata->data = g_variant_new_int64(intvalue);
229 } else if (pdata->pdo->meta_type == G_VARIANT_TYPE_DOUBLE) {
230 if (!PyFloat_Check(obj)) {
231 PyErr_Format(PyExc_TypeError, "This output was registered "
232 "as 'float', but something else was passed.");
235 dvalue = PyFloat_AsDouble(obj);
236 if (PyErr_Occurred())
238 pdata->data = g_variant_new_double(dvalue);
241 PyGILState_Release(gstate);
246 PyGILState_Release(gstate);
248 return SRD_ERR_PYTHON;
251 static void release_meta(GVariant *gvar)
255 g_variant_unref(gvar);
258 static PyObject *Decoder_put(PyObject *self, PyObject *args)
261 PyObject *py_data, *py_res;
262 struct srd_decoder_inst *di, *next_di;
263 struct srd_pd_output *pdo;
264 struct srd_proto_data pdata;
265 uint64_t start_sample, end_sample;
267 struct srd_pd_callback *cb;
268 PyGILState_STATE gstate;
272 gstate = PyGILState_Ensure();
274 if (!(di = srd_inst_find_by_obj(NULL, self))) {
275 /* Shouldn't happen. */
276 srd_dbg("put(): self instance not found.");
280 if (!PyArg_ParseTuple(args, "KKiO", &start_sample, &end_sample,
281 &output_id, &py_data)) {
283 * This throws an exception, but by returning NULL here we let
284 * Python raise it. This results in a much better trace in
285 * controller.c on the decode() method call.
290 if (!(l = g_slist_nth(di->pd_output, output_id))) {
291 srd_err("Protocol decoder %s submitted invalid output ID %d.",
292 di->decoder->name, output_id);
297 srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on oid %d.",
298 di->inst_id, start_sample, end_sample,
299 output_type_name(pdo->output_type), output_id);
301 pdata.start_sample = start_sample;
302 pdata.end_sample = end_sample;
306 switch (pdo->output_type) {
308 /* Annotations are only fed to callbacks. */
309 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
310 /* Convert from PyDict to srd_proto_data_annotation. */
311 if (convert_annotation(di, py_data, &pdata) != SRD_OK) {
312 /* An error was already logged. */
315 Py_BEGIN_ALLOW_THREADS
316 cb->cb(&pdata, cb->cb_data);
318 release_annotation(pdata.data);
321 case SRD_OUTPUT_PYTHON:
322 for (l = di->next_di; l; l = l->next) {
324 srd_spew("Sending %" PRIu64 "-%" PRIu64 " to instance %s",
325 start_sample, end_sample, next_di->inst_id);
326 if (!(py_res = PyObject_CallMethod(
327 next_di->py_inst, "decode", "KKO", start_sample,
328 end_sample, py_data))) {
329 srd_exception_catch("Calling %s decode() failed",
334 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
335 /* Frontends aren't really supposed to get Python
336 * callbacks, but it's useful for testing. */
337 pdata.data = py_data;
338 cb->cb(&pdata, cb->cb_data);
341 case SRD_OUTPUT_BINARY:
342 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
343 /* Convert from PyDict to srd_proto_data_binary. */
344 if (convert_binary(di, py_data, &pdata) != SRD_OK) {
345 /* An error was already logged. */
348 Py_BEGIN_ALLOW_THREADS
349 cb->cb(&pdata, cb->cb_data);
351 release_binary(pdata.data);
354 case SRD_OUTPUT_META:
355 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
356 /* Annotations need converting from PyObject. */
357 if (convert_meta(&pdata, py_data) != SRD_OK) {
358 /* An exception was already set up. */
361 Py_BEGIN_ALLOW_THREADS
362 cb->cb(&pdata, cb->cb_data);
364 release_meta(pdata.data);
368 srd_err("Protocol decoder %s submitted invalid output type %d.",
369 di->decoder->name, pdo->output_type);
373 PyGILState_Release(gstate);
378 PyGILState_Release(gstate);
383 static PyObject *Decoder_register(PyObject *self, PyObject *args,
386 struct srd_decoder_inst *di;
387 struct srd_pd_output *pdo;
388 PyObject *py_new_output_id;
389 PyTypeObject *meta_type_py;
390 const GVariantType *meta_type_gv;
392 char *proto_id, *meta_name, *meta_descr;
393 char *keywords[] = {"output_type", "proto_id", "meta", NULL};
394 PyGILState_STATE gstate;
397 struct srd_pd_output *cmp;
399 gstate = PyGILState_Ensure();
403 meta_name = meta_descr = NULL;
405 if (!(di = srd_inst_find_by_obj(NULL, self))) {
406 PyErr_SetString(PyExc_Exception, "decoder instance not found");
410 /* Default to instance id, which defaults to class id. */
411 proto_id = di->inst_id;
412 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
413 &output_type, &proto_id,
414 &meta_type_py, &meta_name, &meta_descr)) {
415 /* Let Python raise this exception. */
419 /* Check if the meta value's type is supported. */
420 is_meta = output_type == SRD_OUTPUT_META;
422 if (meta_type_py == &PyLong_Type)
423 meta_type_gv = G_VARIANT_TYPE_INT64;
424 else if (meta_type_py == &PyFloat_Type)
425 meta_type_gv = G_VARIANT_TYPE_DOUBLE;
427 PyErr_Format(PyExc_TypeError, "Unsupported type.");
433 for (l = di->pd_output; l; l = l->next) {
435 if (cmp->output_type != output_type)
437 if (strcmp(cmp->proto_id, proto_id) != 0)
439 if (is_meta && cmp->meta_type != meta_type_gv)
441 if (is_meta && strcmp(cmp->meta_name, meta_name) != 0)
443 if (is_meta && strcmp(cmp->meta_descr, meta_descr) != 0)
449 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
450 PyGILState_Release(gstate);
451 return py_new_output_id;
454 srd_dbg("Instance %s creating new output type %d for %s.",
455 di->inst_id, output_type, proto_id);
457 pdo = g_malloc(sizeof(struct srd_pd_output));
459 /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
460 pdo->pdo_id = g_slist_length(di->pd_output);
461 pdo->output_type = output_type;
463 pdo->proto_id = g_strdup(proto_id);
465 if (output_type == SRD_OUTPUT_META) {
466 pdo->meta_type = meta_type_gv;
467 pdo->meta_name = g_strdup(meta_name);
468 pdo->meta_descr = g_strdup(meta_descr);
471 di->pd_output = g_slist_append(di->pd_output, pdo);
472 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
474 PyGILState_Release(gstate);
476 return py_new_output_id;
479 PyGILState_Release(gstate);
484 static int get_term_type(const char *v)
488 return SRD_TERM_HIGH;
492 return SRD_TERM_RISING_EDGE;
494 return SRD_TERM_FALLING_EDGE;
496 return SRD_TERM_EITHER_EDGE;
498 return SRD_TERM_NO_EDGE;
507 * Get the pin values at the current sample number.
509 * @param di The decoder instance to use. Must not be NULL.
510 * The number of channels must be >= 1.
512 * @return A newly allocated PyTuple containing the pin values at the
513 * current sample number.
515 static PyObject *get_current_pinvalues(const struct srd_decoder_inst *di)
519 const uint8_t *sample_pos;
520 int byte_offset, bit_offset;
521 PyObject *py_pinvalues;
522 PyGILState_STATE gstate;
525 srd_err("Invalid decoder instance.");
529 gstate = PyGILState_Ensure();
531 py_pinvalues = PyTuple_New(di->dec_num_channels);
533 for (i = 0; i < di->dec_num_channels; i++) {
534 /* A channelmap value of -1 means "unused optional channel". */
535 if (di->dec_channelmap[i] == -1) {
536 /* Value of unused channel is 0xff, instead of 0 or 1. */
537 PyTuple_SetItem(py_pinvalues, i, PyLong_FromLong(0xff));
539 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
540 byte_offset = di->dec_channelmap[i] / 8;
541 bit_offset = di->dec_channelmap[i] % 8;
542 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
543 PyTuple_SetItem(py_pinvalues, i, PyLong_FromLong(sample));
547 PyGILState_Release(gstate);
553 * Create a list of terms in the specified condition.
555 * If there are no terms in the condition, 'term_list' will be NULL.
557 * @param py_dict A Python dict containing terms. Must not be NULL.
558 * @param term_list Pointer to a GSList which will be set to the newly
559 * created list of terms. Must not be NULL.
561 * @return SRD_OK upon success, a negative error code otherwise.
563 static int create_term_list(PyObject *py_dict, GSList **term_list)
566 PyObject *py_key, *py_value;
567 struct srd_term *term;
568 uint64_t num_samples_to_skip;
570 PyGILState_STATE gstate;
572 if (!py_dict || !term_list)
575 /* "Create" an empty GSList of terms. */
578 gstate = PyGILState_Ensure();
580 /* Iterate over all items in the current dict. */
581 while (PyDict_Next(py_dict, &pos, &py_key, &py_value)) {
582 /* Check whether the current key is a string or a number. */
583 if (PyLong_Check(py_key)) {
584 /* The key is a number. */
585 /* TODO: Check if the number is a valid channel. */
586 /* Get the value string. */
587 if ((py_pydictitem_as_str(py_dict, py_key, &term_str)) != SRD_OK) {
588 srd_err("Failed to get the value.");
591 term = g_malloc(sizeof(struct srd_term));
592 term->type = get_term_type(term_str);
593 term->channel = PyLong_AsLong(py_key);
595 } else if (PyUnicode_Check(py_key)) {
596 /* The key is a string. */
597 /* TODO: Check if it's "skip". */
598 if ((py_pydictitem_as_long(py_dict, py_key, &num_samples_to_skip)) != SRD_OK) {
599 srd_err("Failed to get number of samples to skip.");
602 term = g_malloc(sizeof(struct srd_term));
603 term->type = SRD_TERM_SKIP;
604 term->num_samples_to_skip = num_samples_to_skip;
605 term->num_samples_already_skipped = 0;
607 srd_err("Term key is neither a string nor a number.");
611 /* Add the term to the list of terms. */
612 *term_list = g_slist_append(*term_list, term);
615 PyGILState_Release(gstate);
620 PyGILState_Release(gstate);
626 * Replace the current condition list with the new one.
628 * @param self TODO. Must not be NULL.
629 * @param args TODO. Must not be NULL.
631 * @retval SRD_OK The new condition list was set successfully.
632 * @retval SRD_ERR There was an error setting the new condition list.
633 * The contents of di->condition_list are undefined.
636 static int set_new_condition_list(PyObject *self, PyObject *args)
638 struct srd_decoder_inst *di;
640 PyObject *py_conditionlist, *py_conds, *py_dict;
641 int i, num_conditions, ret;
642 PyGILState_STATE gstate;
647 gstate = PyGILState_Ensure();
649 /* Get the decoder instance. */
650 if (!(di = srd_inst_find_by_obj(NULL, self))) {
651 PyErr_SetString(PyExc_Exception, "decoder instance not found");
656 * Return an error condition from .wait() when termination is
657 * requested, such that decode() will terminate.
659 if (di->want_wait_terminate) {
660 srd_dbg("%s: %s: Skip (want_term).", di->inst_id, __func__);
665 * Parse the argument of self.wait() into 'py_conds', and check
666 * the data type. The argument is optional, None is assumed in
667 * its absence. None or an empty dict or an empty list mean that
668 * there is no condition, and the next available sample shall
669 * get returned to the caller.
672 if (!PyArg_ParseTuple(args, "|O", &py_conds)) {
673 /* Let Python raise this exception. */
676 if (py_conds == Py_None) {
677 /* 'py_conds' is None. */
679 } else if (PyList_Check(py_conds)) {
680 /* 'py_conds' is a list. */
681 py_conditionlist = py_conds;
682 num_conditions = PyList_Size(py_conditionlist);
683 if (num_conditions == 0)
684 goto ret_9999; /* The PD invoked self.wait([]). */
685 Py_IncRef(py_conditionlist);
686 } else if (PyDict_Check(py_conds)) {
687 /* 'py_conds' is a dict. */
688 if (PyDict_Size(py_conds) == 0)
689 goto ret_9999; /* The PD invoked self.wait({}). */
690 /* Make a list and put the dict in there for convenience. */
691 py_conditionlist = PyList_New(1);
693 PyList_SetItem(py_conditionlist, 0, py_conds);
696 srd_err("Condition list is neither a list nor a dict.");
700 /* Free the old condition list. */
701 condition_list_free(di);
705 /* Iterate over the conditions, set di->condition_list accordingly. */
706 for (i = 0; i < num_conditions; i++) {
707 /* Get a condition (dict) from the condition list. */
708 py_dict = PyList_GetItem(py_conditionlist, i);
709 if (!PyDict_Check(py_dict)) {
710 srd_err("Condition is not a dict.");
715 /* Create the list of terms in this condition. */
716 if ((ret = create_term_list(py_dict, &term_list)) < 0)
719 /* Add the new condition to the PD instance's condition list. */
720 di->condition_list = g_slist_append(di->condition_list, term_list);
723 Py_DecRef(py_conditionlist);
725 PyGILState_Release(gstate);
730 PyGILState_Release(gstate);
735 PyGILState_Release(gstate);
741 * Create a SKIP condition list for condition-less .wait() calls.
743 * @param di Decoder instance.
744 * @param count Number of samples to skip.
746 * @retval SRD_OK The new condition list was set successfully.
747 * @retval SRD_ERR There was an error setting the new condition list.
748 * The contents of di->condition_list are undefined.
750 * This routine is a reduced and specialized version of the @ref
751 * set_new_condition_list() and @ref create_term_list() routines which
752 * gets invoked when .wait() was called without specifications for
753 * conditions. This minor duplication of the SKIP term list creation
754 * simplifies the logic and avoids the creation of expensive Python
755 * objects with "constant" values which the caller did not pass in the
756 * first place. It results in maximum sharing of match handling code
759 static int set_skip_condition(struct srd_decoder_inst *di, uint64_t count)
761 struct srd_term *term;
764 condition_list_free(di);
765 term = g_malloc(sizeof(*term));
766 term->type = SRD_TERM_SKIP;
767 term->num_samples_to_skip = count;
768 term->num_samples_already_skipped = 0;
769 term_list = g_slist_append(NULL, term);
770 di->condition_list = g_slist_append(di->condition_list, term_list);
775 static PyObject *Decoder_wait(PyObject *self, PyObject *args)
780 gboolean found_match;
781 struct srd_decoder_inst *di;
782 PyObject *py_pinvalues, *py_matched;
783 PyGILState_STATE gstate;
788 gstate = PyGILState_Ensure();
790 if (!(di = srd_inst_find_by_obj(NULL, self))) {
791 PyErr_SetString(PyExc_Exception, "decoder instance not found");
792 PyGILState_Release(gstate);
796 ret = set_new_condition_list(self, args);
798 srd_dbg("%s: %s: Aborting wait().", di->inst_id, __func__);
803 * Empty condition list, automatic match. Arrange for the
804 * execution of regular match handling code paths such that
805 * the next available sample is returned to the caller.
806 * Make sure to skip one sample when "anywhere within the
807 * stream", yet make sure to not skip sample number 0.
809 if (di->abs_cur_samplenum)
811 else if (!di->condition_list)
815 ret = set_skip_condition(di, skip_count);
817 srd_dbg("%s: %s: Cannot setup condition-less wait().",
818 di->inst_id, __func__);
825 Py_BEGIN_ALLOW_THREADS
827 /* Wait for new samples to process, or termination request. */
828 g_mutex_lock(&di->data_mutex);
829 while (!di->got_new_samples && !di->want_wait_terminate)
830 g_cond_wait(&di->got_new_samples_cond, &di->data_mutex);
833 * Check whether any of the current condition(s) match.
834 * Arrange for termination requests to take a code path which
835 * won't find new samples to process, pretends to have processed
836 * previously stored samples, and returns to the main thread,
837 * while the termination request still gets signalled.
841 /* Ignore return value for now, should never be negative. */
842 (void)process_samples_until_condition_match(di, &found_match);
846 /* If there's a match, set self.samplenum etc. and return. */
848 /* Set self.samplenum to the (absolute) sample number that matched. */
849 PyObject_SetAttrString(di->py_inst, "samplenum",
850 PyLong_FromLong(di->abs_cur_samplenum));
852 if (di->match_array && di->match_array->len > 0) {
853 py_matched = PyTuple_New(di->match_array->len);
854 for (i = 0; i < di->match_array->len; i++)
855 PyTuple_SetItem(py_matched, i, PyBool_FromLong(di->match_array->data[i]));
856 PyObject_SetAttrString(di->py_inst, "matched", py_matched);
857 match_array_free(di);
859 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
862 py_pinvalues = get_current_pinvalues(di);
864 g_mutex_unlock(&di->data_mutex);
866 PyGILState_Release(gstate);
871 /* No match, reset state for the next chunk. */
872 di->got_new_samples = FALSE;
873 di->handled_all_samples = TRUE;
874 di->abs_start_samplenum = 0;
875 di->abs_end_samplenum = 0;
879 /* Signal the main thread that we handled all samples. */
880 g_cond_signal(&di->handled_all_samples_cond);
883 * When termination of wait() and decode() was requested,
884 * then exit the loop after releasing the mutex.
886 if (di->want_wait_terminate) {
887 srd_dbg("%s: %s: Will return from wait().",
888 di->inst_id, __func__);
889 g_mutex_unlock(&di->data_mutex);
893 g_mutex_unlock(&di->data_mutex);
896 PyGILState_Release(gstate);
901 PyGILState_Release(gstate);
907 * Return whether the specified channel was supplied to the decoder.
909 * @param self TODO. Must not be NULL.
910 * @param args TODO. Must not be NULL.
912 * @retval Py_True The channel has been supplied by the frontend.
913 * @retval Py_False The channel has been supplied by the frontend.
914 * @retval NULL An error occurred.
916 static PyObject *Decoder_has_channel(PyObject *self, PyObject *args)
919 struct srd_decoder_inst *di;
920 PyGILState_STATE gstate;
925 gstate = PyGILState_Ensure();
927 if (!(di = srd_inst_find_by_obj(NULL, self))) {
928 PyErr_SetString(PyExc_Exception, "decoder instance not found");
933 * Get the integer argument of self.has_channel(). Check for
934 * the range of supported PD input channel numbers.
936 if (!PyArg_ParseTuple(args, "i", &idx)) {
937 /* Let Python raise this exception. */
941 count = g_slist_length(di->decoder->channels) +
942 g_slist_length(di->decoder->opt_channels);
943 if (idx < 0 || idx >= count) {
944 srd_err("Invalid index %d, PD channel count %d.", idx, count);
945 PyErr_SetString(PyExc_IndexError, "invalid channel index");
949 PyGILState_Release(gstate);
951 return (di->dec_channelmap[idx] == -1) ? Py_False : Py_True;
954 PyGILState_Release(gstate);
959 static PyMethodDef Decoder_methods[] = {
960 {"put", Decoder_put, METH_VARARGS,
961 "Accepts a dictionary with the following keys: startsample, endsample, data"},
962 {"register", (PyCFunction)Decoder_register, METH_VARARGS|METH_KEYWORDS,
963 "Register a new output stream"},
964 {"wait", Decoder_wait, METH_VARARGS,
965 "Wait for one or more conditions to occur"},
966 {"has_channel", Decoder_has_channel, METH_VARARGS,
967 "Report whether a channel was supplied"},
968 {NULL, NULL, 0, NULL}
972 * Create the sigrokdecode.Decoder type.
974 * @return The new type object.
978 SRD_PRIV PyObject *srd_Decoder_type_new(void)
981 PyType_Slot slots[] = {
982 { Py_tp_doc, "sigrok Decoder base class" },
983 { Py_tp_methods, Decoder_methods },
984 { Py_tp_new, (void *)&PyType_GenericNew },
988 PyGILState_STATE gstate;
990 gstate = PyGILState_Ensure();
992 spec.name = "sigrokdecode.Decoder";
993 spec.basicsize = sizeof(srd_Decoder);
995 spec.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
998 py_obj = PyType_FromSpec(&spec);
1000 PyGILState_Release(gstate);