+ /* TODO: Parts of this code need to be improved later. */
+
+ /* State machine. */
+ if (devc->state == SEND_INIT) {
+ /* On the first run, send the "init" command. */
+ buf[0] = 0x10;
+ buf[1] = 0x04;
+ buf[2] = 0x0d;
+ sr_spew("Sending init command: %02x %02x %02x.",
+ buf[0], buf[1], buf[2]);
+ if ((ret = serial_write(serial, buf, 3)) < 0) {
+ sr_err("Error sending init command: %d.", ret);
+ return FALSE;
+ }
+ devc->state = GET_INIT_REPLY;
+ } else if (devc->state == GET_INIT_REPLY) {
+ /* If we just sent the "init" command, get its reply. */
+ if ((ret = serial_read(serial, buf, 2)) < 0) {
+ sr_err("Error reading init reply: %d.", ret);
+ return FALSE;
+ }
+ sr_spew("Received init reply: %02x %02x.", buf[0], buf[1]);
+ /* Expected reply: 0x05 0x0d */
+ if (buf[0] != 0x05 || buf[1] != 0x0d) {
+ sr_err("Received incorrect init reply, retrying.");
+ devc->state = SEND_INIT;
+ return TRUE;
+ }
+ devc->state = SEND_PACKET_REQUEST;
+ } else if (devc->state == SEND_PACKET_REQUEST) {
+ /* Request a packet (send 0x30 ZZ 0x0d). */
+ buf[0] = 0x30;
+ buf[1] = 0x00; /* ZZ */
+ buf[2] = 0x0d;
+ sr_spew("Sending data request command: %02x %02x %02x.",
+ buf[0], buf[1], buf[2]);
+ if ((ret = serial_write(serial, buf, 3)) < 0) {
+ sr_err("Error sending request command: %d.", ret);
+ return FALSE;
+ }
+ devc->buflen = 0;
+ devc->state = GET_PACKET;
+ } else if (devc->state == GET_PACKET) {
+ /* Read a packet from the device. */
+ ret = serial_read(serial, devc->buf + devc->buflen,
+ 4 - devc->buflen);
+ if (ret < 0) {
+ sr_err("Error reading packet: %d.", ret);
+ return TRUE;
+ }
+
+ devc->buflen += ret;
+
+ /* Didn't receive all 4 bytes, yet. */
+ if (devc->buflen != 4)
+ return TRUE;
+
+ sr_spew("Received packet: %02x %02x %02x %02x.", devc->buf[0],
+ devc->buf[1], devc->buf[2], devc->buf[3]);
+
+ /* Expected reply: AA BB ZZ+1 0x0d */
+ if (devc->buf[2] != 0x01 || devc->buf[3] != 0x0d) {
+ sr_err("Received incorrect request reply, retrying.");
+ devc->state = SEND_PACKET_REQUEST;
+ return TRUE;
+ }
+
+ decode_packet(sdi);
+
+ devc->state = SEND_PACKET_REQUEST;
+ } else {
+ sr_err("Invalid state: %d.", devc->state);
+ return FALSE;
+ }