Prvni ulozeni z chegewara githubu

This commit is contained in:
2023-02-25 16:13:53 +01:00
commit 01eb80dfe2
3279 changed files with 638407 additions and 0 deletions

View File

@ -0,0 +1,19 @@
### Bluetooth Serial Library
A simple Serial compatible library using ESP32 classical bluetooth (SPP)
#### How to use it?
- Download one bluetooth terminal app in your smartphone<br>
For Android: https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal <br>
For iOS: https://itunes.apple.com/us/app/hm10-bluetooth-serial-lite/id1030454675
- Flash an example sketch to your ESP32
- Scan and pair the device in your smartphone
- Open the bluetooth terminal app
- Enjoy

View File

@ -0,0 +1,114 @@
/**
* Bluetooth Classic Example
* Scan for devices - asyncronously, print device as soon as found
* query devices for SPP - SDP profile
* connect to first device offering a SPP connection
*
* Example python server:
* source: https://gist.github.com/ukBaz/217875c83c2535d22a16ba38fc8f2a91
*
* Tested with Raspberry Pi onboard Wifi/BT, USB BT 4.0 dongles, USB BT 1.1 dongles,
* 202202: does NOT work with USB BT 2.0 dongles when esp32 aduino lib is compiled with SSP support!
* see https://github.com/espressif/esp-idf/issues/8394
*
* use ESP_SPP_SEC_ENCRYPT|ESP_SPP_SEC_AUTHENTICATE in connect() if remote side requests 'RequireAuthentication': dbus.Boolean(True),
* use ESP_SPP_SEC_NONE or ESP_SPP_SEC_ENCRYPT|ESP_SPP_SEC_AUTHENTICATE in connect() if remote side has Authentication: False
*/
#include <map>
#include <BluetoothSerial.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
BluetoothSerial SerialBT;
#define BT_DISCOVER_TIME 10000
esp_spp_sec_t sec_mask=ESP_SPP_SEC_NONE; // or ESP_SPP_SEC_ENCRYPT|ESP_SPP_SEC_AUTHENTICATE to request pincode confirmation
esp_spp_role_t role=ESP_SPP_ROLE_SLAVE; // or ESP_SPP_ROLE_MASTER
// std::map<BTAddress, BTAdvertisedDeviceSet> btDeviceList;
void setup() {
Serial.begin(115200);
if(! SerialBT.begin("ESP32test", true) ) {
Serial.println("========== serialBT failed!");
abort();
}
// SerialBT.setPin("1234"); // doesn't seem to change anything
// SerialBT.enableSSP(); // doesn't seem to change anything
Serial.println("Starting discoverAsync...");
BTScanResults* btDeviceList = SerialBT.getScanResults(); // maybe accessing from different threads!
if (SerialBT.discoverAsync([](BTAdvertisedDevice* pDevice) {
// BTAdvertisedDeviceSet*set = reinterpret_cast<BTAdvertisedDeviceSet*>(pDevice);
// btDeviceList[pDevice->getAddress()] = * set;
Serial.printf(">>>>>>>>>>>Found a new device asynchronously: %s\n", pDevice->toString().c_str());
} )
) {
delay(BT_DISCOVER_TIME);
Serial.print("Stopping discoverAsync... ");
SerialBT.discoverAsyncStop();
Serial.println("discoverAsync stopped");
delay(5000);
if(btDeviceList->getCount() > 0) {
BTAddress addr;
int channel=0;
Serial.println("Found devices:");
for (int i=0; i < btDeviceList->getCount(); i++) {
BTAdvertisedDevice *device=btDeviceList->getDevice(i);
Serial.printf(" ----- %s %s %d\n", device->getAddress().toString().c_str(), device->getName().c_str(), device->getRSSI());
std::map<int,std::string> channels=SerialBT.getChannels(device->getAddress());
Serial.printf("scanned for services, found %d\n", channels.size());
for(auto const &entry : channels) {
Serial.printf(" channel %d (%s)\n", entry.first, entry.second.c_str());
}
if(channels.size() > 0) {
addr = device->getAddress();
channel=channels.begin()->first;
}
}
if(addr) {
Serial.printf("connecting to %s - %d\n", addr.toString().c_str(), channel);
SerialBT.connect(addr, channel, sec_mask, role);
}
} else {
Serial.println("Didn't find any devices");
}
} else {
Serial.println("Error on discoverAsync f.e. not workin after a \"connect\"");
}
}
String sendData="Hi from esp32!\n";
void loop() {
if(! SerialBT.isClosed() && SerialBT.connected()) {
if( SerialBT.write((const uint8_t*) sendData.c_str(),sendData.length()) != sendData.length()) {
Serial.println("tx: error");
} else {
Serial.printf("tx: %s",sendData.c_str());
}
if(SerialBT.available()) {
Serial.print("rx: ");
while(SerialBT.available()) {
int c=SerialBT.read();
if(c >= 0) {
Serial.print((char) c);
}
}
Serial.println();
}
} else {
Serial.println("not connected");
}
delay(1000);
}

