WaveshareCloud Wiki Help

Device-to-Device Communication

How can device-to-device communication be achieved through Waveshare Cloud?

Communication Principle

Publish/Subscribe Pattern

The Publish-Subscribe pattern is a messaging pattern that decouples the sender (publisher) from the receiver ( subscriber), allowing them to communicate without direct connections or knowledge of each other's existence.

In MQTT's Publish/Subscribe pattern, a central role called the broker is responsible for routing and distributing all messages. Publishers send messages with topics to the broker, and subscribers subscribe to topics to receive messages of interest.

In MQTT, topics and subscriptions cannot be registered or created in advance, so the broker cannot predict whether there will be subscribers for a particular topic or how many subscribers there will be. Therefore, messages are only forwarded to current subscribers, and if there are no subscribers, the message is discarded.

MQTT Publish/Subscribe pattern consists of 4 main components: Publisher, Subscriber, Broker, and Topic.

  • Publisher

    Responsible for publishing messages to a topic. Publishers can only send data to one topic at a time, and they don't need to care about whether subscribers are online when publishing messages.

  • Subscriber

    Subscribers receive messages by subscribing to topics. Subscribers can subscribe to multiple topics at once. MQTT also supports load balancing subscriptions among multiple subscribers using shared subscriptions.

  • Broker

    Responsible for receiving messages from publishers and forwarding them to subscribers based on the conditions. The broker also needs to handle client-initiated requests such as connection, disconnection, subscription, and unsubscribing.

  • Topic

    Topics are the foundation for message routing in MQTT. They resemble URL paths and use slashes (/) for hierarchy, e.g., sensor/1/temperature. A topic can have multiple subscribers, and the broker forwards messages to all subscribers under that topic. A topic can also have multiple publishers, and the broker forwards messages in the order they arrive.

MQTT

Message Routing in MQTT Publish/Subscribe

In the MQTT Publish/Subscribe pattern, a client can be both a publisher and a subscriber, and it can have both roles simultaneously. When a client publishes a message, it is sent to the broker, and the broker routes the message to all subscribers interested in that topic. When a client subscribes to a topic, it receives all messages forwarded by the broker under that topic. The broker routes messages based on the topics they belong to.

Waveshare Cloud's message filtering works through topics: subscribers subscribe to topics they are interested in, and publishers include their own topics in all messages. The broker determines which subscribers to forward messages to based on the message's topic.

Message Routing

ESP32 Code Implementation

Get Address Parameters

Address Parameters

Code Reference: ESP32 Connects to Waveshare Cloud SDK (Recommended to copy the entire code below)

Here, the control parameters for the message callback are defined as

{ "data": { "builtIn": 0 // 0 or 1 } }

Complete code

#include <ArduinoJson.h> #include <Arduino.h> #include <PubSubClient.h> #include <WiFi.h> #include <WiFiClientSecure.h> #define MSG_BUFFER_SIZE (50) #define STASSID "" #define STAPSK "" const char* mqtt_server = "mqtt.waveshare.cloud"; int PORT = 1883; const char* ID = "19ba7e8b"; char sub[] = "Sub/1/37/19ba7e8b"; char pub[] = "Pub/1/37/19ba7e8b"; StaticJsonDocument<400> sendJson; StaticJsonDocument<400> readJson; unsigned long lastUpdateTime = 0; const char* ssid = STASSID; const char* password = STAPSK; char msg[MSG_BUFFER_SIZE]; WiFiClient espClient; PubSubClient client(espClient); const unsigned long updateInterval = 5000; void setup() { Serial.begin(9600); setup_wifi(); client.setServer(mqtt_server, PORT); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); } void callback(char* topic, byte* payload, unsigned int length) { String inputString; for (int i = 0; i < length; i++) { inputString += (char)payload[i]; } Serial.println(inputString); int dataBegin = inputString.indexOf("\"data\""); if (dataBegin == -1) { Serial.println(F("Missing 'data' field in JSON.")); return; } int builtInBegin = inputString.indexOf("\"builtIn\"", dataBegin); if (builtInBegin == -1) { Serial.println(F("Missing 'builtIn' field in 'data' object.")); return; } int valueBegin = inputString.indexOf(':', builtInBegin); int valueEnd = inputString.indexOf('}', valueBegin); if (valueBegin == -1 || valueEnd == -1) { Serial.println(F("Invalid 'builtIn' value.")); return; } String builtInValueStr = inputString.substring(valueBegin + 1, valueEnd); int builtInValue = builtInValueStr.toInt(); if (builtInValue == 0) { Serial.println("close!"); sendJsonData(0); } else { Serial.println("open!"); sendJsonData(1); } } void setup_wifi() { Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void reconnect() { while (!client.connected()) { if (client.connect(ID)) { client.subscribe(sub); } else { Serial.print(client.state()); delay(5000); } } } void sendJsonData(int value) { sendJson["builtIn"] = value; String pubres; serializeJson(sendJson, pubres); int str_len = pubres.length() + 1; char char_array[str_len]; pubres.toCharArray(char_array, str_len); client.publish(pub, char_array); }

SIM7028 NB-IoT HAT Command Implementation

Get SIM7028 Client ID

6d583946

Command Set

Command

Response

Continue Input?

Input Value

Explanation

AT+CMQTTSTART

+CMQTTSTART: 0

No

——

Enable MQTT functionality

AT+CMQTTACCQ=0,"82b52f8b",0

OK

No

——

Set Client ID82b52f8b represents the Client ID obtained from the platform, the last 0 represents the use of the MQTT protocol (non-SSL)

AT+CMQTTCONNECT=0, tcp://mqtt.waveshare.cloud: 1883,20,1

+CMQTTCONNECT: 0,0

No

——

Connect to the MQTT server, the return value 0,0 represents a successful connection

AT+CMQTTSUB=0,17,1

>

Icon available

Pub/1/37/19ba7e8b

ESP32 Pub Topic

AT+CMQTTTOPIC=0,17

>

Icon available

Sub/1/37/19ba7e8b

ESP32 Sub Topic

AT+CMQTTPAYLOAD=0,22

>

Icon available

{"data":{"builtIn":1}}

Enter the message body

AT+CMQTTPUB=0,1,60

+CMQTTPUB: 0,0

No

——

Send message

Command Example

Fbe9095c
Last modified: 12 一月 2024