-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy patharduinojson.ino
69 lines (54 loc) · 1.71 KB
/
arduinojson.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// dependencies: bblanchon/ArduinoJson
#include <PicoMQTT.h>
#if __has_include("config.h")
#include "config.h"
#endif
#ifndef WIFI_SSID
#define WIFI_SSID "WiFi SSID"
#endif
#ifndef WIFI_PASSWORD
#define WIFI_PASSWORD "password"
#endif
#include <ArduinoJson.h>
PicoMQTT::Client mqtt("broker.hivemq.com");
unsigned long last_publish_time = 0;
int greeting_number = 1;
void setup() {
// Setup serial
Serial.begin(115200);
// Connect to WiFi
Serial.printf("Connecting to WiFi %s\n", WIFI_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) { delay(1000); }
Serial.println("WiFi connected.");
// Subscribe to a topic and attach a callback
mqtt.subscribe("picomqtt/json/#", [](const char * topic, Stream & stream) {
Serial.printf("Received message in topic '%s':\n", topic);
JsonDocument json;
if (deserializeJson(json, stream)) {
Serial.println("Json parsing failed.");
return;
}
serializeJsonPretty(json, Serial);
Serial.println();
});
mqtt.begin();
}
void loop() {
mqtt.loop();
// Publish a greeting message every 3 seconds.
if (millis() - last_publish_time >= 3000) {
String topic = "picomqtt/json/esp-" + WiFi.macAddress();
Serial.printf("Publishing in topic '%s'...\n", topic.c_str());
// build JSON document
JsonDocument json;
json["foo"] = "bar";
json["millis"] = millis();
// publish using begin_publish()/send() API
auto publish = mqtt.begin_publish(topic, measureJson(json));
serializeJson(json, publish);
publish.send();
last_publish_time = millis();
}
}