feat(events): deliver state changes to the configurable operator event center

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:27 +03:00
parent d4ed96f3cd
commit 1b67d5f7df
35 changed files with 2058 additions and 8 deletions
@@ -0,0 +1,258 @@
package node
import (
"context"
"encoding/json"
"log"
"os"
"regexp"
"sync"
"time"
)
// Transitions share the existing authenticated heartbeat. This queue never opens a transport.
type operatorEvent struct {
ID string `json:"id"`
At int64 `json:"at"`
Kind string `json:"kind"`
Device string `json:"device,omitempty"`
Session string `json:"session,omitempty"`
}
type operatorJournal struct {
States map[string]string `json:"states,omitempty"`
Binding string `json:"binding"`
Last string `json:"last"`
Delivery string `json:"delivery"`
Pending []operatorEvent `json:"pending,omitempty"`
}
type operatorOutbox struct {
mu sync.Mutex
path string
data operatorJournal
owner string
bound bool
}
func openOperatorOutbox(path string) *operatorOutbox {
s := &operatorOutbox{path: path}
raw, err := os.ReadFile(path)
if err == nil && len(raw) <= 131072 {
var data operatorJournal
if json.Unmarshal(raw, &data) == nil && len(data.Pending) <= 128 && len(data.States) <= 256 {
s.data = data
}
} else if err != nil && !os.IsNotExist(err) {
log.Printf("operator event journal: %v", err)
}
return s
}
// Ignore observations still arriving from a retired binding after a re-pair.
func (s *operatorOutbox) setOwner(binding string) {
if s == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
s.owner, s.bound = binding, true
}
func (s *operatorOutbox) commit(data operatorJournal) bool {
if err := savePrivateJSON(s.path, data); err != nil {
log.Printf("operator event journal: %v", err)
return false
}
s.data = data
return true
}
func (s *operatorOutbox) transition(binding, source, status string, at time.Time) {
s.mu.Lock()
defer s.mu.Unlock()
if s.bound && s.owner != binding {
return
}
data := s.data
if data.Binding != binding {
data = operatorJournal{Binding: binding}
}
previous := &data.Last
if source == "delivery" {
previous = &data.Delivery
}
if status == *previous || (*previous == "" && status != "online") {
return
}
if *previous != "" {
kind := source + ".loss"
if status == "online" {
kind = source + ".recovery"
}
data.enqueue(operatorEvent{ID: token(), At: at.Unix(), Kind: kind})
}
*previous = status
s.commit(data)
}
func (s *operatorOutbox) batch(binding string) []operatorEvent {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
if s.data.Binding != binding {
return nil
}
rows := s.data.Pending
return append([]operatorEvent(nil), rows[:min(len(rows), 8)]...)
}
func (s *operatorOutbox) acknowledge(binding string, sent []operatorEvent, raw json.RawMessage) {
if s == nil || len(sent) == 0 {
return
}
var id string
if json.Unmarshal(raw, &id) != nil || id != sent[len(sent)-1].ID {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.data.Binding != binding {
return
}
for i, e := range s.data.Pending {
if e.ID == id {
data := s.data
data.Pending = append([]operatorEvent(nil), data.Pending[i+1:]...)
s.commit(data)
return
}
}
}
type operatorSample struct {
snapshot map[string]any
at time.Time
watch bool
}
// The driver intentionally stops refreshing sample ages without a viewer. Do not
// classify that as a fault. Device disappearance is still observable while idle.
func vescEventStatus(sample operatorSample) string {
devices, _ := sample.snapshot["devices"].([]any)
profile, _ := sample.snapshot["profile"].(map[string]any)
bindings, _ := profile["bindings"].(map[string]any)
if sample.snapshot["supported"] != true || len(devices) == 0 {
return "lost"
}
for _, raw := range bindings {
b, _ := raw.(map[string]any)
found := false
for _, r := range devices {
d, _ := r.(map[string]any)
id, _ := b["device_id"].(string)
uuid, _ := b["uuid"].(string)
if id != "" && uuid != "" && d["id"] == id && d["uuid"] == uuid {
found = true
break
}
}
if !found {
return "lost"
}
}
for _, raw := range devices {
d, _ := raw.(map[string]any)
age, ok := finiteNumber(d["age_ms"])
if !ok || age < 0 || age >= 1000 {
if !sample.watch {
return ""
}
return "lost"
}
}
return "online"
}
type operatorDebounce struct {
candidate string
since, last time.Time
}
func (d *operatorDebounce) sample(sample operatorSample) (string, time.Time) {
return d.update(vescEventStatus(sample), sample.at, time.Second)
}
func (d *operatorDebounce) update(status string, at time.Time, maxGap time.Duration) (string, time.Time) {
if status != d.candidate || (maxGap > 0 && at.Sub(d.last) > maxGap) {
d.candidate, d.since = status, at
}
d.last = at
if status != "" && at.Sub(d.since) >= 2*time.Second {
return status, d.since
}
return "", time.Time{}
}
func (s *operatorOutbox) observe(ctx context.Context, binding string, samples <-chan operatorSample, delivery <-chan deliveryOutcome) {
var debounce, transport operatorDebounce
observerStarted := time.Now()
for {
select {
case <-ctx.Done():
return
case result := <-delivery:
if status, at := transport.update(result.status, result.at, 0); status != "" {
s.transition(binding, "delivery", status, at)
}
case sample := <-samples:
s.driverSafety(binding, sample, observerStarted)
if status, at := debounce.sample(sample); status != "" {
s.transition(binding, "telemetry", status, at)
}
}
}
}
type deliveryOutcome struct {
status string
at time.Time
}
func (s *roverStreamState) noteTelemetryDelivery(success bool) {
if s.operatorDelivery == nil {
return
}
status := "lost"
if success {
status = "online"
}
select {
case s.operatorDelivery <- deliveryOutcome{status, time.Now()}:
default:
}
}
// A driver fault can occur after Core has already lost contact. Record the
// driver's receipt, including its original time, without executing any action.
var controlSessionID = regexp.MustCompile("^[0-9a-f]{32}$")
func (s *operatorOutbox) driverSafety(binding string, sample operatorSample, started time.Time) {
stop, _ := sample.snapshot["last_stop"].(map[string]any)
id, _ := stop["session_id"].(string)
if stop["state"] == "fault" && controlSessionID.MatchString(id) {
stamp, _ := stop["at"].(string)
at, err := time.Parse(time.RFC3339Nano, stamp)
if err == nil && !at.Before(started) && !at.After(sample.at.Add(time.Second)) {
s.recordState(binding, "driver-fault", id, operatorEvent{Kind: "control.stop", At: at.Unix(), Session: id}, true)
}
}
if sample.snapshot["state"] != "ready" && sample.snapshot["state"] != "driving" {
return
}
session, _ := sample.snapshot["session_id"].(string)
s.mu.Lock()
fault := s.data.States["driver-fault"]
recovered := s.data.States["driver-recovery"]
eligible := s.data.Binding == binding && fault != "" && fault != recovered && session != fault
s.mu.Unlock()
if eligible && controlSessionID.MatchString(session) {
s.recordState(binding, "driver-recovery", fault, operatorEvent{Kind: "control.ready", At: sample.at.Unix(), Session: session}, true)
}
}
@@ -0,0 +1,179 @@
package node
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestOperatorEventsQuietDebounceAndOfflineReplay(t *testing.T) {
path := filepath.Join(t.TempDir(), "events.json")
out := openOperatorOutbox(path)
var filter operatorDebounce
now := time.Unix(1000, 0)
sample := func(count int, age float64, watch bool) {
snap := map[string]any{"supported": true, "devices": []any{map[string]any{"id": "a", "uuid": "b", "age_ms": age}}}
for i := 0; i < count; i++ {
now = now.Add(250 * time.Millisecond)
if status, at := filter.sample(operatorSample{snap, now, watch}); status != "" {
out.transition("bound", "telemetry", status, at)
}
}
}
sample(100, 14, true)
sample(6, 1200, true)
sample(100, 12, true)
sample(80, 9000, false)
if len(out.batch("bound")) != 0 {
t.Fatal("healthy, idle or transient produced network data")
}
sample(40, 2000, true)
sample(40, 13, true)
batch := out.batch("bound")
if len(batch) != 2 || batch[0].Kind != "telemetry.loss" || batch[1].Kind != "telemetry.recovery" {
t.Fatal(batch)
}
out = openOperatorOutbox(path)
if len(out.batch("other")) != 0 || out.batch("bound")[0].ID != batch[0].ID {
t.Fatal("binding/restart")
}
out.acknowledge("bound", batch, json.RawMessage(`"wrong"`))
if len(out.batch("bound")) != 2 {
t.Fatal("unconfirmed batch erased")
}
raw, _ := json.Marshal(batch[1].ID)
out.acknowledge("bound", batch, raw)
if len(openOperatorOutbox(path).batch("bound")) != 0 {
t.Fatal("confirmed data replayed")
}
}
func TestDeliveryFailureIsIndependentOfLocalVESC(t *testing.T) {
out := openOperatorOutbox(filepath.Join(t.TempDir(), "events.json"))
var filter operatorDebounce
start := time.Unix(1000, 0)
out.transition("board", "telemetry", "online", start)
for i, state := range []string{"online", "online", "online", "lost", "online", "lost", "lost", "lost", "online", "online", "online"} {
if confirmed, at := filter.update(state, start.Add(time.Duration(i)*time.Second), 0); confirmed != "" {
out.transition("board", "delivery", confirmed, at)
}
}
batch := out.batch("board")
if len(batch) != 2 || batch[0].Kind != "delivery.loss" || batch[0].At != 1005 || batch[1].Kind != "delivery.recovery" {
t.Fatal(batch)
}
}
func TestBoardEventTransitionsAcrossBootAndOffline(t *testing.T) {
path := filepath.Join(t.TempDir(), "events.json")
out := openOperatorOutbox(path)
at := time.Unix(1450, 0)
id, second := modelDeviceID(&sensorModels[2], "camera A"), modelDeviceID(&sensorModels[2], "camera B")
a := usbSensor{model: &sensorModels[2], id: id}
b := usbSensor{model: &sensorModels[2], id: second}
for range 30 {
out.observeCameras("owner", []usbSensor{a, b}, map[string]string{id: "online", second: "idle"}, at)
out.observeState("owner", "boot", "boot-1", "board.boot", "", at, false)
out.observeState("owner", "thermal", "online", "thermal.recovery", "", at, false)
}
if got := out.batch("owner"); len(got) != 0 {
t.Fatal("initial inventory generated traffic", got)
}
for range 20 {
out.observeCameras("owner", []usbSensor{a}, map[string]string{id: "lost"}, at)
out.observeState("owner", "thermal", "lost", "thermal.loss", "", at, true)
}
out = openOperatorOutbox(path)
for range 20 {
out.observeCameras("owner", []usbSensor{a, b}, map[string]string{id: "online", second: "idle"}, at)
out.observeState("owner", "thermal", "online", "thermal.recovery", "", at, false)
out.observeState("owner", "shutdown", "boot-1", "board.shutdown", "", at, true)
out.observeState("owner", "boot", "boot-2", "board.boot", "", at, false)
}
seen := map[string]int{}
batch := out.batch("owner")
for _, e := range batch {
seen[e.Kind]++
if e.Kind == "camera.loss" && e.Device != second {
t.Fatal(e)
}
if e.Kind == "frames.loss" && e.Device != id {
t.Fatal(e)
}
}
for _, kind := range []string{"frames.loss", "frames.recovery", "camera.loss", "camera.recovery", "thermal.loss", "thermal.recovery", "board.shutdown", "board.boot"} {
if seen[kind] != 1 {
t.Fatalf("%s: %v", kind, batch)
}
}
ack, _ := json.Marshal(batch[len(batch)-1].ID)
out.acknowledge("owner", batch, ack)
out.observeCameras("owner", []usbSensor{a, b}, map[string]string{id: "idle"}, at)
out.observeCameras("owner", []usbSensor{a, b}, map[string]string{id: "online"}, at)
if len(out.batch("owner")) != 0 || len(out.batch("other")) != 0 {
t.Fatal("idle viewer generated a recovery")
}
}
func TestCPUCoolingScopeAndUnreadableState(t *testing.T) {
root := t.TempDir()
create := func(n, typ, val string) {
p := filepath.Join(root, "sys/class/thermal", n)
if err := os.MkdirAll(p, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(p, "type"), []byte(typ), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(p, "cur_state"), []byte(val), 0644); err != nil {
t.Fatal(err)
}
}
create("cooling_device0", "Fan", "3")
if cpuCoolingState(root) != "" {
t.Fatal("fan does not prove processor throttling")
}
create("cooling_device1", "Processor", "2")
if cpuCoolingState(root) != "lost" {
t.Fatal("missed thermal limit")
}
create("cooling_device2", "Processor", "unknown")
create("cooling_device1", "Processor", "0")
if cpuCoolingState(root) != "" {
t.Fatal("unknown read reported as recovery")
}
create("cooling_device2", "Processor", "0")
if cpuCoolingState(root) != "online" {
t.Fatal("missed recovery")
}
}
func TestDriverFaultRecoveryAndRetiredBinding(t *testing.T) {
out := openOperatorOutbox(filepath.Join(t.TempDir(), "events.json"))
out.setOwner("board")
now := time.Unix(1000, 0)
ended, next := strings.Repeat("a", 32), strings.Repeat("b", 32)
receipt := map[string]any{"state": "fault", "session_id": ended, "at": now.Format(time.RFC3339Nano)}
snap := map[string]any{"state": "fault", "last_stop": receipt}
sample := operatorSample{snapshot: snap, at: now}
out.driverSafety("board", sample, now.Add(time.Minute))
if len(out.batch("board")) != 0 {
t.Fatal("old receipt replayed")
}
for range 50 {
out.driverSafety("board", sample, now)
}
snap["state"], snap["session_id"] = "ready", next
for range 50 {
out.driverSafety("board", sample, now)
}
out.observeState("retired", "thermal", "lost", "thermal.loss", "", now, true)
out.transition("retired", "telemetry", "online", now)
got := out.batch("board")
if len(got) != 2 || got[0].Kind != "control.stop" || got[0].Session != ended || got[1].Kind != "control.ready" || got[1].Session != next {
t.Fatal(got)
}
}
@@ -0,0 +1,189 @@
package node
import (
"bufio"
"context"
_ "embed"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
// The saved state changes only on an edge. Neither a disk write nor an event
// packet is needed for another identical observation.
func (s *operatorOutbox) observeState(binding, key, value, kind, device string, at time.Time, reportFirst bool) {
s.recordState(binding, key, value, operatorEvent{At: at.Unix(), Kind: kind, Device: device}, reportFirst)
}
func (s *operatorOutbox) recordState(binding, key, value string, event operatorEvent, reportFirst bool) {
if s == nil || binding == "" || value == "" {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.bound && s.owner != binding {
return
}
data := s.data
if data.Binding != binding {
data = operatorJournal{Binding: binding}
}
last := data.States[key]
if last == value {
return
}
states := make(map[string]string, len(data.States)+1)
for k, v := range data.States {
states[k] = v
}
// Retire inactive attachments first. Never let a changing USB identity grow the journal forever.
if last == "" && len(states) >= 256 {
for k, v := range states {
if (strings.HasPrefix(k, "camera:") && v == "lost") || (strings.HasPrefix(k, "frames:") && v == "idle") {
delete(states, k)
break
}
}
if len(states) >= 256 {
return
}
}
states[key] = value
data.States = states
if event.Kind != "" && (last != "" || reportFirst) && !(last == "idle" && event.Kind == "frames.recovery") {
event.ID = token()
data.enqueue(event)
}
s.commit(data)
}
func (data *operatorJournal) enqueue(event operatorEvent) {
pending := data.Pending
if len(pending) >= 128 {
pending = pending[1:]
}
data.Pending = append(append([]operatorEvent(nil), pending...), event)
}
func (s *operatorOutbox) observeCameras(binding string, usb []usbSensor, frames map[string]string, at time.Time) {
if s == nil {
return
}
present := map[string]bool{}
for _, u := range usb {
if u.model.ID == "insta360.x4" || u.model.ID == "realsense.d455" {
present[u.id] = true
}
}
s.mu.Lock()
primed := s.data.Binding == binding && s.data.States["usb"] == "known"
var absent []string
if primed {
for k, state := range s.data.States {
if id, ok := strings.CutPrefix(k, "camera:"); ok && state == "online" && !present[id] {
absent = append(absent, id)
}
}
}
s.mu.Unlock()
for _, id := range absent {
s.observeState(binding, "camera:"+id, "lost", "camera.loss", id, at, false)
s.observeState(binding, "frames:"+id, "idle", "", id, at, false)
}
for id := range present {
s.observeState(binding, "camera:"+id, "online", "camera.recovery", id, at, primed)
status := frames[id]
switch status {
case "idle":
s.observeState(binding, "frames:"+id, status, "", id, at, false)
case "online":
s.observeState(binding, "frames:"+id, status, "frames.recovery", id, at, false)
case "lost":
s.observeState(binding, "frames:"+id, status, "frames.loss", id, at, true)
}
}
s.observeState(binding, "usb", "known", "", "", at, false)
}
func cpuCoolingState(root string) string {
paths, _ := filepath.Glob(filepath.Join(root, "sys/class/thermal/cooling_device*"))
known, unknown := false, false
for _, p := range paths {
raw, _ := os.ReadFile(filepath.Join(p, "type"))
typ := strings.ToLower(strings.TrimSpace(string(raw)))
if typ != "processor" && typ != "intel_powerclamp" && !strings.HasPrefix(typ, "thermal-cpufreq") && !strings.HasPrefix(typ, "cpufreq-") {
continue
}
raw, err := os.ReadFile(filepath.Join(p, "cur_state"))
level, e := strconv.Atoi(strings.TrimSpace(string(raw)))
if err != nil || e != nil || level < 0 {
unknown = true
continue
}
known = true
if level > 0 {
return "lost"
}
}
if known && !unknown {
return "online"
}
return ""
}
var linuxBootID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")
func bootIdentity() string {
b, _ := os.ReadFile("/proc/sys/kernel/random/boot_id")
id := strings.TrimSpace(string(b))
if linuxBootID.MatchString(id) {
return id
}
return ""
}
//go:embed operator_shutdown.py
var shutdownSubscriber string
func (p *Pairing) watchShutdown(ctx context.Context) {
if runtime.GOOS != "linux" || p.operatorEvents == nil {
return
}
boot := bootIdentity()
if boot == "" {
return
}
for ctx.Err() == nil {
cmd := exec.CommandContext(ctx, "/usr/bin/python3", "-I", "-c", shutdownSubscriber)
output, err := cmd.StdoutPipe()
if err == nil && cmd.Start() == nil {
scanner := bufio.NewScanner(output)
for scanner.Scan() {
if scanner.Text() != "prepare" {
continue
}
if b := p.roverBinding(); b != nil {
// A Core-initiated shutdown already has an authenticated command receipt.
if p.Power != nil && p.Power.shuttingDown(b.BindingID) {
continue
}
p.operatorEvents.observeState(b.BindingID, "shutdown", boot, "board.shutdown", "", time.Now(), true)
}
}
_ = cmd.Wait()
}
if !roverWait(ctx, 30*time.Second) {
return
}
}
}
func (p *NodePower) shuttingDown(binding string) bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.command.BindingID == binding && (p.result.State == "executing" || p.result.State == "submitted")
}
@@ -0,0 +1,23 @@
"""Subscribe locally to logind. A power cut cannot produce this signal."""
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
def prepare(active):
if active:
print("prepare", flush=True)
bus.add_signal_receiver(
prepare,
"PrepareForShutdown",
"org.freedesktop.login1.Manager",
bus_name="org.freedesktop.login1",
path="/org/freedesktop/login1",
)
GLib.MainLoop().run()
+2
View File
@@ -44,6 +44,7 @@ type PairState struct {
Revocations []CoreBinding `json:"revocations,omitempty"`
}
type Pairing struct {
operatorEvents *operatorOutbox
Power *NodePower
Budget *LinkBudget
Routers *routers.Collector
@@ -74,6 +75,7 @@ func OpenPairing(store *Store, dir, version string, inventory func() Inventory)
p := &Pairing{store: store, path: filepath.Join(dir, "core-binding.json"), now: time.Now, inventory: inventory, version: version, connection: "offline", clients: make(map[string]*http.Client), state: PairState{Schema: PairSchema, Phase: "unpaired"}}
id, name := store.Public()
p.RoverConfiguration = OpenRoverConfiguration(dir, id, name)
p.operatorEvents = openOperatorOutbox(filepath.Join(dir, "operator-events.json"))
data, e := os.ReadFile(p.path)
if os.IsNotExist(e) {
return p, nil
@@ -155,6 +155,7 @@ func (p *Pairing) Run(ctx context.Context) {
p.uplink = newUplink(ctx)
go monitorNetBird(ctx)
go p.networkWatch(ctx)
go p.watchShutdown(ctx)
go p.channel(ctx)
go p.roverChannel(ctx)
var server *http.Server
@@ -307,6 +308,7 @@ func (p *Pairing) sendEncoded(ctx context.Context, b CoreBinding, path string, p
}
func (p *Pairing) channel(ctx context.Context) {
instance := "agent_" + token()
boot := bootIdentity()
var changed <-chan struct{}
var speedChanged <-chan struct{}
if p.Routers != nil {
@@ -348,7 +350,17 @@ func (p *Pairing) channel(ctx context.Context) {
}
if binding != nil {
id, name := p.store.Public()
payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID, "node_id": id, "name": name, "version": p.version, "execution_binding": map[string]string{"node_id": id, "agent_instance_id": instance, "platform": "linux"}, "host": p.inventory(), "devices": []any{}}
host := p.inventory()
at := p.now()
p.operatorEvents.observeState(binding.BindingID, "boot", boot, "board.boot", "", at, false)
if status := cpuCoolingState("/"); status != "" {
kind := "thermal.recovery"
if status == "lost" {
kind = "thermal.loss"
}
p.operatorEvents.observeState(binding.BindingID, "thermal", status, kind, "", at, status == "lost")
}
payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID, "node_id": id, "name": name, "version": p.version, "execution_binding": map[string]string{"node_id": id, "agent_instance_id": instance, "platform": "linux"}, "host": host, "devices": []any{}}
if p.RoverConfiguration != nil {
payload["rover_configuration"] = p.RoverConfiguration.Snapshot()
}
@@ -366,7 +378,10 @@ func (p *Pairing) channel(ctx context.Context) {
payload["core_endpoint"] = binding.Endpoint
payload["endpoint_revision"] = binding.EndpointRevision
if p.Sensors != nil {
inv := p.Sensors.Inventory()
inv, usb, frames := p.Sensors.inventoryWithCameraState()
if host.USBReadable && usb != nil {
p.operatorEvents.observeCameras(binding.BindingID, usb, frames, p.now())
}
payload["devices"] = inv["items"]
payload["sensor_state"] = inv
payload["sensor_results"] = p.Sensors.RemoteResults()
@@ -384,6 +399,10 @@ func (p *Pairing) channel(ctx context.Context) {
if p.Routers != nil {
payload["routers"] = p.Routers.Snapshot()
}
sentEvents := p.operatorEvents.batch(binding.BindingID)
if len(sentEvents) > 0 {
payload["operator_events_v1"] = sentEvents
}
result, status, e := p.sendHeartbeat(ctx, *binding, payload)
received := time.Now()
var networkRequestResult json.RawMessage
@@ -457,6 +476,7 @@ func (p *Pairing) channel(ctx context.Context) {
}
p.mu.Unlock()
if e == nil && status == http.StatusOK {
p.operatorEvents.acknowledge(binding.BindingID, sentEvents, result["operator_events_ack"])
p.networkLocalAcknowledged(*binding)
}
p.acceptNetworkRequestResult(networkRequestResult)
@@ -20,10 +20,12 @@ import (
// The control loop reads an immutable value, never the background-work mutex.
func (p *Pairing) publishRoverBinding() {
if p.state.Phase != "paired" || p.state.Binding == nil {
p.operatorEvents.setOwner("")
p.roverAuthority.Store(nil)
return
}
b := *p.state.Binding
p.operatorEvents.setOwner(b.BindingID)
p.roverAuthority.Store(&b)
}
func (p *Pairing) roverBinding() *CoreBinding {
@@ -84,6 +86,15 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
ctx, cancel := context.WithCancel(parent)
var workers sync.WaitGroup
defer func() { cancel(); workers.Wait() }()
if p.operatorEvents != nil {
state.operatorSamples = make(chan operatorSample, 1)
state.operatorDelivery = make(chan deliveryOutcome, 2)
workers.Add(1)
go func() {
defer workers.Done()
p.operatorEvents.observe(ctx, b.BindingID, state.operatorSamples, state.operatorDelivery)
}()
}
workers.Add(4)
optional := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
defer optional.CloseIdleConnections()
@@ -26,6 +26,9 @@ type roverStreamReply struct {
// clocks. Server time was sampled after that send, so it gives an upper bound
// on server-minus-local monotonic offset even on an asymmetric network.
type roverStreamState struct {
operatorDelivery chan deliveryOutcome
operatorSamples chan operatorSample
lastOperatorSample time.Time
budget *LinkBudget
latestDatagram bool
roverDetails bool
@@ -225,6 +228,13 @@ func (s *roverStreamState) deliveredAt(snapshot map[string]any, stop uint64, sam
defer s.mu.Unlock()
s.snapshotAt = sampled
s.snapshot = snapshot
if s.operatorSamples != nil && sampled.Sub(s.lastOperatorSample) >= 250*time.Millisecond {
select {
case s.operatorSamples <- operatorSample{snapshot, sampled, s.watch}:
s.lastOperatorSample = sampled
default:
}
}
s.snapshotClock = s.observationClockAt(sampled)
if stop != 0 && stop == s.stopRevision {
s.stopPending = false
@@ -51,6 +51,7 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b
acknowledgedRevision = 0
budgetAt = time.Time{}
if !connected {
state.noteTelemetryDelivery(false)
if !roverWait(ctx, 250*time.Millisecond) {
return
}
@@ -71,6 +72,9 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b
state.stopStream()
}
frame := result.frame
if result.sequence > applied {
state.noteTelemetryDelivery(frame.Stage == "")
}
state.recordDev("telemetry", roverTelemetryEvidence(result, state, epoch))
diagnostic.record(result.started, frame)
if frame.Stage == "" || frame.Stage == "telemetry_transport" {
@@ -119,10 +119,14 @@ type usbSensor struct {
// Read-only OS discovery works before any vendor runtime has been installed.
// An absent or duplicated serial is not enough authority to initialize a unit.
func discoverSensors(root string) []usbSensor {
paths, _ := filepath.Glob(filepath.Join(root, "*"))
entries, err := os.ReadDir(root)
if err != nil {
return nil
}
items := []usbSensor{}
counts := map[string]int{}
for _, path := range paths {
for _, entry := range entries {
path := filepath.Join(root, entry.Name())
read := func(name string) string {
data, _ := os.ReadFile(filepath.Join(path, name))
return strings.TrimSpace(string(data))
+12 -1
View File
@@ -209,6 +209,11 @@ func (s *Sensors) modelDriver(ctx context.Context, model *sensorModel, path stri
return result, nil
}
func (s *Sensors) Inventory() map[string]any {
inventory, _, _ := s.inventoryWithCameraState()
return inventory
}
func (s *Sensors) inventoryWithCameraState() (map[string]any, []usbSensor, map[string]string) {
frameState := map[string]string{}
// Concurrent local/remote refreshes must observe the same hotplug generation.
s.inventoryMu.Lock()
defer s.inventoryMu.Unlock()
@@ -232,6 +237,12 @@ func (s *Sensors) Inventory() map[string]any {
continue
}
id, _ := item["id"].(string)
if model.ID == "insta360.x4" {
if status, ok := item["local_frame_state"].(string); ok {
frameState[id] = status
}
delete(item, "local_frame_state")
}
if modelForDevice(id) != model || seen[id] {
continue
}
@@ -326,7 +337,7 @@ func (s *Sensors) Inventory() map[string]any {
for i, value := range preparations {
preparations[i] = preparationView(value)
}
return map[string]any{"schema": "missioncore.node.devices/v1", "items": items, "preparation": preparation, "preparations": preparations, "operations": operations}
return map[string]any{"schema": "missioncore.node.devices/v1", "items": items, "preparation": preparation, "preparations": preparations, "operations": operations}, usb, frameState
}
func (s *Sensors) discovery(id, speed string, online bool) map[string]any {
now := time.Now().UTC().Format(time.RFC3339Nano)