2016-05-29 14:21:16 -05:00
|
|
|
#include <errno.h>
|
|
|
|
|
|
|
|
#include <tabby/link.h>
|
|
|
|
#include <tabby/printer.h>
|
|
|
|
|
|
|
|
#define PACKET_RECV_ERROR_THRESHOLD 30
|
|
|
|
|
|
|
|
static uint16_t checksum(tabby_printer_packet_header *header, void *body) {
|
|
|
|
uint16_t checksum = header->data[2]
|
|
|
|
+ header->data[3]
|
|
|
|
+ header->data[4]
|
|
|
|
+ header->data[5];
|
|
|
|
|
|
|
|
size_t i;
|
|
|
|
|
|
|
|
for (i=0; i<header->size; i++) {
|
|
|
|
checksum += ((uint8_t *)body)[i];
|
|
|
|
}
|
|
|
|
|
|
|
|
return checksum;
|
|
|
|
}
|
|
|
|
|
|
|
|
int tabby_printer_packet_recv(int fd, tabby_printer_packet_header *header,
|
|
|
|
void *body,
|
2016-05-30 21:53:10 -05:00
|
|
|
uint16_t *sum) {
|
2016-05-29 14:21:16 -05:00
|
|
|
ssize_t len;
|
|
|
|
|
|
|
|
size_t i = 0,
|
2016-05-30 21:53:10 -05:00
|
|
|
b = 0;
|
2016-05-29 14:21:16 -05:00
|
|
|
|
2016-05-30 21:53:10 -05:00
|
|
|
uint8_t value;
|
2016-05-29 14:21:16 -05:00
|
|
|
|
|
|
|
memset(header, '\0', sizeof(*header));
|
2016-05-30 21:53:10 -05:00
|
|
|
|
|
|
|
*sum = 0;
|
2016-05-29 14:21:16 -05:00
|
|
|
|
2016-05-31 23:28:55 -05:00
|
|
|
while ((len = read(fd, &value, 1)) >= 0) {
|
2016-05-30 21:53:10 -05:00
|
|
|
if (i == 0) {
|
2016-05-31 19:32:20 -05:00
|
|
|
if (value == 0x88) {
|
2016-05-30 21:53:10 -05:00
|
|
|
header->preamble[0] = value;
|
|
|
|
i++;
|
|
|
|
} else {
|
2016-05-31 19:32:20 -05:00
|
|
|
continue;
|
2016-05-29 14:21:16 -05:00
|
|
|
}
|
2016-05-30 21:53:10 -05:00
|
|
|
} else if (i == 1) {
|
|
|
|
if (value == 0x33) {
|
|
|
|
header->preamble[1] = value;
|
|
|
|
i++;
|
|
|
|
} else {
|
|
|
|
i = 0;
|
2016-05-31 19:32:20 -05:00
|
|
|
continue;
|
2016-05-30 21:53:10 -05:00
|
|
|
}
|
|
|
|
} else if (i == 2) {
|
|
|
|
header->type = value;
|
|
|
|
i++;
|
|
|
|
} else if (i == 3) {
|
|
|
|
header->compression = value;
|
|
|
|
i++;
|
|
|
|
} else if (i == 4) {
|
|
|
|
header->size = value;
|
|
|
|
i++;
|
|
|
|
} else if (i == 5) {
|
|
|
|
header->size |= value << 8;
|
|
|
|
i++;
|
2016-05-31 19:32:20 -05:00
|
|
|
|
2016-05-30 21:53:10 -05:00
|
|
|
b = 0;
|
|
|
|
} else if (b < header->size) {
|
|
|
|
((uint8_t *)body)[b++] = value;
|
|
|
|
} else if (b == header->size) {
|
|
|
|
*sum = value;
|
|
|
|
b++;
|
|
|
|
} else if (b == header->size + 1) {
|
|
|
|
*sum |= value << 8;
|
|
|
|
|
|
|
|
if (checksum(header, body) != *sum) {
|
|
|
|
errno = EIO;
|
2016-05-29 14:21:16 -05:00
|
|
|
|
2016-05-30 21:53:10 -05:00
|
|
|
goto error_io;
|
|
|
|
}
|
2016-05-29 14:21:16 -05:00
|
|
|
|
2016-05-30 21:53:10 -05:00
|
|
|
return errno = 0;
|
|
|
|
}
|
2016-05-29 14:21:16 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
error_io:
|
|
|
|
return -errno;
|
|
|
|
}
|
|
|
|
|
|
|
|
int tabby_printer_response_send(int fd, uint8_t device, uint8_t status) {
|
|
|
|
uint8_t response[2] = {
|
|
|
|
device, status
|
|
|
|
};
|
|
|
|
|
2016-05-31 23:28:55 -05:00
|
|
|
return write(fd, &response, sizeof(response));
|
2016-05-29 14:21:16 -05:00
|
|
|
}
|