espressif / arduino-esp32

Arduino core for the ESP32
GNU Lesser General Public License v2.1
13.41k stars 7.37k forks source link

ESP32 halts when repeatedly invoking ble.begin() & ble.end() #1711

Closed muojp closed 4 years ago

muojp commented 6 years ago

Hardware:

Board: DOIT-ESP32-DevBoard Core Installation/update date: 31/jul/2018 IDE name: Arduino IDE 1.8.5 Flash Frequency: 80Mhz Upload Speed: 115200

Description:

I tested SimpleBLE library and found it freezes ESP32 board if you periodically call begin() and end(). On my board, ESP32 halts or reboots at 33rd time of calling begin().

Here are some detail:

Sketch:

#include "SimpleBLE.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

SimpleBLE ble;

void setup() {
    Serial.begin(115200);
    Serial.setDebugOutput(true);
}

void loop() {
  for (int i = 0; i < 64; i++) {
    ble.begin("My BLE node");
    Serial.println(String(i));
    delay(500);
    ble.end();
  }
}

Debug Messages:

ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:952
load:0x40078000,len:6084
load:0x40080000,len:7936
entry 0x40080310
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
abort() was called at PC 0x4008a255 on core 0

Backtrace: 0x40090c38:0x3ffdaaf0 0x40090e3b:0x3ffdab10 0x4008a255:0x3ffdab30 0x4008a280:0x3ffdab50 0x4008a3d1:0x3ffdab80 0x4014de6f:0x3ffdaba0 0x40147771:0x3ffdae60 0x401400c1:0x3ffdaeb0 0x40116b73:0x3ffdaee0 0x40111d3a:0x3ffdaf00 0x4012db6e:0x3ffdaf20 0x4010a8b1:0x3ffdaf40 0x40111b36:0x3ffdaf60 0x400ecfe6:0x3ffdaf80

Rebooting...
muojp commented 6 years ago

Workaround: perform make menuconfig and disable dynamic memory allocation for BT/BLE

image

KorochanOne commented 6 years ago

I got the same problem with SerialBT. (SerialBT.begin()/SerialBT.end()) I 'd like to try your workaround but I don't know how to use make menuconfig for ESP32-Arduino. Is there good manual for how to change menucinfig for ESP32-Arduino.

abort() was called at PC 0x4008a255 on core 0

Backtrace: 0x40090c38:0x3ffdba20 0x40090e3b:0x3ffdba40 0x4008a255:0x3ffdba60 0x4008a280:0x3ffdba80 0x4008a3d1:0x3ffdbab0 0x4014e3d7:0x3ffdbad0 0x40147cd5:0x3ffdbd90 0x40140625:0x3ffdbde0 0x400d72ab:0x3ffdbe10 0x400efb3d:0x3ffdbe30 0x400e6ff1:0x3ffdbe50 0x4012b9b3:0x3ffdbe70 0x40114291:0x3ffdbee0 0x40114211:0x3ffdbf00 0x4011436e:0x3ffdbf20 0x400efa96:0x3ffdbf40

Rebooting... ets Jun 8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:952 load:0x40078000,len:6084 load:0x40080000,len:7936 entry 0x40080310 HIT ANY KEY......................

itofficeeu commented 5 years ago

Hardware:

Board: Heltec WiFi LoRa 32 Chip: ESP32D0WDQ6 (revision (unknown 0xa)) IDE name: Arduino IDE 1.8.5

Description:

I can confirm to be able to reproduce this issue with the sketch from @muojp. I am using a Heltec WiFi LoRa 32 with a ESP32 on board. The ESP32 either hangs after 30 times, or crashes and restarts.

I'm not using any OS - and hence do not know how to disable dynamic memory allocation as "muojp".

I am experiencing similar issues in another program using BLEDevice.h - like in this series of includes:

#include <CayenneLPP.h>
#include <lmic.h>
#include <hal/hal.h>
#include <Wire.h>
#include <SPI.h>
#include <SSD1306.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include "BLEDevice.h"

Here the Bluetooth client hangs 42 loops after the Bluetooth server is turned of. Between those two events, is the client scanning for devices 42 times - and during scanning, all the time not finding any. If it finds some random Bluetooth units in between, it seems to keep the program running. I will do further studies on my setup regarding the seemingly positive influence of other Bluetooth devices around.

