Skip to content

Commit

Permalink
Merge branch 'feature/async-mqtt' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
jptrsn committed Oct 13, 2018
2 parents e147acb + 43bce87 commit 01181e5
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 51 deletions.
119 changes: 77 additions & 42 deletions ESP32-mqtt-room.ino
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@
Ported to Arduino ESP32 by Evandro Copercini
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncTCP.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <AsyncMqttClient.h>
#include <ArduinoJSON.h>
#include "BLEBeacon.h"
#include "BLEEddystoneTLM.h"
#include "BLEEddystoneURL.h"
Expand All @@ -29,7 +34,9 @@ uint16_t beconUUID = 0xFEAA;
#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8))

WiFiClient espClient;
PubSubClient client(espClient);
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

TaskHandle_t CoreZeroTask;

Expand Down Expand Up @@ -82,23 +89,63 @@ float calculateDistance(int rssi, int txPower) {

}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");

if (client.connect(uint64_to_string(ESP.getEfuseMac()), mqttUser, mqttPassword )) {
Serial.print("connected with client id ");
Serial.println(uint64_to_string(ESP.getEfuseMac()));
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
void connectToWifi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
WiFi.setHostname(hostname);
}

void connectToMqtt() {
Serial.println("Connecting to MQTT");
mqttClient.setCredentials(mqttUser, mqttPassword);
mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch(event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
}
}

void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);

String publishTopic = String(channel) + "/" + room;
if (mqttClient.publish((char *)publishTopic.c_str(), 0, 0, "Hello from ESP32") == true) {
Serial.println("Success sending message to topic");
} else {
Serial.println("Error sending message");
}

}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println("Disconnected from MQTT.");

if (WiFi.isConnected()) {
xTimerStart(mqttReconnectTimer, 0);
}
}

void onMqttPublish(uint16_t packetId) {
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {

void onResult(BLEAdvertisedDevice advertisedDevice) {
Expand Down Expand Up @@ -227,7 +274,7 @@ class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {

String publishTopic = String(channel) + "/" + room;

if (client.publish((char *)publishTopic.c_str(), JSONmessageBuffer) == true) {
if (mqttClient.publish((char *)publishTopic.c_str(), 0, 0, JSONmessageBuffer) == true) {

Serial.print("Success sending message to topic: "); Serial.println(publishTopic);
// Serial.print("Message: "); Serial.println(JSONmessageBuffer);
Expand Down Expand Up @@ -256,46 +303,36 @@ void createTaskOnCoreZero() {


void setup() {

Serial.begin(115200);
createTaskOnCoreZero();
WiFi.begin(ssid, password);
WiFi.setHostname(hostname);

Serial.print("Connecting to WiFi..");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

Serial.println();
Serial.print("Connected to the WiFi network as ");
Serial.println(hostname);
WiFi.onEvent(WiFiEvent);

client.setServer(mqttServer, mqttPort);
reconnect();
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);

String publishTopic = String(channel) + "/" + room;
if (client.publish((char *)publishTopic.c_str(), "Hello from ESP32") == true) {
Serial.println("Success sending message to topic");
} else {
Serial.println("Error sending message");
}
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(mqttHost, mqttPort);

connectToWifi();

createTaskOnCoreZero();

BLEDevice::init("");
pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster

}

unsigned long last = 0;

void loop() {
if (!client.connected()) {
reconnect();
}

// vTaskDelay(10); // watchdog timer
vTaskDelay(10); // watchdog timer

if (millis() - last > (waitTime * 1000) || last == 0) {
Serial.println("Scanning...");
Expand All @@ -304,8 +341,6 @@ void loop() {
last = millis();
}



}

char *uint64_to_string(uint64_t input) {
Expand Down
4 changes: 2 additions & 2 deletions Settings.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
//Replace with a human-friendly host name.
#define hostname "esp32_room_presence"

//Replace with your MQTT Broker address; example: #define mqttServer "192.168.0.112"
#define mqttServer "$MQTT_BROKER_ADDRESS$"
//Replace with your MQTT Broker address; example: #define mqttHost IPAddress(192, 168, 1, 195)
#define mqttHost IPAddress(192, 168, 1, 195)

//Replace with your MQTT Broker port; example: #define mqttPort 1883
#define mqttPort $MQTT_PORT$
Expand Down
2 changes: 1 addition & 1 deletion Settings_CI.h
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#define ssid "Travis"
#define password "123456789"
#define hostname "esp32_room_presence"
#define mqttServer "192.168.1.1"
#define mqttHost IPAddress(192, 168, 1, 195)
#define mqttPort 1883
#define mqttUser "homeassistant"
#define mqttPassword "123456789"
Expand Down
11 changes: 6 additions & 5 deletions lib/BLEEddystoneTLM/BLEEddystoneTLM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*
* Created on: Mar 12, 2018
* Author: pcbreflux
* See original repository at https://github.com/pcbreflux/espressif/tree/master/esp32/arduino/sketchbook/ESP32_BLE_beaconscan
*/
#include "Arduino.h"
#include "sdkconfig.h"
Expand Down Expand Up @@ -57,27 +58,27 @@ std::string BLEEddystoneTLM::toString() {
std::string out = "";
String buff;
uint32_t rawsec;

out += "Version ";
buff = String(m_eddystoneData.version, DEC);
out += buff.c_str();
out += "\n";

out += "Battery Voltage ";
buff = String(ENDIAN_CHANGE_U16(m_eddystoneData.volt), DEC);
out += buff.c_str();
out += " mV\n";

out += "Temperature ";
buff = String((float)m_eddystoneData.temp, 1);
out += buff.c_str();
out += " °C\n";

out += "Adv. Count ";
buff = String(ENDIAN_CHANGE_U32(m_eddystoneData.advCount), DEC);
out += buff.c_str();
out += "\n";

out += "Time ";
rawsec = ENDIAN_CHANGE_U32(m_eddystoneData.tmil);
buff = "0000"+String(rawsec/864000, DEC);
Expand Down
1 change: 1 addition & 0 deletions lib/BLEEddystoneTLM/BLEEddystoneTLM.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*
* Created on: Mar 12, 2018
* Author: pcbreflux
* See original repository at https://github.com/pcbreflux/espressif/tree/master/esp32/arduino/sketchbook/ESP32_BLE_beaconscan
*/

#ifndef _BLEEddystoneTLM_H_
Expand Down
1 change: 1 addition & 0 deletions lib/BLEEddystoneURL/BLEEddystoneURL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*
* Created on: Mar 12, 2018
* Author: pcbreflux
* See original repository at https://github.com/pcbreflux/espressif/tree/master/esp32/arduino/sketchbook/ESP32_BLE_beaconscan
*/
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
Expand Down
1 change: 1 addition & 0 deletions lib/BLEEddystoneURL/BLEEddystoneURL.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*
* Created on: Mar 12, 2018
* Author: pcbreflux
* See original repository at https://github.com/pcbreflux/espressif/tree/master/esp32/arduino/sketchbook/ESP32_BLE_beaconscan
*/

#ifndef _BLEEddystoneURL_H_
Expand Down
2 changes: 1 addition & 1 deletion platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ src_dir = .
platform = espressif32
framework = arduino
board = esp32dev
lib_deps = [email protected], [email protected], ESP32 BLE Arduino, [email protected], [email protected]
lib_deps = [email protected], ESP32 BLE Arduino, [email protected], [email protected]
board_build.partitions = partitions_singleapp.csv
upload_port = COM13

0 comments on commit 01181e5

Please sign in to comment.