View File

@ -0,0 +1,33 @@
//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Evandro Copercini - 2018
//
//This example creates a bridge between Serial and Classical Bluetooth (SPP)
//and also demonstrate that SerialBT have the same functionalities of a normal Serial
#include "BluetoothSerial.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}

View File

@ -0,0 +1,60 @@
//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Victor Tchistiak - 2019
//
//This example demostrates master mode bluetooth connection and pin
//it creates a bridge between Serial and Classical Bluetooth (SPP)
//this is an extention of the SerialToSerialBT example by Evandro Copercini - 2018
//
#include "BluetoothSerial.h"
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
BluetoothSerial SerialBT;
String MACadd = "AA:BB:CC:11:22:33";
uint8_t address[6] = {0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33};
//uint8_t address[6] = {0x00, 0x1D, 0xA5, 0x02, 0xC3, 0x22};
String name = "OBDII";
const char *pin = "1234"; //<- standard pin would be provided by default
bool connected;
void setup() {
Serial.begin(115200);
//SerialBT.setPin(pin);
SerialBT.begin("ESP32test", true);
//SerialBT.setPin(pin);
Serial.println("The device started in master mode, make sure remote BT device is on!");
// connect(address) is fast (upto 10 secs max), connect(name) is slow (upto 30 secs max) as it needs
// to resolve name to address first, but it allows to connect to different devices with the same name.
// Set CoreDebugLevel to Info to view devices bluetooth address and device names
connected = SerialBT.connect(name);
//connected = SerialBT.connect(address);
if(connected) {
Serial.println("Connected Succesfully!");
} else {
while(!SerialBT.connected(10000)) {
Serial.println("Failed to connect. Make sure remote device is available and in range, then restart app.");
}
}
// disconnect() may take upto 10 secs max
if (SerialBT.disconnect()) {
Serial.println("Disconnected Succesfully!");
}
// this would reconnect to the name(will use address, if resolved) or address used with connect(name/address).
SerialBT.connect();
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}

View File