The following are data printed in the terminal. The value, "88.99" is the value gathered by the client (the unit that hangs) from the Bluetooth server, which is another ESP32 "barebone" (ESP-WROOM-32).

After the first semicolon - in each row - the program in the client gets the value from the server, if they are connected. If they aren't connected, the clients starts a scan for 2 seconds. The clients presents whatever it finds in these 2 seconds, prints a second semicolon and the program continues with the next loop. So all the double semicolons are scans without any connections established and no data - or any other device found. The text "Now disconnected from BLE unit." comes just after the connection the Bluetooth server is lost. The final row only has one semicolon - and it is here where the ESP32 hangs in a scan - maybe before or after the real scan.

   ...
;88.99;
;88.99;
;88.99;
;88.99;
;;
Now disconnected from BLE unit.
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;

The scan is in my case started with

  if (connected)
  {
    std::string remoteValue = pRemoteCharacteristic->readValue();
    Serial.print( String(remoteValue.c_str()) );
  }
  else if(doScan) 
  {
    BLEDevice::getScan()->start(2);
  }

Every loop is terminated with a delay(9000);.

The software in the Bluetooth server is a copy from: https://github.com/nkolban/ESP32_BLE_Arduino/blob/master/examples/BLE_server/BLE_server.ino

The client is (modified slightly) based on this: https://github.com/nkolban/ESP32_BLE_Arduino/blob/master/examples/BLE_client/BLE_client.ino

I will check if my modifications have had influence, but doubt it, as the problem seems to exist outside my code too. - Otherwise would this thread not exist.

Just mentioned now; There are also a issue with Bluetooth when the client starts up. But that is for another thread.

A part of the source for compiling is:

/home/xox/arduino-1.8.5/arduino-builder -dump-prefs -logger=machine -hardware /home/xox/arduino-1.8.5/hardware -hardware /home/xox/.arduino15/packages -hardware /home/xox/Arduino/hardware -tools /home/xox/arduino-1.8.5/tools-builder -tools /home/xox/arduino-1.8.5/hardware/tools/avr -tools /home/xox/.arduino15/packages -built-in-libraries /home/xox/arduino-1.8.5/libraries -libraries /home/xox/Arduino/libraries -fqbn=heltec:esp32:wifi_lora_32:FlashFreq=80,UploadSpeed=921600 -ide-version=10805 -build-path /tmp/arduino_build_171071 -warnings=none -build-cache /tmp/arduino_cache_306563 -prefs=build.warn_data_percentage=75 -verbose /home/xox/Desktop/electronics_generel/lora/lora_hub/hub_w_2019.01.07-1920/hub_w_2019.01.07-1920.ino
/home/xox/arduino-1.8.5/arduino-builder -compile -logger=machine -hardware /home/xox/arduino-1.8.5/hardware -hardware /home/xox/.arduino15/packages -hardware /home/xox/Arduino/hardware -tools /home/xox/arduino-1.8.5/tools-builder -tools /home/xox/arduino-1.8.5/hardware/tools/avr -tools /home/xox/.arduino15/packages -built-in-libraries /home/xox/arduino-1.8.5/libraries -libraries /home/xox/Arduino/libraries -fqbn=heltec:esp32:wifi_lora_32:FlashFreq=80,UploadSpeed=921600 -ide-version=10805 -build-path /tmp/arduino_build_171071 -warnings=none -build-cache /tmp/arduino_cache_306563 -prefs=build.warn_data_percentage=75 -verbose /home/xox/Desktop/electronics_generel/lora/lora_hub/hub_w_2019.01.07-1920/hub_w_2019.01.07-1920.ino
Using board 'wifi_lora_32' from platform in folder: /home/xox/Arduino/hardware/heltec/esp32
Using core 'esp32' from platform in folder: /home/xox/Arduino/hardware/heltec/esp32
Build options changed, rebuilding all
Detecting libraries used...

...

