3 个版本
0.1.2 | 2023 年 3 月 29 日 |
---|---|
0.1.1 | 2023 年 3 月 29 日 |
0.1.0 | 2023 年 3 月 28 日 |
#169 在 WebSocket
每月 36 次下载
45KB
865 行
moonsock
Moonsock 是一种简单的方法,可以从任何 tokio 可以运行且您可以通过互联网访问您 3D 打印机的地方(通常在您的本地网络内)使用 Rust 连接到 klipper/moonraker 3D 打印机的 WebSocket。
用法
在打开 MoonConnection 时,请确保为您的用例设置足够的读/写缓冲区。在下面的示例中,两者都设置为 1000。
连接到打印机
在 tokio 运行时内部创建一个新的 MoonConnection 以打开 WebSocket。
// I prefer starting my own tokio runtimes for this sort of use-case.
use tokio::runtime::Builder;
use moonsock::{MoonConnection, MoonMSG, MoonMethod};
println!("Starting Main Runtime");
let moon_rt = Builder::new_multi_thread()
.worker_threads(1)
.thread_name("Moonraker Websocket Main")
.enable_all()
.build()
.unwrap();
// Note: the port might be different for you, but 7125 is moonraker's default port. Check your moonraker.conf if you have problems
let url = "ws://[printer ip or hostname]:7125/websocket";
let mut connection = moon_rt.block_on(MoonConnection::new(URL.to_string(), 1000, 1000));
基本发送消息
以下示例需要在 tokio 运行时中运行。
let id = 4242;
connection.send(MoonMSG::gcode(
String::from("G90"),
id,
)).await.unwrap();
// Using our moon_rt from above it could be called like this:
moon_rt.block_on(connection.send(MoonMSG::gcode(
String::from("G90"),
id,
)).await.unwrap());
发送消息并等待其响应
send_listen
方法将发送一条消息并返回该特定消息的响应。为了明确,它不返回下一个接收到的响应,它返回第一个具有与发送消息 ID 匹配的 ID 的响应。由于 send_listen
方法是异步的,因此它不会在等待时阻塞线程。应在发送的消息上设置 ID,否则未来可能永远不会返回。
let temp_id = 42342;
let message = MoonMSG::new(MoonMethod::ServerTemperatureStore, None, Some(temp_id));
match connection.send_listen(message.clone()).await {
Ok(message) => {
...
},
Err(err) => println!("ERROR: {}", err),
}
接收消息
match connection.recv().await {
Some(msg) => println!("Received: {:?}", msg),
None => println!("Failed to receive message from connection"),
}
crate 的完整性
当前解析器不支持所有消息类型,但大多数重要的类型都得到了支持。如果您需要更多消息的支持,请随时提出问题或分叉此项目并添加支持。
依赖关系
~5–17MB
~251K SLoC