Connect a device to IoT Platform and enable messaging by using the Paho MQTT library for Rust.
Usage notes
All operations in this topic use common user permissions. If an operation requires administrator permissions, run the sudo command.
Prerequisites
A product and a device are created in an instance in the IoT Platform console. A device certificate and an MQTT endpoint are obtained. The certificate information includes the ProductKey, DeviceName, and DeviceSecret. For more information, see the following topics:
Prepare a development environment
-
Ubuntu 18.04
-
Cargo 1.61.0 or later
-
On Linux, run the following command to install Cargo and manage dependencies.
sudo apt-get install cargo cmake
Connect a device to IoT Platform
-
Download the sample code package and decompress it to the
aiot-rust-demodirectory. The directory contains the following files.File
Description
src/mqtt-basic-demo/main.rsThe logic code for connecting a device to IoT Platform and enabling communications.
Cargo.tomlThe project manifest file.
-
In the
src/mqtt-basic-demo/main.rsfile, replace the values of theproduct_key,device_name, anddevice_secretparameters with your device certificate information.let product_key = "gb80*****"; let device_name = "mqtt_******o"; let timestamp = "2524****000"; let device_secret = b"f***********************b"; let host = "tcp://iot-060axxxx.mqtt.iothub.aliyuncs.com:1883" -
Run the
cargo buildcommand to compile the project. The following sample output is returned.Compiling hex-literal v0.3.4 Compiling hmac-sha256 v0.1.7 Compiling openssl-src v111.24.0+1.1.1s Compiling cmake v0.1.49 Compiling slab v0.4.7 Compiling openssl-sys v0.9.80 Compiling paho-mqtt-sys v0.8.0 (https://github.com/eclipse/paho.mqtt.rust.git?branch=master#8e1f7342) Compiling concurrent-queue v2.1.0 Compiling crossbeam-channel v0.5.6 Compiling async-channel v1.8.0 Compiling futures-macro v0.3.25 Compiling thiserror-impl v1.0.38 Compiling futures-executor v0.3.25 Compiling futures v0.3.25 Compiling paho-mqtt v0.12.0 (https://github.com/eclipse/paho.mqtt.rust.git?branch=master#8e1f7342) Compiling mqtt-example v0.1.0 Finished dev [unoptimized + debuginfo] target(s) in 20.83s -
Run the
./target/debug/mqtt_basic_democommand to run the project. The following sample output is returned.starting Alibaba iot demo... subscribed to topic:=/gb80sxxxx/mqtt_basic_demo/user/get published to topic:=/gb80sxxxx/mqtt_basic_demo/user/update start receiving...