Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "M5StickCPlus.h"
- #include <WiFi.h>
- #include "AsyncMqttClient.h"
- #define SSID "mywifi"
- #define WIFI_PASS "mypass"
- #define HOST "192.168.0.166"
- #define CLIENT_ID "test"
- #define PORT 1883
- #define USER "mosquitto"
- #define MQTT_PASS "mosquitto"
- bool mqtt_connect_retry = true;
- unsigned int counter = 0;
- AsyncMqttClient mqtt_client;
- void mqtt_disconnect_callback(AsyncMqttClientDisconnectReason reason) {
- Serial.printf("%s: disconnected, reason = %hu\r\n", __func__, (uint8_t) reason);
- mqtt_connect_retry = true;
- }
- void setup() {
- M5.begin(false, true, true);
- Serial.begin(115200);
- WiFi.begin(SSID, WIFI_PASS);
- delay(10000);
- IPAddress host_ip;
- host_ip.fromString(HOST);
- mqtt_client.setServer(host_ip, PORT);
- mqtt_client.setClientId(CLIENT_ID);
- mqtt_client.setCredentials(USER, MQTT_PASS);
- mqtt_client.setCleanSession(false);
- mqtt_client.onDisconnect(mqtt_disconnect_callback);
- mqtt_client.setKeepAlive(900);
- }
- void loop() {
- int status = WiFi.status();
- if (status == WL_CONNECTED) {
- Serial.printf("%s: wifi connected\r\n", __func__);
- if (mqtt_client.connected()) {
- Serial.printf("%s: mqtt connected\r\n", __func__);
- mqtt_client.publish("test/testA", 0, true, "test 1");
- mqtt_client.publish("test/testB", 0, true, "test 2");
- mqtt_client.publish("test/testC", 0, true, "test 3");
- } else if (mqtt_connect_retry) {
- Serial.printf("%s: mqtt disconnected, reconnecting\r\n", __func__);
- mqtt_client.connect();
- mqtt_connect_retry = false;
- } else {
- Serial.printf("%s: reconnecting mqtt\r\n", __func__);
- }
- } else if (status == WL_DISCONNECTED || status == WL_CONNECT_FAILED || status == WL_CONNECTION_LOST ) {
- Serial.printf("%s: wifi disconnected, reconnecting\r\n", __func__);
- WiFi.reconnect();
- } else {
- Serial.printf("%s: stalling\r\n", __func__);
- }
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement