-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButtonDetector.swift
More file actions
44 lines (38 loc) · 1.27 KB
/
Copy pathButtonDetector.swift
File metadata and controls
44 lines (38 loc) · 1.27 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
import Foundation
/// Wykrywanie kliknięcia z BLE (`0x22`, bajt [1], zbocze 0→1).
@MainActor
/// Wykrywa zbocze narastające przycisku w strumieniu BLE.
final class ButtonDetector {
/// Ostatnia wartość bajtu przycisku odebrana z pakietu.
private(set) var lastSeenButtonByte: UInt8 = 0
private var lastButton: UInt8 = 0
private var pendingClick = false
/// Informuje, czy oczekuje nieodebrany impuls kliknięcia.
var didClick: Bool { pendingClick }
/// Przetwarza pojedynczy pakiet BLE i wykrywa zbocze 0→1.
func process(_ data: [UInt8]) {
guard !data.isEmpty else { return }
if data.count > BLEButtonDecoder.buttonIndex, data[0] == BLEButtonDecoder.packetHeader {
lastSeenButtonByte = data[BLEButtonDecoder.buttonIndex]
}
if BLEButtonDecoder.risingEdgeAnywhere(in: data, lastButton: &lastButton) {
pendingClick = true
}
}
/// Ustawia oczekujący impuls (np. z TrikiParser preset v2).
func latchClick() {
pendingClick = true
}
/// Jednorazowe odczytanie impulsu kliknięcia (co klatkę).
func consumeClick() -> Bool {
let edge = pendingClick
pendingClick = false
return edge
}
/// Resetuje stan detektora kliknięć.
func reset() {
lastButton = 0
lastSeenButtonByte = 0
pendingClick = false
}
}