The BaseBluetooth class provides a comprehensive Bluetooth abstraction
that serves as the unified interface for all Bluetooth operations in the
HardFOC system. It supports both Bluetooth Classic and Bluetooth Low Energy
(BLE), device discovery, pairing, connection management, and data transfer
across different hardware implementations.
โจ Key Features
๐ฒ Dual Mode Support - Both Bluetooth Classic and BLE in a single interface
๐ Device Discovery - Scan for and discover nearby Bluetooth devices
enumclasshf_bt_err_t:hf_u32_t{// Success codesBT_SUCCESS=0,// General errorsBT_ERR_FAILURE=1,BT_ERR_NOT_INITIALIZED=2,BT_ERR_ALREADY_INITIALIZED=3,BT_ERR_INVALID_PARAMETER=4,BT_ERR_NULL_POINTER=5,BT_ERR_OUT_OF_MEMORY=6,// Connection errorsBT_ERR_CONNECTION_FAILED=7,BT_ERR_CONNECTION_TIMEOUT=8,BT_ERR_CONNECTION_LOST=9,BT_ERR_DEVICE_NOT_FOUND=10,BT_ERR_DEVICE_UNREACHABLE=11,BT_ERR_MAX_CONNECTIONS_REACHED=12,// Pairing errorsBT_ERR_PAIRING_FAILED=13,BT_ERR_PAIRING_REJECTED=14,BT_ERR_AUTHENTICATION_FAILED=15,BT_ERR_AUTHORIZATION_FAILED=16,BT_ERR_ENCRYPTION_FAILED=17,// Discovery errorsBT_ERR_DISCOVERY_FAILED=18,BT_ERR_DISCOVERY_TIMEOUT=19,BT_ERR_SERVICE_NOT_FOUND=20,BT_ERR_CHARACTERISTIC_NOT_FOUND=21,// Data transfer errorsBT_ERR_SEND_FAILED=22,BT_ERR_RECEIVE_FAILED=23,BT_ERR_BUFFER_OVERFLOW=24,BT_ERR_INVALID_DATA_SIZE=25,// BLE specific errorsBLE_ERR_ADVERTISING_FAILED=26,BLE_ERR_GATT_ERROR=27,BLE_ERR_INVALID_ATT_SIZE=28,BLE_ERR_INVALID_HANDLE=29,// Classic specific errorsBT_CLASSIC_ERR_SPP_FAILED=30,BT_CLASSIC_ERR_PROFILE_ERROR=31,BT_CLASSIC_ERR_SDP_FAILED=32,// System errorsBT_ERR_SYSTEM_ERROR=33,BT_ERR_PERMISSION_DENIED=34,BT_ERR_OPERATION_ABORTED=35};
๐ Error Code Categories
Category
Range
Description
|โโโ-|โโ-|โโโโ-|
Success
0
Successful operation
General
1-6
Basic initialization and parameter errors
Connection
7-12
Device connection and management errors
Pairing
13-17
Security and pairing errors
Discovery
18-21
Device and service discovery errors
Data Transfer
22-25
Data transmission errors
BLE Specific
26-29
BLE protocol specific errors
Classic Specific
30-32
Classic Bluetooth errors
System
33-35
System-level errors
๐ง Core API
๐ฏ Essential Methods
Initialization & Configuration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @brief Ensure the Bluetooth controller is initialized
* @return hf_bt_err_t Error code
*/virtualhf_bt_err_tEnsureInitialized()=0;/**
* @brief Set Bluetooth operating mode
* @param mode Bluetooth mode (Classic, BLE, or Dual)
* @return hf_bt_err_t Error code
*/virtualhf_bt_err_tSetMode(hf_bt_mode_tmode)=0;/**
* @brief Check if Bluetooth is initialized
* @return bool True if initialized
*/virtualboolIsInitialized()const=0;
/**
* @brief Send data to connected device
* @param connection_id Target connection ID
* @param data Data buffer to send
* @param data_size Size of data to send
* @return hf_bt_err_t Error code
*/virtualhf_bt_err_tSendData(hf_u32_tconnection_id,consthf_u8_t*data,hf_u32_tdata_size)=0;/**
* @brief Receive data from connected device
* @param connection_id Source connection ID
* @param data Buffer to store received data
* @param buffer_size Size of receive buffer
* @param received_size Actual bytes received
* @return hf_bt_err_t Error code
*/virtualhf_bt_err_tReceiveData(hf_u32_tconnection_id,hf_u8_t*data,hf_u32_tbuffer_size,hf_u32_t&received_size)=0;
๐ Data Structures
๐ฒ Bluetooth Mode Types
1
2
3
4
5
6
enumclasshf_bt_mode_t:hf_u8_t{BT_MODE_DISABLED=0,///< Bluetooth disabledBT_MODE_CLASSIC=1,///< Classic Bluetooth onlyBT_MODE_BLE=2,///< BLE onlyBT_MODE_DUAL=3///< Both Classic and BLE};
๐ฑ Device Information
1
2
3
4
5
6
7
8
9
10
structhf_bt_device_t{bt_addr_taddress;///< Device MAC addresscharname[32];///< Device namehf_u32_tclass_of_device;///< Class of device (Classic BT)hf_i8_trssi;///< Signal strength (dBm)hf_bt_device_type_tdevice_type;///< Device type (Classic/BLE/Dual)boolis_paired;///< Pairing statusboolis_bonded;///< Bonding statushf_u32_tlast_seen_time_ms;///< Last discovery time};
๐ Security Configuration
1
2
3
4
5
6
7
8
structhf_bt_security_config_t{boolrequire_pairing;///< Require pairing for connectionsboolrequire_bonding;///< Require bonding (stored keys)boolrequire_mitm_protection;///< Man-in-the-middle protectionbooluse_secure_connections;///< Use secure connections (if available)hf_u32_tpasskey;///< Static passkey (if used)hf_bt_io_capabilities_tio_cap;///< I/O capabilities for pairing};
๐ Bluetooth Statistics
1
2
3
4
5
6
7
8
9
10
11
12
structhf_bt_statistics_t{hf_u32_ttotal_connections;///< Total connection attemptshf_u32_tsuccessful_connections;///< Successful connectionshf_u32_tfailed_connections;///< Failed connectionshf_u32_ttotal_bytes_sent;///< Total bytes transmittedhf_u32_ttotal_bytes_received;///< Total bytes receivedhf_u32_tpairing_attempts;///< Total pairing attemptshf_u32_tsuccessful_pairings;///< Successful pairingshf_u32_tdiscovery_scans;///< Total discovery scanshf_u32_tdevices_discovered;///< Total devices discoveredhf_u32_tactive_connections;///< Currently active connections};
๐ฒ Bluetooth Modes
๐ป Classic Bluetooth
Classic Bluetooth is ideal for:
Audio streaming (A2DP profile)
File transfers (OBEX/FTP profiles)
Serial data (SPP profile)
Human interface devices (HID profile)
1
2
3
4
5
6
7
8
// Configure for Classic Bluetoothhf_bt_classic_config_tclassic_config={.device_name="HardFOC Controller",.discoverable=true,.connectable=true,.profiles=BT_PROFILE_SPP|BT_PROFILE_A2DP};bluetooth.SetClassicConfig(classic_config);
๐ก Bluetooth Low Energy (BLE)
BLE is optimal for:
Sensor data collection (low power, periodic data)
IoT applications (battery-powered devices)
Beacon applications (advertising-only mode)
Mobile app integration (smartphones/tablets)
1
2
3
4
5
6
7
8
9
// Configure for BLEhf_ble_config_tble_config={.device_name="HardFOC BLE",.advertising_interval_ms=100,.connection_interval_ms=20,.slave_latency=0,.supervision_timeout_ms=4000};bluetooth.SetBleConfig(ble_config);
๐ Dual Mode
Dual mode enables both Classic and BLE simultaneously:
#include"inc/base/BaseBluetooth.h"classBleSensorBeacon{private:// ESP32C6 implementation would inherit from BaseBluetooth// class Esp32C6Bluetooth : public BaseBluetooth { ... };BaseBluetooth*bluetooth*;hf_u32_tservice_handle*;hf_u32_tcharacteristic_handle*;public:boolinitialize(){// Initialize Bluetooth in BLE modeif(bluetooth*.EnsureInitialized()!=hf_bt_err_t::BT_SUCCESS){returnfalse;}if(bluetooth*.SetMode(hf_bt_mode_t::BT_MODE_BLE)!=hf_bt_err_t::BT_SUCCESS){returnfalse;}// Create GATT service for sensor datahf_ble_service_tsensor_service={.uuid={0x12,0x34,0x56,0x78},// Custom UUID.primary=true};if(bluetooth*.CreateGattService(sensor_service)!=hf_bt_err_t::BT_SUCCESS){returnfalse;}// Start advertisingreturnbluetooth*.StartAdvertising()==hf_bt_err_t::BT_SUCCESS;}voidadvertise_sensor_data(floattemperature,floathumidity){// Pack sensor datastruct{floattemperature;floathumidity;hf_u32_ttimestamp;}sensor_data={.temperature=temperature,.humidity=humidity,.timestamp=esp_timer_get_time()/1000};// Update characteristic valuebluetooth*.UpdateCharacteristic(characteristic_handle*,(hf_u8_t*)&sensor_data,sizeof(sensor_data));printf("๐ก BLE: Broadcasting T=%.1fยฐC, H=%.1f%%\n",temperature,humidity);}};
#include"inc/base/BaseBluetooth.h"classBluetoothSerialBridge{private:// ESP32C6 implementation would inherit from BaseBluetooth// class Esp32C6Bluetooth : public BaseBluetooth { ... };BaseBluetooth*bluetooth*;hf_u32_tspp_connection_id*;boolis_connected*;public:BluetoothSerialBridge():spp_connection_id*(0),is_connected*(false){}boolinitialize(){// Initialize Classic Bluetooth with SPP profileif(bluetooth*.EnsureInitialized()!=hf_bt_err_t::BT_SUCCESS){returnfalse;}if(bluetooth*.SetMode(hf_bt_mode_t::BT_MODE_CLASSIC)!=hf_bt_err_t::BT_SUCCESS){returnfalse;}// Configure Classic Bluetoothhf_bt_classic_config_tconfig={.device_name="HardFOC Serial",.discoverable=true,.connectable=true,.profiles=BT_PROFILE_SPP};if(bluetooth*.SetClassicConfig(config)!=hf_bt_err_t::BT_SUCCESS){returnfalse;}// Register connection event callbackbluetooth*.RegisterEventCallback([this](hf_bt_event_t&event){this->handle_bluetooth_event(event);});printf("๐ป Classic Bluetooth SPP ready for connections\n");returntrue;}voidsend_message(conststd::string&message){if(!is_connected*){printf("โ No Bluetooth connection active\n");return;}hf_bt_err_tresult=bluetooth*.SendData(spp_connection_id*,(hf_u8_t*)message.c_str(),message.length());if(result==hf_bt_err_t::BT_SUCCESS){printf("๐ค BT Sent: %s\n",message.c_str());}else{printf("โ BT Send failed: %d\n",static_cast<int>(result));}}voidcheck_for_messages(){if(!is_connected*)return;hf_u8_tbuffer[256];hf_u32_treceived_size;hf_bt_err_tresult=bluetooth*.ReceiveData(spp_connection_id*,buffer,sizeof(buffer)-1,received_size);if(result==hf_bt_err_t::BT_SUCCESS&&received_size>0){buffer[received_size]='\0';// Null terminateprintf("๐ฅ BT Received: %s\n",(char*)buffer);// Echo the message backsend_message("Echo: "+std::string((char*)buffer));}}private:voidhandle_bluetooth_event(hf_bt_event_t&event){switch(event.type){caseBT_EVENT_CONNECTION_ESTABLISHED:spp_connection_id*=event.connection_id;is_connected*=true;printf("โ Bluetooth device connected (ID: %lu)\n",spp_connection_id*);break;caseBT_EVENT_CONNECTION_LOST:if(event.connection_id==spp_connection_id*){is_connected*=false;printf("โ Bluetooth device disconnected\n");}break;caseBT_EVENT_PAIRING_REQUEST:printf("๐ Pairing request from device\n");bluetooth*.AcceptPairing(event.device_addr);break;}}};
#include"inc/mcu/esp32/EspBluetooth.h"classBluetoothDeviceManager{private:EspBluetoothbluetooth*;std::vector<hf_bt_device_t>discovered_devices*;public:boolinitialize(){if(bluetooth*.EnsureInitialized()!=hf_bt_err_t::BT_SUCCESS){returnfalse;}// Enable dual mode for maximum compatibilityreturnbluetooth*.SetMode(hf_bt_mode_t::BT_MODE_DUAL)==hf_bt_err_t::BT_SUCCESS;}voidscan_for_devices(hf_u32_tscan_duration_s=15){printf("๐ Starting Bluetooth device scan (%lu seconds)...\n",scan_duration_s);// Clear previous resultsdiscovered_devices*.clear();// Start discoveryif(bluetooth*.StartDiscovery(scan_duration_s)!=hf_bt_err_t::BT_SUCCESS){printf("โ Failed to start device discovery\n");return;}// Wait for scan to completevTaskDelay(pdMS_TO_TICKS(scan_duration_s*1000));// Get discovered deviceshf_bt_device_tdevices[20];hf_u32_tdevice_count;if(bluetooth*.GetDiscoveredDevices(devices,20,device_count)==hf_bt_err_t::BT_SUCCESS){printf("๐ฑ Found %lu Bluetooth devices:\n",device_count);for(hf_u32_ti=0;i<device_count;i++){discovered_devices*.push_back(devices[i]);print_device_info(devices[i]);}}bluetooth*.StopDiscovery();}boolconnect_to_device(conststd::string&device_name){// Find device by nameautodevice_it=std::find_if(discovered_devices*.begin(),discovered_devices*.end(),[&device_name](consthf_bt_device_t&dev){returnstd::string(dev.name)==device_name;});if(device_it==discovered_devices*.end()){printf("โ Device '%s' not found in scan results\n",device_name.c_str());returnfalse;}printf("๐ Connecting to device: %s\n",device_name.c_str());hf_u32_tconnection_id;hf_bt_err_tresult=bluetooth*.ConnectToDevice(device_it->address,connection_id);if(result==hf_bt_err_t::BT_SUCCESS){printf("โ Successfully connected to %s (ID: %lu)\n",device_name.c_str(),connection_id);returntrue;}else{printf("โ Failed to connect to %s: %d\n",device_name.c_str(),static_cast<int>(result));returnfalse;}}voidshow_statistics(){hf_bt_statistics_tstats;if(bluetooth*.GetStatistics(stats)==hf_bt_err_t::BT_SUCCESS){printf("๐ Bluetooth Statistics:\n");printf(" Total Connections: %lu\n",stats.total_connections);printf(" Success Rate: %.1f%%\n",(float)stats.successful_connections/stats.total_connections*100.0f);printf(" Data Sent: %lu bytes\n",stats.total_bytes_sent);printf(" Data Received: %lu bytes\n",stats.total_bytes_received);printf(" Active Connections: %lu\n",stats.active_connections);printf(" Devices Discovered: %lu\n",stats.devices_discovered);}}private:voidprint_device_info(consthf_bt_device_t&device){constchar*type_str=(device.device_type==BT_DEVICE_TYPE_CLASSIC)?"Classic":(device.device_type==BT_DEVICE_TYPE_BLE)?"BLE":"Dual";printf(" ๐ฑ %s [%s] RSSI: %ddBm %s%s\n",device.name,type_str,device.rssi,device.is_paired?"(Paired)":"",device.is_bonded?"(Bonded)":"");}};
๐งช Best Practices
โ Recommended Practices
๐ฏ Choose Appropriate Mode
1
2
3
4
5
6
7
8
// For low-power sensorsbluetooth.SetMode(hf_bt_mode_t::BT_MODE_BLE);// For audio/data streamingbluetooth.SetMode(hf_bt_mode_t::BT_MODE_CLASSIC);// For maximum compatibilitybluetooth.SetMode(hf_bt_mode_t::BT_MODE_DUAL);
// Regular statistics monitoringhf_bt_statistics_tstats;bluetooth.GetStatistics(stats);if(stats.successful_connections<stats.total_connections*0.9f){printf("โ ๏ธ Low Bluetooth connection success rate\n");}
โ Common Pitfalls
๐ซ Not Checking Connection Status
1
2
3
4
5
6
7
8
// BAD: Sending without checking connectionbluetooth.SendData(connection_id,data,size);// GOOD: Always verify connectionboolconnected;if(bluetooth.IsDeviceConnected(connection_id,connected)==BT_SUCCESS&&connected){bluetooth.SendData(connection_id,data,size);}
๐ซ Ignoring Power Management
1
2
3
4
5
6
// BAD: Always on, drains batterybluetooth.SetMode(hf_bt_mode_t::BT_MODE_DUAL);// GOOD: Use BLE for battery-powered applicationsbluetooth.SetMode(hf_bt_mode_t::BT_MODE_BLE);bluetooth.SetLowPowerMode(true);
๐ซ Poor Error Handling
1
2
3
4
5
6
7
8
// BAD: Ignoring connection failuresbluetooth.ConnectToDevice(addr,connection_id);// GOOD: Handle connection failures gracefullyif(bluetooth.ConnectToDevice(addr,connection_id)!=BT_SUCCESS){printf("Connection failed, will retry in 5 seconds\n");// Implement retry logic}
๐ฏ Performance Tips
โก Optimize BLE Connection Parameters
1
2
3
4
5
hf_ble_config_tble_config={.connection_interval_ms=7.5f,// Faster updates.slave_latency=0,// No latency.supervision_timeout_ms=4000// 4 second timeout};
๐ฑ Use Appropriate Advertising Intervals
1
2
3
4
5
// Fast connection establishmentbluetooth.SetAdvertisingInterval(20);// 20ms for quick discovery// Battery conservationbluetooth.SetAdvertisingInterval(1000);// 1s for low power
๐ Implement Connection Pooling
1
2
3
// Manage multiple connections efficientlystd::vector<hf_u32_t>active_connections;// Reuse connections instead of creating new ones
๐ฒ Professional Bluetooth Communication for Modern Applications
Enabling seamless wireless connectivity with robust security and optimal performance