@ -0,0 +1,79 @@
//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Richard Li - 2020
//
//This example creates a bridge between Serial and Classical Bluetooth (SPP with authentication)
//and also demonstrate that SerialBT have the same functionalities of a normal Serial
#include "BluetoothSerial.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
BluetoothSerial SerialBT;
boolean confirmRequestPending = true;
void BTConfirmRequestCallback(uint32_t numVal)
{
confirmRequestPending = true;
Serial.println(numVal);
}
void BTAuthCompleteCallback(boolean success)
{
confirmRequestPending = false;
if (success)
{
Serial.println("Pairing success!!");
}
else
{
Serial.println("Pairing failed, rejected by user!!");
}
}
void setup()
{
Serial.begin(115200);
SerialBT.enableSSP();
SerialBT.onConfirmRequest(BTConfirmRequestCallback);
SerialBT.onAuthComplete(BTAuthCompleteCallback);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop()
{
if (confirmRequestPending)
{
if (Serial.available())
{
int dat = Serial.read();
if (dat == 'Y' || dat == 'y')
{
SerialBT.confirmReply(true);
}
else
{
SerialBT.confirmReply(false);
}
}
}
else
{
if (Serial.available())
{
SerialBT.write(Serial.read());
}
if (SerialBT.available())
{
Serial.write(SerialBT.read());
}
delay(20);
}
}

View File

@ -0,0 +1,56 @@
#include <BluetoothSerial.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
BluetoothSerial SerialBT;
#define BT_DISCOVER_TIME 10000
static bool btScanAsync = true;
static bool btScanSync = true;
void btAdvertisedDeviceFound(BTAdvertisedDevice* pDevice) {
Serial.printf("Found a device asynchronously: %s\n", pDevice->toString().c_str());
}
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
if (btScanAsync) {
Serial.print("Starting discoverAsync...");
if (SerialBT.discoverAsync(btAdvertisedDeviceFound)) {
Serial.println("Findings will be reported in \"btAdvertisedDeviceFound\"");
delay(10000);
Serial.print("Stopping discoverAsync... ");
SerialBT.discoverAsyncStop();
Serial.println("stopped");
} else {
Serial.println("Error on discoverAsync f.e. not workin after a \"connect\"");
}
}
if (btScanSync) {
Serial.println("Starting discover...");
BTScanResults *pResults = SerialBT.discover(BT_DISCOVER_TIME);
if (pResults)
pResults->dump(&Serial);
else
Serial.println("Error on BT Scan, no result!");
}
}
void loop() {
delay(100);
}

View File

@ -0,0 +1,91 @@
//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Victor Tchistiak - 2019
//
//This example demonstrates reading and removing paired devices stored on the ESP32 flash memory
//Sometimes you may find your ESP32 device could not connect to the remote device despite
//many successful connections earlier. This is most likely a result of client replacing your paired
//device info with new one from other device. The BT clients store connection info for paired devices,
//but it is limited to a few devices only. When new device pairs and number of stored devices is exceeded,
//one of the previously paired devices would be replaced with new one.
//The only remedy is to delete this saved bound device from your device flash memory
//and pair with the other device again.
//
#include "esp_bt_main.h"
#include "esp_bt_device.h"
#include"esp_gap_bt_api.h"
#include "esp_err.h"
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
#define REMOVE_BONDED_DEVICES 0 // <- Set to 0 to view all bonded devices addresses, set to 1 to remove
#define PAIR_MAX_DEVICES 20
uint8_t pairedDeviceBtAddr[PAIR_MAX_DEVICES][6];
char bda_str[18];
bool initBluetooth()
{
if(!btStart()) {
Serial.println("Failed to initialize controller");
return false;
}
if(esp_bluedroid_init() != ESP_OK) {
Serial.println("Failed to initialize bluedroid");
return false;
}
if(esp_bluedroid_enable() != ESP_OK) {
Serial.println("Failed to enable bluedroid");
return false;
}
return true;
}
char *bda2str(const uint8_t* bda, char *str, size_t size)
{
if (bda == NULL || str == NULL || size < 18) {
return NULL;
}
sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
return str;
}
void setup() {
Serial.begin(115200);
initBluetooth();
Serial.print("ESP32 bluetooth address: "); Serial.println(bda2str(esp_bt_dev_get_address(), bda_str, 18));
// Get the numbers of bonded/paired devices in the BT module
int count = esp_bt_gap_get_bond_device_num();
if(!count) {
Serial.println("No bonded device found.");
} else {
Serial.print("Bonded device count: "); Serial.println(count);
if(PAIR_MAX_DEVICES < count) {
count = PAIR_MAX_DEVICES;
Serial.print("Reset bonded device count: "); Serial.println(count);
}
esp_err_t tError = esp_bt_gap_get_bond_device_list(&count, pairedDeviceBtAddr);
if(ESP_OK == tError) {
for(int i = 0; i < count; i++) {
Serial.print("Found bonded device # "); Serial.print(i); Serial.print(" -> ");
Serial.println(bda2str(pairedDeviceBtAddr[i], bda_str, 18));
if(REMOVE_BONDED_DEVICES) {
esp_err_t tError = esp_bt_gap_remove_bond_device(pairedDeviceBtAddr[i]);
if(ESP_OK == tError) {
Serial.print("Removed bonded device # ");
} else {
Serial.print("Failed to remove bonded device # ");
}
Serial.println(i);
}
}
}
}
}
void loop() {}

