Crate mqtt_service

Crate mqtt_service 

Source
Expand description

stable pipeline dev/1 pipeline docs crates.io

§mqtt-service

This crate provides a convenient support for the MQTT Response-Pattern. It uses the rumqttc library to connect to the MQTT broker.

Note: this crate is feature complete, and few changes are expected.

§How to use

Add mqtt-service, mqtt-client and tokio to your project:

cargo add mqtt-service

mqtt-service needs a tokio runtime and a mqtt_channel::Client:

let rt = tokio::runtime::Runtime::new().unwrap();
let (connection, task) = mqtt_channel::Client::build(
  "name-of-the-client-raw",
  env::var("MQTT_SERVICE_MQTT_SERVER_HOSTNAME").unwrap_or("localhost".to_string()),
  1883,
)
.start();
rt.spawn(task);

Then a mqtt-service client can be created:

let client = Client::new(connection);

Then you can create a JSON service with:

rt.spawn(
  connection
    .clone()
    .create_json_service(
      "mqtt-service/test_json/addition",
      Box::new(|request: &Request| Response {
        r: request.a + request.b,
      }),
      10,
    )
    .map(|r| r.unwrap()),
);

Alternatively, you can use create_raw_service for higher control on the serialization of message. Then the service can be called using call_json_service (or call_raw_service):

let fut = connection
  .call_json_service::<Request, Response>(
    "mqtt-service/test_json/addition",
    &Request { a: 1.0, b: 2.0 },
  )
  .unwrap();

let res = rt.block_on(fut).unwrap();

Structs§

Client
Handle to the connection

Enums§

Error