diff sw/sniff-rx/initflush.c @ 22:b112c2df6c43

sw: simtrace3-sniff-rx program written, compiles
author Mychaela Falconia <falcon@freecalypso.org>
date Tue, 22 Aug 2023 06:16:44 +0000
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sw/sniff-rx/initflush.c	Tue Aug 22 06:16:44 2023 +0000
@@ -0,0 +1,41 @@
+/*
+ * FTDI chip+driver combo (specifically the combination of FTDI chips and
+ * ftdi_sio driver in Linux, not sure who is the actual culprit) exhibits
+ * this unpleasant behaviour: even though we request "please flush all
+ * previous input" when we set our termios params, old accumulated serial
+ * Rx bytes still remain in some buffer somewhere, and a newly started
+ * serial application receives this stale garbage.  As a workaround,
+ * we do an additional flush of our own: we put the fd in non-blocking mode
+ * and keep reading and discarding data until we get EAGAIN or EWOULDBLOCK.
+ */
+
+#include <sys/types.h>
+#include <sys/errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+extern int target_fd;
+
+void
+init_serial_flush()
+{
+	u_char buf[512];
+	int cc;
+
+	set_serial_nonblock(1);
+	for (;;) {
+		cc = read(target_fd, buf, sizeof buf);
+		if (cc <= 0)
+			break;
+	}
+	if (cc == 0) {
+		fprintf(stderr,
+			"read EOF from serial port during initial flush\n");
+		exit(1);
+	}
+	if (errno == EAGAIN || errno == EWOULDBLOCK)
+		return;		/* success */
+	perror("serial port read");
+	exit(1);
+}