View File

@ -0,0 +1,26 @@
#######################################
# Syntax Coloring Map For BluetoothSerial
#######################################
#######################################
# Library (KEYWORD3)
#######################################
BluetoothSerial KEYWORD3
#######################################
# Datatypes (KEYWORD1)
#######################################
BluetoothSerial KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
SerialBT KEYWORD2
hasClient KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@ -0,0 +1,9 @@
name=BluetoothSerial
version=2.0.0
author=Evandro Copercini
maintainer=Evandro Copercini
sentence=Simple UART to Classical Bluetooth bridge for ESP32
paragraph=
category=Communication
url=
architectures=esp32

View File

@ -0,0 +1,106 @@
/*
* BTAddress.cpp
*
* Created on: Jul 2, 2017
* Author: kolban
* Ported on: Feb 5, 2021
* Author: Thomas M. (ArcticSnowSky)
*/
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
#include "BTAddress.h"
#include <string>
#include <sstream>
#include <iomanip>
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#ifdef ARDUINO_ARCH_ESP32
#include "esp32-hal-log.h"
#endif
/**
* @brief Create an address from the native ESP32 representation.
* @param [in] address The native representation.
*/
BTAddress::BTAddress(esp_bd_addr_t address) {
memcpy(m_address, address, ESP_BD_ADDR_LEN);
} // BTAddress
BTAddress::BTAddress() {
bzero(m_address, ESP_BD_ADDR_LEN);
} // BTAddress
/**
* @brief Create an address from a hex string
*
* A hex string is of the format:
* ```
* 00:00:00:00:00:00
* ```
* which is 17 characters in length.
*
* @param [in] stringAddress The hex representation of the address.
*/
BTAddress::BTAddress(std::string stringAddress) {
if (stringAddress.length() != 17) return;
int data[6];
sscanf(stringAddress.c_str(), "%x:%x:%x:%x:%x:%x", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5]);
m_address[0] = (uint8_t) data[0];
m_address[1] = (uint8_t) data[1];
m_address[2] = (uint8_t) data[2];
m_address[3] = (uint8_t) data[3];
m_address[4] = (uint8_t) data[4];
m_address[5] = (uint8_t) data[5];
} // BTAddress
/**
* @brief Determine if this address equals another.
* @param [in] otherAddress The other address to compare against.
* @return True if the addresses are equal.
*/
bool BTAddress::equals(BTAddress otherAddress) {
return memcmp(otherAddress.getNative(), m_address, 6) == 0;
} // equals
BTAddress::operator bool () const {
for(int i = 0; i < ESP_BD_ADDR_LEN; i++){
if(this->m_address[i])
return true;
}
return false;
} // operator ()
/**
* @brief Return the native representation of the address.
* @return The native representation of the address.
*/
esp_bd_addr_t *BTAddress::getNative() const {
return const_cast<esp_bd_addr_t *>(&m_address);
} // getNative
/**
* @brief Convert a BT address to a string.
*
* A string representation of an address is in the format:
*
* ```
* xx:xx:xx:xx:xx:xx
* ```
*
* @return The string representation of the address.
*/
std::string BTAddress::toString() const {
auto size = 18;
char *res = (char*)malloc(size);
snprintf(res, size, "%02x:%02x:%02x:%02x:%02x:%02x", m_address[0], m_address[1], m_address[2], m_address[3], m_address[4], m_address[5]);
std::string ret(res);
free(res);
return ret;
} // toString
#endif

