Files
csprng_test/uart.c
T
2026-06-15 10:31:58 +02:00

89 lines
2.2 KiB
C

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <termios.h>
#include "common.h"
int set_serial_device(int fd){
struct termios serial_cnf;
if (tcgetattr(fd, &serial_cnf) < 0){
printf("It's a TTY device\n");
close(fd);
return -1;
}
cfsetispeed(&serial_cnf, B115200);
cfsetospeed(&serial_cnf, B115200);
serial_cnf.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
serial_cnf.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable software flow control
serial_cnf.c_iflag &= ~(INLCR | ICRNL | IGNCR);
serial_cnf.c_cflag &= ~CRTSCTS; // Disable hardware control
serial_cnf.c_cflag |= CREAD | CLOCAL;
/* Set 8N1 (8 bits, no parity, 1 stop bit) */
serial_cnf.c_cflag &= ~PARENB; // No parity
serial_cnf.c_cflag &= ~CSTOPB; // 1 stop bit
serial_cnf.c_cflag &= ~CSIZE; // clear data
serial_cnf.c_cflag |= CS8; // 8 data bits
serial_cnf.c_oflag &= ~OPOST; // Disable output processing
serial_cnf.c_cc[VMIN] = 1;
serial_cnf.c_cc[VTIME] = 0;
tcflush(fd, TCIFLUSH);
if (tcsetattr(fd, TCSANOW/*TCSAFLUSH*/, &serial_cnf) < 0) {
printf("Failed to serial_cnfure the serial port\n");
close(fd);
return -1;
}
return 0;
}
static unsigned short csum(unsigned short *buf, int nwords) {
unsigned long sum = 0;
while (nwords > 0) {
sum += *buf++;
nwords--;
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
int send_uart(struct prng **s_prng){
int fd;
if ((fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY)) < 0){
printf("Failed to read the device\n");
exit(-1);
}
set_serial_device(fd);
char buffer[sizeof(struct prng)];
u_int8_t cmd = 1;
//printf("Sending command...\n");
size_t len = write(fd, &cmd, 1);
//printf("Data sent: %ld\n\n", len);
// Read data
//printf("Receiving data...\n");
int total_len = 0;
while (total_len < sizeof(struct prng)){
len = read(fd, buffer + total_len, sizeof(struct prng));
//printf("Len recv: %ld\n", len);
total_len += len;
}
*s_prng = (struct prng *)buffer;
close(fd);
return 0;
}