libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
packet.cpp
1#include "packet.hpp"
2
3#include "crc.hpp"
4#include "libxr_mem.hpp"
5
6using namespace LibXR;
7
8void Topic::PackedDataHeader::SetDataLen(uint32_t len)
9{
10 data_len_raw[0] = static_cast<uint8_t>(len);
11 data_len_raw[1] = static_cast<uint8_t>(len >> 8);
12 data_len_raw[2] = static_cast<uint8_t>(len >> 16);
13}
14
15uint32_t Topic::PackedDataHeader::GetDataLen() const
16{
17 return static_cast<uint32_t>(data_len_raw[0]) |
18 static_cast<uint32_t>(data_len_raw[1]) << 8 |
19 static_cast<uint32_t>(data_len_raw[2]) << 16;
20}
21
22void Topic::PackedDataHeader::SetTimestamp(MicrosecondTimestamp timestamp)
23{
24 uint64_t value = static_cast<uint64_t>(timestamp);
25 ASSERT((value >> 48U) == 0);
26 for (size_t i = 0; i < sizeof(timestamp_us_raw); i++)
27 {
28 timestamp_us_raw[i] = static_cast<uint8_t>(value >> (i * 8U));
29 }
30}
31
32MicrosecondTimestamp Topic::PackedDataHeader::GetTimestamp() const
33{
34 uint64_t value = 0;
35 for (size_t i = 0; i < sizeof(timestamp_us_raw); i++)
36 {
37 value |= static_cast<uint64_t>(timestamp_us_raw[i]) << (i * 8U);
38 }
39 return MicrosecondTimestamp(value);
40}
41
42void Topic::PackBytes(uint32_t topic_name_crc32, RawData buffer,
43 MicrosecondTimestamp timestamp, ConstRawData data)
44{
45 ASSERT(buffer.addr_ != nullptr);
46 ASSERT(buffer.size_ >= PACK_BASE_SIZE + data.size_);
47
48 auto* pack = reinterpret_cast<PackedData<uint8_t>*>(buffer.addr_);
49
50 LibXR::Memory::FastCopy(&pack->raw.data_, data.addr_, data.size_);
51
52 pack->raw.header_.prefix = PACKET_PREFIX;
53 pack->raw.header_.version = PACKET_VERSION;
54 pack->raw.header_.topic_name_crc32 = topic_name_crc32;
55 pack->raw.header_.SetDataLen(data.size_);
56 pack->raw.header_.SetTimestamp(timestamp);
57 pack->raw.header_.pack_header_crc8 =
58 CRC8::Calculate(&pack->raw, sizeof(PackedDataHeader) - sizeof(uint8_t));
59
60 uint8_t* crc8_pack = reinterpret_cast<uint8_t*>(
61 reinterpret_cast<uint8_t*>(pack) + PACK_BASE_SIZE + data.size_ - sizeof(uint8_t));
62 *crc8_pack = CRC8::Calculate(pack, PACK_BASE_SIZE - sizeof(uint8_t) + data.size_);
63}
static uint8_t Calculate(const void *raw, size_t len)
计算数据的 CRC8 校验码 / Computes the CRC8 checksum for the given data
Definition crc_o3.cpp:3
只读原始数据视图 / Immutable raw data view
size_t size_
数据字节数 / Data size in bytes
const void * addr_
数据起始地址 / Data start address
static void FastCopy(void *dst, const void *src, size_t size)
快速内存拷贝 / Fast memory copy
微秒时间戳 / Microsecond timestamp
可写原始数据视图 / Mutable raw data view
size_t size_
数据字节数 / Data size in bytes
void * addr_
数据起始地址 / Data start address
static void PackBytes(uint32_t topic_name_crc32, RawData buffer, MicrosecondTimestamp timestamp, ConstRawData data)
将一段 payload 字节和 topic 元数据拼成 packet / Pack one payload byte range together with topic metadata into on...
Definition packet.cpp:42
LibXR 命名空间
Definition ch32_can.hpp:14