7个版本 (破坏性)
0.6.0 | 2024年6月2日 |
---|---|
0.5.0 | 2024年2月20日 |
0.4.0 | 2023年12月7日 |
0.3.0 | 2023年10月10日 |
0.1.0 | 2022年1月1日 |
#402 in 游戏开发
每月21次下载
25KB
294 行
bevy_serial
bevy_serial
是一个插件,为 bevy 添加非阻塞串行通信。该插件基于 mio-serial
,可以实现非阻塞高性能 I/O。
通过 bevy 的事件系统实现从/向串行端口读写。每个串行端口通过端口号或您选择的唯一标签进行处理。这些事件处理器被添加到以下阶段以最小化帧延迟。
- 读取:
PreUpdate
- 写入:
PostUpdate
用法
简单示例
这里有一个简单的示例
use bevy::prelude::*;
use bevy_serial::{SerialPlugin, SerialReadEvent, SerialWriteEvent};
// to write data to serial port periodically
#[derive(Resource)]
struct SerialWriteTimer(Timer);
const SERIAL_PORT: &str = "/dev/ttyUSB0";
fn main() {
App::new()
.add_plugins(MinimalPlugins)
// simply specify port name and baud rate for `SerialPlugin`
.add_plugins(SerialPlugin::new(SERIAL_PORT, 115200))
// to write data to serial port periodically (every 1 second)
.insert_resource(SerialWriteTimer(Timer::from_seconds(
1.0,
TimerMode::Repeating,
)))
// reading and writing from/to serial port is achieved via bevy's event system
.add_systems(Update, read_serial)
.add_systems(Update, write_serial)
.run();
}
// reading event for serial port
fn read_serial(mut ev_serial: EventReader<SerialReadEvent>) {
// you can get label of the port and received data buffer from `SerialReadEvent`
for SerialReadEvent(label, buffer) in ev_serial.read() {
let s = String::from_utf8(buffer.clone()).unwrap();
println!("received packet from {label}: {s}");
}
}
// writing event for serial port
fn write_serial(
mut ev_serial: EventWriter<SerialWriteEvent>,
mut timer: ResMut<SerialWriteTimer>,
time: Res<Time>,
) {
// write msg to serial port every 1 second not to flood serial port
if timer.0.tick(time.delta()).just_finished() {
// you can write to serial port via `SerialWriteEvent` with label and buffer to write
let buffer = b"Hello, bevy!";
ev_serial.send(SerialWriteEvent(SERIAL_PORT.to_string(), buffer.to_vec()));
}
}
具有额外配置的多个串行端口
您可以添加具有额外配置的多个串行端口。
fn main() {
App::new()
.add_plugins(MinimalPlugins)
// you can specify various configurations for multiple serial ports by this way
.add_plugins(SerialPlugin::new_with_config(vec![SerialConfig {
label: Some(SERIAL_LABEL.to_string()),
port_name: SERIAL_PORT.to_string(),
baud_rate: 115200,
data_bits: DataBits::Eight,
flow_control: FlowControl::None,
parity: Parity::None,
stop_bits: StopBits::One,
timeout: Duration::from_millis(0),
read_buffer_len: 2048,
read_result_handler: Some(Arc::new(|label, result| {
println!("Read result of {label}: {result:?}");
})),
write_result_handler: Some(Arc::new(|label, result| {
println!("Write result of {label}: {result:?}");
})),
}]))
// reading and writing from/to serial port is achieved via bevy's event system
.add_systems(Update, read_serial)
.add_systems(Update, write_serial)
.run();
}
支持的版本
bevy | bevy_serial |
---|---|
0.13 | 0.5, 0.6 |
0.12 | 0.4 |
0.11 | 0.3 |
0.6 | 0.2 |
0.5 | 0.1 |
许可证
双许可
- MIT
- Apache 2.0
依赖项
~20–51MB
~806K SLoC