-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMotionSDK+Connection.swift
More file actions
402 lines (359 loc) · 12.9 KB
/
Copy pathMotionSDK+Connection.swift
File metadata and controls
402 lines (359 loc) · 12.9 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import Combine
import Foundation
private let motionHudPublishInterval: TimeInterval = 0.12
private let buttonClickHighlightDuration: TimeInterval = 0.12
/// Adds focused motion sdk helpers.
extension MotionSDK {
/// Skan BLE + auto-connect do jedynego urządzenia z „triki” w nazwie.
public func connect() {
ensureBLEPipeline()
trikiController?.ble.autoConnectWhenSingleLikelyMatch = true
trikiController?.connect()
}
/// Ponowne połączenie z ostatnim zapamiętanym urządzeniem (bez pełnego skanu).
public func connectLastDevice() {
ensureBLEPipeline()
trikiController?.ble.autoConnectWhenSingleLikelyMatch = false
trikiController?.ble.connectCachedPeripheralIfAvailable()
}
/// Zamyka połączenie BLE i czyści stan sesji.
public func disconnect() {
bleManager?.disconnect()
resetConnectionState()
}
/// Wywołuj co klatkę gry (~60 Hz) po `connect()` — zwraca gotowy `GameInput`.
@discardableResult
/// Handles `pollInput`.
///
/// - Parameters:
/// - deltaTime: Input used by this operation.
/// - Returns: Result produced by this operation.
public func pollInput(deltaTime: TimeInterval? = nil) -> GameInput {
trikiController?.tick(deltaTime: deltaTime)
applyTrikiGamepadToEngine()
let now = Date().timeIntervalSince1970
guard let parser = streamParser else {
updateFrame(deltaTime: deltaTime)
let buttonClick = resolveButtonClick(impulses: (false, false), now: now)
var copy = input
copy.bleButtonClick = buttonClick
if config.mode == .paddle {
copy.primaryAction = buttonClick
} else if buttonClick {
copy.primaryAction = copy.primaryAction || buttonClick
}
latestEnrichedInput = copy
return copy
}
let stale = trikiBLEMode.packetStaleSeconds
if now - lastPacketAt > stale, isReceiving { isReceiving = false }
syncTrikiPublishedState()
if config.mode == .paddle {
parser.refreshTiltSensors()
parser.flushImpulsesOnly()
let impulses = parser.consumeImpulses()
let out = updateFrame(deltaTime: deltaTime)
let buttonClick = resolveButtonClick(impulses: impulses, now: now)
var enriched = makeEnrichedGameInput(
output: out,
sdkInput: input,
parser: parser,
impulses: impulses,
buttonClick: buttonClick
)
applyTrikiGamepadSignals(&enriched)
finalizeAdaptiveInput(&enriched)
latestEnrichedInput = enriched
publishLiveInputIfNeeded(now: now, input: enriched)
return enriched
}
parser.flush()
setIngressSupplement(
rotation: parser.sensors.rotation,
tiltX: parser.sensors.tiltX,
gyroY: parser.sensors.gyroY
)
let out = updateFrame(deltaTime: deltaTime)
let impulses = parser.consumeImpulses()
let buttonClick = resolveButtonClick(impulses: impulses, now: now)
var enriched = makeEnrichedGameInput(
output: out,
sdkInput: input,
parser: parser,
impulses: impulses,
buttonClick: buttonClick
)
applyTrikiGamepadSignals(&enriched)
finalizeAdaptiveInput(&enriched)
latestEnrichedInput = enriched
publishLiveInputIfNeeded(now: now, input: enriched)
return enriched
}
/// Pobiera ostatnią wzbogaconą ramkę wejścia bez aktualizacji stanu.
public func snapshotInput() -> GameInput { latestEnrichedInput }
/// Czyści impuls przycisku BLE po wejściu w menu (unika fałszywego „WSTECZ” / OK).
public func discardStaleButtonInput() {
_ = button.consumeClick()
buttonClickHighlightUntil = 0
lastSampledButtonByte = button.lastSeenButtonByte
streamParser?.discardPendingImpulses()
}
/// Kalibruje neutralną pozycję na podstawie bieżących danych.
public func calibrateNeutralPose() {
_ = pollInput()
engine.calibrateCenter()
engine.resetPaddleMotion()
refreshLiveInputFromEngine()
}
/// Resetuje środek paletki.
public func resetPaddleCenter() {
engine.resetCenter()
refreshLiveInputFromEngine()
}
/// Odwraca znak offsetu paletki.
public func flipPaddleOffsetSign() {
engine.flipPaddleOffsetSign()
refreshLiveInputFromEngine()
}
// MARK: - DEV / BLE diagnostics
/// Włącza logowanie surowych bajtów BLE.
public var debugBLEBytes: Bool {
get { bleManager?.debugRXBytes ?? false }
set { bleManager?.debugRXBytes = newValue }
}
/// Włącza logowanie całych pakietów BLE w trybie deweloperskim.
public var logBLEPacketsInDevMode: Bool {
get { bleManager?.logRXPacketsInDevMode ?? false }
set { bleManager?.logRXPacketsInDevMode = newValue }
}
/// Bufor logów BLE z aktualnej sesji.
public var bleDevLog: [String] { bleManager?.devRawLog ?? [] }
/// Narzędzie do analizy zmian bajtów między pakietami BLE.
public var bleByteProbe: BLEByteProbe { bleManager?.byteProbe ?? BLEByteProbe() }
/// Resetuje stan analizatora bajtów BLE i czyści log.
public func resetBLEProbe() {
bleManager?.byteProbe.reset()
bleManager?.devRawLog.removeAll()
}
/// Czyści bufor logów BLE.
public func clearBLEDevLog() { bleManager?.devRawLog.removeAll() }
/// Czy zapisano UUID ostatniego urządzenia (szybkie ponowne połączenie).
public var hasCachedBLEDevice: Bool {
bleManager?.cachedPeripheralUUID != nil
}
/// Log monitora trybu BLE (Δt między pakietami).
public var debugBLEMonitorLogging: Bool {
get { trikiController?.debugBLEMonitorLogging ?? false }
set { trikiController?.debugBLEMonitorLogging = newValue }
}
// MARK: - Private
/// Handles `ensureBLEPipeline`.
func ensureBLEPipeline() {
guard trikiController == nil else { return }
let triki = TrikiGameController()
let parser = MotionParser()
parser.retainRecentFrames = false
trikiController = triki
bleManager = triki.ble
streamParser = parser
triki.ble.rxBytes
.receive(on: DispatchQueue.main)
.sink { [weak self] bytes in
guard let self, !bytes.isEmpty else { return }
self.enqueueBLE(bytes)
self.streamParser?.enqueue(data: bytes)
self.lastPacketAt = Date().timeIntervalSince1970
}
.store(in: &bleCancellables)
triki.$isConnected
.removeDuplicates()
.sink { [weak self] connected in
self?.isConnected = connected
if !connected { self?.resetConnectionState() }
}
.store(in: &bleCancellables)
triki.$bleMode
.removeDuplicates()
.sink { [weak self] mode in
self?.trikiBLEMode = mode
}
.store(in: &bleCancellables)
triki.$idleStatusMessage
.sink { [weak self] message in
self?.trikiIdleStatusMessage = message
}
.store(in: &bleCancellables)
triki.$isReceiving
.removeDuplicates()
.sink { [weak self] receiving in
self?.isReceiving = receiving
}
.store(in: &bleCancellables)
}
func syncTrikiPublishedState() {
guard let triki = trikiController else { return }
trikiBLEMode = triki.getBLEMode()
trikiIdleStatusMessage = triki.idleStatusMessage
}
/// Handles `resetConnectionState`.
func resetConnectionState() {
streamParser?.resetStream()
trikiController?.resetSession()
reset()
liveInput = GameInput()
latestEnrichedInput = GameInput()
isReceiving = false
trikiBLEMode = .unknown
trikiIdleStatusMessage = nil
lastHudPublishAt = 0
lastFramePosX = nil
lastFramePosY = nil
}
/// Mapuje wyjście gamepada na silnik pozycji (bez surowych osi w API gry).
func applyTrikiGamepadToEngine() {
guard let triki = trikiController else { return }
let pad = triki.gameInput
if config.mode == .paddle {
let scaled = Double(pad.direction) * BLEGyroParser.gyroDivisor
engine.setRawX(scaled)
} else {
engine.updateRaw(x: Double(pad.direction), y: Double(pad.velocity))
}
}
/// Handles `refreshLiveInputFromEngine`.
func refreshLiveInputFromEngine() {
let out = output
var enriched = makeEnrichedGameInput(
output: out,
sdkInput: input,
parser: streamParser,
impulses: (false, false)
)
applyTrikiGamepadSignals(&enriched)
finalizeAdaptiveInput(&enriched)
latestEnrichedInput = enriched
liveInput = enriched
lastHudPublishAt = Date().timeIntervalSince1970
}
/// Handles `publishLiveInputIfNeeded`.
///
/// - Parameters:
/// - now: Input used by this operation.
/// - input: Input used by this operation.
func publishLiveInputIfNeeded(now: TimeInterval, input: GameInput) {
guard now - lastHudPublishAt >= motionHudPublishInterval else { return }
lastHudPublishAt = now
liveInput = input
}
/// Applies Triki gamepad velocity/tilt edges to `GameInput` (all tryby gier).
func applyTrikiGamepadSignals(_ input: inout GameInput) {
guard let pad = trikiController?.gameInput else { return }
input.tiltLeft = pad.isTiltLeft
input.tiltRight = pad.isTiltRight
let vel = Double(pad.velocity)
input.trikiVelocity = vel
input.isMoving = pad.isMoving
input.intensity = max(input.intensity, vel)
input.flick = input.flick || pad.isSwing
let dir = Double(pad.direction)
if dir != 0, vel > 0.5 {
input.deltaX = dir * vel * 0.012
}
}
/// Uzupełnia `bleMode`, Δpos i strategię adaptacyjną dla gier.
func finalizeAdaptiveInput(_ input: inout GameInput) {
input.bleMode = trikiBLEMode
let prevX = lastFramePosX ?? input.posX
let prevY = lastFramePosY ?? input.posY
input.frameDeltaX = input.posX - prevX
input.frameDeltaY = input.posY - prevY
lastFramePosX = input.posX
lastFramePosY = input.posY
}
/// Jednorazowe zebranie impulsu przycisku BLE na końcu `pollInput` (nie w `publishInput`).
func resolveButtonClick(impulses: (click: Bool, shake: Bool), now: TimeInterval) -> Bool {
if trikiController?.consumeButtonEdge() == true {
button.latchClick()
}
let packetEdge = button.consumeClick()
let currentByte = button.lastSeenButtonByte
let levelEdge = BLEButtonDecoder.isPressed(currentByte)
&& !BLEButtonDecoder.isPressed(lastSampledButtonByte)
lastSampledButtonByte = currentByte
let freshEdge = packetEdge || impulses.click || levelEdge
if freshEdge {
buttonClickHighlightUntil = now + buttonClickHighlightDuration
}
return freshEdge || now < buttonClickHighlightUntil
}
/// Builds a UI/game-friendly input snapshot from raw engine output and parser state.
///
/// - Parameters:
/// - output: Current processed motion output frame.
/// - sdkInput: Base input snapshot that will be enriched.
/// - parser: Optional parser containing latest sensor payload.
/// - impulses: Edge-triggered click/shake impulses for this frame.
/// - buttonClick: Resolved BLE button edge for this poll (includes short HUD latch).
/// - Returns: Enriched `GameInput` used by HUD and gameplay layers.
func makeEnrichedGameInput(
output: MotionOutput,
sdkInput: GameInput,
parser: MotionParser?,
impulses: (click: Bool, shake: Bool),
buttonClick: Bool = false
) -> GameInput {
let dbg = debug
var enriched = sdkInput
enriched.moveX = dbg.rawX
enriched.moveY = dbg.rawY
enriched.posX = output.x
enriched.posY = output.y
enriched.deltaX = dbg.relX
enriched.deltaY = dbg.relY
if let parser {
enriched.tiltX = parser.sensors.tiltX
enriched.tiltY = parser.sensors.tiltY
enriched.rotation = output.x
enriched.lateral = output.x
enriched.lateralSmooth = output.x
enriched.velocityY = dbg.relY
enriched.intensity = output.velocityX
enriched.shake = impulses.shake || (trikiController?.gameInput.isShake ?? false)
enriched.sensors = parser.sensors
enriched.pointerDirection = pointerDirection(posX: output.x, posY: output.y)
}
enriched.bleButtonClick = buttonClick
if config.mode == .paddle {
enriched.primaryAction = buttonClick
} else if buttonClick {
enriched.primaryAction = enriched.primaryAction || buttonClick
}
applyClickToSensors(&enriched, clickEdge: buttonClick)
return enriched
}
/// Sets one-shot click flag on sensors when a BLE button edge was detected.
func applyClickToSensors(_ input: inout GameInput, clickEdge: Bool) {
guard clickEdge else { return }
var sensors = input.sensors
sensors.click = true
input.sensors = sensors
}
/// Converts normalized pointer coordinates into a coarse cardinal direction.
///
/// - Parameters:
/// - posX: Normalized horizontal pointer position.
/// - posY: Normalized vertical pointer position.
/// - threshold: Deadzone threshold treated as centered pointer.
/// - Returns: Dominant pointer direction used by UI hints.
func pointerDirection(
posX: Double,
posY: Double,
threshold: Double = 0.08
) -> PointerDirection {
let absX = abs(posX)
let absY = abs(posY)
if absX < threshold, absY < threshold { return .center }
if absX >= absY { return posX < 0 ? .left : .right }
return posY < 0 ? .down : .up
}
}