#include "client.h" #include #include #include void init_Client(Client* client, bool test_is_valid, uint8_t address, void* serial_port) { client->TEST_IS_VALID = test_is_valid; client->address = address; client->_send_sequence_number = 0; client->poll_final = 1; client->_receive_sequence_number = 0; client->serial_port = serial_port; } 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); void* serial_port = client->serial_port; // Write result to serial port to establish connection // ... // Wait for acknowledgment frame // Read bytes from serial port // ... uint8_t received[256]; // Example buffer size, adjust as needed size_t received_length = 0; // Process received bytes // ... // Validate acknowledgment frame HDLCFrame frame; init_HDLCFrame(&frame, 0, 0, received + 3, received_length - 6); if (validate(client, &frame, received, received_length)) { // Connection established } 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); void* serial_port = client->serial_port; sendSerialData(client->serial_port, &i_frame.base.data, i_frame.base.data_length); client->_send_sequence_number++; } void receive_data(Client* client) { void* serial_port = client->serial_port; // Read data from serial port // ... // Process received data // ... } bool validate(Client* client, HDLCFrame* frame, uint8_t* received_data, size_t received_length) { uint8_t control = received_data[2]; if ((control & 0x01) == 0) { // I-frame printf("i frame\n"); uint8_t send_sequence_number = (control >> 1) & 0x07; uint16_t crc = (received_data[received_length - 2] << 8) | received_data[received_length - 3]; uint16_t calculated_crc = calculate_fcs(received_data + 1, received_length - 4); if (crc == calculated_crc && send_sequence_number == client->_receive_sequence_number && client->TEST_IS_VALID) { client->_receive_sequence_number++; return true; } } else if ((control & 0x03) == 1) { // S-frame printf("s frame\n"); // Handle S-frame } else { // U-frame printf("u frame\n"); // Handle U-frame } return false; } int sendSerialData(const char* port, const char* data, size_t 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_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; }