+typedef gboolean (*packet_valid_t)(const uint8_t *buf);
+
+/**
+ * Try to find a valid packet in a serial data stream
+ *
+ * @param fd File descriptor of the serial port.
+ * @param buf Buffer containing the bytes to write.
+ * @param count Size of the buffer.
+ * @param packet_size Size, in bytes, of a valid packet
+ * @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 he given timeout,
+ * SR_ERR upon failure.
+ */
+static int serial_stream_detect(struct sr_serial_dev_inst *serial,
+ uint8_t *buf, size_t *buflen,
+ const size_t packet_size,
+ packet_valid_t is_valid,
+ uint64_t timeout_ms, int baudrate)
+{
+ uint64_t start;
+ uint64_t time;
+ uint64_t byte_delay_us;
+ size_t ibuf, i;
+ int len;
+ const size_t maxlen = *buflen;
+
+ if(maxlen < (packet_size << 1) ) {
+ sr_err("Buffer size must be at least twice the packet size");
+ return SR_ERR;
+ }
+
+ timeout_ms *= 1000;
+ /* Assume 8n1 transmission. That is 10 bits for every byte */
+ byte_delay_us = 10000000 / baudrate;
+ start = g_get_monotonic_time();
+
+ i = ibuf = len = 0;
+ while (ibuf < maxlen) {
+ len = serial_read(serial, &buf[ibuf], 1);
+ if (len > 0)
+ ibuf+= len;
+ if ((ibuf - i) >= packet_size) {
+ /* We have at least a packet's worth of data */
+ if (is_valid(&buf[i])) {
+ time = g_get_monotonic_time()-start;
+ time /= 1000;
+ sr_spew("Serial detection took %li ms", time);
+ *buflen = ibuf;
+ return SR_OK;
+ }
+ /* Not a valid packet; continue searching */
+ i++;
+ }
+ if (g_get_monotonic_time() - start > timeout_ms) {
+ /* Timeout */
+ sr_warn("Serial detection timeout");
+ break;
+ }
+ g_usleep(byte_delay_us);
+ }
+
+ *buflen = ibuf;
+ return SR_ERR;
+
+}
+