79 lines
1.7 KiB
C
79 lines
1.7 KiB
C
/*
|
|
* AUTHOR: Alexander Popov <iiiypuk {at} fastmail.fm>
|
|
* DESC: ...
|
|
*/
|
|
|
|
#ifndef DEVICE_H_
|
|
#define DEVICE_H_
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
json_t *device_get_available() {
|
|
struct sp_port **port_list;
|
|
enum sp_return result = sp_list_ports(&port_list);
|
|
|
|
json_t *ports_data = NULL;
|
|
json_t *ports_array = NULL;
|
|
|
|
ports_array = json_array();
|
|
|
|
if (result == SP_OK) {
|
|
/* Get the name of the port. */
|
|
int i;
|
|
for (i = 0; port_list[i] != NULL; i++) {
|
|
struct sp_port *port = port_list[i];
|
|
char *port_name = sp_get_port_name(port);
|
|
|
|
json_array_append(ports_array, json_string(port_name));
|
|
}
|
|
|
|
sp_free_port_list(port_list);
|
|
}
|
|
|
|
ports_data = json_object();
|
|
json_object_set_new(ports_data, "ports", ports_array);
|
|
|
|
return ports_data;
|
|
}
|
|
|
|
int device_connect(const char *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));
|
|
|
|
return 0;
|
|
}
|
|
|
|
int device_disconnect() {
|
|
sp_close(serial_port);
|
|
}
|
|
|
|
#endif
|