From fe585ebf0e2bfd3e98e755134080d3ecda317a58 Mon Sep 17 00:00:00 2001 From: jptrsn Date: Mon, 10 Dec 2018 23:29:24 -0500 Subject: [PATCH 1/8] Added scan duration parameter to settings --- ESP32-mqtt-room.ino | 3 ++- Settings.h | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/ESP32-mqtt-room.ino b/ESP32-mqtt-room.ino index 2897cab..b067fe4 100644 --- a/ESP32-mqtt-room.ino +++ b/ESP32-mqtt-room.ino @@ -31,7 +31,7 @@ extern "C" { #include "Settings_local.h" BLEScan* pBLEScan; -int scanTime = 5; //In seconds +int scanTime = scanDuration; //In seconds int waitTime = scanInterval; //In seconds bool updateInProgress = false; @@ -352,6 +352,7 @@ void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, 1); mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToMqtt)); wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToWifi)); diff --git a/Settings.h b/Settings.h index db248b9..343da28 100644 --- a/Settings.h +++ b/Settings.h @@ -30,3 +30,4 @@ // Define bluetooth scan parameters #define scanInterval 15 // Define the interval in seconds between scans +#define scanDuration 10 // Define the length of time in seconds for which the device will actively scan From e090524a652f9239ab24baf4ed8506ac61ce5ee2 Mon Sep 17 00:00:00 2001 From: jptrsn Date: Tue, 11 Dec 2018 21:38:34 -0500 Subject: [PATCH 2/8] Check for mqtt connected before attempting to send report --- ESP32-mqtt-room.ino | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ESP32-mqtt-room.ino b/ESP32-mqtt-room.ino index b067fe4..4c78bcb 100644 --- a/ESP32-mqtt-room.ino +++ b/ESP32-mqtt-room.ino @@ -122,9 +122,9 @@ void onMqttConnect(bool sessionPresent) { Serial.print("Session present: "); Serial.println(sessionPresent); - if (mqttClient.publish(availabilityTopic, 0, 0, "CONNECTED") == true) { + if (mqttClient.publish(healthTopic, 0, 0, "CONNECTED") == true) { Serial.print("Success sending message to topic:\t"); - Serial.println(availabilityTopic); + Serial.println(healthTopic); } else { Serial.println("Error sending message"); } @@ -293,7 +293,7 @@ class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { }; unsigned long last = 0; - +const char* healthTopic = (String(availabilityTopic) + "/" + String(room)).toCharArray(); TaskHandle_t BLEScan; void scanForDevices(void * parameter) { @@ -303,7 +303,9 @@ void scanForDevices(void * parameter) { BLEScanResults foundDevices = pBLEScan->start(scanTime); Serial.printf("Scan done! Devices found: %d\t",foundDevices.getCount()); for (uint32_t i = 0; i < foundDevices.getCount(); i++) { - reportDevice(foundDevices.getDevice(i)); + if (mqttClient.connected()) { + reportDevice(foundDevices.getDevice(i)); + } } last = millis(); Serial.println("Reports sent"); @@ -363,7 +365,7 @@ void setup() { mqttClient.onDisconnect(onMqttDisconnect); mqttClient.setServer(mqttHost, mqttPort); - mqttClient.setWill(availabilityTopic, 0, 0, "DISCONNECTED"); + mqttClient.setWill(healthTopic, 0, 0, "DISCONNECTED"); connectToWifi(); From e4ba533d41e76c9fd69a8c7098edd945e189e4da Mon Sep 17 00:00:00 2001 From: jptrsn Date: Wed, 12 Dec 2018 08:34:58 -0500 Subject: [PATCH 3/8] fix for health topic bug --- ESP32-mqtt-room.ino | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ESP32-mqtt-room.ino b/ESP32-mqtt-room.ino index 4c78bcb..439e84c 100644 --- a/ESP32-mqtt-room.ino +++ b/ESP32-mqtt-room.ino @@ -122,9 +122,9 @@ void onMqttConnect(bool sessionPresent) { Serial.print("Session present: "); Serial.println(sessionPresent); - if (mqttClient.publish(healthTopic, 0, 0, "CONNECTED") == true) { + if (mqttClient.publish(availabilityTopic, 0, 0, "CONNECTED") == true) { Serial.print("Success sending message to topic:\t"); - Serial.println(healthTopic); + Serial.println(availabilityTopic); } else { Serial.println("Error sending message"); } @@ -293,7 +293,6 @@ class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { }; unsigned long last = 0; -const char* healthTopic = (String(availabilityTopic) + "/" + String(room)).toCharArray(); TaskHandle_t BLEScan; void scanForDevices(void * parameter) { @@ -365,7 +364,7 @@ void setup() { mqttClient.onDisconnect(onMqttDisconnect); mqttClient.setServer(mqttHost, mqttPort); - mqttClient.setWill(healthTopic, 0, 0, "DISCONNECTED"); + mqttClient.setWill(availabilityTopic, 0, 0, "DISCONNECTED"); connectToWifi(); From 8ed3b2eeddbde30568928089569cad399510b61a Mon Sep 17 00:00:00 2001 From: jptrsn Date: Tue, 18 Dec 2018 20:53:46 -0500 Subject: [PATCH 4/8] Stability improvements --- .gitignore | 1 + ESP32-mqtt-room.ino | 102 ++++++++++++++++++++++++-------------------- Settings.h | 3 +- platformio.ini | 2 +- 4 files changed, 58 insertions(+), 50 deletions(-) diff --git a/.gitignore b/.gitignore index 860fe6d..0fce769 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ Settings_local.h .idea .dblite include/ +Settings_*.h diff --git a/ESP32-mqtt-room.ino b/ESP32-mqtt-room.ino index 439e84c..9d31144 100644 --- a/ESP32-mqtt-room.ino +++ b/ESP32-mqtt-room.ino @@ -28,16 +28,15 @@ extern "C" { #include "BLEBeacon.h" #include "BLEEddystoneTLM.h" #include "BLEEddystoneURL.h" -#include "Settings_local.h" +#include "Settings_module.h" BLEScan* pBLEScan; -int scanTime = scanDuration; //In seconds +int scanTime = 3; //In seconds int waitTime = scanInterval; //In seconds bool updateInProgress = false; uint16_t beconUUID = 0xFEAA; #define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) -#define LED_BUILTIN 2 WiFiClient espClient; AsyncMqttClient mqttClient; @@ -87,8 +86,8 @@ float calculateDistance(int rssi, int txPower) { void connectToWifi() { Serial.println("Connecting to WiFi..."); - WiFi.begin(ssid, password); - WiFi.setHostname(hostname); + WiFi.setHostname(hostname); + WiFi.begin(ssid, password); } void connectToMqtt() { @@ -101,19 +100,29 @@ void WiFiEvent(WiFiEvent_t event) { Serial.print("[WiFi-event] event:"); Serial.println(event); switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: - digitalWrite(LED_BUILTIN, 0); - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - connectToMqtt(); - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - digitalWrite(LED_BUILTIN, 1); - Serial.println("WiFi lost connection"); - xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi - xTimerStart(wifiReconnectTimer, 0); - break; + case SYSTEM_EVENT_STA_GOT_IP: + digitalWrite(LED_BUILTIN, 0); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + connectToMqtt(); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + digitalWrite(LED_BUILTIN, 1); + Serial.println("WiFi lost connection"); + mqttClient.disconnect(); + xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + xTimerStart(wifiReconnectTimer, 0); + break; + case SYSTEM_EVENT_WIFI_READY: + Serial.println("Wifi Ready"); + break; + case SYSTEM_EVENT_STA_START: + // Serial.println("STA Start"); + break; + case SYSTEM_EVENT_STA_STOP: + Serial.println("STA Stop"); + break; + } } @@ -133,17 +142,12 @@ void onMqttConnect(bool sessionPresent) { void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { Serial.println("Disconnected from MQTT."); - - if (WiFi.isConnected()) { + if (WiFi.isConnected() && !updateInProgress) { + Serial.println("Starting reconnect timer"); xTimerStart(mqttReconnectTimer, 0); } } -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} void reportDevice(BLEAdvertisedDevice advertisedDevice) { @@ -166,8 +170,8 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { // Serial.print("Name: "); // Serial.println(nameBLE); JSONencoder["name"] = nameBLE; - } else { - JSONencoder["name"] = "unknown"; + // } else { + // JSONencoder["name"] = "unknown"; } // Serial.printf("\n\n"); @@ -267,16 +271,23 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { String publishTopic = String(channel) + "/" + room; - if (mqttClient.publish((char *)publishTopic.c_str(), 0, 0, JSONmessageBuffer) == true) { + if (mqttClient.connected()) { + if (mqttClient.publish((char *)publishTopic.c_str(), 0, 0, JSONmessageBuffer) == true) { - // Serial.print("Success sending message to topic: "); Serial.println(publishTopic); + // Serial.print("Success sending message to topic: "); Serial.println(publishTopic); + + } else { + Serial.print("Error sending message: "); + Serial.println(publishTopic); + Serial.print("Message: "); + Serial.println(JSONmessageBuffer); + } + } else { + + Serial.println("MQTT disconnected."); + + } - } else { - Serial.print("Error sending message: "); - Serial.println(publishTopic); - Serial.print("Message: "); - Serial.println(JSONmessageBuffer); - } } class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { @@ -285,7 +296,7 @@ class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { digitalWrite(LED_BUILTIN, 1); // Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str()); - vTaskDelay(100 / portTICK_PERIOD_MS); + vTaskDelay(10 / portTICK_PERIOD_MS); digitalWrite(LED_BUILTIN, 0); } @@ -315,15 +326,11 @@ void scanForDevices(void * parameter) { void configureOTA() { ArduinoOTA .onStart([]() { + Serial.println("OTA Start"); + pBLEScan->stop(); updateInProgress = true; - String type; - if (ArduinoOTA.getCommand() == U_FLASH) - type = "sketch"; - else // U_SPIFFS - type = "filesystem"; - - // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() - Serial.println("Start updating " + type); + mqttClient.disconnect(true); + xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi }) .onEnd([]() { updateInProgress = false; @@ -332,7 +339,7 @@ void configureOTA() { }) .onProgress([](unsigned int progress, unsigned int total) { byte percent = (progress / (total / 100)); - Serial.printf("Progress: %u%%\n", percent); + Serial.printf("Progress: %u% \n", percent); digitalWrite(LED_BUILTIN, percent % 2); }) .onError([](ota_error_t error) { @@ -365,6 +372,7 @@ void setup() { mqttClient.setServer(mqttHost, mqttPort); mqttClient.setWill(availabilityTopic, 0, 0, "DISCONNECTED"); + mqttClient.setKeepAlive(60); connectToWifi(); @@ -374,8 +382,8 @@ void setup() { pBLEScan = BLEDevice::getScan(); //create new scan pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster - // pBLEScan->setInterval(100); - // pBLEScan->setWindow(200); + pBLEScan->setInterval(0x80); + pBLEScan->setWindow(0x10); xTaskCreatePinnedToCore( scanForDevices, diff --git a/Settings.h b/Settings.h index 343da28..0c6f22f 100644 --- a/Settings.h +++ b/Settings.h @@ -26,8 +26,7 @@ #define channel "room_presence" //Define the topic for publishing availability -#define availabilityTopic "presence_nodes/esp32" +#define availabilityTopic "presence_nodes/" room // Define bluetooth scan parameters #define scanInterval 15 // Define the interval in seconds between scans -#define scanDuration 10 // Define the length of time in seconds for which the device will actively scan diff --git a/platformio.ini b/platformio.ini index 16b478e..9949f39 100644 --- a/platformio.ini +++ b/platformio.ini @@ -15,6 +15,6 @@ src_dir = . platform = espressif32 framework = arduino board = esp32dev -lib_deps = ArduinoJSON@5.13.2, ESP32 BLE Arduino, AsyncMqttClient@0.8.2, AsyncTCP@1.0.1 +lib_deps = ArduinoJSON@5.13.2, ESP32 BLE Arduino, AsyncMqttClient, AsyncTCP board_build.partitions = partitions_singleapp.csv upload_port = COM13 From 2ab9f9979897d3cac26d342d3b4f804f727b4789 Mon Sep 17 00:00:00 2001 From: jptrsn Date: Wed, 26 Dec 2018 14:55:33 -0500 Subject: [PATCH 5/8] Fix for hostname causing disconnection --- ESP32-mqtt-room.ino | 31 ++++++++++++++++++++----------- Settings.h | 6 ++++++ 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/ESP32-mqtt-room.ino b/ESP32-mqtt-room.ino index 9d31144..1b2b836 100644 --- a/ESP32-mqtt-room.ino +++ b/ESP32-mqtt-room.ino @@ -28,14 +28,14 @@ extern "C" { #include "BLEBeacon.h" #include "BLEEddystoneTLM.h" #include "BLEEddystoneURL.h" -#include "Settings_module.h" +#include "Settings_local.h" BLEScan* pBLEScan; int scanTime = 3; //In seconds int waitTime = scanInterval; //In seconds bool updateInProgress = false; -uint16_t beconUUID = 0xFEAA; +uint16_t beaconUUID = 0xFEAA; #define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) WiFiClient espClient; @@ -86,8 +86,10 @@ float calculateDistance(int rssi, int txPower) { void connectToWifi() { Serial.println("Connecting to WiFi..."); - WiFi.setHostname(hostname); + Serial.print("Setting hostname to "); + Serial.println(hostname); WiFi.begin(ssid, password); + WiFi.setHostname(hostname); } void connectToMqtt() { @@ -101,13 +103,13 @@ void WiFiEvent(WiFiEvent_t event) { Serial.println(event); switch(event) { case SYSTEM_EVENT_STA_GOT_IP: - digitalWrite(LED_BUILTIN, 0); + digitalWrite(LED_BUILTIN, !LED_ON); Serial.println("IP address: "); Serial.println(WiFi.localIP()); connectToMqtt(); break; case SYSTEM_EVENT_STA_DISCONNECTED: - digitalWrite(LED_BUILTIN, 1); + digitalWrite(LED_BUILTIN, LED_ON); Serial.println("WiFi lost connection"); mqttClient.disconnect(); xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi @@ -180,7 +182,7 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { uint8_t cServiceData[100]; strServiceData.copy((char *)cServiceData, strServiceData.length(), 0); - if (advertisedDevice.getServiceDataUUID().equals(BLEUUID(beconUUID))==true) { // found Eddystone UUID + if (advertisedDevice.getServiceDataUUID().equals(BLEUUID(beaconUUID))==true) { // found Eddystone UUID // Serial.printf("is Eddystone: %d %s length %d\n", advertisedDevice.getServiceDataUUID().bitSize(), advertisedDevice.getServiceDataUUID().toString().c_str(),strServiceData.length()); if (cServiceData[0]==0x10) { BLEEddystoneURL oBeacon = BLEEddystoneURL(); @@ -294,10 +296,10 @@ class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { void onResult(BLEAdvertisedDevice advertisedDevice) { - digitalWrite(LED_BUILTIN, 1); + digitalWrite(LED_BUILTIN, LED_ON); // Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str()); vTaskDelay(10 / portTICK_PERIOD_MS); - digitalWrite(LED_BUILTIN, 0); + digitalWrite(LED_BUILTIN, !LED_ON); } @@ -308,10 +310,17 @@ TaskHandle_t BLEScan; void scanForDevices(void * parameter) { while(1) { - if (!updateInProgress && WiFi.isConnected() && mqttClient.connected() && (millis() - last > (waitTime * 1000) || last == 0)) { + if (!updateInProgress && WiFi.isConnected() && (millis() - last > (waitTime * 1000) || last == 0)) { + // mqttClient.disconnect(true); + // xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi Serial.print("Scanning...\t"); BLEScanResults foundDevices = pBLEScan->start(scanTime); Serial.printf("Scan done! Devices found: %d\t",foundDevices.getCount()); + // mqttClient.connect(); + // while (!mqttClient.connected()) { + // Serial.print("."); + // vTaskDelay(10 / portTICK_PERIOD_MS); + // } for (uint32_t i = 0; i < foundDevices.getCount(); i++) { if (mqttClient.connected()) { reportDevice(foundDevices.getDevice(i)); @@ -334,7 +343,7 @@ void configureOTA() { }) .onEnd([]() { updateInProgress = false; - digitalWrite(LED_BUILTIN, 0); + digitalWrite(LED_BUILTIN, !LED_ON); Serial.println("\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { @@ -360,7 +369,7 @@ void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); - digitalWrite(LED_BUILTIN, 1); + digitalWrite(LED_BUILTIN, LED_ON); mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToMqtt)); wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToWifi)); diff --git a/Settings.h b/Settings.h index 0c6f22f..b006816 100644 --- a/Settings.h +++ b/Settings.h @@ -22,6 +22,12 @@ //Replace with the room name where the node will be placed; example: #define room "living-room" #define room "$ROOM_NAME$" +//Specify the LED pin. For most dev boards, this is GPIO2 +#define LED_BUILTIN 2 + +// Logic level for turning the led on. Most boards use active low, meaning LED_ON should be set to 0 +#define LED_ON 0 + //Define the base topic for room detection. Usually "room_presence" #define channel "room_presence" From 6e5d6946a669c04cbc964aa225c690a6de8ae521 Mon Sep 17 00:00:00 2001 From: jptrsn Date: Thu, 27 Dec 2018 09:12:56 -0500 Subject: [PATCH 6/8] Set mqtt client ID to same as host name --- ESP32-mqtt-room.ino | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/ESP32-mqtt-room.ino b/ESP32-mqtt-room.ino index 1b2b836..bf2502d 100644 --- a/ESP32-mqtt-room.ino +++ b/ESP32-mqtt-room.ino @@ -28,7 +28,7 @@ extern "C" { #include "BLEBeacon.h" #include "BLEEddystoneTLM.h" #include "BLEEddystoneURL.h" -#include "Settings_local.h" +#include "Settings_bedroom.h" BLEScan* pBLEScan; int scanTime = 3; //In seconds @@ -86,8 +86,6 @@ float calculateDistance(int rssi, int txPower) { void connectToWifi() { Serial.println("Connecting to WiFi..."); - Serial.print("Setting hostname to "); - Serial.println(hostname); WiFi.begin(ssid, password); WiFi.setHostname(hostname); } @@ -95,6 +93,7 @@ void connectToWifi() { void connectToMqtt() { Serial.println("Connecting to MQTT"); mqttClient.setCredentials(mqttUser, mqttPassword); + mqttClient.setClientId(hostname); mqttClient.connect(); } @@ -220,6 +219,7 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { // Serial.printf("Major: %d Minor: %d UUID: %s Power: %d\n",ENDIAN_CHANGE_U16(oBeacon.getMajor()),ENDIAN_CHANGE_U16(oBeacon.getMinor()),proximityUUID.c_str(),oBeacon.getSignalPower()); float distance = calculateDistance(rssi, oBeacon.getSignalPower()); + // Serial.print("RSSI: "); // Serial.print(rssi); // Serial.print("\ttxPower: "); @@ -240,15 +240,17 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { } else { + float distance; + if (advertisedDevice.haveTXPower()) { - float distance = calculateDistance(rssi, advertisedDevice.getTXPower()); + distance = calculateDistance(rssi, advertisedDevice.getTXPower()); JSONencoder["txPower"] = advertisedDevice.getTXPower(); - JSONencoder["distance"] = distance; } else { - float distance = calculateDistance(rssi, -59); - JSONencoder["distance"] = distance; + distance = calculateDistance(rssi, -59); } + JSONencoder["distance"] = distance; + // Serial.printf("strManufacturerData: %d \n",strManufacturerData.length()); // TODO: parse manufacturer data @@ -273,7 +275,7 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { String publishTopic = String(channel) + "/" + room; - if (mqttClient.connected()) { + if (mqttClient.connected() && JSONencoder["distance"] < maxDistance) { if (mqttClient.publish((char *)publishTopic.c_str(), 0, 0, JSONmessageBuffer) == true) { // Serial.print("Success sending message to topic: "); Serial.println(publishTopic); @@ -284,6 +286,10 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { Serial.print("Message: "); Serial.println(JSONmessageBuffer); } + } else if (mqttClient.connected() && JSONencoder["distance"] >= maxDistance) { + + Serial.printf("%d exceeded distance threshold\n", JSONencoder["distance"]); + } else { Serial.println("MQTT disconnected."); @@ -360,7 +366,7 @@ void configureOTA() { else if (error == OTA_END_ERROR) Serial.println("End Failed"); ESP.restart(); }); - + ArduinoOTA.setHostname(hostname); ArduinoOTA.begin(); } From 150a55cf160f56ec88958e1ac53693b39ad9e9b7 Mon Sep 17 00:00:00 2001 From: jptrsn Date: Sun, 13 Jan 2019 09:42:24 -0500 Subject: [PATCH 7/8] Reverted introduction of crashing bug --- ESP32-mqtt-room.ino | 26 ++-- Settings.h | 6 +- lib/BLEEddystoneTLM/BLEEddystoneTLM.cpp | 135 --------------------- lib/BLEEddystoneTLM/BLEEddystoneTLM.h | 51 -------- lib/BLEEddystoneURL/BLEEddystoneURL.cpp | 150 ------------------------ lib/BLEEddystoneURL/BLEEddystoneURL.h | 43 ------- lib/readme.txt | 41 ------- platformio.ini | 2 +- 8 files changed, 20 insertions(+), 434 deletions(-) delete mode 100644 lib/BLEEddystoneTLM/BLEEddystoneTLM.cpp delete mode 100644 lib/BLEEddystoneTLM/BLEEddystoneTLM.h delete mode 100644 lib/BLEEddystoneURL/BLEEddystoneURL.cpp delete mode 100644 lib/BLEEddystoneURL/BLEEddystoneURL.h delete mode 100644 lib/readme.txt diff --git a/ESP32-mqtt-room.ino b/ESP32-mqtt-room.ino index bf2502d..4c30c02 100644 --- a/ESP32-mqtt-room.ino +++ b/ESP32-mqtt-room.ino @@ -28,7 +28,7 @@ extern "C" { #include "BLEBeacon.h" #include "BLEEddystoneTLM.h" #include "BLEEddystoneURL.h" -#include "Settings_bedroom.h" +#include "Settings_kitchen.h" BLEScan* pBLEScan; int scanTime = 3; //In seconds @@ -73,7 +73,9 @@ float calculateDistance(int rssi, int txPower) { if (!txPower) { // somewhat reasonable default value txPower = -59; - } + } else if (txPower > 0) { + txPower = txPower * -1; + } const float ratio = rssi * 1.0 / txPower; if (ratio < 1.0) { @@ -161,6 +163,7 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { mac_address.replace(":",""); mac_address.toLowerCase(); int rssi = advertisedDevice.getRSSI(); + float distance; JSONencoder["id"] = mac_address; JSONencoder["uuid"] = mac_address; @@ -215,10 +218,7 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { String proximityUUID = getProximityUUIDString(oBeacon); - // Serial.printf("iBeacon Frame\n"); - // Serial.printf("Major: %d Minor: %d UUID: %s Power: %d\n",ENDIAN_CHANGE_U16(oBeacon.getMajor()),ENDIAN_CHANGE_U16(oBeacon.getMinor()),proximityUUID.c_str(),oBeacon.getSignalPower()); - - float distance = calculateDistance(rssi, oBeacon.getSignalPower()); + distance = calculateDistance(rssi, oBeacon.getSignalPower()); // Serial.print("RSSI: "); // Serial.print(rssi); @@ -238,9 +238,11 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { JSONencoder["txPower"] = oBeacon.getSignalPower(); JSONencoder["distance"] = distance; - } else { + Serial.printf("iBeacon Frame\n"); + Serial.printf("Major: %d Minor: %d UUID: %s Power: %d Rssi: %d Distance: %f\n",ENDIAN_CHANGE_U16(oBeacon.getMajor()),ENDIAN_CHANGE_U16(oBeacon.getMinor()),proximityUUID.c_str(),oBeacon.getSignalPower(), rssi, distance); + - float distance; + } else { if (advertisedDevice.haveTXPower()) { distance = calculateDistance(rssi, advertisedDevice.getTXPower()); @@ -258,11 +260,11 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { } else { if (advertisedDevice.haveTXPower()) { - float distance = calculateDistance(rssi, advertisedDevice.getTXPower()); + distance = calculateDistance(rssi, advertisedDevice.getTXPower()); JSONencoder["txPower"] = advertisedDevice.getTXPower(); JSONencoder["distance"] = distance; } else { - float distance = calculateDistance(rssi, -59); + distance = calculateDistance(rssi, -59); JSONencoder["distance"] = distance; } @@ -286,9 +288,9 @@ void reportDevice(BLEAdvertisedDevice advertisedDevice) { Serial.print("Message: "); Serial.println(JSONmessageBuffer); } - } else if (mqttClient.connected() && JSONencoder["distance"] >= maxDistance) { + } else if (mqttClient.connected() && distance >= maxDistance) { - Serial.printf("%d exceeded distance threshold\n", JSONencoder["distance"]); + // Serial.printf("%f exceeded distance threshold\n", distance); } else { diff --git a/Settings.h b/Settings.h index b006816..2be23da 100644 --- a/Settings.h +++ b/Settings.h @@ -35,4 +35,8 @@ #define availabilityTopic "presence_nodes/" room // Define bluetooth scan parameters -#define scanInterval 15 // Define the interval in seconds between scans +#define scanInterval 2 // Define the interval in seconds between scans +#define advertisementDuration 3 // Define the duration in seconds that the device should advertise as a beacon to other sensors + +// Maximum distance (in meters) to report. Devices that are calculated to be further than this distance in meters will not be reported +#define maxDistance 5 diff --git a/lib/BLEEddystoneTLM/BLEEddystoneTLM.cpp b/lib/BLEEddystoneTLM/BLEEddystoneTLM.cpp deleted file mode 100644 index c944a29..0000000 --- a/lib/BLEEddystoneTLM/BLEEddystoneTLM.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - * BLEEddystoneTLM.cpp - * - * 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" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include "BLEEddystoneTLM.h" - -static const char LOG_TAG[] = "BLEEddystoneTLM"; -#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) -#define ENDIAN_CHANGE_U32(x) ((((x)&0xFF000000)>>24) + (((x)&0x00FF0000)>>8)) + ((((x)&0xFF00)<<8) + (((x)&0xFF)<<24)) - -BLEEddystoneTLM::BLEEddystoneTLM() { - beconUUID = 0xFEAA; - m_eddystoneData.frameType = EDDYSTONE_TLM_FRAME_TYPE; - m_eddystoneData.version = 0; - m_eddystoneData.volt = 3300; // 3300mV = 3.3V - m_eddystoneData.temp = (uint16_t)((float)23.00); - m_eddystoneData.advCount = 0; - m_eddystoneData.tmil = 0; -} // BLEEddystoneTLM - -std::string BLEEddystoneTLM::getData() { - return std::string((char*)&m_eddystoneData, sizeof(m_eddystoneData)); -} // getData - -BLEUUID BLEEddystoneTLM::getUUID() { - return BLEUUID(beconUUID); -} // getUUID - -uint8_t BLEEddystoneTLM::getVersion() { - return m_eddystoneData.version; -} // getVersion - -uint16_t BLEEddystoneTLM::getVolt() { - return m_eddystoneData.volt; -} // getVolt - -float BLEEddystoneTLM::getTemp() { - return (float)m_eddystoneData.temp; -} // getTemp - -uint32_t BLEEddystoneTLM::getCount() { - return m_eddystoneData.advCount; -} // getCount - -uint32_t BLEEddystoneTLM::getTime() { - return m_eddystoneData.tmil; -} // getTime - -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); - out += buff.substring(buff.length()-4,buff.length()).c_str(); - out += "."; - buff = "00"+String((rawsec/36000)%24, DEC); - out += buff.substring(buff.length()-2,buff.length()).c_str(); - out += ":"; - buff = "00"+String((rawsec/600)%60, DEC); - out += buff.substring(buff.length()-2,buff.length()).c_str(); - out += ":"; - buff = "00"+String((rawsec/10)%60, DEC); - out += buff.substring(buff.length()-2,buff.length()).c_str(); - out += "\n"; - - return out; -} // toString - -/** - * Set the raw data for the beacon record. - */ -void BLEEddystoneTLM::setData(std::string data) { - if (data.length() != sizeof(m_eddystoneData)) { - ESP_LOGE(LOG_TAG, "Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_eddystoneData)); - return; - } - memcpy(&m_eddystoneData, data.data(), data.length()); -} // setData - -void BLEEddystoneTLM::setUUID(BLEUUID l_uuid) { - beconUUID = l_uuid.getNative()->uuid.uuid16; -} // setUUID - -void BLEEddystoneTLM::setVersion(uint8_t version) { - m_eddystoneData.version = version; -} // setVersion - -void BLEEddystoneTLM::setVolt(uint16_t volt) { - m_eddystoneData.volt = volt; -} // setVolt - -void BLEEddystoneTLM::setTemp(float temp) { - m_eddystoneData.temp = (uint16_t)temp; -} // setTemp - -void BLEEddystoneTLM::setCount(uint32_t advCount) { - m_eddystoneData.advCount = advCount; -} // setCount - -void BLEEddystoneTLM::setTime(uint32_t tmil) { - m_eddystoneData.tmil = tmil; -} // setTime - -#endif diff --git a/lib/BLEEddystoneTLM/BLEEddystoneTLM.h b/lib/BLEEddystoneTLM/BLEEddystoneTLM.h deleted file mode 100644 index 94327a3..0000000 --- a/lib/BLEEddystoneTLM/BLEEddystoneTLM.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * BLEEddystoneTLM.cpp - * - * 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_ -#define _BLEEddystoneTLM_H_ -#include "BLEUUID.h" - -#define EDDYSTONE_TLM_FRAME_TYPE 0x20 - -/** - * @brief Representation of a beacon. - * See: - * * https://github.com/google/eddystone - */ -class BLEEddystoneTLM { -private: - uint16_t beconUUID; - struct { - uint8_t frameType; - int8_t version; - uint16_t volt; - uint16_t temp; - uint32_t advCount; - uint32_t tmil; - } __attribute__((packed))m_eddystoneData; -public: - BLEEddystoneTLM(); - std::string getData(); - BLEUUID getUUID(); - uint8_t getVersion(); - uint16_t getVolt(); - float getTemp(); - uint32_t getCount(); - uint32_t getTime(); - std::string toString(); - void setData(std::string data); - void setUUID(BLEUUID l_uuid); - void setVersion(uint8_t version); - void setVolt(uint16_t volt); - void setTemp(float temp); - void setCount(uint32_t advCount); - void setTime(uint32_t tmil); - -}; // BLEEddystoneTLM - -#endif /* _BLEEddystoneTLM_H_ */ diff --git a/lib/BLEEddystoneURL/BLEEddystoneURL.cpp b/lib/BLEEddystoneURL/BLEEddystoneURL.cpp deleted file mode 100644 index 19f02fa..0000000 --- a/lib/BLEEddystoneURL/BLEEddystoneURL.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* - * BLEEddystoneURL.cpp - * - * 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) -#include -#include -#include "BLEEddystoneURL.h" - -static const char LOG_TAG[] = "BLEEddystoneURL"; - -BLEEddystoneURL::BLEEddystoneURL() { - beconUUID = 0xFEAA; - lengthURL = 0; - m_eddystoneData.frameType = EDDYSTONE_URL_FRAME_TYPE; - m_eddystoneData.advertisedTxPower = 0; - memset(m_eddystoneData.url, 0, sizeof(m_eddystoneData.url)); -} // BLEEddystoneURL - -std::string BLEEddystoneURL::getData() { - return std::string((char*)&m_eddystoneData, sizeof(m_eddystoneData)); -} // getData - -BLEUUID BLEEddystoneURL::getUUID() { - return BLEUUID(beconUUID); -} // getUUID - -int8_t BLEEddystoneURL::getPower() { - return m_eddystoneData.advertisedTxPower; -} // getPower - -std::string BLEEddystoneURL::getURL() { - return std::string((char*)&m_eddystoneData.url, sizeof(m_eddystoneData.url)); -} // getURL - -std::string BLEEddystoneURL::getDecodedURL() { - std::string decodedURL = ""; - - switch (m_eddystoneData.url[0]) { - case 0x00: - decodedURL += "http://www."; - break; - case 0x01: - decodedURL += "https://www."; - break; - case 0x02: - decodedURL += "http://"; - break; - case 0x03: - decodedURL += "https://"; - break; - default: - decodedURL += m_eddystoneData.url[0]; - } - - for (int i=1;i33&&m_eddystoneData.url[i]<127) { - decodedURL += m_eddystoneData.url[i]; - } else { - switch (m_eddystoneData.url[i]) { - case 0x00: - decodedURL += ".com/"; - break; - case 0x01: - decodedURL += ".org/"; - break; - case 0x02: - decodedURL += ".edu/"; - break; - case 0x03: - decodedURL += ".net/"; - break; - case 0x04: - decodedURL += ".info/"; - break; - case 0x05: - decodedURL += ".biz/"; - break; - case 0x06: - decodedURL += ".gov/"; - break; - case 0x07: - decodedURL += ".com"; - break; - case 0x08: - decodedURL += ".org"; - break; - case 0x09: - decodedURL += ".edu"; - break; - case 0x0A: - decodedURL += ".net"; - break; - case 0x0B: - decodedURL += ".info"; - break; - case 0x0C: - decodedURL += ".biz"; - break; - case 0x0D: - decodedURL += ".gov"; - break; - } - } - } - - - return decodedURL; -} // getDecodedURL - - - -/** - * Set the raw data for the beacon record. - */ -void BLEEddystoneURL::setData(std::string data) { - if (data.length() > sizeof(m_eddystoneData)) { - ESP_LOGE(LOG_TAG, "Unable to set the data ... length passed in was %d and max expected %d", data.length(), sizeof(m_eddystoneData)); - return; - } - memset(&m_eddystoneData, 0, sizeof(m_eddystoneData)); - memcpy(&m_eddystoneData, data.data(), data.length()); - lengthURL=data.length()-(sizeof(m_eddystoneData)-sizeof(m_eddystoneData.url)); - -} // setData - -void BLEEddystoneURL::setUUID(BLEUUID l_uuid) { - beconUUID = l_uuid.getNative()->uuid.uuid16; -} // setUUID - -void BLEEddystoneURL::setPower(int8_t advertisedTxPower) { - m_eddystoneData.advertisedTxPower = advertisedTxPower; -} // setPower - -void BLEEddystoneURL::setURL(std::string url) { - if (url.length() > sizeof(m_eddystoneData.url)) { - ESP_LOGE(LOG_TAG, "Unable to set the url ... length passed in was %d and max expected %d", url.length(), sizeof(m_eddystoneData.url)); - return; - } - memset(m_eddystoneData.url, 0, sizeof(m_eddystoneData.url)); - memcpy(m_eddystoneData.url, url.data(), url.length()); - lengthURL=url.length(); -} // setURL - - -#endif diff --git a/lib/BLEEddystoneURL/BLEEddystoneURL.h b/lib/BLEEddystoneURL/BLEEddystoneURL.h deleted file mode 100644 index 3ce4632..0000000 --- a/lib/BLEEddystoneURL/BLEEddystoneURL.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * BLEEddystoneURL.cpp - * - * 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_ -#define _BLEEddystoneURL_H_ -#include "BLEUUID.h" - -#define EDDYSTONE_URL_FRAME_TYPE 0x10 - -/** - * @brief Representation of a beacon. - * See: - * * https://github.com/google/eddystone - */ -class BLEEddystoneURL { -private: - uint16_t beconUUID; - uint8_t lengthURL; - struct { - uint8_t frameType; - int8_t advertisedTxPower; - uint8_t url[16]; - } __attribute__((packed))m_eddystoneData; -public: - BLEEddystoneURL(); - std::string getData(); - BLEUUID getUUID(); - int8_t getPower(); - std::string getURL(); - std::string getDecodedURL(); - void setData(std::string data); - void setUUID(BLEUUID l_uuid); - void setPower(int8_t advertisedTxPower); - void setURL(std::string url); - -}; // BLEEddystoneURL - -#endif /* _BLEEddystoneURL_H_ */ diff --git a/lib/readme.txt b/lib/readme.txt deleted file mode 100644 index cfa16df..0000000 --- a/lib/readme.txt +++ /dev/null @@ -1,41 +0,0 @@ - -This directory is intended for project specific (private) libraries. -PlatformIO will compile them to static libraries and link them to executable files. - -The source code of each library should be placed in separate directories, like -"lib/private_lib/[here are source files]". - -For example, see the structure of the following two libraries `Foo` and `Bar`: - -|--lib -| | -| |--Bar -| | |--docs -| | |--examples -| | |--src -| | |- Bar.c -| | |- Bar.h -| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html -| | -| |--Foo -| | |- Foo.c -| | |- Foo.h -| | -| |- readme.txt --> THIS FILE -| -|- platformio.ini -|--src - |- main.c - -Then in `src/main.c` you should use: - -#include -#include - -// rest H/C/CPP code - -PlatformIO will find your libraries automatically, configure preprocessor's -include paths and build them. - -More information about PlatformIO Library Dependency Finder -- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/platformio.ini b/platformio.ini index 9949f39..2535451 100644 --- a/platformio.ini +++ b/platformio.ini @@ -17,4 +17,4 @@ framework = arduino board = esp32dev lib_deps = ArduinoJSON@5.13.2, ESP32 BLE Arduino, AsyncMqttClient, AsyncTCP board_build.partitions = partitions_singleapp.csv -upload_port = COM13 +upload_port = COM9 From c376a1d7d8e32d22c078c6febcc168ce0f17ffeb Mon Sep 17 00:00:00 2001 From: jptrsn Date: Sun, 10 Feb 2019 13:54:19 -0500 Subject: [PATCH 8/8] Fix for asyncTCP update --- platformio.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platformio.ini b/platformio.ini index 2535451..0cd3f41 100644 --- a/platformio.ini +++ b/platformio.ini @@ -15,6 +15,6 @@ src_dir = . platform = espressif32 framework = arduino board = esp32dev -lib_deps = ArduinoJSON@5.13.2, ESP32 BLE Arduino, AsyncMqttClient, AsyncTCP +lib_deps = ArduinoJSON@5.13.4, ESP32 BLE Arduino, AsyncMqttClient@0.8.2, AsyncTCP board_build.partitions = partitions_singleapp.csv -upload_port = COM9 +upload_port = COM13