]> sigrok.org Git - libsigrok.git/blob - src/hardware/lecroy-xstream/protocol.c
lecroy-xstream: Use best-effort strategy for unknown models
[libsigrok.git] / src / hardware / lecroy-xstream / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2017 Sven Schnelle <svens@stackframe.org>
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 struct lecroy_wavedesc_2_x {
27         uint16_t comm_type;
28         uint16_t comm_order; /* 1 - little endian */
29         uint32_t wave_descriptor_length;
30         uint32_t user_text_len;
31         uint32_t res_desc1;
32         uint32_t trigtime_array_length;
33         uint32_t ris_time1_array_length;
34         uint32_t res_array1;
35         uint32_t wave_array1_length;
36         uint32_t wave_array2_length;
37         uint32_t wave_array3_length;
38         uint32_t wave_array4_length;
39         char instrument_name[16];
40         uint32_t instrument_number;
41         char trace_label[16];
42         uint32_t reserved;
43         uint32_t wave_array_count;
44         uint32_t points_per_screen;
45         uint32_t first_valid_point;
46         uint32_t last_valid_point;
47         uint32_t first_point;
48         uint32_t sparsing_factor;
49         uint32_t segment_index;
50         uint32_t subarray_count;
51         uint32_t sweeps_per_acq;
52         uint16_t points_per_pair;
53         uint16_t pair_offset;
54         float vertical_gain;
55         float vertical_offset;
56         float max_value;
57         float min_value;
58         uint16_t nominal_bits;
59         uint16_t nom_subarray_count;
60         float horiz_interval;
61         double horiz_offset;
62         double pixel_offset;
63         char vertunit[48];
64         char horunit[48];
65         uint32_t reserved1;
66         double trigger_time;
67 } __attribute__((packed));
68
69 struct lecroy_wavedesc {
70         char descriptor_name[16];
71         char template_name[16];
72         union {
73                 struct lecroy_wavedesc_2_x version_2_x;
74         };
75 } __attribute__((packed));
76
77 static const char *coupling_options[] = {
78         "A1M", // AC with 1 MOhm termination
79         "D50", // DC with 50 Ohm termination
80         "D1M", // DC with 1 MOhm termination
81         "GND",
82         "OVL",
83 };
84
85 static const char *scope_trigger_slopes[] = {
86         "POS", "NEG",
87 };
88
89 static const char *trigger_sources[] = {
90         "C1", "C2", "C3", "C4", "LINE", "EXT",
91 };
92
93 static const uint64_t timebases[][2] = {
94         /* picoseconds */
95         { 20, 1000000000000 },
96         { 50, 1000000000000 },
97         { 100, 1000000000000 },
98         { 200, 1000000000000 },
99         { 500, 1000000000000 },
100         /* nanoseconds */
101         { 1, 1000000000 },
102         { 2, 1000000000 },
103         { 5, 1000000000 },
104         { 10, 1000000000 },
105         { 20, 1000000000 },
106         { 50, 1000000000 },
107         { 100, 1000000000 },
108         { 200, 1000000000 },
109         { 500, 1000000000 },
110         /* microseconds */
111         { 1, 1000000 },
112         { 2, 1000000 },
113         { 5, 1000000 },
114         { 10, 1000000 },
115         { 20, 1000000 },
116         { 50, 1000000 },
117         { 100, 1000000 },
118         { 200, 1000000 },
119         { 500, 1000000 },
120         /* milliseconds */
121         { 1, 1000 },
122         { 2, 1000 },
123         { 5, 1000 },
124         { 10, 1000 },
125         { 20, 1000 },
126         { 50, 1000 },
127         { 100, 1000 },
128         { 200, 1000 },
129         { 500, 1000 },
130         /* seconds */
131         { 1, 1 },
132         { 2, 1 },
133         { 5, 1 },
134         { 10, 1 },
135         { 20, 1 },
136         { 50, 1 },
137         { 100, 1 },
138         { 200, 1 },
139         { 500, 1 },
140         { 1000, 1 },
141 };
142
143 static const uint64_t vdivs[][2] = {
144         /* millivolts */
145         { 1, 1000 },
146         { 2, 1000 },
147         { 5, 1000 },
148         { 10, 1000 },
149         { 20, 1000 },
150         { 50, 1000 },
151         { 100, 1000 },
152         { 200, 1000 },
153         { 500, 1000 },
154         /* volts */
155         { 1, 1 },
156         { 2, 1 },
157         { 5, 1 },
158         { 10, 1 },
159         { 20, 1 },
160         { 50, 1 },
161 };
162
163 static const char *scope_analog_channel_names[] = {
164         "CH1", "CH2", "CH3", "CH4",
165 };
166
167 static const struct scope_config scope_models[] = {
168         {
169                  /* Default config */
170                 .name = {NULL},
171
172                 .analog_channels = 4,
173                 .analog_names = &scope_analog_channel_names,
174
175                 .coupling_options = &coupling_options,
176                 .num_coupling_options = ARRAY_SIZE(coupling_options),
177
178                 .trigger_sources = &trigger_sources,
179                 .num_trigger_sources = ARRAY_SIZE(trigger_sources),
180
181                 .trigger_slopes = &scope_trigger_slopes,
182                 .num_trigger_slopes = ARRAY_SIZE(scope_trigger_slopes),
183
184                 .timebases = &timebases,
185                 .num_timebases = ARRAY_SIZE(timebases),
186
187                 .vdivs = &vdivs,
188                 .num_vdivs = ARRAY_SIZE(vdivs),
189
190                 .num_xdivs = 10,
191                 .num_ydivs = 8,
192         },
193 };
194
195 static void scope_state_dump(const struct scope_config *config,
196                              struct scope_state *state)
197 {
198         unsigned int i;
199         char *tmp;
200
201         for (i = 0; i < config->analog_channels; i++) {
202                 tmp = sr_voltage_string((*config->vdivs)[state->analog_channels[i].vdiv][0],
203                                         (*config->vdivs)[state->analog_channels[i].vdiv][1]);
204                 sr_info("State of analog channel %d -> %s : %s (coupling) %s (vdiv) %2.2e (offset)",
205                         i + 1, state->analog_channels[i].state ? "On" : "Off",
206                         (*config->coupling_options)[state->analog_channels[i].coupling],
207                         tmp, state->analog_channels[i].vertical_offset);
208         }
209
210         tmp = sr_period_string((*config->timebases)[state->timebase][0],
211                                 (*config->timebases)[state->timebase][1]);
212         sr_info("Current timebase: %s", tmp);
213         g_free(tmp);
214
215         tmp = sr_samplerate_string(state->sample_rate);
216         sr_info("Current samplerate: %s", tmp);
217         g_free(tmp);
218
219         sr_info("Current trigger: %s (source), %s (slope) %.2f (offset)",
220                 (*config->trigger_sources)[state->trigger_source],
221                 (*config->trigger_slopes)[state->trigger_slope],
222                 state->horiz_triggerpos);
223 }
224
225 static int scope_state_get_array_option(const char *resp,
226         const char *(*array)[], unsigned int n, int *result)
227 {
228         unsigned int i;
229
230         for (i = 0; i < n; i++) {
231                 if (!g_strcmp0(resp, (*array)[i])) {
232                         *result = i;
233                         return SR_OK;
234                 }
235         }
236
237         return SR_ERR;
238 }
239
240 /**
241  * This function takes a value of the form "2.000E-03" and returns the index
242  * of an array where a matching pair was found.
243  *
244  * @param value The string to be parsed.
245  * @param array The array of s/f pairs.
246  * @param array_len The number of pairs in the array.
247  * @param result The index at which a matching pair was found.
248  *
249  * @return SR_ERR on any parsing error, SR_OK otherwise.
250  */
251 static int array_float_get(gchar *value, const uint64_t array[][2],
252                 int array_len, unsigned int *result)
253 {
254         struct sr_rational rval;
255         struct sr_rational aval;
256
257         if (sr_parse_rational(value, &rval) != SR_OK)
258                 return SR_ERR;
259
260         for (int i = 0; i < array_len; i++) {
261                 sr_rational_set(&aval, array[i][0], array[i][1]);
262                 if (sr_rational_eq(&rval, &aval)) {
263                         *result = i;
264                         return SR_OK;
265                 }
266         }
267
268         return SR_ERR;
269 }
270
271 static int analog_channel_state_get(struct sr_scpi_dev_inst *scpi,
272                                     const struct scope_config *config,
273                                     struct scope_state *state)
274 {
275         unsigned int i, j;
276         char command[MAX_COMMAND_SIZE];
277         char *tmp_str;
278
279         for (i = 0; i < config->analog_channels; i++) {
280                 g_snprintf(command, sizeof(command), "C%d:TRACE?", i + 1);
281
282                 if (sr_scpi_get_bool(scpi, command,
283                                 &state->analog_channels[i].state) != SR_OK)
284                         return SR_ERR;
285
286                 g_snprintf(command, sizeof(command), "C%d:VDIV?", i + 1);
287
288                 if (sr_scpi_get_string(scpi, command, &tmp_str) != SR_OK)
289                         return SR_ERR;
290
291                 if (array_float_get(tmp_str, ARRAY_AND_SIZE(vdivs), &j) != SR_OK) {
292                         g_free(tmp_str);
293                         sr_err("Could not determine array index for vertical div scale.");
294                         return SR_ERR;
295                 }
296
297                 g_free(tmp_str);
298                 state->analog_channels[i].vdiv = j;
299
300                 g_snprintf(command, sizeof(command), "C%d:OFFSET?", i + 1);
301
302                 if (sr_scpi_get_float(scpi, command, &state->analog_channels[i].vertical_offset) != SR_OK)
303                         return SR_ERR;
304
305                 g_snprintf(command, sizeof(command), "C%d:COUPLING?", i + 1);
306
307                 if (sr_scpi_get_string(scpi, command, &tmp_str) != SR_OK)
308                         return SR_ERR;
309
310
311                 if (scope_state_get_array_option(tmp_str, config->coupling_options,
312                                  config->num_coupling_options,
313                                  &state->analog_channels[i].coupling) != SR_OK)
314                         return SR_ERR;
315
316                 g_free(tmp_str);
317         }
318
319         return SR_OK;
320 }
321
322 SR_PRIV int lecroy_xstream_update_sample_rate(const struct sr_dev_inst *sdi)
323 {
324         struct dev_context *devc;
325         struct scope_state *state;
326         const struct scope_config *config;
327         float memsize, timediv;
328
329         devc = sdi->priv;
330         state = devc->model_state;
331         config = devc->model_config;
332
333         if (sr_scpi_get_float(sdi->conn, "MEMORY_SIZE?", &memsize) != SR_OK)
334                 return SR_ERR;
335
336         if (sr_scpi_get_float(sdi->conn, "TIME_DIV?", &timediv) != SR_OK)
337                 return SR_ERR;
338
339         state->sample_rate = 1 / ((timediv * config->num_xdivs) / memsize);
340
341         return SR_OK;
342 }
343
344 SR_PRIV int lecroy_xstream_state_get(struct sr_dev_inst *sdi)
345 {
346         struct dev_context *devc;
347         struct scope_state *state;
348         const struct scope_config *config;
349         unsigned int i;
350         char *tmp_str, *tmp_str2, *tmpp, *p, *key;
351         char command[MAX_COMMAND_SIZE];
352         char *trig_source = NULL;
353
354         devc = sdi->priv;
355         config = devc->model_config;
356         state = devc->model_state;
357
358         sr_info("Fetching scope state");
359
360         if (analog_channel_state_get(sdi->conn, config, state) != SR_OK)
361                 return SR_ERR;
362
363         if (sr_scpi_get_string(sdi->conn, "TIME_DIV?", &tmp_str) != SR_OK)
364                 return SR_ERR;
365
366         if (array_float_get(tmp_str, ARRAY_AND_SIZE(timebases), &i) != SR_OK) {
367                 g_free(tmp_str);
368                 sr_err("Could not determine array index for timbase scale.");
369                 return SR_ERR;
370         }
371         g_free(tmp_str);
372         state->timebase = i;
373
374         if (sr_scpi_get_string(sdi->conn, "TRIG_SELECT?", &tmp_str) != SR_OK)
375                 return SR_ERR;
376
377         key = tmpp = NULL;
378         tmp_str2 = tmp_str;
379         i = 0;
380         while ((p = strtok_r(tmp_str2, ",", &tmpp))) {
381                 tmp_str2 = NULL;
382                 if (i == 0) {
383                         /* trigger type */
384                 } else if (i & 1) {
385                         key = p;
386                         /* key */
387                 } else if (!(i & 1)) {
388                         if (!strcmp(key, "SR"))
389                                 trig_source = p;
390                 }
391                 i++;
392         }
393
394         if (!trig_source || scope_state_get_array_option(trig_source, config->trigger_sources, config->num_trigger_sources, &state->trigger_source) != SR_OK)
395                 return SR_ERR;
396
397         g_snprintf(command, sizeof(command), "%s:TRIG_SLOPE?", trig_source);
398         if (sr_scpi_get_string(sdi->conn, command, &tmp_str) != SR_OK)
399                 return SR_ERR;
400
401         if (scope_state_get_array_option(tmp_str,
402                 config->trigger_slopes, config->num_trigger_slopes, &state->trigger_slope) != SR_OK)
403                 return SR_ERR;
404
405         if (sr_scpi_get_float(sdi->conn, "TRIG_DELAY?", &state->horiz_triggerpos) != SR_OK)
406                 return SR_ERR;
407
408         if (lecroy_xstream_update_sample_rate(sdi) != SR_OK)
409                 return SR_ERR;
410
411         sr_info("Fetching finished.");
412
413         scope_state_dump(config, state);
414
415         return SR_OK;
416 }
417
418 static struct scope_state *scope_state_new(const struct scope_config *config)
419 {
420         struct scope_state *state;
421
422         state = g_malloc0(sizeof(struct scope_state));
423         state->analog_channels = g_malloc0_n(config->analog_channels,
424                         sizeof(struct analog_channel_state));
425         return state;
426 }
427
428 SR_PRIV void lecroy_xstream_state_free(struct scope_state *state)
429 {
430         g_free(state->analog_channels);
431         g_free(state);
432 }
433
434 SR_PRIV int lecroy_xstream_init_device(struct sr_dev_inst *sdi)
435 {
436         char command[MAX_COMMAND_SIZE];
437         int model_index;
438         unsigned int i, j;
439         struct sr_channel *ch;
440         struct dev_context *devc;
441         gboolean channel_enabled;
442
443         devc = sdi->priv;
444         model_index = -1;
445
446         /* Find the exact model. */
447         for (i = 0; i < ARRAY_SIZE(scope_models); i++) {
448                 for (j = 0; scope_models[i].name[j]; j++) {
449                         if (!strcmp(sdi->model, scope_models[i].name[j])) {
450                                 model_index = i;
451                                 break;
452                         }
453                 }
454                 if (model_index != -1)
455                         break;
456         }
457
458         if (model_index == -1) {
459                 sr_dbg("Unknown LeCroy device, using default config.");
460                 for (i = 0; i < ARRAY_SIZE(scope_models); i++)
461                         if (scope_models[i].name[0] == NULL)
462                                 model_index = i;
463         }
464
465         /* Set the desired response and format modes. */
466         sr_scpi_send(sdi->conn, "COMM_HEADER OFF");
467         sr_scpi_send(sdi->conn, "COMM_FORMAT OFF,WORD,BIN");
468
469         devc->analog_groups = g_malloc0(sizeof(struct sr_channel_group*) *
470                                 scope_models[model_index].analog_channels);
471
472         /* Add analog channels. */
473         for (i = 0; i < scope_models[model_index].analog_channels; i++) {
474                 g_snprintf(command, sizeof(command), "C%d:TRACE?", i + 1);
475
476                 if (sr_scpi_get_bool(sdi->conn, command, &channel_enabled) != SR_OK)
477                         return SR_ERR;
478
479                 g_snprintf(command, sizeof(command), "C%d:VDIV?", i + 1);
480
481                 ch = sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, channel_enabled,
482                            (*scope_models[model_index].analog_names)[i]);
483
484                 devc->analog_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
485
486                 devc->analog_groups[i]->name = g_strdup(
487                         (char *)(*scope_models[model_index].analog_names)[i]);
488                 devc->analog_groups[i]->channels = g_slist_append(NULL, ch);
489
490                 sdi->channel_groups = g_slist_append(sdi->channel_groups,
491                                                    devc->analog_groups[i]);
492         }
493
494         devc->model_config = &scope_models[model_index];
495         devc->frame_limit = 0;
496
497         if (!(devc->model_state = scope_state_new(devc->model_config)))
498                 return SR_ERR_MALLOC;
499
500         return SR_OK;
501 }
502
503 static int lecroy_waveform_2_x_to_analog(GByteArray *data,
504                                          struct lecroy_wavedesc *desc,
505                                          struct sr_datafeed_analog *analog)
506 {
507         struct sr_analog_encoding *encoding = analog->encoding;
508         struct sr_analog_meaning *meaning = analog->meaning;
509         struct sr_analog_spec *spec = analog->spec;
510         float *data_float;
511         int16_t *waveform_data;
512         unsigned int i, num_samples;
513
514         data_float = g_malloc(desc->version_2_x.wave_array_count * sizeof(float));
515         num_samples = desc->version_2_x.wave_array_count;
516
517         waveform_data = (int16_t *)(data->data +
518                                     + desc->version_2_x.wave_descriptor_length
519                                     + desc->version_2_x.user_text_len);
520
521         for (i = 0; i < num_samples; i++)
522                 data_float[i] = (float)waveform_data[i]
523                         * desc->version_2_x.vertical_gain
524                         + desc->version_2_x.vertical_offset;
525
526         analog->data = data_float;
527         analog->num_samples = num_samples;
528
529         encoding->unitsize = sizeof(float);
530         encoding->is_signed = TRUE;
531         encoding->is_float = TRUE;
532         encoding->is_bigendian = FALSE;
533         encoding->scale.p = 1;
534         encoding->scale.q = 1;
535         encoding->offset.p = 0;
536         encoding->offset.q = 1;
537
538         encoding->digits = 6;
539         encoding->is_digits_decimal = FALSE;
540
541         if (strcmp(desc->version_2_x.vertunit, "A")) {
542                 meaning->mq = SR_MQ_CURRENT;
543                 meaning->unit = SR_UNIT_AMPERE;
544         } else {
545                 /* Default to voltage. */
546                 meaning->mq = SR_MQ_VOLTAGE;
547                 meaning->unit = SR_UNIT_VOLT;
548         }
549
550         meaning->mqflags = 0;
551         spec->spec_digits = 3;
552
553         return SR_OK;
554 }
555
556 static int lecroy_waveform_to_analog(GByteArray *data,
557                                      struct sr_datafeed_analog *analog)
558 {
559         struct lecroy_wavedesc *desc;
560
561         if (data->len < sizeof(struct lecroy_wavedesc))
562                 return SR_ERR;
563
564         desc = (struct lecroy_wavedesc *)data->data;
565
566         if (!strncmp(desc->template_name, "LECROY_2_2", 16) ||
567             !strncmp(desc->template_name, "LECROY_2_3", 16)) {
568                 return lecroy_waveform_2_x_to_analog(data, desc, analog);
569         }
570
571         sr_err("Waveformat template '%.16s' not supported.",
572                desc->template_name);
573
574         return SR_ERR;
575 }
576
577 SR_PRIV int lecroy_xstream_receive_data(int fd, int revents, void *cb_data)
578 {
579         struct sr_channel *ch;
580         struct sr_dev_inst *sdi;
581         struct dev_context *devc;
582         struct sr_datafeed_packet packet;
583         GByteArray *data;
584         struct sr_datafeed_analog analog;
585         struct sr_analog_encoding encoding;
586         struct sr_analog_meaning meaning;
587         struct sr_analog_spec spec;
588         char buf[8];
589
590         (void)fd;
591         (void)revents;
592
593         data = NULL;
594
595         if (!(sdi = cb_data))
596                 return TRUE;
597
598         if (!(devc = sdi->priv))
599                 return TRUE;
600
601         ch = devc->current_channel->data;
602
603         /*
604          * Send "frame begin" packet upon reception of data for the
605          * first enabled channel.
606          */
607         if (devc->current_channel == devc->enabled_channels) {
608                 packet.type = SR_DF_FRAME_BEGIN;
609                 sr_session_send(sdi, &packet);
610         }
611
612         if (ch->type != SR_CHANNEL_ANALOG)
613                 return SR_ERR;
614
615         /* Pass on the received data of the channel(s). */
616         if (sr_scpi_read_data(sdi->conn, buf, 4) != 4) {
617                 sr_err("Reading header failed.");
618                 return TRUE;
619         }
620
621         if (sr_scpi_get_block(sdi->conn, NULL, &data) != SR_OK) {
622                 if (data)
623                         g_byte_array_free(data, TRUE);
624                 return TRUE;
625         }
626
627         analog.encoding = &encoding;
628         analog.meaning = &meaning;
629         analog.spec = &spec;
630
631         if (lecroy_waveform_to_analog(data, &analog) != SR_OK)
632                 return SR_ERR;
633
634         meaning.channels = g_slist_append(NULL, ch);
635         packet.payload = &analog;
636         packet.type = SR_DF_ANALOG;
637         sr_session_send(sdi, &packet);
638
639         g_byte_array_free(data, TRUE);
640         data = NULL;
641
642         g_slist_free(meaning.channels);
643         g_free(analog.data);
644
645         /*
646          * Advance to the next enabled channel. When data for all enabled
647          * channels was received, then flush potentially queued logic data,
648          * and send the "frame end" packet.
649          */
650         if (devc->current_channel->next) {
651                 devc->current_channel = devc->current_channel->next;
652                 lecroy_xstream_request_data(sdi);
653                 return TRUE;
654         }
655
656         packet.type = SR_DF_FRAME_END;
657         sr_session_send(sdi, &packet);
658
659         /*
660          * End of frame was reached. Stop acquisition after the specified
661          * number of frames, or continue reception by starting over at
662          * the first enabled channel.
663          */
664         if (++devc->num_frames == devc->frame_limit) {
665                 sr_dev_acquisition_stop(sdi);
666         } else {
667                 devc->current_channel = devc->enabled_channels;
668                 lecroy_xstream_request_data(sdi);
669         }
670
671         return TRUE;
672 }