//
// Created by nano on 4/26/25.
//
#ifndef COMMS_H
#define COMMS_H
#include <libserialport.h>
#include <stdlib.h>

typedef u_int8_t byte;

typedef enum { ALL_BYTES, NOT_ENOUGH_BYTES, ERROR } comm_result;
int comm_output_waiting() ;
/**
 *  Initializes the serial communication for the usb -> uart board
 */
void comm_init_communication();

/**
 * Generates port list from present serial ports.
 * @param port_list pointer to port list to set.
 */
void comm_get_port_list(struct sp_port ***port_list);

void comm_list_serial_ports(struct sp_port **port_list);

/**
 * Opens communication to the selected serial port and sets the correct parameters for the zigbee carrier board.
 */
void comm_open_port();

/**
 * Ends the serial communication for the usb -> uart board
 */
void comm_end_communication();

/**
 * Await fresh data from the serial port
 * @param timeout timeout for waiting for a byte to be ready to read
 * @return if there is data available (1 or 0)
 */
int comm_await_data_ready(int timeout);

/**
 * Check if the serial port is ready to be written to.
 * @param timeout timeout for waiting for a byte to be ready to read
 * @return if data can be written (1 or 0)
 */
int comm_await_ready_for_tx(int timeout);

/**
 *Do a nonblocking read from the serial port
 *@param data pointer to data to read
 *@param amount_of_bytes amount of bytes to read from uart buffer
 *@return if whole buffer was filled, part of the buffer was filled or error
 */
comm_result comm_nonblocking_read(byte *data, int amount_of_bytes);

/**
 *Do a blocking read from the serial port
 *@param data pointer to data to read
 *@param amount_of_bytes amount of bytes to read from uart buffer
 *@param timeout how long to wait for data to be filled
 *@return if whole buffer was filled, part of the buffer was filled or error
 */
comm_result comm_blocking_read(byte *data, int amount_of_bytes, int timeout);

/**
 *Do a nonblocking write from the serial port
 *@param data pointer to data to write
 *@param amount_of_bytes amount of bytes to write to uart
 *@return if whole buffer was written, part of the buffer was written or error
 */
comm_result comm_nonblocking_write(byte *data, int amount_of_bytes);

/**
 *Do a nonblocking write from the serial port
 *@param data pointer to data to write
 *@param amount_of_bytes amount of bytes to write to uart
 *@param timeout how long to wait for data to be filled
 *@return if whole buffer was written, part of the buffer was written or error
 */
comm_result comm_blocking_write(byte *data, int amount_of_bytes, int timeout);

/** Helper function for error handling.
 * Taken from libserialport examples. */
int check(enum sp_return result);


#endif //COMMS_H
