0

该程序旨在通过不可靠的串行通道通过 PL2303 USB 转换器与远处的微控制器进行通信。主循环使用 g_io_add_watch 来监听来自 micro 的数据。然后它调用 g_io_read_chars 读取数据并调用 g_io_write_chars 发送一个单字节确认。微信回响了这一点。从 ReadStationMessage 中调用读取和写入。如果微响应缓慢,ReadStationMessage() 函数会被调用两次,一次是读取数据,一次是接收回波。但是,如果它立即响应,则仅调用一次 ReadStationMessage() 并将回显字节附加到数据中。我不明白当 g_io_write_chars 直到 g_io_read_chars 返回之后才发送确认并且微在收到确认之前什么都不做时,这是怎么可能的。

    #include <gtk/gtk.h>
    #include <errno.h>
    #include <fcntl.h> 
    #include <termios.h>

    int set_interface_attribs(int fd, int speed)
    {
     struct termios tty;
     if (tcgetattr(fd, &tty) < 0) {
      g_print("Error from tcgetattr: %s\n", strerror(errno));
      return -1; }

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

     tty.c_cc[VMIN] = 0; tty.c_cc[VTIME] = 1;

     if (tcsetattr(fd, TCSANOW, &tty) != 0) {
       g_print("Error from tcsetattr: %s\n", strerror(errno));
       return -1;  }
    return 0;
   }

   static gboolean ReadStationMessage( GIOChannel *channel,         GIOCondition condition, guchar* user_data )
   {
    guchar buf[128];
    gsize bytes_read, bytes_written;
    gint i;
    g_print("\nentering ReadStationMessage\n");
    g_io_channel_read_chars( channel, buf, 128, &bytes_read, NULL );
    for( i=0; i<bytes_read; i++ ) g_print("%u ", buf[i]);

    buf[0] = 0;
    g_io_channel_write_chars( channel, buf, 1, &bytes_written, NULL );
    return TRUE;
 }

 int main( int argc, char *argv[] )
 {
  char *portname = "/dev/ttyUSB0";
  gint fd;
  GIOChannel *channel;
  static guchar user_data[128];
  GError *error=NULL;
  guint EventSource_id;

  fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC );
  set_interface_attribs(fd, B9600);
  channel = g_io_channel_unix_new(fd);
  g_io_channel_set_encoding(channel, NULL, &error); // raw data, no encoding
  GIOCondition condition = G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL;
  gtk_init (&argc, &argv);
  EventSource_id = g_io_add_watch( channel, condition, (GIOFunc) ReadStationMessage, user_data );
  return 0;
 }
4

1 回答 1

0

固定的!写入后我需要 g-io-channel-flush 。

于 2020-09-19T05:19:20.417 回答