esp-nimble-cpp 2.6.0
Loading...
Searching...
No Matches
NimBLEScan.h
1/*
2 * Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
3 * esp-nimble-cpp, NimBLE-Arduino contributors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#ifndef NIMBLE_CPP_SCAN_H_
19#define NIMBLE_CPP_SCAN_H_
20
21#include "syscfg/syscfg.h"
22#if CONFIG_BT_NIMBLE_ENABLED && MYNEWT_VAL(BLE_ROLE_OBSERVER)
23
24# include "NimBLEAdvertisedDevice.h"
25# include "NimBLEUtils.h"
26
27# ifdef USING_NIMBLE_ARDUINO_HEADERS
28# include "nimble/nimble/host/include/host/ble_gap.h"
29# else
30# include "host/ble_gap.h"
31# endif
32
33# include <vector>
34# include <cinttypes>
35# include <cstdio>
36
37class NimBLEDevice;
38class NimBLEScan;
39class NimBLEAdvertisedDevice;
40class NimBLEScanCallbacks;
41class NimBLEAddress;
42
50class NimBLEScanResults {
51 public:
52 void dump() const;
53 int getCount() const;
54 const NimBLEAdvertisedDevice* getDevice(uint32_t idx) const;
55 const NimBLEAdvertisedDevice* getDevice(const NimBLEAddress& address) const;
56 std::vector<NimBLEAdvertisedDevice*>::const_iterator begin() const;
57 std::vector<NimBLEAdvertisedDevice*>::const_iterator end() const;
58
59 private:
60 friend NimBLEScan;
61 std::vector<NimBLEAdvertisedDevice*> m_deviceVec;
62};
63
69class NimBLEScan {
70 public:
71 bool start(uint32_t duration, bool isContinue = false, bool restart = true);
72 bool isScanning();
73 void setScanCallbacks(NimBLEScanCallbacks* pScanCallbacks, bool wantDuplicates = false);
74 void setActiveScan(bool active);
75 void setInterval(uint16_t intervalMs);
76 void setWindow(uint16_t windowMs);
77 void setDuplicateFilter(uint8_t enabled);
78 void setLimitedOnly(bool enabled);
79 void setFilterPolicy(uint8_t filter);
80 bool stop();
81 void clearResults();
82 NimBLEScanResults getResults();
83 NimBLEScanResults getResults(uint32_t duration, bool is_continue = false);
84 void setMaxResults(uint8_t maxResults);
85 void erase(const NimBLEAddress& address);
86 void erase(const NimBLEAdvertisedDevice* device);
87 void setScanResponseTimeout(uint32_t timeoutMs);
88 std::string getStatsString() const { return m_stats.toString(); }
89
90# if MYNEWT_VAL(BLE_EXT_ADV)
91 enum Phy { SCAN_1M = 0x01, SCAN_CODED = 0x02, SCAN_ALL = 0x03 };
92 void setPhy(Phy phyMask);
93 void setPeriod(uint32_t periodMs);
94# endif
95
96 private:
97 friend class NimBLEDevice;
98
99 struct stats {
100# if MYNEWT_VAL(NIMBLE_CPP_LOG_LEVEL) >= 4
101 uint32_t devCount = 0; // unique devices seen for the first time
102 uint32_t dupCount = 0; // repeat advertisements from already-known devices
103 uint32_t srMinMs = UINT32_MAX;
104 uint32_t srMaxMs = 0;
105 uint64_t srTotalMs = 0; // uint64 to avoid overflow on long/busy scans
106 uint32_t srCount = 0; // matched scan responses (advertisement + SR pair)
107 uint32_t orphanedSrCount = 0; // scan responses received with no prior advertisement
108 uint32_t missedSrCount = 0; // scannable devices for which no SR ever arrived
109
110 void reset() {
111 devCount = 0;
112 dupCount = 0;
113 srMinMs = UINT32_MAX;
114 srMaxMs = 0;
115 srTotalMs = 0;
116 srCount = 0;
117 orphanedSrCount = 0;
118 missedSrCount = 0;
119 }
120
121 void incDevCount() { devCount++; }
122 void incDupCount() { dupCount++; }
123 void incMissedSrCount() { missedSrCount++; }
124 void incOrphanedSrCount() { orphanedSrCount++; }
125
126 std::string toString() const {
127 std::string out;
128 out.resize(400); // should be more than enough for the stats string
129 snprintf(&out[0],
130 out.size(),
131 "Scan stats:\n"
132 " Devices seen : %" PRIu32
133 "\n"
134 " Duplicate advs : %" PRIu32
135 "\n"
136 " Scan responses : %" PRIu32
137 "\n"
138 " SR timing (ms) : min=%" PRIu32 ", max=%" PRIu32 ", avg=%" PRIu64
139 "\n"
140 " Orphaned SR : %" PRIu32
141 "\n"
142 " Missed SR : %" PRIu32 "\n",
143 devCount,
144 dupCount,
145 srCount,
146 srCount ? srMinMs : 0,
147 srCount ? srMaxMs : 0,
148 srCount ? srTotalMs / srCount : 0,
149 orphanedSrCount,
150 missedSrCount);
151 return out;
152 }
153
154 // Records scan-response round-trip time.
155 void recordSrTime(uint32_t ticks) {
156 uint32_t ms;
157 ble_npl_time_ticks_to_ms(ticks, &ms);
158
159 if (ms < srMinMs) {
160 srMinMs = ms;
161 }
162 if (ms > srMaxMs) {
163 srMaxMs = ms;
164 }
165 srTotalMs += ms;
166 srCount++;
167 return;
168 }
169# else
170 void reset() {}
171 void incDevCount() {}
172 void incDupCount() {}
173 void incMissedSrCount() {}
174 void incOrphanedSrCount() {}
175 std::string toString() const { return ""; }
176 void recordSrTime(uint32_t ticks) {}
177# endif
178 } m_stats;
179
180 NimBLEScan();
181 ~NimBLEScan();
182 static int handleGapEvent(ble_gap_event* event, void* arg);
183 void onHostSync();
184 void onHostDeinit();
185 static void srTimerCb(ble_npl_event* event);
186
187 // Linked list helpers for devices awaiting scan responses
188 void addWaitingDevice(NimBLEAdvertisedDevice* pDev);
189 void removeWaitingDevice(NimBLEAdvertisedDevice* pDev);
190 void clearWaitingList();
191 void resetWaitingTimer();
192
193 NimBLEScanCallbacks* m_pScanCallbacks;
194 ble_gap_disc_params m_scanParams;
195 NimBLEScanResults m_scanResults;
196 NimBLEUtils::TaskData* m_pTaskData;
197 ble_npl_callout m_srTimer{};
198 bool m_srTimerInitialized{false};
199 ble_npl_time_t m_srTimeoutTicks{};
200 uint8_t m_maxResults;
201 NimBLEAdvertisedDevice* m_pWaitingListHead{}; // head of linked list for devices awaiting scan responses
202 NimBLEAdvertisedDevice* m_pWaitingListTail{}; // tail of linked list for FIFO ordering
203
204# if MYNEWT_VAL(BLE_EXT_ADV)
205 uint8_t m_phy{SCAN_ALL};
206 uint16_t m_period{0};
207# endif
208};
209
213class NimBLEScanCallbacks {
214 public:
215 virtual ~NimBLEScanCallbacks() {}
216
221 virtual void onDiscovered(const NimBLEAdvertisedDevice* advertisedDevice);
222
227 virtual void onResult(const NimBLEAdvertisedDevice* advertisedDevice);
228
234 virtual void onScanEnd(const NimBLEScanResults& scanResults, int reason);
235};
236
237#endif // CONFIG_BT_NIMBLE_ENABLED MYNEWT_VAL(BLE_ROLE_OBSERVER)
238#endif // NIMBLE_CPP_SCAN_H_
A BLE device address.
Definition NimBLEAddress.h:42
A model of a BLE Device from which all the BLE roles are created.
Definition NimBLEDevice.h:120
A structure to hold data for a task that is waiting for a response.
Definition NimBLEUtils.h:78