@mentra/bluetooth-sdk 3.5.0-dev.1518 → 3.5.0-dev.1520
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION.md +9 -0
- package/README.md +64 -11
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +10 -0
- package/build/BluetoothSdk.types.d.ts +23 -5
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js +5 -0
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_internal.d.ts +1 -0
- package/build/_internal.d.ts.map +1 -1
- package/build/_internal.js +1 -0
- package/build/_internal.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +20 -9
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts +21 -0
- package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
- package/build/_private/MentraLocalNetworkModule.js.map +1 -1
- package/build/generated/releaseMetadata.js +5 -5
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/glasses-wifi/connection.d.ts +6 -0
- package/build/glasses-wifi/connection.d.ts.map +1 -0
- package/build/glasses-wifi/connection.js +44 -0
- package/build/glasses-wifi/connection.js.map +1 -0
- package/build/glasses-wifi/continuous.d.ts +39 -0
- package/build/glasses-wifi/continuous.d.ts.map +1 -0
- package/build/glasses-wifi/continuous.js +151 -0
- package/build/glasses-wifi/continuous.js.map +1 -0
- package/build/glasses-wifi/files.d.ts +11 -0
- package/build/glasses-wifi/files.d.ts.map +1 -0
- package/build/glasses-wifi/files.js +33 -0
- package/build/glasses-wifi/files.js.map +1 -0
- package/build/glasses-wifi/index.d.ts +20 -0
- package/build/glasses-wifi/index.d.ts.map +1 -0
- package/build/glasses-wifi/index.js +15 -0
- package/build/glasses-wifi/index.js.map +1 -0
- package/build/glasses-wifi/link.d.ts +31 -0
- package/build/glasses-wifi/link.d.ts.map +1 -0
- package/build/glasses-wifi/link.js +71 -0
- package/build/glasses-wifi/link.js.map +1 -0
- package/build/glasses-wifi/native.d.ts +63 -0
- package/build/glasses-wifi/native.d.ts.map +1 -0
- package/build/glasses-wifi/native.js +138 -0
- package/build/glasses-wifi/native.js.map +1 -0
- package/build/glasses-wifi/service.d.ts +86 -0
- package/build/glasses-wifi/service.d.ts.map +1 -0
- package/build/glasses-wifi/service.js +497 -0
- package/build/glasses-wifi/service.js.map +1 -0
- package/build/index.d.ts +4 -2
- package/build/index.d.ts.map +1 -1
- package/build/index.js +24 -6
- package/build/index.js.map +1 -1
- package/build/ota-transport/index.d.ts +2 -43
- package/build/ota-transport/index.d.ts.map +1 -1
- package/build/ota-transport/index.js +3 -49
- package/build/ota-transport/index.js.map +1 -1
- package/build/react/useBluetoothStatus.d.ts.map +1 -1
- package/build/react/useBluetoothStatus.js +5 -24
- package/build/react/useBluetoothStatus.js.map +1 -1
- package/build/react/useMentraBluetooth.d.ts +1 -2
- package/build/react/useMentraBluetooth.d.ts.map +1 -1
- package/build/react/useMentraBluetooth.js +0 -1
- package/build/react/useMentraBluetooth.js.map +1 -1
- package/expo-module.config.json +1 -1
- package/ios/MentraBluetoothSDK.podspec +5 -4
- package/ios/MentraLocalNetworkModule.swift +264 -0
- package/ios/Source/BluetoothSdkDefaults.swift +1 -1
- package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
- package/ios/Source/hotspot/GlassesHotspotNetwork.swift +563 -0
- package/ios/Source/hotspot/HotspotAccessPurpose.swift +5 -0
- package/ios/Source/hotspot/HotspotAddressPolicy.swift +50 -0
- package/ios/Source/hotspot/HotspotInterfacePolicy.swift +155 -0
- package/ios/Source/hotspot/HotspotJoinFailure.swift +27 -0
- package/ios/Source/hotspot/HotspotLeaveCompletion.swift +24 -0
- package/ios/Source/hotspot/HotspotNetworkOwnership.swift +22 -0
- package/ios/Source/hotspot/HotspotReapplyPolicy.swift +26 -0
- package/ios/Source/hotspot/LocalNetworkAccessRequest.swift +160 -0
- package/ios/Source/hotspot/MacHotspotAssociation.swift +415 -0
- package/ios/Source/hotspot/MacHotspotAuthorization.swift +126 -0
- package/ios/Source/hotspot/MacHotspotAuthorizationFacts.swift +51 -0
- package/ios/Source/hotspot/MacHotspotCleanupContinuation.swift +35 -0
- package/ios/Tests/HotspotAddressPolicyTests.swift +30 -0
- package/ios/Tests/HotspotInterfacePolicyTests.swift +304 -0
- package/ios/Tests/HotspotJoinFailureTests.swift +37 -0
- package/ios/Tests/HotspotLeaveCompletionTests.swift +29 -0
- package/ios/Tests/HotspotReapplyPolicyTests.swift +18 -0
- package/ios/Tests/LocalNetworkAccessRequestTests.swift +237 -0
- package/ios/Tests/MacHotspotAssociationTests.swift +521 -0
- package/ios/Tests/MacHotspotAuthorizationFactsTests.swift +62 -0
- package/ios/Tests/MacHotspotAuthorizationTests.swift +348 -0
- package/ios/Tests/MacWifiInvocationTests.swift +76 -0
- package/package.json +7 -2
- package/plugin/build/withIos.d.ts +4 -0
- package/plugin/build/withIos.js +20 -1
- package/src/BluetoothSdk.types.ts +27 -5
- package/src/_internal.ts +1 -0
- package/src/_private/BluetoothSdkModule.ts +20 -10
- package/src/_private/MentraLocalNetworkModule.ts +22 -0
- package/src/generated/releaseMetadata.ts +5 -5
- package/src/glasses-wifi/connection.ts +47 -0
- package/src/glasses-wifi/continuous.ts +177 -0
- package/src/glasses-wifi/files.ts +32 -0
- package/src/glasses-wifi/index.ts +24 -0
- package/src/glasses-wifi/link.ts +94 -0
- package/src/glasses-wifi/native.ts +193 -0
- package/src/glasses-wifi/service.ts +554 -0
- package/src/index.ts +34 -10
- package/src/ota-transport/index.ts +3 -85
- package/src/react/useBluetoothStatus.ts +5 -26
- package/src/react/useMentraBluetooth.ts +0 -3
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// One IPv4 address row reported by `getifaddrs`.
|
|
4
|
+
public struct HotspotInterfaceAddress: Equatable {
|
|
5
|
+
public let name: String
|
|
6
|
+
public let isUp: Bool
|
|
7
|
+
public let ipv4: String
|
|
8
|
+
|
|
9
|
+
public init(name: String, isUp: Bool, ipv4: String) {
|
|
10
|
+
self.name = name
|
|
11
|
+
self.isUp = isUp
|
|
12
|
+
self.ipv4 = ipv4
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/// One `getifaddrs` sample: every attached interface's kernel index (its `AF_LINK` row, present
|
|
17
|
+
/// with or without an IPv4 address) and every IPv4 address row.
|
|
18
|
+
public struct HotspotInterfaceSnapshot: Equatable {
|
|
19
|
+
public let links: [String: Int]
|
|
20
|
+
public let addresses: [HotspotInterfaceAddress]
|
|
21
|
+
/// Attached interfaces whose `AF_LINK` type is `IFT_ETHER`. Apple platforms report Wi-Fi and
|
|
22
|
+
/// wired Ethernet this way; cellular, VPN tunnel and loopback links have other types.
|
|
23
|
+
public let ethernetLinks: Set<String>
|
|
24
|
+
|
|
25
|
+
public init(links: [String: Int], addresses: [HotspotInterfaceAddress], ethernetLinks: Set<String> = []) {
|
|
26
|
+
self.links = links
|
|
27
|
+
self.addresses = addresses
|
|
28
|
+
self.ethernetLinks = ethernetLinks
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/// Network framework's type for one interface on one evaluated path.
|
|
33
|
+
public struct HotspotInterfaceReport: Equatable {
|
|
34
|
+
public let name: String
|
|
35
|
+
public let index: Int
|
|
36
|
+
public let isWifi: Bool
|
|
37
|
+
|
|
38
|
+
public init(name: String, index: Int, isWifi: Bool) {
|
|
39
|
+
self.name = name
|
|
40
|
+
self.index = index
|
|
41
|
+
self.isWifi = isWifi
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/// The Wi-Fi interface carrying the glasses hotspot and the DHCP address it held when verified.
|
|
46
|
+
public struct HotspotInterfaceBinding: Hashable {
|
|
47
|
+
public let interface: String
|
|
48
|
+
public let index: Int
|
|
49
|
+
public let address: String
|
|
50
|
+
|
|
51
|
+
public init(interface: String, index: Int, address: String) {
|
|
52
|
+
self.interface = interface
|
|
53
|
+
self.index = index
|
|
54
|
+
self.address = address
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// Wi-Fi identity learned during one hotspot session. Create a new value for every join.
|
|
59
|
+
///
|
|
60
|
+
/// A path's interface list describes routes, not hardware: after Wi-Fi moves to an AP without
|
|
61
|
+
/// internet, both the default and the Wi-Fi-constrained path can omit it. An interface's type
|
|
62
|
+
/// does not change while it stays attached, so a positive Wi-Fi report is kept for the same
|
|
63
|
+
/// name and kernel index until that interface is detached or replaced. Omission from a later
|
|
64
|
+
/// report is not evidence. Any non-Wi-Fi report for a name rejects it for the rest of the session.
|
|
65
|
+
public struct HotspotWifiIdentity: Equatable {
|
|
66
|
+
public private(set) var trusted: [String: Int] = [:]
|
|
67
|
+
public private(set) var rejected: Set<String> = []
|
|
68
|
+
/// Trusted names later seen detached or replaced. A fresh report may trust the name again
|
|
69
|
+
/// for discovery, but an address verified before the change stays lost.
|
|
70
|
+
public private(set) var detached: Set<String> = []
|
|
71
|
+
|
|
72
|
+
public init() {}
|
|
73
|
+
|
|
74
|
+
public mutating func observe(_ reports: [HotspotInterfaceReport]) {
|
|
75
|
+
for report in reports where !report.isWifi {
|
|
76
|
+
rejected.insert(report.name)
|
|
77
|
+
trusted[report.name] = nil
|
|
78
|
+
}
|
|
79
|
+
for report in reports where report.isWifi && !report.name.isEmpty && report.index > 0 && !rejected.contains(report.name) {
|
|
80
|
+
// A new index means a different interface took the name; only this report vouches for it.
|
|
81
|
+
if let index = trusted[report.name], index != report.index { detached.insert(report.name) }
|
|
82
|
+
trusted[report.name] = report.index
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// Forget an interface that is no longer attached, or whose name now has another index.
|
|
87
|
+
/// Only a new positive report can re-establish it.
|
|
88
|
+
public mutating func observe(_ snapshot: HotspotInterfaceSnapshot) {
|
|
89
|
+
for (name, index) in trusted where snapshot.links[name] != index {
|
|
90
|
+
trusted[name] = nil
|
|
91
|
+
detached.insert(name)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Pin a binding chosen from hotspot client evidence (see `HotspotInterfacePolicy.select`)
|
|
96
|
+
/// as this session's Wi-Fi interface. It then ends exactly like a reported one.
|
|
97
|
+
public mutating func adopt(_ binding: HotspotInterfaceBinding) {
|
|
98
|
+
guard !rejected.contains(binding.interface), !detached.contains(binding.interface) else { return }
|
|
99
|
+
trusted[binding.interface] = binding.index
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// Wi-Fi is not always `en0`: a Mac can have built-in Ethernet on `en0` and Wi-Fi on `en1`.
|
|
104
|
+
/// Identify the hotspot link by interface type and address, never by name or by the first
|
|
105
|
+
/// private address, and keep that exact interface for the rest of the session.
|
|
106
|
+
public enum HotspotInterfacePolicy {
|
|
107
|
+
/// The unique up IPv4 address, on an interface this session trusts as Wi-Fi and that is still
|
|
108
|
+
/// attached with the same index, that can be the hotspot client. With a BLE-reported gateway
|
|
109
|
+
/// it must be a valid client on that gateway's /24. Missing or ambiguous candidates return nil.
|
|
110
|
+
///
|
|
111
|
+
/// A phone on cellular has no Wi-Fi path when the join starts, and after association iOS
|
|
112
|
+
/// leaves the internet-less glasses AP out of both paths, so no Wi-Fi report ever arrives.
|
|
113
|
+
/// Only when the session has no trusted Wi-Fi interface, the hotspot client address is the
|
|
114
|
+
/// evidence instead: the unique valid client of the BLE gateway's /24 on an attached
|
|
115
|
+
/// Ethernet-type link that no path has reported as non-Wi-Fi. Callers bind it only after the
|
|
116
|
+
/// glasses SSID matched, then require a connection from it to reach the gateway, and must
|
|
117
|
+
/// `adopt` it so the session pins that interface.
|
|
118
|
+
public static func select(snapshot: HotspotInterfaceSnapshot, identity: HotspotWifiIdentity,
|
|
119
|
+
gateway: String?) -> HotspotInterfaceBinding?
|
|
120
|
+
{
|
|
121
|
+
if !identity.trusted.isEmpty {
|
|
122
|
+
return unique(snapshot, gateway: gateway) { identity.trusted[$0] }
|
|
123
|
+
}
|
|
124
|
+
guard let gateway else { return nil }
|
|
125
|
+
return unique(snapshot, gateway: gateway) { name in
|
|
126
|
+
guard snapshot.ethernetLinks.contains(name), !identity.rejected.contains(name),
|
|
127
|
+
!identity.detached.contains(name) else { return nil }
|
|
128
|
+
return snapshot.links[name]
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private static func unique(_ snapshot: HotspotInterfaceSnapshot, gateway: String?,
|
|
133
|
+
index eligibleIndex: (String) -> Int?) -> HotspotInterfaceBinding?
|
|
134
|
+
{
|
|
135
|
+
let bindings = Set(snapshot.addresses.compactMap { row -> HotspotInterfaceBinding? in
|
|
136
|
+
guard let index = eligibleIndex(row.name), snapshot.links[row.name] == index,
|
|
137
|
+
row.isUp, HotspotAddressPolicy.isPrivate(row.ipv4) else { return nil }
|
|
138
|
+
if let gateway, !HotspotAddressPolicy.isHotspotClientAddress(row.ipv4, gateway: gateway) { return nil }
|
|
139
|
+
return HotspotInterfaceBinding(interface: row.name, index: index, address: row.ipv4)
|
|
140
|
+
})
|
|
141
|
+
return bindings.count == 1 ? bindings.first : nil
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/// A verified link remains usable only while the same attached interface is up with the same
|
|
145
|
+
/// address. Later path reports may omit it. Another interface acquiring that address, a
|
|
146
|
+
/// detach or replacement under the same name, or a non-Wi-Fi report ends it for the session.
|
|
147
|
+
/// Pass an identity that has already observed `snapshot`.
|
|
148
|
+
public static func isIntact(_ binding: HotspotInterfaceBinding, snapshot: HotspotInterfaceSnapshot,
|
|
149
|
+
identity: HotspotWifiIdentity) -> Bool
|
|
150
|
+
{
|
|
151
|
+
guard identity.trusted[binding.interface] == binding.index, !identity.detached.contains(binding.interface),
|
|
152
|
+
snapshot.links[binding.interface] == binding.index else { return false }
|
|
153
|
+
return snapshot.addresses.contains { $0.name == binding.interface && $0.isUp && $0.ipv4 == binding.address }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Explicit bridge facts; never forward native userInfo or arbitrary NSError descriptions.
|
|
4
|
+
public struct HotspotJoinFailure {
|
|
5
|
+
public let code: String
|
|
6
|
+
public let message: String
|
|
7
|
+
|
|
8
|
+
public init(_ error: Error) {
|
|
9
|
+
if error is CancellationError || (error as? HotspotError)?.message == "Hotspot join cancelled" {
|
|
10
|
+
code = "ERR_HOTSPOT_CANCELLED"
|
|
11
|
+
message = "Hotspot join cancelled"
|
|
12
|
+
} else if let local = error as? HotspotError {
|
|
13
|
+
code = "ERR_HOTSPOT_JOIN"
|
|
14
|
+
// These messages are authored by the owned hotspot implementation, not NSError.
|
|
15
|
+
message = String(local.message.filter { !$0.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) }.prefix(512))
|
|
16
|
+
} else if (error as NSError).domain == "NEHotspotConfigurationErrorDomain", (error as NSError).code == 7 {
|
|
17
|
+
// NEHotspotConfigurationError.userDenied: the person declined the join prompt.
|
|
18
|
+
code = "ERR_HOTSPOT_USER_DENIED"
|
|
19
|
+
message = "The glasses hotspot join was declined"
|
|
20
|
+
} else {
|
|
21
|
+
code = "ERR_HOTSPOT_NATIVE"
|
|
22
|
+
let native = error as NSError
|
|
23
|
+
let domain = native.domain.range(of: "^[A-Za-z0-9_.-]{1,128}$", options: .regularExpression) == nil ? "unavailable" : native.domain
|
|
24
|
+
message = "Hotspot join failed (\(domain), \(native.code))"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/// Queue-confined completion of one leave. Concurrent callers share cleanup;
|
|
2
|
+
/// the original ownership token is released before any caller can start again.
|
|
3
|
+
public final class HotspotLeaveCompletion {
|
|
4
|
+
private var replies: [(Result<Void, Error>) -> Void] = []
|
|
5
|
+
private var pending = true
|
|
6
|
+
private let release: () -> Void
|
|
7
|
+
|
|
8
|
+
public init(release: @escaping () -> Void) {
|
|
9
|
+
self.release = release
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
public func append(_ reply: @escaping (Result<Void, Error>) -> Void) {
|
|
13
|
+
replies.append(reply)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
public func complete(_ result: Result<Void, Error>) {
|
|
17
|
+
guard pending else { return }
|
|
18
|
+
pending = false
|
|
19
|
+
if case .success = result { release() }
|
|
20
|
+
let current = replies
|
|
21
|
+
replies.removeAll()
|
|
22
|
+
current.forEach { $0(result) }
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// One process-wide writer across OTA, gallery and native media sessions.
|
|
4
|
+
/// Callers release only after native association and owned cleanup have ended.
|
|
5
|
+
final class HotspotNetworkOwnership {
|
|
6
|
+
static let shared = HotspotNetworkOwnership()
|
|
7
|
+
private let lock = NSLock()
|
|
8
|
+
private var owner: UUID?
|
|
9
|
+
|
|
10
|
+
func acquire() -> UUID? {
|
|
11
|
+
lock.lock(); defer { lock.unlock() }
|
|
12
|
+
guard owner == nil else { return nil }
|
|
13
|
+
let token = UUID()
|
|
14
|
+
owner = token
|
|
15
|
+
return token
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
func release(_ token: UUID) {
|
|
19
|
+
lock.lock(); defer { lock.unlock() }
|
|
20
|
+
if owner == token { owner = nil }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// When to ask iOS again to join the glasses hotspot.
|
|
4
|
+
///
|
|
5
|
+
/// iOS accepts a hotspot configuration and then makes one short directed scan for it. When that
|
|
6
|
+
/// scan misses the glasses' beacon, iOS shows "Unable to join the network", stays on the current
|
|
7
|
+
/// Wi-Fi and still reports the configuration as applied. Only the phone's current network shows
|
|
8
|
+
/// that the join failed, so a request that has not put the phone on the hotspot after a few
|
|
9
|
+
/// seconds is made again, a bounded number of times, within the join's overall deadline.
|
|
10
|
+
public struct HotspotReapplyPolicy {
|
|
11
|
+
/// Polls of the current network, half a second apart, before a request counts as missed.
|
|
12
|
+
public let pollsBeforeReapply: Int
|
|
13
|
+
/// Requests in one join, the first included.
|
|
14
|
+
public let maxApplies: Int
|
|
15
|
+
|
|
16
|
+
public init(pollsBeforeReapply: Int = 16, maxApplies: Int = 3) {
|
|
17
|
+
self.pollsBeforeReapply = pollsBeforeReapply
|
|
18
|
+
self.maxApplies = maxApplies
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/// Whether to request the join again, with the phone not on the hotspot after `pollsSinceApply`
|
|
22
|
+
/// polls of the `applies`-th request.
|
|
23
|
+
public func shouldReapply(applies: Int, pollsSinceApply: Int) -> Bool {
|
|
24
|
+
applies < maxApplies && pollsSinceApply >= pollsBeforeReapply
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import Network
|
|
3
|
+
|
|
4
|
+
protocol LocalNetworkAccessConnection: AnyObject {
|
|
5
|
+
var onState: ((NWConnection.State, NWPath.UnsatisfiedReason?) -> Void)? { get set }
|
|
6
|
+
func start(queue: DispatchQueue)
|
|
7
|
+
func cancel()
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/// Wait for permission to use the verified local route before starting timed media work.
|
|
11
|
+
/// Connect to the glasses' existing gallery HTTP endpoint to prove local access (TN3179).
|
|
12
|
+
/// Network.framework retries when access is granted. A denied path can also mean that the
|
|
13
|
+
/// alert is still open, so it must not be treated as a terminal error or given a media timeout.
|
|
14
|
+
/// macOS also reports a denied path for about a second and a half right after the Mac joins the
|
|
15
|
+
/// glasses' hotspot, with access granted, while it re-applies its policies to the new network.
|
|
16
|
+
/// The caller is told only when the path stays denied for `permissionGrace`.
|
|
17
|
+
/// Ordinary connection setup has a 30-second budget, paused while permission is required.
|
|
18
|
+
public final class LocalNetworkAccessRequest {
|
|
19
|
+
static let permissionGrace: TimeInterval = 5
|
|
20
|
+
private let queue: DispatchQueue
|
|
21
|
+
private let connection: LocalNetworkAccessConnection
|
|
22
|
+
private let now: () -> TimeInterval
|
|
23
|
+
private let scheduleTimeout: (TimeInterval, DispatchWorkItem) -> Void
|
|
24
|
+
private var remainingConnectivityTime: TimeInterval = 30
|
|
25
|
+
private var timeoutDeadline: TimeInterval?
|
|
26
|
+
private var timeoutWork: DispatchWorkItem?
|
|
27
|
+
private var completion: ((Result<Void, Error>) -> Void)?
|
|
28
|
+
private var waiting: ((String) -> Void)?
|
|
29
|
+
private var permissionWork: DispatchWorkItem?
|
|
30
|
+
private var finished = false
|
|
31
|
+
private var reportedPermission = false
|
|
32
|
+
|
|
33
|
+
public convenience init(localAddress: String, gateway: String, queue: DispatchQueue) {
|
|
34
|
+
self.init(connection: LocalNetworkPermissionConnection(localAddress: localAddress, gateway: gateway), queue: queue)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
init(connection: LocalNetworkAccessConnection, queue: DispatchQueue,
|
|
38
|
+
now: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime },
|
|
39
|
+
scheduleTimeout: ((TimeInterval, DispatchWorkItem) -> Void)? = nil)
|
|
40
|
+
{
|
|
41
|
+
self.connection = connection
|
|
42
|
+
self.queue = queue
|
|
43
|
+
self.now = now
|
|
44
|
+
self.scheduleTimeout = scheduleTimeout ?? { delay, work in queue.asyncAfter(deadline: .now() + delay, execute: work) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// `onPermissionRequired` gets the system's answer, for logs, once the path has stayed denied.
|
|
48
|
+
public func start(onPermissionRequired: @escaping (_ systemAnswer: String) -> Void,
|
|
49
|
+
completion: @escaping (Result<Void, Error>) -> Void)
|
|
50
|
+
{
|
|
51
|
+
queue.async {
|
|
52
|
+
guard !self.finished, self.completion == nil else { return }
|
|
53
|
+
self.completion = completion
|
|
54
|
+
self.waiting = onPermissionRequired
|
|
55
|
+
self.connection.onState = { [weak self] state, reason in
|
|
56
|
+
guard let self, !self.finished else { return }
|
|
57
|
+
switch state {
|
|
58
|
+
case .ready: self.finish(.success(()))
|
|
59
|
+
case .waiting where reason == .localNetworkDenied:
|
|
60
|
+
self.pauseConnectivityTimeout()
|
|
61
|
+
self.reportPermissionIfStillDenied(state)
|
|
62
|
+
// Waiting errors are nonfatal; NWConnection retries when its path recovers.
|
|
63
|
+
// A nil path is not proof of denied permission, but must not fail immediately.
|
|
64
|
+
case .setup, .preparing, .waiting:
|
|
65
|
+
self.cancelPermissionReport()
|
|
66
|
+
self.resumeConnectivityTimeout()
|
|
67
|
+
case let .failed(error): self.finish(.failure(error))
|
|
68
|
+
case .cancelled: self.finish(.failure(CancellationError()))
|
|
69
|
+
@unknown default: break
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
self.resumeConnectivityTimeout()
|
|
73
|
+
self.connection.start(queue: self.queue)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
public func cancel() {
|
|
78
|
+
queue.async { self.finish(.failure(CancellationError())) }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private func reportPermissionIfStillDenied(_ state: NWConnection.State) {
|
|
82
|
+
guard !reportedPermission, permissionWork == nil else { return }
|
|
83
|
+
let grace = Self.permissionGrace
|
|
84
|
+
let work = DispatchWorkItem { [weak self] in
|
|
85
|
+
guard let self, !self.finished, self.permissionWork != nil else { return }
|
|
86
|
+
self.permissionWork = nil
|
|
87
|
+
self.reportedPermission = true
|
|
88
|
+
self.waiting?("NWConnection \(state) unsatisfiedReason=localNetworkDenied for \(Int(grace))s")
|
|
89
|
+
}
|
|
90
|
+
permissionWork = work
|
|
91
|
+
scheduleTimeout(grace, work)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private func cancelPermissionReport() {
|
|
95
|
+
permissionWork?.cancel()
|
|
96
|
+
permissionWork = nil
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private func resumeConnectivityTimeout() {
|
|
100
|
+
guard timeoutDeadline == nil else { return }
|
|
101
|
+
let deadline = now() + remainingConnectivityTime
|
|
102
|
+
timeoutDeadline = deadline
|
|
103
|
+
let work = DispatchWorkItem { [weak self] in
|
|
104
|
+
guard let self, self.timeoutDeadline == deadline else { return }
|
|
105
|
+
self.finish(.failure(HotspotError("Local connection to the glasses timed out")))
|
|
106
|
+
}
|
|
107
|
+
timeoutWork = work
|
|
108
|
+
scheduleTimeout(remainingConnectivityTime, work)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private func pauseConnectivityTimeout() {
|
|
112
|
+
if let deadline = timeoutDeadline { remainingConnectivityTime = max(0, deadline - now()) }
|
|
113
|
+
timeoutDeadline = nil
|
|
114
|
+
timeoutWork?.cancel()
|
|
115
|
+
timeoutWork = nil
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private func finish(_ result: Result<Void, Error>) {
|
|
119
|
+
guard !finished else { return }
|
|
120
|
+
finished = true
|
|
121
|
+
pauseConnectivityTimeout()
|
|
122
|
+
cancelPermissionReport()
|
|
123
|
+
connection.onState = nil
|
|
124
|
+
connection.cancel()
|
|
125
|
+
let reply = completion
|
|
126
|
+
completion = nil
|
|
127
|
+
waiting = nil
|
|
128
|
+
reply?(result)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private final class LocalNetworkPermissionConnection: LocalNetworkAccessConnection {
|
|
133
|
+
var onState: ((NWConnection.State, NWPath.UnsatisfiedReason?) -> Void)?
|
|
134
|
+
private let connection: NWConnection
|
|
135
|
+
|
|
136
|
+
init(localAddress: String, gateway: String) {
|
|
137
|
+
let parameters = NWParameters.tcp
|
|
138
|
+
parameters.requiredLocalEndpoint = .hostPort(host: NWEndpoint.Host(localAddress), port: .any)
|
|
139
|
+
connection = NWConnection(host: NWEndpoint.Host(gateway), port: 8089, using: parameters)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
func start(queue: DispatchQueue) {
|
|
143
|
+
connection.stateUpdateHandler = { [weak self] state in
|
|
144
|
+
guard let self else { return }
|
|
145
|
+
onState?(state, connection.currentPath?.unsatisfiedReason)
|
|
146
|
+
}
|
|
147
|
+
// The path reason can arrive after a waiting update with no currentPath yet.
|
|
148
|
+
connection.pathUpdateHandler = { [weak self] path in
|
|
149
|
+
guard let self else { return }
|
|
150
|
+
onState?(connection.state, path.unsatisfiedReason)
|
|
151
|
+
}
|
|
152
|
+
connection.start(queue: queue)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
func cancel() {
|
|
156
|
+
connection.stateUpdateHandler = nil
|
|
157
|
+
connection.pathUpdateHandler = nil
|
|
158
|
+
connection.cancel()
|
|
159
|
+
}
|
|
160
|
+
}
|