Hello,
i want to use the espressif libary for BLE on ESP32 and for the desktop app i use bleak. I want to send a value SPO2 to the python terminal for the time the power on the ESP is on. But i only can connect for short time after turn the ESP on and it only display my SPO2 Value 1 time. Can someone help? Maybe someone know a good tutorial too?
The first Code for the ESP:
/*
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp
Ported to Arduino ESP32 by Evandro Copercini
updates by chegewara
*/
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE work!");
BLEDevice::init("Long name works now");
BLEServer *pServer = BLEDevice::createServer(); // Erstelle Server
BLEService *pService = pServer->createService(SERVICE_UUID);
BLECharacteristic *pCharacteristic = pService->createCharacteristic( // Erzeuge Charakteristik
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
pCharacteristic->setValue("Hello World says Neil");
pService->start();
// BLEAdvertising *pAdvertising = pServer->getAdvertising(); // this still is working for backward compatibility
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
Serial.println("Characteristic defined! Now you can read it in your phone!");
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000);
}
This is the code for the Python APP:
Libary: GitHub - hbldh/bleak: A cross platform Bluetooth Low Energy Client for Python using asyncio
and:
import asyncio
from bleak import BleakClient
address = "CC:50:E3:9C:15:02"
MODEL_NBR_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8"
async def main(address):
async with BleakClient(address) as client:
model_number = await client.read_gatt_char(MODEL_NBR_UUID)
print("Model Number: {0}".format("".join(map(chr, model_number))))
async def read_spo2(address):
SPO2_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8"
async with BleakClient(address) as client:
spo2_data = await client.read_gatt_char(SPO2_UUID)
spo2_value = int.from_bytes(spo2_data, byteorder='little')
print("SPO2: {0}".format(spo2_value))
async def main(address):
await read_spo2(address)
asyncio.run(main(address))