#include "client.h" #include #include #define START_FLAG 0x7E #define END_FLAG 0x7E void init_Client(Client* client, bool test_is_valid, uint8_t address) { client->TEST_IS_VALID = test_is_valid; client->address = address; client->_send_sequence_number = 0; client->poll_final = 1; client->_receive_sequence_number = 0; } void connect(Client* client) { UFrame u_frame; init_UFrame(&u_frame, client->address, client->poll_final, "BP", NULL, 0); uint8_t result[256]; create_frame(&u_frame.base, result); // Wait for acknowledgment frame bool flag = true; uint8_t data; while(flag){ data = uart_read(); if (data > 0){ flag = false; } } HDLCFrame frame; init_HDLCFrame(&frame, 0, 0, &data + 3, 256 - 6); if (validate(&data, 256)) { return; } else { // Connection failed } } void send(Client* client, uint8_t* data, size_t data_length) { connect(client); IFrame i_frame; init_IFrame(&i_frame, client->address, client->_receive_sequence_number, client->poll_final, client->_send_sequence_number, data, data_length); uint8_t result[256]; create_frame(&i_frame.base, result); uart_send_byte(*i_frame.base.data); client->_send_sequence_number++; } void receive_data(uint8_t* recivedData) { bool flag = true; while(flag){ *recivedData = uart_read(); if (recivedData > 0){ flag = false; } } } #include bool validate(const uint8_t* frame, size_t length) { if (length < 4 || frame[0] != START_FLAG || frame[length - 1] != END_FLAG) { // Invalid frame length or missing start/end flag return false; } uint16_t received_fcs = (frame[length - 3] << 8) | frame[length - 2]; uint16_t calculated_fcs = 0xFFFF; for (size_t i = 1; i < length - 3; i++) { uint8_t byte = frame[i]; calculated_fcs = (calculated_fcs >> 8) ^ (calculated_fcs << 8) ^ byte; calculated_fcs &= 0xFFFF; } return received_fcs == calculated_fcs; } int sendSerialData(const char* port, uint8_t* data, size_t length) { int serial_port = open(port, O_RDWR); if (serial_port < 0) { perror("Error opening the serial port"); return -1; } ssize_t bytes_written = write(serial_port, data, length); if (bytes_written < 0) { perror("Error writing to the serial port"); return -1; } close(serial_port); return bytes_written; } int receiveSerialData(const char* port, uint8_t* data, int length) { int serial_port = open(port, O_RDWR); // Replace "port" with your serial port device if (serial_port < 0) { perror("Error opening the serial port"); return -1; } ssize_t bytes_read = read(serial_port, data, length); if (bytes_read < 0) { perror("Error reading from the serial port"); return -1; } close(serial_port); return bytes_read; }