Skip to content

Commit 98cae0b

Browse files
committed
MCU8MASS-2573 Modify azure example to use callback for messages to handle wildcard subscription
1 parent 904744c commit 98cae0b

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

examples/mqtt_azure/mqtt_azure.ino

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
* @brief This example demonstrates how to connect to the Azure IoT Hub using
33
* the ATECC608 cryptographic chip on the AVR-Iot Cellular mini. Please make
44
* sure your board is provisioned first with the provision sketch.
5+
*
6+
* With Azure, we use a wildcare for subscription, so we need to enable a
7+
* callback for the received messages so that we can grab the specific topic.
58
*/
69

710
#include <Arduino.h>
@@ -18,6 +21,19 @@ const char MQTT_SUB_TOPIC_FMT[] PROGMEM = "devices/%s/messages/devicebound/#";
1821
static char mqtt_sub_topic[128];
1922
static char mqtt_pub_topic[128];
2023

24+
static volatile bool got_message_event = false;
25+
static char message_topic[384];
26+
static volatile uint16_t message_length = 0;
27+
28+
static void onReceive(const char* topic,
29+
const uint16_t length,
30+
__attribute__((unused)) const int32_t id) {
31+
strcpy(message_topic, topic);
32+
message_length = length;
33+
34+
got_message_event = true;
35+
}
36+
2137
bool initTopics() {
2238
ATCA_STATUS status = ECC608.begin();
2339

@@ -67,6 +83,7 @@ void setup() {
6783
// Attempt to connect to Azure
6884
if (MqttClient.beginAzure()) {
6985
MqttClient.subscribe(mqtt_sub_topic);
86+
MqttClient.onReceive(onReceive);
7087
} else {
7188
while (1) {}
7289
}
@@ -83,15 +100,19 @@ void setup() {
83100
Log.error(F("Failed to publish\r\n"));
84101
}
85102

86-
delay(2000);
103+
if (got_message_event) {
104+
105+
String message = MqttClient.readMessage(message_topic,
106+
message_length);
87107

88-
String message = MqttClient.readMessage(mqtt_sub_topic);
108+
// Read message will return an empty string if there were no new
109+
// messages, so anything other than that means that there were a
110+
// new message
111+
if (message != "") {
112+
Log.infof(F("Got new message: %s\r\n"), message.c_str());
113+
}
89114

90-
// Read message will return an empty string if there were no new
91-
// messages, so anything other than that means that there were a
92-
// new message
93-
if (message != "") {
94-
Log.infof(F("Got new message: %s\r\n"), message.c_str());
115+
got_message_event = false;
95116
}
96117

97118
delay(2000);

src/mqtt_client.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
#include <stdbool.h>
1010
#include <stdint.h>
1111

12-
#define MQTT_TOPIC_MAX_LENGTH 128
12+
#define MQTT_TOPIC_MAX_LENGTH (384)
1313

1414
typedef enum { AT_MOST_ONCE = 0, AT_LEAST_ONCE, EXACTLY_ONCE } MqttQoS;
1515

0 commit comments

Comments
 (0)