Skip to content
This repository was archived by the owner on Jan 6, 2023. It is now read-only.

Commit 9f1fa08

Browse files
authored
Move agnostic MQTT functions to library (#95)
This is the first change in encapsulating the MQTT functionality independently from the hardware.
1 parent 565cd0c commit 9f1fa08

File tree

9 files changed

+366
-500
lines changed

9 files changed

+366
-500
lines changed

examples/Esp32-lwmqtt/Esp32-lwmqtt.ino

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,11 @@ void loop() {
3030
connect();
3131
}
3232

33+
// TODO: replace with your code
3334
// publish a message roughly every second.
34-
if (millis() - lastMillis > 1000) {
35+
if (millis() - lastMillis > 60000) {
3536
lastMillis = millis();
37+
//publishTelemetry(mqttClient, "/sensors", getDefaultSensor());
3638
publishTelemetry(getDefaultSensor());
3739
}
38-
}
40+
}

examples/Esp32-lwmqtt/esp32-mqtt.h

Lines changed: 26 additions & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,29 @@
1616
#ifndef __ESP32_MQTT_H__
1717
#define __ESP32_MQTT_H__
1818
#include <String.h>
19+
#include <Client.h>
1920
#include <WiFi.h>
2021
#include <WiFiClientSecure.h>
2122

22-
#include <rBase64.h>
2323
#include <MQTT.h>
2424

2525
#include <CloudIoTCore.h>
26+
#include <CloudIoTCoreMqtt.h>
2627
#include "ciotc_config.h" // Update this file with your configuration
2728

28-
// Initialize the Genuino WiFi SSL client library / RTC
29-
WiFiClientSecure *netClient;
30-
MQTTClient *mqttClient;
29+
// !!REPLACEME!!
30+
// The MQTT callback function for commands and configuration updates
31+
// Place your message handler code here.
32+
void messageReceived(String &topic, String &payload) {
33+
Serial.println("incoming: " + topic + " - " + payload);
34+
}
35+
///////////////////////////////
3136

32-
// Clout IoT configuration that you don't need to change
37+
// Initialize WiFi and MQTT for this board
38+
Client *netClient;
3339
CloudIoTCoreDevice *device;
40+
CloudIoTCoreMqtt *mqtt;
41+
MQTTClient *mqttClient;
3442
unsigned long iss = 0;
3543
String jwt;
3644

@@ -70,159 +78,24 @@ void setupWifi() {
7078
}
7179
}
7280

