obd2_gauge/sketch/obd2_gauge/bluetooth.h
Sebastian Nieto d124d013ab feat(ui): transiciones fluidas de 4 pantallas, integracion GPS y buffer de transicion persistente sin fragmentacion de memoria
- Buffer de transicion persistente (sprTrans) de 25KB asignado una sola vez en setup() para evitar fallos de memoria heap contigua
- Eliminacion de carga y descarga dinamica de fuentes en renderPage2ToSprite durante las transiciones para evitar fugas de RAM
- Timeout de seguridad por hardware de 250ms en waitForTouchRelease() para prevenir bloqueos por ruido en la lamina resistiva
- Pantallas 2 y 3: Reloj atomico GPS con DSEG7 de 80pt y Telemetria satelital completa (rumbo, satelites, altitud, coordenadas)
- Documentacion de conexion y pines para modulo GPS N32+/U-blox
2026-10-11 18:33:03 -03:00

231 lines
No EOL
7.3 KiB
C++

/* Bluetooth function */
//----------------------------------
extern bool ignitionOn;
extern bool wokeFromSleep;
extern TaskHandle_t btTaskHandle;
void initScreen(bool redrawTFT = true);
void plotNoData(uint8_t cell);
void touchBeep();
//convert bt address to text
//{0x00,0x1d,0xa5,0x00,0x12,0x92} -> 00:1d:a5:00:12:92
String ByteArraytoString(esp_bd_addr_t bt_address) {
String txt = "";
String nib = "";
for (uint8_t i=0;i<ESP_BD_ADDR_LEN-1;i++) {//0-4
nib = String(bt_address[i],HEX);
if (nib.length() < 2) nib = "0"+nib;
txt = txt + nib+":";
}//for
nib = String(bt_address[ESP_BD_ADDR_LEN-1],HEX);//5
if (nib.length() < 2) nib = "0"+nib;
txt = txt + nib;
return txt;
}
/*=======================*/
void scanBTdevice() {//scan bluetooth device
setRearLedColor(0, 0, 200);//blue led on
#ifdef SERIAL_DEBUG
Serial.println("Scanning for OBDII Adaptor...");
#endif
Terminal("Scanning for OBDII Adaptor...",0,48,320,191);
btDeviceCount = 0;
// BTScanResults* btDeviceList = BTSerial.getScanResults(); // maybe accessing from different threads!
if (BTSerial.discoverAsync([](BTAdvertisedDevice* pDevice) {
// BTAdvertisedDeviceSet*set = reinterpret_cast<BTAdvertisedDeviceSet*>(pDevice);
// btDeviceList[pDevice->getAddress()] = * set;
String txt = pDevice->toString().c_str();
#ifdef SERIAL_DEBUG
Serial.printf("Found a new device: %s\n", pDevice->toString().c_str());
#endif
deviceName[btDeviceCount] = pDevice->getName().c_str();
deviceAddr[btDeviceCount] = pDevice->getAddress().toString().c_str();
btDeviceCount++;
} )
) {
delay(BT_DISCOVER_TIME);
BTSerial.discoverAsyncStop();
#ifdef SERIAL_DEBUG
Serial.println("Discovering stopped");
#endif
setRearLedOff();//blue led off
delay(1000);//redsicovery delay
} else {
#ifdef SERIAL_DEBUG
Serial.println("Error on discovering bluetooth clients.");
#endif
}
String txt = "Found "+String(btDeviceCount)+" device(s)";
Terminal(txt,0,48,320,191);
//matching scan obd2 and config obd2
for (uint8_t i=0;i<btDeviceCount;i++) {
txt = String(i+1)+". "+deviceName[i]+" - "+deviceAddr[i];
Terminal(txt,0,48,320,191);//list devices
delay(100) ;
String dName = deviceName[i];
dName.toUpperCase();
String dAddr = deviceAddr[i];
dAddr.toLowerCase();
bool isMatch = (dName == "OBDII") ||
(dName.indexOf("OBD") != -1) ||
(dName.indexOf("ELM") != -1) ||
(dName == "DEBIAN") ||
(dAddr == "e8:48:b8:c8:20:00");
if (isMatch) {//match name.
//found device name "OBDII" or emulator
foundOBD2 = true;
//00:1d:a5:00:12:92 -> {0x00,0x1d,0xa5,0x00,0x12,0x92};
//copy match bt mac address to client_name to connect
String str = deviceAddr[i];
uint8_t StringCount = 0;
while (str.length() > 0) {
int8_t index = str.indexOf(':');
if (index == -1) {// No : found
client_addr[StringCount] = strtol(str.c_str(), 0, 16);//convert hex string to byte
str = "";//set length to 0;
//exit loop while
} else {
client_addr[StringCount] = strtol(str.substring(0, index).c_str(),0,16);//convert hex string to byte
StringCount++;
str = str.substring(index+1);
}
}//while mac address copied to client_addr for connect below code
if (ByteArraytoString(client_addr) != ByteArraytoString(recent_client_addr)) {
pref.putBytes("recent_client",client_addr,sizeof(client_addr));//save new bt addr to pref.
memcpy(recent_client_addr, client_addr, sizeof(client_addr));
#ifdef SERIAL_DEBUG
Serial.println(F("Save a new BT client address"));
#endif
}
break; // Stop scanning once a matching device is found!
} else {
foundOBD2 = false;
}
}//for loop list device
//connect to obd2
if (foundOBD2) {
txt = "Connecting to " + client_name +" - " + ByteArraytoString(client_addr);
Terminal(txt,0,48,320,191);
#ifdef SERIAL_DEBUG
Serial.println(txt);
#endif
BTSerial.connect(client_addr, 0, sec_mask, role);//connect to OBDII adaptor
bool blink = false;
uint8_t try_count = 0;
while(!BTSerial.connected(1000) && (try_count < 10)) {
#ifdef SERIAL_DEBUG
Serial.print(F("."));
#endif
blink =! blink;
if (blink) setRearLedColor(0, 0, 200);
else setRearLedOff();
if (blink) tft.setTextColor(TFT_BLUE,TFT_BLACK);
else tft.setTextColor(TFT_BLACK,TFT_BLACK);
tft.drawRightString("$",319,210,4);
try_count++;
}
if (try_count >= 10) {
Terminal("Connect failed!",0,48,320,191);
#ifdef SERIAL_DEBUG
Serial.println(F("Connect failed!"));
#endif
BTSerial.disconnect();
setRearLedOff();
foundOBD2 = false;
} else {
Terminal("Connected Successfully!",0,48,320,191);
#ifdef SERIAL_DEBUG
Serial.println(F("Connected Successfully!"));
#endif
prompt = true;
updateRearLedTheme(); // Set rear RGB LED to active theme color
foundOBD2 = true;
}
} else {
Terminal("OBDII Adaptor not found!",0,48,320,191);
#ifdef SERIAL_DEBUG
Serial.println(F("OBDII Adaptor not found!"));
#endif
} //foundOBD2
}//scanBTDevice
//---------------------------
//connect to recent obdII for fast connection, skip scanning
void connectLastOBDII() {
bool hasRecentAddr = false;
for (uint8_t i = 0; i < 6; i++) {
if (recent_client_addr[i] != 0) {
hasRecentAddr = true;
break;
}
}
if (!hasRecentAddr) {
Terminal("Sin escaner OBDII previo.", 0, 48, 320, 191);
#ifdef SERIAL_DEBUG
Serial.println(F("Sin escaner OBDII previo."));
#endif
foundOBD2 = false;
return;
}
setRearLedColor(0, 0, 200);//blue led on
String txt = "Connecting to " + client_name +" - " + ByteArraytoString(recent_client_addr);
Terminal(txt,0,48,320,191);
#ifdef SERIAL_DEBUG
Serial.println(txt);
#endif
BTSerial.connect(recent_client_addr, 0, sec_mask, role);//connect to OBDII adaptor
uint8_t try_count = 0;
bool blink = false;
while(!BTSerial.connected(1000) && (try_count <3)) {
#ifdef SERIAL_DEBUG
Serial.print(F("."));
#endif
blink =! blink;
if (blink) setRearLedColor(0, 0, 200);
else setRearLedOff();
try_count++;
}
if (try_count == 3) {//cannot connect
Terminal("OBDII Adaptor not found!",0,48,320,191);
#ifdef SERIAL_DEBUG
Serial.println(F("OBDII Adaptor not found!"));
#endif
BTSerial.disconnect();
setRearLedOff();
foundOBD2 = false;
} else {
Terminal("Connected Successfully!",0,48,320,191);
#ifdef SERIAL_DEBUG
Serial.println(F("Connected Successfully!"));
#endif
prompt = true;
updateRearLedTheme(); // Set rear RGB LED to active theme color
foundOBD2 = true;
}
}//connectLasbtOBDII
//---------------------------
//---------------------------
// Resume Bluetooth connection with OBDII scanner upon waking from sleep (en segundo plano, 100% no bloqueante)
bool resumeBluetoothConnection() {
foundOBD2 = false;
if (btTaskHandle != NULL) {
xTaskNotifyGive(btTaskHandle);
}
return true;
}