首页 > 解决方案 > 在 Rust 上使用 paho-mqtt

问题描述

我看到Crates.io有一个已经实现的板条箱MQTT。但是当尝试使用repo中提供的示例时,我遇到了很多错误,作为学习过程的一部分,我正在考虑修复它。

添加后

[dependencies]
paho-mqtt = "0.7.1"

我尝试使用这个 main.rs 构建:

use std::process;

extern crate paho_mqtt as mqtt;

fn main() {
    // Create a client & define connect options
    let cli = mqtt::Client::new("tcp://localhost:1883").unwrap_or_else(|err| {
        println!("Error creating the client: {:?}", err);
        process::exit(1);
    });

    let conn_opts = mqtt::ConnectOptionsBuilder::new()
        .keep_alive_interval(Duration::from_secs(20))
        .clean_session(true)
        .finalize();

    // Connect and wait for it to complete or fail
    if let Err(e) = cli.connect(conn_opts).wait() {
        println!("Unable to connect:\n\t{:?}", e);
        process::exit(1);
    }

    // Create a message and publish it
    let msg = mqtt::Message::new("test", "Hello world!");
    let tok = cli.publish(msg);

    if let Err(e) = tok.wait() {
        println!("Error sending message: {:?}", e);
    }

    // Disconnect from the broker
    let tok = cli.disconnect();
    tok.wait().unwrap();
}

我收到以下错误:

error[E0433]: failed to resolve: use of undeclared type or module `Duration`
  --> src/main.rs:13:30
   |
13 |         .keep_alive_interval(Duration::from_secs(20))
   |                              ^^^^^^^^ use of undeclared type or module `Duration`

error[E0599]: no method named `wait` found for enum `std::result::Result<mqtt::ServerResponse, mqtt::MqttError>` in the current scope
  --> src/main.rs:18:44
   |
18 |     if let Err(e) = cli.connect(conn_opts).wait() {
   |                                            ^^^^ method not found in `std::result::Result<mqtt::ServerResponse, mqtt::MqttError>`

error[E0061]: this function takes 3 arguments but 2 arguments were supplied
  --> src/main.rs:24:15
   |
24 |     let msg = mqtt::Message::new("test", "Hello world!");
   |               ^^^^^^^^^^^^^^^^^^ ------  -------------- supplied 2 arguments
   |               |
   |               expected 3 arguments

error[E0599]: no method named `wait` found for enum `std::result::Result<(), mqtt::MqttError>` in the current scope
  --> src/main.rs:27:25
   |
27 |     if let Err(e) = tok.wait() {
   |                         ^^^^ method not found in `std::result::Result<(), mqtt::MqttError>`

error[E0061]: this function takes 1 argument but 0 arguments were supplied
  --> src/main.rs:32:19
   |
32 |     let tok = cli.disconnect();
   |                   ^^^^^^^^^^- supplied 0 arguments
   |                   |
   |                   expected 1 argument

error[E0599]: no method named `wait` found for enum `std::result::Result<(), mqtt::MqttError>` in the current scope
  --> src/main.rs:33:9
   |
33 |     tok.wait().unwrap();
   |         ^^^^ method not found in `std::result::Result<(), mqtt::MqttError>`

error: aborting due to 6 previous errors

13我可以通过使用解决的错误std::time::Duration

24我可以通过添加来解决行中的错误QoS

我还缺少哪些其他错误?

标签: rustmqtt

解决方案


推荐阅读