snipplets.dev/code/C/libserialport/listen.c

134 lines
2.9 KiB
C

#include <libserialport.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <signal.h>
/* Helper function for error handling. */
int check(enum sp_return result);
void handle_sigint(int sig);
bool INTERRUPT = false;
int main(int argc, char **argv) {
struct sp_port *serial_port;
char *port_name;
const int size = 256;
char *buffer = malloc(size + 1);
const unsigned int timeout = 1000;
int result;
/* Get the port name from the command line. */
if (argc != 2) {
printf("Usage: %s <port>\n\n", argv[0]);
struct sp_port **port_list;
enum sp_return result = sp_list_ports(&port_list);
/* Getting the available ports. */
if (result != SP_OK) {
puts("Getting available ports failed!");
} else {
puts("Available ports:");
int i;
for (i = 0; port_list[i] != NULL; i++) {
/* Get the name of the port. */
struct sp_port *port = port_list[i];
char *port_name = sp_get_port_name(port);
printf(" * %s\n", port_name);
}
printf("\nAvailable %d ports.\n", i);
sp_free_port_list(port_list);
}
return -1;
} else {
port_name = argv[1];
}
printf("Connecting to '%s'...\n", port_name);
check(sp_get_port_by_name(port_name, &serial_port));
check(sp_open(serial_port, SP_MODE_READ_WRITE));
check(sp_set_baudrate(serial_port, 9600));
check(sp_set_bits(serial_port, 8));
check(sp_set_parity(serial_port, SP_PARITY_NONE));
check(sp_set_stopbits(serial_port, 1));
check(sp_set_flowcontrol(serial_port, SP_FLOWCONTROL_NONE));
puts("Connected.");
signal(SIGINT, handle_sigint);
FILE *output_file;
output_file = fopen("./abc.txt", "w");
/* Reading lines from serial port. */
bool reading = true;
while (reading && !INTERRUPT) {
int pos = 0;
/* Character-by-character reading. */
while (pos < size) {
result = check(sp_blocking_read(serial_port, buffer + pos, 1, timeout));
if (result == -1) {
puts("Error reading from serial port");
reading = false;
break;
} else if (result == 0) {
puts("No more data");
break;
} else {
if (buffer[pos] == '\n') {
buffer[pos] = '\0';
break;
}
pos++;
}
}
puts(buffer);
fputs(buffer, output_file);
}
fclose(output_file);
free(buffer);
return 0;
}
/* Helper function for error handling. */
int check(enum sp_return result) {
char *error_message;
switch (result) {
case SP_ERR_ARG:
puts("Error: Invalid argument.");
abort();
case SP_ERR_FAIL:
error_message = sp_last_error_message();
printf("Error: Failed: %s\n", error_message);
sp_free_error_message(error_message);
abort();
case SP_ERR_SUPP:
puts("Error: Not supported.");
abort();
case SP_ERR_MEM:
puts("Error: Couldn't allocate memory.");
abort();
case SP_OK:
default:
return result;
}
}
void handle_sigint(int sig) { INTERRUPT = true; }