rework validate

This commit is contained in:
Qukich 2023-06-25 16:04:52 +03:00
parent 8e4329c9d3
commit 321722d9b1
2 changed files with 24 additions and 27 deletions

View File

@ -3,6 +3,9 @@
#include <stdio.h>
#include <fcntl.h>
#define START_FLAG 0x7E
#define END_FLAG 0x7E
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;
@ -34,7 +37,7 @@ void connect(Client* client) {
HDLCFrame frame;
init_HDLCFrame(&frame, 0, 0, data + 3, 256 - 6);
if (validate(client, &frame, data, 256)) {
if (validate(data, 256)) {
return;
} else {
// Connection failed
@ -66,32 +69,28 @@ void receive_data(Client* client, uint8_t* recivedData, int lenRecived) {
}
}
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
#include <stdbool.h>
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;
}
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); // Replace "port" with your serial port device
int serial_port = open(port, O_RDWR);
if (serial_port < 0) {
perror("Error opening the serial port");

View File

@ -1,6 +1,4 @@
//
// Created by 79513 on 19.06.2023.
//
#ifndef CLIENT_H
#define CLIENT_H
@ -23,7 +21,7 @@ void init_Client(Client* client, bool test_is_valid, uint8_t address, void* seri
void connect(Client* client);
void send(Client* client, uint8_t* data, size_t data_length);
void receive_data(Client* client, uint8_t* recivedData, int lenRecived);
bool validate(Client* client, HDLCFrame* frame, uint8_t* received_data, size_t received_length);
bool validate(const uint8_t* frame, size_t length);
int sendSerialData(const char* port, uint8_t* data, size_t length);
int receiveSerialData(const char* port, uint8_t* data, int length);