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