]> sigrok.org Git - libsigrok.git/blob - src/hardware/demo/demo.c
demo: Use simple timer source instead of pipe
[libsigrok.git] / src / hardware / demo / demo.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2011 Olivier Fauchon <olivier@aixmarseille.com>
6  * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
7  * Copyright (C) 2015 Bartosz Golaszewski <bgolaszewski@baylibre.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
22  */
23
24 #include <stdlib.h>
25 #include <string.h>
26 #include <math.h>
27 #include <libsigrok/libsigrok.h>
28 #include "libsigrok-internal.h"
29
30 #define LOG_PREFIX "demo"
31
32 #define DEFAULT_NUM_LOGIC_CHANNELS     8
33 #define DEFAULT_NUM_ANALOG_CHANNELS    4
34
35 /* The size in bytes of chunks to send through the session bus. */
36 #define LOGIC_BUFSIZE        4096
37 /* Size of the analog pattern space per channel. */
38 #define ANALOG_BUFSIZE       4096
39
40 #define DEFAULT_ANALOG_AMPLITUDE 25
41 #define ANALOG_SAMPLES_PER_PERIOD 20
42
43 /* Logic patterns we can generate. */
44 enum {
45         /**
46          * Spells "sigrok" across 8 channels using '0's (with '1's as
47          * "background") when displayed using the 'bits' output format.
48          * The pattern is repeated every 8 channels, shifted to the right
49          * in time by one bit.
50          */
51         PATTERN_SIGROK,
52
53         /** Pseudo-random values on all channels. */
54         PATTERN_RANDOM,
55
56         /**
57          * Incrementing number across 8 channels. The pattern is repeated
58          * every 8 channels, shifted to the right in time by one bit.
59          */
60         PATTERN_INC,
61
62         /** All channels have a low logic state. */
63         PATTERN_ALL_LOW,
64
65         /** All channels have a high logic state. */
66         PATTERN_ALL_HIGH,
67 };
68
69 /* Analog patterns we can generate. */
70 enum {
71         /**
72          * Square wave.
73          */
74         PATTERN_SQUARE,
75         PATTERN_SINE,
76         PATTERN_TRIANGLE,
77         PATTERN_SAWTOOTH,
78 };
79
80 static const char *logic_pattern_str[] = {
81         "sigrok",
82         "random",
83         "incremental",
84         "all-low",
85         "all-high",
86 };
87
88 static const char *analog_pattern_str[] = {
89         "square",
90         "sine",
91         "triangle",
92         "sawtooth",
93 };
94
95 struct analog_gen {
96         int pattern;
97         float amplitude;
98         float pattern_data[ANALOG_BUFSIZE];
99         unsigned int num_samples;
100         struct sr_datafeed_analog packet;
101         float avg_val; /* Average value */
102         unsigned num_avgs; /* Number of samples averaged */
103 };
104
105 /* Private, per-device-instance driver context. */
106 struct dev_context {
107         uint64_t cur_samplerate;
108         gboolean continuous;
109         uint64_t limit_samples;
110         uint64_t limit_msec;
111         uint64_t logic_counter;
112         uint64_t analog_counter;
113         int64_t starttime;
114         uint64_t step;
115         /* Logic */
116         int32_t num_logic_channels;
117         unsigned int logic_unitsize;
118         /* There is only ever one logic channel group, so its pattern goes here. */
119         uint8_t logic_pattern;
120         unsigned char logic_data[LOGIC_BUFSIZE];
121         /* Analog */
122         int32_t num_analog_channels;
123         GHashTable *ch_ag;
124         gboolean avg; /* True if averaging is enabled */
125         uint64_t avg_samples;
126 };
127
128 static const uint32_t drvopts[] = {
129         SR_CONF_DEMO_DEV,
130         SR_CONF_LOGIC_ANALYZER,
131         SR_CONF_OSCILLOSCOPE,
132 };
133
134 static const uint32_t scanopts[] = {
135         SR_CONF_NUM_LOGIC_CHANNELS,
136         SR_CONF_NUM_ANALOG_CHANNELS,
137 };
138
139 static const uint32_t devopts[] = {
140         SR_CONF_CONTINUOUS | SR_CONF_SET,
141         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
142         SR_CONF_LIMIT_MSEC | SR_CONF_GET | SR_CONF_SET,
143         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
144         SR_CONF_AVERAGING | SR_CONF_GET | SR_CONF_SET,
145         SR_CONF_AVG_SAMPLES | SR_CONF_GET | SR_CONF_SET,
146 };
147
148 static const uint32_t devopts_cg_logic[] = {
149         SR_CONF_PATTERN_MODE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
150 };
151
152 static const uint32_t devopts_cg_analog_group[] = {
153         SR_CONF_AMPLITUDE | SR_CONF_GET | SR_CONF_SET,
154 };
155
156 static const uint32_t devopts_cg_analog_channel[] = {
157         SR_CONF_PATTERN_MODE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
158         SR_CONF_AMPLITUDE | SR_CONF_GET | SR_CONF_SET,
159 };
160
161 static const uint64_t samplerates[] = {
162         SR_HZ(1),
163         SR_GHZ(1),
164         SR_HZ(1),
165 };
166
167 static const uint8_t pattern_sigrok[] = {
168         0x4c, 0x92, 0x92, 0x92, 0x64, 0x00, 0x00, 0x00,
169         0x82, 0xfe, 0xfe, 0x82, 0x00, 0x00, 0x00, 0x00,
170         0x7c, 0x82, 0x82, 0x92, 0x74, 0x00, 0x00, 0x00,
171         0xfe, 0x12, 0x12, 0x32, 0xcc, 0x00, 0x00, 0x00,
172         0x7c, 0x82, 0x82, 0x82, 0x7c, 0x00, 0x00, 0x00,
173         0xfe, 0x10, 0x28, 0x44, 0x82, 0x00, 0x00, 0x00,
174         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
175         0xbe, 0xbe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
176 };
177
178 SR_PRIV struct sr_dev_driver demo_driver_info;
179
180 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data);
181
182 static int init(struct sr_dev_driver *di, struct sr_context *sr_ctx)
183 {
184         return std_init(sr_ctx, di, LOG_PREFIX);
185 }
186
187 static void generate_analog_pattern(struct analog_gen *ag, uint64_t sample_rate)
188 {
189         double t, frequency;
190         float value;
191         unsigned int num_samples, i;
192         int last_end;
193
194         sr_dbg("Generating %s pattern.", analog_pattern_str[ag->pattern]);
195
196         num_samples = ANALOG_BUFSIZE / sizeof(float);
197
198         switch (ag->pattern) {
199         case PATTERN_SQUARE:
200                 value = ag->amplitude;
201                 last_end = 0;
202                 for (i = 0; i < num_samples; i++) {
203                         if (i % 5 == 0)
204                                 value = -value;
205                         if (i % 10 == 0)
206                                 last_end = i;
207                         ag->pattern_data[i] = value;
208                 }
209                 ag->num_samples = last_end;
210                 break;
211         case PATTERN_SINE:
212                 frequency = (double) sample_rate / ANALOG_SAMPLES_PER_PERIOD;
213
214                 /* Make sure the number of samples we put out is an integer
215                  * multiple of our period size */
216                 /* FIXME we actually need only one period. A ringbuffer would be
217                  * useful here. */
218                 while (num_samples % ANALOG_SAMPLES_PER_PERIOD != 0)
219                         num_samples--;
220
221                 for (i = 0; i < num_samples; i++) {
222                         t = (double) i / (double) sample_rate;
223                         ag->pattern_data[i] = ag->amplitude *
224                                                 sin(2 * G_PI * frequency * t);
225                 }
226
227                 ag->num_samples = num_samples;
228                 break;
229         case PATTERN_TRIANGLE:
230                 frequency = (double) sample_rate / ANALOG_SAMPLES_PER_PERIOD;
231
232                 while (num_samples % ANALOG_SAMPLES_PER_PERIOD != 0)
233                         num_samples--;
234
235                 for (i = 0; i < num_samples; i++) {
236                         t = (double) i / (double) sample_rate;
237                         ag->pattern_data[i] = (2 * ag->amplitude / G_PI) *
238                                                 asin(sin(2 * G_PI * frequency * t));
239                 }
240
241                 ag->num_samples = num_samples;
242                 break;
243         case PATTERN_SAWTOOTH:
244                 frequency = (double) sample_rate / ANALOG_SAMPLES_PER_PERIOD;
245
246                 while (num_samples % ANALOG_SAMPLES_PER_PERIOD != 0)
247                         num_samples--;
248
249                 for (i = 0; i < num_samples; i++) {
250                         t = (double) i / (double) sample_rate;
251                         ag->pattern_data[i] = 2 * ag->amplitude *
252                                                 ((t * frequency) - floor(0.5f + t * frequency));
253                 }
254
255                 ag->num_samples = num_samples;
256                 break;
257         }
258 }
259
260 static GSList *scan(struct sr_dev_driver *di, GSList *options)
261 {
262         struct drv_context *drvc;
263         struct dev_context *devc;
264         struct sr_dev_inst *sdi;
265         struct sr_channel *ch;
266         struct sr_channel_group *cg, *acg;
267         struct sr_config *src;
268         struct analog_gen *ag;
269         GSList *devices, *l;
270         int num_logic_channels, num_analog_channels, pattern, i;
271         char channel_name[16];
272
273         drvc = di->context;
274
275         num_logic_channels = DEFAULT_NUM_LOGIC_CHANNELS;
276         num_analog_channels = DEFAULT_NUM_ANALOG_CHANNELS;
277         for (l = options; l; l = l->next) {
278                 src = l->data;
279                 switch (src->key) {
280                 case SR_CONF_NUM_LOGIC_CHANNELS:
281                         num_logic_channels = g_variant_get_int32(src->data);
282                         break;
283                 case SR_CONF_NUM_ANALOG_CHANNELS:
284                         num_analog_channels = g_variant_get_int32(src->data);
285                         break;
286                 }
287         }
288
289         devices = NULL;
290
291         sdi = g_malloc0(sizeof(struct sr_dev_inst));
292         sdi->status = SR_ST_ACTIVE;
293         sdi->model = g_strdup("Demo device");
294         sdi->driver = di;
295
296         devc = g_malloc(sizeof(struct dev_context));
297         devc->cur_samplerate = SR_KHZ(200);
298         devc->limit_samples = 0;
299         devc->limit_msec = 0;
300         devc->step = 0;
301         devc->continuous = FALSE;
302         devc->num_logic_channels = num_logic_channels;
303         devc->logic_unitsize = (devc->num_logic_channels + 7) / 8;
304         devc->logic_pattern = PATTERN_SIGROK;
305         devc->num_analog_channels = num_analog_channels;
306         devc->avg = FALSE;
307         devc->avg_samples = 0;
308
309         /* Logic channels, all in one channel group. */
310         cg = g_malloc0(sizeof(struct sr_channel_group));
311         cg->name = g_strdup("Logic");
312         for (i = 0; i < num_logic_channels; i++) {
313                 sprintf(channel_name, "D%d", i);
314                 ch = sr_channel_new(sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name);
315                 cg->channels = g_slist_append(cg->channels, ch);
316         }
317         sdi->channel_groups = g_slist_append(NULL, cg);
318
319         /* Analog channels, channel groups and pattern generators. */
320         pattern = 0;
321         /* An "Analog" channel group with all analog channels in it. */
322         acg = g_malloc0(sizeof(struct sr_channel_group));
323         acg->name = g_strdup("Analog");
324         sdi->channel_groups = g_slist_append(sdi->channel_groups, acg);
325
326         devc->ch_ag = g_hash_table_new(g_direct_hash, g_direct_equal);
327         for (i = 0; i < num_analog_channels; i++) {
328                 snprintf(channel_name, 16, "A%d", i);
329                 ch = sr_channel_new(sdi, i + num_logic_channels, SR_CHANNEL_ANALOG,
330                                 TRUE, channel_name);
331                 acg->channels = g_slist_append(acg->channels, ch);
332
333                 /* Every analog channel gets its own channel group as well. */
334                 cg = g_malloc0(sizeof(struct sr_channel_group));
335                 cg->name = g_strdup(channel_name);
336                 cg->channels = g_slist_append(NULL, ch);
337                 sdi->channel_groups = g_slist_append(sdi->channel_groups, cg);
338
339                 /* Every channel gets a generator struct. */
340                 ag = g_malloc(sizeof(struct analog_gen));
341                 ag->amplitude = DEFAULT_ANALOG_AMPLITUDE;
342                 ag->packet.channels = cg->channels;
343                 ag->packet.mq = 0;
344                 ag->packet.mqflags = 0;
345                 ag->packet.unit = SR_UNIT_VOLT;
346                 ag->packet.data = ag->pattern_data;
347                 ag->pattern = pattern;
348                 ag->avg_val = 0.0f;
349                 ag->num_avgs = 0;
350                 g_hash_table_insert(devc->ch_ag, ch, ag);
351
352                 if (++pattern == ARRAY_SIZE(analog_pattern_str))
353                         pattern = 0;
354         }
355
356         sdi->priv = devc;
357         devices = g_slist_append(devices, sdi);
358         drvc->instances = g_slist_append(drvc->instances, sdi);
359
360         return devices;
361 }
362
363 static GSList *dev_list(const struct sr_dev_driver *di)
364 {
365         return ((struct drv_context *)(di->context))->instances;
366 }
367
368 static int dev_open(struct sr_dev_inst *sdi)
369 {
370         sdi->status = SR_ST_ACTIVE;
371
372         return SR_OK;
373 }
374
375 static int dev_close(struct sr_dev_inst *sdi)
376 {
377         sdi->status = SR_ST_INACTIVE;
378
379         return SR_OK;
380 }
381
382 static void clear_helper(void *priv)
383 {
384         struct dev_context *devc;
385         GHashTableIter iter;
386         void *value;
387
388         devc = priv;
389
390         /* Analog generators. */
391         g_hash_table_iter_init(&iter, devc->ch_ag);
392         while (g_hash_table_iter_next(&iter, NULL, &value))
393                 g_free(value);
394         g_hash_table_unref(devc->ch_ag);
395         g_free(devc);
396 }
397
398 static int cleanup(const struct sr_dev_driver *di)
399 {
400         return std_dev_clear(di, clear_helper);
401 }
402
403 static int config_get(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
404                 const struct sr_channel_group *cg)
405 {
406         struct dev_context *devc;
407         struct sr_channel *ch;
408         struct analog_gen *ag;
409         int pattern;
410
411         if (!sdi)
412                 return SR_ERR_ARG;
413
414         devc = sdi->priv;
415         switch (key) {
416         case SR_CONF_SAMPLERATE:
417                 *data = g_variant_new_uint64(devc->cur_samplerate);
418                 break;
419         case SR_CONF_LIMIT_SAMPLES:
420                 *data = g_variant_new_uint64(devc->limit_samples);
421                 break;
422         case SR_CONF_LIMIT_MSEC:
423                 *data = g_variant_new_uint64(devc->limit_msec);
424                 break;
425         case SR_CONF_AVERAGING:
426                 *data = g_variant_new_boolean(devc->avg);
427                 break;
428         case SR_CONF_AVG_SAMPLES:
429                 *data = g_variant_new_uint64(devc->avg_samples);
430                 break;
431         case SR_CONF_PATTERN_MODE:
432                 if (!cg)
433                         return SR_ERR_CHANNEL_GROUP;
434                 /* Any channel in the group will do. */
435                 ch = cg->channels->data;
436                 if (ch->type == SR_CHANNEL_LOGIC) {
437                         pattern = devc->logic_pattern;
438                         *data = g_variant_new_string(logic_pattern_str[pattern]);
439                 } else if (ch->type == SR_CHANNEL_ANALOG) {
440                         ag = g_hash_table_lookup(devc->ch_ag, ch);
441                         pattern = ag->pattern;
442                         *data = g_variant_new_string(analog_pattern_str[pattern]);
443                 } else
444                         return SR_ERR_BUG;
445                 break;
446         case SR_CONF_AMPLITUDE:
447                 if (!cg)
448                         return SR_ERR_CHANNEL_GROUP;
449                 /* Any channel in the group will do. */
450                 ch = cg->channels->data;
451                 if (ch->type != SR_CHANNEL_ANALOG)
452                         return SR_ERR_ARG;
453                 ag = g_hash_table_lookup(devc->ch_ag, ch);
454                 *data = g_variant_new_double(ag->amplitude);
455                 break;
456         default:
457                 return SR_ERR_NA;
458         }
459
460         return SR_OK;
461 }
462
463 static int config_set(uint32_t key, GVariant *data, const struct sr_dev_inst *sdi,
464                 const struct sr_channel_group *cg)
465 {
466         struct dev_context *devc;
467         struct analog_gen *ag;
468         struct sr_channel *ch;
469         GSList *l;
470         int logic_pattern, analog_pattern, ret;
471         unsigned int i;
472         const char *stropt;
473
474         devc = sdi->priv;
475
476         if (sdi->status != SR_ST_ACTIVE)
477                 return SR_ERR_DEV_CLOSED;
478
479         ret = SR_OK;
480         switch (key) {
481         case SR_CONF_SAMPLERATE:
482                 devc->cur_samplerate = g_variant_get_uint64(data);
483                 break;
484         case SR_CONF_LIMIT_SAMPLES:
485                 devc->limit_msec = 0;
486                 devc->limit_samples = g_variant_get_uint64(data);
487                 break;
488         case SR_CONF_LIMIT_MSEC:
489                 devc->limit_msec = g_variant_get_uint64(data);
490                 devc->limit_samples = 0;
491                 break;
492         case SR_CONF_AVERAGING:
493                 devc->avg = g_variant_get_boolean(data);
494                 sr_dbg("%s averaging", devc->avg ? "Enabling" : "Disabling");
495                 break;
496         case SR_CONF_AVG_SAMPLES:
497                 devc->avg_samples = g_variant_get_uint64(data);
498                 sr_dbg("Setting averaging rate to %" PRIu64, devc->avg_samples);
499                 break;
500         case SR_CONF_PATTERN_MODE:
501                 if (!cg)
502                         return SR_ERR_CHANNEL_GROUP;
503                 stropt = g_variant_get_string(data, NULL);
504                 logic_pattern = analog_pattern = -1;
505                 for (i = 0; i < ARRAY_SIZE(logic_pattern_str); i++) {
506                         if (!strcmp(stropt, logic_pattern_str[i])) {
507                                 logic_pattern = i;
508                                 break;
509                         }
510                 }
511                 for (i = 0; i < ARRAY_SIZE(analog_pattern_str); i++) {
512                         if (!strcmp(stropt, analog_pattern_str[i])) {
513                                 analog_pattern = i;
514                                 break;
515                         }
516                 }
517                 if (logic_pattern == -1 && analog_pattern == -1)
518                         return SR_ERR_ARG;
519                 for (l = cg->channels; l; l = l->next) {
520                         ch = l->data;
521                         if (ch->type == SR_CHANNEL_LOGIC) {
522                                 if (logic_pattern == -1)
523                                         return SR_ERR_ARG;
524                                 sr_dbg("Setting logic pattern to %s",
525                                                 logic_pattern_str[logic_pattern]);
526                                 devc->logic_pattern = logic_pattern;
527                                 /* Might as well do this now, these are static. */
528                                 if (logic_pattern == PATTERN_ALL_LOW)
529                                         memset(devc->logic_data, 0x00, LOGIC_BUFSIZE);
530                                 else if (logic_pattern == PATTERN_ALL_HIGH)
531                                         memset(devc->logic_data, 0xff, LOGIC_BUFSIZE);
532                         } else if (ch->type == SR_CHANNEL_ANALOG) {
533                                 if (analog_pattern == -1)
534                                         return SR_ERR_ARG;
535                                 sr_dbg("Setting analog pattern for channel %s to %s",
536                                                 ch->name, analog_pattern_str[analog_pattern]);
537                                 ag = g_hash_table_lookup(devc->ch_ag, ch);
538                                 ag->pattern = analog_pattern;
539                         } else
540                                 return SR_ERR_BUG;
541                 }
542                 break;
543         case SR_CONF_AMPLITUDE:
544                 if (!cg)
545                         return SR_ERR_CHANNEL_GROUP;
546                 for (l = cg->channels; l; l = l->next) {
547                         ch = l->data;
548                         if (ch->type != SR_CHANNEL_ANALOG)
549                                 return SR_ERR_ARG;
550                         ag = g_hash_table_lookup(devc->ch_ag, ch);
551                         ag->amplitude = g_variant_get_double(data);
552                 }
553                 break;
554         default:
555                 ret = SR_ERR_NA;
556         }
557
558         return ret;
559 }
560
561 static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
562                 const struct sr_channel_group *cg)
563 {
564         struct sr_channel *ch;
565         GVariant *gvar;
566         GVariantBuilder gvb;
567
568         if (key == SR_CONF_SCAN_OPTIONS) {
569                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
570                                 scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t));
571                 return SR_OK;
572         }
573
574         if (key == SR_CONF_DEVICE_OPTIONS && !sdi) {
575                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
576                                 drvopts, ARRAY_SIZE(drvopts), sizeof(uint32_t));
577                 return SR_OK;
578         }
579
580         if (!sdi)
581                 return SR_ERR_ARG;
582
583         if (!cg) {
584                 switch (key) {
585                 case SR_CONF_DEVICE_OPTIONS:
586                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
587                                         devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
588                         break;
589                 case SR_CONF_SAMPLERATE:
590                         g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
591                         gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"), samplerates,
592                                         ARRAY_SIZE(samplerates), sizeof(uint64_t));
593                         g_variant_builder_add(&gvb, "{sv}", "samplerate-steps", gvar);
594                         *data = g_variant_builder_end(&gvb);
595                         break;
596                 default:
597                         return SR_ERR_NA;
598                 }
599         } else {
600                 ch = cg->channels->data;
601                 switch (key) {
602                 case SR_CONF_DEVICE_OPTIONS:
603                         if (ch->type == SR_CHANNEL_LOGIC)
604                                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
605                                                 devopts_cg_logic, ARRAY_SIZE(devopts_cg_logic),
606                                                 sizeof(uint32_t));
607                         else if (ch->type == SR_CHANNEL_ANALOG) {
608                                 if (strcmp(cg->name, "Analog") == 0)
609                                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
610                                                         devopts_cg_analog_group, ARRAY_SIZE(devopts_cg_analog_group),
611                                                         sizeof(uint32_t));
612                                 else
613                                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
614                                                         devopts_cg_analog_channel, ARRAY_SIZE(devopts_cg_analog_channel),
615                                                         sizeof(uint32_t));
616                         }
617                         else
618                                 return SR_ERR_BUG;
619                         break;
620                 case SR_CONF_PATTERN_MODE:
621                         /* The analog group (with all 4 channels) shall not have a pattern property. */
622                         if (strcmp(cg->name, "Analog") == 0)
623                                 return SR_ERR_NA;
624
625                         if (ch->type == SR_CHANNEL_LOGIC)
626                                 *data = g_variant_new_strv(logic_pattern_str,
627                                                 ARRAY_SIZE(logic_pattern_str));
628                         else if (ch->type == SR_CHANNEL_ANALOG)
629                                 *data = g_variant_new_strv(analog_pattern_str,
630                                                 ARRAY_SIZE(analog_pattern_str));
631                         else
632                                 return SR_ERR_BUG;
633                         break;
634                 default:
635                         return SR_ERR_NA;
636                 }
637         }
638
639         return SR_OK;
640 }
641
642 static void logic_generator(struct sr_dev_inst *sdi, uint64_t size)
643 {
644         struct dev_context *devc;
645         uint64_t i, j;
646         uint8_t pat;
647
648         devc = sdi->priv;
649
650         switch (devc->logic_pattern) {
651         case PATTERN_SIGROK:
652                 memset(devc->logic_data, 0x00, size);
653                 for (i = 0; i < size; i += devc->logic_unitsize) {
654                         for (j = 0; j < devc->logic_unitsize; j++) {
655                                 pat = pattern_sigrok[(devc->step + j) % sizeof(pattern_sigrok)] >> 1;
656                                 devc->logic_data[i + j] = ~pat;
657                         }
658                         devc->step++;
659                 }
660                 break;
661         case PATTERN_RANDOM:
662                 for (i = 0; i < size; i++)
663                         devc->logic_data[i] = (uint8_t)(rand() & 0xff);
664                 break;
665         case PATTERN_INC:
666                 for (i = 0; i < size; i++) {
667                         for (j = 0; j < devc->logic_unitsize; j++) {
668                                 devc->logic_data[i + j] = devc->step;
669                         }
670                         devc->step++;
671                 }
672                 break;
673         case PATTERN_ALL_LOW:
674         case PATTERN_ALL_HIGH:
675                 /* These were set when the pattern mode was selected. */
676                 break;
677         default:
678                 sr_err("Unknown pattern: %d.", devc->logic_pattern);
679                 break;
680         }
681 }
682
683 static void send_analog_packet(struct analog_gen *ag,
684                                struct sr_dev_inst *sdi,
685                                uint64_t *analog_sent,
686                                uint64_t analog_todo)
687 {
688         struct sr_datafeed_packet packet;
689         struct dev_context *devc;
690         uint64_t sending_now, to_avg;
691         int ag_pattern_pos;
692         unsigned int i;
693
694         devc = sdi->priv;
695         packet.type = SR_DF_ANALOG;
696         packet.payload = &ag->packet;
697
698         if (!devc->avg) {
699                 ag_pattern_pos = devc->analog_counter % ag->num_samples;
700                 sending_now = MIN(analog_todo, ag->num_samples-ag_pattern_pos);
701                 ag->packet.data = ag->pattern_data + ag_pattern_pos;
702                 ag->packet.num_samples = sending_now;
703                 sr_session_send(sdi, &packet);
704
705                 /* Whichever channel group gets there first. */
706                 *analog_sent = MAX(*analog_sent, sending_now);
707         } else {
708                 ag_pattern_pos = devc->analog_counter % ag->num_samples;
709                 to_avg = MIN(analog_todo, ag->num_samples-ag_pattern_pos);
710
711                 for (i = 0; i < to_avg; i++) {
712                         ag->avg_val = (ag->avg_val +
713                                         *(ag->pattern_data +
714                                           ag_pattern_pos + i)) / 2;
715                         ag->num_avgs++;
716                         /* Time to send averaged data? */
717                         if (devc->avg_samples > 0 &&
718                             ag->num_avgs >= devc->avg_samples)
719                                 goto do_send;
720                 }
721
722                 if (devc->avg_samples == 0) {
723                         /* We're averaging all the samples, so wait with
724                          * sending until the very end.
725                          */
726                         *analog_sent = ag->num_avgs;
727                         return;
728                 }
729
730 do_send:
731                 ag->packet.data = &ag->avg_val;
732                 ag->packet.num_samples = 1;
733
734                 sr_session_send(sdi, &packet);
735                 *analog_sent = ag->num_avgs;
736
737                 ag->num_avgs = 0;
738                 ag->avg_val = 0.0f;
739         }
740 }
741
742 /* Callback handling data */
743 static int prepare_data(int fd, int revents, void *cb_data)
744 {
745         struct sr_dev_inst *sdi;
746         struct dev_context *devc;
747         struct sr_datafeed_packet packet;
748         struct sr_datafeed_logic logic;
749         struct analog_gen *ag;
750         GHashTableIter iter;
751         void *value;
752         uint64_t logic_todo, analog_todo, expected_samplenum, analog_sent, sending_now;
753         int64_t time, elapsed;
754
755         (void)fd;
756         (void)revents;
757
758         sdi = cb_data;
759         devc = sdi->priv;
760         logic_todo = analog_todo = 0;
761
762         /* How many samples should we have sent by now? */
763         time = g_get_monotonic_time();
764         elapsed = time - devc->starttime;
765         expected_samplenum = elapsed * devc->cur_samplerate / (1000 * 1000);
766
767         /* But never more than the limit, if there is one. */
768         if (!devc->continuous)
769                 expected_samplenum = MIN(expected_samplenum, devc->limit_samples);
770
771         /* Of those, how many do we still have to send? */
772         if (devc->num_logic_channels && (devc->logic_counter < devc->limit_samples))
773                 logic_todo = expected_samplenum - devc->logic_counter;
774         if (devc->num_analog_channels && (devc->analog_counter < devc->limit_samples))
775                 analog_todo = expected_samplenum - devc->analog_counter;
776
777         while (logic_todo || analog_todo) {
778                 /* Logic */
779                 if (logic_todo > 0) {
780                         sending_now = MIN(logic_todo, LOGIC_BUFSIZE / devc->logic_unitsize);
781                         logic_generator(sdi, sending_now * devc->logic_unitsize);
782                         packet.type = SR_DF_LOGIC;
783                         packet.payload = &logic;
784                         logic.length = sending_now * devc->logic_unitsize;
785                         logic.unitsize = devc->logic_unitsize;
786                         logic.data = devc->logic_data;
787                         sr_session_send(sdi, &packet);
788                         logic_todo -= sending_now;
789                         devc->logic_counter += sending_now;
790                 }
791
792                 /* Analog, one channel at a time */
793                 if (analog_todo > 0) {
794                         analog_sent = 0;
795
796                         g_hash_table_iter_init(&iter, devc->ch_ag);
797                         while (g_hash_table_iter_next(&iter, NULL, &value)) {
798                                 send_analog_packet(value, sdi,
799                                                    &analog_sent, analog_todo);
800                         }
801                         analog_todo -= analog_sent;
802                         devc->analog_counter += analog_sent;
803                 }
804         }
805
806         if (!devc->continuous
807                         && (!devc->num_logic_channels || devc->logic_counter >= devc->limit_samples)
808                         && (!devc->num_analog_channels || devc->analog_counter >= devc->limit_samples)) {
809                 /* If we're averaging everything - now is the time to send data */
810                 if (devc->avg_samples == 0) {
811                         g_hash_table_iter_init(&iter, devc->ch_ag);
812                         while (g_hash_table_iter_next(&iter, NULL, &value)) {
813                                 ag = value;
814                                 packet.type = SR_DF_ANALOG;
815                                 packet.payload = &ag->packet;
816                                 ag->packet.data = &ag->avg_val;
817                                 ag->packet.num_samples = 1;
818                                 sr_session_send(sdi, &packet);
819                         }
820                 }
821
822                 sr_dbg("Requested number of samples reached.");
823                 dev_acquisition_stop(sdi, cb_data);
824                 return TRUE;
825         }
826
827         return TRUE;
828 }
829
830 static int dev_acquisition_start(const struct sr_dev_inst *sdi, void *cb_data)
831 {
832         struct dev_context *devc;
833         GHashTableIter iter;
834         void *value;
835
836         (void)cb_data;
837
838         if (sdi->status != SR_ST_ACTIVE)
839                 return SR_ERR_DEV_CLOSED;
840
841         devc = sdi->priv;
842         devc->continuous = !devc->limit_samples;
843         devc->logic_counter = devc->analog_counter = 0;
844
845         g_hash_table_iter_init(&iter, devc->ch_ag);
846         while (g_hash_table_iter_next(&iter, NULL, &value))
847                 generate_analog_pattern(value, devc->cur_samplerate);
848
849         sr_session_source_add(sdi->session, -1, 0, 40, prepare_data, (void *)sdi);
850
851         /* Send header packet to the session bus. */
852         std_session_send_df_header(sdi, LOG_PREFIX);
853
854         /* We use this timestamp to decide how many more samples to send. */
855         devc->starttime = g_get_monotonic_time();
856
857         return SR_OK;
858 }
859
860 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
861 {
862         struct sr_datafeed_packet packet;
863
864         (void)cb_data;
865
866         sr_dbg("Stopping acquisition.");
867
868         sr_session_source_remove(sdi->session, -1);
869
870         /* Send last packet. */
871         packet.type = SR_DF_END;
872         sr_session_send(sdi, &packet);
873
874         return SR_OK;
875 }
876
877 SR_PRIV struct sr_dev_driver demo_driver_info = {
878         .name = "demo",
879         .longname = "Demo driver and pattern generator",
880         .api_version = 1,
881         .init = init,
882         .cleanup = cleanup,
883         .scan = scan,
884         .dev_list = dev_list,
885         .dev_clear = NULL,
886         .config_get = config_get,
887         .config_set = config_set,
888         .config_list = config_list,
889         .dev_open = dev_open,
890         .dev_close = dev_close,
891         .dev_acquisition_start = dev_acquisition_start,
892         .dev_acquisition_stop = dev_acquisition_stop,
893         .context = NULL,
894 };