|
| 1 | +#include <stdint.h> |
| 2 | +#include <stdio.h> |
| 3 | + |
| 4 | +#include <logging/log.h> |
| 5 | +#include <logging/log_ctrl.h> |
| 6 | +#include <zephyr.h> |
| 7 | + |
| 8 | +#include <common.h> |
| 9 | +#include <message.h> |
| 10 | + |
| 11 | +LOG_MODULE_REGISTER(message, GLOBAL_LOG_LEVEL); |
| 12 | + |
| 13 | +struct message *message_from_buffer(struct k_heap *heap, uint8_t *data, size_t length) |
| 14 | +{ |
| 15 | + if (length < HEADER_LENGTH || |
| 16 | + length > MAX_MESSAGE_SIZE || |
| 17 | + length != data[PAYLOAD_LENGTH_POS] + HEADER_LENGTH) |
| 18 | + { |
| 19 | + LOG_DBG("Invalid packet"); |
| 20 | + return NULL; |
| 21 | + } |
| 22 | + struct message *msg = (struct message *)k_heap_alloc(heap, sizeof(struct message), K_NO_WAIT); |
| 23 | + if (msg == NULL) |
| 24 | + { |
| 25 | + LOG_ERR("Cannot allocate heap memory"); |
| 26 | + return NULL; |
| 27 | + } |
| 28 | + memcpy(msg->src_mac, data + SRC_MAC_POS, sizeof(uint8_t) * 6); |
| 29 | + memcpy(msg->original_src_mac, data + ORIGINAL_SRC_MAC_POS, sizeof(uint8_t) * 6); |
| 30 | + memcpy(msg->dst_mac, data + DST_MAC_POS, sizeof(uint8_t) * 6); |
| 31 | + msg->msg_number = data[MSG_NUMBER_POS]; |
| 32 | + msg->ttl = data[TTL_POS]; |
| 33 | + msg->payload_len = data[PAYLOAD_LENGTH_POS]; |
| 34 | + msg->payload = (uint8_t *)k_heap_alloc(heap, msg->payload_len, K_NO_WAIT); |
| 35 | + if (msg->payload == NULL) |
| 36 | + { |
| 37 | + LOG_ERR("Cannot allocate heap memory"); |
| 38 | + k_heap_free(heap, msg); |
| 39 | + return NULL; |
| 40 | + } |
| 41 | + memcpy(msg->payload, data + DATA_POS, msg->payload_len); |
| 42 | + return msg; |
| 43 | +} |
| 44 | + |
| 45 | +size_t message_to_buffer(uint8_t *buffer, struct message *msg) |
| 46 | +{ |
| 47 | + memcpy(buffer + SRC_MAC_POS, msg->src_mac, sizeof(uint8_t) * 6); |
| 48 | + memcpy(buffer + ORIGINAL_SRC_MAC_POS, msg->original_src_mac, sizeof(uint8_t) * 6); |
| 49 | + memcpy(buffer + DST_MAC_POS, msg->dst_mac, sizeof(uint8_t) * 6); |
| 50 | + buffer[MSG_NUMBER_POS] = msg->msg_number; |
| 51 | + buffer[TTL_POS] = msg->ttl; |
| 52 | + buffer[PAYLOAD_LENGTH_POS] = msg->payload_len; |
| 53 | + memcpy(buffer + DATA_POS, msg->payload, msg->payload_len); |
| 54 | + return msg->payload_len + HEADER_LENGTH; |
| 55 | +} |
0 commit comments