Archiving built core (caching) in: /tmp/arduino_cache_306563/core/core_heltec_esp32_wifi_lora_32_FlashFreq_80,UploadSpeed_921600_df5b810b8740e28eea3709f28cae0128.a
Linking everything together...
"/home/xox/Arduino/hardware/heltec/esp32/tools/xtensa-esp32-elf/bin/xtensa-esp32-elf-gcc" -nostdlib "-L/home/xox/Arduino/hardware/heltec/esp32/tools/sdk/lib" "-L/home/xox/Arduino/hardware/heltec/esp32/tools/sdk/ld" -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.rom.spiram_incompatible_fns.ld -u ld_include_panic_highint_hdl -u call_user_start_cpu0 -Wl,--gc-sections -Wl,-static -Wl,--undefined=uxTopUsedPriority  -u __cxa_guard_dummy -u __cxx_fatal_exception  -Wl,--start-group "/tmp/arduino_build_171071/sketch/hub_w_2019.01.07-1920.ino.cpp.o" "/tmp/arduino_build_171071/libraries/CayenneLPP/CayenneLPP.cpp.o" "/tmp/arduino_build_171071/libraries/arduino-lmic-master/aes/lmic.c.o" "/tmp/arduino_build_171071/libraries/arduino-lmic-master/aes/other.c.o" "/tmp/arduino_build_171071/libraries/arduino-lmic-master/aes/ideetron/AES-128_V10.cpp.o" "/tmp/arduino_build_171071/libraries/arduino-lmic-master/hal/hal.cpp.o" "/tmp/arduino_build_171071/libraries/arduino-lmic-master/lmic/lmic.c.o" "/tmp/arduino_build_171071/libraries/arduino-lmic-master/lmic/oslmic.c.o" "/tmp/arduino_build_171071/libraries/arduino-lmic-master/lmic/radio.c.o" "/tmp/arduino_build_171071/libraries/Wire/Wire.cpp.o" "/tmp/arduino_build_171071/libraries/SPI/SPI.cpp.o" "/tmp/arduino_build_171071/libraries/ESP8266_and_ESP32_Oled_Driver_for_SSD1306_display/OLEDDisplay.cpp.o" "/tmp/arduino_build_171071/libraries/ESP8266_and_ESP32_Oled_Driver_for_SSD1306_display/OLEDDisplayUi.cpp.o" "/tmp/arduino_build_171071/libraries/Adafruit_BME280_Library/Adafruit_BME280.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLE2902.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLE2904.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEAddress.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEAdvertisedDevice.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEAdvertising.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEBeacon.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLECharacteristic.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLECharacteristicMap.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEClient.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEDescriptor.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEDescriptorMap.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEDevice.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEEddystoneTLM.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEEddystoneURL.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEExceptions.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEHIDDevice.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLERemoteCharacteristic.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLERemoteDescriptor.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLERemoteService.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEScan.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLESecurity.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEServer.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEService.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEServiceMap.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEUUID.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEUtils.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/BLEValue.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/FreeRTOS.cpp.o" "/tmp/arduino_build_171071/libraries/ESP32_BLE_Arduino-master/GeneralUtils.cpp.o" "/tmp/arduino_build_171071/libraries/SoftWire/SoftWire.cpp.o" "/tmp/arduino_build_171071/arduino.ar" -lgcc -lopenssl -lbtdm_app -lfatfs -lwps -lcoexist -lwear_levelling -lesp_http_client -lhal -lnewlib -ldriver -lbootloader_support -lpp -lmesh -lsmartconfig -ljsmn -lwpa -lethernet -lphy -lapp_trace -lconsole -lulp -lwpa_supplicant -lfreertos -lbt -lmicro-ecc -lcxx -lxtensa-debug-module -lmdns -lvfs -lsoc -lcore -lsdmmc -lcoap -ltcpip_adapter -lc_nano -lesp-tls -lrtc -lspi_flash -lwpa2 -lesp32 -lapp_update -lnghttp -lspiffs -lespnow -lnvs_flash -lesp_adc_cal -llog -lsmartconfig_ack -lexpat -lm -lc -lheap -lmbedtls -llwip -lnet80211 -lpthread -ljson  -lstdc++ -Wl,--end-group -Wl,-EL -o "/tmp/arduino_build_171071/hub_w_2019.01.07-1920.ino.elf"
python "/home/xox/Arduino/hardware/heltec/esp32/tools/gen_esp32part.py" -q "/home/xox/Arduino/hardware/heltec/esp32/tools/partitions/default.csv" "/tmp/arduino_build_171071/hub_w_2019.01.07-1920.ino.partitions.bin"
python "/home/xox/Arduino/hardware/heltec/esp32/tools/esptool/esptool.py" --chip esp32 elf2image --flash_mode "dio" --flash_freq "80m" --flash_size "4MB" -o "/tmp/arduino_build_171071/hub_w_2019.01.07-1920.ino.bin" "/tmp/arduino_build_171071/hub_w_2019.01.07-1920.ino.elf"
esptool.py v2.3.1
Multiple libraries were found for "CayenneLPP.h"
 Used: /home/xox/Arduino/libraries/CayenneLPP
 Not used: /home/xox/Arduino/libraries/TheThingsNetwork
