Add BMA456 tap detection with ESP-NOW notify and host snapshot API.
Slaves forward configured tap kinds to the master; goTool exposes CLI, dashboard, REST, and WebSocket with separate notify vs receive and 2s display cache. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+111
-7
@@ -26,6 +26,8 @@ go run . -port /dev/ttyUSB0 clients
|
||||
| `clients` | `0x04` | Lists slaves registered on the master via ESP-NOW |
|
||||
| `deadzone` | `0x06` | Get/set accelerometer deadzone LSB (`-set`, `-value`, `-client`, `-all`) |
|
||||
| `accel` | `0x18` | Cached slave accel snapshot from master (`ACCEL_SNAPSHOT`); alias `accel-read` |
|
||||
| `tap-notify` | `0x1b` | Get/set which tap kinds (single/double/triple) notify via ESP-NOW (`-set`, `-client`, `-all`, `-single`, `-double`, `-triple`) |
|
||||
| `tap` | `0x1c` | Cached tap snapshot from master (`TAP_SNAPSHOT`); events ≤16 ms old |
|
||||
| `unicast-test` | `0x07` | Sends ESP-NOW unicast test to one slave (`-client`, `-seq`) |
|
||||
| `test` | — | Run an automated scenario (JSON configs under `testdata/`) |
|
||||
| `serve` | — | Web dashboard at `http://localhost:8080` (WebSocket live updates) |
|
||||
@@ -68,26 +70,42 @@ make gotool-serve PORT=/dev/ttyUSB0
|
||||
|
||||
Open [http://localhost:8080](http://localhost:8080) — shows master firmware info and the ESP-NOW client table from `CLIENT_INFO`.
|
||||
|
||||
**Tap (dashboard):** two independent controls per slave:
|
||||
|
||||
| Column | Meaning |
|
||||
|--------|---------|
|
||||
| Tap-Notify (S/D/T) | Which tap kinds the **slave** sends to the master over ESP-NOW (UART `TAP_NOTIFY`) — does **not** poll UART |
|
||||
| Tap (An/Aus) | Host **receive**: poll master tap cache (~16 ms) and show last tap for **≥2 s** |
|
||||
|
||||
Enable notify first, then turn receive on to see events. Same split as the external WebSocket API (`set_tap_notify` vs `set_tap_stream`).
|
||||
|
||||
### External API (second HTTP server)
|
||||
|
||||
`serve` starts a separate listener (default **`:8081`**, disable with `-api-addr ""`) for external programs. It shares the same UART connection as the dashboard.
|
||||
|
||||
| Endpoint | Description |
|
||||
|----------|-------------|
|
||||
| `GET /` or `GET /api/v1/` | JSON service info (`default_interval_ms`, min/max, `serial_port`) |
|
||||
| `WebSocket /ws` | Per-connection accel receive + interval; slave ESP-NOW stream control |
|
||||
| `GET /` or `GET /api/v1/` | JSON service info (`default_interval_ms`, min/max, `serial_port`, `tap_display_min_ms`) |
|
||||
| `WebSocket /ws` | Per-connection accel/tap receive + interval; slave ESP-NOW accel/tap control |
|
||||
|
||||
Two layers:
|
||||
**Accel** — two layers:
|
||||
|
||||
1. **`set_stream`** — this WebSocket connection: whether to receive `accel` JSON and at what poll rate (1 ms … 10 s per client; server UART poll uses the minimum among active subscribers).
|
||||
2. **`set_accel_stream`** — firmware: whether a slave sends accel to the master over ESP-NOW (16 ms on the pod).
|
||||
|
||||
Polling runs only when at least one connection has `receive_accel: true` **and** at least one slave streams (via `set_accel_stream` or dashboard `:8080`).
|
||||
Accel polling runs only when at least one connection has `receive_accel: true` **and** at least one slave streams (via `set_accel_stream` or dashboard `:8080`).
|
||||
|
||||
**Hello** (on connect; accel is off until `set_stream`):
|
||||
**Tap** — also two layers (notify alone does **not** poll UART):
|
||||
|
||||
1. **`set_tap_notify`** — firmware: which tap kinds (single/double/triple) the slave sends to the master over ESP-NOW.
|
||||
2. **`set_tap_stream`** — this WebSocket connection: poll `TAP_SNAPSHOT` and push `tap` JSON. Events stay visible for **`tap_display_min_ms`** (2000 ms) after first sight.
|
||||
|
||||
Tap polling runs only when at least one connection has `receive_tap: true` (via `set_tap_stream`).
|
||||
|
||||
**Hello** (on connect; accel/tap receive off until `set_stream` / `set_tap_stream`):
|
||||
|
||||
```json
|
||||
{"type":"hello","serial_port":"/dev/ttyUSB0","interval_ms":16,"commands":["set_stream","get_stream","set_accel_stream","get_accel_stream","set_led_ring","get_battery"]}
|
||||
{"type":"hello","serial_port":"/dev/ttyUSB0","interval_ms":16,"tap_display_min_ms":2000,"note":"set_tap_notify configures slave S/D/T only; set_tap_stream enables tap polling/push","commands":["set_stream","get_stream","set_accel_stream","get_accel_stream","set_tap_stream","get_tap_stream","set_tap_notify","get_tap_notify","set_led_ring","get_battery"]}
|
||||
```
|
||||
|
||||
**Receive accel on this connection** (optional `interval_ms`, default from `-accel-interval`):
|
||||
@@ -125,6 +143,38 @@ Reply:
|
||||
|
||||
Reply: `{"type":"led_ring_status","success":true,"slaves_updated":2,...}`
|
||||
|
||||
**Tap notify** (slave ESP-NOW config; per `client_id`, or `all_clients`):
|
||||
|
||||
```json
|
||||
{"type":"set_tap_notify","client_id":16,"single":true,"double_tap":false,"triple":false}
|
||||
{"type":"get_tap_notify","client_id":16}
|
||||
```
|
||||
|
||||
Reply:
|
||||
|
||||
```json
|
||||
{"type":"tap_notify_status","client_id":16,"success":true,"single":true,"double_tap":false,"triple":false}
|
||||
```
|
||||
|
||||
**Receive tap on this connection** (optional `interval_ms`; default from `-accel-interval`):
|
||||
|
||||
```json
|
||||
{"type":"set_tap_stream","enable":true,"interval_ms":16}
|
||||
{"type":"get_tap_stream"}
|
||||
```
|
||||
|
||||
Reply:
|
||||
|
||||
```json
|
||||
{"type":"tap_stream_status","receive_tap":true,"interval_ms":16,"success":true}
|
||||
```
|
||||
|
||||
**Tap events** (only to connections with `receive_tap: true`; each event shown ≥2 s):
|
||||
|
||||
```json
|
||||
{"type":"tap","port":"/dev/ttyUSB0","success":true,"events":[{"client_id":16,"kind":"single","age_ms":3,"shown_at_ms":1717000000123}]}
|
||||
```
|
||||
|
||||
**Accel** (only to connections with `receive_accel: true`, and only while slaves stream):
|
||||
|
||||
```json
|
||||
@@ -156,6 +206,28 @@ async def main():
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
Tap example (notify first, then enable stream on this connection):
|
||||
|
||||
```python
|
||||
import asyncio, json, websockets
|
||||
|
||||
async def main():
|
||||
async with websockets.connect("ws://127.0.0.1:8081/ws") as ws:
|
||||
print(await ws.recv()) # hello
|
||||
await ws.send(json.dumps({"type": "set_tap_notify", "client_id": 16,
|
||||
"single": True, "double_tap": False, "triple": False}))
|
||||
print(await ws.recv()) # tap_notify_status
|
||||
await ws.send(json.dumps({"type": "set_tap_stream", "enable": True, "interval_ms": 16}))
|
||||
print(await ws.recv()) # tap_stream_status
|
||||
while True:
|
||||
msg = json.loads(await ws.recv())
|
||||
if msg.get("type") == "tap" and msg.get("events"):
|
||||
for e in msg["events"]:
|
||||
print(e["client_id"], e["kind"], "age", e.get("age_ms"))
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
If the UART device is unplugged or the port disappears, `serve` keeps running and retries on each poll interval; the UI shows **UART off** until the port is available again.
|
||||
|
||||
The dashboard can configure nodes using the same UART commands as the CLI:
|
||||
@@ -167,7 +239,7 @@ The dashboard can configure nodes using the same UART commands as the CLI:
|
||||
| Alle Slaves | per-slave ESP-NOW (Master bleibt unverändert; CLI `-all` setzt auch den Master) |
|
||||
| Unicast test | `unicast-test -client ID` |
|
||||
|
||||
HTTP API (used by the web UI): `GET/POST /api/deadzone`, `GET/PUT /api/clients/{id}/accel-stream`, `POST /api/accel-stream` (legacy / `all_clients`), `GET/POST /api/battery`, `POST /api/led-ring`, `POST /api/unicast-test`, `POST /api/find-me`, `POST /api/restart`, `POST /api/ota` (multipart field `firmware`, max 2 MiB).
|
||||
HTTP API (used by the web UI): `GET/POST /api/deadzone`, `GET/PUT /api/clients/{id}/accel-stream`, `POST /api/accel-stream` (legacy / `all_clients`), `GET/PUT /api/clients/{id}/tap-notify`, `PUT /api/clients/{id}/tap-receive`, `GET/POST /api/tap-notify`, `GET /api/tap-snapshot`, `GET/POST /api/battery`, `POST /api/led-ring`, `POST /api/unicast-test`, `POST /api/find-me`, `POST /api/restart`, `POST /api/ota` (multipart field `firmware`, max 2 MiB).
|
||||
|
||||
**LED ring** (`POST /api/led-ring` and WebSocket `set_led_ring` on `:8081`):
|
||||
|
||||
@@ -203,6 +275,38 @@ Content-Type: application/json
|
||||
|
||||
Enable all slaves: `POST /api/accel-stream` with `{"write":true,"enable":true,"all_clients":true}`.
|
||||
|
||||
**Tap notify per slave** (slave → master ESP-NOW; does not start host polling):
|
||||
|
||||
```http
|
||||
GET /api/clients/16/tap-notify
|
||||
→ {"client_id":16,"success":true,"single":false,"double_tap":false,"triple":false}
|
||||
|
||||
PUT /api/clients/16/tap-notify
|
||||
Content-Type: application/json
|
||||
{"single": true, "double_tap": false, "triple": false}
|
||||
→ {"client_id":16,"success":true,"slaves_updated":1,"single":true,"double_tap":false,"triple":false}
|
||||
```
|
||||
|
||||
All slaves: `POST /api/tap-notify` with `{"single":true,"double_tap":false,"triple":false,"all_clients":true}`.
|
||||
|
||||
**Tap receive** (host-side; dashboard polls `TAP_SNAPSHOT` while enabled):
|
||||
|
||||
```http
|
||||
PUT /api/clients/16/tap-receive
|
||||
Content-Type: application/json
|
||||
{"enable": true}
|
||||
→ {"client_id":16,"enabled":true,"success":true}
|
||||
```
|
||||
|
||||
One-shot read (no receive flag): `GET /api/tap-snapshot?client_id=16` → `{"events":[{"client_id":16,"kind":"single","age_ms":4}]}`.
|
||||
|
||||
CLI:
|
||||
|
||||
```bash
|
||||
go run . -port /dev/ttyUSB0 tap-notify -client 16 -set -single
|
||||
go run . -port /dev/ttyUSB0 tap -client 16
|
||||
```
|
||||
|
||||
| UI / API | Behaviour |
|
||||
|----------|-----------|
|
||||
| Firmware OTA card | Same as `ota` CLI; WebSocket `ota_progress` with `step` `master` (UART) then `slaves` (ESP-NOW) |
|
||||
|
||||
+2
-1
@@ -67,8 +67,9 @@ type otaAPIResponse struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func mountServeAPI(mux *http.ServeMux, link *managedSerial, hub *wsHub, streamCtl *accelStreamCtl) {
|
||||
func mountServeAPI(mux *http.ServeMux, link *managedSerial, hub *wsHub, streamCtl *accelStreamCtl, tapCtl *tapNotifyCtl) {
|
||||
mountAccelStreamAPI(mux, link, hub, streamCtl)
|
||||
mountTapAPI(mux, link, hub, tapCtl)
|
||||
mountLedRingAPI(mux, link)
|
||||
mountBatteryAPI(mux, link)
|
||||
mux.HandleFunc("/api/deadzone", func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
+419
-77
@@ -17,6 +17,8 @@ const (
|
||||
defaultAccelStreamInterval = 16 * time.Millisecond
|
||||
minAPIStreamInterval = 1 * time.Millisecond
|
||||
maxAPIStreamInterval = 10 * time.Second
|
||||
// How long tap events stay in API push/cache after first sight (matches dashboard).
|
||||
apiTapDisplayMinMs = 2000
|
||||
)
|
||||
|
||||
// AccelClientSample is one slave's cached accel on the master.
|
||||
@@ -29,12 +31,14 @@ type AccelClientSample struct {
|
||||
AgeMs uint32 `json:"age_ms,omitempty"`
|
||||
}
|
||||
|
||||
// AccelStreamMessage is sent to external WebSocket clients.
|
||||
// AccelStreamMessage is sent to external WebSocket clients (hello + accel samples).
|
||||
type AccelStreamMessage struct {
|
||||
Type string `json:"type"` // "hello" | "accel"
|
||||
Serial string `json:"serial_port,omitempty"`
|
||||
IntervalMs int `json:"interval_ms,omitempty"`
|
||||
Commands []string `json:"commands,omitempty"`
|
||||
Type string `json:"type"` // "hello" | "accel"
|
||||
Serial string `json:"serial_port,omitempty"`
|
||||
IntervalMs int `json:"interval_ms,omitempty"`
|
||||
TapDisplayMinMs int `json:"tap_display_min_ms,omitempty"`
|
||||
Commands []string `json:"commands,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
|
||||
T int64 `json:"t,omitempty"` // Unix nanoseconds
|
||||
Success bool `json:"success,omitempty"`
|
||||
@@ -61,36 +65,88 @@ type AccelStreamStatusMessage struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// TapClientEvent is one tap visible to API clients (fresh or within tap_display_min_ms).
|
||||
type TapClientEvent struct {
|
||||
ClientID uint32 `json:"client_id"`
|
||||
Valid bool `json:"valid"`
|
||||
Kind string `json:"kind,omitempty"` // single | double | triple
|
||||
AgeMs uint32 `json:"age_ms,omitempty"`
|
||||
ShownAtMs int64 `json:"shown_at_ms,omitempty"` // Unix ms when API first saw this tap
|
||||
}
|
||||
|
||||
// TapStreamMessage is pushed to external WebSocket clients when receive_tap is on.
|
||||
type TapStreamMessage struct {
|
||||
Type string `json:"type"` // "tap"
|
||||
T int64 `json:"t,omitempty"`
|
||||
Success bool `json:"success,omitempty"`
|
||||
Events []TapClientEvent `json:"events,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// TapStreamStatusMessage is the reply to set_tap_stream / get_tap_stream (this connection).
|
||||
type TapStreamStatusMessage struct {
|
||||
Type string `json:"type"` // "tap_stream_status"
|
||||
ReceiveTap bool `json:"receive_tap"`
|
||||
IntervalMs int `json:"interval_ms"`
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// TapNotifyStatusMessage is the reply to set_tap_notify / get_tap_notify (slave).
|
||||
type TapNotifyStatusMessage struct {
|
||||
Type string `json:"type"` // "tap_notify_status"
|
||||
ClientID uint32 `json:"client_id"`
|
||||
Single bool `json:"single"`
|
||||
DoubleTap bool `json:"double_tap"`
|
||||
Triple bool `json:"triple"`
|
||||
Success bool `json:"success"`
|
||||
SlavesUpdated uint32 `json:"slaves_updated,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type accelWSCommand struct {
|
||||
Type string `json:"type"`
|
||||
ClientID uint32 `json:"client_id"`
|
||||
Enable *bool `json:"enable"`
|
||||
IntervalMs *int `json:"interval_ms"`
|
||||
Single *bool `json:"single"`
|
||||
DoubleTap *bool `json:"double_tap"`
|
||||
Triple *bool `json:"triple"`
|
||||
AllClients bool `json:"all_clients"`
|
||||
}
|
||||
|
||||
type APIInfoResponse struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
SerialPort string `json:"serial_port"`
|
||||
WebSocket string `json:"websocket"`
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
SerialPort string `json:"serial_port"`
|
||||
WebSocket string `json:"websocket"`
|
||||
DefaultIntervalMs int `json:"default_interval_ms"`
|
||||
MinIntervalMs int `json:"min_interval_ms"`
|
||||
MaxIntervalMs int `json:"max_interval_ms"`
|
||||
Description string `json:"description"`
|
||||
MinIntervalMs int `json:"min_interval_ms"`
|
||||
MaxIntervalMs int `json:"max_interval_ms"`
|
||||
TapDisplayMinMs int `json:"tap_display_min_ms"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type cachedTapEvent struct {
|
||||
kind string
|
||||
shownAt time.Time
|
||||
}
|
||||
|
||||
type wsSubscriber struct {
|
||||
conn *websocket.Conn
|
||||
receiveAccel bool
|
||||
interval time.Duration
|
||||
lastSent time.Time
|
||||
conn *websocket.Conn
|
||||
receiveAccel bool
|
||||
receiveTap bool
|
||||
interval time.Duration
|
||||
lastAccelSent time.Time
|
||||
lastTapSent time.Time
|
||||
}
|
||||
|
||||
type accelStreamHub struct {
|
||||
mu sync.RWMutex
|
||||
clients map[*websocket.Conn]*wsSubscriber
|
||||
mu sync.RWMutex
|
||||
clients map[*websocket.Conn]*wsSubscriber
|
||||
defaultInterval time.Duration
|
||||
configChanged chan struct{}
|
||||
configChanged chan struct{}
|
||||
recentTaps map[uint32]cachedTapEvent
|
||||
}
|
||||
|
||||
func newAccelStreamHub(defaultInterval time.Duration) *accelStreamHub {
|
||||
@@ -129,11 +185,14 @@ func (h *accelStreamHub) register(conn *websocket.Conn, portName string) *wsSubs
|
||||
h.mu.Unlock()
|
||||
|
||||
hello := AccelStreamMessage{
|
||||
Type: "hello",
|
||||
Serial: portName,
|
||||
IntervalMs: int(h.defaultInterval / time.Millisecond),
|
||||
Type: "hello",
|
||||
Serial: portName,
|
||||
IntervalMs: int(h.defaultInterval / time.Millisecond),
|
||||
TapDisplayMinMs: apiTapDisplayMinMs,
|
||||
Note: "set_tap_notify configures slave S/D/T only; set_tap_stream enables tap polling/push",
|
||||
Commands: []string{
|
||||
"set_stream", "get_stream", "set_accel_stream", "get_accel_stream",
|
||||
"set_tap_stream", "get_tap_stream", "set_tap_notify", "get_tap_notify",
|
||||
"set_led_ring", "get_battery",
|
||||
},
|
||||
}
|
||||
@@ -146,6 +205,16 @@ func (h *accelStreamHub) register(conn *websocket.Conn, portName string) *wsSubs
|
||||
func (h *accelStreamHub) unregister(conn *websocket.Conn) {
|
||||
h.mu.Lock()
|
||||
delete(h.clients, conn)
|
||||
anyTap := false
|
||||
for _, sub := range h.clients {
|
||||
if sub.receiveTap {
|
||||
anyTap = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !anyTap {
|
||||
h.recentTaps = nil
|
||||
}
|
||||
h.mu.Unlock()
|
||||
h.notifyConfigChanged()
|
||||
}
|
||||
@@ -161,12 +230,23 @@ func (h *accelStreamHub) anyWantsAccel() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *accelStreamHub) anyWantsTap() bool {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for _, sub := range h.clients {
|
||||
if sub.receiveTap {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *accelStreamHub) minWantedInterval() time.Duration {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
var min time.Duration
|
||||
for _, sub := range h.clients {
|
||||
if !sub.receiveAccel {
|
||||
if !sub.receiveAccel && !sub.receiveTap {
|
||||
continue
|
||||
}
|
||||
if min == 0 || sub.interval < min {
|
||||
@@ -208,6 +288,78 @@ func (h *accelStreamHub) getStream(sub *wsSubscriber) StreamStatusMessage {
|
||||
}
|
||||
}
|
||||
|
||||
func (h *accelStreamHub) setTapStream(sub *wsSubscriber, enable bool, intervalMs *int) TapStreamStatusMessage {
|
||||
h.mu.Lock()
|
||||
sub.receiveTap = enable
|
||||
if !enable {
|
||||
h.recentTaps = nil
|
||||
}
|
||||
if intervalMs != nil {
|
||||
sub.interval = clampAPIInterval(time.Duration(*intervalMs) * time.Millisecond)
|
||||
}
|
||||
ms := int(sub.interval / time.Millisecond)
|
||||
h.mu.Unlock()
|
||||
h.notifyConfigChanged()
|
||||
|
||||
return TapStreamStatusMessage{
|
||||
Type: "tap_stream_status",
|
||||
ReceiveTap: enable,
|
||||
IntervalMs: ms,
|
||||
Success: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *accelStreamHub) getTapStream(sub *wsSubscriber) TapStreamStatusMessage {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return TapStreamStatusMessage{
|
||||
Type: "tap_stream_status",
|
||||
ReceiveTap: sub.receiveTap,
|
||||
IntervalMs: int(sub.interval / time.Millisecond),
|
||||
Success: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *accelStreamHub) ingestTapEvents(incoming []TapClientEvent) []TapClientEvent {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
if h.recentTaps == nil {
|
||||
h.recentTaps = make(map[uint32]cachedTapEvent)
|
||||
}
|
||||
for _, e := range incoming {
|
||||
if !e.Valid || e.Kind == "" {
|
||||
continue
|
||||
}
|
||||
h.recentTaps[e.ClientID] = cachedTapEvent{kind: e.Kind, shownAt: now}
|
||||
}
|
||||
return h.activeTapEventsLocked(now)
|
||||
}
|
||||
|
||||
func (h *accelStreamHub) activeTapEventsLocked(now time.Time) []TapClientEvent {
|
||||
if len(h.recentTaps) == 0 {
|
||||
return nil
|
||||
}
|
||||
cutoff := now.Add(-apiTapDisplayMinMs * time.Millisecond)
|
||||
out := make([]TapClientEvent, 0, len(h.recentTaps))
|
||||
for id, ev := range h.recentTaps {
|
||||
if ev.shownAt.Before(cutoff) {
|
||||
delete(h.recentTaps, id)
|
||||
continue
|
||||
}
|
||||
shownAtMs := ev.shownAt.UnixMilli()
|
||||
out = append(out, TapClientEvent{
|
||||
ClientID: id,
|
||||
Valid: true,
|
||||
Kind: ev.kind,
|
||||
AgeMs: uint32(now.Sub(ev.shownAt).Milliseconds()),
|
||||
ShownAtMs: shownAtMs,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *accelStreamHub) deliver(msg AccelStreamMessage) {
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
@@ -221,10 +373,10 @@ func (h *accelStreamHub) deliver(msg AccelStreamMessage) {
|
||||
if !sub.receiveAccel {
|
||||
continue
|
||||
}
|
||||
if !sub.lastSent.IsZero() && now.Sub(sub.lastSent) < sub.interval {
|
||||
if !sub.lastAccelSent.IsZero() && now.Sub(sub.lastAccelSent) < sub.interval {
|
||||
continue
|
||||
}
|
||||
sub.lastSent = now
|
||||
sub.lastAccelSent = now
|
||||
if err := conn.WriteMessage(websocket.TextMessage, data); err != nil {
|
||||
delete(h.clients, conn)
|
||||
_ = conn.Close()
|
||||
@@ -232,7 +384,31 @@ func (h *accelStreamHub) deliver(msg AccelStreamMessage) {
|
||||
}
|
||||
}
|
||||
|
||||
func runAccelStreamer(link *managedSerial, hub *accelStreamHub, dash *wsHub, ctl *accelStreamCtl, stop <-chan struct{}) {
|
||||
func (h *accelStreamHub) deliverTap(msg TapStreamMessage) {
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
for conn, sub := range h.clients {
|
||||
if !sub.receiveTap {
|
||||
continue
|
||||
}
|
||||
if !sub.lastTapSent.IsZero() && now.Sub(sub.lastTapSent) < sub.interval {
|
||||
continue
|
||||
}
|
||||
sub.lastTapSent = now
|
||||
if err := conn.WriteMessage(websocket.TextMessage, data); err != nil {
|
||||
delete(h.clients, conn)
|
||||
_ = conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runAccelStreamer(link *managedSerial, hub *accelStreamHub, dash *wsHub, ctl *accelStreamCtl, tapCtl *tapNotifyCtl, stop <-chan struct{}) {
|
||||
var ticker *time.Ticker
|
||||
var tick <-chan time.Time
|
||||
|
||||
@@ -258,49 +434,85 @@ func runAccelStreamer(link *managedSerial, hub *accelStreamHub, dash *wsHub, ctl
|
||||
case <-hub.configChanged:
|
||||
resetTicker()
|
||||
case <-tick:
|
||||
if !hub.anyWantsAccel() {
|
||||
continue
|
||||
}
|
||||
if !accelStreamPollingActive(dash, ctl) {
|
||||
continue
|
||||
}
|
||||
now := time.Now().UnixNano()
|
||||
resp, err := link.readAccelSnapshotPoll(0)
|
||||
if errors.Is(err, errUARTBusy) {
|
||||
hub.deliver(AccelStreamMessage{
|
||||
Type: "accel",
|
||||
T: now,
|
||||
Success: false,
|
||||
Error: "uart busy",
|
||||
})
|
||||
continue
|
||||
if hub.anyWantsAccel() && accelStreamPollingActive(dash, ctl) {
|
||||
resp, err := link.readAccelSnapshotPoll(0)
|
||||
if errors.Is(err, errUARTBusy) {
|
||||
hub.deliver(AccelStreamMessage{
|
||||
Type: "accel",
|
||||
T: now,
|
||||
Success: false,
|
||||
Error: "uart busy",
|
||||
})
|
||||
} else if err != nil {
|
||||
hub.deliver(AccelStreamMessage{
|
||||
Type: "accel",
|
||||
T: now,
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
})
|
||||
} else {
|
||||
clients := make([]AccelClientSample, 0, len(resp.GetSamples()))
|
||||
for _, s := range resp.GetSamples() {
|
||||
clients = append(clients, AccelClientSample{
|
||||
ClientID: s.GetClientId(),
|
||||
Valid: s.GetValid(),
|
||||
X: s.GetX(),
|
||||
Y: s.GetY(),
|
||||
Z: s.GetZ(),
|
||||
AgeMs: s.GetAgeMs(),
|
||||
})
|
||||
}
|
||||
hub.deliver(AccelStreamMessage{
|
||||
Type: "accel",
|
||||
T: now,
|
||||
Success: true,
|
||||
Clients: clients,
|
||||
})
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
hub.deliver(AccelStreamMessage{
|
||||
Type: "accel",
|
||||
T: now,
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
if hub.anyWantsTap() {
|
||||
nowMs := time.Now().UnixNano()
|
||||
resp, err := link.readTapSnapshotPoll(0)
|
||||
if errors.Is(err, errUARTBusy) {
|
||||
hub.deliverTap(TapStreamMessage{
|
||||
Type: "tap",
|
||||
T: nowMs,
|
||||
Success: false,
|
||||
Error: "uart busy",
|
||||
})
|
||||
} else if err != nil {
|
||||
hub.deliverTap(TapStreamMessage{
|
||||
Type: "tap",
|
||||
T: nowMs,
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
})
|
||||
} else {
|
||||
fresh := make([]TapClientEvent, 0, len(resp.GetEvents()))
|
||||
for _, e := range resp.GetEvents() {
|
||||
if !e.GetValid() {
|
||||
continue
|
||||
}
|
||||
fresh = append(fresh, TapClientEvent{
|
||||
ClientID: e.GetClientId(),
|
||||
Valid: true,
|
||||
Kind: tapKindLabelPB(e.GetKind()),
|
||||
AgeMs: e.GetAgeMs(),
|
||||
})
|
||||
}
|
||||
events := hub.ingestTapEvents(fresh)
|
||||
if len(events) == 0 {
|
||||
continue
|
||||
}
|
||||
hub.deliverTap(TapStreamMessage{
|
||||
Type: "tap",
|
||||
T: nowMs,
|
||||
Success: true,
|
||||
Events: events,
|
||||
})
|
||||
}
|
||||
}
|
||||
clients := make([]AccelClientSample, 0, len(resp.GetSamples()))
|
||||
for _, s := range resp.GetSamples() {
|
||||
clients = append(clients, AccelClientSample{
|
||||
ClientID: s.GetClientId(),
|
||||
Valid: s.GetValid(),
|
||||
X: s.GetX(),
|
||||
Y: s.GetY(),
|
||||
Z: s.GetZ(),
|
||||
AgeMs: s.GetAgeMs(),
|
||||
})
|
||||
}
|
||||
hub.deliver(AccelStreamMessage{
|
||||
Type: "accel",
|
||||
T: now,
|
||||
Success: true,
|
||||
Clients: clients,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -354,7 +566,63 @@ func writeAccelStreamStatus(conn *websocket.Conn, out accelStreamAPIResponse) {
|
||||
_ = conn.WriteMessage(websocket.TextMessage, data)
|
||||
}
|
||||
|
||||
func handleAccelWSCommand(conn *websocket.Conn, sub *wsSubscriber, data []byte, link *managedSerial, dash *wsHub, ctl *accelStreamCtl, hub *accelStreamHub) {
|
||||
func writeTapStreamStatus(conn *websocket.Conn, msg TapStreamStatusMessage) {
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = conn.WriteMessage(websocket.TextMessage, data)
|
||||
}
|
||||
|
||||
func writeTapNotifyStatus(conn *websocket.Conn, out tapNotifyAPIResponse) {
|
||||
msg := TapNotifyStatusMessage{
|
||||
Type: "tap_notify_status",
|
||||
ClientID: out.ClientID,
|
||||
Single: out.Single,
|
||||
DoubleTap: out.DoubleTap,
|
||||
Triple: out.Triple,
|
||||
Success: out.Success,
|
||||
SlavesUpdated: out.SlavesUpdated,
|
||||
Error: out.Error,
|
||||
}
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = conn.WriteMessage(websocket.TextMessage, data)
|
||||
}
|
||||
|
||||
func applyTapNotifyClientWS(link *managedSerial, dash *wsHub, tapCtl *tapNotifyCtl, clientID uint32, single, doubleTap, triple bool) tapNotifyAPIResponse {
|
||||
resp, err := link.TapNotify(&pb.TapNotifyRequest{
|
||||
Write: true,
|
||||
ClientId: clientID,
|
||||
Single: single,
|
||||
DoubleTap: doubleTap,
|
||||
Triple: triple,
|
||||
})
|
||||
if err != nil {
|
||||
return tapNotifyAPIResponse{ClientID: clientID, Error: err.Error()}
|
||||
}
|
||||
out := tapNotifyAPIResponse{
|
||||
ClientID: resp.GetClientId(),
|
||||
Success: resp.GetSuccess(),
|
||||
SlavesUpdated: resp.GetSlavesUpdated(),
|
||||
Single: resp.GetSingle(),
|
||||
DoubleTap: resp.GetDoubleTap(),
|
||||
Triple: resp.GetTriple(),
|
||||
}
|
||||
if resp.GetSuccess() {
|
||||
if tapCtl != nil {
|
||||
tapCtl.Set(clientID, single, doubleTap, triple)
|
||||
}
|
||||
if dash != nil {
|
||||
dash.patchClientTapNotify(clientID, single, doubleTap, triple)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func handleAccelWSCommand(conn *websocket.Conn, sub *wsSubscriber, data []byte, link *managedSerial, dash *wsHub, ctl *accelStreamCtl, tapCtl *tapNotifyCtl, hub *accelStreamHub) {
|
||||
var cmd accelWSCommand
|
||||
if err := json.Unmarshal(data, &cmd); err != nil {
|
||||
writeStreamStatus(conn, StreamStatusMessage{Type: "stream_status", Error: "invalid JSON"})
|
||||
@@ -414,6 +682,79 @@ func handleAccelWSCommand(conn *websocket.Conn, sub *wsSubscriber, data []byte,
|
||||
Success: resp.GetSuccess(),
|
||||
})
|
||||
|
||||
case "set_tap_stream":
|
||||
if cmd.Enable == nil {
|
||||
writeTapStreamStatus(conn, TapStreamStatusMessage{
|
||||
Type: "tap_stream_status",
|
||||
Error: "enable required",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeTapStreamStatus(conn, hub.setTapStream(sub, *cmd.Enable, cmd.IntervalMs))
|
||||
|
||||
case "get_tap_stream":
|
||||
writeTapStreamStatus(conn, hub.getTapStream(sub))
|
||||
|
||||
case "set_tap_notify":
|
||||
if cmd.AllClients {
|
||||
if cmd.Single == nil || cmd.DoubleTap == nil || cmd.Triple == nil {
|
||||
writeTapNotifyStatus(conn, tapNotifyAPIResponse{Error: "single, double_tap, triple required"})
|
||||
return
|
||||
}
|
||||
updated, err := applyTapNotifyAll(link, dash, tapCtl, *cmd.Single, *cmd.DoubleTap, *cmd.Triple)
|
||||
if err != nil {
|
||||
writeTapNotifyStatus(conn, tapNotifyAPIResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
writeTapNotifyStatus(conn, tapNotifyAPIResponse{
|
||||
Success: updated > 0,
|
||||
SlavesUpdated: updated,
|
||||
Single: *cmd.Single,
|
||||
DoubleTap: *cmd.DoubleTap,
|
||||
Triple: *cmd.Triple,
|
||||
})
|
||||
return
|
||||
}
|
||||
if cmd.ClientID == 0 {
|
||||
writeTapNotifyStatus(conn, tapNotifyAPIResponse{Error: "client_id required"})
|
||||
return
|
||||
}
|
||||
if cmd.Single == nil || cmd.DoubleTap == nil || cmd.Triple == nil {
|
||||
writeTapNotifyStatus(conn, tapNotifyAPIResponse{
|
||||
ClientID: cmd.ClientID,
|
||||
Error: "single, double_tap, triple required",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeTapNotifyStatus(conn, applyTapNotifyClientWS(link, dash, tapCtl, cmd.ClientID, *cmd.Single, *cmd.DoubleTap, *cmd.Triple))
|
||||
|
||||
case "get_tap_notify":
|
||||
if cmd.ClientID == 0 {
|
||||
writeTapNotifyStatus(conn, tapNotifyAPIResponse{Error: "client_id required"})
|
||||
return
|
||||
}
|
||||
resp, err := link.TapNotifyPoll(&pb.TapNotifyRequest{
|
||||
Write: false,
|
||||
ClientId: cmd.ClientID,
|
||||
})
|
||||
if err != nil {
|
||||
writeTapNotifyStatus(conn, tapNotifyAPIResponse{
|
||||
ClientID: cmd.ClientID,
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
if tapCtl != nil {
|
||||
tapCtl.Set(cmd.ClientID, resp.GetSingle(), resp.GetDoubleTap(), resp.GetTriple())
|
||||
}
|
||||
writeTapNotifyStatus(conn, tapNotifyAPIResponse{
|
||||
ClientID: cmd.ClientID,
|
||||
Success: resp.GetSuccess(),
|
||||
Single: resp.GetSingle(),
|
||||
DoubleTap: resp.GetDoubleTap(),
|
||||
Triple: resp.GetTriple(),
|
||||
})
|
||||
|
||||
case "set_led_ring":
|
||||
var body ledRingAPIRequest
|
||||
if err := json.Unmarshal(data, &body); err != nil {
|
||||
@@ -440,12 +781,12 @@ func handleAccelWSCommand(conn *websocket.Conn, sub *wsSubscriber, data []byte,
|
||||
default:
|
||||
writeStreamStatus(conn, StreamStatusMessage{
|
||||
Type: "stream_status",
|
||||
Error: "unknown type (set_stream, get_stream, set_accel_stream, get_accel_stream, set_led_ring, get_battery)",
|
||||
Error: "unknown type (set_stream, get_stream, set_accel_stream, get_accel_stream, set_tap_stream, get_tap_stream, set_tap_notify, get_tap_notify, set_led_ring, get_battery)",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func serveExternalWS(conn *websocket.Conn, link *managedSerial, dash *wsHub, ctl *accelStreamCtl, portName string, hub *accelStreamHub) {
|
||||
func serveExternalWS(conn *websocket.Conn, link *managedSerial, dash *wsHub, ctl *accelStreamCtl, tapCtl *tapNotifyCtl, portName string, hub *accelStreamHub) {
|
||||
sub := hub.register(conn, portName)
|
||||
defer hub.unregister(conn)
|
||||
defer conn.Close()
|
||||
@@ -455,11 +796,11 @@ func serveExternalWS(conn *websocket.Conn, link *managedSerial, dash *wsHub, ctl
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
handleAccelWSCommand(conn, sub, data, link, dash, ctl, hub)
|
||||
handleAccelWSCommand(conn, sub, data, link, dash, ctl, tapCtl, hub)
|
||||
}
|
||||
}
|
||||
|
||||
func mountExternalAPI(mux *http.ServeMux, portName string, defaultInterval time.Duration, hub *accelStreamHub, link *managedSerial, dash *wsHub, ctl *accelStreamCtl) {
|
||||
func mountExternalAPI(mux *http.ServeMux, portName string, defaultInterval time.Duration, hub *accelStreamHub, link *managedSerial, dash *wsHub, ctl *accelStreamCtl, tapCtl *tapNotifyCtl) {
|
||||
defMs := int(defaultInterval / time.Millisecond)
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/" && r.URL.Path != "/api/v1" && r.URL.Path != "/api/v1/" {
|
||||
@@ -478,7 +819,8 @@ func mountExternalAPI(mux *http.ServeMux, portName string, defaultInterval time.
|
||||
DefaultIntervalMs: defMs,
|
||||
MinIntervalMs: int(minAPIStreamInterval / time.Millisecond),
|
||||
MaxIntervalMs: int(maxAPIStreamInterval / time.Millisecond),
|
||||
Description: "WebSocket: accel stream + set_led_ring (modes: clear, color, progress, digit, blink, find-me)",
|
||||
TapDisplayMinMs: apiTapDisplayMinMs,
|
||||
Description: "WebSocket: set_accel_stream + set_stream for accel; set_tap_notify (slave S/D/T) then set_tap_stream for tap events (shown ≥2s)",
|
||||
})
|
||||
})
|
||||
|
||||
@@ -488,22 +830,22 @@ func mountExternalAPI(mux *http.ServeMux, portName string, defaultInterval time.
|
||||
log.Printf("api websocket upgrade: %v", err)
|
||||
return
|
||||
}
|
||||
serveExternalWS(conn, link, dash, ctl, portName, hub)
|
||||
serveExternalWS(conn, link, dash, ctl, tapCtl, portName, hub)
|
||||
})
|
||||
}
|
||||
|
||||
func runAPIServer(portName string, link *managedSerial, addr string, defaultInterval time.Duration, dash *wsHub, ctl *accelStreamCtl, stop <-chan struct{}) *http.Server {
|
||||
func runAPIServer(portName string, link *managedSerial, addr string, defaultInterval time.Duration, dash *wsHub, ctl *accelStreamCtl, tapCtl *tapNotifyCtl, stop <-chan struct{}) *http.Server {
|
||||
hub := newAccelStreamHub(defaultInterval)
|
||||
go runAccelStreamer(link, hub, dash, ctl, stop)
|
||||
go runAccelStreamer(link, hub, dash, ctl, tapCtl, stop)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mountExternalAPI(mux, portName, defaultInterval, hub, link, dash, ctl)
|
||||
mountExternalAPI(mux, portName, defaultInterval, hub, link, dash, ctl, tapCtl)
|
||||
mountLedRingAPI(mux, link)
|
||||
mountBatteryAPI(mux, link)
|
||||
|
||||
srv := &http.Server{Addr: addr, Handler: mux}
|
||||
go func() {
|
||||
log.Printf("external API http://localhost%s WebSocket ws://localhost%s/ws (default accel interval %s, per-client via set_stream)",
|
||||
log.Printf("external API http://localhost%s WebSocket ws://localhost%s/ws (default stream interval %s, per-client via set_stream / set_tap_stream)",
|
||||
addr, addr, defaultInterval.String())
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Printf("external API server: %v", err)
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"powerpod/gotool/pb"
|
||||
)
|
||||
|
||||
type tapNotifyAPIRequest struct {
|
||||
Write bool `json:"write"`
|
||||
ClientID uint32 `json:"client_id"`
|
||||
AllClients bool `json:"all_clients"`
|
||||
Single bool `json:"single"`
|
||||
DoubleTap bool `json:"double_tap"`
|
||||
Triple bool `json:"triple"`
|
||||
}
|
||||
|
||||
type tapNotifyAPIResponse struct {
|
||||
ClientID uint32 `json:"client_id"`
|
||||
Success bool `json:"success"`
|
||||
SlavesUpdated uint32 `json:"slaves_updated"`
|
||||
Single bool `json:"single"`
|
||||
DoubleTap bool `json:"double_tap"`
|
||||
Triple bool `json:"triple"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type tapSnapshotAPIResponse struct {
|
||||
Events []tapEventView `json:"events"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type tapEventView struct {
|
||||
ClientID uint32 `json:"client_id"`
|
||||
Kind string `json:"kind"`
|
||||
AgeMs uint32 `json:"age_ms"`
|
||||
}
|
||||
|
||||
type tapReceiveAPIResponse struct {
|
||||
ClientID uint32 `json:"client_id"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func mountTapAPI(mux *http.ServeMux, link *managedSerial, hub *wsHub, tapCtl *tapNotifyCtl) {
|
||||
mux.HandleFunc("GET /api/clients/{clientID}/tap-notify", func(w http.ResponseWriter, r *http.Request) {
|
||||
clientID, err := parsePathClientID(r)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, tapNotifyAPIResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
serveTapNotifyGet(w, clientID, link)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/clients/{clientID}/tap-notify", func(w http.ResponseWriter, r *http.Request) {
|
||||
clientID, err := parsePathClientID(r)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, tapNotifyAPIResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
serveClientTapNotifyPut(w, r, clientID, link, hub, tapCtl)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/clients/{clientID}/tap-receive", func(w http.ResponseWriter, r *http.Request) {
|
||||
clientID, err := parsePathClientID(r)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, tapReceiveAPIResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
serveClientTapReceivePut(w, r, clientID, hub)
|
||||
})
|
||||
|
||||
mux.HandleFunc("/api/tap-notify", func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
serveTapNotifyGetQuery(w, r, link)
|
||||
case http.MethodPost:
|
||||
serveTapNotifyPost(w, r, link, hub, tapCtl)
|
||||
default:
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
})
|
||||
|
||||
mux.HandleFunc("/api/tap-snapshot", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
serveTapSnapshotGet(w, r, link)
|
||||
})
|
||||
}
|
||||
|
||||
func applyTapNotifyClient(link *managedSerial, hub *wsHub, tapCtl *tapNotifyCtl, clientID uint32, single, doubleTap, triple bool) tapNotifyAPIResponse {
|
||||
return applyTapNotifyClientWS(link, hub, tapCtl, clientID, single, doubleTap, triple)
|
||||
}
|
||||
|
||||
func serveTapNotifyGet(w http.ResponseWriter, clientID uint32, link *managedSerial) {
|
||||
resp, err := link.TapNotifyPoll(&pb.TapNotifyRequest{
|
||||
Write: false,
|
||||
ClientId: clientID,
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, tapNotifyAPIResponse{
|
||||
ClientID: clientID,
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, tapNotifyAPIResponse{
|
||||
ClientID: resp.GetClientId(),
|
||||
Success: resp.GetSuccess(),
|
||||
Single: resp.GetSingle(),
|
||||
DoubleTap: resp.GetDoubleTap(),
|
||||
Triple: resp.GetTriple(),
|
||||
})
|
||||
}
|
||||
|
||||
func serveTapNotifyGetQuery(w http.ResponseWriter, r *http.Request, link *managedSerial) {
|
||||
clientID, err := parseUintQuery(r, "client_id", 0)
|
||||
if err != nil || clientID == 0 {
|
||||
writeJSON(w, http.StatusBadRequest, tapNotifyAPIResponse{Error: "client_id required"})
|
||||
return
|
||||
}
|
||||
serveTapNotifyGet(w, clientID, link)
|
||||
}
|
||||
|
||||
type clientTapNotifyBody struct {
|
||||
Single bool `json:"single"`
|
||||
DoubleTap bool `json:"double_tap"`
|
||||
Triple bool `json:"triple"`
|
||||
}
|
||||
|
||||
func serveClientTapNotifyPut(w http.ResponseWriter, r *http.Request, clientID uint32, link *managedSerial, hub *wsHub, tapCtl *tapNotifyCtl) {
|
||||
var body clientTapNotifyBody
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, tapNotifyAPIResponse{Error: "invalid JSON"})
|
||||
return
|
||||
}
|
||||
out := applyTapNotifyClient(link, hub, tapCtl, clientID, body.Single, body.DoubleTap, body.Triple)
|
||||
status := http.StatusOK
|
||||
if out.Error != "" || !out.Success {
|
||||
status = http.StatusServiceUnavailable
|
||||
}
|
||||
writeJSON(w, status, out)
|
||||
}
|
||||
|
||||
func serveTapNotifyPost(w http.ResponseWriter, r *http.Request, link *managedSerial, hub *wsHub, tapCtl *tapNotifyCtl) {
|
||||
var body tapNotifyAPIRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, tapNotifyAPIResponse{Error: "invalid JSON"})
|
||||
return
|
||||
}
|
||||
|
||||
if body.AllClients {
|
||||
updated, err := applyTapNotifyAll(link, hub, tapCtl, body.Single, body.DoubleTap, body.Triple)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, tapNotifyAPIResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, tapNotifyAPIResponse{
|
||||
Success: updated > 0,
|
||||
SlavesUpdated: updated,
|
||||
Single: body.Single,
|
||||
DoubleTap: body.DoubleTap,
|
||||
Triple: body.Triple,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if body.ClientID == 0 {
|
||||
writeJSON(w, http.StatusBadRequest, tapNotifyAPIResponse{Error: "client_id required"})
|
||||
return
|
||||
}
|
||||
|
||||
out := applyTapNotifyClient(link, hub, tapCtl, body.ClientID, body.Single, body.DoubleTap, body.Triple)
|
||||
status := http.StatusOK
|
||||
if out.Error != "" || !out.Success {
|
||||
status = http.StatusServiceUnavailable
|
||||
}
|
||||
writeJSON(w, status, out)
|
||||
}
|
||||
|
||||
func serveClientTapReceivePut(w http.ResponseWriter, r *http.Request, clientID uint32, hub *wsHub) {
|
||||
var body struct {
|
||||
Enable bool `json:"enable"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, tapReceiveAPIResponse{Error: "invalid JSON"})
|
||||
return
|
||||
}
|
||||
if hub != nil {
|
||||
hub.patchClientTapReceive(clientID, body.Enable)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, tapReceiveAPIResponse{
|
||||
ClientID: clientID,
|
||||
Enabled: body.Enable,
|
||||
Success: true,
|
||||
})
|
||||
}
|
||||
|
||||
func applyTapNotifyAll(link *managedSerial, hub *wsHub, tapCtl *tapNotifyCtl, single, doubleTap, triple bool) (uint32, error) {
|
||||
resp, err := link.TapNotify(&pb.TapNotifyRequest{
|
||||
Write: true,
|
||||
AllClients: true,
|
||||
Single: single,
|
||||
DoubleTap: doubleTap,
|
||||
Triple: triple,
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !resp.GetSuccess() {
|
||||
return 0, fmt.Errorf("tap notify not applied to any slave")
|
||||
}
|
||||
if hub != nil || tapCtl != nil {
|
||||
clients, _ := link.listClientsPoll()
|
||||
for _, c := range clients {
|
||||
if tapCtl != nil {
|
||||
tapCtl.Set(c.GetId(), single, doubleTap, triple)
|
||||
}
|
||||
if hub != nil {
|
||||
hub.patchClientTapNotify(c.GetId(), single, doubleTap, triple)
|
||||
}
|
||||
}
|
||||
}
|
||||
return resp.GetSlavesUpdated(), nil
|
||||
}
|
||||
|
||||
func serveTapSnapshotGet(w http.ResponseWriter, r *http.Request, link *managedSerial) {
|
||||
clientID, err := parseUintQuery(r, "client_id", 0)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, tapSnapshotAPIResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
resp, err := link.readTapSnapshotPoll(clientID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, tapSnapshotAPIResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
out := tapSnapshotAPIResponse{Events: make([]tapEventView, 0, len(resp.GetEvents()))}
|
||||
for _, e := range resp.GetEvents() {
|
||||
if !e.GetValid() {
|
||||
continue
|
||||
}
|
||||
out.Events = append(out.Events, tapEventView{
|
||||
ClientID: e.GetClientId(),
|
||||
Kind: tapKindLabel(e.GetKind()),
|
||||
AgeMs: e.GetAgeMs(),
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
@@ -171,6 +171,64 @@ func (m *managedSerial) GetAccelStream(clientID uint32) (bool, error) {
|
||||
return resp.GetEnabled(), nil
|
||||
}
|
||||
|
||||
func (m *managedSerial) TapNotify(req *pb.TapNotifyRequest) (*pb.TapNotifyResponse, error) {
|
||||
return m.tapNotifyVia(m.withPort, req)
|
||||
}
|
||||
|
||||
func (m *managedSerial) TapNotifyPoll(req *pb.TapNotifyRequest) (*pb.TapNotifyResponse, error) {
|
||||
return m.tapNotifyVia(m.withPortPoll, req)
|
||||
}
|
||||
|
||||
func (m *managedSerial) tapNotifyVia(
|
||||
portFn func(func(*serialPort) error) error,
|
||||
req *pb.TapNotifyRequest,
|
||||
) (*pb.TapNotifyResponse, error) {
|
||||
var resp *pb.TapNotifyResponse
|
||||
err := portFn(func(sp *serialPort) error {
|
||||
var e error
|
||||
resp, e = sp.TapNotify(req)
|
||||
return e
|
||||
})
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (m *managedSerial) readTapSnapshotPoll(clientID uint32) (*pb.TapSnapshotResponse, error) {
|
||||
msg := &pb.UartMessage{
|
||||
Type: pb.MessageType_TAP_SNAPSHOT,
|
||||
Payload: &pb.UartMessage_TapSnapshotRequest{
|
||||
TapSnapshotRequest: &pb.TapSnapshotRequest{ClientId: clientID},
|
||||
},
|
||||
}
|
||||
body, err := proto.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode: %w", err)
|
||||
}
|
||||
payload := append([]byte{byte(pb.MessageType_TAP_SNAPSHOT)}, body...)
|
||||
respPayload, err := m.exchangePayloadPoll(payload, "TAP_SNAPSHOT")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodeTapSnapshotPayload(respPayload)
|
||||
}
|
||||
|
||||
func decodeTapSnapshotPayload(payload []byte) (*pb.TapSnapshotResponse, error) {
|
||||
if len(payload) < 1 {
|
||||
return nil, fmt.Errorf("empty response payload")
|
||||
}
|
||||
var msg pb.UartMessage
|
||||
if err := proto.Unmarshal(payload[1:], &msg); err != nil {
|
||||
return nil, fmt.Errorf("decode: %w", err)
|
||||
}
|
||||
if msg.GetType() != pb.MessageType_TAP_SNAPSHOT {
|
||||
return nil, fmt.Errorf("unexpected type %v", msg.GetType())
|
||||
}
|
||||
r := msg.GetTapSnapshotResponse()
|
||||
if r == nil {
|
||||
return nil, fmt.Errorf("missing tap_snapshot_response")
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (m *managedSerial) accelStreamVia(
|
||||
portFn func(func(*serialPort) error) error,
|
||||
req *pb.AccelStreamRequest,
|
||||
@@ -325,6 +383,52 @@ func (s *serialPort) AccelStream(req *pb.AccelStreamRequest) (*pb.AccelStreamRes
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *serialPort) TapNotify(req *pb.TapNotifyRequest) (*pb.TapNotifyResponse, error) {
|
||||
msg := &pb.UartMessage{
|
||||
Type: pb.MessageType_TAP_NOTIFY,
|
||||
Payload: &pb.UartMessage_TapNotifyRequest{
|
||||
TapNotifyRequest: req,
|
||||
},
|
||||
}
|
||||
body, err := proto.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode: %w", err)
|
||||
}
|
||||
payload := append([]byte{byte(pb.MessageType_TAP_NOTIFY)}, body...)
|
||||
respPayload, err := s.exchangePayload(payload, "TAP_NOTIFY")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var respMsg pb.UartMessage
|
||||
if err := proto.Unmarshal(respPayload[1:], &respMsg); err != nil {
|
||||
return nil, fmt.Errorf("decode: %w", err)
|
||||
}
|
||||
r := respMsg.GetTapNotifyResponse()
|
||||
if r == nil {
|
||||
return nil, fmt.Errorf("missing tap_notify_response")
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *serialPort) readTapSnapshot(clientID uint32) (*pb.TapSnapshotResponse, error) {
|
||||
msg := &pb.UartMessage{
|
||||
Type: pb.MessageType_TAP_SNAPSHOT,
|
||||
Payload: &pb.UartMessage_TapSnapshotRequest{
|
||||
TapSnapshotRequest: &pb.TapSnapshotRequest{ClientId: clientID},
|
||||
},
|
||||
}
|
||||
body, err := proto.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode: %w", err)
|
||||
}
|
||||
payload := append([]byte{byte(pb.MessageType_TAP_SNAPSHOT)}, body...)
|
||||
respPayload, err := s.exchangePayload(payload, "TAP_SNAPSHOT")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodeTapSnapshotPayload(respPayload)
|
||||
}
|
||||
|
||||
func (s *serialPort) accelDeadzone(req *pb.AccelDeadzoneRequest) (*pb.AccelDeadzoneResponse, error) {
|
||||
msg := &pb.UartMessage{
|
||||
Type: pb.MessageType_ACCEL_DEADZONE,
|
||||
|
||||
+10
-2
@@ -18,9 +18,17 @@ func runClients(sp *serialPort) error {
|
||||
fmt.Printf("clients (%d):\n", len(clients))
|
||||
for i, c := range clients {
|
||||
mac := hex.EncodeToString(c.GetMac())
|
||||
fmt.Printf(" [%d] id=%d mac=%s ver=%d available=%v used=%v last_ping=%d last_success_ping=%d\n",
|
||||
fmt.Printf(" [%d] id=%d mac=%s ver=%d available=%v used=%v last_ping=%d last_success_ping=%d tap=%s/%s/%s\n",
|
||||
i, c.GetId(), mac, c.GetVersion(), c.GetAvailable(), c.GetUsed(),
|
||||
c.GetLastPing(), c.GetLastSuccessPing())
|
||||
c.GetLastPing(), c.GetLastSuccessPing(),
|
||||
boolFlag(c.GetTapNotifySingle()), boolFlag(c.GetTapNotifyDouble()), boolFlag(c.GetTapNotifyTriple()))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func boolFlag(v bool) string {
|
||||
if v {
|
||||
return "on"
|
||||
}
|
||||
return "off"
|
||||
}
|
||||
|
||||
+5
-3
@@ -38,20 +38,22 @@ func runServe(portName string, baud int, args []string) error {
|
||||
|
||||
hub := newWSHub()
|
||||
streamCtl := newAccelStreamCtl()
|
||||
tapCtl := newTapNotifyCtl()
|
||||
stop := make(chan struct{})
|
||||
defer close(stop)
|
||||
go runPoller(link, portName, hub, streamCtl, *interval, stop)
|
||||
go runPoller(link, portName, hub, streamCtl, tapCtl, *interval, stop)
|
||||
go runBatteryPoller(link, hub, 5*time.Second, stop)
|
||||
go runAccelDashboardPoller(link, hub, *accelInterval, stop)
|
||||
go runTapDashboardPoller(link, hub, *accelInterval, stop)
|
||||
|
||||
var apiSrv *http.Server
|
||||
if *apiAddr != "" {
|
||||
apiSrv = runAPIServer(portName, link, *apiAddr, *accelInterval, hub, streamCtl, stop)
|
||||
apiSrv = runAPIServer(portName, link, *apiAddr, *accelInterval, hub, streamCtl, tapCtl, stop)
|
||||
defer shutdownAPIServer(apiSrv)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mountServeAPI(mux, link, hub, streamCtl)
|
||||
mountServeAPI(mux, link, hub, streamCtl, tapCtl)
|
||||
mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := wsUpgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
"powerpod/gotool/pb"
|
||||
)
|
||||
|
||||
func runTapNotify(sp *serialPort, args []string) error {
|
||||
fs := flag.NewFlagSet("tap-notify", flag.ExitOnError)
|
||||
write := fs.Bool("set", false, "write tap notify flags (default: read)")
|
||||
clientID := fs.Uint("client", 0, "client id (>0 required for read/set one slave)")
|
||||
all := fs.Bool("all", false, "apply to all registered slaves (with -set)")
|
||||
single := fs.Bool("single", false, "notify on single tap")
|
||||
doubleTap := fs.Bool("double", false, "notify on double tap")
|
||||
triple := fs.Bool("triple", false, "notify on triple tap")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !*write && (*all || *clientID == 0) {
|
||||
return fmt.Errorf("read requires -client <id>")
|
||||
}
|
||||
if *write && !*all && *clientID == 0 {
|
||||
return fmt.Errorf("set requires -client <id> or -all")
|
||||
}
|
||||
|
||||
r, err := sp.TapNotify(&pb.TapNotifyRequest{
|
||||
Write: *write,
|
||||
ClientId: uint32(*clientID),
|
||||
AllClients: *all,
|
||||
Single: *single,
|
||||
DoubleTap: *doubleTap,
|
||||
Triple: *triple,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("client_id=%d success=%v slaves_updated=%d single=%v double=%v triple=%v\n",
|
||||
r.GetClientId(), r.GetSuccess(), r.GetSlavesUpdated(),
|
||||
r.GetSingle(), r.GetDoubleTap(), r.GetTriple())
|
||||
return nil
|
||||
}
|
||||
|
||||
func runTapSnapshot(sp *serialPort, args []string) error {
|
||||
fs := flag.NewFlagSet("tap", flag.ExitOnError)
|
||||
clientID := fs.Uint("client", 0, "client id (0 = all slaves with tap notify)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
return runTapSnapshotForClient(sp, uint32(*clientID))
|
||||
}
|
||||
|
||||
func runTapSnapshotForClient(sp *serialPort, clientID uint32) error {
|
||||
r, err := sp.readTapSnapshot(clientID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
events := r.GetEvents()
|
||||
if len(events) == 0 {
|
||||
fmt.Println("no tap events (none pending or older than 16 ms)")
|
||||
return nil
|
||||
}
|
||||
for _, e := range events {
|
||||
fmt.Printf("client %d: %s (age %d ms)\n",
|
||||
e.GetClientId(), tapKindLabel(e.GetKind()), e.GetAgeMs())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func tapKindLabel(k pb.TapKind) string {
|
||||
switch k {
|
||||
case pb.TapKind_TAP_SINGLE:
|
||||
return "single"
|
||||
case pb.TapKind_TAP_DOUBLE:
|
||||
return "double"
|
||||
case pb.TapKind_TAP_TRIPLE:
|
||||
return "triple"
|
||||
default:
|
||||
return "none"
|
||||
}
|
||||
}
|
||||
+257
-4
@@ -41,6 +41,13 @@ type ClientView struct {
|
||||
AccelZ int32 `json:"accel_z"`
|
||||
AccelAgeMs uint32 `json:"accel_age_ms"`
|
||||
AccelStream bool `json:"accel_stream"`
|
||||
TapNotifySingle bool `json:"tap_notify_single"`
|
||||
TapNotifyDouble bool `json:"tap_notify_double"`
|
||||
TapNotifyTriple bool `json:"tap_notify_triple"`
|
||||
/** Host-side: poll master tap cache for this slave (~16 ms). */
|
||||
TapReceive bool `json:"tap_receive"`
|
||||
LastTap string `json:"last_tap,omitempty"`
|
||||
LastTapAt int64 `json:"last_tap_at,omitempty"`
|
||||
Lipo1 lipoReadingJSON `json:"lipo1"`
|
||||
Lipo2 lipoReadingJSON `json:"lipo2"`
|
||||
BatteryAgeMs uint32 `json:"battery_age_ms,omitempty"`
|
||||
@@ -71,6 +78,8 @@ func (h *wsHub) setState(st DashboardState) {
|
||||
prev := h.state
|
||||
st.Clients = preserveClientAccel(st.Clients, prev.Clients)
|
||||
st.Clients = preserveClientBattery(st.Clients, prev.Clients)
|
||||
st.Clients = preserveClientTapReceive(st.Clients, prev.Clients)
|
||||
st.Clients = preserveClientTap(st.Clients, prev.Clients)
|
||||
if !st.Master.Lipo1.Valid && !st.Master.Lipo2.Valid {
|
||||
if prev.Master.Lipo1.Valid || prev.Master.Lipo2.Valid {
|
||||
st.Master.Lipo1 = prev.Master.Lipo1
|
||||
@@ -206,6 +215,124 @@ func anyClientAccelStream(clients []ClientView) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func anyClientTapNotify(clients []ClientView) bool {
|
||||
for _, c := range clients {
|
||||
if c.TapNotifySingle || c.TapNotifyDouble || c.TapNotifyTriple {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func anyClientTapReceive(clients []ClientView) bool {
|
||||
for _, c := range clients {
|
||||
if c.TapReceive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func preserveClientTapReceive(newClients, oldClients []ClientView) []ClientView {
|
||||
if len(oldClients) == 0 {
|
||||
return newClients
|
||||
}
|
||||
oldByID := make(map[uint32]ClientView, len(oldClients))
|
||||
for _, c := range oldClients {
|
||||
oldByID[c.ID] = c
|
||||
}
|
||||
out := make([]ClientView, len(newClients))
|
||||
for i, c := range newClients {
|
||||
out[i] = c
|
||||
prev, ok := oldByID[c.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out[i].TapReceive = prev.TapReceive
|
||||
if !prev.TapReceive {
|
||||
continue
|
||||
}
|
||||
if c.LastTap == "" && prev.LastTap != "" {
|
||||
cutoff := time.Now().Add(-clientTapDisplayMinMs * time.Millisecond).UnixMilli()
|
||||
if prev.LastTapAt >= cutoff {
|
||||
out[i].LastTap = prev.LastTap
|
||||
out[i].LastTapAt = prev.LastTapAt
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func tapKindLabelPB(k pb.TapKind) string {
|
||||
switch k {
|
||||
case pb.TapKind_TAP_SINGLE:
|
||||
return "single"
|
||||
case pb.TapKind_TAP_DOUBLE:
|
||||
return "double"
|
||||
case pb.TapKind_TAP_TRIPLE:
|
||||
return "triple"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func applyTapEvents(clients []ClientView, events []*pb.TapEvent) []ClientView {
|
||||
if len(events) == 0 {
|
||||
return clients
|
||||
}
|
||||
byID := make(map[uint32]*pb.TapEvent, len(events))
|
||||
for _, e := range events {
|
||||
if e.GetValid() {
|
||||
byID[e.GetClientId()] = e
|
||||
}
|
||||
}
|
||||
if len(byID) == 0 {
|
||||
return clients
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
out := make([]ClientView, len(clients))
|
||||
for i, c := range clients {
|
||||
out[i] = c
|
||||
if !c.TapReceive {
|
||||
continue
|
||||
}
|
||||
e, ok := byID[c.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out[i].LastTap = tapKindLabelPB(e.GetKind())
|
||||
out[i].LastTapAt = now
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const clientTapDisplayMinMs = 2000
|
||||
|
||||
func preserveClientTap(newClients, oldClients []ClientView) []ClientView {
|
||||
if len(oldClients) == 0 {
|
||||
return newClients
|
||||
}
|
||||
oldByID := make(map[uint32]ClientView, len(oldClients))
|
||||
for _, c := range oldClients {
|
||||
oldByID[c.ID] = c
|
||||
}
|
||||
cutoff := time.Now().Add(-clientTapDisplayMinMs * time.Millisecond).UnixMilli()
|
||||
out := make([]ClientView, len(newClients))
|
||||
for i, c := range newClients {
|
||||
out[i] = c
|
||||
if c.LastTap != "" {
|
||||
continue
|
||||
}
|
||||
prev, ok := oldByID[c.ID]
|
||||
if !ok || prev.LastTap == "" || prev.LastTapAt < cutoff {
|
||||
continue
|
||||
}
|
||||
out[i].LastTap = prev.LastTap
|
||||
out[i].LastTapAt = prev.LastTapAt
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// patchClientAccelStream updates stream flag immediately (e.g. after REST) and pushes WS.
|
||||
func (h *wsHub) patchClientAccelStream(clientID uint32, enabled bool) {
|
||||
h.mu.Lock()
|
||||
@@ -246,6 +373,51 @@ func (h *wsHub) anyAccelStreamEnabled() bool {
|
||||
return anyClientAccelStream(h.state.Clients)
|
||||
}
|
||||
|
||||
func (h *wsHub) anyTapNotifyEnabled() bool {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return anyClientTapNotify(h.state.Clients)
|
||||
}
|
||||
|
||||
func (h *wsHub) anyTapReceiveEnabled() bool {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return anyClientTapReceive(h.state.Clients)
|
||||
}
|
||||
|
||||
// patchClientTapNotify updates tap notify flags immediately (e.g. after REST) and pushes WS.
|
||||
func (h *wsHub) patchClientTapNotify(clientID uint32, single, doubleTap, triple bool) {
|
||||
h.mu.Lock()
|
||||
for i := range h.state.Clients {
|
||||
if h.state.Clients[i].ID != clientID {
|
||||
continue
|
||||
}
|
||||
h.state.Clients[i].TapNotifySingle = single
|
||||
h.state.Clients[i].TapNotifyDouble = doubleTap
|
||||
h.state.Clients[i].TapNotifyTriple = triple
|
||||
if !single && !doubleTap && !triple {
|
||||
h.state.Clients[i].LastTap = ""
|
||||
h.state.Clients[i].LastTapAt = 0
|
||||
}
|
||||
break
|
||||
}
|
||||
st := h.state
|
||||
st.UpdatedAt = time.Now().Format(time.RFC3339)
|
||||
conns := make([]*websocket.Conn, 0, len(h.clients))
|
||||
for c := range h.clients {
|
||||
conns = append(conns, c)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
data, err := json.Marshal(st)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, c := range conns {
|
||||
_ = c.WriteMessage(websocket.TextMessage, data)
|
||||
}
|
||||
}
|
||||
|
||||
// mergeAccel updates cached accel on clients and pushes state to dashboard WebSockets.
|
||||
func (h *wsHub) mergeAccel(samples []*pb.AccelSample) {
|
||||
h.mu.Lock()
|
||||
@@ -268,6 +440,60 @@ func (h *wsHub) mergeAccel(samples []*pb.AccelSample) {
|
||||
}
|
||||
}
|
||||
|
||||
func (h *wsHub) patchClientTapReceive(clientID uint32, enabled bool) {
|
||||
h.mu.Lock()
|
||||
for i := range h.state.Clients {
|
||||
if h.state.Clients[i].ID != clientID {
|
||||
continue
|
||||
}
|
||||
h.state.Clients[i].TapReceive = enabled
|
||||
if !enabled {
|
||||
h.state.Clients[i].LastTap = ""
|
||||
h.state.Clients[i].LastTapAt = 0
|
||||
}
|
||||
break
|
||||
}
|
||||
st := h.state
|
||||
st.UpdatedAt = time.Now().Format(time.RFC3339)
|
||||
conns := make([]*websocket.Conn, 0, len(h.clients))
|
||||
for c := range h.clients {
|
||||
conns = append(conns, c)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
data, err := json.Marshal(st)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, c := range conns {
|
||||
_ = c.WriteMessage(websocket.TextMessage, data)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *wsHub) mergeTap(events []*pb.TapEvent) {
|
||||
if len(events) == 0 {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
st := h.state
|
||||
st.Clients = applyTapEvents(st.Clients, events)
|
||||
st.UpdatedAt = time.Now().Format(time.RFC3339)
|
||||
h.state = st
|
||||
conns := make([]*websocket.Conn, 0, len(h.clients))
|
||||
for c := range h.clients {
|
||||
conns = append(conns, c)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
data, err := json.Marshal(st)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, c := range conns {
|
||||
_ = c.WriteMessage(websocket.TextMessage, data)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *wsHub) broadcastRaw(v any) {
|
||||
h.mu.RLock()
|
||||
conns := make([]*websocket.Conn, 0, len(h.clients))
|
||||
@@ -285,7 +511,7 @@ func (h *wsHub) broadcastRaw(v any) {
|
||||
}
|
||||
}
|
||||
|
||||
func pollDashboard(link *managedSerial, portName string, last *DashboardState, streamCtl *accelStreamCtl) DashboardState {
|
||||
func pollDashboard(link *managedSerial, portName string, last *DashboardState, streamCtl *accelStreamCtl, tapCtl *tapNotifyCtl) DashboardState {
|
||||
st := DashboardState{
|
||||
UpdatedAt: time.Now().Format(time.RFC3339),
|
||||
SerialPort: portName,
|
||||
@@ -332,6 +558,9 @@ func pollDashboard(link *managedSerial, portName string, last *DashboardState, s
|
||||
LastPing: c.GetLastPing(),
|
||||
LastSuccessPing: c.GetLastSuccessPing(),
|
||||
AccelStream: c.GetAccelStreamEnabled(),
|
||||
TapNotifySingle: c.GetTapNotifySingle(),
|
||||
TapNotifyDouble: c.GetTapNotifyDouble(),
|
||||
TapNotifyTriple: c.GetTapNotifyTriple(),
|
||||
}
|
||||
st.Clients = append(st.Clients, cv)
|
||||
}
|
||||
@@ -358,6 +587,9 @@ func pollDashboard(link *managedSerial, portName string, last *DashboardState, s
|
||||
if streamCtl != nil {
|
||||
streamCtl.SyncFromClients(st.Clients)
|
||||
}
|
||||
if tapCtl != nil {
|
||||
tapCtl.SyncFromClients(st.Clients)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
@@ -436,6 +668,27 @@ func runAccelDashboardPoller(link *managedSerial, hub *wsHub, interval time.Dura
|
||||
}
|
||||
}
|
||||
|
||||
func runTapDashboardPoller(link *managedSerial, hub *wsHub, interval time.Duration, stop <-chan struct{}) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
if hub.clientCount() == 0 || !hub.anyTapReceiveEnabled() {
|
||||
continue
|
||||
}
|
||||
snap, err := link.readTapSnapshotPoll(0)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
hub.mergeTap(snap.GetEvents())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *wsHub) clientCount() int {
|
||||
h.mu.RLock()
|
||||
n := len(h.clients)
|
||||
@@ -490,15 +743,15 @@ func formatMAC(mac []byte) string {
|
||||
return hex.EncodeToString(mac)
|
||||
}
|
||||
|
||||
func runPoller(link *managedSerial, portName string, hub *wsHub, streamCtl *accelStreamCtl, interval time.Duration, stop <-chan struct{}) {
|
||||
// streamCtl kept for external API; dashboard uses hub.state AccelStream flags.
|
||||
func runPoller(link *managedSerial, portName string, hub *wsHub, streamCtl *accelStreamCtl, tapCtl *tapNotifyCtl, interval time.Duration, stop <-chan struct{}) {
|
||||
// streamCtl / tapCtl kept for external API; dashboard uses hub.state flags.
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
uartUp := false
|
||||
var lastGood DashboardState
|
||||
publish := func() {
|
||||
st := pollDashboard(link, portName, &lastGood, streamCtl)
|
||||
st := pollDashboard(link, portName, &lastGood, streamCtl, tapCtl)
|
||||
if st.UARTConnected && st.SerialOK {
|
||||
lastGood = st
|
||||
}
|
||||
|
||||
+7
-1
@@ -16,6 +16,8 @@ func usage() {
|
||||
fmt.Fprintf(os.Stderr, " version firmware version and git hash\n")
|
||||
fmt.Fprintf(os.Stderr, " clients registered ESP-NOW slaves on the master\n")
|
||||
fmt.Fprintf(os.Stderr, " deadzone get/set accelerometer deadzone (LSB)\n")
|
||||
fmt.Fprintf(os.Stderr, " tap-notify get/set which tap kinds notify via ESP-NOW\n")
|
||||
fmt.Fprintf(os.Stderr, " tap read cached tap events from master\n")
|
||||
fmt.Fprintf(os.Stderr, " accel read cached slave accel snapshot from master\n")
|
||||
fmt.Fprintf(os.Stderr, " unicast-test send ESP-NOW unicast test to one slave\n")
|
||||
fmt.Fprintf(os.Stderr, " test run automated scenario (see testdata/)\n")
|
||||
@@ -51,7 +53,7 @@ func main() {
|
||||
os.Exit(2)
|
||||
}
|
||||
runErr = runServe(*portName, *baud, flag.Args()[1:])
|
||||
case "version", "clients", "client-info", "deadzone", "accel-deadzone", "accel", "accel-read", "accel_read", "unicast-test", "unicast_test", "led-ring", "led_ring", "find-me", "find_me", "restart", "ota", "ota-progress", "ota_progress":
|
||||
case "version", "clients", "client-info", "deadzone", "accel-deadzone", "tap-notify", "tap_notify", "tap", "accel", "accel-read", "accel_read", "unicast-test", "unicast_test", "led-ring", "led_ring", "find-me", "find_me", "restart", "ota", "ota-progress", "ota_progress":
|
||||
if *portName == "" {
|
||||
fmt.Fprintf(os.Stderr, "command %q requires -port\n\n", cmd)
|
||||
usage()
|
||||
@@ -69,6 +71,10 @@ func main() {
|
||||
runErr = runClients(sp)
|
||||
case "deadzone", "accel-deadzone":
|
||||
runErr = runDeadzone(sp, flag.Args()[1:])
|
||||
case "tap-notify", "tap_notify":
|
||||
runErr = runTapNotify(sp, flag.Args()[1:])
|
||||
case "tap":
|
||||
runErr = runTapSnapshot(sp, flag.Args()[1:])
|
||||
case "accel", "accel-read", "accel_read":
|
||||
runErr = runAccel(sp)
|
||||
case "unicast-test", "unicast_test":
|
||||
|
||||
+665
-131
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import "sync"
|
||||
|
||||
// tapNotifyCtl tracks which slaves have tap notify enabled (mirrors firmware / dashboard).
|
||||
type tapNotifyCtl struct {
|
||||
mu sync.Mutex
|
||||
flags map[uint32]tapNotifyFlags
|
||||
}
|
||||
|
||||
type tapNotifyFlags struct {
|
||||
single bool
|
||||
doubleTap bool
|
||||
triple bool
|
||||
}
|
||||
|
||||
func newTapNotifyCtl() *tapNotifyCtl {
|
||||
return &tapNotifyCtl{flags: make(map[uint32]tapNotifyFlags)}
|
||||
}
|
||||
|
||||
func (c *tapNotifyCtl) Set(clientID uint32, single, doubleTap, triple bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !single && !doubleTap && !triple {
|
||||
delete(c.flags, clientID)
|
||||
return
|
||||
}
|
||||
c.flags[clientID] = tapNotifyFlags{single: single, doubleTap: doubleTap, triple: triple}
|
||||
}
|
||||
|
||||
func (c *tapNotifyCtl) Any() bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return len(c.flags) > 0
|
||||
}
|
||||
|
||||
func (c *tapNotifyCtl) SyncFromClients(clients []ClientView) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.flags = make(map[uint32]tapNotifyFlags)
|
||||
for _, cl := range clients {
|
||||
if cl.TapNotifySingle || cl.TapNotifyDouble || cl.TapNotifyTriple {
|
||||
c.flags[cl.ID] = tapNotifyFlags{
|
||||
single: cl.TapNotifySingle,
|
||||
doubleTap: cl.TapNotifyDouble,
|
||||
triple: cl.TapNotifyTriple,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+227
-3
@@ -62,6 +62,25 @@
|
||||
}
|
||||
.accel-stale { color: var(--pp-text-muted); }
|
||||
|
||||
.tap-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.15rem;
|
||||
font-size: 0.72rem;
|
||||
color: var(--pp-text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.tap-toggle input { margin: 0; }
|
||||
.tap-hit {
|
||||
color: #ffd166;
|
||||
font-weight: 600;
|
||||
animation: tap-flash 2s ease-out;
|
||||
}
|
||||
@keyframes tap-flash {
|
||||
from { color: #fff; transform: scale(1.08); }
|
||||
to { color: #ffd166; transform: scale(1); }
|
||||
}
|
||||
|
||||
.pp-table {
|
||||
--bs-table-color: var(--pp-text);
|
||||
--bs-table-bg: transparent;
|
||||
@@ -271,9 +290,21 @@
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-muted small px-3 pt-2 mb-0">
|
||||
Accel-Stream pro Slave per „Stream an“ aktivieren (~16 ms ESP-NOW). Ohne Aktivierung keine Werte.
|
||||
Accel-Stream pro Slave per „Stream an“ aktivieren (~16 ms ESP-NOW). Tap-Notify (S/D/T)
|
||||
konfiguriert den Slave; „Empfang an“ startet das Abfragen von Tap-Events (~16 ms).
|
||||
</p>
|
||||
<div class="card-body p-0 pt-2">
|
||||
<div class="px-3 pb-2 d-flex flex-wrap gap-2 align-items-center">
|
||||
<span class="text-muted small">Tap alle Slaves:</span>
|
||||
<label class="tap-toggle"><input type="checkbox" x-model="allTapSingle" :disabled="busy"> S</label>
|
||||
<label class="tap-toggle"><input type="checkbox" x-model="allTapDouble" :disabled="busy"> D</label>
|
||||
<label class="tap-toggle"><input type="checkbox" x-model="allTapTriple" :disabled="busy"> T</label>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm"
|
||||
@click="setTapNotifyAll(allTapSingle, allTapDouble, allTapTriple)"
|
||||
:disabled="busy || !state.uart_connected">
|
||||
Tap setzen
|
||||
</button>
|
||||
</div>
|
||||
<div class="card-body p-0 pt-1">
|
||||
<div class="table-responsive">
|
||||
<table class="table pp-table table-hover">
|
||||
<thead>
|
||||
@@ -286,12 +317,14 @@
|
||||
<th>Accel (LSB)</th>
|
||||
<th>Akku</th>
|
||||
<th>Stream</th>
|
||||
<th>Tap-Notify</th>
|
||||
<th>Tap</th>
|
||||
<th>Aktion</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template x-if="!(state.clients || []).length">
|
||||
<tr><td colspan="9" class="text-muted text-center py-4">No clients</td></tr>
|
||||
<tr><td colspan="11" class="text-muted text-center py-4">No clients</td></tr>
|
||||
</template>
|
||||
<template x-for="c in (state.clients || [])" :key="c.id + c.mac">
|
||||
<tr>
|
||||
@@ -319,6 +352,40 @@
|
||||
:disabled="busy || !state.uart_connected || !c.available"
|
||||
x-text="c.accel_stream ? 'Aus' : 'An'"></button>
|
||||
</td>
|
||||
<td>
|
||||
<div class="d-flex flex-wrap gap-1 align-items-center">
|
||||
<label class="tap-toggle" title="Single tap">
|
||||
<input type="checkbox"
|
||||
:checked="c.tap_notify_single"
|
||||
@change="setTapNotify(c.id, $event.target.checked, c.tap_notify_double, c.tap_notify_triple)"
|
||||
:disabled="busy || !state.uart_connected || !c.available"> S
|
||||
</label>
|
||||
<label class="tap-toggle" title="Double tap">
|
||||
<input type="checkbox"
|
||||
:checked="c.tap_notify_double"
|
||||
@change="setTapNotify(c.id, c.tap_notify_single, $event.target.checked, c.tap_notify_triple)"
|
||||
:disabled="busy || !state.uart_connected || !c.available"> D
|
||||
</label>
|
||||
<label class="tap-toggle" title="Triple tap">
|
||||
<input type="checkbox"
|
||||
:checked="c.tap_notify_triple"
|
||||
@change="setTapNotify(c.id, c.tap_notify_single, c.tap_notify_double, $event.target.checked)"
|
||||
:disabled="busy || !state.uart_connected || !c.available"> T
|
||||
</label>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="d-flex flex-wrap gap-1 align-items-center">
|
||||
<button type="button"
|
||||
class="btn btn-sm"
|
||||
:class="c.tap_receive ? 'btn-warning' : 'btn-outline-success'"
|
||||
@click="setTapReceive(c.id, !c.tap_receive)"
|
||||
:disabled="busy || !state.uart_connected || !c.available || !tapNotifyAny(c)"
|
||||
x-text="c.tap_receive ? 'Aus' : 'An'"
|
||||
title="Tap-Events vom Master abfragen"></button>
|
||||
<span :class="tapCellClass(c)" x-text="formatLastTap(c)" :title="tapTitle(c)"></span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="d-flex flex-wrap gap-1 align-items-center">
|
||||
<input type="number" class="form-control form-control-sm dz-input"
|
||||
@@ -556,7 +623,13 @@
|
||||
wsConnected: false,
|
||||
masterDz: 100,
|
||||
allDz: 100,
|
||||
allTapSingle: false,
|
||||
allTapDouble: false,
|
||||
allTapTriple: false,
|
||||
slaveDz: {},
|
||||
TAP_DISPLAY_MS: 2000,
|
||||
tapDisplay: {},
|
||||
_tapClock: 0,
|
||||
otaFile: null,
|
||||
ota: {
|
||||
active: false, phase: '', step: '', percent: 0,
|
||||
@@ -584,6 +657,8 @@
|
||||
const url = proto + '//' + location.host + '/ws';
|
||||
if (this._batteryTimer) clearInterval(this._batteryTimer);
|
||||
this._batteryTimer = setInterval(() => this.refreshBattery(), 5000);
|
||||
if (this._tapTimer) clearInterval(this._tapTimer);
|
||||
this._tapTimer = setInterval(() => { this._tapClock++; }, 250);
|
||||
const connect = () => {
|
||||
this.ws = new WebSocket(url);
|
||||
this.ws.onopen = () => {
|
||||
@@ -608,6 +683,7 @@
|
||||
const prev = this.state;
|
||||
this.state = msg;
|
||||
this.preserveBatteryInState(prev, this.state);
|
||||
this.syncTapDisplay(msg.clients || []);
|
||||
if (msg.master?.deadzone != null) {
|
||||
this.masterDz = msg.master.deadzone;
|
||||
}
|
||||
@@ -718,6 +794,56 @@
|
||||
if (c.accel_age_ms != null && c.accel_age_ms > 200) return 'accel-stale';
|
||||
return '';
|
||||
},
|
||||
tapNotifyAny(c) {
|
||||
return !!(c?.tap_notify_single || c?.tap_notify_double || c?.tap_notify_triple);
|
||||
},
|
||||
syncTapDisplay(clients) {
|
||||
const now = Date.now();
|
||||
for (const c of clients) {
|
||||
if (!c?.last_tap || !c?.last_tap_at) continue;
|
||||
const prev = this.tapDisplay[c.id];
|
||||
if (!prev || c.last_tap_at >= prev.shownAt) {
|
||||
this.tapDisplay[c.id] = { kind: c.last_tap, shownAt: c.last_tap_at };
|
||||
}
|
||||
}
|
||||
for (const id of Object.keys(this.tapDisplay)) {
|
||||
if (now - this.tapDisplay[id].shownAt > this.TAP_DISPLAY_MS + 500) {
|
||||
delete this.tapDisplay[id];
|
||||
}
|
||||
}
|
||||
},
|
||||
activeTapDisplay(c) {
|
||||
void this._tapClock;
|
||||
const d = this.tapDisplay[c?.id];
|
||||
if (!d) return null;
|
||||
if (Date.now() - d.shownAt >= this.TAP_DISPLAY_MS) return null;
|
||||
return d;
|
||||
},
|
||||
formatLastTap(c) {
|
||||
if (!c?.tap_receive) return '—';
|
||||
if (!this.tapNotifyAny(c)) return '—';
|
||||
const labels = { single: 'Single', double: 'Double', triple: 'Triple' };
|
||||
const d = this.activeTapDisplay(c);
|
||||
if (d) return labels[d.kind] || d.kind;
|
||||
if (!c?.last_tap) return '…';
|
||||
return labels[c.last_tap] || c.last_tap;
|
||||
},
|
||||
tapTitle(c) {
|
||||
if (!c?.tap_receive) return 'Tap-Empfang aus — „An“ klicken';
|
||||
if (!this.tapNotifyAny(c)) return 'Tap-Notify nicht konfiguriert (S/D/T)';
|
||||
const d = this.activeTapDisplay(c);
|
||||
if (!d && !c?.last_tap) return 'Warte auf Tap-Event…';
|
||||
const kind = d?.kind || c?.last_tap;
|
||||
const at = d?.shownAt || c?.last_tap_at;
|
||||
const age = at ? (Date.now() - at) + ' ms her' : '';
|
||||
return `Letzter Tap: ${kind}${age ? ' · ' + age : ''}`;
|
||||
},
|
||||
tapCellClass(c) {
|
||||
if (this.activeTapDisplay(c)) return 'tap-hit';
|
||||
if (!c?.last_tap || !c?.last_tap_at) return 'text-muted';
|
||||
if (Date.now() - c.last_tap_at < this.TAP_DISPLAY_MS) return 'tap-hit';
|
||||
return '';
|
||||
},
|
||||
formatSize(n) {
|
||||
if (n == null) return '';
|
||||
if (n < 1024) return n + ' B';
|
||||
@@ -992,6 +1118,104 @@
|
||||
this.busy = false;
|
||||
}
|
||||
},
|
||||
patchClientTapNotify(clientId, single, doubleTap, triple) {
|
||||
const clients = (this.state.clients || []).map((c) => {
|
||||
if (c.id !== clientId) return c;
|
||||
const next = {
|
||||
...c,
|
||||
tap_notify_single: single,
|
||||
tap_notify_double: doubleTap,
|
||||
tap_notify_triple: triple
|
||||
};
|
||||
if (!single && !doubleTap && !triple) {
|
||||
next.last_tap = '';
|
||||
next.last_tap_at = 0;
|
||||
delete this.tapDisplay[c.id];
|
||||
}
|
||||
return next;
|
||||
});
|
||||
this.state = { ...this.state, clients };
|
||||
},
|
||||
async setTapNotify(clientId, single, doubleTap, triple) {
|
||||
this.busy = true;
|
||||
try {
|
||||
const r = await fetch(`/api/clients/${clientId}/tap-notify`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ single, double_tap: doubleTap, triple })
|
||||
});
|
||||
const data = await r.json();
|
||||
if (!r.ok || !data.success) {
|
||||
this.flash(data.error || `Tap-Notify Slave ${clientId} fehlgeschlagen`, false);
|
||||
return;
|
||||
}
|
||||
this.patchClientTapNotify(clientId, !!data.single, !!data.double_tap, !!data.triple);
|
||||
const on = [data.single && 'S', data.double_tap && 'D', data.triple && 'T'].filter(Boolean).join('/') || 'aus';
|
||||
this.flash(`Slave ${clientId}: Tap-Notify ${on}`, true);
|
||||
} catch (e) {
|
||||
this.flash(String(e), false);
|
||||
} finally {
|
||||
this.busy = false;
|
||||
}
|
||||
},
|
||||
async setTapNotifyAll(single, doubleTap, triple) {
|
||||
this.busy = true;
|
||||
try {
|
||||
const r = await fetch('/api/tap-notify', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ all_clients: true, single, double_tap: doubleTap, triple })
|
||||
});
|
||||
const data = await r.json();
|
||||
if (!r.ok || !data.success) {
|
||||
this.flash(data.error || 'Tap-Notify für alle Slaves fehlgeschlagen', false);
|
||||
return;
|
||||
}
|
||||
for (const c of (this.state.clients || [])) {
|
||||
this.patchClientTapNotify(c.id, !!single, !!doubleTap, !!triple);
|
||||
}
|
||||
const on = [single && 'S', doubleTap && 'D', triple && 'T'].filter(Boolean).join('/') || 'aus';
|
||||
this.flash(`Alle Slaves: Tap-Notify ${on} (${data.slaves_updated} aktualisiert)`, true);
|
||||
} catch (e) {
|
||||
this.flash(String(e), false);
|
||||
} finally {
|
||||
this.busy = false;
|
||||
}
|
||||
},
|
||||
patchClientTapReceive(clientId, enabled) {
|
||||
const clients = (this.state.clients || []).map((c) => {
|
||||
if (c.id !== clientId) return c;
|
||||
const next = { ...c, tap_receive: enabled };
|
||||
if (!enabled) {
|
||||
next.last_tap = '';
|
||||
next.last_tap_at = 0;
|
||||
delete this.tapDisplay[clientId];
|
||||
}
|
||||
return next;
|
||||
});
|
||||
this.state = { ...this.state, clients };
|
||||
},
|
||||
async setTapReceive(clientId, enable) {
|
||||
this.busy = true;
|
||||
try {
|
||||
const r = await fetch(`/api/clients/${clientId}/tap-receive`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enable })
|
||||
});
|
||||
const data = await r.json();
|
||||
if (!r.ok || !data.success) {
|
||||
this.flash(data.error || `Tap-Empfang Slave ${clientId} fehlgeschlagen`, false);
|
||||
return;
|
||||
}
|
||||
this.patchClientTapReceive(clientId, !!data.enabled);
|
||||
this.flash(`Slave ${clientId}: Tap-Empfang ${data.enabled ? 'an' : 'aus'}`, true);
|
||||
} catch (e) {
|
||||
this.flash(String(e), false);
|
||||
} finally {
|
||||
this.busy = false;
|
||||
}
|
||||
},
|
||||
async setDeadzoneAll(deadzone) {
|
||||
if (deadzone == null || deadzone < 0) {
|
||||
this.flash('Ungültiger Deadzone-Wert', false);
|
||||
|
||||
Reference in New Issue
Block a user