Bob Mottram 7 months ago
parent
commit
d911691305
1 changed files with 117 additions and 117 deletions
  1. 117
    117
      IoT/esp8266_mqtt.ino

+ 117
- 117
IoT/esp8266_mqtt.ino View File

@@ -26,12 +26,12 @@
26 26
 #define LOG_PRINTFLN(fmt, ...)	logfln(fmt, ##__VA_ARGS__)
27 27
 #define LOG_SIZE_MAX 128
28 28
 void logfln(const char *fmt, ...) {
29
-	char buf[LOG_SIZE_MAX];
30
-	va_list ap;
31
-	va_start(ap, fmt);
32
-	vsnprintf(buf, LOG_SIZE_MAX, fmt, ap);
33
-	va_end(ap);
34
-	Serial.println(buf);
29
+    char buf[LOG_SIZE_MAX];
30
+    va_list ap;
31
+    va_start(ap, fmt);
32
+    vsnprintf(buf, LOG_SIZE_MAX, fmt, ap);
33
+    va_end(ap);
34
+    Serial.println(buf);
35 35
 }
36 36
 
37 37
 #define LED_BACKUP_OK               13
@@ -47,128 +47,128 @@ static WiFiClient network;
47 47
 class System: public MqttClient::System {
48 48
 public:
49 49
 
50
-	unsigned long millis() const {
51
-		return ::millis();
52
-	}
50
+    unsigned long millis() const {
51
+        return ::millis();
52
+    }
53 53
 
54
-	void yield(void) {
55
-		::yield();
56
-	}
54
+    void yield(void) {
55
+        ::yield();
56
+    }
57 57
 };
58 58
 
59 59
 // ============== Setup all objects ============================================