View File

@ -0,0 +1,39 @@
/*
* BTAddress.h
*
* Created on: Jul 2, 2017
* Author: kolban
* Ported on: Feb 5, 2021
* Author: Thomas M. (ArcticSnowSky)
*/
#ifndef COMPONENTS_CPP_UTILS_BTADDRESS_H_
#define COMPONENTS_CPP_UTILS_BTADDRESS_H_
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
#include <esp_gap_bt_api.h> // ESP32 BT
#include <string>
/**
* @brief A %BT device address.
*
* Every %BT device has a unique address which can be used to identify it and form connections.
*/
class BTAddress {
public:
BTAddress();
BTAddress(esp_bd_addr_t address);
BTAddress(std::string stringAddress);
bool equals(BTAddress otherAddress);
operator bool () const;
esp_bd_addr_t* getNative() const;
std::string toString() const;
private:
esp_bd_addr_t m_address;
};
#endif /* CONFIG_BT_ENABLED */
#endif /* COMPONENTS_CPP_UTILS_BTADDRESS_H_ */

View File

@ -0,0 +1,65 @@
/*
* BTAdvertisedDevice.h
*
* Created on: Feb 5, 2021
* Author: Thomas M. (ArcticSnowSky)
*/
#ifndef __BTADVERTISEDDEVICE_H__
#define __BTADVERTISEDDEVICE_H__
#include "BTAddress.h"
class BTAdvertisedDevice {
public:
virtual ~BTAdvertisedDevice() = default;
virtual BTAddress getAddress();
virtual uint32_t getCOD() const;
virtual std::string getName() const;
virtual int8_t getRSSI() const;
virtual bool haveCOD() const;
virtual bool haveName() const;
virtual bool haveRSSI() const;
virtual std::string toString();
};
class BTAdvertisedDeviceSet : public virtual BTAdvertisedDevice {
public:
BTAdvertisedDeviceSet();
//~BTAdvertisedDeviceSet() = default;
BTAddress getAddress();
uint32_t getCOD() const;
std::string getName() const;
int8_t getRSSI() const;
bool haveCOD() const;
bool haveName() const;
bool haveRSSI() const;
std::string toString();
void setAddress(BTAddress address);
void setCOD(uint32_t cod);
void setName(std::string name);
void setRSSI(int8_t rssi);
bool m_haveCOD;
bool m_haveName;
bool m_haveRSSI;
BTAddress m_address = BTAddress((uint8_t*)"\0\0\0\0\0\0");
uint32_t m_cod;
std::string m_name;
int8_t m_rssi;
};
#endif

View File

@ -0,0 +1,78 @@
/*
* BTAdvertisedDeviceSet.cpp
*
* Created on: Feb 5, 2021
* Author: Thomas M. (ArcticSnowSky)
*/
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
//#include <map>
#include "BTAdvertisedDevice.h"
//#include "BTScan.h"
BTAdvertisedDeviceSet::BTAdvertisedDeviceSet() {
m_cod = 0;
m_name = "";
m_rssi = 0;
m_haveCOD = false;
m_haveName = false;
m_haveRSSI = false;
} // BTAdvertisedDeviceSet
BTAddress BTAdvertisedDeviceSet::getAddress() { return m_address; }
uint32_t BTAdvertisedDeviceSet::getCOD() const { return m_cod; }
std::string BTAdvertisedDeviceSet::getName() const { return m_name; }
int8_t BTAdvertisedDeviceSet::getRSSI() const { return m_rssi; }
bool BTAdvertisedDeviceSet::haveCOD() const { return m_haveCOD; }
bool BTAdvertisedDeviceSet::haveName() const { return m_haveName; }
bool BTAdvertisedDeviceSet::haveRSSI() const { return m_haveRSSI; }
/**
* @brief Create a string representation of this device.
* @return A string representation of this device.
*/
std::string BTAdvertisedDeviceSet::toString() {
std::string res = "Name: " + getName() + ", Address: " + getAddress().toString();
if (haveCOD()) {
char val[6];
snprintf(val, sizeof(val), "%d", getCOD());
res += ", cod: ";
res += val;
}
if (haveRSSI()) {
char val[6];
snprintf(val, sizeof(val), "%d", (int8_t)getRSSI());
res += ", rssi: ";
res += val;
}
return res;
} // toString
void BTAdvertisedDeviceSet::setAddress(BTAddress address) {
m_address = address;
}
void BTAdvertisedDeviceSet::setCOD(uint32_t cod) {
m_cod = cod;
m_haveCOD = true;
}
void BTAdvertisedDeviceSet::setName(std::string name) {
m_name = name;
m_haveName = true;
}
void BTAdvertisedDeviceSet::setRSSI(int8_t rssi) {
m_rssi = rssi;
m_haveRSSI = true;
}
#endif /* CONFIG_BT_ENABLED */

