magstrip/uart.c
2021-02-14 17:54:00 +01:00

116 lines
2.6 KiB
C

/*
* Copyright (C) 2009 Nicole Faerber <nicole.faerber@dpin.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <termios.h>
static int fd = -1;
int open_uart(char *device, speed_t baud)
{
struct termios ti;
if (!device)
device = "/dev/ttyS0";
fd = open(device, O_RDWR | O_NOCTTY);
if (fd < 0) {
fprintf(stderr, "Can't open serial port '%s': %s (%d)\n", device, strerror(errno), errno);
fd = -1;
return -1;
}
tcflush(fd, TCIOFLUSH);
if (tcgetattr(fd, &ti) < 0) {
fprintf(stderr, "Can't get port settings: %s (%d)\n", strerror(errno), errno);
close(fd);
fd = -1;
return -1;
}
cfmakeraw(&ti);
ti.c_cflag |= CLOCAL;
ti.c_cflag &= ~CRTSCTS;
//ti.c_cflag |= CRTSCTS;
//ti.c_cflag |= PARENB;
ti.c_cflag |= IGNBRK;
ti.c_cc[VMIN] = 1;
ti.c_cc[VTIME] = 0;
if (baud == 0)
baud = B115200;
cfsetospeed(&ti, baud);
if (tcsetattr(fd, TCSANOW, &ti) < 0) {
fprintf(stderr, "Can't change port settings: %s (%d)\n", strerror(errno), errno);
close(fd);
fd = -1;
return -1;
}
tcflush(fd, TCIOFLUSH);
if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK) < 0) {
fprintf(stderr, "Can't set non blocking mode: %s (%d)\n", strerror(errno), errno);
close(fd);
fd = -1;
return -1;
}
return 0;
}
int uart_get_fd(void)
{
return fd;
}
void put_uart(uint8_t ch)
{
if (write(fd, &ch, 1) < 0)
fprintf(stderr, "UART write error\n");
}
void write_uart(char *buf, int size)
{
int remain = size;
int ret;
do {
ret = write(fd, buf, size);
if (ret < 0)
fprintf(stderr, "UART write error\n");
remain -= ret;
buf += ret;
} while (remain && (ret>=0));
}
uint8_t get_uart(uint8_t *ch)
{
int res = read(fd, ch, 1);
return res > 0 ? res : 0;
}
int uart_read(char *rxbuf, int maxlen)
{
return read(fd, rxbuf, maxlen);
}
void close_uart(void)
{
close(fd);
fd = -1;
}