60 60
 void setup() {
61
-	// Setup hardware serial for logging
62
-	Serial.begin(HW_UART_SPEED);
63
-
64
-  // setup backup status leds
65
-  pinMode(LED_BACKUP_OK,OUTPUT);
66
-  pinMode(LED_BACKUP_FAIL,OUTPUT);
67
-  digitalWrite(LED_BACKUP_OK,LOW);
68
-  digitalWrite(LED_BACKUP_FAIL,LOW);
69
-
70
-  digitalWrite(LED_BUILTIN,LOW);
71
-
72
-	// Setup WiFi network
73
-	WiFi.mode(WIFI_STA);
74
-	WiFi.hostname("ESP_" MQTT_ID);
75
-	WiFi.begin("YourSSID", "YourPassword");
76
-	LOG_PRINTFLN("\n");
77
-	LOG_PRINTFLN("Connecting to WiFi");
78
-	while (WiFi.status() != WL_CONNECTED) {
79
-		delay(500);
80
-		LOG_PRINTFLN(".");
81
-	}
82
-	LOG_PRINTFLN("Connected to WiFi");
83
-	LOG_PRINTFLN("IP: %s", WiFi.localIP().toString().c_str());
84
-
85
-	// Setup MqttClient
86
-	MqttClient::System *mqttSystem = new System;
87
-	MqttClient::Logger *mqttLogger = new MqttClient::LoggerImpl<HardwareSerial>(Serial);
88
-	MqttClient::Network * mqttNetwork = new MqttClient::NetworkClientImpl<WiFiClient>(network, *mqttSystem);
89
-	//// Make 128 bytes send buffer
90
-	MqttClient::Buffer *mqttSendBuffer = new MqttClient::ArrayBuffer<128>();
91
-	//// Make 128 bytes receive buffer
92
-	MqttClient::Buffer *mqttRecvBuffer = new MqttClient::ArrayBuffer<128>();
93
-	//// Allow up to 2 subscriptions simultaneously
94
-	MqttClient::MessageHandlers *mqttMessageHandlers = new MqttClient::MessageHandlersImpl<2>();
95
-	//// Configure client options
96
-	MqttClient::Options mqttOptions;
97
-	////// Set command timeout to 10 seconds
98
-	mqttOptions.commandTimeoutMs = 10000;
99
-	//// Make client object
100
-	mqtt = new MqttClient(
101
-		mqttOptions, *mqttLogger, *mqttSystem, *mqttNetwork, *mqttSendBuffer,
102
-		*mqttRecvBuffer, *mqttMessageHandlers
103
-	);
61
+    // Setup hardware serial for logging
62
+    Serial.begin(HW_UART_SPEED);
63
+
64
+    // setup backup status leds
65
+    pinMode(LED_BACKUP_OK,OUTPUT);
66
+    pinMode(LED_BACKUP_FAIL,OUTPUT);
67
+    digitalWrite(LED_BACKUP_OK,LOW);
68
+    digitalWrite(LED_BACKUP_FAIL,LOW);
69
+
70
+    digitalWrite(LED_BUILTIN,LOW);
71
+
72
+    // Setup WiFi network
73
+    WiFi.mode(WIFI_STA);
74
+    WiFi.hostname("ESP_" MQTT_ID);
75
+    WiFi.begin("YourSSID", "YourPassword");
76
+    LOG_PRINTFLN("\n");
77
+    LOG_PRINTFLN("Connecting to WiFi");
78
+    while (WiFi.status() != WL_CONNECTED) {
79
+        delay(500);
80
+        LOG_PRINTFLN(".");
81
+    }
82
+    LOG_PRINTFLN("Connected to WiFi");
83
+    LOG_PRINTFLN("IP: %s", WiFi.localIP().toString().c_str());
84
+
85
+    // Setup MqttClient
86
+    MqttClient::System *mqttSystem = new System;
87
+    MqttClient::Logger *mqttLogger = new MqttClient::LoggerImpl<HardwareSerial>(Serial);
88
+    MqttClient::Network * mqttNetwork = new MqttClient::NetworkClientImpl<WiFiClient>(network, *mqttSystem);
89
+    //// Make 128 bytes send buffer
90
+    MqttClient::Buffer *mqttSendBuffer = new MqttClient::ArrayBuffer<128>();
91
+    //// Make 128 bytes receive buffer
92
+    MqttClient::Buffer *mqttRecvBuffer = new MqttClient::ArrayBuffer<128>();
93
+    //// Allow up to 2 subscriptions simultaneously
94
+    MqttClient::MessageHandlers *mqttMessageHandlers = new MqttClient::MessageHandlersImpl<2>();
95
+    //// Configure client options
96
+    MqttClient::Options mqttOptions;
97
+    ////// Set command timeout to 10 seconds
98
+    mqttOptions.commandTimeoutMs = 10000;
99
+    //// Make client object
100
+    mqtt = new MqttClient(
101
+        mqttOptions, *mqttLogger, *mqttSystem, *mqttNetwork, *mqttSendBuffer,
102
+        *mqttRecvBuffer, *mqttMessageHandlers
103
+    );
104 104
 }
105 105
 
106 106
 // ============== Subscription callback ========================================
107 107
 void processMessage(MqttClient::MessageData& md) {
108
-  const MqttClient::Message& msg = md.message;
109
-  char payload[msg.payloadLen + 1];
110
-  memcpy(payload, msg.payload, msg.payloadLen);
111
-  payload[msg.payloadLen] = '\0';
112
-
113
-  if (strstr(payload,"Backup")) {
114
-      if (strstr(payload,"succeed")) {
115
-          digitalWrite(LED_BACKUP_OK,HIGH);
116
-          digitalWrite(LED_BACKUP_FAIL,LOW);
117
-      }
118
-      else {
119
-          digitalWrite(LED_BACKUP_OK,LOW);
120
-          digitalWrite(LED_BACKUP_FAIL,HIGH);
121
-      }
122
-  }
123
-  LOG_PRINTFLN(
124
-    "Message arrived: qos %d, retained %d, dup %d, packetid %d, payload:[%s]",
125
-    msg.qos, msg.retained, msg.dup, msg.id, payload
126
-  );
108
+    const MqttClient::Message& msg = md.message;
109
+    char payload[msg.payloadLen + 1];
110
+    memcpy(payload, msg.payload, msg.payloadLen);
111
+    payload[msg.payloadLen] = '\0';
112
+
113
+    if (strstr(payload,"Backup")) {
114
+        if (strstr(payload,"succeed")) {
115
+            digitalWrite(LED_BACKUP_OK,HIGH);
116
+            digitalWrite(LED_BACKUP_FAIL,LOW);
117
+        }
118
+        else {
119
+            digitalWrite(LED_BACKUP_OK,LOW);
120
+            digitalWrite(LED_BACKUP_FAIL,HIGH);
121
+        }
122
+    }
123
+    LOG_PRINTFLN(
124
+        "Message arrived: qos %d, retained %d, dup %d, packetid %d, payload:[%s]",
125
+        msg.qos, msg.retained, msg.dup, msg.id, payload
126
+    );
127 127
 }
