/
SensorSettingView.swift
274 lines (230 loc) · 8.1 KB
/
SensorSettingView.swift
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//
// SensorSettingView.swift
// Komusou
//
// Created by gurrium on 2022/03/25.
//
import Combine
import CoreBluetooth
import SwiftUI
struct SensorSettingView: View {
@ObservedObject
private var state = SensorSettingViewState()
var body: some View {
List {
Row(
isSheetPresented: $state.isSpeedSensorSheetPresented,
itemLabel: "スピードセンサー",
valueLabel: state.speedSensorName
) {
SensorSelectingView(didError: $state.didError, didSelectSensor: state.connectToSpeedSensor(uuid:))
}
// TODO: ケイデンスセンサー
}
.listStyle(.insetGrouped)
}
private struct Row<Content: View>: View {
@Binding
var isSheetPresented: Bool
let itemLabel: String
let valueLabel: String
@ViewBuilder
let sheetContent: () -> Content
var body: some View {
Button {
isSheetPresented = true
} label: {
HStack {
Text(itemLabel)
Spacer()
Text(valueLabel)
.foregroundColor(.secondary)
}
}
.sheet(isPresented: $isSheetPresented, content: sheetContent)
.tint(.primary)
}
}
}
final class SensorSettingViewState: ObservableObject {
@Published
private(set) var speedSensorName = ""
@Published
var isSpeedSensorSheetPresented = false
@Published
var didError = false
private var cancellables = Set<AnyCancellable>()
init() {
BluetoothManager.shared.$connectedSpeedSensor.map { $0?.name ?? "" }.assign(to: &$speedSensorName)
}
func connectToSpeedSensor(uuid: UUID) {
BluetoothManager.shared.connectToSpeedSensor(uuid: uuid).sink { [unowned self] result in
switch result {
case .failure:
self.didError = true
case .finished:
break
}
} receiveValue: { [unowned self] _ in
self.isSpeedSensorSheetPresented = false
}
.store(in: &cancellables)
}
}
struct SensorSelectingView: View {
@ObservedObject
private var state = SensorSelectingViewState()
private var didSelectSensor: (UUID) -> Void
@Binding
private var didError: Bool
init(didError: Binding<Bool>, didSelectSensor: @escaping (UUID) -> Void) {
_didError = didError
self.didSelectSensor = didSelectSensor
}
var body: some View {
List {
Section {
if !state.sensors.isEmpty {
ForEach(state.sensors, id: \.0) { item in
Button {
didSelectSensor(item.0)
} label: {
Text(item.1)
}
}
}
} header: {
HStack(spacing: 8) {
Text("センサー")
ProgressView()
}
}
}
.listStyle(.insetGrouped)
.alert("接続に失敗しました", isPresented: $didError) {}
.onAppear(perform: state.startScanningSensors)
.onDisappear(perform: state.stopScanningSensors)
}
}
final class SensorSelectingViewState: ObservableObject {
@Published
var sensors: [(UUID, String)] = []
private var cancellables = Set<AnyCancellable>()
init() {
BluetoothManager.shared.$discoveredPeripherals.map { peripherals in
peripherals.compactMap { peripheral in
guard let name = peripheral.value.name else { return nil }
return (peripheral.key, name)
}
}.assign(to: &$sensors)
}
func startScanningSensors() {
BluetoothManager.shared.startScanningSensors()
}
func stopScanningSensors() {
BluetoothManager.shared.stopScanningSensors()
}
}
struct SensorSettingView_Previews: PreviewProvider {
static var previews: some View {
SensorSettingView()
}
}
// TODO: モックできるようにする
final class BluetoothManager: NSObject {
struct ConnectingWithPeripheralError: Error {}
typealias ConnectingWithPeripheralFuture = Future<Void, ConnectingWithPeripheralError>
static let shared = BluetoothManager()
private static let kSpeedSensorKey = "speed_sensor_key"
@Published
private(set) var discoveredPeripherals = [UUID: CBPeripheral]()
@Published
private(set) var connectedSpeedSensor: CBPeripheral?
private var connectedSpeedSensorUUID: UUID? {
get {
if let uuid = _connectedSpeedSensorUUID { return uuid }
let retrieved = UUID(uuidString: userDefaults.string(forKey: Self.kSpeedSensorKey) ?? "")
_connectedSpeedSensorUUID = retrieved
return retrieved
}
set {
_connectedSpeedSensorUUID = newValue
if let newValue = newValue {
userDefaults.set(newValue.uuidString, forKey: Self.kSpeedSensorKey)
} else {
userDefaults.removeObject(forKey: Self.kSpeedSensorKey)
}
}
}
private var _connectedSpeedSensorUUID: UUID?
private var connectingSpeedSensorUUID: UUID?
private var isBluetoothEnabled: Bool {
centralManager.state == .poweredOn
}
private var speedSensorPromise: ConnectingWithPeripheralFuture.Promise?
private var cancellables = Set<AnyCancellable>()
private let centralManager = CBCentralManager()
private let userDefaults = UserDefaults.standard
override init() {
super.init()
// TODO: 起動時の処理
// Bluetoothの許可の確認
// 以前接続したセンサーに接続する
centralManager.delegate = self
$connectedSpeedSensor.sink { [unowned self] sensor in
self.connectedSpeedSensorUUID = sensor?.identifier
}
.store(in: &cancellables)
}
deinit {
// TODO: disconnect
}
func startScanningSensors() {
guard isBluetoothEnabled, !centralManager.isScanning else { return }
// TODO: デバッグが終わったら self.centralManager.scanForPeripherals(withServices: [.cyclingSpeedAndCadence], options: nil) にする
centralManager.scanForPeripherals(withServices: nil, options: nil)
}
func stopScanningSensors() {
discoveredPeripherals.removeAll()
centralManager.stopScan()
}
func connectToSpeedSensor(uuid: UUID) -> ConnectingWithPeripheralFuture {
guard let peripheral = discoveredPeripherals[uuid] else {
return .init { $0(.failure(.init())) }
}
if let speedSensor = connectedSpeedSensor {
centralManager.cancelPeripheralConnection(speedSensor)
}
connectingSpeedSensorUUID = uuid
centralManager.connect(peripheral)
return .init { [weak self] promise in
self?.speedSensorPromise = promise
}
}
}
extension BluetoothManager: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_: CBCentralManager) {}
func centralManager(_: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData _: [String: Any], rssi _: NSNumber) {
discoveredPeripherals[peripheral.identifier] = peripheral
}
func centralManager(_: CBCentralManager, didConnect peripheral: CBPeripheral) {
switch peripheral.identifier {
case connectingSpeedSensorUUID:
connectingSpeedSensorUUID = nil
connectedSpeedSensor = peripheral
speedSensorPromise?(.success(()))
default:
centralManager.cancelPeripheralConnection(peripheral)
}
}
func centralManager(_: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error _: Error?) {
switch peripheral.identifier {
case connectingSpeedSensorUUID:
connectingSpeedSensorUUID = nil
speedSensorPromise?(.failure(.init()))
default:
break
}
}
}
extension BluetoothManager: CBPeripheralDelegate {}