]> sigrok.org Git - libsigrokdecode.git/blob - tests/runtc.c
Make the data unit size configurable
[libsigrokdecode.git] / tests / runtc.c
1 /*
2  * This file is part of the libsigrokdecode project.
3  *
4  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 #include "../libsigrokdecode.h"
21 #include <libsigrok/libsigrok.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stdarg.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <time.h>
31 #include <sys/time.h>
32 #include <sys/resource.h>
33 #include <glib.h>
34 #ifdef __LINUX__
35 #include <sched.h>
36 #endif
37 #include "../config.h"
38
39 int debug = FALSE;
40 int statistics = FALSE;
41
42 struct probe {
43         char *name;
44         int probe;
45 };
46
47 struct option {
48         char *key;
49         char *value;
50 };
51
52 struct pd {
53         char *name;
54         GSList *probes;
55         GSList *options;
56 };
57
58 struct output {
59         char *pd;
60         int type;
61         char *class;
62         int class_idx;
63         char *outfile;
64         int outfd;
65 };
66
67
68 static void logmsg(char *prefix, FILE *out, const char *format, va_list args)
69 {
70         if (prefix)
71                 fprintf(out, "%s", prefix);
72         vfprintf(out, format, args);
73         fprintf(out, "\n");
74 }
75
76 static void DBG(const char *format, ...)
77 {
78         va_list args;
79
80         if (!debug)
81                 return;
82         va_start(args, format);
83         logmsg("DBG: ", stdout, format, args);
84         va_end(args);
85 }
86
87 static void ERR(const char *format, ...)
88 {
89         va_list args;
90
91         va_start(args, format);
92         logmsg("Error: ", stderr, format, args);
93         va_end(args);
94 }
95
96 static int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
97 {
98         (void)cb_data;
99
100         if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
101                 logmsg("Error: sr: ", stderr, format, args);
102         else if (debug)
103                 logmsg("DBG: sr: ", stdout, format, args);
104
105         return SRD_OK;
106 }
107
108 static int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
109 {
110         (void)cb_data;
111
112         if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
113                 logmsg("Error: srd: ", stderr, format, args);
114         else if (debug)
115                 logmsg("DBG: srd: ", stdout, format, args);
116
117         return SRD_OK;
118 }
119
120 static void usage(char *msg)
121 {
122         if (msg)
123                 fprintf(stderr, "%s\n", msg);
124
125         printf("Usage: runtc [-dPpoiOf]\n");
126         printf("  -d  Debug\n");
127         printf("  -P  <protocol decoder>\n");
128         printf("  -p  <probename=probenum> (optional)\n");
129         printf("  -o  <probeoption=value> (optional)\n");
130         printf("  -i <input file>\n");
131         printf("  -O <output-pd:output-type[:output-class]>\n");
132         printf("  -f <output file> (optional)\n");
133         exit(msg ? 1 : 0);
134
135 }
136
137 /* This is a neutered version of libsigrokdecode's py_str_as_str(). It
138  * does no error checking, but then the only strings it processes are
139  * generated by Python's repr(), so are known good. */
140 static char *py_str_as_str(const PyObject *py_str)
141 {
142         PyObject *py_encstr;
143         char *str, *outstr;
144
145         py_encstr = PyUnicode_AsEncodedString((PyObject *)py_str, "utf-8", NULL);
146         str = PyBytes_AS_STRING(py_encstr);
147         outstr = g_strdup(str);
148         Py_DecRef(py_encstr);
149
150         return outstr;
151 }
152
153 static void srd_cb_py(struct srd_proto_data *pdata, void *cb_data)
154 {
155         struct output *op;
156         PyObject *pydata, *pyrepr;
157         GString *out;
158         char *s;
159
160         DBG("Python output from %s", pdata->pdo->di->inst_id);
161         op = cb_data;
162         pydata = pdata->data;
163         DBG("ptr %p", pydata);
164
165         if (strcmp(pdata->pdo->di->inst_id, op->pd))
166                 /* This is not the PD selected for output. */
167                 return;
168
169         if (!(pyrepr = PyObject_Repr(pydata))) {
170                 ERR("Invalid Python object.");
171                 return;
172         }
173         s = py_str_as_str(pyrepr);
174         Py_DecRef(pyrepr);
175
176         /* Output format for testing is '<ss>-<es> <inst-id>: <repr>\n' */
177         out = g_string_sized_new(128);
178         g_string_printf(out, "%"PRIu64"-%"PRIu64" %s: %s\n",
179                         pdata->start_sample, pdata->end_sample,
180                         pdata->pdo->di->inst_id, s);
181         g_free(s);
182         if (write(op->outfd, out->str, out->len) == -1)
183                 ERR("SRD_OUTPUT_PYTHON callback write failure!");
184         DBG("wrote '%s'", out->str);
185         g_string_free(out, TRUE);
186
187 }
188
189 static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
190 {
191         struct srd_proto_data_binary *pdb;
192         struct output *op;
193         GString *out;
194         unsigned int i;
195
196         DBG("Binary output from %s", pdata->pdo->di->inst_id);
197         op = cb_data;
198         pdb = pdata->data;
199
200         if (strcmp(pdata->pdo->di->inst_id, op->pd))
201                 /* This is not the PD selected for output. */
202                 return;
203
204         if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
205                 /*
206                  * This output takes a specific binary class,
207                  * but not the one that just came in.
208                  */
209                 return;
210
211         out = g_string_sized_new(128);
212         g_string_printf(out, "%"PRIu64"-%"PRIu64" %s:",
213                         pdata->start_sample, pdata->end_sample,
214                         pdata->pdo->di->inst_id);
215         for (i = 0; i < pdb->size; i++) {
216                 g_string_append_printf(out, " %.2x", pdb->data[i]);
217         }
218         g_string_append(out, "\n");
219         if (write(op->outfd, out->str, out->len) == -1)
220                 ERR("SRD_OUTPUT_BINARY callback write failure!");
221
222 }
223
224 static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
225 {
226         struct srd_decoder *dec;
227         struct srd_proto_data_annotation *pda;
228         struct output *op;
229         GString *line;
230         int i;
231         char **dec_ann;
232
233         DBG("Annotation output from %s", pdata->pdo->di->inst_id);
234         op = cb_data;
235         pda = pdata->data;
236         dec = pdata->pdo->di->decoder;
237         if (strcmp(pdata->pdo->di->inst_id, op->pd))
238                 /* This is not the PD selected for output. */
239                 return;
240
241         if (op->class_idx != -1 && op->class_idx != pda->ann_format)
242                 /*
243                  * This output takes a specific annotation class,
244                  * but not the one that just came in.
245                  */
246                 return;
247
248         dec_ann = g_slist_nth_data(dec->annotations, pda->ann_format);
249         line = g_string_sized_new(256);
250         g_string_printf(line, "%"PRIu64"-%"PRIu64" %s: %s:",
251                         pdata->start_sample, pdata->end_sample,
252                         pdata->pdo->di->inst_id, dec_ann[0]);
253         for (i = 0; pda->ann_text[i]; i++)
254                 g_string_append_printf(line, " \"%s\"", pda->ann_text[i]);
255         g_string_append(line, "\n");
256         if (write(op->outfd, line->str, line->len) == -1)
257                 ERR("SRD_OUTPUT_ANN callback write failure!");
258         g_string_free(line, TRUE);
259
260 }
261
262 static void sr_cb(const struct sr_dev_inst *sdi,
263                 const struct sr_datafeed_packet *packet, void *cb_data)
264 {
265         const struct sr_datafeed_logic *logic;
266         struct srd_session *sess;
267         GVariant *gvar;
268         uint64_t samplerate;
269         int num_samples;
270         static int samplecnt = 0;
271
272         sess = cb_data;
273
274         switch (packet->type) {
275         case SR_DF_HEADER:
276                 DBG("Received SR_DF_HEADER");
277                 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
278                                 &gvar) != SR_OK) {
279                         ERR("Getting samplerate failed");
280                         break;
281                 }
282                 samplerate = g_variant_get_uint64(gvar);
283                 g_variant_unref(gvar);
284                 if (srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE,
285                                 g_variant_new_uint64(samplerate)) != SRD_OK) {
286                         ERR("Setting samplerate failed");
287                         break;
288                 }
289                 if (srd_session_start(sess) != SRD_OK) {
290                         ERR("Session start failed");
291                         break;
292                 }
293                 break;
294         case SR_DF_LOGIC:
295                 logic = packet->payload;
296                 num_samples = logic->length / logic->unitsize;
297                 DBG("Received SR_DF_LOGIC: %d samples", num_samples);
298                 srd_session_send(sess, samplecnt, samplecnt + num_samples,
299                                 logic->data, logic->length);
300                 samplecnt += logic->length / logic->unitsize;
301                 break;
302         case SR_DF_END:
303                 DBG("Received SR_DF_END");
304                 break;
305         }
306
307 }
308
309 static int run_testcase(char *infile, GSList *pdlist, struct output *op)
310 {
311         struct srd_session *sess;
312         struct srd_decoder *dec;
313         struct srd_decoder_inst *di, *prev_di;
314         srd_pd_output_callback_t cb;
315         struct pd *pd;
316         struct probe *probe;
317         struct option *option;
318         GVariant *gvar;
319         GHashTable *probes, *opts;
320         GSList *pdl, *l;
321         int idx;
322         int max_probe;
323         char **decoder_class;
324
325         if (op->outfile) {
326                 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
327                         ERR("Unable to open %s for writing: %s", op->outfile,
328                                         strerror(errno));
329                         return FALSE;
330                 }
331         }
332
333         if (sr_session_load(infile) != SR_OK)
334                 return FALSE;
335
336         if (srd_session_new(&sess) != SRD_OK)
337                 return FALSE;
338         sr_session_datafeed_callback_add(sr_cb, sess);
339         switch (op->type) {
340         case SRD_OUTPUT_ANN:
341                 cb = srd_cb_ann;
342                 break;
343         case SRD_OUTPUT_BINARY:
344                 cb = srd_cb_bin;
345                 break;
346         case SRD_OUTPUT_PYTHON:
347                 cb = srd_cb_py;
348                 break;
349         default:
350                 return FALSE;
351         }
352         srd_pd_output_callback_add(sess, op->type, cb, op);
353
354         prev_di = NULL;
355         pd = NULL;
356         for (pdl = pdlist; pdl; pdl = pdl->next) {
357                 pd = pdl->data;
358                 if (srd_decoder_load(pd->name) != SRD_OK)
359                         return FALSE;
360
361                 /* Instantiate decoder and pass in options. */
362                 opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
363                                 (GDestroyNotify)g_variant_unref);
364                 for (l = pd->options; l; l = l->next) {
365                         option = l->data;
366                         g_hash_table_insert(opts, option->key, option->value);
367                 }
368                 if (!(di = srd_inst_new(sess, pd->name, opts)))
369                         return FALSE;
370                 g_hash_table_destroy(opts);
371
372                 /* Map probes. */
373                 if (pd->probes) {
374                         probes = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
375                                         (GDestroyNotify)g_variant_unref);
376                         max_probe = 0;
377                         for (l = pd->probes; l; l = l->next) {
378                                 probe = l->data;
379                                 if (probe->probe > max_probe)
380                                         max_probe = probe->probe;
381                                 gvar = g_variant_new_int32(probe->probe);
382                                 g_variant_ref_sink(gvar);
383                                 g_hash_table_insert(probes, probe->name, gvar);
384                         }
385                         if (srd_inst_probe_set_all(di, probes,
386                                         (max_probe + 8) / 8) != SRD_OK)
387                                 return FALSE;
388                         g_hash_table_destroy(probes);
389                 }
390
391                 /* If this is not the first decoder in the list, stack it
392                  * on top of the previous one. */
393                 if (prev_di) {
394                         if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
395                                 ERR("Failed to stack decoder instances.");
396                                 return FALSE;
397                         }
398                 }
399                 prev_di = di;
400         }
401
402         /* Resolve top decoder's class index, so we can match. */
403         dec = srd_decoder_get_by_id(pd->name);
404         if (op->class) {
405                 if (op->type == SRD_OUTPUT_ANN)
406                         l = dec->annotations;
407                 else if (op->type == SRD_OUTPUT_BINARY)
408                         l = dec->binary;
409                 else
410                         /* Only annotations and binary can have a class. */
411                         return FALSE;
412                 idx = 0;
413                 while (l) {
414                         decoder_class = l->data;
415                         if (!strcmp(decoder_class[0], op->class)) {
416                                 op->class_idx = idx;
417                                 break;
418                         } else
419                                 idx++;
420                         l = l->next;
421                 }
422                 if (op->class_idx == -1) {
423                         ERR("Output class '%s' not found in decoder %s.",
424                                         op->class, pd->name);
425                         return FALSE;
426                 } else
427                         DBG("Class %s index is %d", op->class, op->class_idx);
428         }
429
430         sr_session_start();
431         sr_session_run();
432         sr_session_stop();
433
434         srd_session_destroy(sess);
435
436         if (op->outfile)
437                 close(op->outfd);
438
439         return TRUE;
440 }
441
442 int main(int argc, char **argv)
443 {
444         struct sr_context *ctx;
445         GSList *pdlist;
446         struct pd *pd;
447         struct probe *probe;
448         struct option *option;
449         struct output *op;
450         int ret;
451         char c, *opt_infile, **kv, **opstr;
452
453         op = malloc(sizeof(struct output));
454         op->pd = NULL;
455         op->type = -1;
456         op->class = NULL;
457         op->class_idx = -1;
458         op->outfd = 1;
459
460         pdlist = NULL;
461         opt_infile = NULL;
462         pd = NULL;
463         while ((c = getopt(argc, argv, "dP:p:o:i:O:f:S")) != -1) {
464                 switch(c) {
465                 case 'd':
466                         debug = TRUE;
467                         break;
468                 case 'P':
469                         pd = g_malloc(sizeof(struct pd));
470                         pd->name = g_strdup(optarg);
471                         pd->probes = pd->options = NULL;
472                         pdlist = g_slist_append(pdlist, pd);
473                         break;
474                 case 'p':
475                 case 'o':
476                         if (g_slist_length(pdlist) == 0) {
477                                 /* No previous -P. */
478                                 ERR("Syntax error at '%s'", optarg);
479                                 usage(NULL);
480                         }
481                         kv = g_strsplit(optarg, "=", 0);
482                         if (!kv[0] || (!kv[1] || kv[2])) {
483                                 /* Need x=y. */
484                                 ERR("Syntax error at '%s'", optarg);
485                                 g_strfreev(kv);
486                                 usage(NULL);
487                         }
488                         if (c == 'p') {
489                                 probe = malloc(sizeof(struct probe));
490                                 probe->name = g_strdup(kv[0]);
491                                 probe->probe = strtoul(kv[1], 0, 10);
492                                 /* Apply to last PD. */
493                                 pd->probes = g_slist_append(pd->probes, probe);
494                         } else {
495                                 option = malloc(sizeof(struct option));
496                                 option->key = g_strdup(kv[0]);
497                                 option->value = g_strdup(kv[1]);
498                                 /* Apply to last PD. */
499                                 pd->options = g_slist_append(pd->options, option);
500                         }
501                         break;
502                 case 'i':
503                         opt_infile = optarg;
504                         break;
505                 case 'O':
506                         opstr = g_strsplit(optarg, ":", 0);
507                         if (!opstr[0] || !opstr[1]) {
508                                 /* Need at least abc:def. */
509                                 ERR("Syntax error at '%s'", optarg);
510                                 g_strfreev(opstr);
511                                 usage(NULL);
512                         }
513                         op->pd = g_strdup(opstr[0]);
514                         if (!strcmp(opstr[1], "annotation"))
515                                 op->type = SRD_OUTPUT_ANN;
516                         else if (!strcmp(opstr[1], "binary"))
517                                 op->type = SRD_OUTPUT_BINARY;
518                         else if (!strcmp(opstr[1], "python"))
519                                 op->type = SRD_OUTPUT_PYTHON;
520                         else {
521                                 ERR("Unknown output type '%s'", opstr[1]);
522                                 g_strfreev(opstr);
523                                 usage(NULL);
524                         }
525                         if (opstr[2])
526                                 op->class = g_strdup(opstr[2]);
527                         g_strfreev(opstr);
528                         break;
529                 case 'f':
530                         op->outfile = g_strdup(optarg);
531                         op->outfd = -1;
532                         break;
533                 case 'S':
534                         statistics = TRUE;
535                         break;
536                 default:
537                         usage(NULL);
538                 }
539         }
540         if (argc > optind)
541                 usage(NULL);
542         if (g_slist_length(pdlist) == 0)
543                 usage(NULL);
544         if (!opt_infile)
545                 usage(NULL);
546         if (!op->pd || op->type == -1)
547                 usage(NULL);
548
549         sr_log_callback_set(sr_log, NULL);
550         if (sr_init(&ctx) != SR_OK)
551                 return 1;
552
553         srd_log_callback_set(srd_log, NULL);
554         if (srd_init(DECODERS_DIR) != SRD_OK)
555                 return 1;
556
557         ret = 0;
558         if (!run_testcase(opt_infile, pdlist, op))
559                 ret = 1;
560
561         srd_exit();
562         sr_exit(ctx);
563
564         return ret;
565 }