[BT] Add BM2 voltage (#1495)

* [BT] Add BM2 voltage

Voltage retrieval through a BLE connection, frequency of the BLE connection is defined by `intervalcnct`

* Add doc

Credits to https://github.com/KrystianD/bm2-battery-monitor
This commit is contained in:
Florian authored and GitHub committed 2023-03-02 11:02:03 -06:00
1 parent 1cdf6558a9
commit f35baa9da0
5 files changed
+112 -5

No files matched your search

+75 -1
View File
@@ -4,7 +4,6 @@
# include "ArduinoJson.h"
# include "ArduinoLog.h"
# include "ZgatewayBLEConnect.h"
# define convertTemp_CtoF(c) ((c * 1.8) + 32)
extern bool ProcessLock;
@@ -255,6 +254,81 @@ void DT24_connect::publishData() {
}
}
/*-----------------------BM2 HANDLING-----------------------*/
void BM2_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) {
if (m_taskHandle == nullptr) {
return; // unexpected notification
}
if (!ProcessLock) {
Log.trace(F("Callback from %s characteristic" CR), pChar->getUUID().toString().c_str());
if (length == 16) {
Log.trace(F("Device identified creating BLE buffer" CR));
JsonObject& BLEdata = getBTJsonObject();
String mac_address = m_pClient->getPeerAddress().toString().c_str();
mac_address.toUpperCase();
BLEdata["model"] = "BM2 Battery Monitor";
BLEdata["id"] = (char*)mac_address.c_str();
mbedtls_aes_context aes;
mbedtls_aes_init(&aes);
unsigned char output[16];
unsigned char iv[16] = {};
unsigned char key[16] = {
108,
101,
97,
103,
101,
110,
100,
255,
254,
49,
56,
56,
50,
52,
54,
54,
};
mbedtls_aes_setkey_dec(&aes, key, 128);
mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, 16, iv, (uint8_t*)&pData[0], output);
mbedtls_aes_free(&aes);
float volt = ((output[2] | (output[1] << 8)) >> 4) / 100.0f;
BLEdata["volt"] = volt;
Log.trace(F("volt: %F" CR), volt);
pubBT(BLEdata);
} else {
Log.notice(F("Invalid notification data" CR));
return;
}
} else {
Log.trace(F("Callback process canceled by processLock" CR));
}
xTaskNotifyGive(m_taskHandle);
}
void BM2_connect::publishData() {
NimBLEUUID serviceUUID("fff0");
NimBLEUUID charUUID("fff4");
NimBLERemoteCharacteristic* pChar = getCharacteristic(serviceUUID, charUUID);
if (pChar && pChar->canNotify()) {
Log.trace(F("Registering notification" CR));
if (pChar->subscribe(true, std::bind(&BM2_connect::notifyCB, this,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4))) {
m_taskHandle = xTaskGetCurrentTaskHandle();
if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(BLE_CNCT_TIMEOUT)) == pdFALSE) {
m_taskHandle = nullptr;
}
} else {
Log.notice(F("Failed registering notification" CR));
}
}
}
/*-----------------------HHCCJCY01HHCC HANDLING-----------------------*/
void HHCCJCY01HHCC_connect::publishData() {
NimBLEUUID serviceUUID("00001204-0000-1000-8000-00805f9b34fb");