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