Multiple libraries were found for "SSD1306.h"
 Used: /home/xox/Arduino/libraries/ESP8266_and_ESP32_Oled_Driver_for_SSD1306_display
 Not used: /home/xox/Arduino/hardware/heltec/esp32/libraries/OLED
Multiple libraries were found for "BLEDevice.h"
 Used: /home/xox/Arduino/libraries/ESP32_BLE_Arduino-master
 Not used: /home/xox/Arduino/hardware/heltec/esp32/libraries/BLE
 Not used: /home/xox/Arduino/hardware/heltec/esp32/libraries/BLE
 Not used: /home/xox/Arduino/hardware/heltec/esp32/libraries/BLE
 Not used: /home/xox/Arduino/hardware/heltec/esp32/libraries/BLE
Using library CayenneLPP at version 1.0.1 in folder: /home/xox/Arduino/libraries/CayenneLPP 
Using library arduino-lmic-master at version 1.5.0+arduino-2 in folder: /home/xox/Arduino/libraries/arduino-lmic-master 
Using library Wire at version 1.0 in folder: /home/xox/Arduino/hardware/heltec/esp32/libraries/Wire 
Using library SPI at version 1.0 in folder: /home/xox/Arduino/hardware/heltec/esp32/libraries/SPI 
Using library ESP8266_and_ESP32_Oled_Driver_for_SSD1306_display at version 4.0.0 in folder: /home/xox/Arduino/libraries/ESP8266_and_ESP32_Oled_Driver_for_SSD1306_display 
Using library Adafruit_Sensors at version 1.0.2 in folder: /home/xox/Arduino/libraries/Adafruit_Sensors 
Using library Adafruit_BME280_Library at version 1.0.7 in folder: /home/xox/Arduino/libraries/Adafruit_BME280_Library 
Using library ESP32_BLE_Arduino-master at version 1.0.1 in folder: /home/xox/Arduino/libraries/ESP32_BLE_Arduino-master 
Using library AsyncDelay at version 1.0.2 in folder: /home/xox/Arduino/libraries/AsyncDelay 
Using library SoftWire at version 2.0.0 in folder: /home/xox/Arduino/libraries/SoftWire 
Sketch uses 1166525 bytes (88%) of program storage space. Maximum is 1310720 bytes.
Global variables use 59812 bytes (20%) of dynamic memory, leaving 235100 bytes for local variables. Maximum is 294912 bytes.
python /home/xox/Arduino/hardware/heltec/esp32/tools/esptool/esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 /home/xox/Arduino/hardware/heltec/esp32/tools/partitions/boot_app0.bin 0x1000 /home/xox/Arduino/hardware/heltec/esp32/tools/sdk/bin/bootloader_dio_80m.bin 0x10000 /tmp/arduino_build_171071/hub_w_2019.01.07-1920.ino.bin 0x8000 /tmp/arduino_build_171071/hub_w_2019.01.07-1920.ino.partitions.bin 
esptool.py v2.3.1
Connecting.....
Chip is ESP32D0WDQ6 (revision (unknown 0xa))
Features: WiFi, BT, Dual Core, VRef calibration in efuse
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Configuring flash size...
Auto-detected Flash size: 8MB
Compressed 8192 bytes to 47...

