GKD.RoboCtrl
RoboMaster Linux 电控:异步 IO、设备驱动与机器人控制
载入中...
搜索中...
未找到
serial.h
浏览该文件的文档.
1
6#pragma once
7
8#include <array>
9#include <asio.hpp>
10#include <cstddef>
11#include <cstdint>
12#include <format>
13#include <span>
14#include <string>
15#include <utility>
16#include <vector>
17
18#include "core/async.hpp"
19#include "io/base.hpp"
20#include "utils/concepts.hpp"
21#include "utils/utils.hpp"
22#include "io/write_queue.hpp"
23#include "core/logger.h"
24
25namespace roboctrl::io{
26
27
31class serial : public keyed_io_base<uint8_t>, public logable<serial>{
32public:
36 struct info_type{
37 using key_type = std::string;
38 using owner_type = serial;
39
40 std::string name;
41 std::string device;
42 unsigned int baud_rate {};
43 bool raw {false}; // Dedicated byte stream; excludes 55 AA key framing.
44
45 const std::string& key()const{
46 return name;
47 }
48 };
49
50 using key_type = std::uint8_t;
51
55 explicit serial(info_type info);
56
58 void start();
59
63 awaitable<void> send(key_type key,byte_span data);
64
67 if (!info_.raw) throw std::logic_error("raw callback requires serial.raw=true");
68 raw_callbacks_.add([fn](data_ptr data) mutable { return fn(byte_span{*data}); });
69 }
70 awaitable<void> send_raw(byte_span data);
71
76
78 inline std::string desc()const{
79 return std::format("serial port ({} on {} @ {}bps)",info_.name,info_.device,info_.baud_rate);
80 }
81private:
82 void process_receive_buffer();
83
84private:
85 asio::serial_port port_;
86 write_queue write_queue_;
87 info_type info_;
88 std::array<std::byte,256> read_buffer_;
89 std::vector<std::byte> receive_buffer_;
90 bool started_ {false};
91 callback<data_ptr> raw_callbacks_;
92
93 // 兼容当前 Linux/RM 端的小端线序:数值 0xAA55 在线上为 55 AA。
94 static constexpr std::array<std::byte, 2> header_bytes{
95 std::byte{0x55}, std::byte{0xAA}};
96};
97
98static_assert(keyed_io<serial>);
99}
异步任务上下文组件。
管理一组协程回调的容器。
Definition callback.hpp:36
void add(F &&f)
添加一个新的回调。
Definition callback.hpp:55
带 key 的 IO 基类,根据键值派发数据。
Definition base.hpp:157
串口设备对象。
Definition serial.h:31
awaitable< void > send(key_type key, byte_span data)
发送字节数据。
Definition serial.cpp:39
void start()
启动串口接收协程;重复调用不会重复启动。
Definition serial.cpp:31
std::string desc() const
返回包含逻辑名称、设备路径和波特率的可读描述。
Definition serial.h:78
awaitable< void > task()
接收循环任务。
Definition serial.cpp:93
void on_raw_data(callback_fn< byte_span > auto fn)
Definition serial.h:66
将同一异步流上的写操作串行化。
用于提供日志功能的辅助基类 通过CRTP模式实现,要求派生类实现desc()方法以提供描述信息,在继承时传入派生类自身类型作为模板参数。 继承这个类后,派生类可以方便地使用log_debug、log_i...
Definition logger.h:178
约束回调类型可被调用且返回 void 或 awaitable<void>。
Definition callback.hpp:27
公共Concept与元类型工具。
IO的基础组件。
std::shared_ptr< const std::vector< std::byte > > data_ptr
只读共享数据缓冲。
Definition base.hpp:40
std::span< const std::byte > byte_span
只读 byte span。
Definition base.hpp:45
用于日志输出的组件。
asio::awaitable< T > awaitable
协程任务类型。
Definition async.hpp:46
串口初始化参数。
Definition serial.h:36
常用数值与字节工具集合。