Reputation: 504
I'm building some IoT devices which are controlled by ESP32. I want to have real time control via Android application. Because WiFi is too power hungry (my devices are battery powered) I've decided to connect using BLE which should be more suitable option.
I have Xamarin Android app which acts as a GATT server because it allows for multiple devices connected and aggregated in my app. ESP32 device connects to the server when I advertise and properly receives notifications for example when I click the button. The problem is that I have no idea how to manage the situation when user exits the app. How to restore the connections? It is no problem to save some deviceId in local db on the android device but can anyone tell me what steps should I take to achieve following results:
User connects app to the device, exits the app or leave the ble range and when he opens it again connection is restored and user can send some data to the device.
On ESP32 there seems to be no reconnect option and on android theoretically there is but when device is not a server but client (autoconnect = true) Maybe I did it the wrong way (devices should be servers but is then possible to be connected to multiple devices and achieve results of real time control?)
I will appreciate any advices :)
Upvotes: 2
Views: 1095
Reputation: 504
So after some research and Youssif answer I indeed attempted to switch the roles and make esp32 act as the server and android app as client. (Despite it seemed counter-intuitive at first)
It turned out that as a android ble client there are much more options and I think it is more supported path. Shiny.NET library which I use to manage whole BLE thing has great possibilities to make this process quite pleasant (if you get through poor documentation).
Here is the path to achieve the results I anticipated:
I didn't use any specific terms because it is not the point. My application is written in C# Xamarin, but the same path is for naitive android apps, these are just implementation detail.
Upvotes: 0
Reputation: 13345
With BLE you cannot initiate a connection from a peripheral device. The central device is responsible for initiating and maintaining the connection. As such, you have two options to achieve what you want:-
Option 1: as you said, switch the roles so that the Android device is the central in the connection. This way you can set autoconnect = true and this might be the easier option.
Option 2: maintain the roles, but add code on the ESP32 side so that upon disconnection, the ESP32 switches to a continuous scanning mode where it searches for the Android device, and as soon as it finds it, it would reconnect. If you want to save battery on the ESP32 then you can have it go to sleep and only wake up periodically to do a quick scan in case the Android device became available again.
Upvotes: 1