From ba45fbbead04ce1cf515e33a32f277c84d9e7334 Mon Sep 17 00:00:00 2001 From: k2-alfadhala <khalid2.al-fadhala@live.uwe.ac.uk> Date: Sun, 13 Apr 2025 15:42:39 +0000 Subject: [PATCH] prtocol.c --- protocol.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 protocol.c diff --git a/protocol.c b/protocol.c new file mode 100644 index 0000000..3190624 --- /dev/null +++ b/protocol.c @@ -0,0 +1,68 @@ +#include "protocol.h" +#include "usb_serial.h" +#include <string.h> +#include <stdio.h> +#include <stdlib.h> + +void packet_init(Packet *pkt, uint8_t *data, size_t len) { + pkt->start = 0xAAAA; + pkt->type = 1; + pkt->length = sizeof(Packet) + len - sizeof(uint8_t*); + pkt->seq = 1; + pkt->dtype = 1; + pkt->data = malloc(len); + + if (pkt->data) { + memcpy(pkt->data, data, len); + pkt->chk = compute_checksum(pkt->data, len); + } else { + pkt->chk = 0; + } +} + +void packet_free(Packet *pkt) { + if (pkt->data) { + free(pkt->data); + pkt->data = NULL; + } +} + +int proto_send(const Packet* pkt) { + if (!usb_serial_connected()) + return -1; + + if (pkt->length > MAX_PAYLOAD_SIZE) + return -2; + + uint8_t buf[sizeof(Packet)]; + memcpy(buf, pkt, sizeof(Packet) - 1); + buf[sizeof(Packet) - 1] = compute_checksum(buf, sizeof(Packet) - 1); + + int sent = usb_serial_write(buf, sizeof(Packet)); + return (sent == sizeof(Packet)) ? sent : -3; +} + +int proto_recv(Packet* pkt, int max_size) { + if (max_size < sizeof(Packet)) + return -1; + + int got = usb_serial_read((uint8_t*)pkt, sizeof(Packet)); + if (got != sizeof(Packet)) + return -2; + + if (compute_checksum((uint8_t*)pkt, sizeof(Packet) - 1) != pkt->chk) + return -3; + + return got; +} + +void proto_cleanup(void) { + usb_serial_cleanup(); +} +void proto_disconnect(void) {} +uint8_t compute_checksum(const uint8_t* data, int len) { + uint8_t chk = 0; + for (int i = 0; i < len; i++) + chk ^= data[i]; + return chk; +} -- GitLab