]> sigrok.org Git - libsigrok.git/blob - src/hardware/zketech-ebd-usb/protocol.c
zketech-ebd-usb: Minor style fixes
[libsigrok.git] / src / hardware / zketech-ebd-usb / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2018 Sven Bursch-Osewold <sb_git@bursch.com>
5  * Copyright (C) 2019 King Kévin <kingkevin@cuvoodoo.info>
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 #include <config.h>
22 #include "protocol.h"
23
24 /* Log a byte-array as hex values. */
25 static void log_buf(const char *message, uint8_t buf[], size_t count)
26 {
27         char buffer[count * 2 + 1];
28
29         for (size_t i = 0; i < count; i++) {
30                 sprintf(&buffer[2 * i], "%02X", buf[i]);
31         }
32
33         buffer[count * 2] = 0;
34
35         sr_dbg("%s: %s [%zu bytes]", message, buffer, count);
36 }
37
38 /* Send a command to the device. */
39 static int send_cmd(struct sr_serial_dev_inst *serial, uint8_t buf[],
40         size_t count)
41 {
42         int ret;
43
44         log_buf("Sending", buf, count);
45         for (size_t byte = 0; byte < count; byte++) {
46                 ret = serial_write_blocking(serial, &buf[byte], 1, 0);
47                 if (ret < 0) {
48                         sr_err("Error sending command: %d.", ret);
49                         return ret;
50                 }
51                 /*
52                  * Wait between bytes to prevent data loss at the receiving
53                  * side.
54                  */
55                 g_usleep(10000);
56         }
57
58         return (ret == (int)count) ? SR_OK : SR_ERR;
59 }
60
61 /* Decode high byte and low byte into a float. */
62 static float decode_value(uint8_t hi, uint8_t lo, float divisor)
63 {
64         return ((float)hi * 240.0 + (float)lo) / divisor;
65 }
66
67 /* Encode a float into high byte and low byte. */
68 static void encode_value(float current, uint8_t *hi, uint8_t *lo, float divisor)
69 {
70         int value;
71
72         value = (int)(current * divisor);
73         sr_dbg("Value %d %d %d", value, value / 240, value % 240);
74         *hi = value / 240;
75         *lo = value % 240;
76 }
77
78 /* Send updated configuration values to the load. */
79 static int send_cfg(struct sr_serial_dev_inst *serial, struct dev_context *devc)
80 {
81         uint8_t send[] = {0xfa, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8};
82
83         encode_value(devc->current_limit, &send[2], &send[3], 1000.0);
84         encode_value(devc->uvc_threshold, &send[4], &send[5], 100.0);
85
86         send[8] = send[1] ^ send[2] ^ send[3] ^ send[4] ^ send[5] ^ send[6] ^ send[7];
87
88         return send_cmd(serial, send, 10);
89 }
90
91 /* Send the init/connect sequence; drive starts sending voltage and current. */
92 SR_PRIV int ebd_init(struct sr_serial_dev_inst *serial, struct dev_context *devc)
93 {
94         uint8_t init[] = { 0xfa, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0xf8 };
95
96         (void)devc;
97
98         return send_cmd(serial, init, 10);
99 }
100
101 /* Start the load functionality. */
102 SR_PRIV int ebd_loadstart(struct sr_serial_dev_inst *serial,
103         struct dev_context *devc)
104 {
105         int ret;
106         uint8_t start[] = { 0xfa, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xf8 };
107
108         encode_value(devc->current_limit, &start[2], &start[3], 1000.0);
109         encode_value(devc->uvc_threshold, &start[4], &start[5], 100.0);
110
111         start[8] = start[1] ^ start[2] ^ start[3] ^ start[4] ^ start[5] ^ start[6] ^ start[7];
112
113         sr_info("Activating load");
114         ret = send_cmd(serial, start, 10);
115         if (ret)
116                 return ret;
117
118         sr_dbg("current limit: %.03f", devc->current_limit);
119         sr_dbg("under-voltage threshold: %.02f", devc->uvc_threshold);
120         if (ebd_current_is0(devc))
121                 return SR_OK;
122
123         return ret;
124 }
125
126 /* Toggle the load functionality. */
127 SR_PRIV int ebd_loadtoggle(struct sr_serial_dev_inst *serial,
128         struct dev_context *devc)
129 {
130         uint8_t toggle[] = { 0xfa, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xF8 };
131
132         (void)devc;
133
134         sr_info("Toggling load");
135         return send_cmd(serial, toggle, 10);
136 }
137
138 /* Stop the drive. */
139 SR_PRIV int ebd_stop(struct sr_serial_dev_inst *serial, struct dev_context *devc)
140 {
141         uint8_t stop[] = { 0xfa, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0xF8 };
142
143         (void)devc;
144
145         return send_cmd(serial, stop, 10);
146 }
147
148 /**
149  * Receive a complete message.
150  *
151  * @param[in] serial Serial port from which to read the packet
152  * @param[in] length Buffer length
153  * @param[out] buf Buffer to write packet to
154  *
155  * @return packet length (0 = timeout, -1 = error)
156  */
157 SR_PRIV int ebd_read_message(struct sr_serial_dev_inst *serial, size_t length,
158         uint8_t *buf)
159 {
160         int ret;
161         gboolean message_complete;
162         size_t turn, max_turns;
163         size_t message_length;
164
165         /* Check parameters. */
166         if (serial == NULL) {
167                 sr_err("Serial device to receive packet missing.");
168                 return -1;
169         }
170         if (length < 3) {
171                 sr_err("Packet buffer not large enough.");
172                 return -1;
173         }
174         if (buf == NULL) {
175                 sr_err("Packet buffer missing.");
176                 return -1;
177         }
178
179         message_complete = FALSE;
180         turn = 0;
181         max_turns = 200;
182         message_length = 0;
183         buf[message_length] = 0;
184
185         /* Try to read data. */
186         while (!message_complete && turn < max_turns) {
187                 /* Wait for header byte. */
188                 message_length = 0;
189                 while ((buf[0] != MSG_FRAME_BEGIN) && (turn < max_turns)) {
190                         ret = serial_read_blocking(serial, &buf[0], 1, serial_timeout(serial, 1));
191                         if (ret < 0) {
192                                 sr_err("Error %d reading byte.", ret);
193                                 return ret;
194                         } else if (ret == 1) {
195                                 if (buf[message_length] != MSG_FRAME_BEGIN) {
196                                         sr_warn("Not frame begin byte %02x received",
197                                                 buf[message_length]);
198                                 } else {
199                                         sr_dbg("Message header received: %02x",
200                                                 buf[message_length]);
201                                         message_length += ret;
202                                 }
203                         }
204                         turn++;
205                 }
206                 /* Read until end byte. */
207                 while ((buf[message_length - 1] != MSG_FRAME_END)
208                         && (message_length < length) && (turn < max_turns)) {
209
210                         ret = serial_read_blocking(serial, &buf[message_length], 1, serial_timeout(serial, 1));
211                         if (ret < 0) {
212                                 sr_err("Error %d reading byte.", ret);
213                                 return ret;
214                         } else if (ret == 1) {
215                                 if (buf[message_length] == MSG_FRAME_BEGIN) {
216                                         sr_warn("Frame begin before end received");
217                                         message_length = 1;
218                                 } else {
219                                         sr_dbg("Message data received: %02x",
220                                                 buf[message_length]);
221                                         message_length += ret;
222                                 }
223                         }
224                         turn++;
225                 }
226                 /* Verify frame. */
227                 if (turn < max_turns) {
228                         if (buf[message_length - 1] == MSG_FRAME_END) {
229                                 message_complete = TRUE;
230                                 sr_dbg("Message end received");
231                         } else {
232                                 sr_warn("Frame end not received");
233                         }
234                 } else {
235                         sr_warn("Invalid data and timeout");
236                 }
237         }
238
239         if (message_complete && message_length > 2) {
240                 ret = message_length;
241         } else if (turn >= max_turns) {
242                 ret = 0;
243         } else {
244                 ret = -1;
245         }
246         return ret;
247 }
248
249 static void ebd_send_value(const struct sr_dev_inst *sdi, struct sr_channel *ch,
250         float value, enum sr_mq mq, enum sr_unit unit, int digits)
251 {
252         struct sr_datafeed_packet packet;
253         struct sr_datafeed_analog analog;
254         struct sr_analog_encoding encoding;
255         struct sr_analog_meaning meaning;
256         struct sr_analog_spec spec;
257
258         sr_analog_init(&analog, &encoding, &meaning, &spec, digits);
259         analog.meaning->channels = g_slist_append(NULL, ch);
260         analog.num_samples = 1;
261         analog.data = &value;
262         analog.meaning->mq = mq;
263         analog.meaning->unit = unit;
264         analog.meaning->mqflags = SR_MQFLAG_DC;
265
266         packet.type = SR_DF_ANALOG;
267         packet.payload = &analog;
268         sr_session_send(sdi, &packet);
269         g_slist_free(analog.meaning->channels);
270 }
271
272 SR_PRIV int ebd_receive_data(int fd, int revents, void *cb_data)
273 {
274         struct sr_dev_inst *sdi;
275         struct dev_context *devc;
276         struct sr_serial_dev_inst *serial;
277         float current, current_limit;
278         float voltage, voltage_dp, voltage_dm, uvc_threshold;
279         uint8_t reply[MSG_MAX_LEN];
280         int ret, i;
281         uint8_t checksum;
282
283         (void)revents;
284         (void)fd;
285
286         if (!(sdi = cb_data))
287                 return FALSE;
288
289         if (!(devc = sdi->priv))
290                 return FALSE;
291
292         serial = sdi->conn;
293         current_limit = devc->current_limit;
294         uvc_threshold = devc->uvc_threshold;
295
296         ret = ebd_read_message(serial, MSG_MAX_LEN, reply);
297
298         /* Tests for correct message. */
299         if (ret == -1) {
300                 sr_err("Can't receive messages");
301                 return SR_ERR;
302         } else if (ret == 0) {
303                 sr_err("No messages received");
304                 devc->running = FALSE;
305                 return 0;
306         } else if ((ret != 19) ||
307                 ((reply[1] != 0x00) && (reply[1] != 0x0a) && (reply[1] != 0x64) && (reply[1] != 0x6e))) {
308
309                 sr_info("Not measurement message received");
310                 return ret;
311         }
312
313         /* Verify checksum */
314         checksum = 0;
315         for (i = 1; i < ret - 1; i++) {
316                 checksum ^= reply[i];
317         }
318         if (checksum != 0) {
319                 sr_warn("Invalid checksum");
320                 /* Don't exit on wrong checksum, the device can recover */
321                 return ret;
322         }
323
324         devc->running = TRUE;
325         if ((reply[1] == 0x00) || (reply[1] == 0x64))
326                 devc->load_activated = FALSE;
327         else if ((reply[1] == 0x0a) || (reply[1] == 0x6e))
328                 devc->load_activated = TRUE;
329
330         /* Calculate values. */
331         current = decode_value(reply[2], reply[3], 10000.0);
332         voltage = decode_value(reply[4], reply[5], 1000.0);
333         voltage_dp = decode_value(reply[6], reply[7], 1000.0);
334         voltage_dm = decode_value(reply[8], reply[9], 1000.0);
335         if (reply[1] == 0x0a) {
336                 current_limit = decode_value(reply[10], reply[11], 1000.0);
337                 uvc_threshold = decode_value(reply[12], reply[13], 100.0);
338         }
339
340         sr_dbg("VBUS current %.04f A", current);
341         sr_dbg("VBUS voltage %.03f V", voltage);
342         sr_dbg("D+ voltage %.03f V", voltage_dp);
343         sr_dbg("D- voltage %.03f V", voltage_dm);
344         if (reply[1] == 0x0a) {
345                 sr_dbg("Current limit %.03f A", current_limit);
346                 sr_dbg("UVC threshold %.03f V", uvc_threshold);
347         }
348
349         /* Update load state. */
350         if (devc->load_activated && ebd_current_is0(devc)) {
351                 ebd_loadtoggle(serial, devc);
352         } else if (!devc->load_activated && !ebd_current_is0(devc)) {
353                 ebd_loadstart(serial, devc);
354         } else if (devc->load_activated &&
355                 ((current_limit != devc->current_limit) || (uvc_threshold != devc->uvc_threshold))) {
356
357                 sr_dbg("Adjusting limit from %.03f A %.03f V to %.03f A %.03f V",
358                         current_limit, uvc_threshold, devc->current_limit,
359                         devc->uvc_threshold);
360                 send_cfg(serial, devc);
361         }
362
363         /* Begin frame. */
364         std_session_send_df_frame_begin(sdi);
365
366         /* Values */
367         ebd_send_value(sdi, sdi->channels->data, voltage,
368                 SR_MQ_VOLTAGE, SR_UNIT_VOLT, 3);
369         ebd_send_value(sdi, sdi->channels->next->data, current,
370                 SR_MQ_CURRENT, SR_UNIT_AMPERE, 4);
371         ebd_send_value(sdi, sdi->channels->next->next->data, voltage_dp,
372                 SR_MQ_VOLTAGE, SR_UNIT_VOLT, 3);
373         ebd_send_value(sdi, sdi->channels->next->next->next->data, voltage_dm,
374                 SR_MQ_VOLTAGE, SR_UNIT_VOLT, 3);
375
376         /* End frame. */
377         std_session_send_df_frame_end(sdi);
378
379         sr_sw_limits_update_samples_read(&devc->limits, 1);
380         if (sr_sw_limits_check(&devc->limits))
381                 sr_dev_acquisition_stop(sdi);
382
383         return TRUE;
384 }
385
386 SR_PRIV int ebd_get_current_limit(const struct sr_dev_inst *sdi, float *current)
387 {
388         struct dev_context *devc;
389
390         if (!(devc = sdi->priv))
391                 return SR_ERR;
392
393         g_mutex_lock(&devc->rw_mutex);
394         *current = devc->current_limit;
395         g_mutex_unlock(&devc->rw_mutex);
396
397         return SR_OK;
398 }
399
400 SR_PRIV int ebd_set_current_limit(const struct sr_dev_inst *sdi, float current)
401 {
402         struct dev_context *devc;
403         int ret;
404
405         if (!(devc = sdi->priv))
406                 return SR_ERR;
407
408         g_mutex_lock(&devc->rw_mutex);
409         devc->current_limit = current;
410
411         if (!devc->running) {
412                 sr_dbg("Setting current limit later.");
413                 g_mutex_unlock(&devc->rw_mutex);
414                 return SR_OK;
415         }
416
417         sr_dbg("Setting current limit to %fV.", current);
418
419         if (devc->load_activated) {
420                 if (ebd_current_is0(devc)) {
421                         /* Stop load. */
422                         ret = ebd_loadtoggle(sdi->conn, devc);
423                 } else {
424                         /* Send new current. */
425                         ret = send_cfg(sdi->conn, devc);
426                 }
427         } else {
428                 if (ebd_current_is0(devc)) {
429                         /* Nothing to do. */
430                         ret = SR_OK;
431                 } else {
432                         /* Start load. */
433                         ret = ebd_loadstart(sdi->conn, devc);
434                 }
435         }
436
437         g_mutex_unlock(&devc->rw_mutex);
438
439         return ret;
440 }
441
442 SR_PRIV int ebd_get_uvc_threshold(const struct sr_dev_inst *sdi, float *voltage)
443 {
444         struct dev_context *devc;
445
446         if (!(devc = sdi->priv))
447                 return SR_ERR;
448
449         g_mutex_lock(&devc->rw_mutex);
450         *voltage = devc->uvc_threshold;
451         g_mutex_unlock(&devc->rw_mutex);
452
453         return SR_OK;
454 }
455
456 SR_PRIV int ebd_set_uvc_threshold(const struct sr_dev_inst *sdi, float voltage)
457 {
458         struct dev_context *devc;
459         int ret;
460
461         if (!(devc = sdi->priv))
462                 return SR_ERR;
463
464         g_mutex_lock(&devc->rw_mutex);
465         devc->uvc_threshold = voltage;
466
467         if (!devc->running) {
468                 sr_dbg("Setting uvc threshold later.");
469                 g_mutex_unlock(&devc->rw_mutex);
470                 return SR_OK;
471         }
472
473         sr_dbg("Setting uvc threshold to %fV.", voltage);
474
475         if (devc->load_activated) {
476                 if (ebd_current_is0(devc)) {
477                         /* Stop load. */
478                         ret = ebd_loadtoggle(sdi->conn, devc);
479                 } else {
480                         /* Send new current. */
481                         ret = send_cfg(sdi->conn, devc);
482                 }
483         } else {
484                 if (ebd_current_is0(devc)) {
485                         /* Nothing to do. */
486                         ret = SR_OK;
487                 } else {
488                         /* Start load. */
489                         ret = ebd_loadstart(sdi->conn, devc);
490                 }
491         }
492
493         g_mutex_unlock(&devc->rw_mutex);
494
495         return ret;
496 }
497
498 SR_PRIV gboolean ebd_current_is0(struct dev_context *devc)
499 {
500         return devc->current_limit < 0.001;
501 }