View File

@ -0,0 +1,42 @@
/*
* BTScan.h
*
* Created on: Feb 5, 2021
* Author: Thomas M. (ArcticSnowSky)
*/
#ifndef __BTSCAN_H__
#define __BTSCAN_H__
#include <map>
#include <string>
#include <Print.h>
#include "BTAddress.h"
#include "BTAdvertisedDevice.h"
class BTAdvertisedDevice;
class BTAdvertisedDeviceSet;
class BTScanResults {
public:
virtual ~BTScanResults() = default;
virtual void dump(Print *print = nullptr);
virtual int getCount();
virtual BTAdvertisedDevice* getDevice(int i);
};
class BTScanResultsSet : public BTScanResults {
public:
void dump(Print *print = nullptr);
int getCount();
BTAdvertisedDevice* getDevice(int i);
bool add(BTAdvertisedDeviceSet advertisedDevice, bool unique = true);
void clear();
std::map<std::string, BTAdvertisedDeviceSet> m_vectorAdvertisedDevices;
};
#endif

View File

@ -0,0 +1,95 @@
/*
* BTScanResultsSet.cpp
*
* Created on: Feb 5, 2021
* Author: Thomas M. (ArcticSnowSky)
*/
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
#include <esp_err.h>
#include "BTAdvertisedDevice.h"
#include "BTScan.h"
//#include "GeneralUtils.h"
#include "esp32-hal-log.h"
class BTAdvertisedDevice;
/**
* @brief Dump the scan results to the log.
*/
void BTScanResultsSet::dump(Print *print) {
int cnt = getCount();
if (print == nullptr) {
log_v(">> Dump scan results : %d", cnt);
for (int i=0; i < cnt; i++) {
BTAdvertisedDevice* dev = getDevice(i);
if (dev)
log_d("- %d: %s\n", i+1, dev->toString().c_str());
else
log_d("- %d is null\n", i+1);
}
log_v("-- dump finished --");
} else {
print->printf(">> Dump scan results: %d\n", cnt);
for (int i=0; i < cnt; i++) {
BTAdvertisedDevice* dev = getDevice(i);
if (dev)
print->printf("- %d: %s\n", i+1, dev->toString().c_str());
else
print->printf("- %d is null\n", i+1);
}
print->println("-- Dump finished --");
}
} // dump
/**
* @brief Return the count of devices found in the last scan.
* @return The number of devices found in the last scan.
*/
int BTScanResultsSet::getCount() {
return m_vectorAdvertisedDevices.size();
} // getCount
/**
* @brief Return the specified device at the given index.
* The index should be between 0 and getCount()-1.
* @param [in] i The index of the device.
* @return The device at the specified index.
*/
BTAdvertisedDevice* BTScanResultsSet::getDevice(int i) {
if (i < 0)
return nullptr;
int x = 0;
BTAdvertisedDeviceSet* pDev = &m_vectorAdvertisedDevices.begin()->second;
for (auto it = m_vectorAdvertisedDevices.begin(); it != m_vectorAdvertisedDevices.end(); it++) {
pDev = &it->second;
if (x==i) break;
x++;
}
return x==i ? pDev : nullptr;
}
void BTScanResultsSet::clear() {
//for(auto _dev : m_vectorAdvertisedDevices)
// delete _dev.second;
m_vectorAdvertisedDevices.clear();
}
bool BTScanResultsSet::add(BTAdvertisedDeviceSet advertisedDevice, bool unique) {
std::string key = advertisedDevice.getAddress().toString();
if (!unique || m_vectorAdvertisedDevices.count(key) == 0) {
m_vectorAdvertisedDevices.insert(std::pair<std::string, BTAdvertisedDeviceSet>(key, advertisedDevice));
return true;
} else
return false;
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,95 @@
// Copyright 2018 Evandro Luis Copercini
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _BLUETOOTH_SERIAL_H_
#define _BLUETOOTH_SERIAL_H_
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
#include "Arduino.h"
#include "Stream.h"
#include <esp_gap_bt_api.h>
#include <esp_spp_api.h>
#include <functional>
#include <map>
#include "BTScan.h"
typedef std::function<void(const uint8_t *buffer, size_t size)> BluetoothSerialDataCb;
typedef std::function<void(uint32_t num_val)> ConfirmRequestCb;
typedef std::function<void(boolean success)> AuthCompleteCb;
typedef std::function<void(BTAdvertisedDevice* pAdvertisedDevice)> BTAdvertisedDeviceCb;
class BluetoothSerial: public Stream
{
public:
BluetoothSerial(void);
~BluetoothSerial(void);
bool begin(String localName=String(), bool isMaster=false);
bool begin(unsigned long baud){//compatibility
return begin();
}
int available(void);
int peek(void);
bool hasClient(void);
int read(void);
size_t write(uint8_t c);
size_t write(const uint8_t *buffer, size_t size);
void flush();
void end(void);
void setTimeout(int timeoutMS);
void onData(BluetoothSerialDataCb cb);
esp_err_t register_callback(esp_spp_cb_t * callback);
void onConfirmRequest(ConfirmRequestCb cb);
void onAuthComplete(AuthCompleteCb cb);
void confirmReply(boolean confirm);
void enableSSP();
bool setPin(const char *pin);
bool connect(String remoteName);
bool connect(uint8_t remoteAddress[], int channel=0, esp_spp_sec_t sec_mask=(ESP_SPP_SEC_ENCRYPT|ESP_SPP_SEC_AUTHENTICATE), esp_spp_role_t role=ESP_SPP_ROLE_MASTER);
bool connect(const BTAddress &remoteAddress, int channel=0, esp_spp_sec_t sec_mask=(ESP_SPP_SEC_ENCRYPT|ESP_SPP_SEC_AUTHENTICATE), esp_spp_role_t role=ESP_SPP_ROLE_MASTER) {
return connect(*remoteAddress.getNative(), channel, sec_mask); };
bool connect();
bool connected(int timeout=0);
bool isClosed();
bool isReady(bool checkMaster=false, int timeout=0);
bool disconnect();
bool unpairDevice(uint8_t remoteAddress[]);
BTScanResults* discover(int timeout=0x30*1280);
bool discoverAsync(BTAdvertisedDeviceCb cb, int timeout=0x30*1280);
void discoverAsyncStop();
void discoverClear();
BTScanResults* getScanResults();
std::map<int, std::string> getChannels(const BTAddress &remoteAddress);
const int INQ_TIME = 1280; // Inquire Time unit 1280 ms
const int MIN_INQ_TIME = (ESP_BT_GAP_MIN_INQ_LEN * INQ_TIME);
const int MAX_INQ_TIME = (ESP_BT_GAP_MAX_INQ_LEN * INQ_TIME);
operator bool() const;
private:
String local_name;
int timeoutTicks=0;
};
#endif
#endif