Writing at 0x0000e000... (100 %)
Wrote 8192 bytes (47 compressed) at 0x0000e000 in 0.0 seconds (effective 32638.1 kbit/s)...
Hash of data verified.
Flash params set to 0x023f
Compressed 13696 bytes to 8946...

Writing at 0x00001000... (100 %)
Wrote 13696 bytes (8946 compressed) at 0x00001000 in 0.1 seconds (effective 1045.4 kbit/s)...
Hash of data verified.
Compressed 1166672 bytes to 658878...

Writing at 0x00010000... (2 %)
Writing at 0x00014000... (4 %)
...
Writing at 0x000ac000... (97 %)
Writing at 0x000b0000... (100 %)
Wrote 1166672 bytes (658878 compressed) at 0x00010000 in 10.2 seconds (effective 913.2 kbit/s)...
Hash of data verified.
Compressed 3072 bytes to 144...

Writing at 0x00008000... (100 %)
Wrote 3072 bytes (144 compressed) at 0x00008000 in 0.0 seconds (effective 8580.6 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...
kenken64 commented 5 years ago

Is it possible to get attention to this problem?

wakwak-koba commented 5 years ago

I found and fixed many bugs in BLECLient, and supports multiple device connection and reconnection after disconnection. If you are using BLECLient, please try my Fork. https://github.com/wakwak-koba/arduino-esp32

Please see the difference for details. https://github.com/espressif/arduino-esp32/compare/master...wakwak-koba:master

kenken64 commented 5 years ago

I found and fixed many bugs in BLECLient, and supports multiple device connection and reconnection after disconnection. If you are using BLECLient, please try my Fork. https://github.com/wakwak-koba/arduino-esp32

Please see the difference for details. master...wakwak-koba:master

how to install and test from your fork ?

wakwak-koba commented 5 years ago

If you have already installed the original arduino-esp32, please overwrite the following files into your arduino-esp32 environment.

Required: https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLEClient.cpp https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLEClient.h https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLEDevice.cpp https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLEDevice.h https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLERemoteCharacteristic.cpp https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLERemoteCharacteristic.h https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLERemoteService.cpp

Not required: https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLEScan.cpp https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLEScan.h https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/src/BLEAdvertisedDevice.cpp

If necessary: https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/examples/BLE_clients_catch_notifies/BLE_clients_catch_notifies.ino

stale[bot] commented 5 years ago

[STALE_SET] This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.

stale[bot] commented 4 years ago

[STALE_DEL] This stale issue has been automatically closed. Thank you for your contributions.

fronik commented 4 years ago

If you have already installed the original arduino-esp32, please overwrite the following files into your arduino-esp32 environment.

Required: https://github.com/wakwak-koba/arduino-esp32/blob/master/libraries/BLE/...

Hi, thank you very much for your work. I use yours BLE fork. And it is much more stable. But after prolonged use (6h - 48h) still hangs. I'm a novice, and I can't cope with the problem alone. Can I count on your help? After work 6h - 48h, hangs on step: pRemoteCharacteristic->writeValue(buf, 2, true); And today in the port monitor at the time of hovering, I saw the following message: [E][BLEClient.cpp:302] gattClientEventHandler(): Config mtu failed

My Project (PlatformIO):

#include <Arduino.h>
#include <BLEDevice.h>
#include <WiFi.h>

// WiFi
const char* ssid     = "WiFiName";
const char* password = "WiFiPass";
WiFiServer server(80);
String header;

// Bluetooth
#define FLORA_ADDR "c4:7c:8d:62:11:11" //MAC Xiaomi Flower Care
BLEClient* pClient = BLEDevice::createClient();
// The remote service we wish to connect to.
static BLEUUID serviceUUID("00001204-0000-1000-8000-00805f9b34fb");
// The characteristic of the remote service we are interested in.
static BLEUUID uuid_sensor_data("00001a01-0000-1000-8000-00805f9b34fb");
static BLEUUID uuid_write_mode("00001a00-0000-1000-8000-00805f9b34fb");
static BLEAddress floraAddress(FLORA_ADDR);
static BLERemoteCharacteristic* pRemoteCharacteristic;
int temp;
int moisture;
int light;
int conductivity;

//Other

uint32_t millisControl = 0;         
uint32_t TimerP1 = 30;              
uint32_t TimerP1Start = 0;          
uint32_t TimerP1Stop = TimerP1;     

void getSensorData(BLEAddress pAddress){ 
  btStart();
  Serial.print("=== Forming a connection to Flora device ===");
  Serial.println(pAddress.toString().c_str());
  Serial.println(" - Connection to Flora");
  if (!pClient->connect(pAddress)){
      pClient->disconnect();
      delay(500);
      Serial.println(" - Cannot connect to Flora.");
      return; 
  } else {
      Serial.println(" - Connected to Flora");

      // Obtain a reference to the service we are after in the remote BLE server.
      BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
      if (pRemoteService == nullptr) {
          Serial.print("Failed to find our service UUID: ");
          Serial.println(serviceUUID.toString().c_str());
      } else {
          Serial.println(" - Found our service");

          pRemoteCharacteristic = pRemoteService->getCharacteristic(uuid_write_mode);
          Serial.println(" - pRemoteCharacteristic = ");
          uint8_t buf[2] = {0xA0, 0x1F};
            Serial.println(" - Step: uint8_t buf[2] = {0xA0, 0x1F}; ");
          pRemoteCharacteristic->writeValue(buf, 2, true);
            Serial.println(" - Step: pRemoteCharacteristic->writeValue(buf, 2, true); ");

          // Obtain a reference to the characteristic in the service of the remote BLE server.
          pRemoteCharacteristic = pRemoteService->getCharacteristic(uuid_sensor_data);
          Serial.println(pRemoteService->toString().c_str());
          if (pRemoteCharacteristic == nullptr) {
              Serial.print("Failed to find our characteristic UUID: ");
              Serial.println(uuid_sensor_data.toString().c_str());
          } else {
              Serial.println(" - Found our characteristic");

              // Read the value of the characteristic.
              std::string value = pRemoteCharacteristic->readValue();
                Serial.println("The characteristic value was: ");
              const char *val = value.c_str();
                              Serial.print("Hex: ");
              for (int i = 0; i < 16; i++) {
                Serial.print((int)val[i], HEX);
                Serial.print(" ");
              }

              temp = (val[0] + val[1] * 256) / 10;
              moisture = val[7];
              light = val[3] + val[4] * 256;
              conductivity = val[8] + val[9] * 256;

              Serial.println("");
              Serial.print("Temperature: ");
              Serial.println(temp);

              Serial.print("Moisture: ");
              Serial.println(moisture);

              Serial.print("Light: ");
              Serial.println(light);

              Serial.print("Conductivity: ");
              Serial.println(conductivity);
          }
      }
  }

  pClient->disconnect();
  //btStop();
  Serial.println((String)"BTserial Free Heap Size:" + ESP.getFreeHeap());
  Serial.println("");
  delay(500);
}

void TimerCheck() {
  TimerP1Stop = TimerP1 - ((millis()/1000) -  TimerP1Start);
  if (TimerP1 < (millis()/1000) -  TimerP1Start) {
    getSensorData(floraAddress);
    TimerP1Start = (millis()/1000);
  }
}

void millisOverControl() {
  if (millisControl > millis())  {
      TimerP1Start = (millis()/1000);
  } else {
    millisControl = millis();
  }
}

void setup() {
  Serial.begin(115200);

  // Bluetooth
  BLEDevice::init("");

  // WiFi
  Serial.print("Connecting to "); 
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected.");  //  "WiFi подключен."
  Serial.println("IP address: ");  //  "IP-адрес: "
  Serial.println(WiFi.localIP());
  server.begin();

}

void loop() {
  WiFiClient client = server.available();

    if (client) {
    Serial.println("New Client.");  
    String currentLine = "";        
    while (client.connected()) {    
      if (client.available()) {     
        char c = client.read();     
        Serial.write(c);            
        header += c;
        if (c == '\n') {            
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            if (header.indexOf("GET /Miflora") >= 0) {
              Serial.println("WEB: Miflora"); 
              getSensorData(floraAddress);
              TimerP1Start = (millis()/1000);
            } else if (header.indexOf("GET /Test2") >= 0) {
              Serial.println("Test2");
            }

            client.println("<html><head><meta charset='UTF-8' name='viewport' content='width=device-width, initial-scale=1'>");
            client.println("<link rel='icon' href='data:,'><link rel='stylesheet' href='http://bootswatch.com/4/yeti/bootstrap.css' media='screen'>");
            client.println("<body><div class='container'><div class='page-header'><div class='row'><div class='col-lg-12'><div class='well bs-component'><div class='row'><div class='col-lg-12'><div class='card border-primary'>");
            client.println("<h1 class='card-header'>Flora Control</h1><div class='progress'>");
            client.println("<div class='progress-bar progress-bar-striped' role='progressbar' style='width: 100%' aria-valuenow='100' aria-valuemin='0' aria-valuemax='100'></div></div>");
            client.println("<h6 class='card-header'><b>Monitor</b></h6><div class='card-body'>");
            client.println("<form class='bs-component'><fieldset><div class='form-group row'>");
            client.println("<div class='col-lg-2'><label class='control-label'>Timer:</label>");
            client.println((String)"<div><label class='control-label'>" + TimerP1Stop + "/" + TimerP1 + "</label></div></div>"); 
            client.println("<div class='col-lg-1'></div></div><div class='bs-docs-section form-group row'>");
            client.println("<div class='col-lg-2'><label class='control-label'>Moisture: </label>");
            client.println((String)"<div><label class='control-label'>" + moisture + "</label></div></div>");
            client.println("<div class='col-lg-2'><label class='control-label'>Conductivity:</label>");
            client.println((String)"<div><label class='control-label'>" + conductivity + "</label></div></div>");
            client.println("<div class='col-lg-2'><label class='control-label'>Light:</label>");
            client.println((String)"<div><label class='control-label'>" + light + "</label></div></div>");
            client.println("<div class='col-lg-2'><label class='control-label'>Temp:</label>");
            client.println((String)"<div><label class='control-label'>" + temp + "</label></div></div>");
            client.println("</div><div class='bs-docs-section form-group row'>");
            client.println("<div class='col-lg-2'><label class='control-label'>Refresh</label>");
            client.println("<input type='button' class='btn btn-warning btn-sm btn-block' onclick=\"location.href='/'\" value='Refresh'></input></div>");             // Link: /

            client.println("<div class='col-lg-2'><label class='control-label'>Hand Request:</label>");
            client.println("<input type='button' class='btn btn-primary btn-sm btn-block' onclick=\"location.href='/Miflora'\" value='MiFlora'></input></div>");       // Link: /Miflora1
            client.println("</div></div></fieldset></form></div>");
            client.println("</div></div></div></div></div></div></div></div></body></html>");

            client.println();
            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;      
        }
      } else {
      break;
      }
    }
    delay(100);
    header = "";
    client.stop();
    Serial.println("Client disconnected."); //  "Клиент отключен."
    Serial.println("");
  }

  millisOverControl();
  TimerCheck();
  delay(500);

}

platformio.ini

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino

monitor_speed = 115200
upload_speed= 921600
board_build.partitions = no_ota.csv
build_flags =
  -W

And sorry for my English, i use google translate.

fronik commented 4 years ago

And yet, ESP32 continues respond to ping. But more than anything is not working (WEB Server or loop)

wakwak-koba commented 4 years ago

If WiFi is not used, will there be a change in uptime? I have experience of encountering the phenomenon that BLE disconnects when using with WiFi.

fronik commented 4 years ago

Ok. i will test without wifi.

fronik commented 4 years ago

I found a similar problem: https://github.com/nkolban/esp32-snippets/issues/874#issuecomment-520212109

I made such corrections:

FreeRTOS.cpp

 68: xSemaphoreTake(m_semaphore, 30000UL);
194: rc = ::xSemaphoreTake(m_semaphore, 30000UL) == pdTRUE; 

Then started testing (with WiFi) two ESP32 boards (2x ESP32 and 2x MiFlora). Test run: 21.11.2019 - 03.12.2019 Interval get data from MiFlora every 30 seconds (for hard test).

Testing stop. ESP32 no freeze.