[SYS] Add Blufi support (#1913)

* First build with IDF, tested with esp32dev-ble only.

* Fix frameworks for non-esp32 boards

* Add blufi support.

* Adds an environment to use esp-idf and Arduino as a component to facilitate incorporating blufi for onboarding and configuration.

---------

Co-authored-by: h2zero <powellperalata@gmail.com>
This commit is contained in:
h2zeroandh2zero authored and GitHub committed 2024-03-15 07:53:13 -05:00
1 parent e55431ad94
commit ffe88feddc
14 files changed
+760 -9

No files matched your search

+265
View File
@@ -0,0 +1,265 @@
/*
OpenMQTTGateway - ESP8266 or Arduino program for home automation
Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker
Send and receiving command by MQTT
This program enables to:
- receive MQTT data from a topic and send signal (RF, IR, BLE, GSM) corresponding to the received MQTT data
- publish MQTT data to a different topic related to received signals (RF, IR, BLE, GSM)
Copyright: (c)Florian ROBERT
This file is part of OpenMQTTGateway.
OpenMQTTGateway is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenMQTTGateway is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ESP32) && defined(USE_BLUFI)
# include "esp_blufi_api.h"
extern "C" {
# include "esp_blufi.h"
}
/* store the station info for send back to phone */
//static bool gl_sta_connected = false;
bool omg_blufi_ble_connected = false;
static uint8_t gl_sta_bssid[6];
static uint8_t gl_sta_ssid[32];
static uint8_t gl_sta_passwd[64];
static int gl_sta_ssid_len;
static bool gl_sta_is_connecting = false;
static esp_blufi_extra_info_t gl_sta_conn_info;
static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t* param);
void wifi_event_handler(arduino_event_id_t event);
esp_err_t blufi_security_init(void);
void blufi_dh_negotiate_data_handler(uint8_t* data, int len, uint8_t** output_data, int* output_len, bool* need_free);
int blufi_aes_encrypt(uint8_t iv8, uint8_t* crypt_data, int crypt_len);
int blufi_aes_decrypt(uint8_t iv8, uint8_t* crypt_data, int crypt_len);
uint16_t blufi_crc_checksum(uint8_t iv8, uint8_t* data, int len);
void blufi_security_deinit(void);
static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t* param) {
/* actually, should post to blufi_task handle the procedure,
* now, as a example, we do it more simply */
switch (event) {
case ESP_BLUFI_EVENT_INIT_FINISH:
Log.notice(F("BLUFI init finish" CR));
esp_blufi_adv_start();
break;
case ESP_BLUFI_EVENT_DEINIT_FINISH:
Log.notice(F("BLUFI deinit finish" CR));
NimBLEDevice::deinit(true);
break;
case ESP_BLUFI_EVENT_BLE_CONNECT:
omg_blufi_ble_connected = true;
esp_blufi_adv_stop();
blufi_security_init();
break;
case ESP_BLUFI_EVENT_BLE_DISCONNECT:
omg_blufi_ble_connected = false;
blufi_security_deinit();
if (WiFi.isConnected()) {
esp_blufi_deinit();
} else {
esp_blufi_adv_start();
}
break;
case ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP:
Log.notice(F("BLUFI requset wifi connect to AP" CR));
WiFi.begin((char*)gl_sta_ssid, (char*)gl_sta_passwd);
gl_sta_is_connecting = true;
break;
case ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP:
Log.notice(F("BLUFI requset wifi disconnect from AP\n" CR));
WiFi.disconnect();
break;
case ESP_BLUFI_EVENT_REPORT_ERROR:
Log.notice(F("BLUFI report error, error code %d\n" CR), param->report_error.state);
esp_blufi_send_error_info(param->report_error.state);
break;
case ESP_BLUFI_EVENT_GET_WIFI_STATUS: {
esp_blufi_extra_info_t info;
if (WiFi.isConnected()) {
memset(&info, 0, sizeof(esp_blufi_extra_info_t));
memcpy(info.sta_bssid, gl_sta_bssid, 6);
info.sta_bssid_set = true;
info.sta_ssid = gl_sta_ssid;
info.sta_ssid_len = gl_sta_ssid_len;
esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_SUCCESS, 0, &info);
} else if (gl_sta_is_connecting) {
esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONNECTING, 0, &gl_sta_conn_info);
} else {
esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_FAIL, 0, &gl_sta_conn_info);
}
break;
}
case ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE:
esp_blufi_disconnect();
break;
case ESP_BLUFI_EVENT_RECV_STA_SSID:
strncpy((char*)gl_sta_ssid, (char*)param->sta_ssid.ssid, param->sta_ssid.ssid_len);
gl_sta_ssid[param->sta_ssid.ssid_len] = '\0';
Log.notice(F("Recv STA SSID %s" CR), gl_sta_ssid);
break;
case ESP_BLUFI_EVENT_RECV_STA_PASSWD:
strncpy((char*)gl_sta_passwd, (char*)param->sta_passwd.passwd, param->sta_passwd.passwd_len);
gl_sta_passwd[param->sta_passwd.passwd_len] = '\0';
Log.notice(F("Recv STA PASSWORD %s" CR), gl_sta_passwd);
break;
case ESP_BLUFI_EVENT_GET_WIFI_LIST: {
WiFi.scanNetworks(true);
break;
}
case ESP_BLUFI_EVENT_RECV_CUSTOM_DATA: {
Log.notice(F("Recv Custom Data %" PRIu32 CR), param->custom_data.data_len);
esp_log_buffer_hex("Custom Data", param->custom_data.data, param->custom_data.data_len);
DynamicJsonDocument json(1024);
auto error = deserializeJson(json, param->custom_data.data);
if (error) {
Log.error(F("deserialize config failed: %s, buffer capacity: %u" CR), error.c_str(), json.capacity());
break;
}
if (!json.isNull()) {
Log.trace(F("\nparsed json, size: %u" CR), json.memoryUsage());
if (json.containsKey("mqtt_server"))
strcpy(mqtt_server, json["mqtt_server"]);
if (json.containsKey("mqtt_port"))
strcpy(mqtt_port, json["mqtt_port"]);
if (json.containsKey("mqtt_user"))
strcpy(mqtt_user, json["mqtt_user"]);
if (json.containsKey("mqtt_pass"))
strcpy(mqtt_pass, json["mqtt_pass"]);
if (json.containsKey("mqtt_topic"))
strcpy(mqtt_topic, json["mqtt_topic"]);
if (json.containsKey("mqtt_broker_secure"))
mqtt_secure = json["mqtt_broker_secure"].as<bool>();
if (json.containsKey("gateway_name"))
strcpy(gateway_name, json["gateway_name"]);
saveConfig();
}
break;
}
case ESP_BLUFI_EVENT_RECV_USERNAME:
break;
case ESP_BLUFI_EVENT_RECV_CA_CERT:
break;
case ESP_BLUFI_EVENT_RECV_CLIENT_CERT:
break;
case ESP_BLUFI_EVENT_RECV_SERVER_CERT:
break;
case ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY:
break;
;
case ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY:
break;
default:
break;
}
}
void wifi_event_handler(arduino_event_id_t event) {
switch (event) {
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
case ARDUINO_EVENT_WIFI_STA_GOT_IP: {
gl_sta_is_connecting = false;
esp_blufi_extra_info_t info;
memset(&info, 0, sizeof(esp_blufi_extra_info_t));
memcpy(info.sta_bssid, gl_sta_bssid, 6);
info.sta_bssid_set = true;
info.sta_ssid = gl_sta_ssid;
info.sta_ssid_len = gl_sta_ssid_len;
if (omg_blufi_ble_connected == true) {
esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_SUCCESS, 0, &info);
}
break;
}
case ARDUINO_EVENT_WIFI_SCAN_DONE: {
uint16_t apCount = WiFi.scanComplete();
if (apCount == 0) {
Log.notice(F("No AP found" CR));
break;
}
wifi_ap_record_t* ap_list = (wifi_ap_record_t*)malloc(sizeof(wifi_ap_record_t) * apCount);
if (!ap_list) {
Log.error(F("malloc error, ap_list is NULL"));
break;
}
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&apCount, ap_list));
esp_blufi_ap_record_t* blufi_ap_list = (esp_blufi_ap_record_t*)malloc(apCount * sizeof(esp_blufi_ap_record_t));
if (!blufi_ap_list) {
if (ap_list) {
free(ap_list);
}
Log.error(F("malloc error, blufi_ap_list is NULL" CR));
break;
}
for (int i = 0; i < apCount; ++i) {
blufi_ap_list[i].rssi = ap_list[i].rssi;
memcpy(blufi_ap_list[i].ssid, ap_list[i].ssid, sizeof(ap_list[i].ssid));
}
if (omg_blufi_ble_connected == true) {
esp_blufi_send_wifi_list(apCount, blufi_ap_list);
}
free(ap_list);
free(blufi_ap_list);
break;
}
default:
break;
}
return;
}
static esp_blufi_callbacks_t example_callbacks = {
.event_cb = example_event_callback,
.negotiate_data_handler = blufi_dh_negotiate_data_handler,
.encrypt_func = blufi_aes_encrypt,
.decrypt_func = blufi_aes_decrypt,
.checksum_func = blufi_crc_checksum,
};
bool startBlufi() {
esp_err_t ret = ESP_OK;
WiFi.onEvent(wifi_event_handler);
ret = esp_blufi_register_callbacks(&example_callbacks);
if (ret) {
Log.error(F("%s blufi register failed, error code = %x" CR), __func__, ret);
return false;
}
if (NimBLEDevice::getInitialized()) {
NimBLEDevice::deinit(true);
delay(50);
}
esp_blufi_btc_init();
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_WIFI_STA);
char advName[20] = {0};
snprintf(advName, sizeof(advName), "OMGBFI_%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
NimBLEDevice::init(advName);
esp_blufi_gatt_svr_init();
ble_gatts_start();
return esp_blufi_profile_init() == ESP_OK;
}
#endif // defined(ESP32) && defined(USE_BLUFI)
+197
View File
@@ -0,0 +1,197 @@
/*
* SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#if defined(ESP32) && defined(USE_BLUFI)
# include "esp_blufi_api.h"
# include "esp_crc.h"
# include "mbedtls/aes.h"
# include "mbedtls/dhm.h"
# include "mbedtls/md5.h"
/*
The SEC_TYPE_xxx is for self-defined packet data type in the procedure of "BLUFI negotiate key"
If user use other negotiation procedure to exchange(or generate) key, should redefine the type by yourself.
*/
# define SEC_TYPE_DH_PARAM_LEN 0x00
# define SEC_TYPE_DH_PARAM_DATA 0x01
# define SEC_TYPE_DH_P 0x02
# define SEC_TYPE_DH_G 0x03
# define SEC_TYPE_DH_PUBLIC 0x04
struct blufi_security {
# define DH_SELF_PUB_KEY_LEN 128
# define DH_SELF_PUB_KEY_BIT_LEN (DH_SELF_PUB_KEY_LEN * 8)
uint8_t self_public_key[DH_SELF_PUB_KEY_LEN];
# define SHARE_KEY_LEN 128
# define SHARE_KEY_BIT_LEN (SHARE_KEY_LEN * 8)
uint8_t share_key[SHARE_KEY_LEN];
size_t share_len;
# define PSK_LEN 16
uint8_t psk[PSK_LEN];
uint8_t* dh_param;
int dh_param_len;
uint8_t iv[16];
mbedtls_dhm_context dhm;
mbedtls_aes_context aes;
};
static struct blufi_security* blufi_sec;
static int myrand(void* rng_state, unsigned char* output, size_t len) {
esp_fill_random(output, len);
return (0);
}
extern "C" void btc_blufi_report_error(esp_blufi_error_state_t state);
void blufi_dh_negotiate_data_handler(uint8_t* data, int len, uint8_t** output_data, int* output_len, bool* need_free) {
int ret;
uint8_t type = data[0];
if (blufi_sec == NULL) {
Log.error(F("BLUFI Security is not initialized" CR));
btc_blufi_report_error(ESP_BLUFI_INIT_SECURITY_ERROR);
return;
}
switch (type) {
case SEC_TYPE_DH_PARAM_LEN:
blufi_sec->dh_param_len = ((data[1] << 8) | data[2]);
if (blufi_sec->dh_param) {
free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
}
blufi_sec->dh_param = (uint8_t*)malloc(blufi_sec->dh_param_len);
if (blufi_sec->dh_param == NULL) {
btc_blufi_report_error(ESP_BLUFI_DH_MALLOC_ERROR);
Log.error(F("%s, malloc failed\n" CR), __func__);
return;
}
break;
case SEC_TYPE_DH_PARAM_DATA: {
if (blufi_sec->dh_param == NULL) {
Log.error(F("%s, blufi_sec->dh_param == NULL" CR), __func__);
btc_blufi_report_error(ESP_BLUFI_DH_PARAM_ERROR);
return;
}
uint8_t* param = blufi_sec->dh_param;
memcpy(blufi_sec->dh_param, &data[1], blufi_sec->dh_param_len);
ret = mbedtls_dhm_read_params(&blufi_sec->dhm, &param, &param[blufi_sec->dh_param_len]);
if (ret) {
Log.error(F("%s read param failed %d" CR), __func__, ret);
btc_blufi_report_error(ESP_BLUFI_READ_PARAM_ERROR);
return;
}
free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
ret = mbedtls_dhm_make_public(&blufi_sec->dhm, (int)mbedtls_mpi_size(&blufi_sec->dhm.P), blufi_sec->self_public_key, blufi_sec->dhm.len, myrand, NULL);
if (ret) {
Log.error(F("%s make public failed %d" CR), __func__, ret);
btc_blufi_report_error(ESP_BLUFI_MAKE_PUBLIC_ERROR);
return;
}
ret = mbedtls_dhm_calc_secret(&blufi_sec->dhm,
blufi_sec->share_key,
SHARE_KEY_BIT_LEN,
&blufi_sec->share_len,
myrand, NULL);
if (ret) {
Log.error(F("%s mbedtls_dhm_calc_secret failed %d" CR), __func__, ret);
btc_blufi_report_error(ESP_BLUFI_DH_PARAM_ERROR);
return;
}
mbedtls_md5(blufi_sec->share_key, blufi_sec->share_len, blufi_sec->psk);
mbedtls_aes_setkey_enc(&blufi_sec->aes, blufi_sec->psk, 128);
/* alloc output data */
*output_data = &blufi_sec->self_public_key[0];
*output_len = blufi_sec->dhm.len;
*need_free = false;
} break;
case SEC_TYPE_DH_P:
break;
case SEC_TYPE_DH_G:
break;
case SEC_TYPE_DH_PUBLIC:
break;
}
}
int blufi_aes_encrypt(uint8_t iv8, uint8_t* crypt_data, int crypt_len) {
int ret;
size_t iv_offset = 0;
uint8_t iv0[16];
memcpy(iv0, blufi_sec->iv, sizeof(blufi_sec->iv));
iv0[0] = iv8; /* set iv8 as the iv0[0] */
ret = mbedtls_aes_crypt_cfb128(&blufi_sec->aes, MBEDTLS_AES_ENCRYPT, crypt_len, &iv_offset, iv0, crypt_data, crypt_data);
if (ret) {
return -1;
}
return crypt_len;
}
int blufi_aes_decrypt(uint8_t iv8, uint8_t* crypt_data, int crypt_len) {
int ret;
size_t iv_offset = 0;
uint8_t iv0[16];
memcpy(iv0, blufi_sec->iv, sizeof(blufi_sec->iv));
iv0[0] = iv8; /* set iv8 as the iv0[0] */
ret = mbedtls_aes_crypt_cfb128(&blufi_sec->aes, MBEDTLS_AES_DECRYPT, crypt_len, &iv_offset, iv0, crypt_data, crypt_data);
if (ret) {
return -1;
}
return crypt_len;
}
uint16_t blufi_crc_checksum(uint8_t iv8, uint8_t* data, int len) {
/* This iv8 ignore, not used */
return esp_crc16_be(0, data, len);
}
esp_err_t blufi_security_init(void) {
blufi_sec = (struct blufi_security*)malloc(sizeof(struct blufi_security));
if (blufi_sec == NULL) {
return ESP_FAIL;
}
memset(blufi_sec, 0x0, sizeof(struct blufi_security));
mbedtls_dhm_init(&blufi_sec->dhm);
mbedtls_aes_init(&blufi_sec->aes);
memset(blufi_sec->iv, 0x0, 16);
return 0;
}
void blufi_security_deinit(void) {
if (blufi_sec == NULL) {
return;
}
if (blufi_sec->dh_param) {
free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
}
mbedtls_dhm_free(&blufi_sec->dhm);
mbedtls_aes_free(&blufi_sec->aes);
memset(blufi_sec, 0x0, sizeof(struct blufi_security));
free(blufi_sec);
blufi_sec = NULL;
}
#endif // defined(ESP32) && defined(USE_BLUFI)
+4 -1
View File
@@ -43,7 +43,6 @@ QueueHandle_t BLEQueue;
# include <decoder.h>
# include <driver/adc.h>
# include <esp_bt.h>
# include <esp_bt_main.h>
# include <esp_wifi.h>
# include <atomic>
@@ -892,7 +891,11 @@ void setupBTTasksAndBLE() {
xTaskCreatePinnedToCore(
procBLETask, /* Function to implement the task */
"procBLETask", /* Name of the task */
# ifdef USE_BLUFI
13000,
# else
8500, /* Stack size in bytes */
# endif
NULL, /* Task input parameter */
2, /* Priority of the task (set higher than core task) */
&xProcBLETaskHandle, /* Task handle. */
+1 -1
View File
@@ -76,7 +76,7 @@ void MeasureGPIOInput() {
}
# endif
Log.notice(F("Erasing ESP Config, restarting" CR));
setup_wifimanager(true);
setupwifi(true);
}
} else {
resetTime = 0;
+20 -6
View File
@@ -1133,14 +1133,14 @@ void setup() {
# ifdef ESP32_ETHERNET
setup_ethernet_esp32();
# endif
if (!failSafeMode && !ethConnected) setup_wifimanager(false);
if (!failSafeMode && !ethConnected) setupwifi(false);
} else {
# ifdef ESP32_ETHERNET
setup_ethernet_esp32();
# endif
Log.notice(F("No config in flash, launching wifi manager" CR));
// In failSafeMode we don't want to setup wifi manager as it has already been done before
if (!failSafeMode) setup_wifimanager(false);
if (!failSafeMode) setupwifi(false);
}
# endif
@@ -1362,6 +1362,13 @@ void setup() {
#if defined(ESP8266) || defined(ESP32)
// Bypass for ESP not reconnecting automaticaly the second time https://github.com/espressif/arduino-esp32/issues/2501
bool wifi_reconnect_bypass() {
# if defined(ESP32) && defined(USE_BLUFI)
extern bool omg_blufi_ble_connected;
if (omg_blufi_ble_connected) {
Log.notice(F("BLUFI is connected, bypassing wifi reconnect" CR));
return true;
}
# endif
uint8_t wifi_autoreconnect_cnt = 0;
# ifdef ESP32
while (WiFi.status() != WL_CONNECTED && wifi_autoreconnect_cnt < maxConnectionRetryNetwork) {
@@ -1628,7 +1635,7 @@ void blockingWaitForReset() {
Log.trace(F("mounted file system" CR));
if (SPIFFS.exists("/config.json")) {
Log.notice(F("Erasing ESP Config, restarting" CR));
setup_wifimanager(true);
setupwifi(true);
}
}
delay(30000);
@@ -1636,7 +1643,7 @@ void blockingWaitForReset() {
Log.notice(F("Going into failsafe mode without peripherals" CR));
// Failsafe mode enable to connect to Wifi or change the firmware without the peripherals setup
failSafeMode = true;
setup_wifimanager(false);
setupwifi(false);
}
}
}
@@ -1766,13 +1773,20 @@ bool loadConfigFromFlash() {
return result;
}
void setup_wifimanager(bool reset_settings) {
void setupwifi(bool reset_settings) {
delay(10);
WiFi.mode(WIFI_STA);
if (reset_settings)
eraseAndRestart();
# if defined(ESP32) && defined(USE_BLUFI)
if (!wifi_reconnect_bypass()) {
startBlufi();
return;
}
# endif
# ifdef USE_MAC_AS_GATEWAY_NAME
String s = WiFi.macAddress();
snprintf(WifiManager_ssid, MAC_NAME_MAX_LEN, "%s_%.2s%.2s", Gateway_Short_Name, s.c_str(), s.c_str() + 3);
@@ -2881,7 +2895,7 @@ void MQTTtoSYS(char* topicOri, JsonObject& SYSdata) { // json object decoding
ESPRestart(5);
} else if (strstr(cmd, eraseCmd) != NULL) { //erase and restart
# ifndef ESPWifiManualSetup
setup_wifimanager(true);
setupwifi(true);
# endif
} else if (strstr(cmd, statusCmd) != NULL) { //erase and restart
stateMeasures();