-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDeviceRegistry.swift
More file actions
224 lines (190 loc) · 8.21 KB
/
Copy pathDeviceRegistry.swift
File metadata and controls
224 lines (190 loc) · 8.21 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/*
* Copyright 2025, OpenRemote Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import Foundation
import ESPProvision
import os
protocol ORESPProvisionManager {
func searchESPDevices(devicePrefix: String, transport: ESPTransport, security: ESPSecurity) async throws -> [ORESPDevice]
func stopESPDevicesSearch()
}
struct EspressifProvisionManager: ORESPProvisionManager {
var provisionManager: ESPProvisionManager = ESPProvisionManager.shared
public func searchESPDevices(devicePrefix: String, transport: ESPTransport, security: ESPSecurity = .secure) async throws -> [ORESPDevice] {
return try await withCheckedThrowingContinuation { continuation in
// We want to protect ourself against multiple resume of the continuation
// This happened because searchESPDevices would call its callback a second time with an error when explicitly stopping the device search
// even after the search has already completed with a list of device
var alreadyResumed = false
provisionManager.searchESPDevices(devicePrefix: devicePrefix, transport: transport, security: security) { deviceList, error in
if let error {
if !alreadyResumed {
alreadyResumed = true
continuation.resume(throwing: error)
}
} else {
alreadyResumed = true
continuation.resume(returning: deviceList ?? [])
}
}
}
}
public func stopESPDevicesSearch() {
provisionManager.stopESPDevicesSearch()
}
}
class DeviceRegistry {
private static let logger = Logger(
subsystem: Bundle.main.bundleIdentifier!,
category: String(describing: ESPProvisionProvider.self)
)
var callbackChannel: CallbackChannel?
private let timeSource: any TimeSource
private var loopDetector: LoopDetector
var searchDeviceTimeout: TimeInterval {
get {
loopDetector.timeout
}
set {
self.loopDetector.timeout = newValue
}
}
var searchDeviceMaxIterations: Int {
get {
loopDetector.maxIterations
}
set {
self.loopDetector.maxIterations = newValue
}
}
private var devices: [DiscoveredDevice] = []
private var devicesIndex: [UUID: DiscoveredDevice] = [:]
// TODO: check if here or some place else or how to be set ?
var provisionManager: ORESPProvisionManager?
public private(set) var bleScanning = false
init(searchDeviceTimeout: TimeInterval, searchDeviceMaxIterations: Int, timeSource: any TimeSource = SystemTimeSource()) {
self.timeSource = timeSource
self.loopDetector = LoopDetector(timeout: searchDeviceTimeout, maxIterations: searchDeviceMaxIterations, timeSource: timeSource)
}
func enable() {
provisionManager = EspressifProvisionManager(provisionManager: ESPProvisionManager.shared)
}
func disable() {
if bleScanning {
stopDevicesScan()
}
provisionManager = nil
}
public func startDevicesScan(prefix: String? = nil) {
resetDevicesList()
loopDetector.reset()
if !bleScanning {
bleScanning = true
devicesScan(prefix: prefix ?? "")
}
}
public func stopDevicesScan(sendMessage: Bool = true) {
bleScanning = false
provisionManager?.stopESPDevicesSearch()
if sendMessage {
callbackChannel?.sendMessage(action: Actions.stopBleScan, data: nil)
}
}
private func devicesScan(prefix: String) {
if let provisionManager {
Task {
do {
if loopDetector.detectLoop() {
self.stopDevicesScan(sendMessage: false)
sendDeviceScanError(ESPProviderErrorCode.timeoutError)
return
}
Self.logger.trace("devicesScan will searchESPDevices")
let deviceList = try await provisionManager.searchESPDevices(devicePrefix: prefix, transport: .ble, security: .secure)
Self.logger.trace("devicesScan return from searchESPDevices")
if self.bleScanning { // If we're not scanning anymore, we don't report back
var devicesChanged = false
for device in deviceList where self.getDeviceNamed(device.name) == nil {
// We need to assign an id to each device, so web app can refer to it
// At this stage, we name is also unique but having an id would allow duplicates at some point
devicesChanged = true
let dev = DiscoveredDevice(device: device)
self.registerDevice(dev)
}
// If there are devices in the list and the list changed since the last time, we communicated to web app
if !self.devices.isEmpty && devicesChanged {
callbackChannel?.sendMessage(action: Actions.startBleScan, data: ["devices": self.devices.map(\.info)])
}
self.devicesScan(prefix: prefix)
}
} catch {
Self.logger.warning("Error during device scan: \(error.localizedDescription)")
// The only error applicable to us here is espDeviceNotFound, we don't care about it
// All other possible errors are about camera for QR code or Soft AP
// Still be cautious about that and don't loop the scan for these kinds of errors
if let cssError = error as? ESPDeviceCSSError {
if case .espDeviceNotFound = cssError {
if self.bleScanning {
self.devicesScan(prefix: prefix)
}
} else { sendDeviceScanError(ESPProviderErrorCode.genericError) }
} else { sendDeviceScanError(ESPProviderErrorCode.genericError) }
// TODO: seems we can't have BLE permissions error here, but want to test
}
}
}
}
private func sendDeviceScanError(_ error: ESPProviderErrorCode, errorMessage: String? = nil) {
var data: [String: Any] = ["errorCode": error.rawValue]
if let errorMessage {
data["errorMessage"] = errorMessage
}
callbackChannel?.sendMessage(action: Actions.stopBleScan, data: data)
}
private func resetDevicesList() {
devices = []
devicesIndex = [:]
}
private func getDeviceNamed(_ name: String) -> DiscoveredDevice? {
return devices.first(where: { $0.device.name == name })
}
func getDeviceWithId(_ id: UUID) -> DiscoveredDevice? {
return devicesIndex[id]
}
private func registerDevice(_ device: DiscoveredDevice) {
devices.append(device)
devicesIndex[device.id] = device
}
}
// TODO
/*private*/ struct DiscoveredDevice: Hashable, Equatable {
var id = UUID()
var device: ORESPDevice
func hash(into hasher: inout Hasher) {
hasher.combine(device.name)
}
static func == (lhs: DiscoveredDevice, rhs: DiscoveredDevice) -> Bool {
lhs.device.name == rhs.device.name
}
var info: [String: Any] {
[
"id": id.uuidString,
"name": device.name
]
}
}