Mutate relevant compilation variables into config (#1256)

* Move minRssi in config_BT.h
Move var definitions next to compilation var definitions

* Introduce UseExtDecoder when is def MQTTDecodeTopic
Replace #ifdef MQTTDecodeTopic by #if UseExtDecoder

* Rename AttemptBLECOnnect to AttemptBLEConnect

* Create a struct (BTConfig_s) for BT configuration data
Create a default config for BTConfig_s (BTConfig_default) based on defines
Create a global variable (BTConfig) to hold live BT configuration data and initialize it
Move bleConnect to BTConfig

* Move BLEscanBeforeConnect in BTConfig

* Move BLEinterval in BTConfig

* Move PublishOnlySensors in BTConfig

* Move hassPresence in BTConfig

* Move minRssi into BTConfig

* Introduce presenceTopic into BTConfig

* Move MQTTDecodeTopic as extDecoderTopic into BTConfig

* Mutate UseExtDecoder as runtime var BTConfig.extDecoderTopic

* Remove ServicedataMinLength (unused)
Always declare AttemptBLEConnect & BLE_FILTER_CONNECTABLE

* Mutate BLE_FILTER_CONNECTABLE as runtime parameter BTConfig.filterConnectable

* Mutate pubKnownBLEServiceData as runtime var in BTConfig
Mutate pubUnknownBLEServiceData as runtime var in BTConfig
Mutate pubBLEManufacturerData as runtime var in BTConfig
Mutate pubUnknownBLEManufacturerData as runtime var in BTConfig
Mutate pubBLEServiceUUID as runtime var in BTConfig

* Mutate useBeaconUuidForTopic as runtime var in BTConfig
Mutate useBeaconUuidForPresence as runtime var in BTConfig

* Small optimization

* Formatting of config_BT

Co-authored-by: Florian <1technophile@users.noreply.github.com>
This commit is contained in:
BadandFlorian authored and GitHub committed 2022-08-20 14:28:25 -05:00
1 parent 8f9db357e9
commit 9120d06932
4 files changed
+128 -103

No files matched your search

+59 -81
View File
@@ -60,15 +60,16 @@ QueueHandle_t BLEQueue;
using namespace std; using namespace std;
// Global struct to store live BT configuration data
BTConfig_s BTConfig = BTConfig_default;
# define device_flags_init 0 << 0 # define device_flags_init 0 << 0
# define device_flags_isDisc 1 << 0 # define device_flags_isDisc 1 << 0
# define device_flags_isWhiteL 1 << 1 # define device_flags_isWhiteL 1 << 1
# define device_flags_isBlackL 1 << 2 # define device_flags_isBlackL 1 << 2
# define device_flags_connect 1 << 3 # define device_flags_connect 1 << 3
# ifndef MQTTDecodeTopic
TheengsDecoder decoder; TheengsDecoder decoder;
# endif
struct decompose { struct decompose {
int start; int start;
@@ -92,20 +93,14 @@ static BLEdevice NO_DEVICE_FOUND = {{0},
TheengsDecoder::BLE_ID_NUM::UNKNOWN_MODEL}; TheengsDecoder::BLE_ID_NUM::UNKNOWN_MODEL};
static bool oneWhite = false; static bool oneWhite = false;
int minRssi = abs(MinimumRSSI); //minimum rssi value
void pubBTMainCore(JsonObject& data, bool haPresenceEnabled = true) { void pubBTMainCore(JsonObject& data, bool haPresenceEnabled = true) {
if (abs((int)data["rssi"] | 0) < minRssi && data.containsKey("id")) { if (abs((int)data["rssi"] | 0) < BTConfig.minRssi && data.containsKey("id")) {
String topic = data["id"].as<const char*>(); String topic = data["id"].as<const char*>();
topic.replace(":", ""); // Initially publish topic ends with MAC address topic.replace(":", ""); // Initially publish topic ends with MAC address
# if useBeaconUuidForTopic if (BTConfig.pubBeaconUuidForTopic && !BTConfig.extDecoderEnable && data.containsKey("model_id") && data["model_id"].as<String>() == "IBEACON")
if (data.containsKey("model_id") && data["model_id"].as<String>() == "IBEACON")
topic = data["uuid"].as<const char*>(); // If model_id is IBEACON, use uuid as topic topic = data["uuid"].as<const char*>(); // If model_id is IBEACON, use uuid as topic
# endif if (BTConfig.extDecoderEnable && !data.containsKey("model"))
# ifdef MQTTDecodeTopic topic = BTConfig.extDecoderTopic; // If external decoder, use this topic to send data
if (!data.containsKey("model"))
topic = MQTTDecodeTopic; // If external decoder, topic is MQTTDecodeTopic
# endif
topic = subjectBTtoMQTT + String("/") + topic; topic = subjectBTtoMQTT + String("/") + topic;
pub((char*)topic.c_str(), data); pub((char*)topic.c_str(), data);
} }
@@ -114,13 +109,11 @@ void pubBTMainCore(JsonObject& data, bool haPresenceEnabled = true) {
data.remove("servicedatauuid"); data.remove("servicedatauuid");
if (data.containsKey("servicedata")) if (data.containsKey("servicedata"))
data.remove("servicedata"); data.remove("servicedata");
# if useBeaconUuidForPresence if (BTConfig.presenceUseBeaconUuid && data.containsKey("model_id") && data["model_id"].as<String>() == "IBEACON") {
if (data.containsKey("model_id") && data["model_id"].as<String>() == "IBEACON") {
data["mac"] = data["id"]; data["mac"] = data["id"];
data["id"] = data["uuid"]; data["id"] = data["uuid"];
} }
# endif String topic = String(mqtt_topic) + BTConfig.presenceTopic + String(gateway_name);
String topic = String(mqtt_topic) + subjectHomePresence + String(gateway_name);
Log.trace(F("Pub HA Presence %s" CR), topic.c_str()); Log.trace(F("Pub HA Presence %s" CR), topic.c_str());
pub_custom_topic((char*)topic.c_str(), data, false); pub_custom_topic((char*)topic.c_str(), data, false);
} }
@@ -448,12 +441,10 @@ void procBLETask(void* pvParameters) {
Log.notice(F("Device detected: %s" CR), (char*)mac_adress.c_str()); Log.notice(F("Device detected: %s" CR), (char*)mac_adress.c_str());
BLEdevice* device = getDeviceByMac(BLEdata["id"].as<const char*>()); BLEdevice* device = getDeviceByMac(BLEdata["id"].as<const char*>());
# if BLE_FILTER_CONNECTABLE if (BTConfig.filterConnectable && device->connect) {
if (device->connect) {
Log.notice(F("Filtered connectable device" CR)); Log.notice(F("Filtered connectable device" CR));
continue; continue;
} }
# endif
if ((!oneWhite || isWhite(device)) && !isBlack(device)) { //if not black listed MAC we go AND if we have no white MAC or this MAC is white we go out if ((!oneWhite || isWhite(device)) && !isBlack(device)) { //if not black listed MAC we go AND if we have no white MAC or this MAC is white we go out
if (advertisedDevice->haveName()) if (advertisedDevice->haveName())
@@ -467,7 +458,7 @@ void procBLETask(void* pvParameters) {
BLEdata["rssi"] = (int)advertisedDevice->getRSSI(); BLEdata["rssi"] = (int)advertisedDevice->getRSSI();
if (advertisedDevice->haveTXPower()) if (advertisedDevice->haveTXPower())
BLEdata["txpower"] = (int8_t)advertisedDevice->getTXPower(); BLEdata["txpower"] = (int8_t)advertisedDevice->getTXPower();
if (advertisedDevice->haveRSSI() && !publishOnlySensors && hassPresence) { if (advertisedDevice->haveRSSI() && !BTConfig.pubOnlySensors && BTConfig.presenceEnable) {
hass_presence(BLEdata); // this device has an rssi and we don't want only sensors so in consequence we can use it for home assistant room presence component hass_presence(BLEdata); // this device has an rssi and we don't want only sensors so in consequence we can use it for home assistant room presence component
} }
if (advertisedDevice->haveServiceData()) { if (advertisedDevice->haveServiceData()) {
@@ -608,7 +599,7 @@ void coreTask(void* pvParameters) {
if (xSemaphoreTake(semaphoreBLEOperation, pdMS_TO_TICKS(30000)) == pdTRUE) { if (xSemaphoreTake(semaphoreBLEOperation, pdMS_TO_TICKS(30000)) == pdTRUE) {
BLEscan(); BLEscan();
// Launching a connect every BLEscanBeforeConnect // Launching a connect every BLEscanBeforeConnect
if ((!(scanCount % BLEscanBeforeConnect) || scanCount == 1) && bleConnect) if ((!(scanCount % BTConfig.BLEscanBeforeConnect) || scanCount == 1) && BTConfig.bleConnect)
BLEconnect(); BLEconnect();
dumpDevices(); dumpDevices();
xSemaphoreGive(semaphoreBLEOperation); xSemaphoreGive(semaphoreBLEOperation);
@@ -621,7 +612,7 @@ void coreTask(void* pvParameters) {
int scan = atomic_exchange_explicit(&forceBTScan, 0, ::memory_order_seq_cst); // is this enough, it will wait the full deepsleep... int scan = atomic_exchange_explicit(&forceBTScan, 0, ::memory_order_seq_cst); // is this enough, it will wait the full deepsleep...
if (scan == 1) BTforceScan(); if (scan == 1) BTforceScan();
} else { } else {
for (int interval = BLEinterval, waitms; interval > 0; interval -= waitms) { for (int interval = BTConfig.BLEinterval, waitms; interval > 0; interval -= waitms) {
int scan = atomic_exchange_explicit(&forceBTScan, 0, ::memory_order_seq_cst); int scan = atomic_exchange_explicit(&forceBTScan, 0, ::memory_order_seq_cst);
if (scan == 1) BTforceScan(); // should we break after this? if (scan == 1) BTforceScan(); // should we break after this?
delay(waitms = interval > 100 ? 100 : interval); // 100ms delay(waitms = interval > 100 ? 100 : interval); // 100ms
@@ -636,8 +627,8 @@ void coreTask(void* pvParameters) {
void lowPowerESP32() // low power mode void lowPowerESP32() // low power mode
{ {
Log.trace(F("Going to deep sleep for: %l s" CR), (BLEinterval / 1000)); Log.trace(F("Going to deep sleep for: %l s" CR), (BTConfig.BLEinterval / 1000));
deepSleep(BLEinterval * 1000); deepSleep(BTConfig.BLEinterval * 1000);
} }
void deepSleep(uint64_t time_in_us) { void deepSleep(uint64_t time_in_us) {
@@ -681,10 +672,10 @@ void changelowpowermode(int newLowPowerMode) {
} }
void setupBT() { void setupBT() {
Log.notice(F("BLE scans interval: %d" CR), BLEinterval); Log.notice(F("BLE scans interval: %d" CR), BTConfig.BLEinterval);
Log.notice(F("BLE scans number before connect: %d" CR), BLEscanBeforeConnect); Log.notice(F("BLE scans number before connect: %d" CR), BTConfig.BLEscanBeforeConnect);
Log.notice(F("Publishing only BLE sensors: %T" CR), publishOnlySensors); Log.notice(F("Publishing only BLE sensors: %T" CR), BTConfig.pubOnlySensors);
Log.notice(F("minrssi: %d" CR), minRssi); Log.notice(F("minrssi: %d" CR), BTConfig.minRssi);
Log.notice(F("Low Power Mode: %d" CR), lowpowermode); Log.notice(F("Low Power Mode: %d" CR), lowpowermode);
atomic_init(&forceBTScan, 0); // in theory, we don't need this atomic_init(&forceBTScan, 0); // in theory, we don't need this
@@ -742,10 +733,10 @@ unsigned long timebt = 0;
struct decompose d[6] = {{0, 12, true}, {12, 2, false}, {14, 2, false}, {16, 2, false}, {28, 4, true}, {32, 60, false}}; struct decompose d[6] = {{0, 12, true}, {12, 2, false}, {14, 2, false}, {16, 2, false}, {28, 4, true}, {32, 60, false}};
void setupBT() { void setupBT() {
Log.notice(F("BLE interval: %d" CR), BLEinterval); Log.notice(F("BLE interval: %d" CR), BTConfig.BLEinterval);
Log.notice(F("BLE scans number before connect: %d" CR), BLEscanBeforeConnect); Log.notice(F("BLE scans number before connect: %d" CR), BTConfig.BLEscanBeforeConnect);
Log.notice(F("Publishing only BLE sensors: %T" CR), publishOnlySensors); Log.notice(F("Publishing only BLE sensors: %T" CR), BTConfig.pubOnlySensors);
Log.notice(F("minrssi: %d" CR), minRssi); Log.notice(F("minrssi: %d" CR), BTConfig.minRssi);
softserial.begin(HMSerialSpeed); softserial.begin(HMSerialSpeed);
softserial.print(F("AT+ROLE1" CR)); softserial.print(F("AT+ROLE1" CR));
delay(100); delay(100);
@@ -773,7 +764,7 @@ bool BTtoMQTT() {
returnedString += String(a, HEX); returnedString += String(a, HEX);
} }
if (millis() > (timebt + BLEinterval)) { //retrieving data if (millis() > (timebt + BTConfig.BLEinterval)) { //retrieving data
timebt = millis(); timebt = millis();
returnedString.remove(0); //init data string returnedString.remove(0); //init data string
softserial.print(F(QUESTION_MSG)); //start new discovery softserial.print(F(QUESTION_MSG)); //start new discovery
@@ -833,7 +824,7 @@ bool BTtoMQTT() {
return false; //if we have at least one white MAC and this MAC is not white we go out return false; //if we have at least one white MAC and this MAC is not white we go out
BLEdata["rssi"] = (int)rssi; BLEdata["rssi"] = (int)rssi;
if (!publishOnlySensors && hassPresence) if (!BTConfig.pubOnlySensors && BTConfig.presenceEnable)
hass_presence(BLEdata); // this device has an rssi and we don't want only sensors so in consequence we can use it for home assistant room presence component hass_presence(BLEdata); // this device has an rssi and we don't want only sensors so in consequence we can use it for home assistant room presence component
Log.trace(F("Service data: %s" CR), restData.c_str()); Log.trace(F("Service data: %s" CR), restData.c_str());
BLEdata["servicedata"] = restData.c_str(); BLEdata["servicedata"] = restData.c_str();
@@ -887,8 +878,8 @@ void launchBTDiscovery() {
p->sensorModel_id != TheengsDecoder::BLE_ID_NUM::GAEN) { p->sensorModel_id != TheengsDecoder::BLE_ID_NUM::GAEN) {
String macWOdots = String(p->macAdr); String macWOdots = String(p->macAdr);
macWOdots.replace(":", ""); macWOdots.replace(":", "");
# ifndef MQTTDecodeTopic if (!BTConfig.extDecoderEnable && // Do not decode if an external decoter is configured
if (p->sensorModel_id > TheengsDecoder::BLE_ID_NUM::UNKNOWN_MODEL && p->sensorModel_id > TheengsDecoder::BLE_ID_NUM::UNKNOWN_MODEL &&
p->sensorModel_id < TheengsDecoder::BLE_ID_NUM::BLE_ID_MAX && p->sensorModel_id < TheengsDecoder::BLE_ID_NUM::BLE_ID_MAX &&
p->sensorModel_id != TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC) { // Exception on HHCCJCY01HHCC as this one is discoverable and connectable for battery retrieving p->sensorModel_id != TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC) { // Exception on HHCCJCY01HHCC as this one is discoverable and connectable for battery retrieving
Log.trace(F("Looking for Model_id: %d" CR), p->sensorModel_id); Log.trace(F("Looking for Model_id: %d" CR), p->sensorModel_id);
@@ -933,9 +924,7 @@ void launchBTDiscovery() {
} }
} }
} }
} else } else {
# endif
{
if (p->sensorModel_id > BLEconectable::id::MIN && if (p->sensorModel_id > BLEconectable::id::MIN &&
p->sensorModel_id < BLEconectable::id::MAX || p->sensorModel_id < BLEconectable::id::MAX ||
p->sensorModel_id == TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC) { p->sensorModel_id == TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC) {
@@ -968,27 +957,23 @@ void launchBTDiscovery() {
# endif # endif
void PublishDeviceData(JsonObject& BLEdata, bool processBLEData) { void PublishDeviceData(JsonObject& BLEdata, bool processBLEData) {
if (abs((int)BLEdata["rssi"] | 0) < minRssi) { // process only the devices close enough if (abs((int)BLEdata["rssi"] | 0) < BTConfig.minRssi) { // process only the devices close enough
if (processBLEData) process_bledata(BLEdata); if (processBLEData) process_bledata(BLEdata);
if (!publishOnlySensors || BLEdata.containsKey("model") || BLEdata.containsKey("distance")) { if (!BTConfig.pubOnlySensors || BLEdata.containsKey("model") || BLEdata.containsKey("distance")) {
# if !pubBLEServiceUUID if (!BTConfig.pubServiceDataUUID)
RemoveJsonPropertyIf(BLEdata, "servicedatauuid", BLEdata.containsKey("model") && BLEdata.containsKey("servicedatauuid")); RemoveJsonPropertyIf(BLEdata, "servicedatauuid", BLEdata.containsKey("model") && BLEdata.containsKey("servicedatauuid"));
# endif if (!BTConfig.pubKnownServiceData)
# if !pubKnownBLEServiceData
RemoveJsonPropertyIf(BLEdata, "servicedata", BLEdata.containsKey("model") && BLEdata.containsKey("servicedata")); RemoveJsonPropertyIf(BLEdata, "servicedata", BLEdata.containsKey("model") && BLEdata.containsKey("servicedata"));
# endif if (!BTConfig.pubKnownManufData)
# if !pubBLEManufacturerData
RemoveJsonPropertyIf(BLEdata, "manufacturerdata", BLEdata.containsKey("model") && BLEdata.containsKey("manufacturerdata")); RemoveJsonPropertyIf(BLEdata, "manufacturerdata", BLEdata.containsKey("model") && BLEdata.containsKey("manufacturerdata"));
# endif
pubBT(BLEdata); pubBT(BLEdata);
} else { } else {
# if !pubUnknownBLEServiceData if (!BTConfig.pubUnknownServiceData) {
Log.trace(F("Unknown service data, removing it" CR)); Log.trace(F("Unknown service data, removing it" CR));
RemoveJsonPropertyIf(BLEdata, "servicedata", BLEdata.containsKey("servicedata")); RemoveJsonPropertyIf(BLEdata, "servicedata", BLEdata.containsKey("servicedata"));
# endif }
# if !pubUnknownBLEManufacturerData if (!BTConfig.pubUnknownManufData)
RemoveJsonPropertyIf(BLEdata, "manufacturerdata", BLEdata.containsKey("model") && BLEdata.containsKey("manufacturerdata")); RemoveJsonPropertyIf(BLEdata, "manufacturerdata", BLEdata.containsKey("model") && BLEdata.containsKey("manufacturerdata"));
# endif
} }
} else if (BLEdata.containsKey("distance")) { } else if (BLEdata.containsKey("distance")) {
pubBT(BLEdata); pubBT(BLEdata);
@@ -999,10 +984,8 @@ void PublishDeviceData(JsonObject& BLEdata, bool processBLEData) {
void process_bledata(JsonObject& BLEdata) { void process_bledata(JsonObject& BLEdata) {
const char* mac = BLEdata["id"].as<const char*>(); const char* mac = BLEdata["id"].as<const char*>();
int model_id = -1; int model_id = BTConfig.extDecoderEnable ? -1 : decoder.decodeBLEJson(BLEdata);
int mac_type = BLEdata["mac_type"].as<int>(); int mac_type = BLEdata["mac_type"].as<int>();
# ifndef MQTTDecodeTopic
model_id = decoder.decodeBLEJson(BLEdata);
if (model_id >= 0) { // Broadcaster devices if (model_id >= 0) { // Broadcaster devices
Log.trace(F("Decoder found device: %s" CR), BLEdata["model_id"].as<const char*>()); Log.trace(F("Decoder found device: %s" CR), BLEdata["model_id"].as<const char*>());
if (model_id == TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC) { if (model_id == TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC) {
@@ -1010,9 +993,7 @@ void process_bledata(JsonObject& BLEdata) {
} else { } else {
createOrUpdateDevice(mac, device_flags_init, model_id, mac_type); createOrUpdateDevice(mac, device_flags_init, model_id, mac_type);
} }
} else } else {
# endif
{
if (BLEdata.containsKey("name")) { // Connectable devices if (BLEdata.containsKey("name")) { // Connectable devices
std::string name = BLEdata["name"]; std::string name = BLEdata["name"];
if (name.compare("LYWSD03MMC") == 0) if (name.compare("LYWSD03MMC") == 0)
@@ -1028,9 +1009,7 @@ void process_bledata(JsonObject& BLEdata) {
Log.trace(F("Connectable device found: %s" CR), name.c_str()); Log.trace(F("Connectable device found: %s" CR), name.c_str());
createOrUpdateDevice(mac, device_flags_connect, model_id, mac_type); createOrUpdateDevice(mac, device_flags_connect, model_id, mac_type);
} }
} } else if (BTConfig.extDecoderEnable && model_id < 0 && BLEdata.containsKey("servicedata")) {
# ifdef MQTTDecodeTopic
else if (model_id < 0 && BLEdata.containsKey("servicedata")) {
const char* service_data = (const char*)(BLEdata["servicedata"] | ""); const char* service_data = (const char*)(BLEdata["servicedata"] | "");
if (strstr(service_data, "209800") != NULL) { if (strstr(service_data, "209800") != NULL) {
model_id == TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC; model_id == TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC;
@@ -1038,7 +1017,6 @@ void process_bledata(JsonObject& BLEdata) {
createOrUpdateDevice(mac, device_flags_connect, model_id, mac_type); createOrUpdateDevice(mac, device_flags_connect, model_id, mac_type);
} }
} }
# endif
} }
if (model_id < 0) { if (model_id < 0) {
Log.trace(F("No device found " CR)); Log.trace(F("No device found " CR));
@@ -1068,7 +1046,7 @@ void BTforceScan() {
BTtoMQTT(); BTtoMQTT();
Log.trace(F("Scan done" CR)); Log.trace(F("Scan done" CR));
# ifdef ESP32 # ifdef ESP32
if (bleConnect) if (BTConfig.bleConnect)
BLEconnect(); BLEconnect();
# endif # endif
} else { } else {
@@ -1105,7 +1083,7 @@ void immediateBTAction(void* pvParameters) {
std::swap(BLEactions, act_swap); std::swap(BLEactions, act_swap);
// If we stopped the scheduled connect for this action, do the scheduled now // If we stopped the scheduled connect for this action, do the scheduled now
if ((!(scanCount % BLEscanBeforeConnect) || scanCount == 1) && bleConnect) if ((!(scanCount % BTConfig.BLEscanBeforeConnect) || scanCount == 1) && BTConfig.bleConnect)
BLEconnect(); BLEconnect();
xSemaphoreGive(semaphoreBLEOperation); xSemaphoreGive(semaphoreBLEOperation);
} else { } else {
@@ -1234,32 +1212,32 @@ void MQTTtoBT(char* topicOri, JsonObject& BTdata) { // json object decoding
BTforceScan(); BTforceScan();
# endif # endif
} else { } else {
Log.trace(F("Previous interval: %d ms" CR), BLEinterval); Log.trace(F("Previous interval: %d ms" CR), BTConfig.BLEinterval);
BLEinterval = interval; BTConfig.BLEinterval = interval;
Log.notice(F("New interval: %d ms" CR), BLEinterval); Log.notice(F("New interval: %d ms" CR), BTConfig.BLEinterval);
} }
} }
// Number of scan before a connect set // Number of scan before a connect set
if (BTdata.containsKey("scanbcnct")) { if (BTdata.containsKey("scanbcnct")) {
Log.trace(F("BLE scans number before a connect setup" CR)); Log.trace(F("BLE scans number before a connect setup" CR));
Log.trace(F("Previous number: %d" CR), BLEscanBeforeConnect); Log.trace(F("Previous number: %d" CR), BTConfig.BLEscanBeforeConnect);
BLEscanBeforeConnect = (unsigned int)BTdata["scanbcnct"]; BTConfig.BLEscanBeforeConnect = (unsigned int)BTdata["scanbcnct"];
Log.notice(F("New scan number before connect: %d" CR), BLEscanBeforeConnect); Log.notice(F("New scan number before connect: %d" CR), BTConfig.BLEscanBeforeConnect);
} }
// publish all BLE devices discovered or only the identified sensors (like temperature sensors) // publish all BLE devices discovered or only the identified sensors (like temperature sensors)
if (BTdata.containsKey("onlysensors")) { if (BTdata.containsKey("onlysensors")) {
Log.trace(F("Do we publish only sensors" CR)); Log.trace(F("Do we publish only sensors" CR));
Log.trace(F("Previous value: %T" CR), publishOnlySensors); Log.trace(F("Previous value: %T" CR), BTConfig.pubOnlySensors);
publishOnlySensors = (bool)BTdata["onlysensors"]; BTConfig.pubOnlySensors = (bool)BTdata["onlysensors"];
Log.notice(F("New value onlysensors: %T" CR), publishOnlySensors); Log.notice(F("New value onlysensors: %T" CR), BTConfig.pubOnlySensors);
} }
# ifdef ESP32 # ifdef ESP32
// Attempts to connect to elligible devices or not // Attempts to connect to elligible devices or not
if (BTdata.containsKey("bleconnect")) { if (BTdata.containsKey("bleconnect")) {
Log.trace(F("Do we initiate a connection to retrieve data" CR)); Log.trace(F("Do we initiate a connection to retrieve data" CR));
Log.trace(F("Previous value: %T" CR), bleConnect); Log.trace(F("Previous value: %T" CR), BTConfig.bleConnect);
bleConnect = (bool)BTdata["bleconnect"]; BTConfig.bleConnect = (bool)BTdata["bleconnect"];
Log.notice(F("New value bleConnect: %T" CR), bleConnect); Log.notice(F("New value bleConnect: %T" CR), BTConfig.bleConnect);
} }
if (BTdata.containsKey("lowpowermode")) { if (BTdata.containsKey("lowpowermode")) {
changelowpowermode((int)BTdata["lowpowermode"]); changelowpowermode((int)BTdata["lowpowermode"]);
@@ -1270,18 +1248,18 @@ void MQTTtoBT(char* topicOri, JsonObject& BTdata) { // json object decoding
// MinRSSI set // MinRSSI set
if (BTdata.containsKey("minrssi")) { if (BTdata.containsKey("minrssi")) {
// storing Min RSSI for further use if needed // storing Min RSSI for further use if needed
Log.trace(F("Previous minrssi: %d" CR), minRssi); Log.trace(F("Previous minrssi: %d" CR), BTConfig.minRssi);
// set Min RSSI if present if not setting default value // set Min RSSI if present if not setting default value
minRssi = abs((int)BTdata["minrssi"]); BTConfig.minRssi = abs((int)BTdata["minrssi"]);
Log.notice(F("New minrssi: %d" CR), minRssi); Log.notice(F("New minrssi: %d" CR), BTConfig.minRssi);
} }
// Home Assistant presence message // Home Assistant presence message
if (BTdata.containsKey("hasspresence")) { if (BTdata.containsKey("hasspresence")) {
// storing Min RSSI for further use if needed // storing Min RSSI for further use if needed
Log.trace(F("Previous hasspresence: %T" CR), hassPresence); Log.trace(F("Previous hasspresence: %T" CR), BTConfig.presenceEnable);
// set Min RSSI if present if not setting default value // set Min RSSI if present if not setting default value
hassPresence = (bool)BTdata["hasspresence"]; BTConfig.presenceEnable = (bool)BTdata["hasspresence"];
Log.notice(F("New hasspresence: %T" CR), hassPresence); Log.notice(F("New hasspresence: %T" CR), BTConfig.presenceEnable);
} }
} }
} }
+65 -18
View File
@@ -36,24 +36,32 @@ extern void launchBTDiscovery();
extern int btQueueBlocked; extern int btQueueBlocked;
extern int btQueueLengthSum; extern int btQueueLengthSum;
extern int btQueueLengthCount; extern int btQueueLengthCount;
# ifndef AttemptBLECOnnect
# define AttemptBLECOnnect true //do we by default attempt a BLE connection to sensors with ESP32
# endif
bool bleConnect = AttemptBLECOnnect;
// Sets whether to filter publishing of scanned devices that require a connection.
// Setting this to 1 prevents overwriting the publication of the device connection data with the advertised data (Recommended for use with OpenHAB).
# ifndef BLE_FILTER_CONNECTABLE
# define BLE_FILTER_CONNECTABLE 0
# endif
# include "NimBLEDevice.h" # include "NimBLEDevice.h"
#endif #endif
/*----------------------BT topics & parameters-------------------------*/ /*-----------BT TOPICS & COMPILATION PARAMETERS-----------*/
#define subjectBTtoMQTT "/BTtoMQTT" #define subjectBTtoMQTT "/BTtoMQTT"
#define subjectMQTTtoBTset "/commands/MQTTtoBT/config" #define subjectMQTTtoBTset "/commands/MQTTtoBT/config"
// Uncomment to send undecoded device data to another gateway device for decoding // Uncomment to send undecoded device data to another gateway device for decoding
// #define MQTTDecodeTopic "undecoded" // #define MQTTDecodeTopic "undecoded"
#ifndef UseExtDecoder
# ifdef MQTTDecodeTopic
# define UseExtDecoder true
# else
# define UseExtDecoder false
# endif
#endif
#ifndef MQTTDecodeTopic
# define MQTTDecodeTopic "undecoded"
#endif
#ifndef AttemptBLEConnect
# define AttemptBLEConnect true //do we by default attempt a BLE connection to sensors with ESP32
#endif
#ifndef BLE_FILTER_CONNECTABLE
# define BLE_FILTER_CONNECTABLE 0 // Sets whether to filter publishing of scanned devices that require a connection.
#endif // Setting this to 1 prevents overwriting the publication of the device connection data with the advertised data (Recommended for use with OpenHAB).
#define MinimumRSSI -100 //default minimum rssi value, all the devices below -90 will not be reported #define MinimumRSSI -100 //default minimum rssi value, all the devices below -90 will not be reported
@@ -72,15 +80,18 @@ bool bleConnect = AttemptBLECOnnect;
#ifndef ScanBeforeConnect #ifndef ScanBeforeConnect
# define ScanBeforeConnect 10 //define number of scans before connecting to BLE devices (ESP32 only, minimum 1) # define ScanBeforeConnect 10 //define number of scans before connecting to BLE devices (ESP32 only, minimum 1)
#endif #endif
#ifndef BLEScanDuplicateCacheSize #ifndef BLEScanDuplicateCacheSize
# define BLEScanDuplicateCacheSize 200 # define BLEScanDuplicateCacheSize 200
#endif #endif
#ifndef TimeBtwRead #ifndef TimeBtwRead
# define TimeBtwRead 55555 //define default time between 2 scans # define TimeBtwRead 55555 //define default time between 2 scans
#endif #endif
#ifndef PublishOnlySensors #ifndef PublishOnlySensors
# define PublishOnlySensors false //false if we publish all BLE devices discovered or true only the identified sensors (like temperature sensors) # define PublishOnlySensors false //false if we publish all BLE devices discovered or true only the identified sensors (like temperature sensors)
#endif #endif
#ifndef HassPresence #ifndef HassPresence
# define HassPresence false //false if we publish into Home Assistant presence topic # define HassPresence false //false if we publish into Home Assistant presence topic
#endif #endif
@@ -99,13 +110,7 @@ bool bleConnect = AttemptBLECOnnect;
#define CRLR_Length 4 #define CRLR_Length 4
#define BLE_CNCT_TIMEOUT 3000 #define BLE_CNCT_TIMEOUT 3000
#define ServicedataMinLength 27
unsigned int BLEinterval = TimeBtwRead; //time between 2 scans
unsigned int BLEscanBeforeConnect = ScanBeforeConnect; //Number of BLE scans between connection cycles
unsigned long scanCount = 0; unsigned long scanCount = 0;
bool publishOnlySensors = PublishOnlySensors;
bool hassPresence = HassPresence;
#ifndef pubKnownBLEServiceData #ifndef pubKnownBLEServiceData
# define pubKnownBLEServiceData false // define true if you want to publish service data belonging to recognised sensors # define pubKnownBLEServiceData false // define true if you want to publish service data belonging to recognised sensors
@@ -131,13 +136,55 @@ bool hassPresence = HassPresence;
# define useBeaconUuidForTopic false // define true to use iBeacon UUID as topic, instead of sender (random) MAC address # define useBeaconUuidForTopic false // define true to use iBeacon UUID as topic, instead of sender (random) MAC address
#endif #endif
/*-------------------HOME ASSISTANT ROOM PRESENCE ----------------------*/ /*--------------HOME ASSISTANT ROOM PRESENCE--------------*/
#define subjectHomePresence "presence/" // will send Home Assistant room presence message to this topic (first part is same for all rooms, second is room name) #define subjectHomePresence "presence/" // will send Home Assistant room presence message to this topic (first part is same for all rooms, second is room name)
#ifndef useBeaconUuidForPresence #ifndef useBeaconUuidForPresence
# define useBeaconUuidForPresence false // //define true to use iBeacon UUID as for presence, instead of sender MAC (random) address # define useBeaconUuidForPresence false // //define true to use iBeacon UUID as for presence, instead of sender MAC (random) address
#endif #endif
/*----------------CONFIGURABLE PARAMETERS-----------------*/
struct BTConfig_s {
bool bleConnect; // Attempt a BLE connection to sensors with ESP32
unsigned int BLEinterval; // Time between 2 scans
unsigned int BLEscanBeforeConnect; // Number of BLE scans between connection cycles
bool pubOnlySensors; // Publish only the identified sensors (like temperature sensors)
bool presenceEnable; // Publish into Home Assistant presence topic
String presenceTopic; // Home Assistant presence topic to publish on
bool presenceUseBeaconUuid; // Use iBeacon UUID as for presence, instead of sender MAC (random) address
int minRssi; // Minimum rssi value, all the devices below will not be reported
bool extDecoderEnable; // Send undecoded device data to another gateway device for decoding
String extDecoderTopic; // Topic to send undecoded device data on
bool filterConnectable; // Sets whether to filter publishing of scanned devices that require a connection.
bool pubKnownServiceData; // Publish service data belonging to recognised sensors
bool pubUnknownServiceData; // Publish service data belonging to unrecognised sensors (in case you are having too heavy service data) https://github.com/1technophile/OpenMQTTGateway/issues/318#issuecomment-446064707
bool pubKnownManufData; // Publish the manufacturer's data (sometimes contains characters that aren't valid with receiving client)
bool pubUnknownManufData; // Publish the manufacturer's data (sometimes contains characters that aren't valid with receiving client)
bool pubServiceDataUUID; // Publish the service UUID data
bool pubBeaconUuidForTopic; // Use iBeacon UUID as topic, instead of sender (random) MAC address
} BTConfig_default = {
.bleConnect = AttemptBLEConnect,
.BLEinterval = TimeBtwRead,
.BLEscanBeforeConnect = ScanBeforeConnect,
.pubOnlySensors = PublishOnlySensors,
.presenceEnable = HassPresence,
.presenceTopic = subjectHomePresence,
.presenceUseBeaconUuid = useBeaconUuidForPresence,
.minRssi = abs(MinimumRSSI),
.extDecoderEnable = UseExtDecoder,
.extDecoderTopic = MQTTDecodeTopic,
.filterConnectable = BLE_FILTER_CONNECTABLE,
.pubKnownServiceData = pubKnownBLEServiceData,
.pubUnknownServiceData = pubUnknownBLEServiceData,
.pubKnownManufData = pubBLEManufacturerData,
.pubUnknownManufData = pubUnknownBLEManufacturerData,
.pubServiceDataUUID = pubBLEServiceUUID,
.pubBeaconUuidForTopic = useBeaconUuidForTopic,
};
// Global struct to store live BT configuration data
extern BTConfig_s BTConfig;
/*-------------------PIN DEFINITIONS----------------------*/ /*-------------------PIN DEFINITIONS----------------------*/
#if !defined(BT_RX) || !defined(BT_TX) #if !defined(BT_RX) || !defined(BT_TX)
# ifdef ESP8266 # ifdef ESP8266
+2 -2
View File
@@ -1575,8 +1575,8 @@ void stateMeasures() {
SYSdata["btqsnd"] = btQueueLengthCount; SYSdata["btqsnd"] = btQueueLengthCount;
SYSdata["btqavg"] = (btQueueLengthCount > 0 ? btQueueLengthSum / (float)btQueueLengthCount : 0); SYSdata["btqavg"] = (btQueueLengthCount > 0 ? btQueueLengthSum / (float)btQueueLengthCount : 0);
# endif # endif
SYSdata["interval"] = BLEinterval; SYSdata["interval"] = BTConfig.BLEinterval;
SYSdata["scanbcnct"] = BLEscanBeforeConnect; SYSdata["scanbcnct"] = BTConfig.BLEscanBeforeConnect;
SYSdata["scnct"] = scanCount; SYSdata["scnct"] = scanCount;
# endif # endif
# ifdef ZboardM5STACK # ifdef ZboardM5STACK
+2 -2
View File
@@ -482,7 +482,7 @@ build_flags =
'-DGateway_Name="OpenMQTTGateway_ESP32_BLE_C"' '-DGateway_Name="OpenMQTTGateway_ESP32_BLE_C"'
'-DTimeBtwRead=0' '-DTimeBtwRead=0'
'-DScan_duration=1000' '-DScan_duration=1000'
'-DAttemptBLECOnnect=false' '-DAttemptBLEConnect=false'
[env:esp32feather-ble] [env:esp32feather-ble]
platform = ${com.esp32_platform} platform = ${com.esp32_platform}
@@ -519,7 +519,7 @@ build_flags =
; '-DDEFAULT_LOW_POWER_MODE=2' ; '-DDEFAULT_LOW_POWER_MODE=2'
; '-DTimeBtwRead=155000' ; '-DTimeBtwRead=155000'
; '-DScan_duration=2000' ; '-DScan_duration=2000'
; '-DAttemptBLECOnnect=false' ; '-DAttemptBLEConnect=false'
; '-DActiveBLEScan=false' ; '-DActiveBLEScan=false'
; '-DESPWifiManualSetup=true' ; '-DESPWifiManualSetup=true'
; '-DMQTT_USER="lolin-esp32"' ; '-DMQTT_USER="lolin-esp32"'