This repository has been archived on 2023-10-10. You can view files and clone it, but cannot push or open issues/pull-requests.
hackfridge/terminal/barcode.c

110 lines
2.3 KiB
C

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include "config.h"
int g_BarcodeFD;
int barcode_initialize(char *Device)
{
g_BarcodeFD = open(Device, O_RDWR | O_NONBLOCK);
if (g_BarcodeFD == -1)
{
printf("Failed to open barcode reader TTY.\n");
return 1;
}
struct termios Config;
if (!isatty(g_BarcodeFD))
{
printf("Barcode TTY is not a TTY!\n");
return 1;
}
if (tcgetattr(g_BarcodeFD, &Config))
{
printf("Could not get barcode TTY config.\n");
return 1;
}
memset(&Config, 0, sizeof(Config));
Config.c_iflag = 0;
Config.c_oflag = 0;
Config.c_lflag = 0;
Config.c_cflag = CS8|CREAD|CLOCAL;
Config.c_cc[VMIN] = 1;
Config.c_cc[VTIME] = 0;
if (cfsetispeed(&Config, B9600) < 0 || cfsetospeed(&Config, B9600) < 0)
{
printf("Could not set barcode TTY baudrate!\n");
return 1;
}
if (tcsetattr(g_BarcodeFD, TCSAFLUSH, &Config) < 0)
{
printf("Could not set barcode TTY attributes!\n");
return 1;
}
tcflush(g_BarcodeFD, TCIOFLUSH);
return 0;
}
int _async_read_timeout(int FD, char *DataOut, int NumBytes, int Timeout)
{
fd_set Read, Write, Special;
FD_ZERO(&Read);
FD_ZERO(&Write);
FD_ZERO(&Special);
FD_SET(FD, &Read);
struct timeval TTimeout;
memset(&TTimeout, 0, sizeof(TTimeout));
TTimeout.tv_sec = Timeout;
int ResultFD = select(FD + 1, &Read, &Write, &Special, &TTimeout);
if (ResultFD == -1)
{
return -1;
}
return read(FD, DataOut, NumBytes);
}
int barcode_read(char *BarcodeOut)
{
int BytesRead = 0;
// read the first byte with a long timeout
BytesRead += _async_read_timeout(g_BarcodeFD, BarcodeOut + BytesRead, 14, BARCODE_TIMEOUT);
if (BytesRead == -1)
{
printf("Timeout on reading first barcode bytes.\n");
return 1;
}
while (BytesRead < 14)
{
int Result = _async_read_timeout(g_BarcodeFD, BarcodeOut + BytesRead, 14 - BytesRead, 1);
if (Result == -1)
{
printf("Timeout on reading following bytecode bytes.\n");
return 1;
}
BytesRead += Result;
}
BarcodeOut[13] = 0;
return 0;
}