+
+/**
+ * Try to find a valid packet in a serial data stream.
+ *
+ * @param serial Previously initialized serial port structure.
+ * @param buf Buffer containing the bytes to write.
+ * @param buflen Size of the buffer.
+ * @param get_packet_size Callback that assesses the size of incoming packets.
+ * @param is_valid Callback that assesses whether the packet is valid or not.
+ * @param timeout_ms The timeout after which, if no packet is detected, to
+ * abort scanning.
+ * @param baudrate The baudrate of the serial port. This parameter is not
+ * critical, but it helps fine tune the serial port polling
+ * delay.
+ *
+ * @return SR_OK if a valid packet is found within the given timeout,
+ * SR_ERR upon failure.
+ */
+SR_PRIV int brymen_stream_detect(struct sr_serial_dev_inst *serial,
+ uint8_t *buf, size_t *buflen,
+ packet_length_t get_packet_size,
+ packet_valid_t is_valid,
+ uint64_t timeout_ms, int baudrate)
+{
+ int64_t start, time, byte_delay_us;
+ size_t ibuf, i, maxlen;
+ int status, len, packet_len, stream_len;
+
+ maxlen = *buflen;
+
+ sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
+ "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
+
+ /* Assume 8n1 transmission. That is 10 bits for every byte. */
+ byte_delay_us = 10 * (1000000 / baudrate);
+ start = g_get_monotonic_time();
+
+ packet_len = i = ibuf = len = 0;
+ while (ibuf < maxlen) {
+ len = serial_read(serial, &buf[ibuf], maxlen - ibuf);
+ if (len > 0) {
+ ibuf += len;
+ sr_spew("Read %d bytes.", len);
+ }
+
+ time = g_get_monotonic_time() - start;
+ time /= 1000;
+
+ stream_len = ibuf - i;
+ if (stream_len > 0 && packet_len == 0) {
+ /* How large of a packet are we expecting? */
+ packet_len = stream_len;
+ status = get_packet_size(&buf[i], &packet_len);
+ switch(status) {
+ case PACKET_HEADER_OK:
+ /* We know how much data we need to wait for. */
+ break;
+ case PACKET_NEED_MORE_DATA:
+ /* We did not receive the full header. */
+ packet_len = 0;
+ break;
+ case PACKET_INVALID_HEADER:
+ default:
+ /*
+ * We had enough data, but here was an error in
+ * parsing the header. Restart parsing from the
+ * next byte.
+ */
+ packet_len = 0;
+ i++;
+ break;
+ }
+ }
+
+ if ((stream_len >= packet_len) && (packet_len != 0)) {
+ /* We have at least a packet's worth of data. */
+ if (is_valid(&buf[i])) {
+ sr_spew("Found valid %d-byte packet after "
+ "%" PRIu64 "ms.", packet_len, time);
+ *buflen = ibuf;
+ return SR_OK;
+ } else {
+ sr_spew("Got %d bytes, but not a valid "
+ "packet.", packet_len);
+
+ }
+
+ /* Not a valid packet. Continue searching. */
+ i++;
+ packet_len = 0;
+ }
+
+ if (time >= (int64_t)timeout_ms) {
+ /* Timeout */
+ sr_dbg("Detection timed out after %dms.", time);
+ break;
+ }
+ g_usleep(byte_delay_us);
+ }
+
+ *buflen = ibuf;
+ sr_err("Didn't find a valid packet (read %d bytes).", ibuf);
+
+ return SR_ERR;
+}