]> sigrok.org Git - libsigrok.git/blob - src/hardware/yokogawa-dlm/protocol.c
5dc03194af2ca207773f31d4d73ec564bd6c00d1
[libsigrok.git] / src / hardware / yokogawa-dlm / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 abraxa (Soeren Apel) <soeren@apelpie.net>
5  * Based on the Hameg HMO driver by poljar (Damir Jelić) <poljarinho@gmail.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 /** @file
22  * <em>Yokogawa DL/DLM series</em> oscilloscope driver
23  * @internal
24  */
25
26 #include "protocol.h"
27
28 static const uint32_t dlm_devopts[] = {
29         SR_CONF_LOGIC_ANALYZER,
30         SR_CONF_OSCILLOSCOPE,
31         SR_CONF_LIMIT_FRAMES | SR_CONF_SET,
32         SR_CONF_SAMPLERATE | SR_CONF_GET,
33         SR_CONF_TRIGGER_SLOPE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
34         SR_CONF_TRIGGER_SOURCE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
35         SR_CONF_TIMEBASE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
36         SR_CONF_NUM_TIMEBASE | SR_CONF_GET,
37         SR_CONF_HORIZ_TRIGGERPOS | SR_CONF_GET | SR_CONF_SET,
38 };
39
40 static const uint32_t dlm_analog_devopts[] = {
41         SR_CONF_VDIV | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
42         SR_CONF_COUPLING | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
43         SR_CONF_NUM_VDIV | SR_CONF_GET,
44 };
45
46 static const char *dlm_coupling_options[] = {
47         "AC",
48         "DC",
49         "DC50",
50         "GND",
51         NULL,
52 };
53
54 /* Note: Values must correlate to the trigger_slopes values */
55 static const char *dlm_trigger_slopes[] = {
56         "r",
57         "f",
58         NULL,
59 };
60
61 static const char *dlm_2ch_trigger_sources[] = {
62         "1",
63         "2",
64         "LINE",
65         "EXT",
66         NULL,
67 };
68
69 /* TODO: Is BITx handled correctly or is Dx required? */
70 static const char *dlm_4ch_trigger_sources[] = {
71         "1",
72         "2",
73         "3",
74         "4",
75         "LINE",
76         "EXT",
77         "BIT1",
78         "BIT2",
79         "BIT3",
80         "BIT4",
81         "BIT5",
82         "BIT6",
83         "BIT7",
84         "BIT8",
85         NULL,
86 };
87
88 static const uint64_t dlm_timebases[][2] = {
89         /* nanoseconds */
90         { 1, 1000000000 },
91         { 2, 1000000000 },
92         { 5, 1000000000 },
93         { 10, 1000000000 },
94         { 20, 1000000000 },
95         { 50, 1000000000 },
96         { 100, 1000000000 },
97         { 200, 1000000000 },
98         { 500, 1000000000 },
99         /* microseconds */
100         { 1, 1000000 },
101         { 2, 1000000 },
102         { 5, 1000000 },
103         { 10, 1000000 },
104         { 20, 1000000 },
105         { 50, 1000000 },
106         { 100, 1000000 },
107         { 200, 1000000 },
108         { 500, 1000000 },
109         /* milliseconds */
110         { 1, 1000 },
111         { 2, 1000 },
112         { 5, 1000 },
113         { 10, 1000 },
114         { 20, 1000 },
115         { 50, 1000 },
116         { 100, 1000 },
117         { 200, 1000 },
118         { 500, 1000 },
119         /* seconds */
120         { 1, 1 },
121         { 2, 1 },
122         { 5, 1 },
123         { 10, 1 },
124         { 20, 1 },
125         { 50, 1 },
126         { 100, 1 },
127         { 200, 1 },
128         { 500, 1 },
129 };
130
131 static const uint64_t dlm_vdivs[][2] = {
132         /* millivolts */
133         { 2, 1000 },
134         { 5, 1000 },
135         { 10, 1000 },
136         { 20, 1000 },
137         { 50, 1000 },
138         { 100, 1000 },
139         { 200, 1000 },
140         { 500, 1000 },
141         /* volts */
142         { 1, 1 },
143         { 2, 1 },
144         { 5, 1 },
145         { 10, 1 },
146         { 20, 1 },
147         { 50, 1 },
148         { 100, 1 },
149         { 200, 1 },
150         { 500, 1 },
151 };
152
153 static const char *scope_analog_channel_names[] = {
154         "1",
155         "2",
156         "3",
157         "4"
158 };
159
160 static const char *scope_digital_channel_names[] = {
161         "D0",
162         "D1",
163         "D2",
164         "D3",
165         "D4",
166         "D5",
167         "D6",
168         "D7"
169 };
170
171 static struct scope_config scope_models[] = {
172         {
173                 .model_id   = {"710105",  "710115",  "710125",  NULL},
174                 .model_name = {"DLM2022", "DLM2032", "DLM2052", NULL},
175                 .analog_channels = 2,
176                 .digital_channels = 0,
177                 .pods = 0,
178
179                 .analog_names = &scope_analog_channel_names,
180                 .digital_names = &scope_digital_channel_names,
181
182                 .devopts = &dlm_devopts,
183                 .num_devopts = ARRAY_SIZE(dlm_devopts),
184
185                 .analog_devopts = &dlm_analog_devopts,
186                 .num_analog_devopts = ARRAY_SIZE(dlm_analog_devopts),
187
188                 .coupling_options = &dlm_coupling_options,
189                 .trigger_sources = &dlm_2ch_trigger_sources,
190                 .trigger_slopes = &dlm_trigger_slopes,
191
192                 .timebases = &dlm_timebases,
193                 .num_timebases = ARRAY_SIZE(dlm_timebases),
194
195                 .vdivs = &dlm_vdivs,
196                 .num_vdivs = ARRAY_SIZE(dlm_vdivs),
197
198                 .num_xdivs = 10,
199                 .num_ydivs = 8,
200         },
201         {
202                 .model_id    = {"710110",  "710120",  "710130",  NULL},
203                 .model_name  = {"DLM2024", "DLM2034", "DLM2054", NULL},
204                 .analog_channels = 4,
205                 .digital_channels = 8,
206                 .pods = 1,
207
208                 .analog_names = &scope_analog_channel_names,
209                 .digital_names = &scope_digital_channel_names,
210
211                 .devopts = &dlm_devopts,
212                 .num_devopts = ARRAY_SIZE(dlm_devopts),
213
214                 .analog_devopts = &dlm_analog_devopts,
215                 .num_analog_devopts = ARRAY_SIZE(dlm_analog_devopts),
216
217                 .coupling_options = &dlm_coupling_options,
218                 .trigger_sources = &dlm_4ch_trigger_sources,
219                 .trigger_slopes = &dlm_trigger_slopes,
220
221                 .timebases = &dlm_timebases,
222                 .num_timebases = ARRAY_SIZE(dlm_timebases),
223
224                 .vdivs = &dlm_vdivs,
225                 .num_vdivs = ARRAY_SIZE(dlm_vdivs),
226
227                 .num_xdivs = 10,
228                 .num_ydivs = 8,
229         },
230 };
231
232 /**
233  * Prints out the state of the device as we currently know it.
234  *
235  * @param config This is the scope configuration.
236  * @param state The current scope state to print.
237  */
238 static void scope_state_dump(struct scope_config *config,
239                 struct scope_state *state)
240 {
241         unsigned int i;
242         char *tmp;
243
244         for (i = 0; i < config->analog_channels; ++i) {
245                 tmp = sr_voltage_string((*config->vdivs)[state->analog_states[i].vdiv][0],
246                                 (*config->vdivs)[state->analog_states[i].vdiv][1]);
247                 sr_info("State of analog channel  %d -> %s : %s (coupling) %s (vdiv) %2.2e (offset)",
248                                 i + 1, state->analog_states[i].state ? "On" : "Off",
249                                 (*config->coupling_options)[state->analog_states[i].coupling],
250                                 tmp, state->analog_states[i].vertical_offset);
251         }
252
253         for (i = 0; i < config->digital_channels; ++i) {
254                 sr_info("State of digital channel %d -> %s", i,
255                                 state->digital_states[i] ? "On" : "Off");
256         }
257
258         for (i = 0; i < config->pods; ++i) {
259                 sr_info("State of digital POD %d -> %s", i,
260                                 state->pod_states[i] ? "On" : "Off");
261         }
262
263         tmp = sr_period_string((*config->timebases)[state->timebase][0] *
264                         (*config->timebases)[state->timebase][1]);
265         sr_info("Current timebase: %s", tmp);
266         g_free(tmp);
267
268         tmp = sr_samplerate_string(state->sample_rate);
269         sr_info("Current samplerate: %s", tmp);
270         g_free(tmp);
271
272         sr_info("Current samples per acquisition (i.e. frame): %d",
273                         state->samples_per_frame);
274
275         sr_info("Current trigger: %s (source), %s (slope) %.2f (offset)",
276                         (*config->trigger_sources)[state->trigger_source],
277                         (*config->trigger_slopes)[state->trigger_slope],
278                         state->horiz_triggerpos);
279 }
280
281 /**
282  * Searches through an array of strings and returns the index to the
283  * array where a given string is located.
284  *
285  * @param value The string to search for.
286  * @param array The array of strings.
287  * @param result The index at which value is located in array. -1 on error.
288  *
289  * @return SR_ERR when value couldn't be found, SR_OK otherwise.
290  */
291 static int array_option_get(char *value, const char *(*array)[],
292                 int *result)
293 {
294         unsigned int i;
295
296         *result = -1;
297
298         for (i = 0; (*array)[i]; ++i)
299                 if (!g_strcmp0(value, (*array)[i])) {
300                         *result = i;
301                         break;
302                 }
303
304         if (*result == -1)
305                 return SR_ERR;
306
307         return SR_OK;
308 }
309
310 /**
311  * This function takes a value of the form "2.000E-03", converts it to a
312  * significand / factor pair and returns the index of an array where
313  * a matching pair was found.
314  *
315  * It's a bit convoluted because of floating-point issues. The value "10.00E-09"
316  * is parsed by g_ascii_strtod() as 0.000000009999999939, for example.
317  * Therefore it's easier to break the number up into two strings and handle
318  * them separately.
319  *
320  * @param value The string to be parsed.
321  * @param array The array of s/f pairs.
322  * @param array_len The number of pairs in the array.
323  * @param result The index at which a matching pair was found.
324  *
325  * @return SR_ERR on any parsing error, SR_OK otherwise.
326  */
327 static int array_float_get(gchar *value, const uint64_t array[][2],
328                 int array_len, int *result)
329 {
330         int i;
331         uint64_t f;
332         float s;
333         unsigned int s_int;
334         gchar ss[10], es[10];
335
336         memset(ss, 0, sizeof(ss));
337         memset(es, 0, sizeof(es));
338
339         strncpy(ss, value, 5);
340         strncpy(es, &(value[6]), 3);
341
342         if (sr_atof_ascii(ss, &s) != SR_OK)
343                 return SR_ERR;
344         if (sr_atoi(es, &i) != SR_OK)
345                 return SR_ERR;
346
347         /* Transform e.g. 10^-03 to 1000 as the array stores the inverse. */
348         f = pow(10, abs(i));
349
350         /* Adjust the significand/factor pair to make sure
351          * that f is a multiple of 1000.
352          */
353         while ((int)fmod(log10(f), 3) > 0) { s *= 10; f *= 10; }
354
355         /* Truncate s to circumvent rounding errors. */
356         s_int = (unsigned int)s;
357
358         for (i = 0; i < array_len; i++) {
359                 if ( (s_int == array[i][0]) && (f == array[i][1]) ) {
360                         *result = i;
361                         return SR_OK;
362                 }
363         }
364
365         return SR_ERR;
366 }
367
368 /**
369  * Obtains information about all analog channels from the oscilloscope.
370  * The internal state information is updated accordingly.
371  *
372  * @param scpi An open SCPI connection.
373  * @param config The device's device configuration.
374  * @param state The device's state information.
375  *
376  * @return SR_ERR on error, SR_OK otherwise.
377  */
378 static int analog_channel_state_get(struct sr_scpi_dev_inst *scpi,
379                 struct scope_config *config,
380                 struct scope_state *state)
381 {
382         int i, j;
383         gchar *response;
384
385         for (i = 0; i < config->analog_channels; ++i) {
386
387                 if (dlm_analog_chan_state_get(scpi, i + 1,
388                                 &state->analog_states[i].state) != SR_OK)
389                         return SR_ERR;
390
391                 if (dlm_analog_chan_vdiv_get(scpi, i + 1, &response) != SR_OK)
392                         return SR_ERR;
393
394                 if (array_float_get(response, *config->vdivs, config->num_vdivs,
395                                 &j) != SR_OK) {
396                         g_free(response);
397                         return SR_ERR;
398                 }
399
400                 g_free(response);
401                 state->analog_states[i].vdiv = j;
402
403                 if (dlm_analog_chan_voffs_get(scpi, i + 1,
404                                 &state->analog_states[i].vertical_offset) != SR_OK)
405                         return SR_ERR;
406
407                 if (dlm_analog_chan_wrange_get(scpi, i + 1,
408                                 &state->analog_states[i].waveform_range) != SR_OK)
409                         return SR_ERR;
410
411                 if (dlm_analog_chan_woffs_get(scpi, i + 1,
412                                 &state->analog_states[i].waveform_offset) != SR_OK)
413                         return SR_ERR;
414
415                 if (dlm_analog_chan_coupl_get(scpi, i + 1, &response) != SR_OK) {
416                         g_free(response);
417                         return SR_ERR;
418                 }
419
420                 if (array_option_get(response, config->coupling_options,
421                                 &state->analog_states[i].coupling) != SR_OK) {
422                         g_free(response);
423                         return SR_ERR;
424                 }
425                 g_free(response);
426         }
427
428         return SR_OK;
429 }
430
431 /**
432  * Obtains information about all digital channels from the oscilloscope.
433  * The internal state information is updated accordingly.
434  *
435  * @param scpi An open SCPI connection.
436  * @param config The device's device configuration.
437  * @param state The device's state information.
438  *
439  * @return SR_ERR on error, SR_OK otherwise.
440  */
441 static int digital_channel_state_get(struct sr_scpi_dev_inst *scpi,
442                 struct scope_config *config,
443                 struct scope_state *state)
444 {
445         unsigned int i;
446
447         if (!config->digital_channels)
448                 {
449                         sr_warn("Tried obtaining digital channel states on a " \
450                                         "model without digital inputs.");
451                         return SR_OK;
452                 }
453
454         for (i = 0; i < config->digital_channels; ++i) {
455                 if (dlm_digital_chan_state_get(scpi, i + 1,
456                                 &state->digital_states[i]) != SR_OK) {
457                         return SR_ERR;
458                 }
459         }
460
461         if (!config->pods)
462         {
463                 sr_warn("Tried obtaining pod states on a model without pods.");
464                 return SR_OK;
465         }
466
467         for (i = 0; i < config->pods; ++i) {
468                 if (dlm_digital_pod_state_get(scpi, i + 'A',
469                                 &state->pod_states[i]) != SR_OK)
470                         return SR_ERR;
471         }
472
473         return SR_OK;
474 }
475
476 /**
477  * Obtains information about the sample rate from the oscilloscope.
478  * The internal state information is updated accordingly.
479  *
480  * @param sdi The device instance.
481  *
482  * @return SR_ERR on error, SR_OK otherwise.
483  */
484 SR_PRIV int dlm_sample_rate_query(const struct sr_dev_inst *sdi)
485 {
486         struct dev_context *devc;
487         struct scope_state *state;
488         float tmp_float;
489
490         devc = sdi->priv;
491         state = devc->model_state;
492
493         /* No need to find an active channel to query the sample rate:
494          * querying any channel will do, so we use channel 1 all the time.
495          */
496         if (dlm_analog_chan_srate_get(sdi->conn, 1, &tmp_float) != SR_OK)
497                 return SR_ERR;
498
499         state->sample_rate = tmp_float;
500
501         return SR_OK;
502 }
503
504 /**
505  * Obtains information about the current device state from the oscilloscope,
506  * including all analog and digital channel configurations.
507  * The internal state information is updated accordingly.
508  *
509  * @param sdi The device instance.
510  *
511  * @return SR_ERR on error, SR_OK otherwise.
512  */
513 SR_PRIV int dlm_scope_state_query(struct sr_dev_inst *sdi)
514 {
515         struct dev_context *devc;
516         struct scope_state *state;
517         struct scope_config *config;
518         float tmp_float;
519         gchar *response;
520         int i;
521
522         devc = sdi->priv;
523         config = devc->model_config;
524         state = devc->model_state;
525
526         if (analog_channel_state_get(sdi->conn, config, state) != SR_OK)
527                 return SR_ERR;
528
529         if (digital_channel_state_get(sdi->conn, config, state) != SR_OK)
530                 return SR_ERR;
531
532         if (dlm_timebase_get(sdi->conn, &response) != SR_OK)
533                 return SR_ERR;
534
535         if (array_float_get(response, *config->timebases,
536                         config->num_timebases, &i) != SR_OK) {
537                 g_free(response);
538                 return SR_ERR;
539         }
540
541         g_free(response);
542         state->timebase = i;
543
544         if (dlm_horiz_trigger_pos_get(sdi->conn, &tmp_float) != SR_OK)
545                 return SR_ERR;
546
547         /* TODO: Check if the calculation makes sense for the DLM. */
548         state->horiz_triggerpos = tmp_float /
549                         (((double)(*config->timebases)[state->timebase][0] /
550                         (*config->timebases)[state->timebase][1]) * config->num_xdivs);
551         state->horiz_triggerpos -= 0.5;
552         state->horiz_triggerpos *= -1;
553
554         if (dlm_trigger_source_get(sdi->conn, &response) != SR_OK) {
555                 g_free(response);
556                 return SR_ERR;
557         }
558
559         if (array_option_get(response, config->trigger_sources,
560                         &state->trigger_source) != SR_OK) {
561                 g_free(response);
562                 return SR_ERR;
563         }
564
565         g_free(response);
566
567         if (dlm_trigger_slope_get(sdi->conn, &i) != SR_OK)
568                 return SR_ERR;
569
570         state->trigger_slope = i;
571
572         if (dlm_acq_length_get(sdi->conn, &state->samples_per_frame) != SR_OK) {
573                 sr_err("Failed to query acquisition length.");
574                 return SR_ERR;
575         }
576
577         dlm_sample_rate_query(sdi);
578
579         scope_state_dump(config, state);
580
581         return SR_OK;
582 }
583
584 /**
585  * Creates a new device state structure.
586  *
587  * @param config The device configuration to use.
588  *
589  * @return The newly allocated scope_state struct.
590  */
591 static struct scope_state *dlm_scope_state_new(struct scope_config *config)
592 {
593         struct scope_state *state;
594
595         state = g_malloc0(sizeof(struct scope_state));
596
597         state->analog_states = g_malloc0(config->analog_channels *
598                         sizeof(struct analog_channel_state));
599
600         state->digital_states = g_malloc0(config->digital_channels *
601                         sizeof(gboolean));
602
603         state->pod_states = g_malloc0(config->pods * sizeof(gboolean));
604
605         return state;
606 }
607
608 /**
609  * Frees the memory that was allocated by a call to dlm_scope_state_new().
610  *
611  * @param state The device state structure whose memory is to be freed.
612  */
613 SR_PRIV void dlm_scope_state_destroy(struct scope_state *state)
614 {
615         g_free(state->analog_states);
616         g_free(state->digital_states);
617         g_free(state->pod_states);
618         g_free(state);
619 }
620
621 SR_PRIV int dlm_model_get(char *model_id, char **model_name, int *model_index)
622 {
623         unsigned int i, j;
624
625         *model_index = -1;
626         *model_name = NULL;
627
628         for (i = 0; i < ARRAY_SIZE(scope_models); i++) {
629                 for (j = 0; scope_models[i].model_id[j]; j++) {
630                         if (!strcmp(model_id, scope_models[i].model_id[j])) {
631                                 *model_index = i;
632                                 *model_name = (char *)scope_models[i].model_name[j];
633                                 break;
634                         }
635                 }
636                 if (*model_index != -1)
637                         break;
638         }
639
640         if (*model_index == -1) {
641                 sr_err("Found unsupported DLM device with model identifier %s.",
642                                 model_id);
643                 return SR_ERR_NA;
644         }
645
646         return SR_OK;
647 }
648
649 /**
650  * Attempts to initialize a DL/DLM device and prepares internal structures
651  * if a suitable device was found.
652  *
653  * @param sdi The device instance.
654  */
655 SR_PRIV int dlm_device_init(struct sr_dev_inst *sdi, int model_index)
656 {
657         char tmp[25];
658         int i;
659         struct sr_channel *ch;
660         struct dev_context *devc;
661
662         devc = sdi->priv;
663
664         devc->analog_groups = g_malloc0(sizeof(struct sr_channel_group*) *
665                         scope_models[model_index].analog_channels);
666
667         devc->digital_groups = g_malloc0(sizeof(struct sr_channel_group*) *
668                         scope_models[model_index].digital_channels);
669
670         /* Add analog channels. */
671         for (i = 0; i < scope_models[model_index].analog_channels; i++) {
672                 ch = sr_channel_new(i, SR_CHANNEL_ANALOG, TRUE,
673                                 (*scope_models[model_index].analog_names)[i]);
674                 sdi->channels = g_slist_append(sdi->channels, ch);
675
676                 devc->analog_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
677
678                 devc->analog_groups[i]->name = g_strdup(
679                                 (char *)(*scope_models[model_index].analog_names)[i]);
680                 devc->analog_groups[i]->channels = g_slist_append(NULL, ch);
681
682                 sdi->channel_groups = g_slist_append(sdi->channel_groups,
683                                 devc->analog_groups[i]);
684         }
685
686         /* Add digital channel groups. */
687         for (i = 0; i < scope_models[model_index].pods; ++i) {
688                 g_snprintf(tmp, sizeof(tmp), "POD%d", i);
689
690                 devc->digital_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
691                 if (!devc->digital_groups[i])
692                         return SR_ERR_MALLOC;
693
694                 devc->digital_groups[i]->name = g_strdup(tmp);
695                 sdi->channel_groups = g_slist_append(sdi->channel_groups,
696                                 devc->digital_groups[i]);
697         }
698
699         /* Add digital channels. */
700         for (i = 0; i < scope_models[model_index].digital_channels; i++) {
701                 ch = sr_channel_new(i, SR_CHANNEL_LOGIC, TRUE,
702                                 (*scope_models[model_index].digital_names)[i]);
703                 sdi->channels = g_slist_append(sdi->channels, ch);
704
705                 devc->digital_groups[i / 8]->channels = g_slist_append(
706                                 devc->digital_groups[i / 8]->channels, ch);
707         }
708         devc->model_config = &scope_models[model_index];
709         devc->frame_limit = 0;
710
711         if (!(devc->model_state = dlm_scope_state_new(devc->model_config)))
712                 return SR_ERR_MALLOC;
713
714         /* Disable non-standard response behavior. */
715         if (dlm_response_headers_set(sdi->conn, FALSE) != SR_OK)
716                 return SR_ERR;
717
718         return SR_OK;
719 }
720
721 SR_PRIV int dlm_channel_data_request(const struct sr_dev_inst *sdi)
722 {
723         struct dev_context *devc;
724         struct sr_channel *ch;
725         int result;
726
727         devc = sdi->priv;
728         ch = devc->current_channel->data;
729
730         switch (ch->type) {
731         case SR_CHANNEL_ANALOG:
732                 result = dlm_analog_data_get(sdi->conn, ch->index + 1);
733                 break;
734         case SR_CHANNEL_LOGIC:
735                 result = dlm_digital_data_get(sdi->conn);
736                 break;
737         default:
738                 sr_err("Invalid channel type encountered (%d).",
739                                 ch->type);
740                 result = SR_ERR;
741         }
742
743         if (result == SR_OK)
744                 devc->data_pending = TRUE;
745         else
746                 devc->data_pending = FALSE;
747
748         return result;
749 }
750
751 /**
752  * Reads and removes the block data header from a given data input.
753  * Format is #ndddd... with n being the number of decimal digits d.
754  * The string dddd... contains the decimal-encoded length of the data.
755  * Example: #9000000013 would yield a length of 13 bytes.
756  *
757  * @param data The input data.
758  * @param len The determined input data length.
759  */
760 static int dlm_block_data_header_process(GArray *data, int *len)
761 {
762         int i, n;
763         gchar s[20];
764
765         if (g_array_index(data, gchar, 0) != '#')
766                 return SR_ERR;
767
768         n = (uint8_t)(g_array_index(data, gchar, 1) - '0');
769
770         for (i = 0; i < n; i++)
771                 s[i] = g_array_index(data, gchar, 2 + i);
772         s[i] = 0;
773
774         if (sr_atoi(s, len) != SR_OK)
775                 return SR_ERR;
776
777         g_array_remove_range(data, 0, 2 + n);
778
779         return SR_OK;
780 }
781
782 /**
783  * Turns raw sample data into voltages and sends them off to the session bus.
784  *
785  * @param data The raw sample data.
786  * @ch_state Pointer to the state of the channel whose data we're processing.
787  * @sdi The device instance.
788  *
789  * @return SR_ERR when data is trucated, SR_OK otherwise.
790  */
791 static int dlm_analog_samples_send(GArray *data,
792                 struct analog_channel_state *ch_state,
793                 struct sr_dev_inst *sdi)
794 {
795         uint32_t i, samples;
796         float voltage, range, offset;
797         GArray *float_data;
798         struct dev_context *devc;
799         struct scope_state *model_state;
800         struct sr_channel *ch;
801         struct sr_datafeed_analog analog;
802         struct sr_datafeed_packet packet;
803
804         devc = sdi->priv;
805         model_state = devc->model_state;
806         samples = model_state->samples_per_frame;
807         ch = devc->current_channel->data;
808
809         if (data->len < samples * sizeof(uint8_t)) {
810                 sr_err("Truncated waveform data packet received.");
811                 return SR_ERR;
812         }
813
814         range  = ch_state->waveform_range;
815         offset = ch_state->waveform_offset;
816
817         /* Convert byte sample to voltage according to
818          * page 269 of the Communication Interface User's Manual.
819          */
820         float_data = g_array_new(FALSE, FALSE, sizeof(float));
821         for (i = 0; i < samples; i++) {
822                 voltage = (float)g_array_index(data, int8_t, i);
823                 voltage = (range * voltage /
824                                 DLM_DIVISION_FOR_BYTE_FORMAT) + offset;
825                 g_array_append_val(float_data, voltage);
826         }
827
828         analog.channels = g_slist_append(NULL, ch);
829         analog.num_samples = float_data->len;
830         analog.data = (float*)float_data->data;
831         analog.mq = SR_MQ_VOLTAGE;
832         analog.unit = SR_UNIT_VOLT;
833         analog.mqflags = 0;
834         packet.type = SR_DF_ANALOG;
835         packet.payload = &analog;
836         sr_session_send(sdi, &packet);
837         g_slist_free(analog.channels);
838
839         g_array_free(float_data, TRUE);
840         g_array_remove_range(data, 0, samples * sizeof(uint8_t));
841
842         return SR_OK;
843 }
844
845 /**
846  * Sends logic sample data off to the session bus.
847  *
848  * @param data The raw sample data.
849  * @ch_state Pointer to the state of the channel whose data we're processing.
850  * @sdi The device instance.
851  *
852  * @return SR_ERR when data is trucated, SR_OK otherwise.
853  */
854 static int dlm_digital_samples_send(GArray *data,
855                 struct sr_dev_inst *sdi)
856 {
857         struct dev_context *devc;
858         struct scope_state *model_state;
859         uint32_t samples;
860         struct sr_datafeed_logic logic;
861         struct sr_datafeed_packet packet;
862
863         devc = sdi->priv;
864         model_state = devc->model_state;
865         samples = model_state->samples_per_frame;
866
867         if (data->len < samples * sizeof(uint8_t)) {
868                 sr_err("Truncated waveform data packet received.");
869                 return SR_ERR;
870         }
871
872         logic.length = samples;
873         logic.unitsize = 1;
874         logic.data = data->data;
875         packet.type = SR_DF_LOGIC;
876         packet.payload = &logic;
877         sr_session_send(sdi, &packet);
878
879         g_array_remove_range(data, 0, samples * sizeof(uint8_t));
880
881         return SR_OK;
882 }
883
884 /**
885  * Attempts to query sample data from the oscilloscope in order to send it
886  * to the session bus for further processing.
887  *
888  * @param fd The file descriptor used as the event source.
889  * @param revents The received events.
890  * @param cb_data Callback data, in this case our device instance.
891  *
892  * @return TRUE in case of success or a recoverable error,
893  *  FALSE when a fatal error was encountered.
894  */
895 SR_PRIV int dlm_data_receive(int fd, int revents, void *cb_data)
896 {
897         struct sr_dev_inst *sdi;
898         struct scope_state *model_state;
899         struct dev_context *devc;
900         struct sr_channel *ch;
901         struct sr_datafeed_packet packet;
902         int chunk_len, num_bytes;
903         static GArray *data = NULL;
904
905         (void)fd;
906         (void)revents;
907
908         if (!(sdi = cb_data))
909                 return FALSE;
910
911         if (!(devc = sdi->priv))
912                 return FALSE;
913
914         if (!(model_state = (struct scope_state*)devc->model_state))
915                 return FALSE;
916
917         /* Are we waiting for a response from the device? */
918         if (!devc->data_pending)
919                 return TRUE;
920
921         /* Check if a new query response is coming our way. */
922         if (!data) {
923                 if (sr_scpi_read_begin(sdi->conn) == SR_OK)
924                         /* The 16 here accounts for the header and EOL. */
925                         data = g_array_sized_new(FALSE, FALSE, sizeof(uint8_t),
926                                         16 + model_state->samples_per_frame);
927                 else
928                         return TRUE;
929         }
930
931         /* Store incoming data. */
932         chunk_len = sr_scpi_read_data(sdi->conn, devc->receive_buffer,
933                         RECEIVE_BUFFER_SIZE);
934         if (chunk_len < 0) {
935                 sr_err("Error while reading data: %d", chunk_len);
936                 goto fail;
937         }
938         g_array_append_vals(data, devc->receive_buffer, chunk_len);
939
940         /* Read the entire query response before processing. */
941         if (!sr_scpi_read_complete(sdi->conn))
942                 return TRUE;
943
944         /* We finished reading and are no longer waiting for data. */
945         devc->data_pending = FALSE;
946
947         /* Signal the beginning of a new frame if this is the first channel. */
948         if (devc->current_channel == devc->enabled_channels) {
949                 packet.type = SR_DF_FRAME_BEGIN;
950                 sr_session_send(sdi, &packet);
951         }
952
953         if (dlm_block_data_header_process(data, &num_bytes) != SR_OK) {
954                 sr_err("Encountered malformed block data header.");
955                 goto fail;
956         }
957
958         if (num_bytes == 0) {
959                 sr_warn("Zero-length waveform data packet received. " \
960                                 "Live mode not supported yet, stopping " \
961                                 "acquisition and retrying.");
962                 /* Don't care about return value here. */
963                 dlm_acquisition_stop(sdi->conn);
964                 g_array_free(data, TRUE);
965                 dlm_channel_data_request(sdi);
966                 return TRUE;
967         }
968
969         ch = devc->current_channel->data;
970         switch (ch->type) {
971         case SR_CHANNEL_ANALOG:
972                 if (dlm_analog_samples_send(data,
973                                 &model_state->analog_states[ch->index],
974                                 sdi) != SR_OK)
975                         goto fail;
976                 break;
977         case SR_CHANNEL_LOGIC:
978                 if (dlm_digital_samples_send(data, sdi) != SR_OK)
979                         goto fail;
980                 break;
981         default:
982                 sr_err("Invalid channel type encountered.");
983                 break;
984         }
985
986         g_array_free(data, TRUE);
987         data = NULL;
988
989         /* Signal the end of this frame if this was the last enabled channel
990          * and set the next enabled channel. Then, request its data.
991          */
992         if (!devc->current_channel->next) {
993                 packet.type = SR_DF_FRAME_END;
994                 sr_session_send(sdi, &packet);
995                 devc->current_channel = devc->enabled_channels;
996
997                 /* As of now we only support importing the current acquisition
998                  * data so we're going to stop at this point.
999                  */
1000                 sdi->driver->dev_acquisition_stop(sdi, cb_data);
1001                 return TRUE;
1002         } else
1003                 devc->current_channel = devc->current_channel->next;
1004
1005         if (dlm_channel_data_request(sdi) != SR_OK) {
1006                 sr_err("Failed to request aquisition data.");
1007                 goto fail;
1008         }
1009
1010         return TRUE;
1011
1012 fail:
1013         if (data) {
1014                 g_array_free(data, TRUE);
1015                 data = NULL;
1016         }
1017
1018         return FALSE;
1019 }