]> sigrok.org Git - libsigrok.git/blob - src/hardware/yokogawa-dlm/protocol.c
Fix a bunch of typos.
[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_HDIV | 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 const 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(const 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                 const 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                 const 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         const 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(const 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(sdi, i, SR_CHANNEL_ANALOG, TRUE,
673                                 (*scope_models[model_index].analog_names)[i]);
674
675                 devc->analog_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
676
677                 devc->analog_groups[i]->name = g_strdup(
678                                 (char *)(*scope_models[model_index].analog_names)[i]);
679                 devc->analog_groups[i]->channels = g_slist_append(NULL, ch);
680
681                 sdi->channel_groups = g_slist_append(sdi->channel_groups,
682                                 devc->analog_groups[i]);
683         }
684
685         /* Add digital channel groups. */
686         for (i = 0; i < scope_models[model_index].pods; ++i) {
687                 g_snprintf(tmp, sizeof(tmp), "POD%d", i);
688
689                 devc->digital_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
690                 if (!devc->digital_groups[i])
691                         return SR_ERR_MALLOC;
692
693                 devc->digital_groups[i]->name = g_strdup(tmp);
694                 sdi->channel_groups = g_slist_append(sdi->channel_groups,
695                                 devc->digital_groups[i]);
696         }
697
698         /* Add digital channels. */
699         for (i = 0; i < scope_models[model_index].digital_channels; i++) {
700                 ch = sr_channel_new(sdi, i, SR_CHANNEL_LOGIC, TRUE,
701                                 (*scope_models[model_index].digital_names)[i]);
702
703                 devc->digital_groups[i / 8]->channels = g_slist_append(
704                                 devc->digital_groups[i / 8]->channels, ch);
705         }
706         devc->model_config = &scope_models[model_index];
707         devc->frame_limit = 0;
708
709         if (!(devc->model_state = dlm_scope_state_new(devc->model_config)))
710                 return SR_ERR_MALLOC;
711
712         /* Disable non-standard response behavior. */
713         if (dlm_response_headers_set(sdi->conn, FALSE) != SR_OK)
714                 return SR_ERR;
715
716         return SR_OK;
717 }
718
719 SR_PRIV int dlm_channel_data_request(const struct sr_dev_inst *sdi)
720 {
721         struct dev_context *devc;
722         struct sr_channel *ch;
723         int result;
724
725         devc = sdi->priv;
726         ch = devc->current_channel->data;
727
728         switch (ch->type) {
729         case SR_CHANNEL_ANALOG:
730                 result = dlm_analog_data_get(sdi->conn, ch->index + 1);
731                 break;
732         case SR_CHANNEL_LOGIC:
733                 result = dlm_digital_data_get(sdi->conn);
734                 break;
735         default:
736                 sr_err("Invalid channel type encountered (%d).",
737                                 ch->type);
738                 result = SR_ERR;
739         }
740
741         if (result == SR_OK)
742                 devc->data_pending = TRUE;
743         else
744                 devc->data_pending = FALSE;
745
746         return result;
747 }
748
749 /**
750  * Reads and removes the block data header from a given data input.
751  * Format is #ndddd... with n being the number of decimal digits d.
752  * The string dddd... contains the decimal-encoded length of the data.
753  * Example: #9000000013 would yield a length of 13 bytes.
754  *
755  * @param data The input data.
756  * @param len The determined input data length.
757  */
758 static int dlm_block_data_header_process(GArray *data, int *len)
759 {
760         int i, n;
761         gchar s[20];
762
763         if (g_array_index(data, gchar, 0) != '#')
764                 return SR_ERR;
765
766         n = (uint8_t)(g_array_index(data, gchar, 1) - '0');
767
768         for (i = 0; i < n; i++)
769                 s[i] = g_array_index(data, gchar, 2 + i);
770         s[i] = 0;
771
772         if (sr_atoi(s, len) != SR_OK)
773                 return SR_ERR;
774
775         g_array_remove_range(data, 0, 2 + n);
776
777         return SR_OK;
778 }
779
780 /**
781  * Turns raw sample data into voltages and sends them off to the session bus.
782  *
783  * @param data The raw sample data.
784  * @ch_state Pointer to the state of the channel whose data we're processing.
785  * @sdi The device instance.
786  *
787  * @return SR_ERR when data is trucated, SR_OK otherwise.
788  */
789 static int dlm_analog_samples_send(GArray *data,
790                 struct analog_channel_state *ch_state,
791                 struct sr_dev_inst *sdi)
792 {
793         uint32_t i, samples;
794         float voltage, range, offset;
795         GArray *float_data;
796         struct dev_context *devc;
797         struct scope_state *model_state;
798         struct sr_channel *ch;
799         struct sr_datafeed_analog analog;
800         struct sr_datafeed_packet packet;
801
802         devc = sdi->priv;
803         model_state = devc->model_state;
804         samples = model_state->samples_per_frame;
805         ch = devc->current_channel->data;
806
807         if (data->len < samples * sizeof(uint8_t)) {
808                 sr_err("Truncated waveform data packet received.");
809                 return SR_ERR;
810         }
811
812         range  = ch_state->waveform_range;
813         offset = ch_state->waveform_offset;
814
815         /* Convert byte sample to voltage according to
816          * page 269 of the Communication Interface User's Manual.
817          */
818         float_data = g_array_new(FALSE, FALSE, sizeof(float));
819         for (i = 0; i < samples; i++) {
820                 voltage = (float)g_array_index(data, int8_t, i);
821                 voltage = (range * voltage /
822                                 DLM_DIVISION_FOR_BYTE_FORMAT) + offset;
823                 g_array_append_val(float_data, voltage);
824         }
825
826         analog.channels = g_slist_append(NULL, ch);
827         analog.num_samples = float_data->len;
828         analog.data = (float*)float_data->data;
829         analog.mq = SR_MQ_VOLTAGE;
830         analog.unit = SR_UNIT_VOLT;
831         analog.mqflags = 0;
832         packet.type = SR_DF_ANALOG;
833         packet.payload = &analog;
834         sr_session_send(sdi, &packet);
835         g_slist_free(analog.channels);
836
837         g_array_free(float_data, TRUE);
838         g_array_remove_range(data, 0, samples * sizeof(uint8_t));
839
840         return SR_OK;
841 }
842
843 /**
844  * Sends logic sample data off to the session bus.
845  *
846  * @param data The raw sample data.
847  * @ch_state Pointer to the state of the channel whose data we're processing.
848  * @sdi The device instance.
849  *
850  * @return SR_ERR when data is trucated, SR_OK otherwise.
851  */
852 static int dlm_digital_samples_send(GArray *data,
853                 struct sr_dev_inst *sdi)
854 {
855         struct dev_context *devc;
856         struct scope_state *model_state;
857         uint32_t samples;
858         struct sr_datafeed_logic logic;
859         struct sr_datafeed_packet packet;
860
861         devc = sdi->priv;
862         model_state = devc->model_state;
863         samples = model_state->samples_per_frame;
864
865         if (data->len < samples * sizeof(uint8_t)) {
866                 sr_err("Truncated waveform data packet received.");
867                 return SR_ERR;
868         }
869
870         logic.length = samples;
871         logic.unitsize = 1;
872         logic.data = data->data;
873         packet.type = SR_DF_LOGIC;
874         packet.payload = &logic;
875         sr_session_send(sdi, &packet);
876
877         g_array_remove_range(data, 0, samples * sizeof(uint8_t));
878
879         return SR_OK;
880 }
881
882 /**
883  * Attempts to query sample data from the oscilloscope in order to send it
884  * to the session bus for further processing.
885  *
886  * @param fd The file descriptor used as the event source.
887  * @param revents The received events.
888  * @param cb_data Callback data, in this case our device instance.
889  *
890  * @return TRUE in case of success or a recoverable error,
891  *  FALSE when a fatal error was encountered.
892  */
893 SR_PRIV int dlm_data_receive(int fd, int revents, void *cb_data)
894 {
895         struct sr_dev_inst *sdi;
896         struct scope_state *model_state;
897         struct dev_context *devc;
898         struct sr_channel *ch;
899         struct sr_datafeed_packet packet;
900         int chunk_len, num_bytes;
901         static GArray *data = NULL;
902
903         (void)fd;
904         (void)revents;
905
906         if (!(sdi = cb_data))
907                 return FALSE;
908
909         if (!(devc = sdi->priv))
910                 return FALSE;
911
912         if (!(model_state = (struct scope_state*)devc->model_state))
913                 return FALSE;
914
915         /* Are we waiting for a response from the device? */
916         if (!devc->data_pending)
917                 return TRUE;
918
919         /* Check if a new query response is coming our way. */
920         if (!data) {
921                 if (sr_scpi_read_begin(sdi->conn) == SR_OK)
922                         /* The 16 here accounts for the header and EOL. */
923                         data = g_array_sized_new(FALSE, FALSE, sizeof(uint8_t),
924                                         16 + model_state->samples_per_frame);
925                 else
926                         return TRUE;
927         }
928
929         /* Store incoming data. */
930         chunk_len = sr_scpi_read_data(sdi->conn, devc->receive_buffer,
931                         RECEIVE_BUFFER_SIZE);
932         if (chunk_len < 0) {
933                 sr_err("Error while reading data: %d", chunk_len);
934                 goto fail;
935         }
936         g_array_append_vals(data, devc->receive_buffer, chunk_len);
937
938         /* Read the entire query response before processing. */
939         if (!sr_scpi_read_complete(sdi->conn))
940                 return TRUE;
941
942         /* We finished reading and are no longer waiting for data. */
943         devc->data_pending = FALSE;
944
945         /* Signal the beginning of a new frame if this is the first channel. */
946         if (devc->current_channel == devc->enabled_channels) {
947                 packet.type = SR_DF_FRAME_BEGIN;
948                 sr_session_send(sdi, &packet);
949         }
950
951         if (dlm_block_data_header_process(data, &num_bytes) != SR_OK) {
952                 sr_err("Encountered malformed block data header.");
953                 goto fail;
954         }
955
956         if (num_bytes == 0) {
957                 sr_warn("Zero-length waveform data packet received. " \
958                                 "Live mode not supported yet, stopping " \
959                                 "acquisition and retrying.");
960                 /* Don't care about return value here. */
961                 dlm_acquisition_stop(sdi->conn);
962                 g_array_free(data, TRUE);
963                 dlm_channel_data_request(sdi);
964                 return TRUE;
965         }
966
967         ch = devc->current_channel->data;
968         switch (ch->type) {
969         case SR_CHANNEL_ANALOG:
970                 if (dlm_analog_samples_send(data,
971                                 &model_state->analog_states[ch->index],
972                                 sdi) != SR_OK)
973                         goto fail;
974                 break;
975         case SR_CHANNEL_LOGIC:
976                 if (dlm_digital_samples_send(data, sdi) != SR_OK)
977                         goto fail;
978                 break;
979         default:
980                 sr_err("Invalid channel type encountered.");
981                 break;
982         }
983
984         g_array_free(data, TRUE);
985         data = NULL;
986
987         /* Signal the end of this frame if this was the last enabled channel
988          * and set the next enabled channel. Then, request its data.
989          */
990         if (!devc->current_channel->next) {
991                 packet.type = SR_DF_FRAME_END;
992                 sr_session_send(sdi, &packet);
993                 devc->current_channel = devc->enabled_channels;
994
995                 /* As of now we only support importing the current acquisition
996                  * data so we're going to stop at this point.
997                  */
998                 sdi->driver->dev_acquisition_stop(sdi, cb_data);
999                 return TRUE;
1000         } else
1001                 devc->current_channel = devc->current_channel->next;
1002
1003         if (dlm_channel_data_request(sdi) != SR_OK) {
1004                 sr_err("Failed to request acquisition data.");
1005                 goto fail;
1006         }
1007
1008         return TRUE;
1009
1010 fail:
1011         if (data) {
1012                 g_array_free(data, TRUE);
1013                 data = NULL;
1014         }
1015
1016         return FALSE;
1017 }