]> sigrok.org Git - libsigrok.git/blob - src/hardware/uni-t-ut32x/protocol.c
uni-t-ut32x: improve robustness of packet parser, more diagnostics
[libsigrok.git] / src / hardware / uni-t-ut32x / protocol.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 <config.h>
21 #include <string.h>
22 #include <math.h>
23 #include "protocol.h"
24
25 #define SEP     "\r\n"
26 #define BLANK   ':'
27 #define NEG     ';'
28
29 /*
30  * Get a temperature value from a four-character buffer. The value is
31  * encoded in ASCII and the unit is deci-degrees (tenths of degrees).
32  */
33 static float parse_temperature(unsigned char *buf)
34 {
35         float temp;
36         int i;
37         gboolean negative;
38
39         negative = FALSE;
40         temp = 0.0;
41         for (i = 0; i < 4; i++) {
42                 if (buf[i] == BLANK)
43                         continue;
44                 if (buf[i] == NEG) {
45                         if (negative) {
46                                 sr_dbg("Double negative sign!");
47                                 return NAN;
48                         }
49                         negative = TRUE;
50                         continue;
51                 }
52                 if (buf[i] < '0' || buf[i] > '9') {
53                         sr_dbg("Invalid digit '%.2x'!", buf[i]);
54                         return NAN;
55                 }
56                 temp *= 10;
57                 temp += buf[i] - '0';
58         }
59         temp /= 10;
60         if (negative)
61                 temp = -temp;
62
63         return temp;
64 }
65
66 static void process_packet(struct sr_dev_inst *sdi, uint8_t *pkt, size_t len)
67 {
68         struct dev_context *devc;
69         struct sr_datafeed_packet packet;
70         struct sr_datafeed_analog analog;
71         struct sr_analog_encoding encoding;
72         struct sr_analog_meaning meaning;
73         struct sr_analog_spec spec;
74         GString *spew;
75         float temp;
76         gboolean is_valid;
77
78         if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
79                 spew = sr_hexdump_new(pkt, len);
80                 sr_spew("Got a packet, len %zu, bytes%s", len, spew->str);
81                 sr_hexdump_free(spew);
82         }
83         if (len != PACKET_SIZE)
84                 return;
85         if (pkt[17] != SEP[0] || pkt[18] != SEP[1])
86                 return;
87         if (pkt[8] != '0' || pkt[16] != '1')
88                 return;
89         sr_dbg("Processing 19-byte packet.");
90
91         is_valid = TRUE;
92         if (pkt[1] == NEG && pkt[2] == NEG && pkt[3] == NEG && pkt[4] == NEG)
93                 /* No measurement: missing channel, empty storage location, ... */
94                 is_valid = FALSE;
95
96         temp = parse_temperature(&pkt[1]);
97         if (isnan(temp))
98                 is_valid = FALSE;
99
100         if (is_valid) {
101                 memset(&packet, 0, sizeof(packet));
102                 sr_analog_init(&analog, &encoding, &meaning, &spec, 1);
103                 analog.meaning->mq = SR_MQ_TEMPERATURE;
104                 analog.meaning->mqflags = 0;
105                 switch (pkt[5] - '0') {
106                 case 1:
107                         analog.meaning->unit = SR_UNIT_CELSIUS;
108                         break;
109                 case 2:
110                         analog.meaning->unit = SR_UNIT_FAHRENHEIT;
111                         break;
112                 case 3:
113                         analog.meaning->unit = SR_UNIT_KELVIN;
114                         break;
115                 default:
116                         /* We can still pass on the measurement, whatever it is. */
117                         sr_dbg("Unknown unit 0x%.2x.", pkt[5]);
118                 }
119                 switch (pkt[13] - '0') {
120                 case 0:
121                         /* Channel T1. */
122                         analog.meaning->channels = g_slist_append(NULL, g_slist_nth_data(sdi->channels, 0));
123                         break;
124                 case 1:
125                         /* Channel T2. */
126                         analog.meaning->channels = g_slist_append(NULL, g_slist_nth_data(sdi->channels, 1));
127                         break;
128                 case 2:
129                 case 3:
130                         /* Channel T1-T2. */
131                         analog.meaning->channels = g_slist_append(NULL, g_slist_nth_data(sdi->channels, 2));
132                         analog.meaning->mqflags |= SR_MQFLAG_RELATIVE;
133                         break;
134                 default:
135                         sr_err("Unknown channel 0x%.2x.", pkt[13]);
136                         is_valid = FALSE;
137                 }
138                 if (is_valid) {
139                         analog.num_samples = 1;
140                         analog.data = &temp;
141                         packet.type = SR_DF_ANALOG;
142                         packet.payload = &analog;
143                         sr_session_send(sdi, &packet);
144                         g_slist_free(analog.meaning->channels);
145                 }
146         }
147
148         /*
149          * We count packets even if the measurement was invalid. This way
150          * a sample limit on "Memory" data source still works: Unused
151          * memory slots come through as "----" measurements.
152          */
153         devc = sdi->priv;
154         sr_sw_limits_update_samples_read(&devc->limits, 1);
155         if (sr_sw_limits_check(&devc->limits))
156                 sr_dev_acquisition_stop(sdi);
157 }
158
159 SR_PRIV void LIBUSB_CALL uni_t_ut32x_receive_transfer(struct libusb_transfer *transfer)
160 {
161         struct dev_context *devc;
162         struct sr_dev_inst *sdi;
163         int hid_payload_len, ret;
164
165         sdi = transfer->user_data;
166         devc = sdi->priv;
167         if (transfer->actual_length == 8) {
168                 /* CH9325 encodes length in low nibble of first byte, with
169                  * bytes 1-7 being the (padded) payload. */
170                 hid_payload_len = transfer->buffer[0] & 0x0f;
171                 memcpy(devc->packet + devc->packet_len, transfer->buffer + 1,
172                                 hid_payload_len);
173                 devc->packet_len += hid_payload_len;
174                 if (devc->packet_len >= 2
175                                 && devc->packet[devc->packet_len - 2] == SEP[0]
176                                 && devc->packet[devc->packet_len - 1] == SEP[1]) {
177                         /* Got end of packet. */
178                         process_packet(sdi, devc->packet, devc->packet_len);
179                         devc->packet_len = 0;
180                 } else if (devc->packet_len > PACKET_SIZE) {
181                         /* Guard against garbage from the device overrunning
182                          * our packet buffer. */
183                         sr_dbg("Buffer overrun!");
184                         process_packet(sdi, devc->packet, devc->packet_len);
185                         devc->packet_len = 0;
186                 }
187         }
188
189         /* Get the next transfer (unless we're shutting down). */
190         if (sdi->status != SR_ST_STOPPING) {
191                 if ((ret = libusb_submit_transfer(devc->xfer)) != 0) {
192                         sr_dbg("Failed to resubmit transfer: %s", libusb_error_name(ret));
193                         sdi->status = SR_ST_STOPPING;
194                         libusb_free_transfer(devc->xfer);
195                 }
196         } else
197                 libusb_free_transfer(devc->xfer);
198
199 }
200
201 SR_PRIV int uni_t_ut32x_handle_events(int fd, int revents, void *cb_data)
202 {
203         struct drv_context *drvc;
204         struct dev_context *devc;
205         struct sr_dev_driver *di;
206         struct sr_dev_inst *sdi;
207         struct sr_usb_dev_inst *usb;
208         struct timeval tv;
209         int len, ret;
210         unsigned char cmd[2];
211
212         (void)fd;
213         (void)revents;
214
215         if (!(sdi = cb_data))
216                 return TRUE;
217
218         di = sdi->driver;
219         drvc = di->context;
220
221         if (!(devc = sdi->priv))
222                 return TRUE;
223
224         memset(&tv, 0, sizeof(struct timeval));
225         libusb_handle_events_timeout_completed(drvc->sr_ctx->libusb_ctx, &tv,
226                         NULL);
227
228         if (sdi->status == SR_ST_STOPPING) {
229                 usb_source_remove(sdi->session, drvc->sr_ctx);
230                 std_session_send_df_end(sdi);
231
232                 /* Tell the device to stop sending USB packets. */
233                 usb = sdi->conn;
234                 cmd[0] = 0x01;
235                 cmd[1] = CMD_STOP;
236                 ret = libusb_bulk_transfer(usb->devhdl, EP_OUT, cmd, 2, &len, 5);
237                 if (ret != 0 || len != 2) {
238                         /* Warning only, doesn't matter. */
239                         sr_dbg("Failed to send stop command: %s", libusb_error_name(ret));
240                 }
241
242                 sdi->status = SR_ST_ACTIVE;
243                 return TRUE;
244         }
245
246         return TRUE;
247 }