c++ - 为什么这个串行/调制解调器代码会弄乱我的终端显示?

标签 c++ linux terminal serial-port modem

我已经编写了一些代码,基本上使用正则表达式/dev/tty* 在 unix 系统上查找任何调制解调器,然后对于任何匹配项,查看是否可以打开端口,如果可以,则发送 AT 命令并检查响应消息是否包含字符“OK”。

该代码确实找到了调制解调器,但不幸的是它弄乱了终端显示。见下文。我注意到它还会打印 AT 命令 - 请参阅下面的输出。为什么我的终端显示改变了,我该如何解决?

运行程序后,如果您输入一个命令并输入,例如 ls,该命令不会显示,但当您按回车键时,您会看到输出。

代码如下:

#include <iostream>
#include <string>
#include <unordered_map>
#include <iomanip>

#include <memory>

#include <sstream>
#include <thread>

#include <iostream>
#include <filesystem>
#include <regex>

#include <unistd.h>  // close
#include <fcntl.h>   // open, O_RDWR, etc
#include <termios.h>

#include <string.h>

#include <sys/select.h>  // timeouts for read

#include <sys/timeb.h>   // measure time taken

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        // Error from tcgetattr - can use strerror(errno)
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
      // Error from tcsetattr- use strerror(errno)
        return -1;
    }
    return 0;
}

long enumerate_ports(std::unordered_map <std::string, std::string>& ports) {

    // ls /dev | grep ^tty.*
    const std::regex my_filter( "^tty.*" );
    std::string path = "/dev/";
    for (const auto & entry : std::filesystem::directory_iterator(path)) {
     std::smatch sm;

     std::string tmp = entry.path().filename().string();
     // if we have a regex match attempt to open port and send AT command
     if (std::regex_match(tmp, sm, my_filter)) {
     std::string portname = entry.path().string();
         int fd = ::open(portname.c_str(), O_RDWR | O_NOCTTY);
         if (fd < 0) {
       // Error opening port
             continue;
         } else {
       // port was opened successfully
           // try to write AT command and do we get an OK response
           // baudrate 9600, 8 bits, no parity, 1 stop bit
           if(set_interface_attribs(fd, B9600) != 0) {
             ::close(fd);
         continue;
           }

           int wlen = ::write(fd, "AT\r\n", 4);
           if (wlen != 4) {
         // Error from write
               ::close(fd);
               continue;
           }

          // tcdrain() waits until all output written to the object referred 
          // to by fd has been transmitted.
           tcdrain(fd);

           fd_set set;
           struct timeval timeout;

           FD_ZERO(&set); /* clear the set */
           FD_SET(fd, &set); /* add our file descriptor to the set */

           timeout.tv_sec = 0;
           timeout.tv_usec = 100000; // 100 milliseconds

           // wait for data to be read or timeout
           int rv = select(fd + 1, &set, NULL, NULL, &timeout);
           if(rv > 0) {  // no timeout or error
               unsigned char buf[80];
               const int bytes_read = ::read(fd, buf, sizeof(buf) - 1);
               if (bytes_read > 0) {
                   buf[bytes_read] = 0;
                   unsigned char* p = buf;
                   // scan for "OK"
                   for (int i = 0; i < bytes_read; ++i) {
             if (*p == 'O' && i < bytes_read - 1 && *(p+1) == 'K') {
                       // we have a positive response from device so add to ports
                       ports[portname] = "";
                       break;
                     }
                     p++;
                   }
               }
        }
       ::close(fd);
         }
     }
   }

   return ports.size();
}


int main() {

    struct timeb start, end;
    int diff;
    ftime(&start);

    // get list of ports available on system
    std::unordered_map <std::string, std::string> ports;
    long result = enumerate_ports(ports);
    std::cout << "No. found modems: " << result << std::endl;
    for (const auto& item : ports) {
        std::cout << item.first << "->" << item.second << std::endl;
    }

    ftime(&end);
    diff = (int) (1000.0 * (end.time - start.time)
        + (end.millitm - start.millitm));

    printf("Operation took %u milliseconds\n", diff);
}

输出:

acomber@mail:~/Documents/projects/modem/serial/gdbplay$ ls
main.cpp  main.o  Makefile  serial
acomber@mail:~/Documents/projects/modem/serial/gdbplay$ make serial
g++ -Wall -Werror -ggdb3 -std=c++17 -pedantic  -c main.cpp
g++ -o serial -Wall -Werror -ggdb3 -std=c++17 -pedantic  main.o -L/usr/lib -lstdc++fs
acomber@mail:~/Documents/projects/modem/serial/gdbplay$ sudo ./serial
[sudo] password for acomber: 
AT
No. found modems: 1
                   /dev/ttyACM0->
                                 Operation took 8643 milliseconds
                                                                 acomber@mail:~/Documents/projects/modem/serial/gdbplay$

最佳答案

Why does this serial/modem code mess up my terminal display?

精确的答案要求您在执行代码之前发布终端的设置,即 stty -a

The code does find a modem but unfortunately it messes up the terminal display.

最简单(即直接)的解决方法/解决方案是坚持保存然后恢复终端的 termios 设置的旧(但很少遵循)建议,如 this example .

您的代码中需要的简单更改类似于(请忽略 C 和 C++ 的混合;我只知道 C)以下补丁。

 struct termios savetty;

 int set_interface_attribs(int fd, int speed)
 {
+    struct termios tty;

     if (tcgetattr(fd, &tty) < 0) {
         // Error from tcgetattr - can use strerror(errno)
         return -1;
     }
+    savetty = tty;    /* preserve original settings for restoration */

     cfsetospeed(&tty, (speed_t)speed);
     cfsetispeed(&tty, (speed_t)speed);

然后在 enumerate_ports() 中,::close(fd); 的最后两个实例需要替换为将执行恢复的序列:

+    if (tcsetattr(fd, &savetty) < 0) {
+        // report cannot restore attributes
+    }
     ::close(fd);

After running the program, if you enter a command and enter, eg ls, the command is not shown ...

这显然是清除 ECHO 属性的结果。
“丢失”回车可能是由于清除了 OPOST。
其他被您的程序清除但可能预期由 shell 设置的显着属性是 ICANON、ICRNL 和 IEXTEN。
但是,与其尝试确定究竟需要撤消什么,正确且有保证的修复方法是简单地将 termios 设置恢复到其原始状态。

另一种(惰性)方法是在执行程序后使用 stty sane 命令。

关于c++ - 为什么这个串行/调制解调器代码会弄乱我的终端显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56315825/

相关文章:

c++ - 底层 STL:在没有新 vector 的情况下将 std::vector 连接到自身

c++ - C++中的哈希表/无序映射

c# - 无法解析/理解 "overriding virtual function differs only by calling convention"

regex - 使用 bash 删除字符串的一部分

linux - 浏览器尝试下载 .pl 文件而不是执行它 - apache2、perl cgi 脚本、ubuntu

linux - 如何删除文件中的终端控制转义序列?

根据分号表现不同的 C++ 程序

python - 启用 PyROOT Ubuntu 14.04

visual-studio-code - 如何在 VS Code 中快速关闭所有打开的终端?

git - 在 git 中提交现在需要 gpg?