76 lines
1.5 KiB
C
76 lines
1.5 KiB
C
#include <errno.h>
|
|
#include <error.h>
|
|
#include <stdio.h>
|
|
#include <memory.h>
|
|
#include <malloc.h>
|
|
#include <termios.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
|
|
#include "iqbasic.h"
|
|
|
|
#define DIE(...) error_at_line(1, errno, __FILE__, __LINE__, __VA_ARGS__)
|
|
|
|
void vario_send(int fd, const char *line)
|
|
{
|
|
int len = strlen(line);
|
|
char *buf = (char*)malloc(sizeof(char)*len+3);
|
|
int rc;
|
|
sprintf(buf, "%s\r\n", line);
|
|
do {
|
|
rc = write(fd, buf, len+2);
|
|
} while (rc == -1 && errno == EINTR);
|
|
if (rc == -1)
|
|
DIE("write");
|
|
}
|
|
|
|
int vario_recv(int fd, char *buf, int maxlen)
|
|
{
|
|
int pos = 0;
|
|
int n;
|
|
char c;
|
|
|
|
do {
|
|
do {
|
|
n = read(fd, &c, 1);
|
|
} while(n == -1 && errno == EINTR);
|
|
|
|
if(n == -1)
|
|
DIE("read");
|
|
if(n == 1)
|
|
buf[pos++] = c;
|
|
|
|
} while(c != '\n' && pos < maxlen);
|
|
|
|
if(pos >= maxlen)
|
|
DIE("buffer too small");
|
|
|
|
return pos;
|
|
}
|
|
|
|
int vario_open(char *device)
|
|
{
|
|
int fd = open(device, O_NOCTTY | O_NONBLOCK | O_RDWR);
|
|
if (fd == -1)
|
|
DIE("%s", device);
|
|
if (tcflush(fd, TCIOFLUSH) == -1)
|
|
error(1, errno, "tcflush %s", device, strerror(errno));
|
|
|
|
struct termios termios;
|
|
memset(&termios, 0, sizeof termios);
|
|
termios.c_iflag = IGNPAR;
|
|
termios.c_cflag = CLOCAL | CREAD | CS8;
|
|
cfsetispeed(&termios, B57600);
|
|
cfsetospeed(&termios, B57600);
|
|
if (tcsetattr(fd, TCSANOW, &termios) == -1)
|
|
DIE("tcsetattr: %s: %s", device, strerror(errno));
|
|
|
|
return fd;
|
|
}
|
|
|
|
void vario_close(int fd)
|
|
{
|
|
if (close(fd) == -1)
|
|
DIE("close: %s", strerror(errno));
|
|
}
|