blynkkk / blynk-library

Blynk library for IoT boards. Works with Arduino, ESP32, ESP8266, Raspberry Pi, Particle, ARM Mbed, etc.
https://blynk.io
MIT License
3.81k stars 1.38k forks source link

Flushing buffer in direct mode (BLE / Bluetooth classic) #565

Open FedericoBusero opened 2 years ago

FedericoBusero commented 2 years ago

Description

When running Blynk in direct mode (using Bluetooth/BLE), the connection can stop working after "Packet too big", "Invalid header type" or "Bad hdr len". The cause is the loss of one or more bytes, which makes the Blynk protocol get out of sync, resulting in a connection being closed.

A typical case is an Arduino Uno/Nano connected with a HM-10 module using SoftSerial (to keep Serial for debugging). Sometimes a byte is lost due to a bad softserial connection, and then the communication gets out of sync.

However, it is not necessary to close the open connection, it just needs to resync. Because the Blynk protocol misses sync bytes, it should be done in another way. In this solution, it makes use of the fact that Blynk on BT/BLE is sending its bytes in blocks, starting with the header. So, in case the systen is no longer synced, we just need to flush the buffer to get it in sync again. Using this fix, the stability of BLE in Blynk increases a lot when using SoftSerial.

Issues Resolved