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