我在gtk的串行通道上读写之间存在计时问题

问题描述

该程序旨在通过PL2303 usb转换器与远程微控制器在不可靠的串行通道上进行通信。主循环使用g_io_add_watch监听来自微型计算机的数据。然后,它调用g_io_read_chars读取数据,并调用g_io_write_chars发送一个字节的确认。微型回声。从ReadStationMessage内部调用读取和写入。如果micro的响应速度很慢,则两次调用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,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;
 }

解决方法

已修复!写完后我需要g-io-channel-flush。