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