我不确定您在这里真正要寻找的是什么;对此进行简单编码将非常简单,而且这个问题看起来不值得我使用成熟的 FSM 表驱动方法。
这是一些类似 C 的伪代码:
double pc = 0.01;
int sensorsfd;
void loop(void) {
for (;;) {
fd_set readfds, writefds, exceptfds;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
FD_SET(sensorsfd, &readfds);
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 1; /* 0.001 seconds */
int r;
send_polling_packet();
r = select(sensorsfd+1, &readfds, &writefds, &exceptfds, &tv);
if (r == -1 && errno == EINTR) {
continue;
} else if (r == -1) {
perror("select() failed");
exit(1);
} else if (r == 0) {
/* timeout expired */
pc = min (pc + 0.01, 1.0);
} else if (r == 1) {
/* sensorsfd won't block when reading it */
packet_t p = read_packet(sensorsfd);
/* should also handle _no packet_ if the sensors
socket returns EOF */
if (packet_corrupted(p)) {
pc /= 2;
} else {
handle_packet(p);
}
} else {
/* error in program logic */
}
}
}
伪代码,因为我只是写了这个并且没有测试它的机制。如果您的程序变得比这复杂得多,您可能希望将所有select(2)
设置封装到它自己的函数中,并可能包含处理来自传感器套接字的数据包的所有细节。