commit 5a718f4e0005fd215cf4362025175a187e26cdaa
parent cc23c47c55bfd937c7e30d0e01438e951e9e5e04
Author: Matsuda Kenji <info@mtkn.jp>
Date: Sun, 24 Aug 2025 07:30:57 +0900
add console programme
Diffstat:
A | cons/cons.c | | | 130 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 130 insertions(+), 0 deletions(-)
diff --git a/cons/cons.c b/cons/cons.c
@@ -0,0 +1,130 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/termios.h>
+#include <unistd.h>
+
+int device_open();
+int setparms(int fd, int baud);
+int flush(int fd);
+
+#define ERRLEN 128
+char err[ERRLEN];
+
+int
+main(void)
+{
+ int fd;
+ int ret = 0;
+ struct termios *term;
+
+ fd = device_open();
+ if (fd < 0) {
+ fprintf(stderr, "can't open device: %s\n", strerror(errno));
+ return 1;
+ }
+ if (setparms(fd, 115200) < 0) {
+ fprintf(stderr, "setparm: %s\n", err);
+ return 1;
+ }
+
+ if (flush(fd) < 0) {
+ fprintf(stderr, "flush: %s\n", strerror(errno));
+ ret = errno;
+ goto defer;
+ }
+
+ char buf[10];
+ int n;
+ for (;;) {
+ n = read(0, buf, 10);
+ if (n == 0) {
+ fprintf(stderr, "eof\n");
+ break;
+ } else if (n < 0) {
+ fprintf(stderr, "read stdin: %s\n", strerror(errno));
+ ret = errno;
+ goto defer;
+ }
+ n = write(fd, buf, n);
+ if (n < 0) {
+ fprintf(stderr, "write to tty %s\n", strerror(errno));
+ ret = errno;
+ goto defer;
+ }
+ n = read(fd, buf, 10);
+ if (n < 0) {
+ fprintf(stderr, "read tty: %s\n", strerror(errno));
+ ret = errno;
+ goto defer;
+ }
+ n = write(1, buf, n);
+ if (n < 0) {
+ fprintf(stderr, "write to stdout %s\n", strerror(errno));
+ ret = errno;
+ goto defer;
+ }
+ }
+
+defer:
+ close(fd);
+ return ret;
+}
+
+int
+device_open()
+{
+ int n;
+ int fd;
+
+ fd = open("/dev/ttyU0", O_RDWR|O_NDELAY|O_NOCTTY);
+ if (fd < 0)
+ return -1;
+ n = fcntl(fd, F_GETFL, 0);
+ fcntl(fd, F_SETFL, n&~O_NDELAY);
+ return fd;
+}
+
+int
+setparms(int fd, int baud)
+{
+ struct termios tty;
+ if (tcgetattr(fd, &tty) < 0) {
+ snprintf(err, ERRLEN, "tcgetattr: %s", strerror(errno));
+ return -1;
+ }
+ if (cfsetospeed(&tty, (speed_t)baud) < 0) {
+ snprintf(err, ERRLEN, "cfsetospeed: %s", strerror(errno));
+ return -1;
+ }
+ if (cfsetispeed(&tty, (speed_t)baud) < 0) {
+ snprintf(err, ERRLEN, "cfsetispeed: %s", strerror(errno));
+ return -1;
+ }
+ tty.c_cflag = (tty.c_cflag&~CSIZE) | CS8;
+ tty.c_iflag = IGNBRK;
+ tty.c_lflag = 0;
+ tty.c_oflag = 0;
+ tty.c_cflag |= CLOCAL|CREAD;
+ tty.c_cc[VMIN] = 1;
+ tty.c_cc[VTIME] = 5;
+ tty.c_iflag &= ~(IXON|IXOFF|IXANY); // TODO: xon, xoff?
+ // TODO: parity
+ tty.c_cflag &= ~CSTOPB; // stop bit == 1
+ if (tcsetattr(fd, TCSANOW, &tty) < 0) {
+ snprintf(err, ERRLEN, "tcseattr: %s", strerror(errno));
+ return -1;
+ }
+ // TODO: rs485
+ return 0;
+}
+
+int
+flush(int fd)
+{
+ int out = 0;
+ return ioctl(fd, TIOCFLUSH, &out);
+}