]> sigrok.org Git - libsigrok.git/blob - src/hardware/uni-t-ut181a/api.c
output/csv: use intermediate time_t var, silence compiler warning
[libsigrok.git] / src / hardware / uni-t-ut181a / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2019-2020 Gerhard Sittig <gerhard.sittig@gmx.net>
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 "protocol.h"
22
23 static const uint32_t scanopts[] = {
24         SR_CONF_CONN,
25         SR_CONF_SERIALCOMM,
26 };
27
28 static const uint32_t drvopts[] = {
29         SR_CONF_MULTIMETER,
30         SR_CONF_THERMOMETER, /* Supports two temperature probes and diffs. */
31 };
32
33 static const uint32_t devopts[] = {
34         SR_CONF_CONN | SR_CONF_GET,
35         SR_CONF_CONTINUOUS,
36         SR_CONF_LIMIT_FRAMES | SR_CONF_GET | SR_CONF_SET,
37         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
38         SR_CONF_LIMIT_MSEC | SR_CONF_GET | SR_CONF_SET,
39         SR_CONF_DATA_SOURCE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
40         SR_CONF_DATALOG | SR_CONF_GET | SR_CONF_SET,
41         /* TODO SR_CONF_DATALOG is bool only, how to setup interval/duration? */
42         SR_CONF_MEASURED_QUANTITY | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
43         SR_CONF_RANGE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
44 };
45
46 static const char *channel_names[] = {
47         [UT181A_CH_MAIN] = "P1",
48         [UT181A_CH_AUX1] = "P2",
49         [UT181A_CH_AUX2] = "P3",
50         [UT181A_CH_AUX3] = "P4",
51         [UT181A_CH_BAR] = "bar",
52 #if UT181A_WITH_TIMESTAMP
53         [UT181A_CH_TIME] = "TS",
54 #endif
55 };
56
57 /*
58  * (Re-)retrieve the list of recordings and their names. These can change
59  * without the driver's being aware, the set is under user control.
60  *
61  * TODO Need to re-allocate the list of recording names when a larger
62  * recordings count is seen than previously allocated? This implementation
63  * assumes a known maximum number of recordings, the manual is vague on
64  * these limits.
65  */
66 static int ut181a_update_recordings(const struct sr_dev_inst *sdi)
67 {
68         struct dev_context *devc;
69         struct sr_serial_dev_inst *serial;
70         size_t rec_count, rec_idx;
71         int ret;
72
73         if (!sdi)
74                 return SR_ERR_ARG;
75         devc = sdi->priv;
76         serial = sdi->conn;
77
78         ret = ut181a_send_cmd_get_recs_count(serial);
79         if (ret < 0)
80                 return ret;
81         ret = ut181a_configure_waitfor(devc, FALSE, 0, 0,
82                 FALSE, TRUE, FALSE, FALSE);
83         if (ret < 0)
84                 return ret;
85         ret = ut181a_waitfor_response(sdi, 100);
86         if (ret < 0)
87                 return ret;
88
89         rec_count = devc->wait_state.data_value;
90         if (rec_count > ARRAY_SIZE(devc->record_names))
91                 rec_count = ARRAY_SIZE(devc->record_names);
92         for (rec_idx = 0; rec_idx < rec_count; rec_idx++) {
93                 devc->info.rec_info.rec_idx = rec_idx;
94                 ret = ut181a_send_cmd_get_rec_info(serial, rec_idx);
95                 if (ret < 0)
96                         return ret;
97                 ret = ut181a_configure_waitfor(devc,
98                         FALSE, CMD_CODE_GET_REC_INFO, 0,
99                         FALSE, FALSE, FALSE, FALSE);
100                 if (ret < 0)
101                         return ret;
102                 ret = ut181a_waitfor_response(sdi, 100);
103                 if (ret < 0)
104                         return ret;
105         }
106         devc->record_count = rec_count;
107         devc->data_source_count = DATA_SOURCE_REC_FIRST + devc->record_count;
108
109         return SR_OK;
110 }
111
112 /*
113  * Retrieve the device's current state. Run monitor mode for some time
114  * until the 'mode' (meter's current function) became available. There
115  * is no other way of querying the meter's current state.
116  */
117 static int ut181a_query_initial_state(struct sr_dev_inst *sdi, int timeout_ms)
118 {
119         struct dev_context *devc;
120         struct sr_serial_dev_inst *serial;
121         gint64 deadline;
122         int ret;
123
124         if (!sdi)
125                 return SR_ERR_ARG;
126         devc = sdi->priv;
127         serial = sdi->conn;
128
129         devc->info.meas_head.mode = 0;
130         ret = ut181a_send_cmd_monitor(serial, TRUE);
131         if (ret < 0)
132                 return ret;
133         ret = ut181a_configure_waitfor(devc, FALSE, 0, 0,
134                 TRUE, FALSE, FALSE, FALSE);
135         if (ret < 0)
136                 return ret;
137         deadline = g_get_monotonic_time();
138         deadline += timeout_ms * 1000;
139         while (1) {
140                 ret = ut181a_waitfor_response(sdi, 100);
141                 if (ret < 0)
142                         return ret;
143                 if (devc->info.meas_head.mode)
144                         break;
145                 if (g_get_monotonic_time() >= deadline)
146                         return SR_ERR_DATA;
147         }
148         (void)ut181a_send_cmd_monitor(serial, FALSE);
149         ret = ut181a_configure_waitfor(devc, TRUE, 0, 0,
150                 FALSE, FALSE, FALSE, FALSE);
151         if (ret < 0)
152                 return ret;
153         (void)ut181a_waitfor_response(sdi, 100);
154
155         return SR_OK;
156 }
157
158 static GSList *scan(struct sr_dev_driver *di, GSList *options)
159 {
160         const char *conn, *serialcomm;
161         struct sr_config *src;
162         GSList *l, *devices;
163         struct sr_serial_dev_inst *serial;
164         int ret;
165         char conn_id[64];
166         struct sr_dev_inst *sdi;
167         struct dev_context *devc;
168         size_t idx, ds_idx;
169
170         /*
171          * Implementor's note:
172          * Do _not_ add a default conn value here. Always expect users to
173          * specify the connection. Never match in the absence of a user spec.
174          *
175          * Motivation: There is no way to identify the DMM itself. Neither
176          * are the cable nor its chip unique to the device. They are not even
177          * specific to the series or the vendor. The DMM ships with a generic
178          * CP2110 USB-to-UART bridge. Attempts to auto probe will disturb
179          * other types of devices which may be attached to the probed conn.
180          *
181          * On the other hand it's perfectly fine to communicate to the
182          * device and assume that the device model will accept the requests,
183          * once the user specified the connection (and the driver), and thus
184          * instructed this driver to start such activity.
185          */
186         conn = NULL;
187         serialcomm = "9600/8n1";
188         for (l = options; l; l = l->next) {
189                 src = l->data;
190                 switch (src->key) {
191                 case SR_CONF_CONN:
192                         conn = g_variant_get_string(src->data, NULL);
193                         break;
194                 case SR_CONF_SERIALCOMM:
195                         serialcomm = g_variant_get_string(src->data, NULL);
196                         break;
197                 }
198         }
199         if (!conn)
200                 return NULL;
201
202         devices = NULL;
203         serial = sr_serial_dev_inst_new(conn, serialcomm);
204         ret = serial_open(serial, SERIAL_RDWR);
205         snprintf(conn_id, sizeof(conn_id), "%s", serial->port);
206         /*
207          * We cannot identify the device at this point in time.
208          * Successful open shall suffice for now. More activity
209          * will communicate to the device later, after the driver
210          * instance got created. See below for details.
211          */
212         if (ret != SR_OK) {
213                 serial_close(serial);
214                 sr_serial_dev_inst_free(serial);
215                 return devices;
216         }
217
218         sdi = g_malloc0(sizeof(*sdi));
219         sdi->status = SR_ST_INACTIVE;
220         sdi->vendor = g_strdup("UNI-T");
221         sdi->model = g_strdup("UT181A");
222         sdi->inst_type = SR_INST_SERIAL;
223         sdi->conn = serial;
224         sdi->connection_id = g_strdup(conn_id);
225         devc = g_malloc0(sizeof(*devc));
226         sdi->priv = devc;
227         sr_sw_limits_init(&devc->limits);
228         for (idx = 0; idx < ARRAY_SIZE(channel_names); idx++) {
229                 sr_channel_new(sdi, idx, SR_CHANNEL_ANALOG, TRUE,
230                         channel_names[idx]);
231         }
232
233         /*
234          * Run monitor mode for a while to determine the current state
235          * of the device (which cannot get queried by other means). This
236          * also deals with devices which happen to already be in monitor
237          * mode when we connect to them. As a byproduct this query drains
238          * potentially pending RX data, before getting recording details.
239          */
240         devc->disable_feed = 1;
241         ret = ut181a_query_initial_state(sdi, 2000);
242         if (ret < 0) {
243                 serial_close(serial);
244                 sr_serial_dev_inst_free(serial);
245                 return devices;
246         }
247
248         /*
249          * Number of recordings and their names are dynamic and under
250          * the user's control. Prepare for a maximum number of string
251          * labels, and fetch (and re-fetch) their names and current
252          * count on demand.
253          */
254         devc->data_source_names[DATA_SOURCE_LIVE] = "Live";
255         devc->data_source_names[DATA_SOURCE_SAVE] = "Save";
256         for (idx = 0; idx < MAX_REC_COUNT; idx++) {
257                 ds_idx = DATA_SOURCE_REC_FIRST + idx;
258                 devc->data_source_names[ds_idx] = &devc->record_names[idx][0];
259         }
260         devc->data_source_count = DATA_SOURCE_REC_FIRST;
261         ret = ut181a_update_recordings(sdi);
262         devc->data_source_count = DATA_SOURCE_REC_FIRST + devc->record_count;
263         if (ret < 0) {
264                 serial_close(serial);
265                 sr_serial_dev_inst_free(serial);
266                 return devices;
267         }
268
269         devc->disable_feed = 0;
270         serial_close(serial);
271
272         devices = g_slist_append(devices, sdi);
273
274         return std_scan_complete(di, devices);
275 }
276
277 static int config_get(uint32_t key, GVariant **data,
278         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
279 {
280         struct dev_context *devc;
281         const struct mqopt_item *mqitem;
282         GVariant *arr[2];
283         const char *range;
284
285         (void)cg;
286
287         devc = sdi->priv;
288         switch (key) {
289         case SR_CONF_CONN:
290                 *data = g_variant_new_string(sdi->connection_id);
291                 break;
292         case SR_CONF_LIMIT_FRAMES:
293         case SR_CONF_LIMIT_SAMPLES:
294         case SR_CONF_LIMIT_MSEC:
295                 if (!devc)
296                         return SR_ERR_ARG;
297                 return sr_sw_limits_config_get(&devc->limits, key, data);
298         case SR_CONF_DATA_SOURCE:
299                 if (!devc)
300                         return SR_ERR_ARG;
301                 *data = g_variant_new_string(devc->data_source_names[devc->data_source]);
302                 break;
303         case SR_CONF_DATALOG:
304                 if (!devc)
305                         return SR_ERR_ARG;
306                 *data = g_variant_new_boolean(devc->is_recording ? TRUE : FALSE);
307                 break;
308         case SR_CONF_MEASURED_QUANTITY:
309                 if (!devc)
310                         return SR_ERR_ARG;
311                 mqitem = ut181a_get_mqitem_from_mode(devc->info.meas_head.mode);
312                 if (!mqitem)
313                         return SR_ERR_NA;
314                 arr[0] = g_variant_new_uint32(mqitem->mq);
315                 arr[1] = g_variant_new_uint64(mqitem->mqflags);
316                 *data = g_variant_new_tuple(arr, ARRAY_SIZE(arr));
317                 break;
318         case SR_CONF_RANGE:
319                 if (!devc)
320                         return SR_ERR_ARG;
321                 range = ut181a_get_range_from_packet_bytes(devc);
322                 if (!range || !*range)
323                         return SR_ERR_NA;
324                 *data = g_variant_new_string(range);
325                 break;
326         default:
327                 return SR_ERR_NA;
328         }
329
330         return SR_OK;
331 }
332
333 static int config_set(uint32_t key, GVariant *data,
334         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
335 {
336         struct dev_context *devc;
337         ssize_t idx;
338         gboolean on;
339         GVariant *tuple_child;
340         enum sr_mq mq;
341         enum sr_mqflag mqflags;
342         uint16_t mode;
343         int ret;
344         size_t rec_no;
345         const char *range;
346
347         (void)cg;
348
349         devc = sdi->priv;
350         switch (key) {
351         case SR_CONF_LIMIT_FRAMES:
352         case SR_CONF_LIMIT_SAMPLES:
353         case SR_CONF_LIMIT_MSEC:
354                 if (!devc)
355                         return SR_ERR_ARG;
356                 return sr_sw_limits_config_set(&devc->limits, key, data);
357         case SR_CONF_DATA_SOURCE:
358                 if (!devc)
359                         return SR_ERR_ARG;
360                 /* Prefer data source names for the lookup. */
361                 idx = std_str_idx(data, devc->data_source_names, devc->data_source_count);
362                 if (idx >= 0) {
363                         devc->data_source = idx;
364                         break;
365                 }
366                 /*
367                  * Support record number (1-based) as a fallback. The DMM
368                  * "supports" ambiguous recording names (keeps offering a
369                  * previously stored name for each new recording, neither
370                  * automatically increments nor suggests timestamps).
371                  */
372                 if (sr_atoi(g_variant_get_string(data, NULL), &ret) != SR_OK)
373                         return SR_ERR_ARG;
374                 if (ret <= 0)
375                         return SR_ERR_ARG;
376                 rec_no = ret;
377                 if (rec_no > devc->record_count)
378                         return SR_ERR_ARG;
379                 devc->data_source = DATA_SOURCE_REC_FIRST + rec_no - 1;
380                 break;
381         case SR_CONF_DATALOG:
382                 if (!devc)
383                         return SR_ERR_ARG;
384                 on = g_variant_get_boolean(data);
385                 sr_err("DIAG: record start/stop %d, currently ENOIMPL", on);
386                 return SR_ERR_NA;
387                 /*
388                  * TODO Send command 0x0a (start) or 0x0b (stop). Though
389                  * start needs a name (ymd timestamp?) and interval and
390                  * duration (arbitrary choice? 1s for 1d?). Or shall this
391                  * SET request control "save" items instead? Take one
392                  * sample each for every 'datalog=on' request? Combine
393                  * limit_samples and limit_msec with datalog to configure
394                  * a recording's parameters?
395                  */
396                 break;
397         case SR_CONF_MEASURED_QUANTITY:
398                 if (!devc)
399                         return SR_ERR_ARG;
400                 tuple_child = g_variant_get_child_value(data, 0);
401                 mq = g_variant_get_uint32(tuple_child);
402                 g_variant_unref(tuple_child);
403                 tuple_child = g_variant_get_child_value(data, 1);
404                 mqflags = g_variant_get_uint64(tuple_child);
405                 g_variant_unref(tuple_child);
406                 mode = ut181a_get_mode_from_mq_flags(mq, mqflags);
407                 if (!mode)
408                         return SR_ERR_NA;
409                 ret = ut181a_send_cmd_setmode(sdi->conn, mode);
410                 if (ret < 0)
411                         return ret;
412                 ret = ut181a_waitfor_response(sdi->conn, 100);
413                 if (ret < 0)
414                         return ret;
415                 if (devc->info.rsp_head.rsp_type != RSP_TYPE_REPLY_CODE)
416                         return SR_ERR_DATA;
417                 if (!devc->info.reply_code.ok)
418                         return SR_ERR_DATA;
419                 break;
420         case SR_CONF_RANGE:
421                 range = g_variant_get_string(data, NULL);
422                 return ut181a_set_range_from_text(sdi, range);
423         default:
424                 return SR_ERR_NA;
425         }
426
427         return SR_OK;
428 }
429
430 static int config_list(uint32_t key, GVariant **data,
431         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
432 {
433         struct dev_context *devc;
434         int ret;
435
436         devc = sdi ? sdi->priv : NULL;
437         switch (key) {
438         case SR_CONF_SCAN_OPTIONS:
439         case SR_CONF_DEVICE_OPTIONS:
440                 return STD_CONFIG_LIST(key, data, sdi, cg, scanopts, drvopts, devopts);
441         case SR_CONF_DATA_SOURCE:
442                 if (!devc)
443                         return SR_ERR_NA;
444                 ret = ut181a_update_recordings(sdi);
445                 if (ret < 0)
446                         return ret;
447                 *data = g_variant_new_strv(devc->data_source_names, devc->data_source_count);
448                 break;
449         case SR_CONF_MEASURED_QUANTITY:
450                 *data = ut181a_get_mq_flags_list();
451                 break;
452         case SR_CONF_RANGE:
453                 *data = ut181a_get_ranges_list();
454                 break;
455         default:
456                 return SR_ERR_NA;
457         }
458
459         return SR_OK;
460 }
461
462 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
463 {
464         struct dev_context *devc;
465         struct sr_serial_dev_inst *serial;
466         int ret;
467         size_t rec_idx;
468
469         devc = sdi->priv;
470         serial = sdi->conn;
471         serial_flush(serial);
472
473         /*
474          * Send an acquisition start command which depends on the
475          * currently selected data source. Enter monitor mode for
476          * Live readings, get saved or recorded data otherwise. The
477          * latter require queries for sample counts, then run chunked
478          * download sequences (single item for Save, set of samples
479          * for Recordings).
480          */
481         if (devc->data_source == DATA_SOURCE_LIVE) {
482                 ret = ut181a_send_cmd_monitor(serial, TRUE);
483         } else if (devc->data_source == DATA_SOURCE_SAVE) {
484                 /*
485                  * There is only one sequence of saved measurements in
486                  * the device, but its length is yet unknown. Determine
487                  * the number of saved items, and initiate the reception
488                  * of the first value. Completion of data reception will
489                  * drive subsequent progress.
490                  */
491                 ret = ut181a_send_cmd_get_save_count(serial);
492                 if (ret < 0)
493                         return ret;
494                 ret = ut181a_configure_waitfor(devc, FALSE, 0, 0,
495                         FALSE, FALSE, TRUE, FALSE);
496                 if (ret < 0)
497                         return ret;
498                 ret = ut181a_waitfor_response(sdi, 200);
499                 if (ret < 0)
500                         return ret;
501                 devc->info.save_info.save_count = devc->wait_state.data_value;
502                 devc->info.save_info.save_idx = 0;
503                 ret = ut181a_send_cmd_get_saved_value(serial, 0);
504         } else if (devc->data_source >= DATA_SOURCE_REC_FIRST) {
505                 /*
506                  * When we get here, the data source got selected, which
507                  * includes an update of the device's list of recordings.
508                  * So the index should be good, just the number of samples
509                  * in that recording is yet unknown. Get the sample count
510                  * and initiate the reception of the first chunk, completed
511                  * reception of a chunk advances through the sequence.
512                  */
513                 rec_idx = devc->data_source - DATA_SOURCE_REC_FIRST;
514                 if (rec_idx >= devc->record_count)
515                         return SR_ERR_DATA;
516                 devc->info.rec_info.rec_count = devc->record_count;
517                 devc->info.rec_info.rec_idx = rec_idx;
518                 devc->info.rec_info.auto_next = 0;
519                 devc->info.rec_info.auto_feed = 1;
520                 ret = ut181a_send_cmd_get_rec_info(serial, rec_idx);
521                 if (ret < 0)
522                         return ret;
523                 ret = ut181a_configure_waitfor(devc,
524                         FALSE, CMD_CODE_GET_REC_INFO, 0,
525                         FALSE, FALSE, FALSE, FALSE);
526                 if (ret < 0)
527                         return ret;
528                 ret = ut181a_waitfor_response(sdi, 200);
529                 if (ret < 0)
530                         return ret;
531                 devc->info.rec_data.samples_total = devc->wait_state.data_value;
532                 devc->info.rec_data.samples_curr = 0;
533                 ret = ut181a_send_cmd_get_rec_samples(serial, rec_idx, 0);
534         } else {
535                 sr_err("Unhandled data source %d, programming error?",
536                         (int)devc->data_source);
537                 ret = SR_ERR_BUG;
538         }
539         if (ret < 0)
540                 return ret;
541
542         sr_sw_limits_acquisition_start(&devc->limits);
543         devc->recv_count = 0;
544         std_session_send_df_header(sdi);
545
546         serial_source_add(sdi->session, serial, G_IO_IN, 10,
547                 ut181a_handle_events, (void *)sdi);
548
549         return SR_OK;
550 }
551
552 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
553 {
554
555         sdi->status = SR_ST_STOPPING;
556         /* Initiate stop here. Activity happens in ut181a_handle_events(). */
557
558         return SR_OK;
559 }
560
561 static struct sr_dev_driver uni_t_ut181a_driver_info = {
562         .name = "uni-t-ut181a",
563         .longname = "UNI-T UT181A",
564         .api_version = 1,
565         .init = std_init,
566         .cleanup = std_cleanup,
567         .scan = scan,
568         .dev_list = std_dev_list,
569         .dev_clear = std_dev_clear,
570         .config_get = config_get,
571         .config_set = config_set,
572         .config_list = config_list,
573         .dev_open = std_serial_dev_open,
574         .dev_close = std_serial_dev_close,
575         .dev_acquisition_start = dev_acquisition_start,
576         .dev_acquisition_stop = dev_acquisition_stop,
577         .context = NULL,
578 };
579 SR_REGISTER_DEV_DRIVER(uni_t_ut181a_driver_info);