#include #include #include #include #include #include #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/ttyUSB0", O_RDWR | O_NOCTTY)) < 0){ printf("Failed to read the device\n"); exit(-1); } set_serial_device(fd); char buffer[sizeof(struct prng)]; char buf_cmd[sizeof(struct cmd)]; struct cmd s_cmd = {0}; s_cmd.version = CSPRNG_VERS; s_cmd.cmd = CSPRNG_CMD_GET_RNG; memcpy(buf_cmd, &s_cmd, sizeof(struct cmd)); //printf("Sending command...\n"); size_t len = write(fd, &buf_cmd, sizeof(struct cmd)); //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; }