]> sigrok.org Git - libsigrok.git/blob - hardware/kecheng-kc-330b/api.c
kecheng-kc-330b: Code cleanup
[libsigrok.git] / hardware / kecheng-kc-330b / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <string.h>
21 #include "protocol.h"
22
23 #define USB_CONN "1041.8101"
24 #define VENDOR "Kecheng"
25 #define USB_INTERFACE 0
26
27 static const int32_t hwcaps[] = {
28         SR_CONF_SOUNDLEVELMETER,
29         SR_CONF_LIMIT_SAMPLES,
30         SR_CONF_CONTINUOUS,
31         SR_CONF_DATALOG,
32         SR_CONF_SPL_WEIGHT_FREQ,
33         SR_CONF_SPL_WEIGHT_TIME,
34         SR_CONF_DATA_SOURCE,
35 };
36
37 SR_PRIV const uint64_t kecheng_kc_330b_sample_intervals[][2] = {
38         { 1, 8 },
39         { 1, 2 },
40         { 1, 1 },
41         { 2, 1 },
42         { 5, 1 },
43         { 10, 1 },
44         { 60, 1 },
45 };
46
47 static const char *weight_freq[] = {
48         "A",
49         "C",
50 };
51
52 static const char *weight_time[] = {
53         "F",
54         "S",
55 };
56
57 static const char *data_sources[] = {
58         "Live",
59         "Memory",
60 };
61
62 SR_PRIV struct sr_dev_driver kecheng_kc_330b_driver_info;
63 static struct sr_dev_driver *di = &kecheng_kc_330b_driver_info;
64
65
66 static int init(struct sr_context *sr_ctx)
67 {
68         return std_init(sr_ctx, di, LOG_PREFIX);
69 }
70
71 static int scan_kecheng(struct sr_usb_dev_inst *usb, char **model)
72 {
73         struct drv_context *drvc;
74         int len, ret;
75         unsigned char cmd, buf[32];
76
77         drvc = di->priv;
78         if (sr_usb_open(drvc->sr_ctx->libusb_ctx, usb) != SR_OK)
79                 return SR_ERR;
80
81         cmd = CMD_IDENTIFY;
82         ret = libusb_bulk_transfer(usb->devhdl, EP_OUT, &cmd, 1, &len, 5);
83         if (ret != 0) {
84                 libusb_close(usb->devhdl);
85                 sr_dbg("Failed to send Identify command: %s", libusb_error_name(ret));
86                 return SR_ERR;
87         }
88
89         ret = libusb_bulk_transfer(usb->devhdl, EP_IN, buf, 32, &len, 10);
90         if (ret != 0) {
91                 libusb_close(usb->devhdl);
92                 sr_dbg("Failed to receive response: %s", libusb_error_name(ret));
93                 return SR_ERR;
94         }
95
96         libusb_close(usb->devhdl);
97         usb->devhdl = NULL;
98
99         if (len < 2 || buf[0] != (CMD_IDENTIFY | 0x80) || buf[1] > 30) {
100                 sr_dbg("Invalid response to Identify command");
101                 return SR_ERR;
102         }
103
104         buf[buf[1] + 2] = '\x0';
105         *model = g_strndup((const gchar *)buf + 2, 30);
106
107         return SR_OK;
108 }
109
110 static GSList *scan(GSList *options)
111 {
112         struct drv_context *drvc;
113         struct dev_context *devc;
114         struct sr_dev_inst *sdi;
115         struct sr_probe *probe;
116         GSList *usb_devices, *devices, *l;
117         char *model;
118
119         (void)options;
120
121         drvc = di->priv;
122         drvc->instances = NULL;
123
124         devices = NULL;
125         if ((usb_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, USB_CONN))) {
126                 /* We have a list of sr_usb_dev_inst matching the connection
127                  * string. Wrap them in sr_dev_inst and we're done. */
128                 for (l = usb_devices; l; l = l->next) {
129                         if (scan_kecheng(l->data, &model) != SR_OK)
130                                 continue;
131                         if (!(sdi = sr_dev_inst_new(0, SR_ST_INACTIVE, VENDOR,
132                                         model, NULL)))
133                                 return NULL;
134                         g_free(model);
135                         sdi->driver = di;
136                         sdi->inst_type = SR_INST_USB;
137                         sdi->conn = l->data;
138                         if (!(probe = sr_probe_new(0, SR_PROBE_ANALOG, TRUE, "SPL")))
139                                 return NULL;
140                         sdi->probes = g_slist_append(sdi->probes, probe);
141
142                         if (!(devc = g_try_malloc(sizeof(struct dev_context)))) {
143                                 sr_dbg("Device context malloc failed.");
144                                 return NULL;
145                         }
146                         sdi->priv = devc;
147                         devc->limit_samples = 0;
148                         /* The protocol provides no way to read the current
149                          * settings, so we'll enforce these. */
150                         devc->sample_interval = DEFAULT_SAMPLE_INTERVAL;
151                         devc->alarm_low = DEFAULT_ALARM_LOW;
152                         devc->alarm_high = DEFAULT_ALARM_HIGH;
153                         devc->mqflags = DEFAULT_WEIGHT_TIME | DEFAULT_WEIGHT_FREQ;
154                         devc->data_source = DEFAULT_DATA_SOURCE;
155                         devc->config_dirty = FALSE;
156
157                         /* TODO: Set date/time? */
158
159                         drvc->instances = g_slist_append(drvc->instances, sdi);
160                         devices = g_slist_append(devices, sdi);
161                 }
162                 g_slist_free(usb_devices);
163         } else
164                 g_slist_free_full(usb_devices, g_free);
165
166         return devices;
167 }
168
169 static GSList *dev_list(void)
170 {
171         struct drv_context *drvc;
172
173         drvc = di->priv;
174
175         return drvc->instances;
176 }
177
178 static int dev_clear(void)
179 {
180         return std_dev_clear(di, NULL);
181 }
182
183 static int dev_open(struct sr_dev_inst *sdi)
184 {
185         struct drv_context *drvc;
186         struct sr_usb_dev_inst *usb;
187         int ret;
188
189         if (!(drvc = di->priv)) {
190                 sr_err("Driver was not initialized.");
191                 return SR_ERR;
192         }
193
194         usb = sdi->conn;
195
196         if (sr_usb_open(drvc->sr_ctx->libusb_ctx, usb) != SR_OK)
197                 return SR_ERR;
198
199         if ((ret = libusb_set_configuration(usb->devhdl, 1))) {
200                 sr_err("Failed to set configuration: %s.", libusb_error_name(ret));
201                 return SR_ERR;
202         }
203
204         if ((ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE))) {
205                 sr_err("Failed to claim interface: %s.", libusb_error_name(ret));
206                 return SR_ERR;
207         }
208         sdi->status = SR_ST_ACTIVE;
209
210         return ret;
211 }
212
213 static int dev_close(struct sr_dev_inst *sdi)
214 {
215         struct dev_context *devc;
216         struct sr_usb_dev_inst *usb;
217
218         if (!di->priv) {
219                 sr_err("Driver was not initialized.");
220                 return SR_ERR;
221         }
222
223         usb = sdi->conn;
224
225         if (!usb->devhdl)
226                 /*  Nothing to do. */
227                 return SR_OK;
228
229         /* This allows a frontend to configure the device without ever
230          * doing an acquisition step. */
231         devc = sdi->priv;
232         if (!devc->config_dirty)
233                 kecheng_kc_330b_configure(sdi);
234
235         libusb_release_interface(usb->devhdl, USB_INTERFACE);
236         libusb_close(usb->devhdl);
237         usb->devhdl = NULL;
238         sdi->status = SR_ST_INACTIVE;
239
240         return SR_OK;
241 }
242
243 static int cleanup(void)
244 {
245         int ret;
246         struct drv_context *drvc;
247
248         if (!(drvc = di->priv))
249                 /* Can get called on an unused driver, doesn't matter. */
250                 return SR_OK;
251
252         ret = dev_clear();
253         g_free(drvc);
254         di->priv = NULL;
255
256         return ret;
257 }
258
259 static int config_get(int key, GVariant **data, const struct sr_dev_inst *sdi)
260 {
261         struct dev_context *devc;
262         GVariant *rational[2];
263         const uint64_t *si;
264
265         devc = sdi->priv;
266         switch (key) {
267         case SR_CONF_LIMIT_SAMPLES:
268                 *data = g_variant_new_uint64(devc->limit_samples);
269                 break;
270         case SR_CONF_SAMPLE_INTERVAL:
271                 si = kecheng_kc_330b_sample_intervals[devc->sample_interval];
272                 rational[0] = g_variant_new_uint64(si[0]);
273                 rational[1] = g_variant_new_uint64(si[1]);
274                 *data = g_variant_new_tuple(rational, 2);
275                 break;
276         case SR_CONF_DATALOG:
277                 /* There really isn't a way to be sure the device is logging. */
278                 return SR_ERR_NA;
279                 break;
280         case SR_CONF_SPL_WEIGHT_FREQ:
281                 if (devc->mqflags & SR_MQFLAG_SPL_FREQ_WEIGHT_A)
282                         *data = g_variant_new_string("A");
283                 else
284                         *data = g_variant_new_string("C");
285                 break;
286         case SR_CONF_SPL_WEIGHT_TIME:
287                 if (devc->mqflags & SR_MQFLAG_SPL_TIME_WEIGHT_F)
288                         *data = g_variant_new_string("F");
289                 else
290                         *data = g_variant_new_string("S");
291                 break;
292         case SR_CONF_DATA_SOURCE:
293                 if (devc->data_source == DATA_SOURCE_LIVE)
294                         *data = g_variant_new_string("Live");
295                 else
296                         *data = g_variant_new_string("Memory");
297                 break;
298         default:
299                 return SR_ERR_NA;
300         }
301
302         return SR_OK;
303 }
304
305 static int config_set(int key, GVariant *data, const struct sr_dev_inst *sdi)
306 {
307         struct dev_context *devc;
308         uint64_t p, q;
309         unsigned int i;
310         int tmp, ret;
311         const char *tmp_str;
312
313         if (sdi->status != SR_ST_ACTIVE)
314                 return SR_ERR_DEV_CLOSED;
315
316         if (!di->priv) {
317                 sr_err("Driver was not initialized.");
318                 return SR_ERR;
319         }
320
321         devc = sdi->priv;
322         ret = SR_OK;
323         switch (key) {
324         case SR_CONF_LIMIT_SAMPLES:
325                 devc->limit_samples = g_variant_get_uint64(data);
326                 sr_dbg("Setting sample limit to %" PRIu64 ".",
327                        devc->limit_samples);
328                 break;
329         case SR_CONF_SAMPLE_INTERVAL:
330                 g_variant_get(data, "(tt)", &p, &q);
331                 for (i = 0; i < ARRAY_SIZE(kecheng_kc_330b_sample_intervals); i++) {
332                         if (kecheng_kc_330b_sample_intervals[i][0] != p || kecheng_kc_330b_sample_intervals[i][1] != q)
333                                 continue;
334                         devc->sample_interval = i;
335                         devc->config_dirty = TRUE;
336                         break;
337                 }
338                 if (i == ARRAY_SIZE(kecheng_kc_330b_sample_intervals))
339                         ret = SR_ERR_ARG;
340                 break;
341         case SR_CONF_SPL_WEIGHT_FREQ:
342                 tmp_str = g_variant_get_string(data, NULL);
343                 if (!strcmp(tmp_str, "A"))
344                         tmp = SR_MQFLAG_SPL_FREQ_WEIGHT_A;
345                 else if (!strcmp(tmp_str, "C"))
346                         tmp = SR_MQFLAG_SPL_FREQ_WEIGHT_C;
347                 else
348                         return SR_ERR_ARG;
349                 devc->mqflags &= ~(SR_MQFLAG_SPL_FREQ_WEIGHT_A | SR_MQFLAG_SPL_FREQ_WEIGHT_C);
350                 devc->mqflags |= tmp;
351                 devc->config_dirty = TRUE;
352                 break;
353         case SR_CONF_SPL_WEIGHT_TIME:
354                 tmp_str = g_variant_get_string(data, NULL);
355                 if (!strcmp(tmp_str, "F"))
356                         tmp = SR_MQFLAG_SPL_TIME_WEIGHT_F;
357                 else if (!strcmp(tmp_str, "S"))
358                         tmp = SR_MQFLAG_SPL_TIME_WEIGHT_S;
359                 else
360                         return SR_ERR_ARG;
361                 devc->mqflags &= ~(SR_MQFLAG_SPL_TIME_WEIGHT_F | SR_MQFLAG_SPL_TIME_WEIGHT_S);
362                 devc->mqflags |= tmp;
363                 devc->config_dirty = TRUE;
364                 break;
365         case SR_CONF_DATA_SOURCE:
366                 tmp_str = g_variant_get_string(data, NULL);
367                 if (!strcmp(tmp_str, "Live"))
368                         devc->data_source = DATA_SOURCE_LIVE;
369                 else if (!strcmp(tmp_str, "Memory"))
370                         devc->data_source = DATA_SOURCE_MEMORY;
371                 else
372                         return SR_ERR;
373                 devc->config_dirty = TRUE;
374                 break;
375         default:
376                 ret = SR_ERR_NA;
377         }
378
379         return ret;
380 }
381
382 static int config_list(int key, GVariant **data, const struct sr_dev_inst *sdi)
383 {
384         GVariant *tuple, *rational[2];
385         GVariantBuilder gvb;
386         unsigned int i;
387
388         (void)sdi;
389
390         switch (key) {
391         case SR_CONF_DEVICE_OPTIONS:
392                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
393                                 hwcaps, ARRAY_SIZE(hwcaps), sizeof(int32_t));
394                 break;
395         case SR_CONF_SAMPLE_INTERVAL:
396                 g_variant_builder_init(&gvb, G_VARIANT_TYPE_ARRAY);
397                 for (i = 0; i < ARRAY_SIZE(kecheng_kc_330b_sample_intervals); i++) {
398                         rational[0] = g_variant_new_uint64(kecheng_kc_330b_sample_intervals[i][0]);
399                         rational[1] = g_variant_new_uint64(kecheng_kc_330b_sample_intervals[i][1]);
400                         tuple = g_variant_new_tuple(rational, 2);
401                         g_variant_builder_add_value(&gvb, tuple);
402                 }
403                 *data = g_variant_builder_end(&gvb);
404                 break;
405         case SR_CONF_SPL_WEIGHT_FREQ:
406                 *data = g_variant_new_strv(weight_freq, ARRAY_SIZE(weight_freq));
407                 break;
408         case SR_CONF_SPL_WEIGHT_TIME:
409                 *data = g_variant_new_strv(weight_time, ARRAY_SIZE(weight_time));
410                 break;
411         case SR_CONF_DATA_SOURCE:
412                 *data = g_variant_new_strv(data_sources, ARRAY_SIZE(data_sources));
413                 break;
414         default:
415                 return SR_ERR_NA;
416         }
417
418         return SR_OK;
419 }
420
421 static int dev_acquisition_start(const struct sr_dev_inst *sdi,
422                 void *cb_data)
423 {
424         struct drv_context *drvc;
425         struct dev_context *devc;
426         struct sr_datafeed_packet packet;
427         struct sr_datafeed_meta meta;
428         struct sr_config *src;
429         struct sr_usb_dev_inst *usb;
430         GVariant *gvar, *rational[2];
431         const struct libusb_pollfd **pfd;
432         const uint64_t *si;
433         int stored_mqflags, req_len, buf_len, len, ret, i;
434         unsigned char buf[9];
435
436         if (sdi->status != SR_ST_ACTIVE)
437                 return SR_ERR_DEV_CLOSED;
438
439         drvc = di->priv;
440         devc = sdi->priv;
441         usb = sdi->conn;
442
443         devc->cb_data = cb_data;
444         devc->num_samples = 0;
445
446         /* Send header packet to the session bus. */
447         std_session_send_df_header(cb_data, LOG_PREFIX);
448
449         if (devc->data_source == DATA_SOURCE_LIVE) {
450                 /* Force configuration. */
451                 kecheng_kc_330b_configure(sdi);
452
453                 if (kecheng_kc_330b_status_get(sdi, &ret) != SR_OK)
454                         return SR_ERR;
455                 if (ret != DEVICE_ACTIVE) {
456                         sr_err("Device is inactive");
457                         /* Still continue though, since the device will
458                          * just return 30.0 until the user hits the button
459                          * on the device -- and then start feeding good
460                          * samples back. */
461                 }
462         } else {
463                 if (kecheng_kc_330b_log_info_get(sdi, buf) != SR_OK)
464                         return SR_ERR;
465                 stored_mqflags = buf[4] ? SR_MQFLAG_SPL_TIME_WEIGHT_S : SR_MQFLAG_SPL_TIME_WEIGHT_F;
466                 stored_mqflags |= buf[5] ? SR_MQFLAG_SPL_FREQ_WEIGHT_C : SR_MQFLAG_SPL_FREQ_WEIGHT_A;
467                 devc->stored_samples = (buf[7] << 8) | buf[8];
468                 if (devc->stored_samples == 0) {
469                         /* Notify frontend of empty log by sending start/end packets. */
470                         packet.type = SR_DF_END;
471                         sr_session_send(cb_data, &packet);
472                         return SR_OK;
473                 }
474
475                 if (devc->limit_samples && devc->limit_samples < devc->stored_samples)
476                         devc->stored_samples = devc->limit_samples;
477
478                 si = kecheng_kc_330b_sample_intervals[buf[1]];
479                 rational[0] = g_variant_new_uint64(si[0]);
480                 rational[1] = g_variant_new_uint64(si[1]);
481                 gvar = g_variant_new_tuple(rational, 2);
482                 src = sr_config_new(SR_CONF_SAMPLE_INTERVAL, gvar);
483                 packet.type = SR_DF_META;
484                 packet.payload = &meta;
485                 meta.config = g_slist_append(NULL, src);
486                 sr_session_send(devc->cb_data, &packet);
487                 g_free(src);
488         }
489
490         if (!(devc->xfer = libusb_alloc_transfer(0)))
491                 return SR_ERR;
492
493         pfd = libusb_get_pollfds(drvc->sr_ctx->libusb_ctx);
494         for (i = 0; pfd[i]; i++) {
495                 /* Handle USB events every 10ms. */
496                 sr_source_add(pfd[i]->fd, pfd[i]->events, 10,
497                                 kecheng_kc_330b_handle_events, (void *)sdi);
498                 /* We'll need to remove this fd later. */
499                 devc->usbfd[i] = pfd[i]->fd;
500         }
501         devc->usbfd[i] = -1;
502
503         if (devc->data_source == DATA_SOURCE_LIVE) {
504                 buf[0] = CMD_GET_LIVE_SPL;
505                 buf_len = 1;
506                 devc->state = LIVE_SPL_WAIT;
507                 devc->last_live_request = g_get_monotonic_time() / 1000;
508                 req_len = 3;
509         } else {
510                 buf[0] = CMD_GET_LOG_DATA;
511                 buf[1] = 0;
512                 buf[2] = 0;
513                 buf_len = 4;
514                 devc->state = LOG_DATA_WAIT;
515                 if (devc->stored_samples < 63)
516                         buf[3] = devc->stored_samples;
517                 else
518                         buf[3] = 63;
519                 /* Command ack byte + 2 bytes per sample. */
520                 req_len = 1 + buf[3] * 2;
521         }
522
523         ret = libusb_bulk_transfer(usb->devhdl, EP_OUT, buf, buf_len, &len, 5);
524         if (ret != 0 || len != 1) {
525                 sr_dbg("Failed to start acquisition: %s", libusb_error_name(ret));
526                 libusb_free_transfer(devc->xfer);
527                 return SR_ERR;
528         }
529
530         libusb_fill_bulk_transfer(devc->xfer, usb->devhdl, EP_IN, devc->buf,
531                         req_len, kecheng_kc_330b_receive_transfer, (void *)sdi, 15);
532         if (libusb_submit_transfer(devc->xfer) != 0) {
533                 libusb_free_transfer(devc->xfer);
534                 return SR_ERR;
535         }
536
537         return SR_OK;
538 }
539
540 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
541 {
542         struct dev_context *devc;
543
544         (void)cb_data;
545
546         if (sdi->status != SR_ST_ACTIVE)
547                 return SR_ERR_DEV_CLOSED;
548
549         /* Signal USB transfer handler to clean up and stop. */
550         sdi->status = SR_ST_STOPPING;
551
552         devc = sdi->priv;
553         if (devc->data_source == DATA_SOURCE_MEMORY && devc->config_dirty) {
554                 /* The protocol doesn't have a command to clear stored data;
555                  * it clears it whenever new configuration is set. That means
556                  * we can't just configure the device any time we want when
557                  * it's in DATA_SOURCE_MEMORY mode. The only safe time to do
558                  * it is now, when we're sure we've pulled in all the stored
559                  * data. */
560                 kecheng_kc_330b_configure(sdi);
561         }
562
563         return SR_OK;
564 }
565
566 SR_PRIV struct sr_dev_driver kecheng_kc_330b_driver_info = {
567         .name = "kecheng-kc-330b",
568         .longname = "Kecheng KC-330B",
569         .api_version = 1,
570         .init = init,
571         .cleanup = cleanup,
572         .scan = scan,
573         .dev_list = dev_list,
574         .dev_clear = dev_clear,
575         .config_get = config_get,
576         .config_set = config_set,
577         .config_list = config_list,
578         .dev_open = dev_open,
579         .dev_close = dev_close,
580         .dev_acquisition_start = dev_acquisition_start,
581         .dev_acquisition_stop = dev_acquisition_stop,
582         .priv = NULL,
583 };