]> sigrok.org Git - libsigrok.git/blob - src/hardware/hameg-hmo/protocol.c
hameg-hmo: Add SR_CONF_LIMIT_SAMPLES support.
[libsigrok.git] / src / hardware / hameg-hmo / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 poljar (Damir Jelić) <poljarinho@gmail.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 <config.h>
21 #include <math.h>
22 #include <stdlib.h>
23 #include "scpi.h"
24 #include "protocol.h"
25
26 SR_PRIV void hmo_queue_logic_data(struct dev_context *devc,
27                                   size_t group, GByteArray *pod_data);
28 SR_PRIV void hmo_send_logic_packet(struct sr_dev_inst *sdi,
29                                    struct dev_context *devc);
30 SR_PRIV void hmo_cleanup_logic_data(struct dev_context *devc);
31
32 static const char *hameg_scpi_dialect[] = {
33         [SCPI_CMD_GET_DIG_DATA]             = ":FORM UINT,8;:POD%d:DATA?",
34         [SCPI_CMD_GET_TIMEBASE]             = ":TIM:SCAL?",
35         [SCPI_CMD_SET_TIMEBASE]             = ":TIM:SCAL %s",
36         [SCPI_CMD_GET_COUPLING]             = ":CHAN%d:COUP?",
37         [SCPI_CMD_SET_COUPLING]             = ":CHAN%d:COUP %s",
38         [SCPI_CMD_GET_SAMPLE_RATE]          = ":ACQ:SRAT?",
39         [SCPI_CMD_GET_SAMPLE_RATE_LIVE]     = ":%s:DATA:POINTS?",
40         [SCPI_CMD_GET_ANALOG_DATA]          = ":FORM:BORD %s;" \
41                                               ":FORM REAL,32;:CHAN%d:DATA?",
42         [SCPI_CMD_GET_VERTICAL_DIV]         = ":CHAN%d:SCAL?",
43         [SCPI_CMD_SET_VERTICAL_DIV]         = ":CHAN%d:SCAL %s",
44         [SCPI_CMD_GET_DIG_POD_STATE]        = ":POD%d:STAT?",
45         [SCPI_CMD_SET_DIG_POD_STATE]        = ":POD%d:STAT %d",
46         [SCPI_CMD_GET_TRIGGER_SLOPE]        = ":TRIG:A:EDGE:SLOP?",
47         [SCPI_CMD_SET_TRIGGER_SLOPE]        = ":TRIG:A:EDGE:SLOP %s",
48         [SCPI_CMD_GET_TRIGGER_SOURCE]       = ":TRIG:A:SOUR?",
49         [SCPI_CMD_SET_TRIGGER_SOURCE]       = ":TRIG:A:SOUR %s",
50         [SCPI_CMD_GET_DIG_CHAN_STATE]       = ":LOG%d:STAT?",
51         [SCPI_CMD_SET_DIG_CHAN_STATE]       = ":LOG%d:STAT %d",
52         [SCPI_CMD_GET_VERTICAL_OFFSET]      = ":CHAN%d:POS?",
53         [SCPI_CMD_GET_HORIZ_TRIGGERPOS]     = ":TIM:POS?",
54         [SCPI_CMD_SET_HORIZ_TRIGGERPOS]     = ":TIM:POS %s",
55         [SCPI_CMD_GET_ANALOG_CHAN_STATE]    = ":CHAN%d:STAT?",
56         [SCPI_CMD_SET_ANALOG_CHAN_STATE]    = ":CHAN%d:STAT %d",
57         [SCPI_CMD_GET_PROBE_UNIT]           = ":PROB%d:SET:ATT:UNIT?",
58 };
59
60 static const uint32_t devopts[] = {
61         SR_CONF_OSCILLOSCOPE,
62         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
63         SR_CONF_LIMIT_FRAMES | SR_CONF_GET | SR_CONF_SET,
64         SR_CONF_SAMPLERATE | SR_CONF_GET,
65         SR_CONF_TIMEBASE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
66         SR_CONF_NUM_HDIV | SR_CONF_GET,
67         SR_CONF_HORIZ_TRIGGERPOS | SR_CONF_GET | SR_CONF_SET,
68         SR_CONF_TRIGGER_SOURCE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
69         SR_CONF_TRIGGER_SLOPE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
70 };
71
72 static const uint32_t devopts_cg_analog[] = {
73         SR_CONF_NUM_VDIV | SR_CONF_GET,
74         SR_CONF_VDIV | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
75         SR_CONF_COUPLING | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
76 };
77
78 static const char *coupling_options[] = {
79         "AC",  // AC with 50 Ohm termination (152x, 202x, 30xx, 1202)
80         "ACL", // AC with 1 MOhm termination
81         "DC",  // DC with 50 Ohm termination
82         "DCL", // DC with 1 MOhm termination
83         "GND",
84 };
85
86 static const char *scope_trigger_slopes[] = {
87         "POS",
88         "NEG",
89         "EITH",
90 };
91
92 /* HMO compact2 */
93 static const char *an2_dig8_trigger_sources[] = {
94         "CH1", "CH2",
95         "LINE", "EXT", "PATT", "BUS1", "BUS2",
96         "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
97 };
98
99 /* HMO xxx2 */
100 static const char *an2_dig16_trigger_sources[] = {
101         "CH1", "CH2",
102         "LINE", "EXT", "PATT", "BUS1", "BUS2",
103         "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
104         "D8", "D9", "D10", "D11", "D12", "D13", "D14", "D15",
105 };
106
107 /* HMO compact4 */
108 static const char *an4_dig8_trigger_sources[] = {
109         "CH1", "CH2", "CH3", "CH4",
110         "LINE", "EXT", "PATT", "BUS1", "BUS2",
111         "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
112 };
113
114 /* HMO xxx4 */
115 static const char *an4_dig16_trigger_sources[] = {
116         "CH1", "CH2", "CH3", "CH4",
117         "LINE", "EXT", "PATT", "BUS1", "BUS2",
118         "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
119         "D8", "D9", "D10", "D11", "D12", "D13", "D14", "D15",
120 };
121
122 static const uint64_t timebases[][2] = {
123         /* nanoseconds */
124         { 2, 1000000000 },
125         { 5, 1000000000 },
126         { 10, 1000000000 },
127         { 20, 1000000000 },
128         { 50, 1000000000 },
129         { 100, 1000000000 },
130         { 200, 1000000000 },
131         { 500, 1000000000 },
132         /* microseconds */
133         { 1, 1000000 },
134         { 2, 1000000 },
135         { 5, 1000000 },
136         { 10, 1000000 },
137         { 20, 1000000 },
138         { 50, 1000000 },
139         { 100, 1000000 },
140         { 200, 1000000 },
141         { 500, 1000000 },
142         /* milliseconds */
143         { 1, 1000 },
144         { 2, 1000 },
145         { 5, 1000 },
146         { 10, 1000 },
147         { 20, 1000 },
148         { 50, 1000 },
149         { 100, 1000 },
150         { 200, 1000 },
151         { 500, 1000 },
152         /* seconds */
153         { 1, 1 },
154         { 2, 1 },
155         { 5, 1 },
156         { 10, 1 },
157         { 20, 1 },
158         { 50, 1 },
159 };
160
161 static const uint64_t vdivs[][2] = {
162         /* millivolts */
163         { 1, 1000 },
164         { 2, 1000 },
165         { 5, 1000 },
166         { 10, 1000 },
167         { 20, 1000 },
168         { 50, 1000 },
169         { 100, 1000 },
170         { 200, 1000 },
171         { 500, 1000 },
172         /* volts */
173         { 1, 1 },
174         { 2, 1 },
175         { 5, 1 },
176         { 10, 1 },
177         { 20, 1 },
178         { 50, 1 },
179 };
180
181 static const char *scope_analog_channel_names[] = {
182         "CH1", "CH2", "CH3", "CH4",
183 };
184
185 static const char *scope_digital_channel_names[] = {
186         "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
187         "D8", "D9", "D10", "D11", "D12", "D13", "D14", "D15",
188 };
189
190 static const struct scope_config scope_models[] = {
191         {
192                 /* HMO722/1002/1022/1522/2022 support only 8 digital channels. */
193                 .name = {"HMO722", "HMO1002", "HMO1022", "HMO1522", "HMO2022", NULL},
194                 .analog_channels = 2,
195                 .digital_channels = 8,
196                 .digital_pods = 1,
197
198                 .analog_names = &scope_analog_channel_names,
199                 .digital_names = &scope_digital_channel_names,
200
201                 .devopts = &devopts,
202                 .num_devopts = ARRAY_SIZE(devopts),
203
204                 .devopts_cg_analog = &devopts_cg_analog,
205                 .num_devopts_cg_analog = ARRAY_SIZE(devopts_cg_analog),
206
207                 .coupling_options = &coupling_options,
208                 .num_coupling_options = ARRAY_SIZE(coupling_options),
209
210                 .trigger_sources = &an2_dig8_trigger_sources,
211                 .num_trigger_sources = ARRAY_SIZE(an2_dig8_trigger_sources),
212
213                 .trigger_slopes = &scope_trigger_slopes,
214                 .num_trigger_slopes = ARRAY_SIZE(scope_trigger_slopes),
215
216                 .timebases = &timebases,
217                 .num_timebases = ARRAY_SIZE(timebases),
218
219                 .vdivs = &vdivs,
220                 .num_vdivs = ARRAY_SIZE(vdivs),
221
222                 .num_xdivs = 12,
223                 .num_ydivs = 8,
224
225                 .scpi_dialect = &hameg_scpi_dialect,
226         },
227         {
228                 /* HMO3032/3042/3052/3522 support 16 digital channels. */
229                 .name = {"HMO3032", "HMO3042", "HMO3052", "HMO3522", NULL},
230                 .analog_channels = 2,
231                 .digital_channels = 16,
232                 .digital_pods = 2,
233
234                 .analog_names = &scope_analog_channel_names,
235                 .digital_names = &scope_digital_channel_names,
236
237                 .devopts = &devopts,
238                 .num_devopts = ARRAY_SIZE(devopts),
239
240                 .devopts_cg_analog = &devopts_cg_analog,
241                 .num_devopts_cg_analog = ARRAY_SIZE(devopts_cg_analog),
242
243                 .coupling_options = &coupling_options,
244                 .num_coupling_options = ARRAY_SIZE(coupling_options),
245
246                 .trigger_sources = &an2_dig16_trigger_sources,
247                 .num_trigger_sources = ARRAY_SIZE(an2_dig16_trigger_sources),
248
249                 .trigger_slopes = &scope_trigger_slopes,
250                 .num_trigger_slopes = ARRAY_SIZE(scope_trigger_slopes),
251
252                 .timebases = &timebases,
253                 .num_timebases = ARRAY_SIZE(timebases),
254
255                 .vdivs = &vdivs,
256                 .num_vdivs = ARRAY_SIZE(vdivs),
257
258                 .num_xdivs = 12,
259                 .num_ydivs = 8,
260
261                 .scpi_dialect = &hameg_scpi_dialect,
262         },
263         {
264                 .name = {"HMO724", "HMO1024", "HMO1524", "HMO2024", NULL},
265                 .analog_channels = 4,
266                 .digital_channels = 8,
267                 .digital_pods = 1,
268
269                 .analog_names = &scope_analog_channel_names,
270                 .digital_names = &scope_digital_channel_names,
271
272                 .devopts = &devopts,
273                 .num_devopts = ARRAY_SIZE(devopts),
274
275                 .devopts_cg_analog = &devopts_cg_analog,
276                 .num_devopts_cg_analog = ARRAY_SIZE(devopts_cg_analog),
277
278                 .coupling_options = &coupling_options,
279                 .num_coupling_options = ARRAY_SIZE(coupling_options),
280
281                 .trigger_sources = &an4_dig8_trigger_sources,
282                 .num_trigger_sources = ARRAY_SIZE(an4_dig8_trigger_sources),
283
284                 .trigger_slopes = &scope_trigger_slopes,
285                 .num_trigger_slopes = ARRAY_SIZE(scope_trigger_slopes),
286
287                 .timebases = &timebases,
288                 .num_timebases = ARRAY_SIZE(timebases),
289
290                 .vdivs = &vdivs,
291                 .num_vdivs = ARRAY_SIZE(vdivs),
292
293                 .num_xdivs = 12,
294                 .num_ydivs = 8,
295
296                 .scpi_dialect = &hameg_scpi_dialect,
297         },
298         {
299                 .name = {"HMO2524", "HMO3034", "HMO3044", "HMO3054", "HMO3524", NULL},
300                 .analog_channels = 4,
301                 .digital_channels = 16,
302                 .digital_pods = 2,
303
304                 .analog_names = &scope_analog_channel_names,
305                 .digital_names = &scope_digital_channel_names,
306
307                 .devopts = &devopts,
308                 .num_devopts = ARRAY_SIZE(devopts),
309
310                 .devopts_cg_analog = &devopts_cg_analog,
311                 .num_devopts_cg_analog = ARRAY_SIZE(devopts_cg_analog),
312
313                 .coupling_options = &coupling_options,
314                 .num_coupling_options = ARRAY_SIZE(coupling_options),
315
316                 .trigger_sources = &an4_dig16_trigger_sources,
317                 .num_trigger_sources = ARRAY_SIZE(an4_dig16_trigger_sources),
318
319                 .trigger_slopes = &scope_trigger_slopes,
320                 .num_trigger_slopes = ARRAY_SIZE(scope_trigger_slopes),
321
322                 .timebases = &timebases,
323                 .num_timebases = ARRAY_SIZE(timebases),
324
325                 .vdivs = &vdivs,
326                 .num_vdivs = ARRAY_SIZE(vdivs),
327
328                 .num_xdivs = 12,
329                 .num_ydivs = 8,
330
331                 .scpi_dialect = &hameg_scpi_dialect,
332         },
333 };
334
335 static void scope_state_dump(const struct scope_config *config,
336                              struct scope_state *state)
337 {
338         unsigned int i;
339         char *tmp;
340
341         for (i = 0; i < config->analog_channels; i++) {
342                 tmp = sr_voltage_string((*config->vdivs)[state->analog_channels[i].vdiv][0],
343                                              (*config->vdivs)[state->analog_channels[i].vdiv][1]);
344                 sr_info("State of analog channel %d -> %s : %s (coupling) %s (vdiv) %2.2e (offset)",
345                         i + 1, state->analog_channels[i].state ? "On" : "Off",
346                         (*config->coupling_options)[state->analog_channels[i].coupling],
347                         tmp, state->analog_channels[i].vertical_offset);
348         }
349
350         for (i = 0; i < config->digital_channels; i++) {
351                 sr_info("State of digital channel %d -> %s", i,
352                         state->digital_channels[i] ? "On" : "Off");
353         }
354
355         for (i = 0; i < config->digital_pods; i++) {
356                 sr_info("State of digital POD %d -> %s", i,
357                         state->digital_pods[i] ? "On" : "Off");
358         }
359
360         tmp = sr_period_string((*config->timebases)[state->timebase][0],
361                                (*config->timebases)[state->timebase][1]);
362         sr_info("Current timebase: %s", tmp);
363         g_free(tmp);
364
365         tmp = sr_samplerate_string(state->sample_rate);
366         sr_info("Current samplerate: %s", tmp);
367         g_free(tmp);
368
369         sr_info("Current trigger: %s (source), %s (slope) %.2f (offset)",
370                 (*config->trigger_sources)[state->trigger_source],
371                 (*config->trigger_slopes)[state->trigger_slope],
372                 state->horiz_triggerpos);
373 }
374
375 static int scope_state_get_array_option(struct sr_scpi_dev_inst *scpi,
376                 const char *command, const char *(*array)[], unsigned int n, int *result)
377 {
378         char *tmp;
379         int idx;
380
381         if (sr_scpi_get_string(scpi, command, &tmp) != SR_OK) {
382                 g_free(tmp);
383                 return SR_ERR;
384         }
385
386         if ((idx = std_str_idx_s(tmp, *array, n)) < 0) {
387                 g_free(tmp);
388                 return SR_ERR_ARG;
389         }
390
391         *result = idx;
392
393         g_free(tmp);
394
395         return SR_OK;
396 }
397
398 /**
399  * This function takes a value of the form "2.000E-03" and returns the index
400  * of an array where a matching pair was found.
401  *
402  * @param value The string to be parsed.
403  * @param array The array of s/f pairs.
404  * @param array_len The number of pairs in the array.
405  * @param result The index at which a matching pair was found.
406  *
407  * @return SR_ERR on any parsing error, SR_OK otherwise.
408  */
409 static int array_float_get(gchar *value, const uint64_t array[][2],
410                 int array_len, unsigned int *result)
411 {
412         struct sr_rational rval;
413         struct sr_rational aval;
414
415         if (sr_parse_rational(value, &rval) != SR_OK)
416                 return SR_ERR;
417
418         for (int i = 0; i < array_len; i++) {
419                 sr_rational_set(&aval, array[i][0], array[i][1]);
420                 if (sr_rational_eq(&rval, &aval)) {
421                         *result = i;
422                         return SR_OK;
423                 }
424         }
425
426         return SR_ERR;
427 }
428
429 static struct sr_channel *get_channel_by_index_and_type(GSList *channel_lhead,
430                                                         int index, int type)
431 {
432         while (channel_lhead) {
433                 struct sr_channel *ch = channel_lhead->data;
434                 if (ch->index == index && ch->type == type)
435                         return ch;
436
437                 channel_lhead = channel_lhead->next;
438         }
439
440         return 0;
441 }
442
443 static int analog_channel_state_get(struct sr_dev_inst *sdi,
444                                     const struct scope_config *config,
445                                     struct scope_state *state)
446 {
447         unsigned int i, j;
448         char command[MAX_COMMAND_SIZE];
449         char *tmp_str;
450         struct sr_channel *ch;
451         struct sr_scpi_dev_inst *scpi = sdi->conn;
452
453         for (i = 0; i < config->analog_channels; i++) {
454                 g_snprintf(command, sizeof(command),
455                            (*config->scpi_dialect)[SCPI_CMD_GET_ANALOG_CHAN_STATE],
456                            i + 1);
457
458                 if (sr_scpi_get_bool(scpi, command,
459                                      &state->analog_channels[i].state) != SR_OK)
460                         return SR_ERR;
461
462                 ch = get_channel_by_index_and_type(sdi->channels, i, SR_CHANNEL_ANALOG);
463                 if (ch)
464                         ch->enabled = state->analog_channels[i].state;
465
466                 g_snprintf(command, sizeof(command),
467                            (*config->scpi_dialect)[SCPI_CMD_GET_VERTICAL_DIV],
468                            i + 1);
469
470                 if (sr_scpi_get_string(scpi, command, &tmp_str) != SR_OK)
471                         return SR_ERR;
472
473                 if (array_float_get(tmp_str, ARRAY_AND_SIZE(vdivs), &j) != SR_OK) {
474                         g_free(tmp_str);
475                         sr_err("Could not determine array index for vertical div scale.");
476                         return SR_ERR;
477                 }
478
479                 g_free(tmp_str);
480                 state->analog_channels[i].vdiv = j;
481
482                 g_snprintf(command, sizeof(command),
483                            (*config->scpi_dialect)[SCPI_CMD_GET_VERTICAL_OFFSET],
484                            i + 1);
485
486                 if (sr_scpi_get_float(scpi, command,
487                                      &state->analog_channels[i].vertical_offset) != SR_OK)
488                         return SR_ERR;
489
490                 g_snprintf(command, sizeof(command),
491                            (*config->scpi_dialect)[SCPI_CMD_GET_COUPLING],
492                            i + 1);
493
494                 if (scope_state_get_array_option(scpi, command, config->coupling_options,
495                                          config->num_coupling_options,
496                                          &state->analog_channels[i].coupling) != SR_OK)
497                         return SR_ERR;
498
499                 g_snprintf(command, sizeof(command),
500                            (*config->scpi_dialect)[SCPI_CMD_GET_PROBE_UNIT],
501                            i + 1);
502
503                 if (sr_scpi_get_string(scpi, command, &tmp_str) != SR_OK)
504                         return SR_ERR;
505
506                 if (tmp_str[0] == 'A')
507                         state->analog_channels[i].probe_unit = 'A';
508                 else
509                         state->analog_channels[i].probe_unit = 'V';
510                 g_free(tmp_str);
511         }
512
513         return SR_OK;
514 }
515
516 static int digital_channel_state_get(struct sr_dev_inst *sdi,
517                                      const struct scope_config *config,
518                                      struct scope_state *state)
519 {
520         unsigned int i;
521         char command[MAX_COMMAND_SIZE];
522         struct sr_channel *ch;
523         struct sr_scpi_dev_inst *scpi = sdi->conn;
524
525         for (i = 0; i < config->digital_channels; i++) {
526                 g_snprintf(command, sizeof(command),
527                            (*config->scpi_dialect)[SCPI_CMD_GET_DIG_CHAN_STATE],
528                            i);
529
530                 if (sr_scpi_get_bool(scpi, command,
531                                      &state->digital_channels[i]) != SR_OK)
532                         return SR_ERR;
533
534                 ch = get_channel_by_index_and_type(sdi->channels, i, SR_CHANNEL_LOGIC);
535                 if (ch)
536                         ch->enabled = state->digital_channels[i];
537         }
538
539         for (i = 0; i < config->digital_pods; i++) {
540                 g_snprintf(command, sizeof(command),
541                            (*config->scpi_dialect)[SCPI_CMD_GET_DIG_POD_STATE],
542                            i + 1);
543
544                 if (sr_scpi_get_bool(scpi, command,
545                                      &state->digital_pods[i]) != SR_OK)
546                         return SR_ERR;
547         }
548
549         return SR_OK;
550 }
551
552 SR_PRIV int hmo_update_sample_rate(const struct sr_dev_inst *sdi)
553 {
554         struct dev_context *devc;
555         struct scope_state *state;
556         const struct scope_config *config;
557         int tmp;
558         unsigned int i;
559         float tmp_float;
560         gboolean channel_found;
561         char tmp_str[MAX_COMMAND_SIZE];
562         char chan_name[20];
563
564         devc = sdi->priv;
565         config = devc->model_config;
566         state = devc->model_state;
567         channel_found = FALSE;
568
569         for (i = 0; i < config->analog_channels; i++) {
570                 if (!state->analog_channels[i].state)
571                         continue;
572                 g_snprintf(chan_name, sizeof(chan_name), "CHAN%d", i + 1);
573                 g_snprintf(tmp_str, sizeof(tmp_str),
574                            (*config->scpi_dialect)[SCPI_CMD_GET_SAMPLE_RATE_LIVE],
575                            chan_name);
576                 channel_found = TRUE;
577                 break;
578         }
579
580         if (!channel_found) {
581                 for (i = 0; i < config->digital_pods; i++) {
582                         if (!state->digital_pods[i])
583                                 continue;
584                         g_snprintf(chan_name, sizeof(chan_name), "POD%d", i);
585                         g_snprintf(tmp_str, sizeof(tmp_str),
586                                    (*config->scpi_dialect)[SCPI_CMD_GET_SAMPLE_RATE_LIVE],
587                                    chan_name);
588                         channel_found = TRUE;
589                         break;
590                 }
591         }
592
593         /* No channel is active, ask the instrument for the sample rate
594          * in single shot mode */
595         if (!channel_found) {
596                 if (sr_scpi_get_float(sdi->conn,
597                                       (*config->scpi_dialect)[SCPI_CMD_GET_SAMPLE_RATE],
598                                       &tmp_float) != SR_OK)
599                         return SR_ERR;
600
601                 state->sample_rate = tmp_float;
602         } else {
603                 if (sr_scpi_get_int(sdi->conn, tmp_str, &tmp) != SR_OK)
604                         return SR_ERR;
605                 state->sample_rate = tmp / (((float) (*config->timebases)[state->timebase][0] /
606                                              (*config->timebases)[state->timebase][1]) *
607                                             config->num_xdivs);
608         }
609
610         return SR_OK;
611 }
612
613 SR_PRIV int hmo_scope_state_get(struct sr_dev_inst *sdi)
614 {
615         struct dev_context *devc;
616         struct scope_state *state;
617         const struct scope_config *config;
618         float tmp_float;
619         unsigned int i;
620         char *tmp_str;
621
622         devc = sdi->priv;
623         config = devc->model_config;
624         state = devc->model_state;
625
626         sr_info("Fetching scope state");
627
628         if (analog_channel_state_get(sdi, config, state) != SR_OK)
629                 return SR_ERR;
630
631         if (digital_channel_state_get(sdi, config, state) != SR_OK)
632                 return SR_ERR;
633
634         if (sr_scpi_get_float(sdi->conn,
635                         (*config->scpi_dialect)[SCPI_CMD_GET_TIMEBASE],
636                         &tmp_float) != SR_OK)
637                 return SR_ERR;
638
639         if (sr_scpi_get_string(sdi->conn,
640                         (*config->scpi_dialect)[SCPI_CMD_GET_TIMEBASE],
641                         &tmp_str) != SR_OK)
642                 return SR_ERR;
643
644         if (array_float_get(tmp_str, ARRAY_AND_SIZE(timebases), &i) != SR_OK) {
645                 g_free(tmp_str);
646                 sr_err("Could not determine array index for time base.");
647                 return SR_ERR;
648         }
649         g_free(tmp_str);
650
651         state->timebase = i;
652
653         if (sr_scpi_get_float(sdi->conn,
654                         (*config->scpi_dialect)[SCPI_CMD_GET_HORIZ_TRIGGERPOS],
655                         &tmp_float) != SR_OK)
656                 return SR_ERR;
657         state->horiz_triggerpos = tmp_float /
658                 (((double) (*config->timebases)[state->timebase][0] /
659                   (*config->timebases)[state->timebase][1]) * config->num_xdivs);
660         state->horiz_triggerpos -= 0.5;
661         state->horiz_triggerpos *= -1;
662
663         if (scope_state_get_array_option(sdi->conn,
664                         (*config->scpi_dialect)[SCPI_CMD_GET_TRIGGER_SOURCE],
665                         config->trigger_sources, config->num_trigger_sources,
666                         &state->trigger_source) != SR_OK)
667                 return SR_ERR;
668
669         if (scope_state_get_array_option(sdi->conn,
670                         (*config->scpi_dialect)[SCPI_CMD_GET_TRIGGER_SLOPE],
671                         config->trigger_slopes, config->num_trigger_slopes,
672                         &state->trigger_slope) != SR_OK)
673                 return SR_ERR;
674
675         if (hmo_update_sample_rate(sdi) != SR_OK)
676                 return SR_ERR;
677
678         sr_info("Fetching finished.");
679
680         scope_state_dump(config, state);
681
682         return SR_OK;
683 }
684
685 static struct scope_state *scope_state_new(const struct scope_config *config)
686 {
687         struct scope_state *state;
688
689         state = g_malloc0(sizeof(struct scope_state));
690         state->analog_channels = g_malloc0_n(config->analog_channels,
691                         sizeof(struct analog_channel_state));
692         state->digital_channels = g_malloc0_n(
693                         config->digital_channels, sizeof(gboolean));
694         state->digital_pods = g_malloc0_n(config->digital_pods,
695                         sizeof(gboolean));
696
697         return state;
698 }
699
700 SR_PRIV void hmo_scope_state_free(struct scope_state *state)
701 {
702         g_free(state->analog_channels);
703         g_free(state->digital_channels);
704         g_free(state->digital_pods);
705         g_free(state);
706 }
707
708 SR_PRIV int hmo_init_device(struct sr_dev_inst *sdi)
709 {
710         int model_index;
711         unsigned int i, j, group;
712         struct sr_channel *ch;
713         struct dev_context *devc;
714         int ret;
715
716         devc = sdi->priv;
717         model_index = -1;
718
719         /* Find the exact model. */
720         for (i = 0; i < ARRAY_SIZE(scope_models); i++) {
721                 for (j = 0; scope_models[i].name[j]; j++) {
722                         if (!strcmp(sdi->model, scope_models[i].name[j])) {
723                                 model_index = i;
724                                 break;
725                         }
726                 }
727                 if (model_index != -1)
728                         break;
729         }
730
731         if (model_index == -1) {
732                 sr_dbg("Unsupported HMO device.");
733                 return SR_ERR_NA;
734         }
735
736         devc->analog_groups = g_malloc0(sizeof(struct sr_channel_group*) *
737                                         scope_models[model_index].analog_channels);
738         devc->digital_groups = g_malloc0(sizeof(struct sr_channel_group*) *
739                                          scope_models[model_index].digital_pods);
740         if (!devc->analog_groups || !devc->digital_groups) {
741                 g_free(devc->analog_groups);
742                 g_free(devc->digital_groups);
743                 return SR_ERR_MALLOC;
744         }
745
746         /* Add analog channels. */
747         for (i = 0; i < scope_models[model_index].analog_channels; i++) {
748                 ch = sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, TRUE,
749                            (*scope_models[model_index].analog_names)[i]);
750
751                 devc->analog_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
752
753                 devc->analog_groups[i]->name = g_strdup(
754                         (char *)(*scope_models[model_index].analog_names)[i]);
755                 devc->analog_groups[i]->channels = g_slist_append(NULL, ch);
756
757                 sdi->channel_groups = g_slist_append(sdi->channel_groups,
758                                                    devc->analog_groups[i]);
759         }
760
761         /* Add digital channel groups. */
762         ret = SR_OK;
763         for (i = 0; i < scope_models[model_index].digital_pods; i++) {
764                 devc->digital_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
765                 if (!devc->digital_groups[i]) {
766                         ret = SR_ERR_MALLOC;
767                         break;
768                 }
769                 devc->digital_groups[i]->name = g_strdup_printf("POD%d", i);
770                 sdi->channel_groups = g_slist_append(sdi->channel_groups,
771                                    devc->digital_groups[i]);
772         }
773         if (ret != SR_OK)
774                 return ret;
775
776         /* Add digital channels. */
777         for (i = 0; i < scope_models[model_index].digital_channels; i++) {
778                 ch = sr_channel_new(sdi, i, SR_CHANNEL_LOGIC, TRUE,
779                            (*scope_models[model_index].digital_names)[i]);
780
781                 group = i / 8;
782                 devc->digital_groups[group]->channels = g_slist_append(
783                         devc->digital_groups[group]->channels, ch);
784         }
785
786         devc->model_config = &scope_models[model_index];
787         devc->samples_limit = 0;
788         devc->frame_limit = 0;
789
790         if (!(devc->model_state = scope_state_new(devc->model_config)))
791                 return SR_ERR_MALLOC;
792
793         return SR_OK;
794 }
795
796 /* Queue data of one channel group, for later submission. */
797 SR_PRIV void hmo_queue_logic_data(struct dev_context *devc,
798                                   size_t group, GByteArray *pod_data)
799 {
800         size_t size;
801         GByteArray *store;
802         uint8_t *logic_data;
803         size_t idx, logic_step;
804
805         /*
806          * Upon first invocation, allocate the array which can hold the
807          * combined logic data for all channels. Assume that each channel
808          * will yield an identical number of samples per receive call.
809          *
810          * As a poor man's safety measure: (Silently) skip processing
811          * for unexpected sample counts, and ignore samples for
812          * unexpected channel groups. Don't bother with complicated
813          * resize logic, considering that many models only support one
814          * pod, and the most capable supported models have two pods of
815          * identical size. We haven't yet seen any "odd" configuration.
816          */
817         if (!devc->logic_data) {
818                 size = pod_data->len * devc->pod_count;
819                 store = g_byte_array_sized_new(size);
820                 memset(store->data, 0, size);
821                 store = g_byte_array_set_size(store, size);
822                 devc->logic_data = store;
823         } else {
824                 store = devc->logic_data;
825                 size = store->len / devc->pod_count;
826                 if (group >= devc->pod_count)
827                         return;
828         }
829
830         /*
831          * Fold the data of the most recently received channel group into
832          * the storage, where data resides for all channels combined.
833          */
834         logic_data = store->data;
835         logic_data += group;
836         logic_step = devc->pod_count;
837         for (idx = 0; idx < pod_data->len; idx++) {
838                 *logic_data = pod_data->data[idx];
839                 logic_data += logic_step;
840         }
841
842         /* Truncate acquisition if a smaller number of samples has been requested. */
843         if (devc->samples_limit > 0 && devc->logic_data->len > devc->samples_limit * devc->pod_count)
844                 devc->logic_data->len = devc->samples_limit * devc->pod_count;
845 }
846
847 /* Submit data for all channels, after the individual groups got collected. */
848 SR_PRIV void hmo_send_logic_packet(struct sr_dev_inst *sdi,
849                                    struct dev_context *devc)
850 {
851         struct sr_datafeed_packet packet;
852         struct sr_datafeed_logic logic;
853
854         if (!devc->logic_data)
855                 return;
856
857         logic.data = devc->logic_data->data;
858         logic.length = devc->logic_data->len;
859         logic.unitsize = devc->pod_count;
860
861         packet.type = SR_DF_LOGIC;
862         packet.payload = &logic;
863
864         sr_session_send(sdi, &packet);
865 }
866
867 /* Undo previous resource allocation. */
868 SR_PRIV void hmo_cleanup_logic_data(struct dev_context *devc)
869 {
870
871         if (devc->logic_data) {
872                 g_byte_array_free(devc->logic_data, TRUE);
873                 devc->logic_data = NULL;
874         }
875         /*
876          * Keep 'pod_count'! It's required when more frames will be
877          * received, and does not harm when kept after acquisition.
878          */
879 }
880
881 SR_PRIV int hmo_receive_data(int fd, int revents, void *cb_data)
882 {
883         struct sr_channel *ch;
884         struct sr_dev_inst *sdi;
885         struct dev_context *devc;
886         struct scope_state *state;
887         struct sr_datafeed_packet packet;
888         GByteArray *data;
889         struct sr_datafeed_analog analog;
890         struct sr_analog_encoding encoding;
891         struct sr_analog_meaning meaning;
892         struct sr_analog_spec spec;
893         struct sr_datafeed_logic logic;
894         size_t group;
895
896         (void)fd;
897         (void)revents;
898
899         data = NULL;
900
901         if (!(sdi = cb_data))
902                 return TRUE;
903
904         if (!(devc = sdi->priv))
905                 return TRUE;
906
907         /* Although this is correct in general, the USBTMC libusb implementation
908          * currently does not generate an event prior to the first read. Often
909          * it is ok to start reading just after the 50ms timeout. See bug #785.
910         if (revents != G_IO_IN)
911                 return TRUE;
912         */
913
914         ch = devc->current_channel->data;
915         state = devc->model_state;
916
917         /*
918          * Send "frame begin" packet upon reception of data for the
919          * first enabled channel.
920          */
921         if (devc->current_channel == devc->enabled_channels) {
922                 packet.type = SR_DF_FRAME_BEGIN;
923                 sr_session_send(sdi, &packet);
924         }
925
926         /*
927          * Pass on the received data of the channel(s).
928          */
929         switch (ch->type) {
930         case SR_CHANNEL_ANALOG:
931                 if (sr_scpi_get_block(sdi->conn, NULL, &data) != SR_OK) {
932                         if (data)
933                                 g_byte_array_free(data, TRUE);
934                         return TRUE;
935                 }
936
937                 packet.type = SR_DF_ANALOG;
938
939                 analog.data = data->data;
940                 analog.num_samples = data->len / sizeof(float);
941                 /* Truncate acquisition if a smaller number of samples has been requested. */
942                 if (devc->samples_limit > 0 && analog.num_samples > devc->samples_limit)
943                         analog.num_samples = devc->samples_limit;
944                 analog.encoding = &encoding;
945                 analog.meaning = &meaning;
946                 analog.spec = &spec;
947
948                 encoding.unitsize = sizeof(float);
949                 encoding.is_signed = TRUE;
950                 encoding.is_float = TRUE;
951 #ifdef WORDS_BIGENDIAN
952                 encoding.is_bigendian = TRUE;
953 #else
954                 encoding.is_bigendian = FALSE;
955 #endif
956                 /* TODO: Use proper 'digits' value for this device (and its modes). */
957                 encoding.digits = 2;
958                 encoding.is_digits_decimal = FALSE;
959                 encoding.scale.p = 1;
960                 encoding.scale.q = 1;
961                 encoding.offset.p = 0;
962                 encoding.offset.q = 1;
963                 if (state->analog_channels[ch->index].probe_unit == 'V') {
964                         meaning.mq = SR_MQ_VOLTAGE;
965                         meaning.unit = SR_UNIT_VOLT;
966                 } else {
967                         meaning.mq = SR_MQ_CURRENT;
968                         meaning.unit = SR_UNIT_AMPERE;
969                 }
970                 meaning.mqflags = 0;
971                 meaning.channels = g_slist_append(NULL, ch);
972                 /* TODO: Use proper 'digits' value for this device (and its modes). */
973                 spec.spec_digits = 2;
974                 packet.payload = &analog;
975                 sr_session_send(sdi, &packet);
976                 devc->num_samples = data->len / sizeof(float);
977                 g_slist_free(meaning.channels);
978                 g_byte_array_free(data, TRUE);
979                 data = NULL;
980                 break;
981         case SR_CHANNEL_LOGIC:
982                 if (sr_scpi_get_block(sdi->conn, NULL, &data) != SR_OK) {
983                         if (data)
984                                 g_byte_array_free(data, TRUE);
985                         return TRUE;
986                 }
987
988                 /*
989                  * If only data from the first pod is involved in the
990                  * acquisition, then the raw input bytes can get passed
991                  * forward for performance reasons. When the second pod
992                  * is involved (either alone, or in combination with the
993                  * first pod), then the received bytes need to be put
994                  * into memory in such a layout that all channel groups
995                  * get combined, and a unitsize larger than a single byte
996                  * applies. The "queue" logic transparently copes with
997                  * any such configuration. This works around the lack
998                  * of support for "meaning" to logic data, which is used
999                  * above for analog data.
1000                  */
1001                 if (devc->pod_count == 1) {
1002                         packet.type = SR_DF_LOGIC;
1003                         logic.data = data->data;
1004                         logic.length = data->len;
1005                         /* Truncate acquisition if a smaller number of samples has been requested. */
1006                         if (devc->samples_limit > 0 && logic.length > devc->samples_limit)
1007                                 logic.length = devc->samples_limit;
1008                         logic.unitsize = 1;
1009                         packet.payload = &logic;
1010                         sr_session_send(sdi, &packet);
1011                 } else {
1012                         group = ch->index / 8;
1013                         hmo_queue_logic_data(devc, group, data);
1014                 }
1015
1016                 devc->num_samples = data->len / devc->pod_count;
1017                 g_byte_array_free(data, TRUE);
1018                 data = NULL;
1019                 break;
1020         default:
1021                 sr_err("Invalid channel type.");
1022                 break;
1023         }
1024
1025         /*
1026          * Advance to the next enabled channel. When data for all enabled
1027          * channels was received, then flush potentially queued logic data,
1028          * and send the "frame end" packet.
1029          */
1030         if (devc->current_channel->next) {
1031                 devc->current_channel = devc->current_channel->next;
1032                 hmo_request_data(sdi);
1033                 return TRUE;
1034         }
1035         hmo_send_logic_packet(sdi, devc);
1036
1037         /*
1038          * Release the logic data storage after each frame. This copes
1039          * with sample counts that differ in length per frame. -- Is
1040          * this a real constraint when acquiring multiple frames with
1041          * identical device settings?
1042          */
1043         hmo_cleanup_logic_data(devc);
1044
1045         packet.type = SR_DF_FRAME_END;
1046         sr_session_send(sdi, &packet);
1047
1048         /*
1049          * End of frame was reached. Stop acquisition after the specified
1050          * number of frames or after the specified number of samples, or
1051          * continue reception by starting over at the first enabled channel.
1052          */
1053         if (++devc->num_frames >= devc->frame_limit || devc->num_samples >= devc->samples_limit) {
1054                 sr_dev_acquisition_stop(sdi);
1055                 hmo_cleanup_logic_data(devc);
1056         } else {
1057                 devc->current_channel = devc->enabled_channels;
1058                 hmo_request_data(sdi);
1059         }
1060
1061         return TRUE;
1062 }