mirror of
https://gitlab.fdmci.hva.nl/technische-informatica-sm3/ti-projectten/rooziinuubii79.git
synced 2025-08-04 04:14:58 +00:00
50 lines
1.3 KiB
Markdown
50 lines
1.3 KiB
Markdown
# MQTT
|
|
|
|
## What is MQTT?
|
|
MQTT is a lightweight messaging protocol made for IOT devices. It allows efficient communication between IoT devices, servers, and applications by allowing them to
|
|
publish and subscribe to messages.
|
|
|
|
|
|
## How to connect
|
|
To connect to a MQTT server you need to create a instance of the class.
|
|
|
|
Example:
|
|
```cpp
|
|
// server adress, Client ID, Client Username, Client Password
|
|
MqttClient client("ws://145.92.224.21/ws/", "KobukiRPI", "rpi", "rpiwachtwoordofzo"); // create a client object
|
|
```
|
|
Later in the setup function you need to call ```client.connect();``` to connect to the mqtt server.
|
|
```cpp
|
|
client.connect();
|
|
```
|
|
|
|
When you've connected and the instance is initiated you can subscribe to topics or send messages to topics.
|
|
|
|
|
|
## Subscribing and receiving messages
|
|
Example subscribing to a topic:
|
|
```cpp
|
|
void setup(){
|
|
client.subscribe("home/commands");
|
|
}
|
|
```
|
|
|
|
Example receiving latest message from a topic:
|
|
```cpp
|
|
std::string foo(){
|
|
std::string latestMqttMessage = "";
|
|
latestMqttMessage = client.getLastMessage();
|
|
return latestMqttMessage;
|
|
}
|
|
```
|
|
|
|
If you want to subscribe to mulitple topics you need to initiate multiple instances of the mqtt class.
|
|
|
|
## Publishing messages
|
|
Example publishing a message:
|
|
```cpp
|
|
void foo(std::string Message){
|
|
//channel, payload
|
|
client.publishMessage("kobuki/example", Message);
|
|
}
|
|
``` |