forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathble.cpp
More file actions
65 lines (53 loc) · 1.53 KB
/
Copy pathble.cpp
File metadata and controls
65 lines (53 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "omi/device/ble.hpp"
#include <mutex>
#include <stdexcept>
#include <utility>
namespace omi {
namespace device {
namespace {
std::mutex& BackendMutex() {
static std::mutex mu;
return mu;
}
std::shared_ptr<BleBackend>& BackendSlot() {
static std::shared_ptr<BleBackend> backend;
return backend;
}
std::shared_ptr<BleBackend> RequireBackend() {
auto backend = GetBleBackend();
if (!backend) {
throw BleDisabled();
}
return backend;
}
} // namespace
void SetBleBackend(std::shared_ptr<BleBackend> backend) {
std::lock_guard<std::mutex> lock(BackendMutex());
BackendSlot() = std::move(backend);
}
std::shared_ptr<BleBackend> GetBleBackend() {
std::lock_guard<std::mutex> lock(BackendMutex());
return BackendSlot();
}
std::vector<BleDevice> Scan(int timeout_ms) {
return RequireBackend()->Scan(timeout_ms < 0 ? 0 : timeout_ms);
}
void Listen(const std::string& device_id, PacketCallback callback) {
if (!callback) {
throw std::invalid_argument("Listen callback is empty");
}
RequireBackend()->Notify(device_id, kServiceUuid, kAudioDataUuid, std::move(callback));
}
void ListenPayload(const std::string& device_id, PacketCallback callback) {
if (!callback) {
throw std::invalid_argument("ListenPayload callback is empty");
}
Listen(device_id, [callback = std::move(callback)](const std::vector<std::uint8_t>& packet) {
auto payload = StripPacketHeader(packet.data(), packet.size());
if (!payload.empty()) {
callback(payload);
}
});
}
} // namespace device
} // namespace omi