73-
74-
///////////////////////////////
75-
// MQTT common functions
76-
///////////////////////////////
77-
void messageReceived(String &topic, String &payload) {
78-
Serial.println("incoming: " + topic + " - " + payload);
79-
}
80-
81-
void startMQTT() {
82-
mqttClient->begin("mqtt.googleapis.com", 8883, *netClient);
83-
mqttClient->onMessage(messageReceived);
84-
}
85-
86-
void publishTelemetry(String data) {
87-
mqttClient->publish(device->getEventsTopic(), data);
88-
}
89-
90-
// Helper that just sends default sensor
91-
void publishState(String data) {
92-
mqttClient->publish(device->getStateTopic(), data);
93-
}
94-
95-
// FIXME: Move to config?
96-
int __backoff__ = 1000; // current backoff, milliseconds
97-
int __factor__ = 2.5f;
98-
int __minbackoff__ = 1000; // minimum backoff, ms
99-
int __max_backoff__ = 60000; // maximum backoff, ms
100-
int __jitter__ = 500; // max random jitter, ms
101-
void mqttConnect() {
102-
Serial.print("\nconnecting...");
103-
bool keepgoing = true;
104-
while (keepgoing) {
105-
mqttClient->connect(device->getClientId().c_str(), "unused", getJwt().c_str(), false);
106-
107-
if (mqttClient->lastError() != LWMQTT_SUCCESS){
108-
Serial.println(mqttClient->lastError());
109-
switch(mqttClient->lastError()) {
110-
case (LWMQTT_BUFFER_TOO_SHORT):
111-
Serial.println("LWMQTT_BUFFER_TOO_SHORT");
112-
break;
113-
case (LWMQTT_VARNUM_OVERFLOW):
114-
Serial.println("LWMQTT_VARNUM_OVERFLOW");
115-
break;
116-
case (LWMQTT_NETWORK_FAILED_CONNECT):
117-
Serial.println("LWMQTT_NETWORK_FAILED_CONNECT");
118-
break;
119-
case (LWMQTT_NETWORK_TIMEOUT):
120-
Serial.println("LWMQTT_NETWORK_TIMEOUT");
121-
break;
122-
case (LWMQTT_NETWORK_FAILED_READ):
123-
Serial.println("LWMQTT_NETWORK_FAILED_READ");
124-
break;
125-
case (LWMQTT_NETWORK_FAILED_WRITE):
126-
Serial.println("LWMQTT_NETWORK_FAILED_WRITE");
127-
break;
128-
case (LWMQTT_REMAINING_LENGTH_OVERFLOW):
129-
Serial.println("LWMQTT_REMAINING_LENGTH_OVERFLOW");
130-
break;
131-
case (LWMQTT_REMAINING_LENGTH_MISMATCH):
132-
Serial.println("LWMQTT_REMAINING_LENGTH_MISMATCH");
133-
break;
134-
case (LWMQTT_MISSING_OR_WRONG_PACKET):
135-
Serial.println("LWMQTT_MISSING_OR_WRONG_PACKET");
136-
break;
137-
case (LWMQTT_CONNECTION_DENIED):
138-
Serial.println("LWMQTT_CONNECTION_DENIED");
139-
break;
140-
case (LWMQTT_FAILED_SUBSCRIPTION):
141-
Serial.println("LWMQTT_FAILED_SUBSCRIPTION");
142-
break;
143-
case (LWMQTT_SUBACK_ARRAY_OVERFLOW):
144-
Serial.println("LWMQTT_SUBACK_ARRAY_OVERFLOW");
145-
break;
146-
case (LWMQTT_PONG_TIMEOUT):
147-
Serial.println("LWMQTT_PONG_TIMEOUT");
148-
break;
149-
default:
150-
Serial.println("This error code should never be reached.");
151-
break;
152-
}
153-
154-
Serial.println(mqttClient->returnCode());
155-
switch(mqttClient->returnCode()) {
156-
case (LWMQTT_CONNECTION_ACCEPTED):
157-
Serial.println("OK");
158-
break;
159-
case (LWMQTT_UNACCEPTABLE_PROTOCOL):
160-
Serial.println("LWMQTT_UNACCEPTABLE_PROTOCOLL");
161-
break;
162-
case (LWMQTT_IDENTIFIER_REJECTED):
163-
Serial.println("LWMQTT_IDENTIFIER_REJECTED");
164-
break;
165-
case (LWMQTT_SERVER_UNAVAILABLE):
166-
Serial.println("LWMQTT_SERVER_UNAVAILABLE");
167-
break;
168-
case (LWMQTT_BAD_USERNAME_OR_PASSWORD):
169-
Serial.println("LWMQTT_BAD_USERNAME_OR_PASSWORD");
170-
iss = 0; // Force JWT regeneration
171-
break;
172-
case (LWMQTT_NOT_AUTHORIZED):
173-
Serial.println("LWMQTT_NOT_AUTHORIZED");
174-
iss = 0; // Force JWT regeneration
175-
break;
176-
case (LWMQTT_UNKNOWN_RETURN_CODE):
177-
Serial.println("LWMQTT_UNKNOWN_RETURN_CODE");
178-
break;
179-
default:
180-
Serial.println("This return code should never be reached.");
181-
break;
182-
}
183-
// See https://cloud.google.com/iot/docs/how-tos/exponential-backoff
184-
if (__backoff__ < __minbackoff__) {
185-
__backoff__ = __minbackoff__;
186-
}
187-
__backoff__ = (__backoff__ * __factor__) + random(__jitter__);
188-
if (__backoff__ > __max_backoff__) {
189-
__backoff__ = __max_backoff__;
190-
}
191-
192-
// Clean up the client
193-
mqttClient->disconnect();
194-
Serial.println("Delaying " + String(__backoff__) + "ms");
195-
delay(__backoff__);
196-
keepgoing = true;
197-
} else {
198-
// We're now connected
199-
Serial.println("\nconnected!");
200-
keepgoing = false;
201-
__backoff__ = __minbackoff__;
202-
}
203-
}
204-
205-
mqttClient->subscribe(device->getConfigTopic(), 1); // Set QoS to 1 (ack) for configuration messages
206-
mqttClient->subscribe(device->getCommandsTopic(), 0); // QoS 0 (no ack) for commands
207-
if (ex_num_topics > 0) { // Subscribe to the extra topics
208-
for (int i=0; i < ex_num_topics; i++) {
209-
mqttClient->subscribe(ex_topics[i], 0); // QoS 0 (no ack) for commands
210-
}
81+
void connectWifi() {
82+
Serial.print("checking wifi...");
83+
while (WiFi.status() != WL_CONNECTED) {
84+
Serial.print(".");
85+
delay(1000);
21186
}
212-
213-
publishState("connected");
21487
}
21588

21689
///////////////////////////////
21790
// Orchestrates various methods from preceeding code.
21891
///////////////////////////////
92+
void publishTelemetry(String data) {
93+
mqtt->publishTelemetry(data);
94+
}
95+
21996
void connect() {
220-
Serial.print("checking wifi...");
221-
while (WiFi.status() != WL_CONNECTED) {
222-
Serial.print(".");
223-
delay(1000);
224-
}
225-
mqttConnect();
97+
connectWifi();
98+
mqtt->mqttConnect();
22699
}
227100

228101
void setupCloudIoT() {
@@ -234,6 +107,7 @@ void setupCloudIoT() {
234107
netClient = new WiFiClientSecure();
235108
mqttClient = new MQTTClient(512);
236109
mqttClient->setOptions(180, true, 1000); // keepAlive, cleanSession, timeout
237-
startMQTT();
110+
mqtt = new CloudIoTCoreMqtt(mqttClient, netClient, device);
111+
mqtt->startMQTT();
238112
}
239113
#endif //__ESP32_MQTT_H__
Lines changed: 43 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,44 @@
1-
/******************************************************************************
2-
* Copyright 2018 Google
3-
* Licensed under the Apache License, Version 2.0 (the "License");
4-
* you may not use this file except in compliance with the License.
5-
* You may obtain a copy of the License at
6-
*
7-
* http://www.apache.org/licenses/LICENSE-2.0
8-
*
9-
* Unless required by applicable law or agreed to in writing, software
10-
* distributed under the License is distributed on an "AS IS" BASIS,
11-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-
* See the License for the specific language governing permissions and
13-
* limitations under the License.
14-
*****************************************************************************/
15-
#include "esp8266_mqtt.h"
16-
17-
#ifndef LED_BUILTIN
18-
#define LED_BUILTIN 13
19-
#endif
20-
21-
void setup() {
22-
// put your setup code here, to run once:
23-
Serial.begin(115200);
24-
setupCloudIoT(); // Creates globals for MQTT
25-
pinMode(LED_BUILTIN, OUTPUT);
26-
startMQTT();
27-
}
28-
29-
unsigned long lastMillis = 0;
30-
void loop() {
31-
mqttClient->loop();
32-
delay(10); // <- fixes some issues with WiFi stability
33-
34-
if (!mqttClient->connected()) {
35-
connect();
36-
}
37-
38-
// publish a message roughly every second.
39-
if (millis() - lastMillis > 1000) {
40-
lastMillis = millis();
41-
publishTelemetry(getDefaultSensor());
42-
}
1+
/******************************************************************************
2+
* Copyright 2018 Google
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*****************************************************************************/
15+
#include <CloudIoTCore.h>
16+
17+
#include "esp8266_mqtt.h"
18+
19+
#ifndef LED_BUILTIN
20+
#define LED_BUILTIN 13
21+
#endif
22+
23+
void setup() {
24+
// put your setup code here, to run once:
25+
Serial.begin(115200);
26+
setupCloudIoT(); // Creates globals for MQTT
27+
pinMode(LED_BUILTIN, OUTPUT);
28+
}
29+
30+
unsigned long lastMillis = 0;
31+
void loop() {
32+
mqttClient->loop();
33+
delay(10); // <- fixes some issues with WiFi stability
34+
35+
if (!mqttClient->connected()) {
36+
connect();
37+
}
38+
39+
// TODO: Replace with your code here
40+
if (millis() - lastMillis > 60000) {
41+
lastMillis = millis();
42+
publishTelemetry(getDefaultSensor());
43+
}
4344
}

0 commit comments

Comments
 (0)