How to open a tty device in noncanonical mode on Linux using .NET Core

你离开我真会死。 提交于 2020-06-29 03:51:16

问题


I'm using .NET Core on an embedded Linux platform with good success so far. I just ran into a problem with trying to open a tty device in raw (noncanonical mode) though. If I was using regular C or C++ I would call cfmakeraw() after opening the device, but how do I do that from a .NET Core app?

The device I need to work with is a CDC ACM function driver for the USB client connector, i.e. it's a virtual COM port. It appears in my system as /dev/ttyGS0. I can open the device and then read from it and write to it using this code:

FileStream vcom = new FileStream("/dev/ttyGS0", FileMode.Open);

Because the tty device opens in canonical mode by default I don't receive any characters until the user sends the carriage return character at the end of the line of text. I need to receive each character as it is sent, rather than waiting untill the carriage return is sent, i.e. I need to use raw mode for the tty device.

The code below does not work because .NET Core does not realize that this device is a virtual serial port, so it throws an exception when I try to open it this way. When I open the real UART devices using SerialPort then they do behave in raw mode as expected.

SerialPort serialPort = new SerialPort("/dev/ttyGS0);


回答1:


Since you have a terminal device, you could try to alter its termios configuration prior to actually using it.
Try issuing the shell command stty -F /dev/ttyGS0 raw before you run your program.

The raw setting will make the following termios changes (according to the stty man page) for noncanonical mode:

-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixany -ixoff -imaxbel 
-opost 
-icanon -isig -xcase -iuclc  
min 1 time 0

Note that no c_cflag attributes (e.g. baudrate, parity, character size) nor echo attributes (as you already know) are changed by the raw setting.

For comparison the libc cfmakeraw() routine that you mention makes the following termios settings:

  t->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
  t->c_oflag &= ~OPOST;
  t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
  t->c_cflag &= ~(CSIZE|PARENB);
  t->c_cflag |= CS8;
  t->c_cc[VMIN] = 1;      /* read returns when one char is available.  */
  t->c_cc[VTIME] = 0;

You can use stty -F /dev/ttyGS0 sane to restore the terminal to a default termios configuration.



来源:https://stackoverflow.com/questions/58404561/how-to-open-a-tty-device-in-noncanonical-mode-on-linux-using-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!