128 128
 
129 129
 // ============== Main loop ====================================================
130 130
 void loop() {
131
-	// Check connection status
132
-	if (!mqtt->isConnected()) {
133
-		// Close connection if exists
134
-		network.stop();
135
-		// Re-establish TCP connection with MQTT broker
136
-		LOG_PRINTFLN("Connecting");
137
-		network.connect("192.168.1.95", 1883);
138
-		if (!network.connected()) {
139
-			LOG_PRINTFLN("Can't establish the TCP connection");
140
-			delay(5000);
141
-			ESP.reset();
142
-		}
143
-
144
-		// Start new MQTT connection
145
-		MqttClient::ConnectResult connectResult;
146
-		// Connect
147
-		{
148
-			MQTTPacket_connectData options = MQTTPacket_connectData_initializer;
149
-			options.MQTTVersion = 4;
150
-			options.clientID.cstring = (char*)MQTT_ID;
151
-			options.cleansession = true;
152
-			options.keepAliveInterval = 15; // 15 seconds
153
-			MqttClient::Error::type rc = mqtt->connect(options, connectResult);
154
-			if (rc != MqttClient::Error::SUCCESS) {
155
-				LOG_PRINTFLN("Connection error: %i", rc);
156
-				return;
157
-			}
158
-		}
159
-		{
160
-      MqttClient::Error::type rc = mqtt->subscribe(
161
-        MQTT_TOPIC_SUB, MqttClient::QOS0, processMessage
162
-      );
163
-      if (rc != MqttClient::Error::SUCCESS) {
164
-        LOG_PRINTFLN("Subscribe error: %i", rc);
165
-        LOG_PRINTFLN("Drop connection");
166
-        mqtt->disconnect();
167
-        return;
168
-      }
169
-		}
170
-	} else {
171
-		// Idle for 30 seconds
172
-		mqtt->yield(30000L);
173
-	}
131
+    // Check connection status
132
+    if (!mqtt->isConnected()) {
133
+        // Close connection if exists
134
+        network.stop();
135
+        // Re-establish TCP connection with MQTT broker
136
+        LOG_PRINTFLN("Connecting");
137
+        network.connect("192.168.1.95", 1883);
138
+        if (!network.connected()) {
139
+            LOG_PRINTFLN("Can't establish the TCP connection");
140
+            delay(5000);
141
+            ESP.reset();
142
+        }
143
+
144
+        // Start new MQTT connection
145
+        MqttClient::ConnectResult connectResult;
146
+        // Connect
147
+        {
148
+            MQTTPacket_connectData options = MQTTPacket_connectData_initializer;
149
+            options.MQTTVersion = 4;
150
+            options.clientID.cstring = (char*)MQTT_ID;
151
+            options.cleansession = true;
152
+            options.keepAliveInterval = 15; // 15 seconds
153
+            MqttClient::Error::type rc = mqtt->connect(options, connectResult);
154
+            if (rc != MqttClient::Error::SUCCESS) {
155
+                LOG_PRINTFLN("Connection error: %i", rc);
156
+                return;
157
+            }
158
+        }
159
+        {
160
+            MqttClient::Error::type rc = mqtt->subscribe(
161
+                                             MQTT_TOPIC_SUB, MqttClient::QOS0, processMessage
162
+                                         );
163
+            if (rc != MqttClient::Error::SUCCESS) {
164
+                LOG_PRINTFLN("Subscribe error: %i", rc);
165
+                LOG_PRINTFLN("Drop connection");
166
+                mqtt->disconnect();
167
+                return;
168
+            }
169
+        }
170
+    } else {
171
+        // Idle for 30 seconds
172
+        mqtt->yield(30000L);
173
+    }
174 174
 }

Loading…
Cancel
Save