feat(k1): add USB networking, device management and acquisition recovery
This commit is contained in:
@@ -4,10 +4,11 @@ import {createElement} from 'react';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
|
||||
let server,Detail,presentation,enrolledDevice;
|
||||
let server,Detail,presentation,enrolledDevice,ObservationAction;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
|
||||
({K1Detail:Detail}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Detail.tsx'));
|
||||
({K1ObservationAction:ObservationAction}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1ObservationAction.tsx'));
|
||||
presentation=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/presentation.ts');
|
||||
({enrolledDevice}=await server.ssrLoadModule('../../packages/sensor-ui/src/contracts.ts'));
|
||||
});
|
||||
@@ -88,3 +89,47 @@ test('completed scan with healthy control remains connected and permits a named
|
||||
assert.doesNotMatch(markup,/Проверить состояние K1|Подключить устройство|Устройство остановлено/);
|
||||
assert.equal(presentation.k1Status(stopped,false).tone,'neutral');
|
||||
});
|
||||
test('observation Play only opens configuration; active acquisition offers its existing controls',()=>{
|
||||
let opened=0;
|
||||
const action=ObservationAction({device,fresh:true,configure:()=>opened++});
|
||||
assert.equal(action.props.label,'Начать сканирование K1');assert.equal(action.props.children.props.name,'play');
|
||||
action.props.onClick();assert.equal(opened,1);
|
||||
assert.equal(ObservationAction({device,fresh:false,configure:()=>opened++}),null);
|
||||
const active={...device,snapshot:{...device.snapshot,acquisition:'streaming'}};
|
||||
let stopped=0;const stop=ObservationAction({device:{...active,control:{...active.control,can_stop:true}},fresh:true,stop:()=>stopped++});
|
||||
assert.equal(stop.props.label,'Остановить сканирование K1');stop.props.onClick();assert.equal(stopped,1);assert.equal(opened,1);
|
||||
});
|
||||
test('observation configuration preserves START fields and STOP without a duplicate media viewer',()=>{
|
||||
for(const acquisition of ['idle','starting','streaming','stopping']){
|
||||
const value={...device,snapshot:{...device.snapshot,acquisition}};
|
||||
const markup=renderToStaticMarkup(createElement(Detail,{device:value,enabled:true,previewEnabled:false,backLabel:'Вернуться к наблюдению',transport:{},back:()=>{},refresh:async()=>{},failure:()=>{},createRerunHost:()=>assert.fail('must not allocate another viewer')}));
|
||||
assert.match(markup,/Вернуться к наблюдению/);assert.doesNotMatch(markup,/rerun-viewport__canvas|Открыть пространственную сцену/);
|
||||
if(acquisition==='idle')assert.match(markup,/Название проекта/);
|
||||
if(acquisition==='streaming')assert.match(markup,/Остановить устройство/);
|
||||
}
|
||||
});
|
||||
|
||||
test('observation gear contains only acquisition controls, including before START',()=>{
|
||||
for(const acquisition of ['idle','streaming']){
|
||||
const value={...device,snapshot:{...device.snapshot,acquisition}};
|
||||
const markup=renderToStaticMarkup(createElement(Detail,{device:value,enabled:true,previewEnabled:false,sceneProfile:{view:'plan',save:()=>{}},transport:{},back:()=>{},refresh:async()=>{},failure:()=>{}}));
|
||||
assert.doesNotMatch(markup,/Размер точки|Атрибут цвета|Палитра|rerun-viewport__canvas/);
|
||||
if(acquisition==='idle')assert.match(markup,/Название проекта/);
|
||||
else assert.match(markup,/Остановить устройство/);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test('K1 storage shows used percentage and expires independently of a fresh inventory',()=>{
|
||||
const now=Date.now(),observed_at=new Date(now-1000).toISOString();
|
||||
const almostFull={...device,storage_status:{used_percent:98.99,observed_at}};
|
||||
assert.equal(presentation.k1StorageStatus(almostFull,true,now+18000).tone,'warning');
|
||||
const status=presentation.k1StorageStatus(almostFull,true,now);
|
||||
assert.equal(status.tone,'warning');assert.match(status.label,/занято 99 %.*мало свободного места/);
|
||||
assert.match(render(almostFull),/Хранилище K1: занято 99 %/);
|
||||
for(const [value,fresh,at] of [[almostFull,false,now],[{...almostFull,online:false},true,now],[almostFull,true,now+20000],[{...device,storage_status:null},true,now]]){
|
||||
const unavailable=presentation.k1StorageStatus(value,fresh,at);
|
||||
assert.equal(unavailable.tone,'neutral');assert.match(unavailable.label,/нет свежих данных/);assert.doesNotMatch(unavailable.label,/99/);
|
||||
}
|
||||
assert.equal(presentation.k1StorageStatus({...device,storage_status:{used_percent:0,observed_at}},true,now).tone,'neutral');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {before,after,test} from 'node:test';
|
||||
import {createElement} from 'react';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
|
||||
let server,Observation;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',plugins:[{
|
||||
name:'inline-observation-portals-for-ssr',enforce:'pre',
|
||||
transform(code,id){
|
||||
if(id.endsWith('/K1Observation.tsx')||id.endsWith('/ObservationHeader.tsx'))
|
||||
return code.replace("import {createPortal} from 'react-dom';","import {cloneElement as portalChild} from 'react'; const createPortal=(child: any,_target: unknown,key?: string)=>child&&key?portalChild(child,{key}):child;");
|
||||
},
|
||||
}]});
|
||||
({K1Observation:Observation}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Observation.tsx'));
|
||||
});
|
||||
after(async()=>{await server?.close();});
|
||||
|
||||
const render=(acquisition,enabled)=>renderToStaticMarkup(createElement(Observation,{
|
||||
device:{id:'synthetic-k1',name:'K1',online:enabled,verified:enabled,
|
||||
control:{can_stop:true,acquisition_id:'same-acquisition'},
|
||||
snapshot:{acquisition,context:{session_id:'same-session'}}},
|
||||
transport:{},enabled,fresh:enabled,views:[{id:'points',target:{},statusTarget:{},actionsTarget:{}}],
|
||||
createRerunHost:()=>assert.fail('server rendering must not allocate a viewer'),
|
||||
}));
|
||||
test('an ongoing acquisition retains the spatial surface during a link gap while STOP is disabled',()=>{
|
||||
const online=render('streaming',true),offline=render('streaming',false);
|
||||
for(const markup of [online,offline]){
|
||||
assert.match(markup,/rerun-viewport__canvas/);
|
||||
assert.match(markup,/Окно накопления облака точек/);
|
||||
assert.match(markup,/Позиция воспроизведения/);
|
||||
assert.match(markup,/ЭФИР/);
|
||||
assert.doesNotMatch(markup,/буфер не включён/);
|
||||
assert.match(markup,/Следовать за K1/);
|
||||
assert.doesNotMatch(markup,/data-viewer-controls/);
|
||||
assert.match(markup,/data-pulse="true"/);
|
||||
}
|
||||
const stop=offline.match(/<button\b[^>]*aria-label="Остановить сканирование K1"[^>]*>/)?.[0];
|
||||
assert.ok(stop);assert.match(stop,/disabled=""/);
|
||||
assert.doesNotMatch(offline,/Инициировать запуск/);
|
||||
});
|
||||
test('completed or never-started acquisitions do not retain an active spatial surface',()=>{
|
||||
for(const acquisition of ['idle','failed'])
|
||||
assert.doesNotMatch(render(acquisition,false),/rerun-viewport__canvas/);
|
||||
});
|
||||
@@ -49,7 +49,7 @@ test('source age expires even when metadata repeats, old frames never look live'
|
||||
assert.equal(gate.fresh,false);
|
||||
gate.receive({type:'lidar-state',sequence:1,age_ms:250,points:3});
|
||||
assert.equal(gate.fresh,true);assert.equal(gate.points,3);
|
||||
now+=1800;gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:3});
|
||||
now+=4800;gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:3});
|
||||
assert.equal(gate.fresh,false);
|
||||
gate.receive({type:'lidar-state',sequence:2,age_ms:9000,points:3});
|
||||
assert.equal(gate.fresh,false);
|
||||
@@ -58,6 +58,19 @@ test('source age expires even when metadata repeats, old frames never look live'
|
||||
assert.throws(()=>gate.receive({type:'lidar-state',sequence:4,age_ms:-1,points:4}));
|
||||
});
|
||||
|
||||
test('budgeted cloud accepts a three-second delivery without making an old frame live forever',()=>{
|
||||
let now=10000;const gate=previewFreshness(()=>now);
|
||||
gate.receive({type:'lidar-state',sequence:1,age_ms:3000,points:394});
|
||||
assert.equal(gate.fresh,true);
|
||||
now+=1999;assert.equal(gate.fresh,true);
|
||||
gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:394});
|
||||
now++;assert.equal(gate.fresh,false);
|
||||
gate.receive({type:'lidar-state',sequence:2,age_ms:null,points:394});
|
||||
assert.equal(gate.fresh,false);
|
||||
gate.receive({type:'lidar-state',sequence:3,age_ms:5000,points:394});
|
||||
assert.equal(gate.fresh,false);
|
||||
});
|
||||
|
||||
test('onboard camera admits immediate sourceopen and ignores callbacks after close',()=>{
|
||||
const saved={media:globalThis.MediaSource,create:URL.createObjectURL,revoke:URL.revokeObjectURL};
|
||||
let source,buffer,appended=0,ready=0,failed=0;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readdir,readFile} from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
import ts from 'typescript';
|
||||
|
||||
test('K1 sensor surfaces cannot introduce browser-default explanatory paragraphs',async()=>{
|
||||
const root=new URL('../../../plugins/xgrids-k1/frontend/src/sensors/',import.meta.url);
|
||||
const files=(await readdir(root)).filter(name=>name.endsWith('.tsx'));
|
||||
for(const name of files){
|
||||
const text=await readFile(new URL(name,root),'utf8');
|
||||
const source=ts.createSourceFile(name,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
|
||||
function inspect(node){
|
||||
if((ts.isJsxOpeningElement(node)||ts.isJsxSelfClosingElement(node))&&node.tagName.getText(source)==='p'){
|
||||
assert.ok(node.attributes.properties.some(p=>ts.isJsxAttribute(p)&&p.name.text==='className'),`${name}: explanatory copy must use Description; only explicitly styled viewport/data paragraphs may remain`);
|
||||
}
|
||||
ts.forEachChild(node,inspect);
|
||||
}
|
||||
inspect(source);
|
||||
}
|
||||
});
|
||||
@@ -232,3 +232,74 @@ test('legacy resolution failure invalidates the form before a second stale submi
|
||||
assert.equal(api.enrollmentBluetoothFailure(state),true);
|
||||
assert.match(api.enrollmentNotice(state),/Найдите K1 ещё раз/);
|
||||
});
|
||||
|
||||
test('saved Bridge recovery needs no BLE candidate and dispatches exactly one existing Verify',async()=>{
|
||||
const before={...initial,selected_device_id:null,candidates:[],discovery_generation:0,mode_revision:3,
|
||||
reconnect_target:{device_id:'saved-k1',source:'durable-configured-state'},
|
||||
allowed_actions:['observe-configured-device-network'],acquisition_recovery:{state:'active'}};
|
||||
const commands=[];
|
||||
const transport={submit:async command=>{commands.push(command);return {state:'complete',operation_id:command.operation_id,
|
||||
result:{...before,snapshot_revision:2,selected_device_id:'saved-k1',connected:true,
|
||||
device_session:{device_id:'saved-k1',device_session_id:'new-live-session'},
|
||||
command_result:{operation_id:command.operation_id,status:'succeeded',action:'verify'}}};}};
|
||||
const result=await api.enroll(transport,before,'verify',{device_id:before.reconnect_target.device_id,discovery_generation:0,mode_revision:3});
|
||||
assert.equal(api.enrollmentAllowed(before,'verify'),true);
|
||||
assert.equal(api.enrollmentAllowed(before,'connect'),false);
|
||||
assert.equal(commands.length,1);assert.equal(commands[0].action,'verify');
|
||||
assert.deepEqual(commands[0].parameters,{device_id:'saved-k1',discovery_generation:0,mode_revision:3});
|
||||
assert.equal(api.enrollmentProof(result,'saved-k1').session,'new-live-session');
|
||||
});
|
||||
|
||||
test('unreachable K1 reports power and network checks without claiming power-off or live scanning',()=>{
|
||||
const before={...initial,connected:false,acquisition_recovery:{state:'active'}};
|
||||
assert.match(api.enrollmentRecoveryNotice(before),/не подтверждена/);
|
||||
for(const code of ['connection-verify-device-not-rediscovered','connection-verify-mqtt-unreachable','connection-verify-status-read-timeout']){
|
||||
const value={...before,verification:{status:'failed',error_code:code}};
|
||||
const message=api.enrollmentRecoveryNotice(value);
|
||||
assert.match(message,/Проверьте питание/);assert.match(message,/сети/);
|
||||
assert.doesNotMatch(message,/K1 выключен|съёмка продолжается|съёмка завершена/);
|
||||
assert.equal(api.enrollmentRecoveryNotice(JSON.parse(JSON.stringify(value))),message);
|
||||
}
|
||||
assert.match(api.enrollmentRecoveryNotice({...before,connected:true,acquisition_recovery:{state:'ceased'}}),/Предыдущая съёмка завершена/);
|
||||
assert.match(api.enrollmentRecoveryNotice({...before,fresh:false}),/Нет свежих сведений с БК/);
|
||||
});
|
||||
|
||||
test('onboard reset uses the existing CAS outcome without automatic Scan, Verify or provisioning',async()=>{
|
||||
const before={...initial,can_reset:true,supported_actions:['reset'],mode_revision:4};const commands=[];
|
||||
assert.equal(api.enrollmentAllowed(before,'reset'),true);
|
||||
assert.equal(api.enrollmentAllowed({...before,supported_actions:undefined},'reset'),false);
|
||||
assert.equal(api.enrollmentAllowed({...before,can_reset:undefined},'reset'),false);
|
||||
const transport={submit:async command=>{commands.push(command);return {state:'complete',operation_id:command.operation_id,result:{...before,mode_revision:5,snapshot_revision:2,connected:false,command_result:{operation_id:command.operation_id,action:'reset',status:'succeeded'}}};}};
|
||||
const result=await api.enroll(transport,before,'reset',{mode_revision:4});
|
||||
assert.equal(result.mode_revision,5);assert.equal(commands.length,1);assert.equal(commands[0].action,'reset');
|
||||
assert.deepEqual(commands[0].parameters,{mode_revision:4});
|
||||
transport.submit=async command=>({state:'complete',operation_id:command.operation_id,result:before});
|
||||
await assert.rejects(api.enroll(transport,before,'reset',{mode_revision:4}),/не подтверждён/);
|
||||
});
|
||||
|
||||
test('terminal enrollment without a driver result releases the observer without waiting or replay',async()=>{
|
||||
for(const action of ['connect','verify']){
|
||||
for(const state of ['unknown','failed','rejected']){
|
||||
let posts=0,reads=0,pauses=0,clock=Date.now();
|
||||
const transport={
|
||||
submit:async command=>{posts++;return {operation_id:command.operation_id,state,error:'Действие K1 не подтверждено.'};},
|
||||
operation:async()=>{throw new Error('terminal delivery must not be polled again');},
|
||||
state:async()=>{reads++;return {...initial,connected:true};},
|
||||
};
|
||||
const parameters={device_id:'synthetic-ble',...(action==='connect'?{password:crypto.randomUUID()}: {})};
|
||||
await assert.rejects(api.enroll(transport,initial,action,parameters,{
|
||||
now:()=>clock,pause:async()=>{pauses++;clock+=100000;},
|
||||
}),/Действие K1 не подтверждено/);
|
||||
assert.deepEqual({posts,reads,pauses},{posts:1,reads:0,pauses:0});
|
||||
assert.equal('password' in parameters,false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown delivery with a correlated running result still observes the owned bootstrap',async()=>{
|
||||
const f=fixture(),submit=f.transport.submit;
|
||||
f.transport.submit=async command=>({...await submit(command),state:'unknown'});
|
||||
const result=await api.enroll(f.transport,initial,'connect',f.parameters,f.observer);
|
||||
assert.equal(result.connected,true);
|
||||
assert.deepEqual(f.counts(),{posts:1,reads:1});
|
||||
});
|
||||
|
||||
@@ -94,8 +94,15 @@ func (d *DeviceEnrollment) call(ctx context.Context, path string, command any) (
|
||||
return nil, errors.New("Служба K1 на БК недоступна.")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
limit := int64(65536)
|
||||
if c, ok := command.(SensorCommand); ok && path == "/sensor-operation" && c.Action == "details" && c.Parameters["preview_blueprint"] != nil {
|
||||
// Canonical Rerun profiles include binary schema data (about 100 KiB
|
||||
// as JSON). This bound is for read-only visualization replies only.
|
||||
limit = 1024 * 1024
|
||||
}
|
||||
data, readErr := io.ReadAll(io.LimitReader(response.Body, limit+1))
|
||||
var value map[string]any
|
||||
if json.NewDecoder(io.LimitReader(response.Body, 65536)).Decode(&value) != nil || response.StatusCode != 200 {
|
||||
if readErr != nil || int64(len(data)) > limit || json.Unmarshal(data, &value) != nil || response.StatusCode != 200 {
|
||||
return nil, errors.New("Действие K1 не подтверждено. Обновите состояние устройства.")
|
||||
}
|
||||
return value, nil
|
||||
@@ -108,6 +115,7 @@ func (d *DeviceEnrollment) Status() map[string]any {
|
||||
if e != nil {
|
||||
value = map[string]any{"available": false}
|
||||
}
|
||||
value["supported_actions"] = []string{"scan", "networks", "connect", "verify", "reset"}
|
||||
value["node_id"] = d.nodeID
|
||||
value["name"], _ = os.Hostname()
|
||||
value["fresh"] = true
|
||||
@@ -122,6 +130,12 @@ func (c EnrollmentCommand) valid(nodeID string) bool {
|
||||
keys := map[string]bool{}
|
||||
switch c.Action {
|
||||
case "scan", "networks":
|
||||
case "reset":
|
||||
keys = map[string]bool{"mode_revision": true}
|
||||
v, ok := c.Parameters["mode_revision"].(float64)
|
||||
if !ok || v < 0 || v != float64(int64(v)) {
|
||||
return false
|
||||
}
|
||||
case "connect", "verify":
|
||||
keys = map[string]bool{"device_id": true, "discovery_generation": true, "mode_revision": true}
|
||||
id, ok := c.Parameters["device_id"].(string)
|
||||
@@ -192,7 +206,7 @@ func (d *DeviceEnrollment) Submit(c EnrollmentCommand, remote bool) (*Enrollment
|
||||
}
|
||||
}
|
||||
for _, v := range d.operations {
|
||||
if v.State == "running" {
|
||||
if v.State == "running" && (c.Action != "reset" || v.Action == "reset") {
|
||||
d.mu.Unlock()
|
||||
return nil, errors.New("Дождитесь текущего действия K1.")
|
||||
}
|
||||
@@ -209,7 +223,7 @@ func (d *DeviceEnrollment) Submit(c EnrollmentCommand, remote bool) (*Enrollment
|
||||
return out, nil
|
||||
}
|
||||
for _, v := range d.operations {
|
||||
if v.State == "running" {
|
||||
if v.State == "running" && (c.Action != "reset" || v.Action == "reset") {
|
||||
d.mu.Unlock()
|
||||
return nil, errors.New("Дождитесь текущего действия K1.")
|
||||
}
|
||||
@@ -237,6 +251,11 @@ func (d *DeviceEnrollment) execute(c EnrollmentCommand) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
op := d.operations[c.ID]
|
||||
// A committed local reset supersedes observation of the earlier attempt.
|
||||
// Its late HTTP reply cannot restore that attempt in the host journal.
|
||||
if op.State != "running" {
|
||||
return
|
||||
}
|
||||
op.Updated = time.Now().Unix()
|
||||
op.State = "complete"
|
||||
op.Result = result
|
||||
@@ -244,6 +263,20 @@ func (d *DeviceEnrollment) execute(c EnrollmentCommand) {
|
||||
op.State = "unknown"
|
||||
op.Error = "Действие K1 не подтверждено. Обновите состояние; повторная команда автоматически не отправляется."
|
||||
}
|
||||
if e == nil && c.Action == "reset" && result != nil {
|
||||
proof, _ := result["command_result"].(map[string]any)
|
||||
revision, _ := result["mode_revision"].(float64)
|
||||
if proof["operation_id"] == c.ID && proof["status"] == "succeeded" && revision == c.Parameters["mode_revision"].(float64)+1 {
|
||||
for id, previous := range d.operations {
|
||||
if id != c.ID && previous.State == "running" && previous.RuntimeID == c.RuntimeID {
|
||||
previous.State = "unknown"
|
||||
previous.Error = "Локальная попытка подключения сброшена оператором. История команды сохранена."
|
||||
previous.Updated = time.Now().Unix()
|
||||
_ = savePrivateJSON(filepath.Join(d.root, id+".json"), previous)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if e := savePrivateJSON(filepath.Join(d.root, c.ID+".json"), op); e != nil {
|
||||
op.State = "unknown"
|
||||
op.Error = "Результат не сохранён. Обновите состояние K1."
|
||||
|
||||
@@ -2,6 +2,7 @@ package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -15,6 +16,39 @@ import (
|
||||
|
||||
type enrollmentHTTP func(*http.Request) (*http.Response, error)
|
||||
|
||||
func TestCanonicalK1BlueprintReplyHasBoundedMediaAllowance(t *testing.T) {
|
||||
d, err := OpenDeviceEnrollment(t.TempDir(), "node-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, action string
|
||||
blueprint bool
|
||||
size int
|
||||
accepted bool
|
||||
}{
|
||||
{"canonical profile", "details", true, 102460, true},
|
||||
{"ordinary details", "details", false, 102460, false},
|
||||
{"physical action", "start", true, 102460, false},
|
||||
{"oversized profile", "details", true, 1024*1024 + 1, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d.client = &http.Client{Transport: enrollmentHTTP(func(r *http.Request) (*http.Response, error) {
|
||||
body := `{"result":{"rrd":"` + strings.Repeat("a", tc.size) + `"}}`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
command := SensorCommand{Action: tc.action, Parameters: map[string]any{}}
|
||||
if tc.blueprint {
|
||||
command.Parameters["preview_blueprint"] = map[string]any{}
|
||||
}
|
||||
_, err := d.call(context.Background(), "/sensor-operation", command)
|
||||
if (err == nil) != tc.accepted {
|
||||
t.Fatalf("accepted=%v, error=%v", tc.accepted, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (f enrollmentHTTP) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
func enrollmentRequest() EnrollmentCommand {
|
||||
@@ -109,3 +143,92 @@ func TestEnrollmentRejectsAnotherNodeExpiredAndHostMutation(t *testing.T) {
|
||||
t.Fatal("expired operation admitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrollmentResetAcceptsOnlyModeRevision(t *testing.T) {
|
||||
c := enrollmentRequest()
|
||||
c.Action = "reset"
|
||||
c.Parameters = map[string]any{"mode_revision": float64(7)}
|
||||
if !c.valid("node-test") {
|
||||
t.Fatal("canonical reset was refused")
|
||||
}
|
||||
for _, parameters := range []map[string]any{{}, {"mode_revision": true}, {"mode_revision": float64(-1)}, {"mode_revision": float64(1.5)}, {"mode_revision": float64(7), "device_id": "x"}} {
|
||||
c.Parameters = parameters
|
||||
if c.valid("node-test") {
|
||||
t.Fatal("invalid reset admitted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrollmentResetSupersedesPendingObservationWithoutReplayingCommand(t *testing.T) {
|
||||
d, err := OpenDeviceEnrollment(t.TempDir(), "node-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered, release, replied := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
d.client = &http.Client{Transport: enrollmentHTTP(func(r *http.Request) (*http.Response, error) {
|
||||
body := `{"available":true,"runtime_id":"runtime-test"}`
|
||||
if r.Method == "POST" {
|
||||
var command EnrollmentCommand
|
||||
if err := json.NewDecoder(r.Body).Decode(&command); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if command.Action == "connect" {
|
||||
close(entered)
|
||||
<-release
|
||||
close(replied)
|
||||
body = `{"connected":true}`
|
||||
} else {
|
||||
raw, _ := json.Marshal(map[string]any{"mode_revision": float64(1), "command_result": map[string]any{"operation_id": command.ID, "action": "reset", "status": "succeeded"}})
|
||||
body = string(raw)
|
||||
}
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
old := enrollmentRequest()
|
||||
if _, err := d.Submit(old, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-entered
|
||||
ordinary := enrollmentRequest()
|
||||
ordinary.ID = "op_" + strings.Repeat("b", 32)
|
||||
if _, err := d.Submit(ordinary, true); err == nil {
|
||||
t.Fatal("ordinary action bypassed pending operation")
|
||||
}
|
||||
reset := enrollmentRequest()
|
||||
reset.ID = "op_" + strings.Repeat("c", 32)
|
||||
reset.Action = "reset"
|
||||
reset.Parameters = map[string]any{"mode_revision": float64(0)}
|
||||
if _, err := d.Submit(reset, true); err != nil {
|
||||
close(release)
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for d.Get(reset.ID).State == "running" && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if d.Get(reset.ID).State != "complete" || d.Get(old.ID).State != "unknown" {
|
||||
close(release)
|
||||
t.Fatal("reset did not supersede pending observation")
|
||||
}
|
||||
close(release)
|
||||
<-replied
|
||||
// execute's old reply must leave the reset-owned terminal journal untouched.
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if d.Get(old.ID).State != "unknown" || d.Get(old.ID).Result != nil {
|
||||
t.Fatal("late reply restored old result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrollmentPublishesHostResetSupport(t *testing.T) {
|
||||
d, err := OpenDeviceEnrollment(t.TempDir(), "node-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d.client = &http.Client{Transport: enrollmentHTTP(func(r *http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"available":true,"can_reset":true}`)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
got := d.Status()["supported_actions"].([]string)
|
||||
if strings.Join(got, ",") != "scan,networks,connect,verify,reset" {
|
||||
t.Fatal("host capability does not describe admitted actions")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,8 @@ var sensorModels = []sensorModel{
|
||||
PrepareUnit: "mission-core-node-realsense-prepare.service", Report: "/var/lib/mission-core-node-drivers/preparation.json",
|
||||
Actions: actions("prepare", "details", "rename", "verify", "start", "replay", "stop", "option", "offer", "close-peer")},
|
||||
{ID: "xgrids.k1", Name: "XGRIDS K1", Prefix: "k1", Kind: "k1",
|
||||
Actions: actions("details", "rename", "verify", "start", "stop", "option", "offer", "close-peer")},
|
||||
ActionTimeouts: map[string]time.Duration{"management": 35 * time.Second},
|
||||
Actions: actions("details", "rename", "verify", "start", "stop", "option", "offer", "close-peer", "management")},
|
||||
{ID: "insta360.x4", Name: "Insta360 X4", Prefix: "instax4", Kind: "insta360.x4", Plugin: "missioncore.insta360", Version: "0.1.3",
|
||||
// 2e1a:0002 is shared with other Insta360 models. Require the exact
|
||||
// OS product descriptor as well; SDK identity is verified after prepare.
|
||||
|
||||
@@ -337,3 +337,78 @@ The later LixelGO/iPhone experiment found the preview on a separate transport:
|
||||
left/right RTSP sessions on TCP `8554` with interleaved RTP/TCP and H.264. This
|
||||
proves compressed preview availability, not full-resolution raw frames or
|
||||
camera calibration. See Lab 002.
|
||||
|
||||
|
||||
## Non-terminating system report, 2026-11-01
|
||||
|
||||
On the owner-controlled FW 3.0.2 profile, `report/system_error` also carried
|
||||
`302256130` (`0x12041002`) while fresh non-retained DeviceStatus remained
|
||||
SCANNING and both PCL and pose continued. Treating every message on this topic
|
||||
as a terminal fault closed the application's control owner and disabled its
|
||||
preview despite continuing board ingress. A later READY reconciliation was
|
||||
then reported misleadingly as a changed control binding.
|
||||
|
||||
The retained LixelGO 1.2.5 reconstruction, `bc.bia(SystemErrorReport)`, extracts
|
||||
the upper nibble (`0xB8260C`) and branches separately for levels 2 and 3
|
||||
(`0xB826B4`–`0xB8276C`); this observed level-1 report does not take the
|
||||
level-3 error-action path. Only the exact observed `0x12041002` is admitted as
|
||||
non-terminating. This is not a general exemption for unknown severity-1/2 codes
|
||||
and does not assign an unproved human-readable meaning to the report. The
|
||||
field experiment also observed high disk utilization; temporal coincidence
|
||||
alone does not establish the report's full vendor definition.
|
||||
|
||||
Keep counting and exposing the report in transport diagnostics. Do not refresh
|
||||
identity, freshness, readiness or physical START/STOP outcome from it. A prior
|
||||
unknown/fault system report stays latched; later non-terminating reports cannot
|
||||
clear it. DeviceStatus faults, identity drift, malformed reports and stale
|
||||
control evidence retain their existing fences. There are no new subscriptions,
|
||||
probes, commands or retries. This source change requires package and hardware
|
||||
qualification; it is not evidence of completed field recovery.
|
||||
|
||||
|
||||
## Storage occupancy in operator status, 2026-11-01
|
||||
|
||||
The already subscribed DeviceStatus field 7 carries SystemStatus. The retained
|
||||
LixelGO `Openapi.AiotMsgs.SystemStatus` declaration identifies `DiskTotal` as
|
||||
field 4 and `DiskUsed` as field 5 (non-negative int64). Display only their ratio;
|
||||
no byte/KiB unit is inferred. Proto3 omission of DiskUsed is zero when a valid,
|
||||
positive DiskTotal is present. Missing, duplicate, malformed or impossible
|
||||
storage fields suppress this optional value without changing modeling state.
|
||||
|
||||
Storage comes from non-retained reports on the current control transport and
|
||||
is exposed only when its identity matches the identity admitted by the existing
|
||||
bound validation. Later idle reports update display telemetry without repeating
|
||||
command admission; they never promote themselves to command authority. The Node
|
||||
projection admits source reports no older than five seconds; the UI uses the
|
||||
existing 20-second Fleet inventory freshness window to allow normal delivery.
|
||||
Repeated inventory snapshots cannot refresh the source observation. Unknown
|
||||
occupancy is never presented as zero. The display warns at 95% used; this is
|
||||
an operator presentation threshold, not a decoded vendor error definition or
|
||||
a new START/STOP gate. No additional subscription, request or device command
|
||||
is introduced. The shared K1 device view owns the status, separately from
|
||||
point-cloud visualization settings.
|
||||
|
||||
|
||||
## Returned host path with a surviving data socket, 2026-11-01
|
||||
|
||||
A bounded onboard association interruption reproduced an authority gap: PCL
|
||||
and pose ingress continued, but the host-path epoch changed and invalidated
|
||||
the old control proof. The path returned before the negative-probe threshold;
|
||||
therefore neither a sustained-loss branch nor an MQTT disconnect woke the
|
||||
existing active-acquisition recovery. The UI remained disconnected despite
|
||||
live ingress. The attempted alternate association did not settle: this evidence
|
||||
is a short-gap reproduction, not successful multi-AP handover acceptance.
|
||||
|
||||
The facade now wakes the existing read-only recovery only for an available
|
||||
returned path, an explicitly stale verified control epoch, a scanning control
|
||||
owner, and the existing composite confirmed-START admission. It does not reuse
|
||||
the old control proof, add vendor commands, repeat START, change routes, pin an
|
||||
AP, or weaken physical-command/checkpoint fences. The existing runtime wake
|
||||
coalesces concurrent observations. Regression coverage includes a returned
|
||||
same association, a changed association, and a START requiring reconciliation
|
||||
which must not enter this path.
|
||||
|
||||
Package 0.1.31 is installed on the existing qualified Ubuntu 24.04 amd64 board.
|
||||
Normal Bridge verification and fresh UI scan/cloud were observed after install.
|
||||
Post-install controlled interruption and same-session cloud return remain an
|
||||
open field acceptance gate; source tests and installation alone do not prove it.
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
# K1 USB Ethernet on the onboard computer
|
||||
|
||||
## Scope
|
||||
|
||||
The USB path replaces only K1 → Node radio transport. Node → Control Station
|
||||
delivery, its bounded preview budget, recording, and the shared spatial viewer
|
||||
retain their existing implementations. Wireless enrollment remains available.
|
||||
No Lixel Studio or OpenAPI SDK runtime is introduced.
|
||||
|
||||
The physically qualified environment is one owner-controlled LixelKity K1,
|
||||
firmware V3.0.2, and the prepared Ubuntu 24.04 amd64 onboard computer. This is
|
||||
not clean-OS, multi-device, active-scan cable-disconnect or endurance acceptance.
|
||||
|
||||
## Discovery and admission
|
||||
|
||||
`usb_network.py` observes Linux sysfs for the qualified XGRIDS RNDIS device
|
||||
(2207:0019, product `XGRIDS Device`, driver `rndis_host`). The peer address comes
|
||||
from NetworkManager's DHCP server identifier. The kernel route must use that
|
||||
exact USB interface, a local source address, and no gateway. There is no
|
||||
hardcoded peer IP, interface name, USB port, subnet scan or Wi-Fi fallback.
|
||||
The probe never changes NetworkManager, USB mode, routes or host permissions.
|
||||
|
||||
A hash of the USB serial supplies stable discovery identity. Enumeration and
|
||||
route evidence have a separate generation that changes on re-enumeration.
|
||||
USB identity alone is insufficient: the existing read-only Verify transaction
|
||||
must obtain DeviceInfo, validate the supported firmware, and check the durable
|
||||
device identity pin before committing semantic topology. Commit repeats the
|
||||
USB generation and address checks. A changed attachment invalidates its lease.
|
||||
|
||||
`NodeK1UsbObserver` supplies this evidence to the existing facade under the
|
||||
Node operation lock. It does not issue START. A live wireless dialogue is not
|
||||
silently taken over. After admission the existing connection monitor owns
|
||||
recovery; the observer does not repeatedly reopen an unchanged connection.
|
||||
If terminal local cleanup retires control while USB remains attached, the
|
||||
observer re-enters the same read-only Verify transaction. An active receiver,
|
||||
nonterminal acquisition or concurrent reconfiguration still excludes that
|
||||
handoff. Enumeration never clears a physical START/STOP record.
|
||||
|
||||
USB is a transport value in the existing semantic topology, physical command
|
||||
journal and active acquisition checkpoint. It is deliberately not a Wi-Fi
|
||||
provisioning mode. The original START/STOP sequence and reconciliation rules
|
||||
remain authoritative; reconnecting is not permission to replay START.
|
||||
|
||||
## Physical qualification, 2026-11-02
|
||||
|
||||
The original application dialogue executor was used over the enumerated USB
|
||||
network route. One START and one STOP were sent; no extra command retries were
|
||||
inserted. The device reported SCANNING and subsequently READY.
|
||||
|
||||
- 1,725 consecutive point-cloud frames; no missing sequence numbers.
|
||||
- 6,817,911 decoded points and 1,755 pose messages; zero decode/rejection errors.
|
||||
- Approximately 9.83 cloud frames/s and 3.1 Mbit/s raw application payload.
|
||||
- The existing camera gateway produced 265 unique, decodable H.264 frames,
|
||||
800 × 600 at approximately 10 fps, in a bounded camera capture.
|
||||
- The interface reported 9 receive frame errors across approximately 70,983
|
||||
received packets. There were no application sequence gaps in this sample;
|
||||
the lower-level errors remain an explicit qualification limitation.
|
||||
|
||||
These are K1 → Node measurements, not browser latency or end-to-end delivery
|
||||
acceptance. Raw captures and private identifiers remain outside source control.
|
||||
|
||||
## Installation and remaining acceptance
|
||||
|
||||
The optional `mission-core-xgrids-k1` Debian package owns the runtime change.
|
||||
Its pre-install check requires the existing `prepare-safe` result, then stops
|
||||
only the K1 service. The public package preserves the provisioned application
|
||||
credential and durable journals. Node, VESC and USB-CAN configurations are not
|
||||
modified. Version 0.1.31 is the retained rollback artifact.
|
||||
|
||||
Hardware qualification precedes the product gate: automatic inventory,
|
||||
Observatory project modal, START, cloud/camera preview, STOP and recovery must
|
||||
be checked using the installed package and normal Control Station interface.
|
||||
Do not infer product acceptance from the engineering capture alone.
|
||||
|
||||
The installed 0.1.32 product test confirmed automatic USB inventory, the
|
||||
existing Observatory project modal, START, camera preview, and the custom
|
||||
point-cloud viewport. Two short runs completed STOP normally. A longer run
|
||||
received 28,532 cloud frames / 112,720,068 points with zero decoder errors.
|
||||
This does not establish sequence continuity or operator-preview latency for
|
||||
the longer run.
|
||||
|
||||
At the end of that run, STOP received an application success response, but
|
||||
the bounded wait did not acquire final READY evidence. The device later showed
|
||||
steady green. The existing **Check K1 state** action obtained fresh evidence,
|
||||
closed the acquisition recovery checkpoint and restored `prepare-safe: true`.
|
||||
Neither START nor STOP was replayed. This separates physical command acceptance
|
||||
from a confirmed final state; an ACK alone is not completion.
|
||||
|
||||
Version 0.1.33 addresses the Node adapter's unchanged-USB observation latch
|
||||
and preserves the USB label when its control socket is retired. The canonical
|
||||
command/reconciliation pipeline and installer safety gate remain unchanged.
|
||||
Device reboot, power-off commands, active-scan USB interruption and clean-Ubuntu
|
||||
installation are still separate acceptance gates.
|
||||
|
||||
The 0.1.33 installed follow-up run confirmed automatic USB admission after
|
||||
the package restart, normal UI START, first-entry cloud in the existing custom
|
||||
viewer, camera preview, and UI STOP returning to ready. It received 2,541
|
||||
cloud frames / 10,020,892 points with zero decoder errors. The final acquisition
|
||||
was completed and the preview peer list empty. The checkpoint was ceased,
|
||||
although its projection retained a `cease-failed` diagnostic reason; that
|
||||
diagnostic inconsistency remains to be investigated separately.
|
||||
|
||||
The browser reload test is **not accepted**: the device session and camera
|
||||
returned, the isolated Rerun realm loaded, but this browser received no cloud
|
||||
batches during the bounded observation. Do not conflate working USB ingress
|
||||
with reliable Node → Control Station delivery. Delivery/re-entry, stale-view
|
||||
ownership and preview latency remain an explicit follow-up, as requested by
|
||||
the owner. The point-cloud first-entry bootstrap now loads the bundled runtime
|
||||
document into the same isolated iframe; it does not alter the stream budget,
|
||||
point accumulation, colour settings or the recorder.
|
||||
|
||||
Idle USB unplug/replug was qualified on 0.1.33. The operator disconnected the
|
||||
cable at 15:41:30 UTC and reattached it at 15:41:48 UTC. Linux enumerated a new
|
||||
USB device number (5 → 6), and the existing Verify pipeline opened a fresh
|
||||
device session at 15:41:54.916 UTC. The stable USB identity was preserved; the
|
||||
interface obtained its lease again and the peer route still used USB. The UI
|
||||
showed Connected and the normal new-project controls without a manual Verify,
|
||||
Wi-Fi enrollment or START. The final state was idle, `can_start: true`,
|
||||
`can_stop: false`, `prepare-safe: true`, with no preview peers. This proves
|
||||
idle attachment recovery, not recovery of a scan interrupted mid-acquisition.
|
||||
|
||||
## Preview recovery follow-up, 2026-11-02
|
||||
|
||||
The failed 0.1.33 reload was traced to detached RRD subscribers counting toward
|
||||
the two-active-view limit. A reload creates a new view UUID; a five-minute resume
|
||||
reservation could therefore reject the new page as `Close another live viewer`.
|
||||
The bound is now two active plus two detached resumable views. Oldest detached
|
||||
reservations may expire, but an active view is never evicted. A missing resume
|
||||
cursor fails explicitly instead of silently restarting its native recording.
|
||||
|
||||
The 0.1.34 test returned cloud to the same acquisition after reload, but showed
|
||||
datagrams expiring in the shared budget queue. Version 0.1.35 paces cloud data
|
||||
in 1 KiB fragments before SCTP, using the existing producer allocation and
|
||||
framing headroom. It does not increase cloud demand, change the shared admission
|
||||
deadline, or reduce primary camera/control priority. Pacing alone did not fully
|
||||
stabilize preview latency in the presence of a retained legacy viewer.
|
||||
|
||||
Version 0.1.36 rejects the legacy raw-fMP4 `camera` data channel on a cloud peer.
|
||||
That channel had been admitted under the cloud budget alongside reliable RRD,
|
||||
despite the current camera UI already using its separate RTP/video offer. Only
|
||||
the obsolete channel is closed: its RRD subscription remains usable. Modern
|
||||
camera offers and the acquisition recorder are unchanged. An old page must be
|
||||
refreshed to obtain the separate camera viewer. Preview health exposes admitted
|
||||
channel labels so this boundary can be inspected without packet contents.
|
||||
|
||||
Repeated state reduction after STOP also previously reported `cease-failed`
|
||||
after local cleanup released its operation/evidence owners. The reducer now
|
||||
recognizes the trusted ceased checkpoint of the same completed acquisition,
|
||||
checking the original START whenever its local owner is still present. It
|
||||
does not cease an active checkpoint without evidence, accept another
|
||||
acquisition/START, alter journal bytes or grant recovery authority. The 0.1.35
|
||||
hardware run confirmed completed/ceased, no reason, no peers and prepare-safe
|
||||
after UI STOP; 115 checkpoint/USB tests and 32 preview/media tests pass.
|
||||
|
||||
The 0.1.36 hardware delivery/re-entry acceptance is recorded in the task's
|
||||
`outputs/k1-usb-preview-recovery-20261102/result.json`. Do not treat unit tests
|
||||
or the earlier 0.1.35 first-entry latency sample as final delivery acceptance.
|
||||
|
||||
## Adaptive full-density preview, 2026-11-02
|
||||
|
||||
Node 0.8.53-104 with K1 0.1.38 was installed through the versioned installer.
|
||||
Cloud demand now follows observed native frame size/cadence; complete selected
|
||||
frames retain all points instead of spatially decimating them to fit a fixed
|
||||
small demand. Input frames may coalesce while delivery waits; raw acquisition
|
||||
recording remains independent. Only the selected primary video receives the
|
||||
video priority share. Cloud framing follows its allocation and feedback credit
|
||||
follows the existing adaptive budget instead of a fixed 128 KiB ceiling.
|
||||
|
||||
Node 104 also fixes a recovery deadlock: a quiet primary camera could reserve
|
||||
most of a reduced feedback window while waiting cloud packets could not fill
|
||||
half that window to qualify for growth. Recent denied real packets can now
|
||||
qualify useful demand for growth under healthy feedback; idle declarations
|
||||
alone cannot. Command-pressure and feedback-silence guards remain unchanged.
|
||||
|
||||
The USB J run delivered 3943–4025 points per observed frame to the custom
|
||||
viewer, versus approximately 247 before the change. Over an 81.98-second
|
||||
interval including a delivery pause, this browser received 47.97 kB/s of RRD,
|
||||
0.646 batches/s. Received-frame age samples were 0.39–2.17 seconds; these are
|
||||
not a continuous latency distribution and do not hide the observed pause.
|
||||
After the last of three feedback-silence events, optional credit recovered
|
||||
above 30 Mbit/s in 10.6 seconds without a reconnect. This is an allocation,
|
||||
not a measured physical link capacity.
|
||||
|
||||
Leaving and re-entering the Observatory restored cloud and camera under the
|
||||
same acquisition without another START. However, visible scene recovery took
|
||||
up to 32.17 seconds in the sampled run; signalling and native first-scene
|
||||
presentation remain unresolved. Short inbound tunnel gaps were independently
|
||||
observed while Core transmission continued. Continuous low-latency delivery,
|
||||
full available-bandwidth use and real driving with VESC are not accepted by
|
||||
this test. J ended with UI STOP, fresh READY, a ceased checkpoint and
|
||||
prepare-safe true. Evidence is in the task's `outputs/k1-traffic-20261102/REPORT.md`.
|
||||
|
||||
## Vendor command reference
|
||||
|
||||
The XGRIDS Lixel OpenAPI protocol documentation and the v1.1.0 protobuf schema
|
||||
are references for wire semantics only. The schema includes USB_MASS,
|
||||
USB_ETHER, POWER_OFF and SYSTEM_REBOOT, among other actions. An enum in a newer
|
||||
schema does not qualify that action on this firmware. The initial USB transport
|
||||
change did not expose these maintenance actions.
|
||||
|
||||
The separate 2026-11-03 management increment adds an idle-only mailbox to the
|
||||
existing application MQTT worker. DeviceInfo and ProjectList were read through
|
||||
the current USB Ethernet control channel: 18 real projects, with the scanner
|
||||
still in USB Ethernet mode. No mass-storage switch or filesystem mount was
|
||||
needed. Project deletion has its own vendor command on that same control
|
||||
channel. With explicit owner permission for all test projects, acceptance
|
||||
deleted one (18→17 projects; 81.6→80.7% used), then three selected projects
|
||||
(17→14; 70.8% used), then formatted the remaining test storage (0 projects;
|
||||
0% used as rounded by the device). Every result used a fresh device catalog
|
||||
and storage report, not optimistic removal from the UI.
|
||||
|
||||
K1 0.1.43 executes selected deletion as sequential singular-ID vendor requests
|
||||
inside the existing fenced worker, with one reply per request and no retry.
|
||||
The tested firmware rejected the newer repeated-ID request; partial failure
|
||||
stops the group and retains the confirmed deleted IDs. The common operation
|
||||
deadline remains bounded. A control interruption overlapped the storage test
|
||||
and an owner-reported USB cable replacement; formatting is not an established
|
||||
cause. Existing USB recovery restored confirmed standby and a fresh catalog.
|
||||
No USB-mode change or second format command was sent.
|
||||
Final qualified installation: Node 0.8.53-109 / K1 0.1.43, with all four
|
||||
Node/K1/VESC/USB-CAN services active and prepare-safe true after acceptance.
|
||||
|
||||
Power-off/reboot and USB mode commands use explicit confirmation and
|
||||
generation/revision fencing. A subsequent owner-authorized UI reboot test
|
||||
confirmed USB disappearance and reappearance, then fresh DeviceInfo in USB
|
||||
Ethernet mode and a fresh empty project catalog. The board remained online.
|
||||
Power-off and a USB-mode round-trip remain physically unqualified.
|
||||
|
||||
USB mass-storage removes the current Ethernet control path. Both the UI and
|
||||
the worker reject USB_MASS unless the connection binding is Bridge, so a
|
||||
USB-only operator cannot strand the scanner behind a non-existent return
|
||||
channel. A Bridge mode round-trip still needs physical qualification. The UI
|
||||
calls the modes “Канал управления (USB Ethernet)” and “USB-накопитель”. DeviceInfo,
|
||||
not a command acknowledgement or cached project catalog, supplies actual mode.
|
||||
Reset and firmware upload remain outside this change. No Lixel Studio runtime
|
||||
or alternate OpenAPI authentication/session owner is added.
|
||||
|
||||
References:
|
||||
|
||||
- <https://docs.xgrids.com/en-us/07-plugin-sdk/04-lixel-openapi/v1.1.0/02-connection.html>
|
||||
- <https://github.com/xgrids/Lixel_OpenAPI/tree/a60a73773b0c2da3e582607ff71b32baa1238d4e>
|
||||
@@ -2,17 +2,18 @@ import {useState} from 'react';
|
||||
import {Select,SettingsCard,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {wirelessContributions,type SensorEnrollmentProps,type SensorUiContribution} from './extensions';
|
||||
|
||||
export function WirelessEnrollmentWindow({contributions,transport,onClose,onChange,onComplete,enabled=true}:{
|
||||
export function WirelessEnrollmentWindow({contributions,transport,onClose,onChange,onComplete,enabled=true,initialKind=''}:{
|
||||
contributions:readonly SensorUiContribution[];
|
||||
transport:SensorEnrollmentProps['transport'];onClose:()=>void;onChange:()=>void;
|
||||
onComplete:SensorEnrollmentProps['onComplete'];
|
||||
enabled?:boolean;
|
||||
enabled?:boolean;initialKind?:string;
|
||||
}) {
|
||||
const [selected,setSelected]=useState('');
|
||||
const [selected,setSelected]=useState(initialKind);
|
||||
const supported=wirelessContributions(contributions);
|
||||
const Enrollment=supported.find(value=>value.kind===selected)?.wirelessEnrollment?.View;
|
||||
const renderWindow:SensorEnrollmentProps['renderWindow']=({content,actions,busy=false})=>(
|
||||
const renderWindow:SensorEnrollmentProps['renderWindow']=({content,actions,headerActions,busy=false})=>(
|
||||
<Window open title="Подключение беспроводных устройств к БК" closeOnBackdrop={false} closeOnEscape={!busy} onClose={()=>{if(!busy)onClose();}}
|
||||
headerActions={headerActions}
|
||||
footer={actions?<WindowFooterActions style={{width:'100%'}}>{actions}</WindowFooterActions>:undefined}>
|
||||
<div className="sensor-content">
|
||||
<Select label="Тип устройства" value={selected} disabled={busy}
|
||||
|
||||
@@ -3,7 +3,8 @@ export interface SensorOption { id: string; sensor: string; label: string; value
|
||||
export interface Sensor {
|
||||
transport_generation?:string;
|
||||
preview_priority_v1?:boolean;
|
||||
kind?:string; connection_label?:string; control?:{generation:number;revision:number;phase:string;can_start:boolean;can_stop?:boolean;can_verify?:boolean;network_applied?:boolean;reason_code?:string|null;acquisition_id:string|null;acquisition_phase?:string};
|
||||
kind?:string; connection_label?:string; connection_mode?:string; control?:{generation:number;revision:number;phase:string;can_start:boolean;can_stop?:boolean;can_verify?:boolean;network_applied?:boolean;reason_code?:string|null;acquisition_id:string|null;acquisition_phase?:string};
|
||||
storage_status?:{used_percent:number;observed_at:string}|null;
|
||||
live_settings?: Record<string,unknown>;
|
||||
camera_status?: Record<string,unknown>;
|
||||
can_status?: Record<string,unknown>;
|
||||
|
||||
@@ -5,11 +5,15 @@ export interface EnrollmentState {
|
||||
networks?:{ssid:string;signal:number;security:string}[];
|
||||
connected?:boolean; ready_to_start?:boolean; selected_device_id?:string; ip?:string;
|
||||
snapshot_revision?:number; runtime_started_at?:string; allowed_actions?:string[];
|
||||
can_reset?:boolean; supported_actions?:EnrollmentCommand["action"][];
|
||||
reconnect_target?:{device_id:string;source:'durable-configured-state'}|null;
|
||||
acquisition_recovery?:{status?:string;state?:string;gap_open?:boolean;restart_rehydration_phase?:string;reason_code?:string|null};
|
||||
verification?:{operation_id?:string;status?:string;error_code?:string|null}|null;
|
||||
connection_attempt?:unknown; command_result?:{operation_id:string;action?:string;status:string;error_code?:string};
|
||||
device_session?:{device_session_id:string;device_id:string}; observed_at?:string;
|
||||
}
|
||||
export interface EnrollmentCommand {
|
||||
operation_id:string; node_id:string; runtime_id:string; action:'scan'|'networks'|'connect'|'verify';
|
||||
operation_id:string; node_id:string; runtime_id:string; action:'scan'|'networks'|'connect'|'verify'|'reset';
|
||||
deadline_at:string; parameters:Record<string,unknown>;
|
||||
}
|
||||
export interface EnrollmentOperation {operation_id?:string;state:string;error?:string;result?:EnrollmentState}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {ActivityIndicator,Button,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
|
||||
import {ActivityIndicator,Button,Icon,IconButton,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
|
||||
import type {SensorEnrollmentProps} from '@mission-core/sensor-sdk';
|
||||
import {bridgeFormValid,enroll,enrollmentAllowed,connectionAttempt,enrollmentNotice,enrollmentBluetoothFailure,mergeEnrollmentState,enrollmentProof,enrollmentProofCurrent,type EnrollmentProof,type EnrollmentState} from './enrollment';
|
||||
import {bridgeFormValid,enroll,enrollmentAllowed,connectionAttempt,enrollmentNotice,enrollmentRecoveryNotice,enrollmentBluetoothFailure,mergeEnrollmentState,enrollmentProof,enrollmentProofCurrent,type EnrollmentProof,type EnrollmentState} from './enrollment';
|
||||
import {K1WifiPasswordField} from '../components/K1WifiPasswordField';
|
||||
import {revealEnrollment} from './revealEnrollment';
|
||||
|
||||
@@ -21,7 +21,7 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
|
||||
const [reveal,setReveal]=useState({target:'',revision:0});
|
||||
const content=useRef<HTMLDivElement>(null);
|
||||
const lifetime=useRef<AbortController|null>(null);
|
||||
const running=useRef(false);
|
||||
const running=useRef<AbortController|null>(null);
|
||||
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();
|
||||
@@ -41,11 +41,11 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
|
||||
}
|
||||
}
|
||||
void observe();
|
||||
return()=>{controller.abort();if(timer)clearTimeout(timer);};
|
||||
return()=>{controller.abort();running.current?.abort();if(timer)clearTimeout(timer);};
|
||||
},[transport]);
|
||||
|
||||
const attempt=connectionAttempt(state);
|
||||
const waiting=attempt?.status==='accepted'||attempt?.status==='running';
|
||||
const waiting=attempt?.status==='accepted'||attempt?.status==='running'||state?.verification?.status==='accepted'||state?.verification?.status==='running';
|
||||
const notice=state&&(!state.available||state.fresh===false||attempt?.attempt_id!==dismissedAttempt)?enrollmentNotice(state):'';
|
||||
const bluetoothFailure=!!notice&&enrollmentBluetoothFailure(state);
|
||||
useEffect(()=>{
|
||||
@@ -70,15 +70,19 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
|
||||
return()=>cancelAnimationFrame(frame);
|
||||
},[reveal]);
|
||||
|
||||
async function run(action:'scan'|'networks'|'connect'|'verify'){
|
||||
if(!state||busy||running.current)return;
|
||||
running.current=true;
|
||||
const signal=lifetime.current?.signal;
|
||||
async function run(action:'scan'|'networks'|'connect'|'verify'|'reset',savedTarget=false){
|
||||
if(!state||(action==='reset'?busy==='reset'||!enrollmentAllowed(state,'reset'):!!busy||!!running.current))return;
|
||||
// Supersede only the old UI observer. The canonical reset owns device-runtime cleanup.
|
||||
running.current?.abort();
|
||||
const controller=new AbortController();running.current=controller;
|
||||
const signal=controller.signal;
|
||||
setBusy(action);setError('');
|
||||
if(action!=='networks')setVerified(null);
|
||||
if(action==='scan')setScanned(false);
|
||||
const parameters=action==='connect'||action==='verify'?{
|
||||
device_id:device,discovery_generation:state.discovery_generation,mode_revision:state.mode_revision,
|
||||
const target=savedTarget?state.reconnect_target?.device_id:device;
|
||||
if(savedTarget&&!target){running.current=null;setBusy('');return;}
|
||||
const parameters=action==='reset'?{mode_revision:state.mode_revision}:action==='connect'||action==='verify'?{
|
||||
device_id:target,discovery_generation:state.discovery_generation,mode_revision:state.mode_revision,
|
||||
...(action==='connect'?{ssid,password}:{}),
|
||||
}:{};
|
||||
if(action==='connect')setPassword('');
|
||||
@@ -89,12 +93,13 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
|
||||
if(signal?.aborted)return;
|
||||
onChange();
|
||||
setState(current=>mergeEnrollmentState(current,{...result,node_id:state.node_id,name:state.name}));
|
||||
if(action==='reset'){setDevice('');setPassword('');setSSID('');setNetworks([]);setNetwork('manual');setScanned(false);setNeedsScan(false);setDismissedAttempt('');show('');}
|
||||
if(action==='scan'){
|
||||
setDevice('');setScanned(true);setNeedsScan(false);
|
||||
setDismissedAttempt(connectionAttempt(result)?.attempt_id??'');show('devices');
|
||||
}
|
||||
if(action==='networks'){setNetworks(result.networks??[]);show('networks');}
|
||||
if(action==='connect'||action==='verify'){setVerified(enrollmentProof(result,device));setDismissedAttempt('');}
|
||||
if(action==='connect'||action==='verify'){const proof=enrollmentProof(result,target??'');setVerified(proof);if(proof)setDevice(proof.device);setDismissedAttempt('');}
|
||||
if(action==='connect'&&enrollmentBluetoothFailure(result)){
|
||||
setNeedsScan(true);setDevice('');
|
||||
}
|
||||
@@ -102,8 +107,7 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
|
||||
}catch(cause){
|
||||
if(!signal?.aborted)setError(cause instanceof Error?cause.message:'Не удалось выполнить действие K1.');
|
||||
}finally{
|
||||
running.current=false;
|
||||
if(!signal?.aborted)setBusy('');
|
||||
if(running.current===controller){running.current=null;if(!signal.aborted)setBusy('');}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +121,7 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
|
||||
}
|
||||
|
||||
return renderWindow({busy:pending,
|
||||
headerActions:state?.can_reset?<IconButton label="Сбросить подключение" title={enrollmentAllowed(state,'reset')?'Сбросить текущую попытку подключения':'Для сброса подключения обновите поддержку K1 на БК'} disabled={!enrollmentAllowed(state,'reset')||busy==='opening'} loading={busy==='reset'} onClick={()=>void run('reset')}><Icon name="refresh"/></IconButton>:undefined,
|
||||
actions:confirmed?<Button variant="primary" tone="neutral" width="full" disabled={pending}
|
||||
aria-busy={busy==='opening'} icon={busy==='opening'?<ActivityIndicator size="compact"/>:undefined}
|
||||
onClick={()=>void configure()}>Настроить устройство</Button>:undefined,
|
||||
@@ -128,6 +133,11 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
|
||||
</SettingsCard>
|
||||
{busy!=='loading'&&!ready?<SettingsCard align="center" title="Служба подключения устройств на БК недоступна"
|
||||
description="Проверьте связь с бортовым компьютером и работу приложения на нём."/>:ready&&<>
|
||||
{state?.reconnect_target&&!confirmed&&<SettingsCard title="Сохранённое подключение K1"
|
||||
description={enrollmentRecoveryNotice(state)} actions={
|
||||
<Button disabled={pending||!enrollmentAllowed(state,'verify')} aria-busy={busy==='verify'}
|
||||
icon={busy==='verify'?<ActivityIndicator size="compact"/>:undefined}
|
||||
onClick={()=>void run('verify',true)}>{busy==='verify'?'Проверяем состояние':'Переподключиться'}</Button>}/>}
|
||||
<SettingsCard eyebrow="Шаг 01" title="Bluetooth" description="Найдите K1 рядом с бортовым компьютером и выберите его из списка." actions={
|
||||
<Button disabled={pending||!enrollmentAllowed(state,'scan')} aria-busy={busy==='scan'}
|
||||
icon={busy==='scan'?<ActivityIndicator size="compact"/>:undefined}
|
||||
@@ -166,7 +176,7 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
|
||||
{notice&&!bluetoothFailure&&<div data-enrollment-reveal="result" role="status"><SettingsCard align="center" title={notice}/></div>}
|
||||
</SettingsCard></div>}
|
||||
</>}
|
||||
{notice&&!selected&&!bluetoothFailure&&<div data-enrollment-reveal="result" role="status"><SettingsCard align="center" title={notice}/></div>}
|
||||
{notice&&!selected&&!state?.reconnect_target&&!bluetoothFailure&&<div data-enrollment-reveal="result" role="status"><SettingsCard align="center" title={notice}/></div>}
|
||||
<ToastStack items={error?[{id:'enrollment-error',tone:'error',title:error,durationMs:null}]:[]} onDismiss={()=>setError('')}/>
|
||||
</div>,
|
||||
});
|
||||
|
||||
@@ -5,15 +5,15 @@ import {K1SpatialSession, k1SpatialPhasePresentation} from '../components/K1Spat
|
||||
import {deviceTelemetry} from '../spatialSessionModel';
|
||||
import type {AcquisitionState} from '../spatialSessionModel';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {ActivityIndicator,Button,Icon,IconButton,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {perform,type Sensor,type SensorTransport} from './runtime';
|
||||
import {ActivityIndicator,Button,Description,Icon,IconButton,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {perform} from './runtime';
|
||||
import {K1LiveView} from './K1LiveView';
|
||||
import type {RerunHostFactory} from '@mission-core/sensor-sdk';
|
||||
import type {SensorDetailProps} from '@mission-core/sensor-sdk';
|
||||
import {K1SceneWindows,type SceneTool} from './K1SceneWindows';
|
||||
import {useK1SceneSettings} from './useK1SceneSettings';
|
||||
import {k1ConnectionNotice,k1ManualState,k1Status} from './presentation';
|
||||
import {k1ConnectionNotice,k1ManualState,k1Status,k1StorageStatus} from './presentation';
|
||||
|
||||
export function K1Detail({device,transport,enabled,back,refresh,failure,createRerunHost,reconnect}:{device:Sensor;transport:SensorTransport;enabled:boolean;back:()=>void;refresh:()=>Promise<void>;failure:(error:unknown)=>void;createRerunHost?:RerunHostFactory;reconnect?:()=>void}){
|
||||
export function K1Detail({hideBack=false,maintenanceBlocked=false,device,transport,enabled,back,backLabel='К устройствам',refresh,failure,createRerunHost,reconnect,previewEnabled=true,sceneProfile}:SensorDetailProps&{hideBack?:boolean;maintenanceBlocked?:boolean}){
|
||||
const [busy,setBusy]=useState(''),[tool,setTool]=useState<SceneTool|null>(null),[operationError,setOperationError]=useState('');
|
||||
const [projectName,setProjectName]=useState(''),[projectNameTouched,setProjectNameTouched]=useState(false);
|
||||
const [mountType,setMountType]=useState<MountType>(SUPPORTED_MOUNT_TYPE),[gnssMode,setGnssMode]=useState<GnssMode>(SUPPORTED_GNSS_MODE);
|
||||
@@ -21,18 +21,18 @@ export function K1Detail({device,transport,enabled,back,refresh,failure,createRe
|
||||
const [sceneOpen,setSceneOpen]=useState(['preparing','starting','streaming','stopping'].includes(device.snapshot.acquisition));
|
||||
const acquisitionId=device.control?.acquisition_id;
|
||||
useEffect(()=>{if(acquisitionId&&['preparing','starting','streaming','stopping'].includes(device.snapshot.acquisition))setSceneOpen(true);},[acquisitionId]);
|
||||
const scene=useK1SceneSettings(device,transport,failure);
|
||||
const scene=useK1SceneSettings(device,transport,failure,sceneProfile);
|
||||
const running=useRef(false);
|
||||
const failedAction=useRef('');
|
||||
const streaming=device.snapshot.acquisition==='streaming';
|
||||
const manual=k1ManualState(device,enabled),status=k1Status(device,enabled);
|
||||
const manual=k1ManualState(device,enabled),status=k1Status(device,enabled),storage=k1StorageStatus(device,enabled);
|
||||
const pending=busy||(['preparing','starting'].includes(device.snapshot.acquisition)?'start':device.snapshot.acquisition==='stopping'?'stop':'');
|
||||
async function act(action:'start'|'stop'|'verify'){
|
||||
if(running.current||!enabled)return;
|
||||
if(running.current||!enabled||(action==='start'&&maintenanceBlocked))return;
|
||||
if(action==='start'){setProjectNameTouched(true);if(project.error)return;setSceneOpen(true);}
|
||||
running.current=true;setBusy(action);failedAction.current='';setOperationError('');failure(null);
|
||||
try{await perform(transport,device,action,action==='verify'?{}:{operator_confirmed:true,control_generation:device.control?.generation,acquisition_id:device.control?.acquisition_id??null,...(action==='start'?{project_name:project.value,mount_type:mountType,gnss_mode:gnssMode}:{})});await refresh();}
|
||||
catch{failedAction.current=action;setOperationError(action==='start'?'Результат запуска пока не подтверждён.':action==='stop'?'Результат остановки пока не подтверждён.':'Не удалось подтвердить связь с K1. Проверьте питание сканера; если связь не восстановится, откройте подключение устройства и найдите K1 заново.');await refresh().catch(()=>{});}
|
||||
catch{failedAction.current=action;setOperationError(action==='start'?'Результат запуска пока не подтверждён.':action==='stop'?'Результат остановки пока не подтверждён.':k1ConnectionNotice(device,enabled));await refresh().catch(()=>{});}
|
||||
finally{running.current=false;setBusy('');}
|
||||
}
|
||||
const confirmed=(failedAction.current==='start'&&streaming)||(failedAction.current==='stop'&&device.control?.phase==='completed')||(failedAction.current==='verify'&&manual.connected);
|
||||
@@ -43,22 +43,23 @@ export function K1Detail({device,transport,enabled,back,refresh,failure,createRe
|
||||
{manual.showStop&&<Button size="compact" disabled={!manual.connected||!!pending||(!streaming&&!device.control?.can_stop)} aria-busy={pending==='stop'} icon={pending==='stop'?<ActivityIndicator size="compact"/>:undefined} onClick={()=>void act('stop')}><span className="xgrids-k1-spatial-controls__action-label">{pending==='stop'?'Остановка устройства…':'Остановить устройство и запись'}</span></Button>}
|
||||
</K1SpatialSession>;
|
||||
return <div className="sensor-content">
|
||||
<div className="sensor-actions sensor-inventory-toolbar"><Button onClick={back}>К устройствам</Button><StatusBadge tone={status.tone}>{status.label}</StatusBadge></div>
|
||||
<div className="sensor-actions sensor-inventory-toolbar">{!hideBack&&<Button onClick={back}>{backLabel}</Button>}<StatusBadge tone={status.tone}>{status.label}</StatusBadge></div>
|
||||
<StatusBadge tone={storage.tone}>{storage.label}</StatusBadge>
|
||||
<SettingsCard title={device.name} description="Ручной запуск камеры и лидара на бортовом компьютере. Исходные данные записи сохраняются на БК."
|
||||
actions={manual.connected&&<IconButton label="Настройки устройства" disabled={!!pending} onClick={()=>setTool('display')}><Icon name="settings"/></IconButton>}>
|
||||
actions={manual.connected&&previewEnabled&&<IconButton label="Настройки устройства" disabled={!!pending} onClick={()=>setTool('display')}><Icon name="settings"/></IconButton>}>
|
||||
{manual.connected&&!manual.showStop&&<K1AcquisitionFields mountType={mountType} setMountType={setMountType} gnssMode={gnssMode} setGnssMode={setGnssMode}
|
||||
projectName={projectName} setProjectName={setProjectName} projectNameTouched={projectNameTouched} setProjectNameTouched={setProjectNameTouched} disabled={!!pending}/>}
|
||||
{manual.connected&&(!manual.showStop||pending==='start')&&<Button variant="primary" tone="neutral" disabled={!!pending||!manual.canStart||!!project.error} aria-busy={pending==='start'}
|
||||
{manual.connected&&(!manual.showStop||pending==='start')&&<Button variant="primary" tone="neutral" disabled={maintenanceBlocked||!!pending||!manual.canStart||!!project.error} aria-busy={pending==='start'}
|
||||
icon={pending==='start'?<ActivityIndicator size="compact"/>:undefined} onClick={()=>void act('start')}>{pending==='start'?'Запускаем устройство':'Инициировать запуск'}</Button>}
|
||||
{manual.showStop&&pending!=='start'&&<Button disabled={!manual.connected||!!pending||(!streaming&&!device.control?.can_stop)} aria-busy={pending==='stop'}
|
||||
icon={pending==='stop'?<ActivityIndicator size="compact"/>:undefined} onClick={()=>void act('stop')}>{pending==='stop'?'Останавливаем устройство':'Остановить устройство'}</Button>}
|
||||
{!manual.connected&&device.control?.can_verify&&<Button disabled={!enabled||!!pending} aria-busy={pending==='verify'} icon={pending==='verify'?<ActivityIndicator size="compact"/>:undefined} onClick={()=>void act('verify')}>Проверить состояние K1</Button>}
|
||||
{!manual.connected&&<p role="status">{summary}</p>}
|
||||
{!manual.connected&&reconnect&&!manual.active&&<Button disabled={!enabled||!!pending} onClick={reconnect}>Подключить устройство</Button>}
|
||||
{manual.connected&&!confirmed&&operationError&&<p role="status">{operationError}</p>}
|
||||
{!manual.connected&&<Description role="status">{summary}</Description>}
|
||||
{!manual.connected&&reconnect&&!manual.active&&<Button disabled={!enabled||!!pending} onClick={reconnect}>{device.connection_mode==='usb'?'Подключить по Wi-Fi':'Подключить устройство'}</Button>}
|
||||
{manual.connected&&!confirmed&&operationError&&<Description role="status">{operationError}</Description>}
|
||||
</SettingsCard>
|
||||
{manual.connected&&<K1SceneWindows tool={tool} close={()=>setTool(null)} scene={scene} connected={enabled}/>}
|
||||
{!sceneOpen&&manual.showStop&&<Button onClick={()=>setSceneOpen(true)}>Открыть пространственную сцену</Button>}
|
||||
{sceneOpen&&createRerunHost&&<K1LiveView device={device} transport={transport} createRerunHost={createRerunHost} enabled={enabled&&streaming} scene={scene} openTool={setTool} close={()=>setSceneOpen(false)} sessionControls={sessionControls}/>}
|
||||
{previewEnabled&&!sceneOpen&&manual.showStop&&<Button onClick={()=>setSceneOpen(true)}>Открыть пространственную сцену</Button>}
|
||||
{previewEnabled&&sceneOpen&&createRerunHost&&<K1LiveView device={device} transport={transport} createRerunHost={createRerunHost} enabled={enabled&&streaming} scene={scene} openTool={setTool} close={()=>setSceneOpen(false)} sessionControls={sessionControls}/>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import {useMemo} from 'react';
|
||||
import {observationRerun} from './observationRerun';
|
||||
import type {ReactNode} from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ApplicationPanel, Icon, IconButton, StatusBadge } from '@nodedc/ui-react';
|
||||
@@ -22,7 +24,9 @@ export function K1LiveView({ device, transport, createRerunHost, enabled, scene,
|
||||
const [generation, setGeneration] = useState(0), [status, setStatus] = useState<PreviewStatus>(pendingPreview);
|
||||
const attempts = useRef(0);
|
||||
const report = useCallback((value: PreviewStatus) => { setStatus(value); }, []);
|
||||
useK1Preview(device, transport, createRerunHost, spatial, video, report, generation, enabled);
|
||||
const current=useRef({device,transport,settings:scene.draft,view:'3d'});current.current={device,transport,settings:scene.draft,view:'3d'};
|
||||
const host=useMemo(()=>observationRerun(createRerunHost,()=>current.current),[createRerunHost]);
|
||||
useK1Preview(device, transport, host, spatial, video, report, generation, enabled,scene.draft);
|
||||
useEffect(() => {
|
||||
if (!status.retry || !enabled)
|
||||
return;
|
||||
@@ -68,7 +72,7 @@ export function K1LiveView({ device, transport, createRerunHost, enabled, scene,
|
||||
<div><span>Точек</span><strong>{status.presented?status.points.toLocaleString('ru-RU'):'—'}</strong></div>
|
||||
<div><span>До публикации</span><strong>{status.presented&&device.frames?.mqtt_to_publish_ms!=null?device.frames.mqtt_to_publish_ms.toFixed(1):'—'}<small> мс</small></strong></div>
|
||||
</>}
|
||||
timeline={!focusedAny&&<ObservationTimeline active={status.presented} sourceCount={visible.size} mode="live-only" accumulationSeconds={scene.draft.accumulationSeconds} onAccumulationChange={accumulationSeconds=>scene.stage({accumulationSeconds})} onAccumulationCommit={scene.flush} className="scene-timeline"/>}
|
||||
timeline={!focusedAny&&<ObservationTimeline active={status.presented} sourceCount={visible.size} mode="live-only" accumulationMaxSeconds={scene.draft.accumulationMaxSeconds} accumulationSeconds={scene.draft.accumulationSeconds} onAccumulationChange={accumulationSeconds=>scene.stage({accumulationSeconds})} onAccumulationCommit={scene.flush} className="scene-timeline"/>}
|
||||
media={<FloatingMediaWindow title="K1 · камера справа" subtitle="Видеоканал, опубликованный активным устройством" boundsRef={viewport} rect={cameraRect} maximized={cameraMaximized} active={cameraMaximized} hidden={focused||!visible.has('camera')} onRectChange={setCameraRect} onMaximizedChange={setCameraMaximized} onActivate={()=>{}} onClose={()=>{setCameraMaximized(false);setVisible(current=>{const next=new Set(current);next.delete('camera');return next;});}}
|
||||
status={<span className="floating-observation-window__status">{status.cameraPresented?'Эфир':'Ожидание'}</span>}
|
||||
footer={<span className="floating-observation-window__footer"><span>Бортовой компьютер</span><span>Эфир без буфера</span></span>}>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
.k1-management-mode {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--nodedc-space-3);
|
||||
}
|
||||
.k1-management-mode > :first-child { flex: 1 1 18rem; min-width: 0; }
|
||||
@@ -0,0 +1,53 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {ActivityIndicator,Button,Description,Checker,ConfirmationModal,Icon,IconButton,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {K1Management,ManagementOperation,K1Project} from './useK1Management';
|
||||
import './K1ManagementControls.css';
|
||||
|
||||
type Confirmation={operation:ManagementOperation;title:string;description:string;projects?:K1Project[];revision?:string};
|
||||
export function K1ManagementControls({management:m,storage=false}:{management:K1Management;storage?:boolean}) {
|
||||
const [mode,setMode]=useState<'data'|'storage'>('data'),[selected,setSelected]=useState<string[]>([]);
|
||||
const [confirmation,setConfirmation]=useState<Confirmation|null>(null);
|
||||
const projects=m.catalog?.projects??[];
|
||||
useEffect(()=>{if(m.info?.usb_mode)setMode(m.info.usb_mode);},[m.info?.usb_mode]);
|
||||
useEffect(()=>{setSelected([]);},[m.catalog]);
|
||||
useEffect(()=>{if(storage&&m.canManage&&!m.catalog)void m.run('projects');},[storage,m.info]);
|
||||
const label=m.info?.storage_type==='microSD'?'microSD':m.info?.storage_type==='external-usb'?'Внешний USB-накопитель':'Хранилище K1';
|
||||
function askDelete(items:K1Project[]) {
|
||||
setConfirmation({operation:'delete-projects',title:`Удалить проекты: ${items.length}?`,
|
||||
description:`Записи будут удалены с K1 без возможности отмены: ${items.map(p=>p.name).join(', ')}.`,projects:items,revision:m.catalog?.catalog_revision});
|
||||
}
|
||||
return <div className="sensor-content">
|
||||
<SettingsCard title="Режим USB" description={m.info?`Текущий режим: ${m.info.usb_mode==='storage'?'USB-накопитель':'канал управления (USB Ethernet)'}.`:'Режим устройства ещё не подтверждён.'}>
|
||||
<div className="k1-management-mode">
|
||||
<Select label="Режим USB" variant="split" value={mode} onChange={setMode} disabled={!m.canManage}
|
||||
options={[{value:'data',label:'Канал управления (USB Ethernet)'},{value:'storage',label:'USB-накопитель'}]}/>
|
||||
<Button disabled={!m.canManage||mode===m.info?.usb_mode||(mode==='storage'&&!m.canSwitchToStorage)} onClick={()=>setConfirmation({operation:mode==='storage'?'usb-storage':'usb-data',title:'Изменить режим USB?',description:mode==='storage'?'В режиме USB-накопителя сканирование недоступно. Для новой съёмки верните канал управления.':'K1 вернётся в режим канала управления по USB Ethernet.'})}>Инициализировать режим</Button>
|
||||
</div>
|
||||
{!m.canSwitchToStorage&&<Description>Режим USB-накопителя отключает канал управления по USB. Для переключения и возврата подключите K1 через Bridge. Список проектов доступен без смены режима.</Description>}
|
||||
<Button disabled={!m.ready||!!m.busy} onClick={()=>void m.run('info')}>Обновить состояние</Button>
|
||||
</SettingsCard>
|
||||
{storage?<SettingsCard title={label} description="Проекты на самом сканере. Список и удаление — через канал управления, без перехода в режим USB-накопителя.">
|
||||
<div className="sensor-actions">
|
||||
<Checker label="Выбрать все" checked={!!projects.length&&selected.length===projects.length} disabled={!m.canManage||!projects.length} onChange={checked=>setSelected(checked?projects.map(p=>p.id):[])}/>
|
||||
<Button disabled={!m.canManage} onClick={()=>void m.run('projects')}>Обновить список</Button>
|
||||
<Button disabled={!m.canManage||!selected.length} onClick={()=>askDelete(projects.filter(p=>selected.includes(p.id)))}>Удалить выбранное</Button>
|
||||
</div>
|
||||
<ResourceList>{projects.map(project=><li key={project.id}><ResourceRow title={<Checker label={project.name} checked={selected.includes(project.id)} disabled={!m.canManage} onChange={checked=>setSelected(values=>checked?[...values,project.id]:values.filter(id=>id!==project.id))}/>}
|
||||
actions={<IconButton label={`Удалить ${project.name}`} disabled={!m.canManage} onClick={()=>askDelete([project])}><Icon name="trash"/></IconButton>}/></li>)}</ResourceList>
|
||||
{m.catalog&&!projects.length&&<Description>На K1 нет проектов.</Description>}
|
||||
{!m.catalog&&!m.busy&&<Description>Обновите список проектов.</Description>}
|
||||
<Button disabled={!m.canManage} onClick={()=>setConfirmation({operation:'format-storage',title:'Очистить диск K1?',description:'Все данные основного хранилища K1 будут удалены форматированием. Это действие нельзя отменить.'})}>Очистить диск</Button>
|
||||
</SettingsCard>:<SettingsCard title="Питание устройства">
|
||||
<div className="sensor-actions">
|
||||
<Button disabled={!m.canManage} onClick={()=>setConfirmation({operation:'reboot',title:'Перезагрузить K1?',description:'Связь со сканером временно прервётся. Бортовой компьютер останется включённым.'})}>Перезагрузить устройство</Button>
|
||||
<Button disabled={!m.canManage} onClick={()=>setConfirmation({operation:'power-off',title:'Выключить K1?',description:'Для следующего включения потребуется кнопка питания на сканере. Бортовой компьютер останется включённым.'})}>Выключить устройство</Button>
|
||||
</div>
|
||||
</SettingsCard>}
|
||||
{!m.ready&&<Description role="status">Обслуживание доступно при подтверждённом подключении и после завершения съёмки K1.</Description>}
|
||||
{m.busy&&<Description role="status"><ActivityIndicator size="compact"/> Ожидаем ответ K1…</Description>}
|
||||
{m.message&&<Description role="status">{m.message}</Description>}
|
||||
<ConfirmationModal open={!!confirmation} title={confirmation?.title??''} description={confirmation?.description??''}
|
||||
danger={confirmation?.operation==='delete-projects'||confirmation?.operation==='format-storage'} onClose={()=>setConfirmation(null)}
|
||||
onConfirm={async()=>{if(!confirmation)return;const request=confirmation;const result=await m.run(request.operation,request.projects?.map(p=>p.id),request.revision);setConfirmation(null);if(result?.status==='succeeded'&&storage)void m.run('projects');}}/>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,23 +1,80 @@
|
||||
import {SpatialScene,EmptySpatialStage,heightSlice,ObservationTimeline,useLiveRerunPlayback} from '@mission-core/sensor-sdk';
|
||||
import {useK1SceneSettings} from './useK1SceneSettings';
|
||||
import {useK1CameraPreview} from './useK1CameraPreview';
|
||||
import './livePreview.css';
|
||||
import {observationRerun} from './observationRerun';
|
||||
import {useCallback,useEffect,useMemo,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Icon,IconButton} from '@nodedc/ui-react';
|
||||
import {Button,Description,Icon,IconButton,ToastStack,RangeControl} from '@nodedc/ui-react';
|
||||
import {ObservationHeader,type SensorObservationProps} from '@mission-core/sensor-sdk';
|
||||
import {useK1Preview,pendingPreview,type PreviewStatus} from './useK1Preview';
|
||||
import {K1ObservationAction} from './K1ObservationAction';
|
||||
import {perform} from './runtime';
|
||||
import {k1ConnectionNotice,k1ManualState} from './presentation';
|
||||
|
||||
function ActiveK1Observation({device,transport,enabled,views,createRerunHost}:SensorObservationProps){
|
||||
const spatial=useRef<HTMLDivElement>(null),plan=useRef<HTMLDivElement>(null),video=useRef<HTMLVideoElement>(null);
|
||||
const [status,setStatus]=useState(pendingPreview),[generation,setGeneration]=useState(0);const attempts=useRef(0);
|
||||
type ActiveProps=SensorObservationProps&{stop:()=>void;pending:boolean};
|
||||
function PointPane({view,...props}:ActiveProps&{view:SensorObservationProps['views'][number]}){
|
||||
const {device,transport,createRerunHost}=props;
|
||||
const spatial=useRef<HTMLDivElement>(null),viewport=useRef<HTMLDivElement>(null),video=useRef<HTMLVideoElement>(null);
|
||||
const [status,setStatus]=useState(pendingPreview),[generation,setGeneration]=useState(0);
|
||||
const scene=useK1SceneSettings(device,transport,()=>{}, {view:view.id,settings:props.sceneProfiles?.[view.id],save:value=>props.onSceneChange?.(view.id,value)});
|
||||
const [bounds,setBounds]=useState<{min:number;max:number}|null>(null);
|
||||
const onBounds=useCallback((next:{min:number;max:number})=>setBounds(old=>old&&Math.abs(old.min-next.min)<.01&&Math.abs(old.max-next.max)<.01?old:next),[]);
|
||||
const floor=scene.draft.heightFloor??null,ceiling=scene.draft.heightCeiling??null;
|
||||
const range=bounds?{min:Math.min(0,bounds.min,floor??Infinity),max:Math.max(80,bounds.max,ceiling??-Infinity)}:null;
|
||||
const current=useRef({device,transport,settings:scene.draft,view:view.id,onBounds});current.current={device,transport,settings:scene.draft,view:view.id,onBounds};
|
||||
const host=useMemo(()=>observationRerun(createRerunHost,()=>current.current),[createRerunHost]);
|
||||
const report=useCallback((value:PreviewStatus)=>setStatus(value),[]);
|
||||
const host=useMemo(()=>observationRerun(createRerunHost,plan),[createRerunHost]);
|
||||
useK1Preview(device,transport,host,spatial,video,report,generation,enabled);
|
||||
useEffect(()=>{if(!status.retry)return;const timer=setTimeout(()=>setGeneration(v=>v+1),Math.min(30000,2000*2**Math.min(attempts.current++,4)));return()=>clearTimeout(timer);},[status.retry]);
|
||||
return <>{views.map(view=>{const points=view.id!=='camera',live=points?status.presented:status.cameraPresented;return createPortal(<div className="observation-source">
|
||||
<ObservationHeader targets={view} live={live} label={live?'Прямой эфир':points?status.lidar:status.camera}>{status.retry&&<IconButton label="Повторить подключение K1" onClick={()=>setGeneration(v=>v+1)}><Icon name="refresh"/></IconButton>}</ObservationHeader>
|
||||
<div className="observation-source__media">{points?<div className="observation-rerun" ref={view.id==='plan'?plan:spatial}/>:<video ref={video} autoPlay muted playsInline aria-label={`${device.name} Cam Right`} data-live={live}/>}</div>
|
||||
</div>,view.target,view.id);})}</>;
|
||||
const native=useK1Preview(device,transport,host,spatial,video,report,generation,props.enabled,scene.draft);
|
||||
const playback=useLiveRerunPlayback(native,device.control?.acquisition_id??device.snapshot.context.session_id);
|
||||
useEffect(()=>{if(!status.retry)return;const timer=setTimeout(()=>setGeneration(v=>v+1),5000);return()=>clearTimeout(timer);},[status.retry,generation]);
|
||||
const configure=()=>props.configure?.(view.id);
|
||||
return <div className="observation-source k1-observation-scene" data-k1-history={JSON.stringify(playback.state)}>
|
||||
<ObservationHeader targets={view} live={status.presented} waiting={!status.presented} label={status.lidar}><K1ObservationAction device={device} fresh={props.enabled&&props.fresh!==false} configure={configure} stop={props.stop} pending={props.pending}/><IconButton label="Следовать за K1" aria-pressed={scene.draft.followTrajectory??false} onClick={()=>scene.commit({followTrajectory:!scene.draft.followTrajectory})}><Icon name="target"/></IconButton></ObservationHeader>
|
||||
<SpatialScene viewportRef={viewport}
|
||||
renderer={<><div className="rerun-viewport" data-status={status.hasScene?'ready':'loading'}><div className="rerun-viewport__canvas" data-presented={status.hasScene?'true':'false'} ref={spatial}/></div>
|
||||
{!status.hasScene&&<EmptySpatialStage settings={scene.draft} title="Ожидаем данные K1" detail="Пространственная сцена появится после получения облака точек."/>}</>}
|
||||
status={{tone:status.presented?'success':'warning',pulse:!status.presented,label:status.presented?'Визуализатор готов':status.lidar}}
|
||||
overlays={range&&status.hasScene?<div className="scene-height-slice"><RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor??range.min,ceiling??range.max]} min={range.min} max={range.max} step="any"
|
||||
formatValue={value=>`${value.toFixed(1).replace('.',',')} м`} formatLimit={value=>value.toFixed(1).replace('.',',')}
|
||||
onChange={value=>{const next=heightSlice(value,[range.min,range.max]);scene.commit({heightFloor:next.floor,heightCeiling:next.ceiling});}}/></div>:null}
|
||||
timeline={<ObservationTimeline className="scene-timeline" active={status.presented} sourceCount={1} mode="buffered" seekable={!!playback.state.rangeNs}
|
||||
rangeNs={playback.state.rangeNs} currentNs={playback.state.currentNs} playing={playback.state.playing} followingLive={playback.state.live}
|
||||
onSeek={playback.seek} onPlayingChange={playback.setPlaying} onJumpToEnd={playback.jumpToLive}
|
||||
accumulationSeconds={scene.draft.accumulationSeconds} accumulationMaxSeconds={scene.draft.accumulationMaxSeconds} onAccumulationChange={value=>scene.stage({accumulationSeconds:value})} onAccumulationCommit={scene.flush}/> }
|
||||
metrics={<><div><span>КАДР/С</span><strong>{status.presented?(device.frames?.pcl_fps??0).toFixed(1):'—'}</strong></div><div><span>Точек</span><strong>{status.presented?status.points.toLocaleString('ru-RU'):'—'}</strong></div></>}
|
||||
/>
|
||||
</div>;
|
||||
}
|
||||
function CameraPane({view,...props}:ActiveProps&{view:SensorObservationProps['views'][number]}){
|
||||
const video=useRef<HTMLVideoElement>(null),[generation,setGeneration]=useState(0);
|
||||
const status=useK1CameraPreview(props.device,props.transport,video,props.enabled,generation);
|
||||
return <div className="observation-source"><ObservationHeader targets={view} live={status.cameraPresented} label={status.camera}><K1ObservationAction device={props.device} fresh={props.enabled&&props.fresh!==false} configure={()=>props.configure?.(view.id)} stop={props.stop} pending={props.pending}/><IconButton label="Обновить изображение K1" onClick={()=>setGeneration(v=>v+1)}><Icon name="refresh"/></IconButton></ObservationHeader>
|
||||
<div className="observation-source__media k1-camera-content"><video ref={video} autoPlay muted playsInline aria-label={`${props.device.name} Cam Right`} style={{visibility:status.cameraPresented?'visible':'hidden'}}/>
|
||||
</div>
|
||||
{!status.cameraPresented&&<p className="observation-source__notice" role="status">{status.camera}</p>}</div>;
|
||||
}
|
||||
function ActiveK1Observation(props:ActiveProps){return <>{props.views.map(view=>createPortal(view.id==='camera'?<CameraPane {...props} view={view}/>:<PointPane {...props} view={view}/>,view.target,view.id))}</>;}
|
||||
export function K1Observation(props:SensorObservationProps){
|
||||
if(!props.enabled||props.device.snapshot.acquisition!=='streaming')return <>{props.views.map(view=>createPortal(<div className="observation-source"><ObservationHeader targets={view} live={false} label={props.enabled?'Просмотр остановлен':'Нет связи с источником'}/><p className="observation-source__notice">Начните приём данных в конфигураторе K1.</p></div>,view.target,view.id))}</>;
|
||||
return <ActiveK1Observation {...props}/>;
|
||||
const [pending,setPending]=useState(false),[error,setError]=useState('');
|
||||
const stopping=useRef(false);
|
||||
const stop=async()=>{
|
||||
if(stopping.current||!props.enabled||props.fresh===false||!props.device.control?.can_stop)return;
|
||||
stopping.current=true;setPending(true);setError('');
|
||||
try{await perform(props.transport,props.device,'stop',{operator_confirmed:true,control_generation:props.device.control?.generation,acquisition_id:props.device.control?.acquisition_id??null});}
|
||||
catch{setError('Остановка K1 пока не подтверждена. Проверьте состояние устройства.');}
|
||||
finally{stopping.current=false;setPending(false);}
|
||||
};
|
||||
const toast=<ToastStack items={error?[{id:'k1-observation-stop',tone:'error',title:error}]:[]} onDismiss={()=>setError('')}/>;
|
||||
const fresh=props.enabled&&props.fresh!==false,manual=k1ManualState(props.device,fresh);
|
||||
const label=!manual.connected?'Нет связи с K1':props.device.snapshot.acquisition==='stopping'?'Завершение сканирования':manual.active?'Подготовка сканирования':manual.canStart?'Готов к сканированию':'Подключён';
|
||||
// A link gap pauses the existing preview hook; it must not destroy that
|
||||
// acquisition's native recording, accumulated geometry or resume cursor.
|
||||
if(props.device.snapshot.acquisition!=='streaming')return <>{toast}{props.views.map(view=>createPortal(<div className="observation-source">
|
||||
<ObservationHeader targets={view} live={false} waiting={manual.active} label={label}><K1ObservationAction device={props.device} fresh={fresh} configure={()=>props.configure?.(view.id)} stop={()=>void stop()} pending={pending}/></ObservationHeader>
|
||||
<div className="observation-source__notice"><Description>{manual.connected?(manual.active?'Состояние сканирования доступно в управлении K1.':'Активируйте устройство кнопкой Play в шапке вьюпорта.'):k1ConnectionNotice(props.device,props.fresh!==false)}</Description>
|
||||
{!manual.connected&&!manual.active&&props.reconnect&&<Button onClick={props.reconnect}>Подключить K1</Button>}
|
||||
</div>
|
||||
</div>,view.target,view.id))}</>;
|
||||
return <>{toast}<ActiveK1Observation {...props} stop={()=>void stop()} pending={pending}/></>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import {Icon,IconButton} from '@nodedc/ui-react';
|
||||
import type {Sensor} from './runtime';
|
||||
import {k1ManualState} from './presentation';
|
||||
|
||||
/** Play opens the named-session workflow; Stop acts on the current acquisition. */
|
||||
export function K1ObservationAction({device,fresh,configure,stop,pending=false}:{
|
||||
device:Sensor;fresh:boolean;configure?:()=>void;stop?:()=>void;pending?:boolean;
|
||||
}){
|
||||
const manual=k1ManualState(device,fresh);
|
||||
if(!manual.connected&&!manual.active)return null;
|
||||
if(manual.showStop)return <IconButton label="Остановить сканирование K1" loading={pending||device.snapshot.acquisition==='stopping'}
|
||||
disabled={!manual.connected||!device.control?.can_stop||!stop} onClick={stop}><Icon name="stop"/></IconButton>;
|
||||
if(!configure)return null;
|
||||
return <IconButton label="Начать сканирование K1" disabled={!manual.canStart} onClick={configure}><Icon name="play"/></IconButton>;
|
||||
}
|
||||
@@ -10,7 +10,13 @@ export function K1SceneWindows({ tool, close, scene, connected }: {
|
||||
connected: boolean;
|
||||
}) {
|
||||
const title = tool === 'source' ? 'Визуальный движок' : tool === 'layers' ? 'Слои сцены' : 'Отображение';
|
||||
return <Window open={tool !== null} title={title} placement="end" draggable closeOnBackdrop={false} closeOnEscape={false} lockBodyScroll={false} trapFocus={false} className={`scene-tool-window scene-tool-window--${tool === 'source' ? 'source' : tool === 'layers' ? 'layers' : 'display'}`} onClose={() => { scene.flush(); close(); }}>
|
||||
return <Window open={tool !== null} title={title} placement="center" closeOnBackdrop={false} className={`scene-tool-window scene-tool-window--${tool === 'source' ? 'source' : tool === 'layers' ? 'layers' : 'display'}`} onClose={() => { scene.flush(); close(); }}>
|
||||
<K1SceneControls tool={tool} scene={scene} connected={connected}/>
|
||||
</Window>;
|
||||
}
|
||||
|
||||
export function K1SceneControls({tool,scene,connected}:{tool:SceneTool|null;scene:K1SceneState;connected:boolean}) {
|
||||
return <>
|
||||
{tool === 'display' && <SceneDisplayControls displayDraft={scene.draft} stageDisplayPatch={scene.stage} commitDisplayPatch={scene.commit} flushDisplaySettings={scene.flush}/>}
|
||||
{tool === 'layers' && <SceneLayerControls sceneSettings={scene.draft} pending={scene.pending} applyScenePatch={scene.commit}/>}
|
||||
{tool === 'source' && <Inspector defaultOpen={['connection']} singleOpen sections={[{ id: 'connection', label: 'Подключение', description: 'Живые данные с бортового компьютера', content: <div className="inspector-control-stack">
|
||||
@@ -19,5 +25,5 @@ export function K1SceneWindows({ tool, close, scene, connected }: {
|
||||
<ControlRow label="Режим">Живой просмотр</ControlRow>
|
||||
<p className="scene-window-note">Потоки открываются автоматически после запуска устройства. Запись сохраняется на бортовом компьютере.</p>
|
||||
</div> }]}/>}
|
||||
</Window>;
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {FeatureSettingsWindow} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '@mission-core/sensor-sdk';
|
||||
import {K1Detail} from './K1Detail';
|
||||
import {K1SceneControls,type SceneTool} from './K1SceneWindows';
|
||||
import {useK1SceneSettings} from './useK1SceneSettings';
|
||||
import {useK1Management} from './useK1Management';
|
||||
import {K1ManagementControls} from './K1ManagementControls';
|
||||
import {k1ManualState} from './presentation';
|
||||
|
||||
/** One gear surface; the existing scene owner and persistent viewport profile stay authoritative. */
|
||||
export function K1SettingsWindow(props:SensorDetailProps) {
|
||||
const [section,setSection]=useState<'connection'|'storage'|SceneTool>('connection');
|
||||
const management=useK1Management(props);
|
||||
const scene=useK1SceneSettings(props.device,props.transport,props.failure,props.sceneProfile);
|
||||
const close=()=>{scene.flush();props.back();};
|
||||
const connected=k1ManualState(props.device,props.enabled).connected;
|
||||
useEffect(()=>{if(!connected&&(section==='layers'||section==='display'))setSection('connection');},[connected,section]);
|
||||
return <FeatureSettingsWindow open title={`Настройки · ${props.device.name}`}
|
||||
identity={{title:props.device.name,subtitle:props.device.connection_label,avatarLabel:'K1'}}
|
||||
sections={[
|
||||
{id:'connection',label:'Текущее подключение',icon:'network'},
|
||||
{id:'storage',label:'Локальное хранилище',icon:'folder'},
|
||||
{id:'layers',label:'Слои',icon:'layers',disabled:!connected},
|
||||
{id:'display',label:'Отображение',icon:'sliders',disabled:!connected},
|
||||
]} activeSection={section} onSectionChange={value=>{scene.flush();setSection(value);}} onClose={close}>
|
||||
<div hidden={section!=='connection'} className={section==='connection'?'sensor-content':undefined}><K1Detail {...props} hideBack previewEnabled={false} back={close}
|
||||
maintenanceBlocked={!!management.busy||management.info?.usb_mode==='storage'}/>
|
||||
{section==='connection'&&<K1ManagementControls management={management}/>}</div>
|
||||
{section==='storage'&&<K1ManagementControls management={management} storage/>}
|
||||
{(section==='layers'||section==='display')&&<K1SceneControls tool={section} scene={scene} connected={connected}/>}
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
@@ -31,6 +31,7 @@ export function enrollmentCommand(state:EnrollmentState,action:EnrollmentCommand
|
||||
|
||||
export function enrollmentAllowed(state:EnrollmentState|null,action:EnrollmentCommand['action']):boolean {
|
||||
if(!state?.available||state.fresh===false)return false;
|
||||
if(action==='reset')return state.can_reset===true&&state.supported_actions?.includes('reset')===true;
|
||||
if(!state.allowed_actions)return true; // Older driver, server admission still applies.
|
||||
if(action==='networks')return true;
|
||||
const permissions=action==='scan'?['scan-ble']:action==='connect'?['provision-fresh-device']:
|
||||
@@ -76,13 +77,18 @@ export async function enroll(transport:EnrollmentTransport,initial:EnrollmentSta
|
||||
await pause();assertActive();
|
||||
try{operation=await transport.operation(command.operation_id);}catch{operation=null;}
|
||||
}
|
||||
if(action==='scan'||action==='networks'){
|
||||
if(action==='reset'&&(operation.state!=='complete'||!operation.result||state.command_result?.operation_id!==command.operation_id||state.command_result.status!=='succeeded'||state.mode_revision!==(initial.mode_revision??-1)+1))throw new Error('Сброс подключения пока не подтверждён. Обновите состояние K1.');
|
||||
if(action==='scan'||action==='networks'||action==='reset'){
|
||||
if(action==='scan'&&(operation.state!=='complete'||!operation.result||
|
||||
(state.command_result?.operation_id===command.operation_id&&state.command_result.status!=='succeeded')))
|
||||
throw new Error(scanFailure);
|
||||
if(operation.state!=='complete'||!operation.result)throw new Error(operation.error||unknownResult);
|
||||
return state;
|
||||
}
|
||||
// A terminal delivery without a driver result has no correlated bootstrap result.
|
||||
// Unknown still means unconfirmed: release the UI without replaying a command
|
||||
// or inferring success from a later unrelated connected snapshot.
|
||||
if(!operation.result)throw new Error(operation.error||unknownResult);
|
||||
// A network ACK can precede its owned DeviceInfo bootstrap. Keep observing
|
||||
// the same attempt; no second POST, verify command or target selection occurs.
|
||||
while(true){
|
||||
@@ -156,6 +162,23 @@ export function enrollmentProofCurrent(proof:EnrollmentProof|null,state:Enrollme
|
||||
return !!current&&Object.entries(proof).every(([key,value])=>current[key as keyof EnrollmentProof]===value);
|
||||
}
|
||||
|
||||
/** Existing proof only: no response never proves that the scanner is powered off. */
|
||||
export function enrollmentRecoveryNotice(state:EnrollmentState):string {
|
||||
if(!state.available||state.fresh===false)return 'Нет свежих сведений с БК. Восстанавливаем связь.';
|
||||
const verification=state.verification;
|
||||
if(verification?.status==='accepted'||verification?.status==='running')return 'Проверяем связь и состояние K1.';
|
||||
if(verification?.status==='failed'){
|
||||
const code=verification.error_code;
|
||||
if(code==='connection-verify-route-mismatch')return 'БК не видит K1 в общей сети. Проверьте подключение устройств к одной сети.';
|
||||
if(code==='connection-verify-mqtt-unreachable')return 'K1 не отвечает в общей сети. Проверьте питание и подключение K1 к сети, затем повторите проверку.';
|
||||
if(['connection-verify-device-not-rediscovered','connection-verify-device-not-connectable','connection-verify-status-read-timeout','connection-verify-exact-uuid-scan-timeout','connection-verify-address-unavailable'].includes(code??''))return 'K1 недоступен. Проверьте питание, дождитесь загрузки сканера и проверьте подключение к сети. Затем повторите проверку.';
|
||||
return 'Не удалось подтвердить состояние K1. Проверьте подключение и повторите проверку.';
|
||||
}
|
||||
if(state.connected)return state.acquisition_recovery?.state==='ceased'?'K1 подключён. Предыдущая съёмка завершена.':'Связь с K1 подтверждена.';
|
||||
if(['active','prepared'].includes(state.acquisition_recovery?.state??''))return 'Связь с предыдущей съёмкой не подтверждена. Проверьте состояние K1.';
|
||||
return 'Проверьте связь с K1 в ранее настроенной общей сети.';
|
||||
}
|
||||
|
||||
export function bridgeFormValid(ssid:string,password:string):boolean{
|
||||
const bytes=new TextEncoder();return bytes.encode(ssid).length>0&&bytes.encode(ssid).length<=32&&bytes.encode(password).length>0&&bytes.encode(password).length<=64;
|
||||
}
|
||||
|
||||
@@ -4,3 +4,8 @@
|
||||
.k1-preview.sensor-viewer-expanded .spatial-workspace {height:calc(100vh - 150px)}
|
||||
.k1-camera-content {position:relative;height:100%;min-height:0}
|
||||
.k1-camera-notice {position:absolute;inset:0}
|
||||
|
||||
.k1-observation-scene .spatial-workspace {height:100%;min-height:0;width:100%}
|
||||
.k1-observation-scene .spatial-viewport-shell {min-height:0}
|
||||
|
||||
.k1-observation-scene .scene-information { top: calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); }
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {Sensor,SensorTransport} from './runtime';
|
||||
import {localPreview} from './localPreview';
|
||||
import {previewCamera} from './previewCamera';
|
||||
import {previewFrames} from './previewFrames';
|
||||
/** Existing onboard MSE carrier, independent of cloud view admission. */
|
||||
export function localCameraPreview(device:Sensor,transport:SensorTransport,video:HTMLVideoElement,report:(state:{camera:string;cameraPresented:boolean})=>void){
|
||||
let active=true,decoded=false,last=-1,progress=0;
|
||||
const failed=()=>{if(active)report({camera:'Камера: изображение недоступно',cameraPresented:false});};
|
||||
const ready=()=>{decoded=true;progress=performance.now();};
|
||||
let decoder=previewCamera(video,ready,failed);
|
||||
const connection=localPreview(device,transport,{media:'camera',acquisition_id:device.control?.acquisition_id,view_id:crypto.randomUUID(),after:0},failed);
|
||||
const frames=previewFrames(payload=>decoder.push(payload));
|
||||
connection.camera.onmessage=event=>{try{
|
||||
if(typeof event.data==='string'){const metadata=JSON.parse(event.data);if(metadata.type!=='camera-ready'||typeof metadata.mime!=='string')throw Error('Invalid camera metadata');decoder.close();decoder=previewCamera(video,ready,failed);decoded=false;decoder.open(metadata.mime);}
|
||||
else frames.push(event.data);
|
||||
}catch{failed();}};
|
||||
const timer=setInterval(()=>{if(decoded&&video.currentTime!==last){last=video.currentTime;progress=performance.now();}const fresh=decoded&&performance.now()-progress<2000;report({camera:fresh?'Камера: изображение поступает':'Камера: ожидаем изображение',cameraPresented:fresh});},500);
|
||||
void connection.start().catch(failed);
|
||||
return()=>{active=false;clearInterval(timer);connection.close();frames.close();decoder.close();};
|
||||
}
|
||||
@@ -1,24 +1,41 @@
|
||||
import type {RefObject} from 'react';
|
||||
import type {RerunHostFactory,LiveRerunViewer} from '@mission-core/sensor-sdk';
|
||||
import type {RerunHostFactory,SceneSettings} from '@mission-core/sensor-sdk';
|
||||
import {perform,type Sensor,type SensorTransport} from './runtime';
|
||||
import {k1ScenePatch} from './useK1SceneSettings';
|
||||
|
||||
/** One incoming RRD stream, two independently navigable native views. */
|
||||
export function observationRerun(factory:RerunHostFactory,plan:RefObject<HTMLDivElement|null>):RerunHostFactory {
|
||||
/** Canonical blueprint service; no alternate grid, camera or accumulation defaults. */
|
||||
export function observationRerun(factory:RerunHostFactory,current:()=>{device:Sensor;transport:SensorTransport;settings:SceneSettings;view:string;onBounds?:(bounds:{min:number;max:number})=>void}):RerunHostFactory {
|
||||
return element=>{
|
||||
const spatial=factory(element),overhead=factory(plan.current!);let disposed=false;
|
||||
const controller=new AbortController();
|
||||
const load=async(url:URL)=>{const response=await fetch(url,{signal:controller.signal});if(!response.ok)throw new Error('Не удалось загрузить вид облака точек.');return new Uint8Array(await response.arrayBuffer());};
|
||||
const ready=Promise.all([spatial.ready,overhead.ready,load(new URL('./observation-3d.rbl',import.meta.url)),load(new URL('./observation-plan.rbl',import.meta.url))]).then(([a,b,perspective,top])=>{
|
||||
let primaryBlueprint:ReturnType<LiveRerunViewer['open_channel']>|null=null,secondaryBlueprint:ReturnType<LiveRerunViewer['open_channel']>|null=null,recording:string|null=null;
|
||||
const viewer:LiveRerunViewer={
|
||||
...a.viewer,
|
||||
start:async(source,mount,options)=>{await a.viewer.start(source,mount,options);if(disposed)return;await b.viewer.start(source,b.mount,options);primaryBlueprint=a.viewer.open_channel('observation-perspective');secondaryBlueprint=b.viewer.open_channel('observation-plan');},
|
||||
open_channel:name=>{const first=a.viewer.open_channel(name),second=b.viewer.open_channel(name);return {get ready(){return first.ready&&second.ready;},send_rrd:bytes=>{second.send_rrd(bytes.slice());first.send_rrd(bytes);},close:()=>{first.close();second.close();}};},
|
||||
get_active_recording_id:()=>{const id=a.viewer.get_active_recording_id();if(id&&id!==recording&&primaryBlueprint?.ready&&secondaryBlueprint?.ready&&b.viewer.get_active_recording_id()===id){primaryBlueprint.send_rrd(perspective.slice());secondaryBlueprint.send_rrd(top.slice());recording=id;}return id;},
|
||||
override_panel_state:(panel,state)=>{a.viewer.override_panel_state(panel,state);b.viewer.override_panel_state(panel,state);},
|
||||
set_active_timeline:(id,timeline)=>{a.viewer.set_active_timeline(id,timeline);b.viewer.set_active_timeline(id,timeline);},
|
||||
const host=factory(element),owner=crypto.randomUUID().replaceAll('-','');
|
||||
const timing:{requests:number;started_ms?:number;completed_ms?:number;error?:boolean}={requests:0};
|
||||
const began=performance.now();
|
||||
const report=()=>{element.dataset.k1Profile=JSON.stringify(timing);};
|
||||
let disposed=false,recording:string|null=null,applied='',busy=false,retryAt=0;
|
||||
const ready=host.ready.then(({viewer,mount})=>{
|
||||
let blueprint:ReturnType<typeof viewer.open_channel>|null=null;
|
||||
let sliceKey='',sliceAt=0,boundsAt=0;
|
||||
const refresh=()=>{
|
||||
const id=viewer.get_active_recording_id(),state=current(),settings=k1ScenePatch(state.settings),follow=state.settings.followTrajectory??false;
|
||||
const key=JSON.stringify([id,settings,state.view,follow]);
|
||||
const nextSlice=JSON.stringify([id,state.settings.heightFloor,state.settings.heightCeiling]);
|
||||
// A blueprint can introduce a new native view within the same recording.
|
||||
// Reapply bounded local presentation so that view inherits the slice too.
|
||||
if(id&&(nextSlice!==sliceKey||performance.now()-sliceAt>500)&&viewer.set_height_slice?.(state.settings.heightFloor??null,state.settings.heightCeiling??null)){sliceKey=nextSlice;sliceAt=performance.now();}
|
||||
if(id&&performance.now()-boundsAt>500){boundsAt=performance.now();const bounds=viewer.get_height_bounds?.();if(bounds)state.onBounds?.(bounds);}
|
||||
if(id!==recording)applied='';
|
||||
if(!id||!blueprint?.ready||busy||key===applied||disposed||Date.now()<retryAt)return applied?id:null;
|
||||
busy=true;recording=id;timing.requests++;timing.started_ms=Math.round(performance.now()-began);report();
|
||||
const eye=applied?viewer.get_camera_eye?.():null;
|
||||
void perform<{rrd:string}>(state.transport,state.device,'details',{preview_blueprint:{recording_id:id,owner,view:state.view==='plan'?'plan':'3d',settings,follow_trajectory:follow,host_playback:true,...(eye?{eye}:{})}})
|
||||
.then(result=>{if(disposed||recording!==id)return;const bytes=Uint8Array.from(atob(result.rrd),c=>c.charCodeAt(0));blueprint!.send_rrd(bytes);applied=key;timing.completed_ms=Math.round(performance.now()-began);timing.error=false;report();})
|
||||
.catch(error=>{timing.error=true;report();console.error('K1 spatial profile could not be applied',error);retryAt=Date.now()+3000;}).finally(()=>{busy=false;});
|
||||
return applied?id:null;
|
||||
};
|
||||
return {viewer,mount:a.mount};
|
||||
return {mount,viewer:{...viewer,
|
||||
get ready(){return viewer.ready;},
|
||||
start:async(...args:Parameters<typeof viewer.start>)=>{await viewer.start(...args);if(!disposed)blueprint=viewer.open_channel('canonical-spatial-profile:'+owner);},
|
||||
get_active_recording_id:refresh,
|
||||
}};
|
||||
});
|
||||
return {ready,dispose:()=>{disposed=true;controller.abort();spatial.dispose();overhead.dispose();}};
|
||||
return {ready,dispose:()=>{disposed=true;delete element.dataset.k1Profile;host.dispose();if(recording){const state=current();void perform(state.transport,state.device,'details',{preview_blueprint:{recording_id:recording,owner,release:true}}).catch(()=>{});}}};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type {SensorUiContribution} from '@mission-core/sensor-sdk';
|
||||
import {K1Detail} from './K1Detail';
|
||||
import {K1SettingsWindow} from './K1SettingsWindow';
|
||||
import {DeviceEnrollmentWindow} from './DeviceEnrollmentWindow';
|
||||
import {k1Status} from './presentation';
|
||||
import {K1Observation} from './K1Observation';
|
||||
|
||||
export const xgridsK1SensorUi:SensorUiContribution={
|
||||
kind:'k1', Detail:K1Detail, icon:'network', retainOffline:true, supportsPreparation:false,
|
||||
supportsRenaming:false,status:k1Status,
|
||||
kind:'k1', Detail:K1SettingsWindow, detailPresentation:'modal', icon:'network', retainOffline:true, supportsPreparation:false,
|
||||
supportsRenaming:false,settingsInDetail:true,status:k1Status,
|
||||
wirelessEnrollment:{label:'XGRIDS LixelKity K1',View:DeviceEnrollmentWindow},
|
||||
observation:{Session:K1Observation,catalog:{label:'XGRIDS LixelKity K1',views:[{id:'points',label:'XGRIDS K1 · Облако точек · 3D'},{id:'plan',label:'XGRIDS K1 · Облако точек · Сверху'},{id:'camera',label:'XGRIDS K1 · Камера'}]},views:device=>[{id:'points',label:`${device.name} Point Cloud · 3D`},{id:'plan',label:`${device.name} Point Cloud · Сверху`},{id:'camera',label:`${device.name} Cam Right`}]},
|
||||
observation:{Session:K1Observation,catalog:{label:'XGRIDS LixelKity K1',views:[{id:'points',scene:true,label:'XGRIDS K1 · Облако точек'},{id:'camera',label:'XGRIDS K1 · Камера'}]},views:device=>[{id:'points',scene:true,label:`${device.name} Point Cloud`},{id:'camera',label:`${device.name} Cam Right`}]},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,9 @@ export function k1Status(device:Sensor,fresh:boolean):{label:string;tone:'neutra
|
||||
|
||||
export function k1ConnectionNotice(device:Sensor,fresh:boolean):string {
|
||||
if(!fresh)return 'Нет свежих сведений с БК. Ожидаем восстановления связи.';
|
||||
if(device.connection_mode==='usb')return device.control?.reason_code==='application_authority_unavailable'
|
||||
?'K1 подключён по USB. Служба на БК не смогла авторизовать подключение. Проверьте установленную интеграцию K1.'
|
||||
:'Нет подтверждённой связи с K1 по USB. Проверьте питание сканера и USB-кабель. Состояние съёмки уточняется после восстановления связи.';
|
||||
if(device.control?.reason_code==='application_authority_unavailable')
|
||||
return 'Wi-Fi настроен. Служба K1 на БК не смогла авторизовать подключение. Обновите интеграцию K1 на БК и проверьте состояние устройства.';
|
||||
return device.control?.network_applied
|
||||
@@ -22,3 +25,14 @@ export function k1ManualState(device:Sensor,fresh:boolean) {
|
||||
return {active,connected,canStart:connected&&!active&&device.control?.can_start===true,
|
||||
showStop:active||device.control?.can_stop===true};
|
||||
}
|
||||
|
||||
export function k1StorageStatus(device:Sensor,fresh:boolean,now=Date.now()):{label:string;tone:'neutral'|'warning'} {
|
||||
// Fleet inventory has an existing 20-second heartbeat freshness window.
|
||||
// The driver separately requires a source report no older than five seconds.
|
||||
const value=device.storage_status,age=value?now-Date.parse(value.observed_at):NaN;
|
||||
if(!fresh||!device.online||!device.verified||!value||!Number.isFinite(age)||age<0||age>=20000||
|
||||
!Number.isFinite(value.used_percent)||value.used_percent<0||value.used_percent>100)
|
||||
return {label:'Хранилище K1: нет свежих данных',tone:'neutral'};
|
||||
const percent=(Math.round(value.used_percent*10)/10).toLocaleString('ru-RU');
|
||||
return {label:`Хранилище K1: занято ${percent} %${value.used_percent>=95?' · мало свободного места':''}`,tone:value.used_percent>=95?'warning':'neutral'};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
/** Source-age gate, independent of wall-clock skew between operator and board. */
|
||||
// The optional cloud preview admits 2–3 s delivery and a sampled frame interval.
|
||||
// Keep a finite source-age limit; repeated metadata must never extend it.
|
||||
const CLOUD_PREVIEW_FRESH_MS = 5_000;
|
||||
export function previewFreshness(now: () => number = () => performance.now()) {
|
||||
let sequence = 0, expires = 0, points = 0;
|
||||
return {
|
||||
@@ -17,7 +20,7 @@ export function previewFreshness(now: () => number = () => performance.now()) {
|
||||
return;
|
||||
sequence = frame.sequence!;
|
||||
points = frame.points!;
|
||||
expires = frame.age_ms === null ? 0 : now() + Math.max(0, 2000 - frame.age_ms!);
|
||||
expires = frame.age_ms === null ? 0 : now() + Math.max(0, CLOUD_PREVIEW_FRESH_MS - frame.age_ms!);
|
||||
},
|
||||
get fresh() { return sequence > 0 && now() < expires; },
|
||||
get points() { return points; },
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
export function privateCandidate(sdp: string): string {
|
||||
return sdp.split('\r\n').filter(line => {
|
||||
if (!line.startsWith('a=candidate:'))
|
||||
return true;
|
||||
const fields = line.split(' '), ip = fields[4] ?? '', parts = ip.split('.').map(Number);
|
||||
return fields[7] === 'host' && (ip.endsWith('.local') || (parts.length === 4 && parts.every(v => Number.isInteger(v) && v >= 0 && v <= 255) &&
|
||||
(parts[0] === 10 || parts[0] === 127 || (parts[0] === 192 && parts[1] === 168) || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127))));
|
||||
}).join('\r\n');
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import {useEffect,useState,type RefObject} from 'react';
|
||||
import {perform,type Sensor,type SensorTransport} from './runtime';
|
||||
import {localCameraPreview} from './localCameraPreview';
|
||||
import {privateCandidate} from './previewSignalling';
|
||||
export function useK1CameraPreview(device:Sensor,transport:SensorTransport,video:RefObject<HTMLVideoElement|null>,enabled:boolean,generation=0){
|
||||
const [state,setState]=useState({camera:'Камера: ожидаем изображение',cameraPresented:false});
|
||||
useEffect(()=>{
|
||||
const element=video.current;
|
||||
setState({camera:'Камера: ожидаем изображение',cameraPresented:false});
|
||||
if(!enabled||!element)return;
|
||||
if(transport.localPreview)return localCameraPreview(device,transport,element,setState);
|
||||
let active=true,peer:string|undefined,timer:ReturnType<typeof setInterval>|undefined,ice:ReturnType<typeof setTimeout>|undefined;
|
||||
let pc:RTCPeerConnection;
|
||||
try{pc=new RTCPeerConnection({iceServers:[]});}catch{setState({camera:'Камера: просмотр недоступен',cameraPresented:false});return;}
|
||||
const channel=pc.createDataChannel('sensor');
|
||||
pc.addTransceiver('video',{direction:'recvonly'});
|
||||
pc.ontrack=event=>{if(active){element.srcObject=new MediaStream([event.track]);void element.play().catch(()=>{});}};
|
||||
const fail=()=>{if(active)setState({camera:'Камера: восстанавливаем связь',cameraPresented:false});};
|
||||
let last=-1,progress=0,keepalive=0,retry=0,statsAt=0,statsBusy=false;
|
||||
const connect=async()=>{
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
if(pc.iceGatheringState!=='complete')await new Promise<void>((resolve,reject)=>{
|
||||
ice=setTimeout(()=>reject(Error('ICE timeout')),8000);
|
||||
pc.onicegatheringstatechange=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(ice);resolve();}};
|
||||
});
|
||||
if(!active)return;
|
||||
const answer=await perform<{peer_id:string;sdp:string;type:'answer'}>(transport,device,'offer',{media:'camera',sdp:privateCandidate(pc.localDescription!.sdp),acquisition_id:device.control?.acquisition_id});
|
||||
peer=answer.peer_id;
|
||||
if(!active){void perform(transport,device,'close-peer',{peer_id:peer}).catch(()=>{});return;}
|
||||
await pc.setRemoteDescription(answer);
|
||||
};
|
||||
pc.onconnectionstatechange=()=>{if(['failed','closed'].includes(pc.connectionState))fail();};
|
||||
timer=setInterval(()=>{
|
||||
const now=performance.now();
|
||||
if(element.readyState>=2&&element.currentTime!==last){last=element.currentTime;progress=now;}
|
||||
const fresh=progress>0&&now-progress<2000;
|
||||
setState(previous=>previous.cameraPresented===fresh?previous:{camera:fresh?'Камера: изображение поступает':'Камера: нет свежих кадров',cameraPresented:fresh});
|
||||
if(channel.readyState==='open'&&now-keepalive>5000){channel.send('keepalive');keepalive=now;}
|
||||
if(pc.connectionState==='failed'&&retry++===0)fail();
|
||||
if(!statsBusy&&now-statsAt>=2000){statsAt=now;statsBusy=true;void pc.getStats().then(stats=>{
|
||||
if(!active)return;
|
||||
stats.forEach(row=>{if(row.type==='inbound-rtp'&&row.kind==='video')element.dataset.k1Preview=JSON.stringify({timestamp:row.timestamp,bytes:row.bytesReceived,frames:row.framesDecoded,dropped:row.framesDropped,fps:row.framesPerSecond,decode_seconds:row.totalDecodeTime,jitter_buffer_seconds:row.jitterBufferDelay,jitter_buffer_frames:row.jitterBufferEmittedCount,current_time:element.currentTime});});
|
||||
}).catch(()=>{}).finally(()=>{statsBusy=false;});}
|
||||
},500);
|
||||
void connect().catch(fail);
|
||||
return()=>{active=false;delete element.dataset.k1Preview;clearTimeout(ice);clearInterval(timer);pc.ontrack=null;pc.onconnectionstatechange=null;pc.onicegatheringstatechange=null;pc.close();element.pause();element.srcObject=null;if(peer)void perform(transport,device,'close-peer',{peer_id:peer}).catch(()=>{});};
|
||||
},[device.snapshot.context.session_id,device.control?.acquisition_id,transport,video,enabled,generation]);
|
||||
return state;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import type {SensorDetailProps} from '@mission-core/sensor-sdk';
|
||||
import {perform} from './runtime';
|
||||
import {k1ManualState} from './presentation';
|
||||
|
||||
export type ManagementOperation='info'|'projects'|'delete-projects'|'format-storage'|'usb-storage'|'usb-data'|'power-off'|'reboot';
|
||||
export interface K1Project {id:string;name:string}
|
||||
export interface ManagementResult {status:'succeeded'|'rejected'|'blocked'|'unknown';message?:string;result_code?:number;usb_mode?:'data'|'storage';storage_type?:string;projects?:K1Project[];catalog_revision?:string}
|
||||
export function useK1Management(props:SensorDetailProps) {
|
||||
const {device,enabled}=props,manual=k1ManualState(device,enabled);
|
||||
const ready=manual.connected&&!manual.active&&['connection-ready','completed'].includes(device.control?.phase??'');
|
||||
const identity=`${device.id}:${device.snapshot.context.session_id}:${device.control?.generation}`;
|
||||
const [info,setInfo]=useState<ManagementResult|null>(null),[catalog,setCatalog]=useState<ManagementResult|null>(null);
|
||||
const [busy,setBusy]=useState<ManagementOperation|null>(null),[message,setMessage]=useState('');
|
||||
const running=useRef(false),pendingInfo=useRef(false),latest=useRef(props),identityRef=useRef(identity);
|
||||
latest.current=props;identityRef.current=identity;
|
||||
async function run(operation:ManagementOperation,ids:string[]=[],catalogRevision?:string) {
|
||||
if(running.current)return;
|
||||
const current=latest.current,currentManual=k1ManualState(current.device,current.enabled);
|
||||
if(!currentManual.connected||currentManual.active||!['connection-ready','completed'].includes(current.device.control?.phase??''))return;
|
||||
running.current=true;setBusy(operation);setMessage('');
|
||||
const owner=identityRef.current;
|
||||
try {
|
||||
const result=await perform<ManagementResult>(current.transport,current.device,'management',{
|
||||
operation,operator_confirmed:!['info','projects'].includes(operation),project_ids:ids,
|
||||
catalog_revision:catalogRevision??null,
|
||||
control_generation:current.device.control?.generation,control_revision:current.device.control?.revision,
|
||||
});
|
||||
if(owner!==identityRef.current)return;
|
||||
if(result.status!=='succeeded') {
|
||||
setMessage(result.message??(result.status==='rejected'?`K1 отклонил операцию (код ${result.result_code}).`:'K1 не подтвердил результат операции.'));
|
||||
if(result.status==='unknown')setInfo(null);
|
||||
return result;
|
||||
}
|
||||
if(result.usb_mode)setInfo(result);
|
||||
if(operation==='projects')setCatalog(result);
|
||||
if(['delete-projects','format-storage'].includes(operation))setCatalog(null);
|
||||
if(operation==='power-off'||operation==='reboot')setInfo(null);
|
||||
if(!['info','projects'].includes(operation))setMessage(operation==='power-off'?'K1 подтвердил команду выключения.':operation==='reboot'?'K1 подтвердил команду перезагрузки.':'Операция завершена.');
|
||||
return result;
|
||||
} catch {
|
||||
if(owner===identityRef.current){setInfo(null);setMessage('Не получен результат с борта. Проверьте связь и обновите состояние K1.');}
|
||||
} finally {
|
||||
running.current=false;setBusy(null);void latest.current.refresh().catch(()=>{});
|
||||
if(pendingInfo.current){pendingInfo.current=false;void run('info');}
|
||||
}
|
||||
}
|
||||
useEffect(()=>{setInfo(null);setCatalog(null);setMessage('');if(ready){if(running.current)pendingInfo.current=true;else void run('info');}},[identity,ready]);
|
||||
return {ready,info,catalog,busy,message,run,canManage:ready&&!busy&&!!info,
|
||||
canSwitchToStorage:props.device.connection_mode==='bridge'};
|
||||
}
|
||||
export type K1Management=ReturnType<typeof useK1Management>;
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useEffect, useState, type RefObject } from 'react';
|
||||
import type { RerunHostFactory, LiveRerunViewer } from '@mission-core/sensor-sdk';
|
||||
import {privateCandidate} from './previewSignalling';
|
||||
import {useK1CameraPreview} from './useK1CameraPreview';
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import type { RerunHostFactory, LiveRerunViewer, SceneSettings } from '@mission-core/sensor-sdk';
|
||||
import { perform, type Sensor, type SensorTransport } from './runtime';
|
||||
import { MEDIA_PROTOCOL, previewFrames, previewRecording } from './previewFrames';
|
||||
import { previewCamera } from './previewCamera';
|
||||
import {k1ScenePatch} from './useK1SceneSettings';
|
||||
import { previewFreshness } from './previewFreshness';
|
||||
import {localPreview, type PreviewChannel} from './localPreview';
|
||||
export type PreviewStatus = {
|
||||
@@ -15,33 +17,37 @@ export type PreviewStatus = {
|
||||
points: number;
|
||||
};
|
||||
export const pendingPreview: PreviewStatus = { lidar: 'Лидар: ожидаем данные', camera: 'Камера: ожидаем изображение', retry: false, presented: false, hasScene: false, cameraPresented: false, points: 0 };
|
||||
function privateCandidate(sdp: string): string {
|
||||
return sdp.split('\r\n').filter(line => {
|
||||
if (!line.startsWith('a=candidate:'))
|
||||
return true;
|
||||
const fields = line.split(' '), ip = fields[4] ?? '', parts = ip.split('.').map(Number);
|
||||
return fields[7] === 'host' && (ip.endsWith('.local') || (parts.length === 4 && parts.every(v => Number.isInteger(v) && v >= 0 && v <= 255) &&
|
||||
(parts[0] === 10 || parts[0] === 127 || (parts[0] === 192 && parts[1] === 168) || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127))));
|
||||
}).join('\r\n');
|
||||
}
|
||||
export function useK1Preview(device: Sensor, transport: SensorTransport, createRerunHost: RerunHostFactory, spatial: RefObject<HTMLDivElement | null>, video: RefObject<HTMLVideoElement | null>, onStatus: (value: PreviewStatus) => void, generation = 0, enabled = true) {
|
||||
export function useK1Preview(device: Sensor, transport: SensorTransport, createRerunHost: RerunHostFactory, spatial: RefObject<HTMLDivElement | null>, video: RefObject<HTMLVideoElement | null>, onStatus: (value: PreviewStatus) => void, generation = 0, enabled = true, settings?:SceneSettings) {
|
||||
const cameraStatus=useK1CameraPreview(device,transport,video,enabled,generation);
|
||||
const cameraStatusRef=useRef(cameraStatus);cameraStatusRef.current=cameraStatus;
|
||||
const statusRef=useRef<PreviewStatus>(pendingPreview);
|
||||
const publish=(value:PreviewStatus)=>{statusRef.current=value;onStatus({...value,...cameraStatusRef.current});};
|
||||
useEffect(()=>{onStatus({...statusRef.current,...cameraStatus});},[cameraStatus,onStatus]);
|
||||
const localSettingsKey=transport.localPreview&&settings?JSON.stringify(k1ScenePatch(settings)):'';
|
||||
const settingsRef=useRef(settings);settingsRef.current=settings;
|
||||
const startup = useRef<{at:number;stages:Record<string,number>}>({at:performance.now(),stages:{}});
|
||||
const stamp = (name:string) => { startup.current.stages[name] ??= Math.round(performance.now()-startup.current.at); };
|
||||
const [native, setNative] = useState<LiveRerunViewer | null>(null);
|
||||
// The runtime and native channel belong to this acquisition view, not its peers.
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
startup.current={at:performance.now(),stages:{}};
|
||||
const host = createRerunHost(spatial.current!);
|
||||
void host.ready.then(async ({ viewer, mount }) => {
|
||||
if (!active)
|
||||
return;
|
||||
stamp('realm_ready_ms');
|
||||
await viewer.start(null, mount, { width: '100%', height: '100%', theme: 'dark', hide_welcome_screen: true, enable_history: false, allow_fullscreen: false,
|
||||
panel_state_overrides: { top: 'Hidden', blueprint: 'Hidden', selection: 'Hidden', time: 'Hidden' } });
|
||||
if (!active)
|
||||
return;
|
||||
for (const panel of ['top', 'blueprint', 'selection', 'time'] as const)
|
||||
viewer.override_panel_state(panel, 'hidden');
|
||||
stamp('viewer_ready_ms');
|
||||
setNative(viewer);
|
||||
}).catch(() => { if (active)
|
||||
onStatus({ ...pendingPreview, lidar: 'Визуализатор не загрузился. Обновите страницу.' }); });
|
||||
}).catch(error => { if (active) {
|
||||
console.error('K1 spatial viewer startup failed', error);
|
||||
publish({ ...pendingPreview, lidar: 'Визуализатор не загрузился. Обновите страницу.' }); } });
|
||||
return () => { active = false; setNative(null); host.dispose(); };
|
||||
}, [createRerunHost, spatial, onStatus]);
|
||||
const [view, setView] = useState<{
|
||||
@@ -60,20 +66,24 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
|
||||
useEffect(() => {
|
||||
const currentView = view?.session === device.snapshot.context.session_id && view?.acquisition === device.control?.acquisition_id;
|
||||
const paused = device.snapshot.acquisition === 'streaming'
|
||||
? {lidar:'Лидар: нет связи с БК', camera:'Камера: нет связи с БК'}
|
||||
? {lidar:'Лидар: связь с K1 не подтверждена', camera:'Камера: связь с K1 не подтверждена'}
|
||||
: ['starting','preparing'].includes(device.snapshot.acquisition)
|
||||
? {} : {lidar:'Лидар: приём завершён', camera:'Камера: изображение остановлено'};
|
||||
onStatus({...pendingPreview, hasScene:currentView ? view?.hasScene ?? false : false, ...(!enabled ? paused : {})});
|
||||
publish({...pendingPreview, hasScene:currentView ? view?.hasScene ?? false : false, ...(!enabled ? paused : {})});
|
||||
if (!native || !view || !currentView || !enabled)
|
||||
return;
|
||||
let active = true, failed = false, peerID: string | undefined;
|
||||
let receivedBatches=0,receivedBytes=0,receivedAge:number|null=null;
|
||||
const startedAt=performance.now();
|
||||
const stages:Record<string,number>={};
|
||||
const mark=(name:string)=>{stages[name]??=Math.round(performance.now()-startedAt);};
|
||||
let keepalive: ReturnType<typeof setInterval> | undefined, follow: ReturnType<typeof setInterval> | undefined, iceTimeout: ReturnType<typeof setTimeout> | undefined;
|
||||
let status = { ...pendingPreview, hasScene: view.hasScene };
|
||||
const update = (patch: Partial<PreviewStatus>) => { if (active) {
|
||||
const next = { ...status, ...patch };
|
||||
if (JSON.stringify(next) !== JSON.stringify(status)) {
|
||||
status = next;
|
||||
onStatus(status);
|
||||
publish(status);
|
||||
}
|
||||
} };
|
||||
const viewer = native, freshness = previewFreshness();
|
||||
@@ -84,39 +94,34 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
|
||||
let pc:RTCPeerConnection|null=null;
|
||||
try {if(!transport.localPreview)pc=new RTCPeerConnection({iceServers:[]});}
|
||||
catch {update({lidar:'Не удалось открыть канал просмотра',retry:false});return;}
|
||||
const local=transport.localPreview?localPreview(device,transport,{acquisition_id:device.control?.acquisition_id,view_id:view.id,after:view.recording.after},()=>fail()):null;
|
||||
let rrd:PreviewChannel|RTCDataChannel, camera:PreviewChannel|RTCDataChannel;
|
||||
const local=transport.localPreview?localPreview(device,transport,{media:'cloud',acquisition_id:device.control?.acquisition_id,view_id:view.id,after:view.recording.after,...(settingsRef.current?{settings:k1ScenePatch(settingsRef.current)}:{})},()=>fail()):null;
|
||||
let rrd:PreviewChannel|RTCDataChannel;
|
||||
try {
|
||||
rrd = local?.rrd ?? pc!.createDataChannel('rrd', { ordered: true });
|
||||
camera = local?.camera ?? pc!.createDataChannel('camera', { ordered: true });
|
||||
} catch {
|
||||
local?.close();pc?.close();
|
||||
update({lidar:'Не удалось открыть канал просмотра',camera:'Просмотр недоступен',retry:false});return;
|
||||
}
|
||||
if('binaryType' in rrd)rrd.binaryType = 'arraybuffer';
|
||||
if('binaryType' in camera)camera.binaryType = 'arraybuffer';
|
||||
const closeConnection=()=>{local?.close();pc?.close();};
|
||||
const {channel, previousRecording} = view;
|
||||
const fail = () => { if (!active || failed)
|
||||
return; failed = true; update({ lidar: 'Лидар: восстанавливаем связь', camera: 'Камера: ожидаем соединение', retry: true, presented: false, cameraPresented: false }); clearInterval(follow); clearInterval(keepalive); closeConnection(); };
|
||||
let cameraDecoded = false, cameraFailed = false, lastVideoTime = -1, lastVideoProgress = 0, seenLidar = false;
|
||||
const cameraFail = () => { cameraFailed = true; update({ camera: 'Камера: изображение недоступно', cameraPresented: false }); camera.close(); };
|
||||
let decoder = previewCamera(video.current!, () => { cameraDecoded = true; lastVideoProgress = performance.now(); }, cameraFail);
|
||||
const cameraFrames = previewFrames(payload => decoder.push(payload));
|
||||
let seenLidar = false;
|
||||
let batch: {sequence: number; lidar: Record<string, unknown>; received: number} | null = null;
|
||||
const rrdFrames = previewFrames(payload => {
|
||||
if (!batch || !channel.ready) throw new Error('Viewer unavailable');
|
||||
if (view.recording.accept(batch.sequence, payload)) {
|
||||
const age = batch.lidar.age_ms;
|
||||
receivedAge=typeof age==='number'?age+performance.now()-batch.received:null;
|
||||
freshness.receive({...batch.lidar, age_ms: typeof age === 'number' ? age + performance.now() - batch.received : age});
|
||||
}
|
||||
mark('first_rrd_accepted_ms');
|
||||
rrd.send(JSON.stringify({ack: batch.sequence}));
|
||||
batch = null;
|
||||
});
|
||||
rrd.onclose = () => { if (active && !failed)
|
||||
fail(); };
|
||||
camera.onclose = () => { if (active && !failed)
|
||||
cameraFail(); };
|
||||
rrd.onmessage = (event:{data:string|ArrayBuffer}) => {
|
||||
if (!active)
|
||||
return;
|
||||
@@ -130,44 +135,33 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
|
||||
}
|
||||
if (batch || value.type !== 'rrd-batch' || !Number.isSafeInteger(value.sequence) || value.sequence < 1 || !value.lidar)
|
||||
throw new Error('Invalid RRD batch');
|
||||
batch = {...value, received: performance.now()};
|
||||
batch = {...value, received: performance.now()};receivedBatches++;mark('first_batch_ms');
|
||||
if(receivedBatches===1)console.debug('K1 cloud first batch',JSON.stringify({view:view.id,sequence:value.sequence,lidar:value.lidar}));
|
||||
}
|
||||
else if (event.data instanceof ArrayBuffer)
|
||||
else if (event.data instanceof ArrayBuffer) {
|
||||
receivedBytes+=event.data.byteLength;
|
||||
rrdFrames.push(event.data);
|
||||
}
|
||||
}
|
||||
catch {
|
||||
catch (error) {
|
||||
console.error('K1 cloud preview rejected a native batch', error);
|
||||
fail();
|
||||
}
|
||||
};
|
||||
camera.onmessage = (event:{data:string|ArrayBuffer}) => {
|
||||
if (!active || failed)
|
||||
return;
|
||||
try {
|
||||
if (typeof event.data === 'string') {
|
||||
const metadata = JSON.parse(event.data);
|
||||
if (metadata.type !== 'camera-ready' || typeof metadata.mime !== 'string')
|
||||
throw new Error('Invalid camera metadata');
|
||||
decoder.close();
|
||||
cameraDecoded = false; cameraFailed = false; lastVideoTime = -1;
|
||||
decoder = previewCamera(video.current!, () => {cameraDecoded = true; lastVideoProgress = performance.now();}, cameraFail);
|
||||
decoder.open(metadata.mime);
|
||||
}
|
||||
else if (event.data instanceof ArrayBuffer)
|
||||
cameraFrames.push(event.data);
|
||||
}
|
||||
catch {
|
||||
cameraFail();
|
||||
}
|
||||
};
|
||||
const run = async () => {
|
||||
let lastSettings='';
|
||||
let synchronizedRecording: string | null = null;
|
||||
follow = setInterval(() => {
|
||||
if (!active || failed)
|
||||
return;
|
||||
const settingKey=JSON.stringify(settingsRef.current?k1ScenePatch(settingsRef.current):null);
|
||||
if(!local&&rrd.readyState==='open'&&settingsRef.current&&settingKey!==lastSettings){rrd.send(JSON.stringify({settings:k1ScenePatch(settingsRef.current)}));lastSettings=settingKey;}
|
||||
let presented = false;
|
||||
let nativeState:Record<string,unknown>={previousRecording};
|
||||
try {
|
||||
const id = viewer.get_active_recording_id();
|
||||
const range = id ? viewer.get_time_range(id, 'stream_time') : null;
|
||||
nativeState={...nativeState,recording:id,range};
|
||||
if (id && range) {
|
||||
if (synchronizedRecording !== id) {
|
||||
viewer.set_active_timeline(id, 'stream_time');
|
||||
@@ -176,24 +170,24 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
|
||||
}
|
||||
// Following is owned by the live blueprint. SetTime/SetPlaying would
|
||||
// pin the cursor and override that profile on every heartbeat.
|
||||
presented = id !== previousRecording && freshness.fresh && range.max > range.min;
|
||||
const hasData = id !== previousRecording && range.max > range.min && freshness.points > 0;
|
||||
// A delayed first frame is still a scene. Keep the live
|
||||
// badge age-gated without hiding valid received geometry.
|
||||
view.hasScene ||= hasData;
|
||||
presented = hasData && freshness.fresh;
|
||||
}
|
||||
}
|
||||
catch { /* Native recording/timeline creation is asynchronous. */ }
|
||||
seenLidar ||= presented;
|
||||
catch (error) { nativeState.error=String(error); /* Native recording/timeline creation is asynchronous. */ }
|
||||
if(view.hasScene)mark('first_scene_ms');
|
||||
seenLidar ||= view.hasScene;
|
||||
view.hasScene ||= presented;
|
||||
const v = video.current!;
|
||||
if (cameraDecoded && v.currentTime !== lastVideoTime) {
|
||||
lastVideoTime = v.currentTime;
|
||||
lastVideoProgress = performance.now();
|
||||
}
|
||||
const cameraPresented = cameraDecoded && !cameraFailed && performance.now() - lastVideoProgress < 2000;
|
||||
update({ presented, hasScene: view.hasScene, cameraPresented, points: presented ? freshness.points : 0,
|
||||
lidar: presented ? 'Лидар: данные поступают' : seenLidar ? 'Лидар: нет свежих данных' : 'Лидар: ожидаем данные',
|
||||
camera: cameraFailed ? 'Камера: изображение недоступно' : cameraPresented ? 'Камера: изображение поступает' : cameraDecoded ? 'Камера: нет свежих кадров' : 'Камера: ожидаем изображение' });
|
||||
update({ presented, hasScene: view.hasScene, points: presented ? freshness.points : 0,
|
||||
lidar: presented ? 'Лидар: данные поступают' : seenLidar ? 'Лидар: нет свежих данных' : 'Лидар: ожидаем данные' });
|
||||
if(spatial.current)spatial.current.dataset.k1Preview=JSON.stringify({view:view.id,elapsed_ms:Math.round(performance.now()-startedAt),batches:receivedBatches,bytes:receivedBytes,source_age_ms:receivedAge,points:freshness.points,presented,hasScene:view.hasScene,native:nativeState,startup:startup.current.stages,stages});
|
||||
}, 250);
|
||||
if(local){await local.start();return;}
|
||||
if(!pc)return;
|
||||
mark('offer_started_ms');
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
if (pc.iceGatheringState !== 'complete')
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@@ -205,12 +199,14 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
|
||||
});
|
||||
if (!active)
|
||||
return;
|
||||
mark('ice_ready_ms');
|
||||
const answer = await perform<{
|
||||
peer_id: string;
|
||||
sdp: string;
|
||||
type: 'answer';
|
||||
media_protocol: string;
|
||||
}>(transport, device, 'offer', { sdp: privateCandidate(pc.localDescription!.sdp), acquisition_id: device.control?.acquisition_id, view_id: view.id, after: view.recording.after });
|
||||
}>(transport, device, 'offer', { sdp: privateCandidate(pc.localDescription!.sdp), acquisition_id: device.control?.acquisition_id, view_id: view.id, after: view.recording.after, ...(settingsRef.current?{settings:k1ScenePatch(settingsRef.current)}:{}) });
|
||||
mark('answer_received_ms');
|
||||
peerID = answer.peer_id;
|
||||
if (!active) {
|
||||
void perform(transport, device, 'close-peer', { peer_id: peerID }).catch(() => { });
|
||||
@@ -223,30 +219,28 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
|
||||
update({ lidar: 'Для просмотра требуется обновление приложения на БК', camera: 'Камера: ожидаем обновление', retry: false });
|
||||
return;
|
||||
}
|
||||
pc.onconnectionstatechange = () => { if (active && ['failed', 'closed'].includes(pc?.connectionState ?? 'closed'))
|
||||
pc.onconnectionstatechange = () => { if(pc?.connectionState==='connected')mark('connected_ms'); console.debug('K1 cloud peer state', JSON.stringify({view:view.id,peer:peerID,state:pc?.connectionState,batches:receivedBatches,bytes:receivedBytes}));if (active && ['failed', 'closed'].includes(pc?.connectionState ?? 'closed'))
|
||||
fail(); };
|
||||
await pc.setRemoteDescription({ type: answer.type, sdp: answer.sdp });
|
||||
keepalive = setInterval(() => { for (const c of [rrd, camera])
|
||||
keepalive = setInterval(() => { for (const c of [rrd])
|
||||
if (c.readyState === 'open')
|
||||
c.send('keepalive'); }, 5000);
|
||||
};
|
||||
void run().catch(fail);
|
||||
void run().catch(error => { console.error('K1 cloud preview connection failed', error); fail(); });
|
||||
return () => {
|
||||
active = false;
|
||||
if(spatial.current)delete spatial.current.dataset.k1Preview;
|
||||
clearInterval(keepalive);
|
||||
clearInterval(follow);
|
||||
clearTimeout(iceTimeout);
|
||||
rrd.onmessage = null;
|
||||
camera.onmessage = null;
|
||||
camera.onclose = null;
|
||||
rrd.onclose = null;
|
||||
if(pc){pc.onconnectionstatechange = null;pc.onicegatheringstatechange = null;}
|
||||
closeConnection();
|
||||
rrdFrames.close();
|
||||
cameraFrames.close();
|
||||
decoder.close();
|
||||
if (peerID)
|
||||
void perform(transport, device, 'close-peer', { peer_id: peerID }).catch(() => { });
|
||||
};
|
||||
}, [native, view, device.snapshot.context.session_id, device.control?.acquisition_id, transport, onStatus, video, generation, enabled]);
|
||||
}, [native, view, device.snapshot.context.session_id, device.control?.acquisition_id, transport, onStatus, video, generation, enabled,localSettingsKey]);
|
||||
return native;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { defaultSceneSettings, type SceneSettings } from '@mission-core/sensor-sdk';
|
||||
import { defaultSceneSettings, type SceneSettings, type SensorDetailProps } from '@mission-core/sensor-sdk';
|
||||
import { perform, type Sensor, type SensorTransport } from './runtime';
|
||||
const fields = { pointSize: 'point_size', accumulationSeconds: 'accumulation_seconds', colorMode: 'color_mode', palette: 'palette', customColor: 'custom_color', showPoints: 'show_points', showTrajectory: 'show_trajectory', showGrid: 'show_grid' } as const;
|
||||
export function k1SceneSettings(value: Record<string, unknown> = {}): SceneSettings {
|
||||
@@ -13,9 +13,14 @@ export function k1ScenePatch(settings: SceneSettings) {
|
||||
return Object.fromEntries(Object.entries(fields).map(([key, field]) => [field, settings[key as keyof typeof fields]]));
|
||||
}
|
||||
/** One serialized autosave owner. Scene changes never issue physical commands. */
|
||||
export function useK1SceneSettings(device: Sensor, transport: SensorTransport, failure: (error: unknown) => void) {
|
||||
const [draft, setDraft] = useState(() => k1SceneSettings(device.live_settings));
|
||||
export function useK1SceneSettings(device: Sensor, transport: SensorTransport, failure: (error: unknown) => void, profile?: SensorDetailProps['sceneProfile']) {
|
||||
const [draft, setDraft] = useState(() => profile?.settings ?? k1SceneSettings(device.live_settings));
|
||||
const current = useRef(draft), dirty = useRef(false), running = useRef(false), queued = useRef(false), active = useRef(true);
|
||||
const external=profile?.settings ?? k1SceneSettings(device.live_settings);
|
||||
const externalKey=JSON.stringify(external);
|
||||
useEffect(()=>{if(!dirty.current&&!running.current){current.current=external;setDraft(external);}},[externalKey]);
|
||||
const saveRef=useRef(profile?.save);saveRef.current=profile?.save;
|
||||
useEffect(()=>()=>{if(dirty.current&&saveRef.current)saveRef.current(current.current);},[]);
|
||||
const [pending, setPending] = useState(false);
|
||||
useEffect(() => { active.current = true; return () => { active.current = false; queued.current = false; }; }, []);
|
||||
const stage = (patch: Partial<SceneSettings>) => { current.current = { ...current.current, ...patch }; dirty.current = true; setDraft(current.current); };
|
||||
@@ -32,7 +37,8 @@ export function useK1SceneSettings(device: Sensor, transport: SensorTransport, f
|
||||
queued.current = false;
|
||||
dirty.current = false;
|
||||
const settings = k1ScenePatch(current.current);
|
||||
await perform(transport, device, 'option', { profile: 'live-acquisition', settings });
|
||||
if(saveRef.current)saveRef.current({...current.current});
|
||||
else await perform(transport, device, 'option', { profile: 'live-acquisition', settings });
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
|
||||
@@ -22,7 +22,7 @@ from credential_install import PROFILE_ID, validate # noqa: E402
|
||||
from debian import package # noqa: E402
|
||||
from runtime_payload import files as runtime_files # noqa: E402
|
||||
|
||||
VERSION = "0.1.16"
|
||||
VERSION = "0.1.43"
|
||||
RESOURCES = (
|
||||
"plugins/xgrids-k1/profile_loader.py",
|
||||
"plugins/xgrids-k1/plugin.manifest.json",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"src/k1link/device_plugins/xgrids_k1/connection_attempt.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/connection_supervisor.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/device_identity_pin_store.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/device_management.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/facade.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/firmware_credential.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/host_diagnostics.py",
|
||||
@@ -36,6 +37,7 @@
|
||||
"src/k1link/device_plugins/xgrids_k1/network_provisioning_idempotency_journal.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/node_bridge.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/node_sensor.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/node_usb.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/physical_command_coordinator.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/physical_command_ledger.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/__init__.py",
|
||||
@@ -48,6 +50,8 @@
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/application_session.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/calibration_file.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/calibration_mqtt.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/device_management.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/management_mailbox.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/modeling.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/modeling_control.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/modeling_safety.py",
|
||||
@@ -56,6 +60,7 @@
|
||||
"src/k1link/device_plugins/xgrids_k1/protocol/streams.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/quick_connect_profile.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/semantic_topology_store.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/usb_network.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/viewer/__init__.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/viewer/messages.py",
|
||||
"src/k1link/device_plugins/xgrids_k1/viewer/replay.py",
|
||||
@@ -83,6 +88,7 @@
|
||||
"src/k1link/sessions/store.py",
|
||||
"src/k1link/viewer/__init__.py",
|
||||
"src/k1link/viewer/metrics.py",
|
||||
"src/k1link/viewer/node_camera.py",
|
||||
"src/k1link/viewer/node_local_media.py",
|
||||
"src/k1link/viewer/node_media.py",
|
||||
"src/k1link/viewer/node_rerun.py",
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
{ "id": "state.read", "mutating": false, "secretFields": [] },
|
||||
{ "id": "discovery.scan", "mutating": false, "secretFields": [] },
|
||||
{ "id": "device.inspect", "mutating": false, "secretFields": [] },
|
||||
{ "id": "device.manage", "mutating": true, "secretFields": [] },
|
||||
{ "id": "sensor.catalog.read", "mutating": false, "secretFields": [] },
|
||||
{ "id": "calibration.device-snapshot.read", "mutating": false, "secretFields": [] },
|
||||
{ "id": "network.provision", "mutating": true, "secretFields": ["password"] },
|
||||
|
||||
@@ -164,6 +164,14 @@ def _validate_connection_modes(scope: dict[str, Any]) -> None:
|
||||
"acceptance": "prepared-macos-host-physical-accepted",
|
||||
},
|
||||
}
|
||||
expected["usb"] = {
|
||||
'topology': 'usb-ethernet',
|
||||
'direction': 'k1-usb-ethernet-to-board',
|
||||
'device_network_action': 'none',
|
||||
'host_network_action': 'existing-os-rndis-dhcp',
|
||||
'target_address_policy': 'usb-dhcp-peer-and-exact-kernel-route',
|
||||
'acceptance': 'firmware-3.0.2-physical-transport-qualified',
|
||||
}
|
||||
if set(modes) != set(expected):
|
||||
raise CompatibilityProfileError("connection mode set differs from reviewed evidence")
|
||||
for mode_id, expected_fields in expected.items():
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"version": "3.0.2"
|
||||
},
|
||||
"topology": "local-network-matrix",
|
||||
"claim_limit": "One owner-controlled K1 on exact firmware 3.0.2. Bridge/Mission Core is physically accepted. Quick Connect AP activation and association are accepted only on one prepared macOS host with a preinstalled firmware provider; clean-host bootstrap is not implemented. Direct Connect reuses the physically accepted 99-byte BLE Wi-Fi frame but still requires its own Mission Core physical acceptance. This is not a vendor API or a cross-firmware compatibility claim.",
|
||||
"claim_limit": "One owner-controlled K1 on exact firmware 3.0.2. Bridge/Mission Core is physically accepted. Quick Connect AP activation and association are accepted only on one prepared macOS host with a preinstalled firmware provider; clean-host bootstrap is not implemented. Direct Connect reuses the physically accepted 99-byte BLE Wi-Fi frame but still requires its own Mission Core physical acceptance. This is not a vendor API or a cross-firmware compatibility claim. USB Ethernet START, point/pose capture, camera and STOP were physically qualified on Ubuntu with one K1 FW 3.0.2; hotplug and product UI acceptance are separate gates.",
|
||||
"connection_modes": [
|
||||
{
|
||||
"id": "bridge",
|
||||
@@ -39,6 +39,15 @@
|
||||
"host_network_action": "exact-firmware-provider-and-single-corewlan-association",
|
||||
"target_address_policy": "reviewed-fixed-k1-ap-private-ipv4",
|
||||
"acceptance": "prepared-macos-host-physical-accepted"
|
||||
},
|
||||
{
|
||||
"id": "usb",
|
||||
"topology": "usb-ethernet",
|
||||
"direction": "k1-usb-ethernet-to-board",
|
||||
"device_network_action": "none",
|
||||
"host_network_action": "existing-os-rndis-dhcp",
|
||||
"target_address_policy": "usb-dhcp-peer-and-exact-kernel-route",
|
||||
"acceptance": "firmware-3.0.2-physical-transport-qualified"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -67,6 +67,7 @@ ActiveAcquisitionRecoveryConnectionMode = Literal[
|
||||
"bridge",
|
||||
"quick-connect",
|
||||
"direct-connect",
|
||||
"usb",
|
||||
]
|
||||
ActiveAcquisitionRecoveryEvidencePolicy = Literal["required", "best-effort", "disabled"]
|
||||
ActiveAcquisitionRecoveryMountType = Literal["handheld"]
|
||||
@@ -120,7 +121,7 @@ ActiveAcquisitionRecoveryTransitionKind = Literal[
|
||||
]
|
||||
|
||||
_CHECKPOINT_STATES = frozenset({"prepared", "active", "ceased"})
|
||||
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
|
||||
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
|
||||
_EVIDENCE_POLICIES = frozenset({"required", "best-effort", "disabled"})
|
||||
_MOUNT_TYPES = frozenset({"handheld"})
|
||||
_GNSS_MODES = frozenset({"none"})
|
||||
|
||||
@@ -112,7 +112,7 @@ def _network_attempt_matches_live_control_authority(
|
||||
and isinstance(transport_ref, str)
|
||||
and transport_ref
|
||||
and context.get("transport_ref") == transport_ref
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and context.get("connection_mode") == connection_mode
|
||||
and isinstance(target_ipv4, str)
|
||||
and target_ipv4
|
||||
@@ -187,7 +187,7 @@ def _owned_control_bootstrap_matches_network_attempt(
|
||||
and network_result.get("parent_intent_id") == network_operation_id
|
||||
and isinstance(transport_ref, str)
|
||||
and transport_ref
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and isinstance(target_ipv4, str)
|
||||
and target_ipv4
|
||||
and target_port == CONTROL_MQTT_PORT
|
||||
@@ -252,7 +252,7 @@ def _recovery_verify_matches_network_attempt(
|
||||
and network_result.get("parent_intent_id") == network_operation_id
|
||||
and isinstance(transport_ref, str)
|
||||
and transport_ref
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and isinstance(target_ipv4, str)
|
||||
and target_ipv4
|
||||
and target_port == CONTROL_MQTT_PORT
|
||||
|
||||
@@ -16,7 +16,7 @@ from k1link.device_plugins.xgrids_k1.host_diagnostics import (
|
||||
host_diagnostics_for_reasons,
|
||||
)
|
||||
|
||||
ConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
|
||||
ConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
|
||||
RouteClass = Literal["direct", "default", "tunnel", "unavailable", "unknown"]
|
||||
TcpState = Literal["unknown", "reachable", "unreachable"]
|
||||
IdentityState = Literal["unverified", "verified", "stale", "mismatch"]
|
||||
@@ -27,6 +27,7 @@ DeviceNetworkSource = Literal[
|
||||
"ble-post-write-status",
|
||||
"ble-read-only-status",
|
||||
"durable-semantic-topology",
|
||||
"usb-enumeration",
|
||||
]
|
||||
AllowedAction = Literal[
|
||||
"select-connection-intent",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Plugin action boundary for explicit, idle-only XGRIDS maintenance."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from typing import Any, Literal, Self, cast
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from k1link.web.device_lifecycle import TERMINAL_ACQUISITION_STATES
|
||||
|
||||
ACTION_DEVICE_MANAGE = "device.manage"
|
||||
|
||||
|
||||
class DeviceManagementRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
operation_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,128}$")
|
||||
operation: Literal["info", "projects", "delete-projects", "format-storage", "usb-storage",
|
||||
"usb-data", "power-off", "reboot"]
|
||||
expected_session_generation: int = Field(ge=0)
|
||||
expected_state_revision: int = Field(ge=0)
|
||||
operator_confirmed: bool = False
|
||||
project_ids: list[str] = Field(default_factory=list, max_length=4096)
|
||||
catalog_revision: str | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_operation(self) -> Self:
|
||||
if self.operation not in {"info", "projects"} and not self.operator_confirmed:
|
||||
raise ValueError("Подтвердите операцию с K1")
|
||||
if (self.operation == "delete-projects") != bool(self.project_ids):
|
||||
raise ValueError("Выберите проекты для удаления")
|
||||
if len(set(self.project_ids)) != len(self.project_ids):
|
||||
raise ValueError("Проекты повторяются в выборе")
|
||||
return self
|
||||
|
||||
|
||||
def manage_device(service: Any, request: DeviceManagementRequest) -> dict[str, object]:
|
||||
with service._lock:
|
||||
acquisition = service._acquisition
|
||||
if acquisition is not None and acquisition.state not in TERMINAL_ACQUISITION_STATES:
|
||||
raise ValueError("Сначала завершите съёмку K1")
|
||||
device_id, session_id = service._device_id, service._device_session_id
|
||||
fingerprint = hashlib.sha256(request.model_dump_json().encode()).hexdigest()
|
||||
record, created = service._operations.begin(
|
||||
ACTION_DEVICE_MANAGE, operation_id=request.operation_id,
|
||||
idempotency_key=request.operation_id, device_id=device_id, device_session_id=session_id,
|
||||
deadline_seconds=30, request_fingerprint=fingerprint,
|
||||
)
|
||||
if not created:
|
||||
return cast(dict[str, object], record.result) if record.result else {
|
||||
"status": "unknown", "message": "Операция уже была принята",
|
||||
}
|
||||
try:
|
||||
result = service._application_control_session.manage_device(
|
||||
operation=request.operation, identifier=request.operation_id,
|
||||
project_ids=tuple(request.project_ids), catalog_revision=request.catalog_revision,
|
||||
expected_session_generation=request.expected_session_generation,
|
||||
expected_state_revision=request.expected_state_revision,
|
||||
)
|
||||
except ValueError as exc:
|
||||
result = {"status": "blocked", "message": str(exc)}
|
||||
except Exception:
|
||||
result = {"status": "unknown", "message": "K1 не подтвердил результат операции"}
|
||||
service._operations.transition(
|
||||
record.operation_id, "succeeded" if result["status"] == "succeeded" else "failed",
|
||||
stage_code="device-management", message_code="device.management." + result["status"],
|
||||
result=result,
|
||||
)
|
||||
return cast(dict[str, object], result)
|
||||
@@ -19,14 +19,14 @@ import unicodedata
|
||||
from collections.abc import Awaitable, Callable, Collection, Iterator, Mapping, Sequence
|
||||
from concurrent.futures import Future as ConcurrentFuture
|
||||
from concurrent.futures import TimeoutError as ConcurrentFutureTimeout
|
||||
from contextlib import AbstractContextManager, ExitStack, contextmanager, suppress
|
||||
from contextlib import AbstractContextManager, ExitStack, contextmanager, nullcontext, suppress
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import replace as dataclass_replace
|
||||
from datetime import UTC, datetime
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
from typing import Any, Concatenate, Literal, Protocol, Self, cast
|
||||
from uuid import uuid4
|
||||
from uuid import NAMESPACE_URL, uuid4, uuid5
|
||||
|
||||
from bleak.exc import BleakDeviceNotFoundError, BleakError
|
||||
from missioncore_plugin_sdk.v0alpha2 import (
|
||||
@@ -144,6 +144,11 @@ from k1link.device_plugins.xgrids_k1.device_identity_pin_store import (
|
||||
DeviceIdentityPinStoreCorrupt,
|
||||
DeviceIdentityPinStoreError,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.device_management import (
|
||||
ACTION_DEVICE_MANAGE,
|
||||
DeviceManagementRequest,
|
||||
manage_device,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.firmware_credential import (
|
||||
K1_FW302_CREDENTIAL_PROVIDER_ID,
|
||||
)
|
||||
@@ -263,6 +268,8 @@ from k1link.web.plugin_runtime import (
|
||||
PluginExecutionError,
|
||||
)
|
||||
|
||||
from .usb_network import LinuxK1UsbProbe, UsbNetworkAttachment
|
||||
|
||||
XGRIDS_K1_PLUGIN_ID = "nodedc.device.xgrids-lixelkity-k1"
|
||||
XGRIDS_K1_PLUGIN_VERSION = "0.7.5"
|
||||
XGRIDS_K1_MODEL_ID = "xgrids.lixelkity-k1"
|
||||
@@ -332,12 +339,13 @@ def _capture_network_intent_device(
|
||||
return capture_discovered_device(macos_uuid)
|
||||
|
||||
|
||||
ConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
|
||||
ConnectionTopology = Literal["direct-lan", "device-ap", "controller-hotspot"]
|
||||
ConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
|
||||
ConnectionTopology = Literal["direct-lan", "device-ap", "controller-hotspot", "usb-ethernet"]
|
||||
CONNECTION_TOPOLOGY_BY_MODE: dict[ConnectionMode, ConnectionTopology] = {
|
||||
"bridge": "direct-lan",
|
||||
"quick-connect": "device-ap",
|
||||
"direct-connect": "controller-hotspot",
|
||||
"usb": "usb-ethernet",
|
||||
}
|
||||
|
||||
|
||||
@@ -424,6 +432,7 @@ class ConfiguredEndpointProbeError(RuntimeError):
|
||||
|
||||
|
||||
ACTION_STATE_READ = "state.read"
|
||||
|
||||
ACTION_DISCOVERY_SCAN = "discovery.scan"
|
||||
ACTION_DEVICE_INSPECT = "device.inspect"
|
||||
ACTION_SENSOR_CATALOG_READ = "sensor.catalog.read"
|
||||
@@ -1030,7 +1039,7 @@ class ConnectRequest(StrictRequest):
|
||||
device_id: str = Field(min_length=1, max_length=128)
|
||||
ssid: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
password: SecretStr | None = Field(default=None, min_length=1, max_length=256)
|
||||
connection_mode: ConnectionMode = "bridge"
|
||||
connection_mode: Literal["bridge", "quick-connect", "direct-connect"] = "bridge"
|
||||
compatibility_attestation: CompatibilityAttestationRequest
|
||||
operation_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
idempotency_key: str = Field(min_length=16, max_length=160)
|
||||
@@ -1077,9 +1086,9 @@ class ConnectionVerifyRequest(StrictRequest):
|
||||
# the service resolves that form only from its current/durable exact
|
||||
# target. New clients send the complete server-issued target contract.
|
||||
device_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
source: Literal["fresh-scan", "retained-current-process", "durable-configured-state"] = (
|
||||
"fresh-scan"
|
||||
)
|
||||
source: Literal[
|
||||
"fresh-scan", "retained-current-process", "durable-configured-state", "usb-enumeration"
|
||||
] = "fresh-scan"
|
||||
compatibility_attestation: CompatibilityAttestationRequest | None = None
|
||||
operation_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
# New clients bind Verify to the exact mode draft rendered at the click.
|
||||
@@ -1239,12 +1248,13 @@ class _ProvisionalFreshBridgeTopology:
|
||||
discovery_generation: int
|
||||
device_session_id: str
|
||||
transport_ref: str
|
||||
connection_mode: Literal["bridge"]
|
||||
connection_mode: Literal["bridge", "usb"]
|
||||
ipv4: str
|
||||
firmware_version: str
|
||||
observed_at_utc: str
|
||||
semantic_predecessor_revision: int
|
||||
|
||||
usb_generation: str | None = None
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _ScenarioResetRetiredTransportAuthority:
|
||||
@@ -1395,7 +1405,7 @@ class ViewerSettingsRequest(StrictRequest):
|
||||
color_mode: Literal["intensity", "height", "distance", "rgb", "class"] = "intensity"
|
||||
palette: Literal["turbo", "viridis", "plasma", "grayscale", "custom"] = "turbo"
|
||||
custom_color: str = Field(default="#f7f8f4", pattern=r"^#[0-9A-Fa-f]{6}$")
|
||||
accumulation_seconds: float = Field(default=12.0, ge=0.0, le=120.0)
|
||||
accumulation_seconds: float = Field(default=12.0, ge=0.0, allow_inf_nan=False)
|
||||
show_points: bool = True
|
||||
show_trajectory: bool = True
|
||||
show_grid: bool = True
|
||||
@@ -1476,6 +1486,7 @@ class XgridsK1CompatibilityService:
|
||||
application_authority_loader: ApplicationAuthorityLoader | None = None,
|
||||
calibration_snapshot_reader: DeviceCalibrationSnapshotReader | None = None,
|
||||
host_wifi_association_probe: HostWifiAssociationProbe | None = None,
|
||||
usb_network_probe: LinuxK1UsbProbe | None = None,
|
||||
visualization_bridge_factory: Callable[..., Any] | None = None,
|
||||
) -> None:
|
||||
self.repository_root = repository_root.resolve()
|
||||
@@ -1486,6 +1497,7 @@ class XgridsK1CompatibilityService:
|
||||
# network/control lifecycle owner.
|
||||
configure_ble_runtime_process_lease(self.repository_root)
|
||||
self.evidence_root = resolve_missioncore_evidence_dir(self.repository_root)
|
||||
self._usb_network_probe = usb_network_probe
|
||||
self._host_wifi_association_probe = (
|
||||
host_wifi_association_probe
|
||||
or HostWifiAssociationIdentityProbe(
|
||||
@@ -2163,7 +2175,9 @@ class XgridsK1CompatibilityService:
|
||||
and topology_record is not None
|
||||
and topology_record.transport_ref == transport_ref
|
||||
and topology_record.connection_mode == connection_mode
|
||||
and topology_record.source in {"ble-post-write-status", "ble-read-only-status"}
|
||||
and topology_record.source in {
|
||||
"ble-post-write-status", "ble-read-only-status", "usb-enumeration"
|
||||
}
|
||||
and ledger_record.last_observation.ipv4 == topology_record.ipv4
|
||||
and topology_record.compatibility_profile_id == XGRIDS_K1_COMPATIBILITY_PROFILE_ID
|
||||
):
|
||||
@@ -2259,7 +2273,7 @@ class XgridsK1CompatibilityService:
|
||||
ipv4: str,
|
||||
compatibility_attestation: CompatibilityAttestationRequest,
|
||||
captured_device: CapturedDiscoveredDevice | None,
|
||||
source: Literal["ble-post-write-status", "ble-read-only-status"],
|
||||
source: Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"],
|
||||
observed_at_utc: str,
|
||||
) -> str | None:
|
||||
"""Commit what the K1 reported, independently from the Mac route.
|
||||
@@ -2311,6 +2325,7 @@ class XgridsK1CompatibilityService:
|
||||
"ble-post-write-status",
|
||||
"ble-read-only-status",
|
||||
"durable-semantic-topology",
|
||||
"usb-enumeration",
|
||||
],
|
||||
observed_at_utc: str,
|
||||
force_new_session: bool,
|
||||
@@ -2387,7 +2402,8 @@ class XgridsK1CompatibilityService:
|
||||
self._connection_mode = connection_mode
|
||||
self._device_id = self._device_ids_by_transport_ref.setdefault(
|
||||
transport_ref,
|
||||
new_device_id(),
|
||||
(f"device-{uuid5(NAMESPACE_URL, 'xgrids-k1:' + transport_ref)}"
|
||||
if connection_mode == "usb" else new_device_id()),
|
||||
)
|
||||
self._device_session_id = next_device_session_id
|
||||
self._device_session_opened_at = observed_at_utc
|
||||
@@ -2433,7 +2449,7 @@ class XgridsK1CompatibilityService:
|
||||
connection_mode: ConnectionMode,
|
||||
ipv4: str,
|
||||
firmware_version: str,
|
||||
source: Literal["ble-post-write-status", "ble-read-only-status"],
|
||||
source: Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"],
|
||||
observed_at_utc: str,
|
||||
predecessor_revision: int | None = None,
|
||||
) -> None:
|
||||
@@ -2557,6 +2573,27 @@ class XgridsK1CompatibilityService:
|
||||
"""Bind one kernel route sample to this service's Wi-Fi association."""
|
||||
|
||||
path = _inspect_host_path(target)
|
||||
with self._lock:
|
||||
usb_transport = self._selected_device_id if self._connection_mode == "usb" else None
|
||||
if usb_transport is not None:
|
||||
try:
|
||||
attachment = self._require_usb_attachment(usb_transport)
|
||||
if (attachment.peer_ipv4 != target or attachment.interface != path.interface
|
||||
or attachment.source_ipv4 != path.source_ipv4):
|
||||
raise OSError("USB route changed")
|
||||
except OSError:
|
||||
return HostPathProbeResult(
|
||||
available=False, fingerprint=None, interface=path.interface,
|
||||
source_ipv4=path.source_ipv4, route_class="unavailable",
|
||||
reason_code="usb-attachment-unavailable",
|
||||
)
|
||||
if path.available and path.fingerprint is not None:
|
||||
return dataclass_replace(
|
||||
path, fingerprint=hashlib.sha256(
|
||||
(path.fingerprint + ":" + attachment.generation).encode()
|
||||
).hexdigest(),
|
||||
)
|
||||
return path
|
||||
association = self._host_wifi_association_probe.observe(
|
||||
path.interface,
|
||||
timeout_seconds=association_timeout_seconds,
|
||||
@@ -2572,14 +2609,19 @@ class XgridsK1CompatibilityService:
|
||||
if retained_unproven_path is not None:
|
||||
return retained_unproven_path
|
||||
if (
|
||||
fail_closed_unproven_association
|
||||
and not association["continuity_proven"]
|
||||
# Missing BSSID is a documented macOS privacy condition. Its
|
||||
# process-scoped fallback token still detects route/interface
|
||||
# transitions. The monitor marks that result as unproven below so
|
||||
# it cannot replace a verified association fingerprint merely
|
||||
# because macOS changed what identity fields it disclosed.
|
||||
and association_reason != "association-identity-unavailable"
|
||||
not association["continuity_proven"]
|
||||
and (
|
||||
# Linux supplies no fallback token when NetworkManager cannot
|
||||
# prove association. Report unavailable even during bootstrap;
|
||||
# an empty token cannot be bound to a route fingerprint.
|
||||
association["adapter"] == "linux-networkmanager"
|
||||
or (
|
||||
fail_closed_unproven_association
|
||||
# macOS privacy-limited observations have a process-scoped
|
||||
# fallback token. Preserve their existing continuity policy.
|
||||
and association_reason != "association-identity-unavailable"
|
||||
)
|
||||
)
|
||||
):
|
||||
return HostPathProbeResult(
|
||||
available=False,
|
||||
@@ -3066,6 +3108,7 @@ class XgridsK1CompatibilityService:
|
||||
semantic_predecessor_revision: int | None = None,
|
||||
force_new_intent: bool = False,
|
||||
persist_semantic_topology: bool = True,
|
||||
source: Literal["ble-read-only-status", "usb-enumeration"] = "ble-read-only-status",
|
||||
) -> str:
|
||||
"""Bind an exact BLE status read to a fresh non-mutating intent."""
|
||||
|
||||
@@ -3081,7 +3124,7 @@ class XgridsK1CompatibilityService:
|
||||
connection_mode=connection_mode,
|
||||
ipv4=target.ipv4,
|
||||
firmware_version=firmware_version,
|
||||
source="ble-read-only-status",
|
||||
source=source,
|
||||
observed_at_utc=observed_at_utc,
|
||||
predecessor_revision=semantic_predecessor_revision,
|
||||
)
|
||||
@@ -3110,7 +3153,7 @@ class XgridsK1CompatibilityService:
|
||||
transport_ref=transport_ref,
|
||||
connection_mode=connection_mode,
|
||||
target=target,
|
||||
source="ble-read-only-status",
|
||||
source=source,
|
||||
):
|
||||
raise RuntimeError("read-only статус K1 потерял актуальность до admission")
|
||||
return intent_id
|
||||
@@ -3129,6 +3172,7 @@ class XgridsK1CompatibilityService:
|
||||
force_new_intent: bool = False,
|
||||
force_new_session: bool = False,
|
||||
persist_semantic_topology: bool = True,
|
||||
source: Literal["ble-read-only-status", "usb-enumeration"] = "ble-read-only-status",
|
||||
retained_prepared_stop_owner: _PreparedStopRecoveryOwner | None = None,
|
||||
) -> str:
|
||||
"""Persist, supervise and project one exact non-mutating BLE status.
|
||||
@@ -3168,6 +3212,7 @@ class XgridsK1CompatibilityService:
|
||||
semantic_predecessor_revision=semantic_predecessor_revision,
|
||||
force_new_intent=force_new_intent,
|
||||
persist_semantic_topology=persist_semantic_topology,
|
||||
source=source,
|
||||
)
|
||||
retired_ingress_session_id = self._project_applied_device_topology(
|
||||
transport_ref=transport_ref,
|
||||
@@ -3175,7 +3220,7 @@ class XgridsK1CompatibilityService:
|
||||
target=target,
|
||||
compatibility_attestation=attestation_snapshot,
|
||||
captured_device=captured_device,
|
||||
source="ble-read-only-status",
|
||||
source=source,
|
||||
observed_at_utc=observed_at_utc,
|
||||
force_new_session=force_new_session,
|
||||
retained_prepared_stop_owner=retained_prepared_stop_owner,
|
||||
@@ -5731,7 +5776,7 @@ class XgridsK1CompatibilityService:
|
||||
provisional.reconfiguration_intent_id
|
||||
or f"fresh-verify-rejected-{provisional.device_session_id}"
|
||||
),
|
||||
requested_mode="bridge",
|
||||
requested_mode=provisional.connection_mode,
|
||||
expected_device_id=None,
|
||||
)
|
||||
with self._lock:
|
||||
@@ -5817,12 +5862,21 @@ class XgridsK1CompatibilityService:
|
||||
"DeviceInfo identity не закреплена за выбранным BLE transport",
|
||||
reason_code="device-identity-pin-mismatch",
|
||||
)
|
||||
if provisional.connection_mode == "usb":
|
||||
attachment = self._require_usb_attachment(provisional.transport_ref)
|
||||
if (attachment.generation != provisional.usb_generation
|
||||
or attachment.peer_ipv4 != provisional.ipv4):
|
||||
raise ConnectionVerificationError(
|
||||
"USB-подключение изменилось во время проверки",
|
||||
reason_code="usb-attachment-changed",
|
||||
)
|
||||
self._persist_semantic_topology(
|
||||
transport_ref=provisional.transport_ref,
|
||||
connection_mode=provisional.connection_mode,
|
||||
ipv4=provisional.ipv4,
|
||||
firmware_version=provisional.firmware_version,
|
||||
source="ble-read-only-status",
|
||||
source=("usb-enumeration" if provisional.connection_mode == "usb"
|
||||
else "ble-read-only-status"),
|
||||
observed_at_utc=provisional.observed_at_utc,
|
||||
predecessor_revision=provisional.semantic_predecessor_revision,
|
||||
)
|
||||
@@ -6385,7 +6439,9 @@ class XgridsK1CompatibilityService:
|
||||
),
|
||||
physical_recovery_mode=(
|
||||
cast(ConnectionMode, recovery_connection_mode)
|
||||
if recovery_connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
if recovery_connection_mode in {
|
||||
"bridge", "quick-connect", "direct-connect", "usb"
|
||||
}
|
||||
else None
|
||||
),
|
||||
)
|
||||
@@ -10045,7 +10101,7 @@ class XgridsK1CompatibilityService:
|
||||
and isinstance(scenario_reset_id, str)
|
||||
and isinstance(scenario_reset_revision, int)
|
||||
and scenario_reset_mode
|
||||
in {"bridge", "quick-connect", "direct-connect"}
|
||||
in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and scenario_reset_revision == self._desired_connection_mode_revision
|
||||
and scenario_reset_mode == self._desired_connection_mode
|
||||
):
|
||||
@@ -12642,6 +12698,25 @@ class XgridsK1CompatibilityService:
|
||||
|
||||
persisted = checkpoint.current_active_physical_proof
|
||||
status = checkpoint.current_active_status_proof
|
||||
# The physical READY commit may precede checkpoint cessation (including
|
||||
# a process exit between fsyncs). Reconstruct only that immediate local
|
||||
# predecessor for the existing exact reset/reopen ancestry predicate.
|
||||
# This is an in-memory proof check, never a ledger rewrite or new edge.
|
||||
reopened = record
|
||||
if (
|
||||
record.stage == "resolved"
|
||||
and record.resolution == "start-active-observed"
|
||||
and record.reconciliations
|
||||
and record.reconciliations[-1].kind == "resolved-active-cessation"
|
||||
and record.reconciliations[-1].resolution == "physical-standby-observed"
|
||||
):
|
||||
reopened = dataclass_replace(
|
||||
record,
|
||||
revision=record.revision - 1,
|
||||
stage="observing",
|
||||
resolution=None,
|
||||
reconciliations=record.reconciliations[:-1],
|
||||
)
|
||||
if not (
|
||||
persisted is not None
|
||||
and status is not None
|
||||
@@ -12653,12 +12728,11 @@ class XgridsK1CompatibilityService:
|
||||
and record.operation_id == checkpoint.original_start_operation_id
|
||||
and record.acquisition_id == checkpoint.acquisition_id
|
||||
and record.action == "start"
|
||||
and record.stage == "observing"
|
||||
and record.resolution is None
|
||||
and reopened.stage == "observing"
|
||||
and reopened.resolution is None
|
||||
and record.revision > persisted.ledger_revision
|
||||
and record.payload_sha256 == checkpoint.start_payload_sha256
|
||||
and record.reopened_resolved_start_requires_reconciliation
|
||||
and record.reconciled_physical_state == "active"
|
||||
and reopened.reopened_resolved_start_requires_reconciliation
|
||||
):
|
||||
return False
|
||||
|
||||
@@ -15913,6 +15987,7 @@ class XgridsK1CompatibilityService:
|
||||
"direct-lan": "bridge",
|
||||
"device-ap": "quick-connect",
|
||||
"controller-hotspot": "direct-connect",
|
||||
"usb-ethernet": "usb",
|
||||
}[request.compatibility_attestation.topology]
|
||||
if request.compatibility_attestation is not None
|
||||
else None
|
||||
@@ -15990,7 +16065,8 @@ class XgridsK1CompatibilityService:
|
||||
reason_code="connection-verify-control-dispatch-active",
|
||||
)
|
||||
command_dispatch_gate_acquired = True
|
||||
with self._borrow_network_ble_process_lease():
|
||||
with (nullcontext() if requested_mode == "usb"
|
||||
else self._borrow_network_ble_process_lease()):
|
||||
(
|
||||
verify_operation_id,
|
||||
verify_created,
|
||||
@@ -18152,7 +18228,7 @@ class XgridsK1CompatibilityService:
|
||||
if (
|
||||
not isinstance(transport_ref, str)
|
||||
or not transport_ref.strip()
|
||||
or connection_mode not in {"bridge", "quick-connect", "direct-connect"}
|
||||
or connection_mode not in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
):
|
||||
raise ConnectionVerificationError(
|
||||
"Физическая recovery-цель K1 отсутствует в durable ledger",
|
||||
@@ -18303,6 +18379,7 @@ class XgridsK1CompatibilityService:
|
||||
"direct-lan": "bridge",
|
||||
"device-ap": "quick-connect",
|
||||
"controller-hotspot": "direct-connect",
|
||||
"usb-ethernet": "usb",
|
||||
}[request.compatibility_attestation.topology],
|
||||
)
|
||||
self._require_connection_mode_draft_for_verify(
|
||||
@@ -18874,13 +18951,83 @@ class XgridsK1CompatibilityService:
|
||||
)
|
||||
return association, observation, supervisor_epoch_before
|
||||
|
||||
def _require_usb_attachment(self, transport_ref: str) -> UsbNetworkAttachment:
|
||||
if self._usb_network_probe is None:
|
||||
raise OSError("USB-подключение доступно только на подготовленном БК")
|
||||
return self._usb_network_probe.require(transport_ref)
|
||||
|
||||
async def _adopt_usb_connection_owned(
|
||||
self,
|
||||
transport_ref: str,
|
||||
attestation: CompatibilityAttestationRequest,
|
||||
*,
|
||||
retained_prepared_stop_owner: _PreparedStopRecoveryOwner | None,
|
||||
) -> tuple[str, _ProvisionalFreshBridgeTopology]:
|
||||
"""Supply topology to the existing Verify/DeviceInfo/recovery transaction.
|
||||
|
||||
Caller owns lifecycle, dispatch, provisioning and process gates and has
|
||||
checked active receiver/STOP ownership. No BLE or network write occurs.
|
||||
DHCP is provisional; the common commit still requires the identity pin.
|
||||
"""
|
||||
if self._network_mutation_ledger.snapshot().status in {"corrupt", "unresolved"}:
|
||||
raise ConnectionVerificationError(
|
||||
"Предыдущая настройка сети K1 требует завершения",
|
||||
reason_code="usb-network-reconciliation-required",
|
||||
)
|
||||
self._require_semantic_topology_store_writable()
|
||||
assert self._semantic_topology_store is not None
|
||||
semantic = self._semantic_topology_store.snapshot()
|
||||
attachment = await _run_blocking_operation_without_abandonment(
|
||||
self._require_usb_attachment, transport_ref,
|
||||
)
|
||||
self._retire_application_control_for_network_change(allow_terminal_failure=True)
|
||||
observed_at = _utc_now_iso()
|
||||
intent_id = self._apply_read_only_device_topology(
|
||||
transport_ref=transport_ref, connection_mode="usb",
|
||||
ipv4=attachment.peer_ipv4, firmware_version=attestation.firmware_version,
|
||||
compatibility_attestation=_attestation_snapshot(attestation),
|
||||
observed_at_utc=observed_at, force_new_intent=True, force_new_session=True,
|
||||
persist_semantic_topology=False, source="usb-enumeration",
|
||||
retained_prepared_stop_owner=retained_prepared_stop_owner,
|
||||
)
|
||||
with self._lock:
|
||||
assert self._device_session_id is not None
|
||||
provisional = _ProvisionalFreshBridgeTopology(
|
||||
reconfiguration_intent_id=None,
|
||||
reconfiguration_revision=self._connection_reconfiguration_revision,
|
||||
supervisor_intent_id=intent_id,
|
||||
discovery_generation=self._ble_discovery_generation,
|
||||
device_session_id=self._device_session_id,
|
||||
transport_ref=transport_ref, connection_mode="usb",
|
||||
ipv4=attachment.peer_ipv4, firmware_version=attestation.firmware_version,
|
||||
observed_at_utc=observed_at,
|
||||
semantic_predecessor_revision=semantic.record.revision if semantic.record else 0,
|
||||
usb_generation=attachment.generation,
|
||||
)
|
||||
try:
|
||||
observation = await _run_blocking_operation_without_abandonment(
|
||||
self._probe_control_endpoint, attachment.peer_ipv4,
|
||||
)
|
||||
current = await _run_blocking_operation_without_abandonment(
|
||||
self._require_usb_attachment, transport_ref,
|
||||
)
|
||||
if current != attachment or not observation.reachable:
|
||||
raise ConnectionVerificationError(
|
||||
"K1 найден по USB, но управляющий канал пока недоступен",
|
||||
reason_code="usb-control-endpoint-unavailable",
|
||||
)
|
||||
except BaseException:
|
||||
self._reset_provisional_fresh_bridge_topology(provisional)
|
||||
raise
|
||||
return attachment.peer_ipv4, provisional
|
||||
|
||||
async def _adopt_existing_lan_connection(
|
||||
self,
|
||||
device_id: str,
|
||||
compatibility_attestation: CompatibilityAttestationRequest,
|
||||
*,
|
||||
verification_source: Literal[
|
||||
"fresh-scan", "retained-current-process", "durable-configured-state"
|
||||
"fresh-scan", "retained-current-process", "durable-configured-state", "usb-enumeration"
|
||||
] = "fresh-scan",
|
||||
expected_discovery_generation: int | None = None,
|
||||
expected_mode_revision: int | None = None,
|
||||
@@ -18895,6 +19042,8 @@ class XgridsK1CompatibilityService:
|
||||
requested_mode = "quick-connect"
|
||||
elif compatibility_attestation.topology == "controller-hotspot":
|
||||
requested_mode = "direct-connect"
|
||||
elif compatibility_attestation.topology == "usb-ethernet":
|
||||
requested_mode = "usb"
|
||||
else:
|
||||
raise ValueError("read-only K1 adoption received an unsupported topology")
|
||||
self._require_connection_mode_draft_for_verify(
|
||||
@@ -18991,6 +19140,13 @@ class XgridsK1CompatibilityService:
|
||||
verification_fence_active = False
|
||||
provisional_topology: _ProvisionalFreshBridgeTopology | None = None
|
||||
try:
|
||||
if requested_mode == "usb":
|
||||
return await self._adopt_usb_connection_owned(
|
||||
actual_transport_ref, compatibility_attestation,
|
||||
retained_prepared_stop_owner=(
|
||||
retained_prepared_stop_owner if retained_stop_recovery else None
|
||||
),
|
||||
)
|
||||
ledger_snapshot = self._network_mutation_ledger.snapshot()
|
||||
if (
|
||||
ledger_snapshot.status == "unresolved"
|
||||
@@ -20155,6 +20311,14 @@ class XgridsK1CompatibilityService:
|
||||
rediscover: bool,
|
||||
) -> str:
|
||||
selected_device_id, connection_mode, current_target = self._live_lan_address_context()
|
||||
if connection_mode == "usb":
|
||||
attachment = self._require_usb_attachment(selected_device_id)
|
||||
if attachment.peer_ipv4 != current_target:
|
||||
raise ConnectionVerificationError(
|
||||
"Адрес USB изменился; подтвердите подключение K1",
|
||||
reason_code="usb-attachment-changed",
|
||||
)
|
||||
return attachment.peer_ipv4
|
||||
if connection_mode == "quick-connect":
|
||||
return self._confirm_quick_connect_endpoint(
|
||||
selected_device_id,
|
||||
@@ -20216,6 +20380,14 @@ class XgridsK1CompatibilityService:
|
||||
rediscover: bool,
|
||||
) -> str:
|
||||
selected_device_id, connection_mode, current_target = self._live_lan_address_context()
|
||||
if connection_mode == "usb":
|
||||
attachment = self._require_usb_attachment(selected_device_id)
|
||||
if attachment.peer_ipv4 != current_target:
|
||||
raise ConnectionVerificationError(
|
||||
"Адрес USB изменился; подтвердите подключение K1",
|
||||
reason_code="usb-attachment-changed",
|
||||
)
|
||||
return attachment.peer_ipv4
|
||||
if connection_mode == "quick-connect":
|
||||
return await _run_blocking_operation_without_abandonment(
|
||||
self._confirm_quick_connect_endpoint,
|
||||
@@ -21905,6 +22077,9 @@ class XgridsK1CompatibilityService:
|
||||
runtime_state=runtime_state,
|
||||
)
|
||||
failure_stage = "evidence-lease-acquire"
|
||||
# Match restart rehydration: a dead writer leaves only an unlocked
|
||||
# marker. The canonical helper preserves live owners and all data.
|
||||
recover_stale_active_session_marker(out_dir.parent)
|
||||
lease = ActiveSessionLease.acquire(out_dir.parent, out_dir)
|
||||
with self._lock:
|
||||
if self._acquisition_session_lease is not None:
|
||||
@@ -23915,7 +24090,7 @@ class XgridsK1CompatibilityService:
|
||||
"control_session_id",
|
||||
)
|
||||
)
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and all(
|
||||
isinstance(values[field], int) and not isinstance(values[field], bool)
|
||||
for field in (
|
||||
@@ -24066,7 +24241,7 @@ class XgridsK1CompatibilityService:
|
||||
and isinstance(selected_device_id, str)
|
||||
and isinstance(device_id, str)
|
||||
and isinstance(device_session_id, str)
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and isinstance(target_ipv4, str)
|
||||
and control.get("state") == "scanning"
|
||||
):
|
||||
@@ -24478,7 +24653,7 @@ class XgridsK1CompatibilityService:
|
||||
and isinstance(selected_device_id, str)
|
||||
and isinstance(device_id, str)
|
||||
and isinstance(device_session_id, str)
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and isinstance(target_ipv4, str)
|
||||
and runtime_snapshot.get("source_mode") == "live"
|
||||
and (
|
||||
@@ -24552,7 +24727,7 @@ class XgridsK1CompatibilityService:
|
||||
assert isinstance(runtime_generation, int)
|
||||
assert intent is not None
|
||||
assert isinstance(selected_device_id, str)
|
||||
assert connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
assert connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
assert isinstance(target_ipv4, str)
|
||||
if prepared_stop_owner_current:
|
||||
assert prepared_stop_owner is not None
|
||||
@@ -25035,11 +25210,14 @@ class XgridsK1CompatibilityService:
|
||||
checkpoint_snapshot = store.snapshot()
|
||||
checkpoint = checkpoint_snapshot.checkpoint
|
||||
if checkpoint is not None and checkpoint.state == "ceased":
|
||||
return bool(
|
||||
owned = bool(
|
||||
checkpoint.acquisition_id == expected_acquisition_id
|
||||
and checkpoint.original_start_operation_id
|
||||
== expected_start_operation_id
|
||||
)
|
||||
if owned:
|
||||
self._set_active_acquisition_checkpoint_reason(None)
|
||||
return owned
|
||||
if not (
|
||||
checkpoint_snapshot.status in {"prepared", "active"}
|
||||
and checkpoint is not None
|
||||
@@ -27881,6 +28059,33 @@ class XgridsK1CompatibilityService:
|
||||
self._connection_loss_confirmation_count = 0
|
||||
return
|
||||
|
||||
# A short association gap can revoke the control epoch while the
|
||||
# data socket survives. Once the host path returns, negative probe
|
||||
# streaks are already zero and no MQTT disconnect wakes the receiver.
|
||||
# Hand that exact confirmed START to the existing read-only recovery;
|
||||
# never promote the old control proof into the new host epoch.
|
||||
returned_path = self._connection_supervisor.snapshot()
|
||||
verified = application_control_session.get("verified_control")
|
||||
verified_epoch = (
|
||||
verified.get("host_path_epoch") if isinstance(verified, Mapping) else None
|
||||
)
|
||||
if (
|
||||
application_control_session.get("state") == "scanning"
|
||||
and returned_path.host_path.available
|
||||
and returned_path.control_plane.reason_code == "host-path-epoch-changed"
|
||||
and isinstance(verified_epoch, int)
|
||||
and not isinstance(verified_epoch, bool)
|
||||
and 0 < verified_epoch < returned_path.host_path.epoch
|
||||
and self._request_active_stream_recovery_for_local_loss(
|
||||
"host-path-epoch-changed"
|
||||
)
|
||||
):
|
||||
with self._lock:
|
||||
self._connection_loss_signature = None
|
||||
self._connection_loss_evidence_token = None
|
||||
self._connection_loss_confirmation_count = 0
|
||||
return
|
||||
|
||||
# STOP PREPARE replaces the current successful START ledger row before
|
||||
# the transport can acquire its dispatch fence. Preserve only this
|
||||
# exact, bounded, still-undispatched owner; a terminal control state,
|
||||
@@ -30508,10 +30713,27 @@ class XgridsK1CompatibilityService:
|
||||
stop_operation_id=current_stop_operation_id,
|
||||
)
|
||||
checkpoint_snapshot_status: str | None = None
|
||||
completed_checkpoint_owned = False
|
||||
if self._active_acquisition_checkpoint is not None:
|
||||
try:
|
||||
checkpoint_snapshot_status = (
|
||||
self._active_acquisition_checkpoint.snapshot().status
|
||||
checkpoint_snapshot = self._active_acquisition_checkpoint.snapshot()
|
||||
checkpoint_snapshot_status = checkpoint_snapshot.status
|
||||
checkpoint = checkpoint_snapshot.checkpoint
|
||||
# Completed local cleanup releases operation/evidence owners.
|
||||
# A ceased journal for this same completed acquisition remains
|
||||
# terminal proof; it grants no recovery or command authority.
|
||||
completed_checkpoint_owned = bool(
|
||||
current is not None
|
||||
and current.state == "completed"
|
||||
and checkpoint_snapshot_status == "ceased"
|
||||
and checkpoint is not None
|
||||
and checkpoint.acquisition_id == current.acquisition_id
|
||||
and (
|
||||
canonical_start_operation_id is None
|
||||
or checkpoint.original_start_operation_id
|
||||
== canonical_start_operation_id
|
||||
)
|
||||
and self._active_acquisition_checkpoint_trust == "trusted"
|
||||
)
|
||||
except (ActiveAcquisitionRecoveryCheckpointError, OSError, ValueError):
|
||||
checkpoint_snapshot_status = None
|
||||
@@ -30522,7 +30744,10 @@ class XgridsK1CompatibilityService:
|
||||
# have no checkpoint to cease. Missing/corrupt storage does not
|
||||
# enter this compatibility branch and remains fail closed.
|
||||
or checkpoint_snapshot_status == "empty"
|
||||
or completed_checkpoint_owned
|
||||
)
|
||||
if completed_checkpoint_owned:
|
||||
self._set_active_acquisition_checkpoint_reason(None)
|
||||
if (
|
||||
current is not None
|
||||
and current.control_mode == "plugin-commanded"
|
||||
@@ -31922,6 +32147,7 @@ class XgridsK1ServicePort(Protocol):
|
||||
|
||||
_SNAPSHOT_RUNTIME_FENCED_MUTATING_ACTIONS = frozenset(
|
||||
{
|
||||
ACTION_DEVICE_MANAGE,
|
||||
ACTION_DISCOVERY_SCAN,
|
||||
ACTION_NETWORK_PROVISION,
|
||||
ACTION_CONNECTION_MODE_SELECT,
|
||||
@@ -31950,6 +32176,7 @@ class XgridsK1PluginFacade:
|
||||
plugin_id = XGRIDS_K1_PLUGIN_ID
|
||||
action_ids = frozenset(
|
||||
{
|
||||
ACTION_DEVICE_MANAGE,
|
||||
ACTION_STATE_READ,
|
||||
ACTION_DISCOVERY_SCAN,
|
||||
ACTION_DEVICE_INSPECT,
|
||||
@@ -32078,6 +32305,10 @@ class XgridsK1PluginFacade:
|
||||
mode_request,
|
||||
)
|
||||
self.service.bind_runtime_event_loop(asyncio.get_running_loop())
|
||||
if action_id == ACTION_DEVICE_MANAGE:
|
||||
return await asyncio.to_thread(
|
||||
manage_device, self.service, DeviceManagementRequest.model_validate(payload),
|
||||
)
|
||||
if action_id == ACTION_STATE_READ:
|
||||
EmptyRequest.model_validate(payload)
|
||||
return await self._read_state_single_flight()
|
||||
@@ -33080,7 +33311,7 @@ def _physical_command_pending_reopened_reconciliation_mode(
|
||||
if not (
|
||||
isinstance(operation_id, str)
|
||||
and isinstance(revision, int)
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and isinstance(retirements, list)
|
||||
and isinstance(reopens, list)
|
||||
):
|
||||
@@ -33322,7 +33553,9 @@ def _resolved_apply_durable_observation_target(
|
||||
and isinstance(semantic_record, Mapping)
|
||||
and semantic_record.get("schema_version") == "missioncore.xgrids-k1-semantic-topology/v1"
|
||||
and semantic_record.get("compatibility_profile_id") == XGRIDS_K1_COMPATIBILITY_PROFILE_ID
|
||||
and semantic_record.get("source") in {"ble-post-write-status", "ble-read-only-status"}
|
||||
and semantic_record.get("source") in {
|
||||
"ble-post-write-status", "ble-read-only-status", "usb-enumeration"
|
||||
}
|
||||
):
|
||||
return None
|
||||
|
||||
@@ -33332,7 +33565,7 @@ def _resolved_apply_durable_observation_target(
|
||||
if not (
|
||||
isinstance(transport_ref, str)
|
||||
and transport_ref
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
|
||||
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and isinstance(ipv4, str)
|
||||
and ipv4
|
||||
and physical_transport_ref_comparison_key(transport_ref)
|
||||
@@ -33704,7 +33937,7 @@ def _connection_policy_projection(
|
||||
)
|
||||
recovery_mode = (
|
||||
recovery_mode_raw
|
||||
if recovery_mode_raw in {"bridge", "quick-connect", "direct-connect"}
|
||||
if recovery_mode_raw in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
else None
|
||||
)
|
||||
recovery_advertised = bool(
|
||||
@@ -33820,7 +34053,7 @@ def _connection_policy_projection(
|
||||
semantic_topology_record.get("connection_mode")
|
||||
if isinstance(semantic_topology_record, Mapping)
|
||||
and semantic_topology_record.get("connection_mode")
|
||||
in {"bridge", "quick-connect", "direct-connect"}
|
||||
in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
else None
|
||||
)
|
||||
if transport_is_retired(semantic_recovery_ref):
|
||||
@@ -33947,7 +34180,7 @@ def _connection_policy_projection(
|
||||
and semantic_topology_record.get("transport_ref")
|
||||
and not transport_is_retired(semantic_topology_record.get("transport_ref"))
|
||||
and semantic_topology_record.get("connection_mode")
|
||||
in {"bridge", "quick-connect", "direct-connect"}
|
||||
in {"bridge", "quick-connect", "direct-connect", "usb"}
|
||||
and isinstance(semantic_topology_record.get("ipv4"), str)
|
||||
and semantic_topology_record.get("ipv4")
|
||||
)
|
||||
|
||||
@@ -25,7 +25,12 @@ from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
|
||||
|
||||
def _run(args: list[str], timeout: float = 8) -> str:
|
||||
result = subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False)
|
||||
# nmcli localizes even terse ACTIVE values (for example yes/no -> да/нет).
|
||||
# Pin machine output only for this child; keep UTF-8 SSIDs and host locale.
|
||||
result = subprocess.run(
|
||||
args, capture_output=True, text=True, encoding="utf-8", timeout=timeout,
|
||||
check=False, env={**os.environ, "LC_ALL": "C", "LANG": "C"},
|
||||
)
|
||||
if result.returncode:
|
||||
# Never forward subprocess diagnostics: SSIDs or other local data may occur.
|
||||
raise OSError("Network observation unavailable")
|
||||
|
||||
@@ -24,6 +24,7 @@ NETWORK_MUTATION_LEDGER_LOCK_FILENAME = ".network-mutation.lock"
|
||||
NETWORK_MUTATION_LEDGER_MAX_BYTES = 64 * 1024
|
||||
|
||||
NetworkConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
|
||||
PreviousConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
|
||||
NetworkMutationStage = Literal["prepared", "dispatching", "observing", "resolved"]
|
||||
NetworkMutationWriteMode = Literal["with_response", "without_response"]
|
||||
NetworkMutationResolution = Literal[
|
||||
@@ -105,13 +106,14 @@ class PreviousConnectionEvidence:
|
||||
"""Last admitted topology retained as evidence, never as live reachability."""
|
||||
|
||||
transport_ref: str
|
||||
mode: NetworkConnectionMode
|
||||
mode: PreviousConnectionMode
|
||||
ipv4: str | None
|
||||
device_session_id: str | None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_validate_identifier(self.transport_ref, field_name="transport_ref")
|
||||
_validate_connection_mode(self.mode)
|
||||
if self.mode != "usb":
|
||||
_validate_connection_mode(self.mode)
|
||||
if self.ipv4 is not None:
|
||||
try:
|
||||
parsed = ipaddress.ip_address(self.ipv4)
|
||||
@@ -856,10 +858,11 @@ def _previous_connection_from_mapping(value: object) -> PreviousConnectionEviden
|
||||
label="previous connection",
|
||||
)
|
||||
mode_raw = _required_string(document["mode"], field_name="mode")
|
||||
_validate_connection_mode(mode_raw)
|
||||
if mode_raw != "usb":
|
||||
_validate_connection_mode(mode_raw)
|
||||
return PreviousConnectionEvidence(
|
||||
transport_ref=_required_string(document["transport_ref"], field_name="transport_ref"),
|
||||
mode=cast(NetworkConnectionMode, mode_raw),
|
||||
mode=cast(PreviousConnectionMode, mode_raw),
|
||||
ipv4=_optional_string(document["ipv4"], field_name="ipv4"),
|
||||
device_session_id=_optional_string(
|
||||
document["device_session_id"], field_name="device_session_id"
|
||||
|
||||
@@ -10,6 +10,7 @@ import asyncio
|
||||
import logging
|
||||
import re
|
||||
import traceback
|
||||
from contextlib import suppress
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from uuid import UUID, uuid5
|
||||
@@ -30,6 +31,7 @@ from .facade import (
|
||||
)
|
||||
from .linux_host import LinuxApplicationAuthorityLoader, LinuxWifiAssociationProbe, wifi_networks
|
||||
from .protocol.application_authority import ApplicationAuthorityLoadError
|
||||
from .usb_network import LinuxK1UsbProbe
|
||||
|
||||
ATTESTATION = {
|
||||
"firmware_version": "3.0.2",
|
||||
@@ -42,25 +44,48 @@ def verification_parameters(state, operation_id, *, requested_device_id=None):
|
||||
"""Use the admitted persisted Bridge target before asking for BLE again.
|
||||
|
||||
The facade still checks its ledger, exact identity, route, DeviceInfo and
|
||||
physical reconciliation fences. A saved address alone never grants START.
|
||||
physical reconciliation fences, including any required live GATT read.
|
||||
A saved address alone never grants START.
|
||||
"""
|
||||
parameters = {
|
||||
"expected_snapshot_runtime_id": state["snapshot_runtime_id"],
|
||||
"operation_id": operation_id,
|
||||
}
|
||||
if state.get("active_connection_mode") == "usb" or (
|
||||
state.get("active_connection_mode") is None
|
||||
and state.get("desired_connection_mode") == "usb"
|
||||
):
|
||||
target = state.get("selected_device_id")
|
||||
if isinstance(target, str) and target.startswith("usb:"):
|
||||
parameters.update(
|
||||
device_id=target, source="usb-enumeration",
|
||||
compatibility_attestation={**ATTESTATION, "topology": "usb-ethernet"},
|
||||
expected_mode_revision=state.get("desired_connection_mode_revision"),
|
||||
)
|
||||
return parameters
|
||||
policy = (state.get("connection_policy") or {}).get("actions", {})
|
||||
fresh = policy.get("observe-fresh-device-network") or {}
|
||||
if requested_device_id is not None and fresh.get("allowed") is True and any(
|
||||
item.get("likely_k1") is True
|
||||
and str(item.get("device_id", "")).casefold() == requested_device_id.casefold()
|
||||
for item in state.get("devices", [])
|
||||
):
|
||||
# The caller already carries the current discovery generation. Preserve
|
||||
# the explicitly selected scan result instead of replacing it with the
|
||||
# durable target, whose BlueZ device reference may belong to an old scan.
|
||||
return parameters
|
||||
decision = policy.get("observe-configured-device-network") or {}
|
||||
target = decision.get("required_transport_ref")
|
||||
selected = state.get("selected_device_id")
|
||||
if (decision.get("allowed") is True
|
||||
and decision.get("requires_live_gatt_validation") is False
|
||||
and decision.get("required_connection_mode") == "bridge"
|
||||
and isinstance(target, str) and isinstance(selected, str)
|
||||
and target.casefold() == selected.casefold()
|
||||
and (requested_device_id is None
|
||||
or target.casefold() == requested_device_id.casefold())):
|
||||
if (
|
||||
decision.get("allowed") is True
|
||||
and decision.get("required_connection_mode") == "bridge"
|
||||
and isinstance(target, str)
|
||||
and bool(target.strip())
|
||||
and (requested_device_id is None or target.casefold() == requested_device_id.casefold())
|
||||
):
|
||||
parameters.update(
|
||||
device_id=target, source="durable-configured-state",
|
||||
device_id=target,
|
||||
source="durable-configured-state",
|
||||
compatibility_attestation=ATTESTATION,
|
||||
expected_mode_revision=state.get("desired_connection_mode_revision"),
|
||||
)
|
||||
@@ -99,15 +124,24 @@ def failure_transport_facts(error: BaseException) -> str:
|
||||
seen.add(id(current))
|
||||
stage = getattr(current, "operation_stage", None)
|
||||
if isinstance(stage, str) and stage in {
|
||||
"resolution", "exact-uuid-scan", "connect", "gatt-contract",
|
||||
"baseline-read", "gatt-write", "status-poll", "status-read",
|
||||
"resolution",
|
||||
"exact-uuid-scan",
|
||||
"connect",
|
||||
"gatt-contract",
|
||||
"baseline-read",
|
||||
"gatt-write",
|
||||
"status-poll",
|
||||
"status-read",
|
||||
}:
|
||||
facts["stage"] = stage
|
||||
bluez = getattr(current, "dbus_error", None)
|
||||
if isinstance(bluez, str) and bluez in {
|
||||
"org.bluez.Error.InProgress", "org.bluez.Error.NotReady",
|
||||
"org.bluez.Error.Failed", "org.bluez.Error.NotAuthorized",
|
||||
"org.bluez.Error.NotSupported", "org.bluez.Error.DoesNotExist",
|
||||
"org.bluez.Error.InProgress",
|
||||
"org.bluez.Error.NotReady",
|
||||
"org.bluez.Error.Failed",
|
||||
"org.bluez.Error.NotAuthorized",
|
||||
"org.bluez.Error.NotSupported",
|
||||
"org.bluez.Error.DoesNotExist",
|
||||
"org.freedesktop.DBus.Error.UnknownObject",
|
||||
}:
|
||||
facts["bluez"] = bluez
|
||||
@@ -156,6 +190,7 @@ class NodeBridge:
|
||||
def __init__(self, repository_root: Path, *, service=None):
|
||||
self.rerun = NodeRerunHub()
|
||||
self.application_authority_available = None
|
||||
self.usb_probe = LinuxK1UsbProbe() if service is None else None
|
||||
if service is None:
|
||||
_validate_installed_compatibility_profile(repository_root)
|
||||
loader = LinuxApplicationAuthorityLoader()
|
||||
@@ -170,6 +205,7 @@ class NodeBridge:
|
||||
repository_root,
|
||||
application_authority_loader=loader,
|
||||
host_wifi_association_probe=LinuxWifiAssociationProbe(),
|
||||
usb_network_probe=self.usb_probe,
|
||||
visualization_bridge_factory=self.rerun.create,
|
||||
)
|
||||
self.service = service
|
||||
@@ -191,8 +227,56 @@ class NodeBridge:
|
||||
for key in ("attempt_id", "recovery_operation_id"):
|
||||
if key in attempt:
|
||||
attempt[key] = node_operation_id(attempt[key])
|
||||
target = verification_parameters(snapshot, "projection")
|
||||
checkpoint = snapshot.get("active_acquisition_recovery_checkpoint") or {}
|
||||
reset = snapshot.get("connection_scenario_reset") or {}
|
||||
reset_completed = (reset.get("timing") or {}).get("completed_at_utc")
|
||||
verification = next(
|
||||
(
|
||||
operation
|
||||
for operation in reversed(snapshot.get("operations", []))
|
||||
if operation.get("action") == "connection.verify"
|
||||
and (operation.get("context") or {}).get("snapshot_runtime_id")
|
||||
== snapshot["snapshot_runtime_id"]
|
||||
and (
|
||||
not reset_completed
|
||||
or (
|
||||
operation.get("accepted_at")
|
||||
and datetime.fromisoformat(operation["accepted_at"])
|
||||
> datetime.fromisoformat(reset_completed)
|
||||
)
|
||||
)
|
||||
),
|
||||
None,
|
||||
)
|
||||
return {
|
||||
"reconnect_target": (
|
||||
{"device_id": target["device_id"], "source": target["source"]}
|
||||
if "source" in target
|
||||
else None
|
||||
),
|
||||
"acquisition_recovery": {
|
||||
key: checkpoint[key]
|
||||
for key in (
|
||||
"status",
|
||||
"state",
|
||||
"gap_open",
|
||||
"restart_rehydration_phase",
|
||||
"reason_code",
|
||||
)
|
||||
if key in checkpoint
|
||||
},
|
||||
"verification": (
|
||||
{
|
||||
"operation_id": node_operation_id(verification.get("operation_id")),
|
||||
"status": verification.get("status"),
|
||||
"error_code": (verification.get("error") or {}).get("code"),
|
||||
}
|
||||
if verification
|
||||
else None
|
||||
),
|
||||
"available": True,
|
||||
"can_reset": True,
|
||||
"model": "XGRIDS K1",
|
||||
"mode": "bridge",
|
||||
"runtime_id": snapshot["snapshot_runtime_id"],
|
||||
@@ -292,6 +376,44 @@ class NodeBridge:
|
||||
action, identifier = command["action"], command["operation_id"]
|
||||
plugin_identifier = plugin_operation_id(identifier)
|
||||
parameters = command.get("parameters", {})
|
||||
if action == "reset":
|
||||
# The existing reset owns cancellation, quiescence and local retirement.
|
||||
# Never queue it behind this adapter's network-operation lock or bind
|
||||
# the old monitor through state.read before the canonical reset runs.
|
||||
if datetime.fromisoformat(command["deadline_at"]) <= datetime.now(UTC):
|
||||
raise NodeEnrollmentRejected("command-expired")
|
||||
if (
|
||||
set(parameters) != {"mode_revision"}
|
||||
or type(parameters["mode_revision"]) is not int
|
||||
or parameters["mode_revision"] < 0
|
||||
):
|
||||
raise NodeEnrollmentRejected("device-selection-changed")
|
||||
result = await self.invoke(
|
||||
"connection.mode.select",
|
||||
{
|
||||
"connection_mode": "bridge",
|
||||
"expected_revision": parameters["mode_revision"],
|
||||
"expected_snapshot_runtime_id": command.get("runtime_id"),
|
||||
"reset_scenario": True,
|
||||
"reset_id": plugin_identifier,
|
||||
},
|
||||
identifier,
|
||||
)
|
||||
marker = result.get("connection_scenario_reset") or {}
|
||||
committed = (
|
||||
marker.get("reset_id") == plugin_identifier
|
||||
and marker.get("revision") == parameters["mode_revision"] + 1
|
||||
and marker.get("local_session_closed") is True
|
||||
)
|
||||
return {
|
||||
**self.project(result),
|
||||
"command_result": {
|
||||
"operation_id": identifier,
|
||||
"action": action,
|
||||
"status": "succeeded" if committed else "failed",
|
||||
"error_code": None if committed else "connection-scenario-reset-unconfirmed",
|
||||
},
|
||||
}
|
||||
if action not in {"scan", "networks", "connect", "verify"}:
|
||||
raise NodeEnrollmentRejected("unsupported-action")
|
||||
async with self.lock:
|
||||
@@ -316,10 +438,21 @@ class NodeBridge:
|
||||
else:
|
||||
# Do not derive fences at dispatch: they are the exact version
|
||||
# shown to the operator before credentials were submitted.
|
||||
recovery = (
|
||||
verification_parameters(
|
||||
snapshot, plugin_identifier, requested_device_id=parameters.get("device_id")
|
||||
)
|
||||
if action == "verify"
|
||||
else {}
|
||||
)
|
||||
if (
|
||||
parameters.get("discovery_generation") != state["discovery_generation"]
|
||||
or parameters.get("mode_revision") != state["mode_revision"]
|
||||
or parameters.get("device_id") not in {v["id"] for v in state["candidates"]}
|
||||
or (
|
||||
"source" not in recovery
|
||||
and parameters.get("device_id")
|
||||
not in {v["id"] for v in state["candidates"]}
|
||||
)
|
||||
):
|
||||
raise NodeEnrollmentRejected("device-selection-changed")
|
||||
payload = {
|
||||
@@ -339,9 +472,11 @@ class NodeBridge:
|
||||
password=parameters.get("password"),
|
||||
)
|
||||
else:
|
||||
payload.update(verification_parameters(
|
||||
snapshot, plugin_identifier, requested_device_id=parameters["device_id"],
|
||||
))
|
||||
payload.update(recovery)
|
||||
if "source" in recovery:
|
||||
# The adapter already fenced the displayed discovery generation.
|
||||
# The canonical durable Verify contract has no fresh-scan token.
|
||||
payload.pop("expected_discovery_generation", None)
|
||||
try:
|
||||
result = await self.invoke_journalled(
|
||||
"network.provision" if action == "connect" else "connection.verify",
|
||||
@@ -383,7 +518,8 @@ def create_app(repository_root: Path):
|
||||
sensor = NodeK1Sensor(bridge, peers)
|
||||
|
||||
from fastapi.responses import Response
|
||||
from k1link.viewer.node_local_media import start_local, read_local
|
||||
|
||||
from k1link.viewer.node_local_media import read_local, start_local
|
||||
|
||||
async def preview_request(request):
|
||||
data = await request.body()
|
||||
@@ -393,9 +529,18 @@ def create_app(repository_root: Path):
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app):
|
||||
yield
|
||||
await peers.close_all()
|
||||
await asyncio.to_thread(bridge.service.close)
|
||||
from .node_usb import NodeK1UsbObserver
|
||||
|
||||
observer = NodeK1UsbObserver(bridge, bridge.usb_probe)
|
||||
task = asyncio.create_task(observer.run(), name="k1-usb-observer")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
await peers.close_all()
|
||||
await asyncio.to_thread(bridge.service.close)
|
||||
|
||||
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
||||
|
||||
@@ -403,6 +548,10 @@ def create_app(repository_root: Path):
|
||||
async def status():
|
||||
return await bridge.state()
|
||||
|
||||
@app.get("/preview-health")
|
||||
async def preview_health():
|
||||
return peers.snapshot()
|
||||
|
||||
@app.get("/inventory")
|
||||
async def inventory(request: Request):
|
||||
return await sensor.inventory(request.headers["X-Node-Id"])
|
||||
@@ -414,10 +563,13 @@ def create_app(repository_root: Path):
|
||||
if datetime.fromisoformat(command["deadline_at"]) <= datetime.now(UTC):
|
||||
raise ValueError("Preview request expired")
|
||||
await sensor.admit_preview(command, request.headers["X-Node-Id"])
|
||||
identifier = await start_local(peers, command['parameters'])
|
||||
data = await read_local(peers, identifier, command['parameters'].get('after', 0))
|
||||
return Response(data, media_type="application/vnd.missioncore.preview",
|
||||
headers={"Cache-Control": "no-store"})
|
||||
identifier = await start_local(peers, command["parameters"])
|
||||
data = await read_local(peers, identifier, command["parameters"].get("after", 0))
|
||||
return Response(
|
||||
data,
|
||||
media_type="application/vnd.missioncore.preview",
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return JSONResponse({"error": "Preview unavailable"}, status_code=409)
|
||||
|
||||
@@ -425,9 +577,12 @@ def create_app(repository_root: Path):
|
||||
async def preview_read(request: Request):
|
||||
try:
|
||||
data = await preview_request(request)
|
||||
payload = await read_local(peers, data['peer_id'], data['after'])
|
||||
return Response(payload, media_type="application/vnd.missioncore.preview",
|
||||
headers={"Cache-Control": "no-store"})
|
||||
payload = await read_local(peers, data["peer_id"], data["after"])
|
||||
return Response(
|
||||
payload,
|
||||
media_type="application/vnd.missioncore.preview",
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return JSONResponse({"error": "Preview expired"}, status_code=409)
|
||||
|
||||
@@ -460,7 +615,8 @@ def create_app(repository_root: Path):
|
||||
except Exception as error:
|
||||
logging.getLogger(__name__).warning(
|
||||
"K1 sensor operation failed: exception=%s chain=%s",
|
||||
type(error).__name__, failure_locations(error),
|
||||
type(error).__name__,
|
||||
failure_locations(error),
|
||||
)
|
||||
return {
|
||||
"state": "unknown",
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
"""SDK projection and explicit acquisition actions for the Node-owned K1."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from k1link.viewer.recorded import recorded_blueprint_rrd, recorded_blueprint_sessions
|
||||
from k1link.viewer.rerun_bridge import RerunSceneSettings
|
||||
|
||||
from .facade import (
|
||||
XGRIDS_K1_MODEL_ID,
|
||||
XGRIDS_K1_PLUGIN_ID,
|
||||
@@ -23,6 +29,20 @@ PHYSICAL_ACCEPTANCE_KEYS = (
|
||||
)
|
||||
|
||||
|
||||
def _storage_status(control, connected):
|
||||
value = (control.get("transport") or {}).get("storage_status")
|
||||
if not connected or not isinstance(value, dict):
|
||||
return None
|
||||
used, observed = value.get("used_percent"), value.get("observed_at")
|
||||
if type(used) not in {int, float} or not math.isfinite(used) or not 0 <= used <= 100:
|
||||
return None
|
||||
try:
|
||||
age = (datetime.now(UTC) - datetime.fromisoformat(observed)).total_seconds()
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
return {"used_percent": used, "observed_at": observed} if 0 <= age <= 5 else None
|
||||
|
||||
|
||||
def project_sensor(snapshot, node_id):
|
||||
session = snapshot.get("device_session")
|
||||
if not session:
|
||||
@@ -31,7 +51,7 @@ def project_sensor(snapshot, node_id):
|
||||
lifecycle = snapshot.get("connection_lifecycle", {})
|
||||
connected = (
|
||||
lifecycle.get("connection_ready") is True
|
||||
and snapshot.get("active_connection_mode") == "bridge"
|
||||
and snapshot.get("active_connection_mode") in {"bridge", "usb"}
|
||||
)
|
||||
acquisition = snapshot.get("acquisition") or {}
|
||||
acquisition_state = {
|
||||
@@ -66,6 +86,15 @@ def project_sensor(snapshot, node_id):
|
||||
}
|
||||
control = snapshot.get("application_control_session") or {}
|
||||
attempt = snapshot.get("connection_attempt") or {}
|
||||
connection_mode = snapshot.get("active_connection_mode")
|
||||
if (
|
||||
connection_mode is None
|
||||
and snapshot.get("desired_connection_mode") == "usb"
|
||||
and str(snapshot.get("selected_device_id") or "").startswith("usb:")
|
||||
):
|
||||
# Transport identity survives a retired control socket; it does not
|
||||
# imply that the device is online or that START is admitted.
|
||||
connection_mode = "usb"
|
||||
return {
|
||||
"id": identifier,
|
||||
"name": "XGRIDS K1",
|
||||
@@ -76,7 +105,10 @@ def project_sensor(snapshot, node_id):
|
||||
"verified": connected,
|
||||
"online": connected,
|
||||
"usb": "",
|
||||
"connection_label": "Wi-Fi · " + (snapshot.get("k1_ip") or "—"),
|
||||
"connection_label": (
|
||||
"USB · " if connection_mode == "usb" else "Wi-Fi · "
|
||||
) + (snapshot.get("k1_ip") or "—"),
|
||||
"connection_mode": connection_mode,
|
||||
"layers": ["points", "camera"],
|
||||
"snapshot": {
|
||||
"context": context,
|
||||
@@ -92,15 +124,21 @@ def project_sensor(snapshot, node_id):
|
||||
"phase": control.get("state"),
|
||||
"can_start": lifecycle.get("ready_to_start", False),
|
||||
"can_stop": control.get("state") in {"start-requested", "initializing", "scanning"},
|
||||
"can_verify": any(action in lifecycle.get("allowed_actions", []) for action in (
|
||||
"verify-control-read-only", "observe-current-device-network",
|
||||
"observe-configured-device-network", "observe-fresh-device-network",
|
||||
)),
|
||||
"can_verify": any(
|
||||
action in lifecycle.get("allowed_actions", [])
|
||||
for action in (
|
||||
"verify-control-read-only",
|
||||
"observe-current-device-network",
|
||||
"observe-configured-device-network",
|
||||
"observe-fresh-device-network",
|
||||
)
|
||||
),
|
||||
"network_applied": connected or attempt.get("phase") == "network_applied",
|
||||
"reason_code": None if connected else attempt.get("public_error_code"),
|
||||
"acquisition_id": acquisition.get("acquisition_id"),
|
||||
"acquisition_phase": acquisition.get("state"),
|
||||
},
|
||||
"storage_status": _storage_status(control, connected),
|
||||
"live_settings": snapshot.get("viewer_settings", {}),
|
||||
"frames": snapshot.get("metrics", {}),
|
||||
"recordings": [],
|
||||
@@ -134,12 +172,16 @@ class NodeK1Sensor:
|
||||
|
||||
async def admit_preview(self, command, node_id):
|
||||
item = project_sensor(await self.raw_state(), node_id)
|
||||
if (not item or command.get("action_id") != "offer"
|
||||
or command.get("session", {}).get("device_id") != item["id"]
|
||||
or command["session"].get("session_id") != item["snapshot"]["context"]["session_id"]
|
||||
or item["snapshot"]["acquisition"] != "streaming"
|
||||
or not item["control"]["acquisition_id"]
|
||||
or command.get("parameters", {}).get("acquisition_id") != item["control"]["acquisition_id"]):
|
||||
if (
|
||||
not item
|
||||
or command.get("action_id") != "offer"
|
||||
or command.get("session", {}).get("device_id") != item["id"]
|
||||
or command["session"].get("session_id") != item["snapshot"]["context"]["session_id"]
|
||||
or item["snapshot"]["acquisition"] != "streaming"
|
||||
or not item["control"]["acquisition_id"]
|
||||
or command.get("parameters", {}).get("acquisition_id")
|
||||
!= item["control"]["acquisition_id"]
|
||||
):
|
||||
raise ValueError("Acquisition is not active or changed")
|
||||
return item
|
||||
|
||||
@@ -159,7 +201,70 @@ class NodeK1Sensor:
|
||||
)
|
||||
plugin_identifier = plugin_operation_id(identifier)
|
||||
if action == "details":
|
||||
return item
|
||||
if "preview_blueprint" not in params:
|
||||
return item
|
||||
request = params["preview_blueprint"]
|
||||
if not isinstance(request, dict):
|
||||
raise ValueError("Invalid preview blueprint")
|
||||
recording, owner = request.get("recording_id"), request.get("owner")
|
||||
if (
|
||||
not isinstance(recording, str)
|
||||
or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}", recording)
|
||||
or not isinstance(owner, str)
|
||||
or not re.fullmatch(r"[a-f0-9]{32}", owner)
|
||||
):
|
||||
raise ValueError("Invalid preview identity")
|
||||
if request.get("release") is True:
|
||||
recorded_blueprint_sessions.release(
|
||||
("nodedc_mission_core_spatial", recording, owner)
|
||||
)
|
||||
return {"released": True}
|
||||
if request.get("view") not in {"3d", "plan"}:
|
||||
raise ValueError("Invalid spatial view")
|
||||
settings = ViewerSettingsRequest.model_validate(
|
||||
request.get("settings", state.get("viewer_settings", {}))
|
||||
)
|
||||
follow = request.get("follow_trajectory", False)
|
||||
if not isinstance(follow, bool):
|
||||
raise ValueError("Invalid follow state")
|
||||
host_playback = request.get("host_playback", False)
|
||||
if not isinstance(host_playback, bool):
|
||||
raise ValueError("Invalid playback owner")
|
||||
eye = request.get("eye")
|
||||
eye_fields = {}
|
||||
if eye is not None:
|
||||
import math
|
||||
|
||||
if not isinstance(eye, dict) or set(eye) != {"position", "lookTarget", "eyeUp"}:
|
||||
raise ValueError("Invalid spatial eye")
|
||||
for key, target in (
|
||||
("position", "eye_position"),
|
||||
("lookTarget", "eye_look_target"),
|
||||
("eyeUp", "eye_up"),
|
||||
):
|
||||
value = eye[key]
|
||||
if (
|
||||
not isinstance(value, list)
|
||||
or len(value) != 3
|
||||
or any(type(v) not in {int, float} or not math.isfinite(v) for v in value)
|
||||
):
|
||||
raise ValueError("Invalid spatial eye")
|
||||
eye_fields[target] = tuple(value)
|
||||
payload = await asyncio.to_thread(
|
||||
recorded_blueprint_rrd,
|
||||
RerunSceneSettings(**settings.model_dump()),
|
||||
application_id="nodedc_mission_core_spatial",
|
||||
recording_id=recording,
|
||||
blueprint_session_id=owner,
|
||||
timeline="stream_time",
|
||||
plan_view=request["view"] == "plan",
|
||||
follow_trajectory=follow,
|
||||
reactivate_updates=True,
|
||||
initialize_playback=not host_playback,
|
||||
**eye_fields,
|
||||
)
|
||||
return {"rrd": base64.b64encode(payload).decode("ascii")}
|
||||
|
||||
if action == "close-peer":
|
||||
await self.peers.close(params.get("peer_id"))
|
||||
if params.get("retire_view") is True:
|
||||
@@ -167,17 +272,22 @@ class NodeK1Sensor:
|
||||
return {"ok": True}
|
||||
if action == "offer":
|
||||
acquisition_id = item["control"]["acquisition_id"]
|
||||
if (item["snapshot"]["acquisition"] != "streaming" or not acquisition_id
|
||||
or params.get("acquisition_id") != acquisition_id):
|
||||
if (
|
||||
item["snapshot"]["acquisition"] != "streaming"
|
||||
or not acquisition_id
|
||||
or params.get("acquisition_id") != acquisition_id
|
||||
):
|
||||
raise ValueError("Acquisition is not active or changed")
|
||||
answer = await self.peers.offer(params)
|
||||
# Signalling may outlive STOP or a replacement acquisition. Retire
|
||||
# that disposable preview instead of attaching it to another run.
|
||||
current = project_sensor(await self.raw_state(), node_id)
|
||||
if (current is None or current["snapshot"]["acquisition"] != "streaming"
|
||||
or current["snapshot"]["context"]["session_id"]
|
||||
!= command["session"]["session_id"]
|
||||
or current["control"]["acquisition_id"] != acquisition_id):
|
||||
if (
|
||||
current is None
|
||||
or current["snapshot"]["acquisition"] != "streaming"
|
||||
or current["snapshot"]["context"]["session_id"] != command["session"]["session_id"]
|
||||
or current["control"]["acquisition_id"] != acquisition_id
|
||||
):
|
||||
await self.peers.close(answer["peer_id"])
|
||||
raise ValueError("Acquisition changed during preview signalling")
|
||||
return answer
|
||||
@@ -192,6 +302,17 @@ class NodeK1Sensor:
|
||||
):
|
||||
raise ValueError("Device session changed")
|
||||
runtime = state["snapshot_runtime_id"]
|
||||
if action == "management":
|
||||
if (params.get("control_generation") != current["control"]["generation"]
|
||||
or params.get("control_revision") != current["control"]["revision"]):
|
||||
raise ValueError("Состояние K1 изменилось. Обновите окно")
|
||||
return await self.bridge.invoke("device.manage", {
|
||||
**{key: value for key, value in params.items()
|
||||
if key not in {"control_generation", "control_revision"}},
|
||||
"operation_id": plugin_identifier,
|
||||
"expected_snapshot_runtime_id": runtime,
|
||||
**self.cas(state, acquisition=False),
|
||||
}, identifier)
|
||||
if action == "option":
|
||||
if (
|
||||
set(params) != {"profile", "settings"}
|
||||
@@ -252,8 +373,11 @@ class NodeK1Sensor:
|
||||
control = state.get("application_control_session") or {}
|
||||
phase = control.get("state")
|
||||
physical = control.get("physical_command") or state.get("physical_command") or {}
|
||||
if ("acquisition.start" in dispatched
|
||||
and phase in {"start-requested", "initializing", "scanning"}):
|
||||
if "acquisition.start" in dispatched and phase in {
|
||||
"start-requested",
|
||||
"initializing",
|
||||
"scanning",
|
||||
}:
|
||||
# The just-admitted START owns its pending physical edge.
|
||||
# Returning its state does not dispatch or reconcile it again.
|
||||
return project_sensor(state, node_id)
|
||||
@@ -277,8 +401,15 @@ class NodeK1Sensor:
|
||||
operation_id=prepare_identifier,
|
||||
idempotency_key=prepare_identifier,
|
||||
project_name=project_name,
|
||||
mount_type=params["mount_type"], gnss_mode=params["gnss_mode"],
|
||||
compatibility_attestation=ATTESTATION,
|
||||
mount_type=params["mount_type"],
|
||||
gnss_mode=params["gnss_mode"],
|
||||
compatibility_attestation={
|
||||
**ATTESTATION,
|
||||
"topology": (
|
||||
"usb-ethernet"
|
||||
if state.get("active_connection_mode") == "usb" else "direct-lan"
|
||||
),
|
||||
},
|
||||
)
|
||||
elif phase == "project-ready" and acquisition.get("state") == "prepared":
|
||||
if acquisition.get("project_name") != project_name:
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Node-owned USB hotplug observation feeding the existing K1 Verify pipeline."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .usb_network import LinuxK1UsbProbe
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .node_bridge import NodeBridge
|
||||
|
||||
from .facade import (
|
||||
CompatibilityAttestationRequest,
|
||||
ConnectionVerifyRequest,
|
||||
DesiredConnectionModeRequest,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class NodeK1UsbObserver:
|
||||
def __init__(self, bridge: "NodeBridge", probe: LinuxK1UsbProbe) -> None:
|
||||
self.bridge, self.probe = bridge, probe
|
||||
self.accepted_generation: str | None = None
|
||||
|
||||
async def observe_once(self) -> None:
|
||||
candidates = await asyncio.to_thread(self.probe.discover)
|
||||
if len(candidates) != 1:
|
||||
self.accepted_generation = None
|
||||
return
|
||||
attachment = candidates[0]
|
||||
# Observe-only hotplug never steals a live wireless dialogue. The
|
||||
# facade repeats all physical/receiver/lease checks under its gates.
|
||||
async with self.bridge.lock:
|
||||
state = await self.bridge.invoke("state.read", {}, "usb-observe")
|
||||
mode = state.get("active_connection_mode")
|
||||
if self.accepted_generation == attachment.generation:
|
||||
lifecycle = state.get("connection_lifecycle") or {}
|
||||
acquisition = state.get("acquisition") or {}
|
||||
# A terminal STOP timeout can retire local control without a
|
||||
# USB hotplug. Re-enter the same read-only Verify transaction;
|
||||
# the physical ledger, not enumeration, decides its outcome.
|
||||
# A live receiver remains owned by the connection monitor.
|
||||
if (
|
||||
lifecycle.get("connection_ready") is True
|
||||
or state.get("source_mode") != "idle"
|
||||
or acquisition.get("state") not in {None, "completed", "failed", "aborted"}
|
||||
):
|
||||
return
|
||||
if mode not in {None, "usb"} and (
|
||||
state.get("connection_lifecycle", {}).get("connection_ready") is True
|
||||
or state.get("source_mode") != "idle"
|
||||
):
|
||||
return
|
||||
if (state.get("connection_reconfiguration") or {}).get("intent"):
|
||||
return
|
||||
if state.get("desired_connection_mode") != "usb":
|
||||
state = await asyncio.to_thread(
|
||||
self.bridge.service.select_connection_mode, DesiredConnectionModeRequest(
|
||||
connection_mode="usb",
|
||||
expected_revision=state["desired_connection_mode_revision"],
|
||||
)
|
||||
)
|
||||
# DeviceInfo-only, then the already implemented physical START
|
||||
# reconciliation. This path never creates or reissues START.
|
||||
await self.bridge.service.verify_connection(ConnectionVerifyRequest(
|
||||
device_id=attachment.transport_ref, source="usb-enumeration",
|
||||
compatibility_attestation=CompatibilityAttestationRequest(
|
||||
firmware_version="3.0.2", topology="usb-ethernet",
|
||||
verification="live-device-info",
|
||||
),
|
||||
expected_mode_revision=state["desired_connection_mode_revision"],
|
||||
))
|
||||
self.accepted_generation = attachment.generation
|
||||
|
||||
async def run(self) -> None:
|
||||
while True:
|
||||
try:
|
||||
await self.observe_once()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as error:
|
||||
# Bound retries of topology observation only. Never log native
|
||||
# USB details/credentials or issue a device command here.
|
||||
logger.info("K1 USB observation pending", extra={
|
||||
"event_code": "k1_usb_observation_pending",
|
||||
"reason_code": getattr(error, "reason_code", type(error).__name__),
|
||||
})
|
||||
await asyncio.sleep(5)
|
||||
@@ -57,7 +57,7 @@ class PhysicalCommandRuntimeBinding:
|
||||
compatibility_profile_id: str
|
||||
intent_id: str
|
||||
transport_ref: str
|
||||
connection_mode: Literal["bridge", "quick-connect", "direct-connect"]
|
||||
connection_mode: Literal["bridge", "quick-connect", "direct-connect", "usb"]
|
||||
target_ipv4: str
|
||||
target_port: int
|
||||
host_path_epoch: int
|
||||
|
||||
@@ -45,7 +45,7 @@ _PHYSICAL_COMMAND_ARCHIVE_AFTER_LINK_FSYNC_FAILPOINT: Callable[[], None] | None
|
||||
PHYSICAL_COMMAND_APPLICATION_SUCCESS_CODE = 302252033
|
||||
|
||||
PhysicalCommandAction = Literal["start", "stop"]
|
||||
PhysicalCommandConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
|
||||
PhysicalCommandConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
|
||||
PhysicalCommandStage = Literal["prepared", "dispatching", "observing", "resolved"]
|
||||
PhysicalCommandResolution = Literal[
|
||||
"not-dispatched",
|
||||
@@ -120,7 +120,7 @@ PhysicalSessionState = Literal[
|
||||
]
|
||||
|
||||
_ACTIONS = frozenset({"start", "stop"})
|
||||
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
|
||||
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
|
||||
_STAGES = frozenset({"prepared", "dispatching", "observing", "resolved"})
|
||||
_RESOLUTIONS = frozenset(
|
||||
{
|
||||
@@ -2483,6 +2483,7 @@ class PhysicalCommandLedger:
|
||||
if (
|
||||
current.reconciled_physical_state != "active"
|
||||
and not current.reopened_physical_state_requires_reconciliation
|
||||
and reopened_resolved_start is None
|
||||
):
|
||||
raise PhysicalCommandTransitionError(
|
||||
"active rebind requires a resolved active physical state"
|
||||
@@ -2573,6 +2574,8 @@ class PhysicalCommandLedger:
|
||||
prior_active_observation = (
|
||||
latest_recovery.observation
|
||||
if latest_recovery is not None
|
||||
else reopened_resolved_start.last_status
|
||||
if reopened_resolved_start is not None
|
||||
else current.last_status
|
||||
if current.resolution == "start-active-observed"
|
||||
else _latest_reconciliation_for_operation(current).observation
|
||||
@@ -2692,6 +2695,7 @@ class PhysicalCommandLedger:
|
||||
if (
|
||||
current.reconciled_physical_state != "active"
|
||||
and not reopened_physical_state_requires_reconciliation
|
||||
and reopened_resolved_start is None
|
||||
and not awaiting_ready_after_scan_over
|
||||
):
|
||||
raise PhysicalCommandTransitionError(
|
||||
|
||||
@@ -361,6 +361,7 @@ class PhysicalAcceptanceDialogueExecutor:
|
||||
event_observed: Callable[[], bool],
|
||||
*,
|
||||
reconciled_active_observed: Callable[[], bool] | None = None,
|
||||
standby_work: Callable[[], None] | None = None,
|
||||
) -> OperatorDialogueCheckpoint | None:
|
||||
"""Service the original socket until one exact operator UI event occurs."""
|
||||
|
||||
@@ -382,6 +383,8 @@ class PhysicalAcceptanceDialogueExecutor:
|
||||
"active recovery may replace only the workspace-entry checkpoint"
|
||||
)
|
||||
while True:
|
||||
if standby_work is not None:
|
||||
standby_work()
|
||||
if reconciled_active_observed is not None and reconciled_active_observed():
|
||||
if not self._transport.scan_initialization_complete(binding):
|
||||
raise ApplicationAcceptanceError(
|
||||
@@ -806,11 +809,15 @@ class PhysicalAcceptanceDialogueExecutor:
|
||||
self._active_authority = None
|
||||
self._active_binding = None
|
||||
|
||||
def maintain_standby_until_next_acquisition(self, requested: Callable[[], bool]) -> None:
|
||||
def maintain_standby_until_next_acquisition(
|
||||
self, requested: Callable[[], bool], *, standby_work: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""Pump the retained socket after READY; issue no device commands."""
|
||||
if self._dialogue_stage != "standby-confirmed" or self._standby_binding is None:
|
||||
raise ApplicationAcceptanceError("next acquisition requires confirmed standby")
|
||||
while True:
|
||||
if standby_work is not None:
|
||||
standby_work()
|
||||
self._transport.maintain_open_for(
|
||||
CONTROL_NETWORK_PUMP_QUANTUM_SECONDS,
|
||||
allowed_response_topics={MODELING_STATUS_RESPONSE_TOPIC},
|
||||
|
||||
@@ -53,6 +53,16 @@ from k1link.device_plugins.xgrids_k1.protocol.modeling_safety import (
|
||||
MODELING_REQUEST_TOPIC,
|
||||
)
|
||||
|
||||
from .device_management import (
|
||||
CONTROL_REQUEST,
|
||||
CONTROL_RESPONSE,
|
||||
MAX_PROJECT_RESPONSE_BYTES,
|
||||
PROJECT_REQUEST,
|
||||
PROJECT_RESPONSE,
|
||||
management_action,
|
||||
management_identity,
|
||||
)
|
||||
|
||||
MODELING_RESPONSE_TOPIC = "lixel/application/response/modeling"
|
||||
CONTROL_KEEPALIVE_SECONDS = 60
|
||||
CONTROL_CONNECT_TIMEOUT_SECONDS = 10.0
|
||||
@@ -61,6 +71,10 @@ CONTROL_LOOP_INTERVAL_SECONDS = 0.05
|
||||
MAX_CONTROL_MAINTAIN_SECONDS = 30.0
|
||||
MAX_CONTROL_RESPONSE_BYTES = 64 * 1024
|
||||
SYSTEM_ERROR_TOPIC = "lixel/application/report/system_error"
|
||||
# Exact non-terminating report observed on FW 3.0.2, with LixelGO's
|
||||
# severity-1 handling independently reviewed. Do not generalize by bit prefix:
|
||||
# unknown reports and known session faults remain blocking. See MQTT profile.
|
||||
_NON_TERMINATING_SYSTEM_REPORTS = frozenset({0x12041002})
|
||||
CONTROL_HEARTBEAT_TOPIC = "lixel/application/report/heartbeat"
|
||||
# DeviceInfo proves identity only at one instant. Thereafter the unchanged
|
||||
# control socket must keep producing reviewed MQTT evidence. Ninety seconds
|
||||
@@ -71,6 +85,8 @@ CONTROL_HEARTBEAT_TOPIC = "lixel/application/report/heartbeat"
|
||||
CONTROL_PROOF_TTL_SECONDS = 90.0
|
||||
|
||||
APPLICATION_RESPONSE_TOPIC_BY_REQUEST_TOPIC = {
|
||||
CONTROL_REQUEST: CONTROL_RESPONSE,
|
||||
PROJECT_REQUEST: PROJECT_RESPONSE,
|
||||
DEVICE_INFO_REQUEST_TOPIC: DEVICE_INFO_RESPONSE_TOPIC,
|
||||
MODELING_STATUS_REQUEST_TOPIC: MODELING_STATUS_RESPONSE_TOPIC,
|
||||
GET_RTK_ADVANCE_REQUEST_TOPIC: GET_RTK_ADVANCE_RESPONSE_TOPIC,
|
||||
@@ -149,6 +165,7 @@ CONTROL_SUBSCRIPTION_GROUPS: tuple[tuple[tuple[str, int], ...], ...] = (
|
||||
|
||||
APPLICATION_RESPONSE_TOPICS = frozenset(
|
||||
{
|
||||
CONTROL_RESPONSE, PROJECT_RESPONSE,
|
||||
DEVICE_INFO_RESPONSE_TOPIC,
|
||||
MODELING_STATUS_RESPONSE_TOPIC,
|
||||
GET_RTK_ADVANCE_RESPONSE_TOPIC,
|
||||
@@ -168,6 +185,7 @@ CONTROL_REPORT_TOPICS = frozenset(
|
||||
|
||||
APPLICATION_REQUEST_ALLOWLIST = frozenset(
|
||||
{
|
||||
CONTROL_REQUEST, PROJECT_REQUEST,
|
||||
"lixel/application/request/device_info",
|
||||
"lixel/application/request/modeling_status",
|
||||
"lixel/application/request/get_rtk_advance",
|
||||
@@ -287,6 +305,7 @@ class _ApplicationResponseExpectation:
|
||||
topic: str
|
||||
identity: ApplicationMessageIdentity
|
||||
modeling_action: ModelingAction | None = None
|
||||
management_action: int | None = None
|
||||
|
||||
@property
|
||||
def correlation_key(self) -> tuple[str, str, ModelingAction | None]:
|
||||
@@ -296,9 +315,12 @@ class _ApplicationResponseExpectation:
|
||||
self,
|
||||
observed: ApplicationMessageIdentity,
|
||||
observed_modeling_action: ModelingAction | None,
|
||||
observed_management_action: int | None = None,
|
||||
) -> bool:
|
||||
if self.modeling_action is not observed_modeling_action:
|
||||
return False
|
||||
if self.management_action != observed_management_action:
|
||||
return False
|
||||
if not hmac.compare_digest(self.identity.session_id, observed.session_id):
|
||||
return False
|
||||
if not hmac.compare_digest(self.identity.openapi_key, observed.openapi_key):
|
||||
@@ -338,6 +360,7 @@ class ApplicationMqttTransportSnapshot:
|
||||
control_proof_source: str | None
|
||||
control_proof_fresh: bool
|
||||
control_proof_age_seconds: float | None
|
||||
storage_status: dict[str, object] | None = None
|
||||
clean_session: bool = False
|
||||
keepalive_seconds: int = CONTROL_KEEPALIVE_SECONDS
|
||||
automatic_reconnect: bool = False
|
||||
@@ -374,6 +397,7 @@ class ApplicationMqttTransportSnapshot:
|
||||
"control_proof_source": self.control_proof_source,
|
||||
"control_proof_fresh": self.control_proof_fresh,
|
||||
"control_proof_age_seconds": self.control_proof_age_seconds,
|
||||
"storage_status": dict(self.storage_status) if self.storage_status else None,
|
||||
"clean_session": self.clean_session,
|
||||
"keepalive_seconds": self.keepalive_seconds,
|
||||
"automatic_reconnect": self.automatic_reconnect,
|
||||
@@ -460,11 +484,14 @@ class ReviewedApplicationMqttTransport:
|
||||
self._late_known_responses = 0
|
||||
self._device_status_reports = 0
|
||||
self._system_error_reports = 0
|
||||
self._blocking_system_error = False
|
||||
self._report_decode_errors = 0
|
||||
self._retained_control_reports_ignored = 0
|
||||
self._retained_application_responses_rejected = 0
|
||||
self._latest_device_session_state: str | None = None
|
||||
self._latest_device_project_bound: bool | None = None
|
||||
self._validated_status_identity: tuple[str, str] | None = None
|
||||
self._latest_storage_status: dict[str, object] | None = None
|
||||
self._latest_device_init_ready: bool | None = None
|
||||
self._latest_device_id: str | None = None
|
||||
self._latest_device_serial: str | None = None
|
||||
@@ -1006,6 +1033,14 @@ class ReviewedApplicationMqttTransport:
|
||||
and proof_age <= self._control_proof_ttl_seconds
|
||||
),
|
||||
control_proof_age_seconds=proof_age,
|
||||
storage_status=(
|
||||
dict(self._latest_storage_status)
|
||||
if self._latest_storage_status
|
||||
and self._validated_status_identity is not None
|
||||
and (self._latest_device_id, self._latest_device_serial)
|
||||
== self._validated_status_identity
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
def _new_client(self) -> mqtt.Client:
|
||||
@@ -1108,7 +1143,9 @@ class ReviewedApplicationMqttTransport:
|
||||
self._set_callback_error("control MQTT received an unreviewed subscribed topic")
|
||||
return
|
||||
payload = bytes(message.payload)
|
||||
if len(payload) > MAX_CONTROL_RESPONSE_BYTES:
|
||||
response_limit = (MAX_PROJECT_RESPONSE_BYTES if message.topic == PROJECT_RESPONSE
|
||||
else MAX_CONTROL_RESPONSE_BYTES)
|
||||
if len(payload) > response_limit:
|
||||
self._set_callback_error("control MQTT response exceeds the reviewed bound")
|
||||
return
|
||||
mqtt_retained = bool(getattr(message, "retain", False))
|
||||
@@ -1210,6 +1247,11 @@ class ReviewedApplicationMqttTransport:
|
||||
)
|
||||
self._latest_device_project_bound = bool(device_report.project_id)
|
||||
self._latest_device_init_ready = device_report.init_ready
|
||||
self._latest_storage_status = (
|
||||
{"used_percent": device_report.storage_used_percent,
|
||||
"observed_at": evidence.observed_at_utc}
|
||||
if device_report.storage_used_percent is not None else None
|
||||
)
|
||||
self._latest_device_id = (
|
||||
device_report.header.device_id if device_report.header is not None else None
|
||||
)
|
||||
@@ -1239,6 +1281,9 @@ class ReviewedApplicationMqttTransport:
|
||||
return
|
||||
with self._lock:
|
||||
self._system_error_reports += 1
|
||||
self._blocking_system_error |= (
|
||||
system_error_report.error_code not in _NON_TERMINATING_SYSTEM_REPORTS
|
||||
)
|
||||
self._latest_system_error_code = system_error_report.error_code
|
||||
self._latest_system_error_state = (
|
||||
system_error_report.session_state.name.casefold()
|
||||
@@ -1254,7 +1299,7 @@ class ReviewedApplicationMqttTransport:
|
||||
raise ApplicationControlDeviceFault(
|
||||
"K1 control report decoding failed; no further automatic action is admissible"
|
||||
)
|
||||
if self._system_error_reports or self._latest_device_fault:
|
||||
if self._blocking_system_error or self._latest_device_fault:
|
||||
state = self._latest_system_error_state or self._latest_device_session_state
|
||||
raise ApplicationControlDeviceFault(
|
||||
f"K1 reported a control fault state: {state or 'unknown'}"
|
||||
@@ -1288,6 +1333,10 @@ class ReviewedApplicationMqttTransport:
|
||||
raise ApplicationControlProofStale(
|
||||
"K1 control proof expired without fresh MQTT evidence"
|
||||
)
|
||||
# Bind display telemetry to the proven DeviceInfo identity. Subsequent
|
||||
# reports need not be promoted to command authority just to display
|
||||
# their storage value; each still has to match this exact identity.
|
||||
self._validated_status_identity = (binding.vendor_device_id, binding.device_serial)
|
||||
|
||||
def _mark_control_proof_locked(
|
||||
self,
|
||||
@@ -1496,14 +1545,24 @@ class ReviewedApplicationMqttTransport:
|
||||
ambiguous_reason_code = "retained_application_response"
|
||||
break
|
||||
try:
|
||||
observed = decode_application_message_identity(payload)
|
||||
except ApplicationBootstrapError:
|
||||
observed = (management_identity(payload) if topic == PROJECT_RESPONSE
|
||||
else decode_application_message_identity(payload))
|
||||
except (ApplicationBootstrapError, ValueError):
|
||||
self._poison_locked("response identity decoding failed")
|
||||
ambiguous_message = "control response identity could not be decoded safely"
|
||||
ambiguous_reason_code = "response_identity_decode_failed"
|
||||
break
|
||||
observed_modeling_action: ModelingAction | None = None
|
||||
observed_management_action: int | None = None
|
||||
observed_result_code: int | None = None
|
||||
if topic in {CONTROL_RESPONSE, PROJECT_RESPONSE}:
|
||||
try:
|
||||
observed_management_action = management_action(payload)
|
||||
except ValueError:
|
||||
self._poison_locked("management response action decoding failed")
|
||||
ambiguous_message = "control management response has no exact action"
|
||||
ambiguous_reason_code = "management_response_decode_failed"
|
||||
break
|
||||
if topic == MODELING_RESPONSE_TOPIC:
|
||||
try:
|
||||
modeling_response = decode_modeling_response(payload)
|
||||
@@ -1523,6 +1582,7 @@ class ReviewedApplicationMqttTransport:
|
||||
if self._known_response_expectations[operation_key].matches(
|
||||
observed,
|
||||
observed_modeling_action,
|
||||
observed_management_action,
|
||||
)
|
||||
]
|
||||
next_unobserved = next(
|
||||
@@ -1604,7 +1664,8 @@ class ReviewedApplicationMqttTransport:
|
||||
if response_topic is None:
|
||||
raise ValueError("control request has no reviewed response topic")
|
||||
try:
|
||||
identity = decode_application_message_identity(envelope.payload)
|
||||
identity = (management_identity(envelope.payload) if envelope.topic == PROJECT_REQUEST
|
||||
else decode_application_message_identity(envelope.payload))
|
||||
except ApplicationBootstrapError as exc:
|
||||
raise ValueError("control request identity is not decodable") from exc
|
||||
modeling_action: ModelingAction | None = None
|
||||
@@ -1620,6 +1681,8 @@ class ReviewedApplicationMqttTransport:
|
||||
topic=response_topic,
|
||||
identity=identity,
|
||||
modeling_action=modeling_action,
|
||||
management_action=(management_action(envelope.payload)
|
||||
if envelope.topic in {CONTROL_REQUEST, PROJECT_REQUEST} else None),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -1671,6 +1734,14 @@ class ReviewedApplicationMqttTransport:
|
||||
dispatch_admission_commit: Callable[[], None] | None,
|
||||
) -> None:
|
||||
observer = self._evidence_observer_snapshot()
|
||||
if evidence.operation_key.startswith(("management:", "management-info:")):
|
||||
# The physical START/STOP coordinator deliberately ignores these
|
||||
# explicit idle-only operations. Own their final no-retry admission
|
||||
# here, even when that observer is installed on the shared socket.
|
||||
self._require_dispatch_deadline_open(dispatch_admission_deadline_reached)
|
||||
if dispatch_admission_commit is not None:
|
||||
dispatch_admission_commit()
|
||||
return
|
||||
if observer is not None:
|
||||
observer.publish_dispatching(
|
||||
evidence,
|
||||
|
||||
@@ -6,6 +6,7 @@ import threading
|
||||
import time
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from functools import partial
|
||||
from typing import Literal
|
||||
|
||||
from k1link.device_plugins.xgrids_k1.physical_command_coordinator import (
|
||||
@@ -39,6 +40,10 @@ from k1link.device_plugins.xgrids_k1.protocol.application_mqtt import (
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_publish import (
|
||||
OneShotPublishEnvelope,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.management_mailbox import (
|
||||
MaintenanceJob,
|
||||
ManagementMailbox,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.modeling_control import (
|
||||
CommandHeaderIdentity,
|
||||
ModelingAction,
|
||||
@@ -126,7 +131,7 @@ class ApplicationConnectionBinding:
|
||||
host_path_epoch: int
|
||||
target_ipv4: str
|
||||
target_port: int
|
||||
connection_mode: Literal["bridge", "quick-connect", "direct-connect"]
|
||||
connection_mode: Literal["bridge", "quick-connect", "direct-connect", "usb"]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.intent_id.strip():
|
||||
@@ -264,6 +269,40 @@ class InteractiveApplicationControlSession:
|
||||
# browser response cannot advance a later session that happens to be
|
||||
# in the same named phase.
|
||||
self._state_revision = 0
|
||||
self._management = ManagementMailbox()
|
||||
|
||||
def manage_device(
|
||||
self, *, operation: str, identifier: str, project_ids: tuple[str, ...],
|
||||
expected_session_generation: int, expected_state_revision: int,
|
||||
catalog_revision: str | None = None,
|
||||
) -> dict[str, object]:
|
||||
job = MaintenanceJob(operation, identifier, project_ids, expected_session_generation,
|
||||
expected_state_revision, time.monotonic() + 25, catalog_revision)
|
||||
self._validate_management_job(job)
|
||||
return self._management.submit(job)
|
||||
|
||||
def _validate_management_job(self, job: MaintenanceJob) -> None:
|
||||
coordinator = self._physical_command_coordinator
|
||||
if coordinator is not None:
|
||||
physical = coordinator.snapshot()
|
||||
if physical.get("recovery_requirement") or physical.get("requires_reconciliation"):
|
||||
raise ValueError("Сначала подтвердите состояние предыдущей съёмки K1")
|
||||
with self._lock:
|
||||
self._require_checkpoint_locked(expected_session_generation=job.generation,
|
||||
expected_state_revision=job.revision)
|
||||
if (self._phase not in {"connection-ready", "completed"} or self._cancel_requested
|
||||
or self._workspace_requested.is_set()
|
||||
or self._active_recovery_requested.is_set()):
|
||||
raise ValueError("Обслуживание доступно только после завершения съёмки K1")
|
||||
if job.operation == "usb-storage" and (
|
||||
self._connection_binding is None
|
||||
or self._connection_binding.connection_mode != "bridge"
|
||||
):
|
||||
raise ValueError(
|
||||
"Режим носителя отключает USB-связь. Подключите K1 через Bridge "
|
||||
"для переключения и возврата. Проекты доступны и без смены режима."
|
||||
)
|
||||
self._validate_connection_binding_snapshot("device-management-dispatch")
|
||||
|
||||
def open(
|
||||
self,
|
||||
@@ -389,6 +428,8 @@ class InteractiveApplicationControlSession:
|
||||
return self.snapshot()
|
||||
|
||||
def _require_workspace_entry_locked(self) -> None:
|
||||
if self._management.pending is not None or self._management.block_start:
|
||||
raise ValueError("Завершите обслуживание K1 и подтвердите режим передачи данных")
|
||||
if (self._phase == "completed" and self._transport is not None
|
||||
and not self._cancel_requested):
|
||||
return
|
||||
@@ -968,6 +1009,9 @@ class InteractiveApplicationControlSession:
|
||||
"workspace-entered",
|
||||
self._workspace_requested.is_set,
|
||||
reconciled_active_observed=self._active_recovery_requested.is_set,
|
||||
standby_work=partial(self._management.pump,
|
||||
transport, authority, binding, self._validate_management_job,
|
||||
),
|
||||
)
|
||||
if workspace is None:
|
||||
self._validate_connection_binding("active-recovery-adoption")
|
||||
@@ -1159,7 +1203,12 @@ class InteractiveApplicationControlSession:
|
||||
self._scanning_observer_confirmed = self._scanning_observer is None
|
||||
completed_acquisition = True
|
||||
self._set_phase_locked("completed")
|
||||
executor.maintain_standby_until_next_acquisition(self._workspace_requested.is_set)
|
||||
executor.maintain_standby_until_next_acquisition(
|
||||
self._workspace_requested.is_set,
|
||||
standby_work=partial(self._management.pump,
|
||||
transport, authority, binding, self._validate_management_job,
|
||||
),
|
||||
)
|
||||
self._validate_connection_binding_snapshot("next-acquisition-preflight")
|
||||
# Operation keys and response correlations are one-shot per MQTT
|
||||
# dialogue. A new explicit scan gets a fresh socket, never reset
|
||||
@@ -1488,6 +1537,7 @@ class InteractiveApplicationControlSession:
|
||||
},
|
||||
)
|
||||
finally:
|
||||
self._management.cancel_queued()
|
||||
final_dialogue_snapshot: dict[str, object] | None = None
|
||||
final_transport_snapshot: dict[str, object] | None = None
|
||||
if executor is not None:
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Bounded vendor device/storage messages; no SDK client or new authentication.
|
||||
|
||||
Wire reference: XGRIDS Lixel_OpenAPI aiot_msgs.proto at
|
||||
a60a73773b0c2da3e582607ff71b32baa1238d4e. Execution belongs to the existing
|
||||
interactive control worker, exclusively at its confirmed standby checkpoint.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from enum import IntEnum
|
||||
|
||||
from .application_bootstrap import (
|
||||
ApplicationControlAuthority,
|
||||
ApplicationMessageIdentity,
|
||||
ApplicationRequestHeader,
|
||||
LiveDeviceControlBinding,
|
||||
_bytes_field,
|
||||
_encode_header,
|
||||
_text_field,
|
||||
_varint_field,
|
||||
decode_application_message_identity,
|
||||
)
|
||||
from .application_publish import OneShotPublishEnvelope
|
||||
from .modeling_control import OPENAPI_SUCCESS
|
||||
from .protobuf_wire import ProtoField, iter_fields
|
||||
|
||||
PROJECT_REQUEST = "lixel/application/request/project_list"
|
||||
PROJECT_RESPONSE = "lixel/application/response/project_list"
|
||||
CONTROL_REQUEST = "lixel/application/request/device_control"
|
||||
CONTROL_RESPONSE = "lixel/application/response/device_control"
|
||||
MAX_PROJECT_RESPONSE_BYTES = 4 * 1024 * 1024
|
||||
MAX_PROJECTS = 4096
|
||||
|
||||
|
||||
class ManagementAction(IntEnum):
|
||||
USB_MASS = 15
|
||||
USB_ETHER = 16
|
||||
DISK_FORMAT = 17
|
||||
POWER_OFF = 20
|
||||
SYSTEM_REBOOT = 22
|
||||
LIST_PROJECTS = 23
|
||||
DELETE_PROJECTS = 25
|
||||
|
||||
|
||||
OPERATIONS = {
|
||||
"projects": ManagementAction.LIST_PROJECTS,
|
||||
"delete-projects": ManagementAction.DELETE_PROJECTS,
|
||||
"format-storage": ManagementAction.DISK_FORMAT,
|
||||
"usb-storage": ManagementAction.USB_MASS,
|
||||
"usb-data": ManagementAction.USB_ETHER,
|
||||
"power-off": ManagementAction.POWER_OFF,
|
||||
"reboot": ManagementAction.SYSTEM_REBOOT,
|
||||
}
|
||||
|
||||
|
||||
def management_envelope(
|
||||
operation: str, operation_id: str, authority: ApplicationControlAuthority,
|
||||
binding: LiveDeviceControlBinding, project_ids: tuple[str, ...] = (),
|
||||
) -> OneShotPublishEnvelope:
|
||||
action = OPERATIONS[operation]
|
||||
if len(project_ids) > MAX_PROJECTS or len(set(project_ids)) != len(project_ids):
|
||||
raise ValueError("Invalid project selection")
|
||||
if (action == ManagementAction.DELETE_PROJECTS) != bool(project_ids):
|
||||
raise ValueError("Only project deletion accepts a nonempty project selection")
|
||||
if any(not value or len(value.encode("utf-8")) > 256 for value in project_ids):
|
||||
raise ValueError("Invalid project identifier")
|
||||
project_request = action in {ManagementAction.LIST_PROJECTS, ManagementAction.DELETE_PROJECTS}
|
||||
header = ApplicationRequestHeader(
|
||||
"ProjectListRequest" if project_request else "DeviceControlRequest",
|
||||
authority, binding, context=operation_id,
|
||||
)
|
||||
payload = _bytes_field(1, _encode_header(header)) + _varint_field(2, int(action))
|
||||
payload += b"".join(_text_field(3 if len(project_ids) == 1 else 5, value)
|
||||
for value in project_ids)
|
||||
return OneShotPublishEnvelope(
|
||||
operation_key=f"management:{operation_id}",
|
||||
topic=PROJECT_REQUEST if project_request else CONTROL_REQUEST,
|
||||
payload=payload, payload_sha256=hashlib.sha256(payload).hexdigest(),
|
||||
payload_bytes=len(payload), qos=2, retain=False,
|
||||
)
|
||||
|
||||
|
||||
def unique_fields(payload: bytes, *, maximum: int = 64) -> dict[int, ProtoField]:
|
||||
result: dict[int, ProtoField] = {}
|
||||
for item in iter_fields(payload, max_fields=maximum):
|
||||
if item.number in result:
|
||||
raise ValueError("Duplicate singular vendor field")
|
||||
result[item.number] = item
|
||||
return result
|
||||
|
||||
|
||||
def management_identity(payload: bytes) -> ApplicationMessageIdentity:
|
||||
"""Bound repeated project fields without widening ordinary control decoding."""
|
||||
if len(payload) > MAX_PROJECT_RESPONSE_BYTES:
|
||||
raise ValueError("Project response exceeds the bounded catalog")
|
||||
header = None
|
||||
for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32):
|
||||
if item.number == 1:
|
||||
if header is not None or item.wire_type != 2 or not isinstance(item.value, bytes):
|
||||
raise ValueError("Invalid project response header")
|
||||
header = item.value
|
||||
if header is None:
|
||||
raise ValueError("Project response header is missing")
|
||||
return decode_application_message_identity(_bytes_field(1, header))
|
||||
|
||||
|
||||
def uint(fields: dict[int, ProtoField], key: int, default: int | None = None) -> int:
|
||||
value = fields.get(key)
|
||||
if value is None and default is not None:
|
||||
return default
|
||||
if value is None or value.wire_type != 0 or not isinstance(value.value, int):
|
||||
raise ValueError("Missing vendor integer")
|
||||
return value.value
|
||||
|
||||
|
||||
def management_action(payload: bytes) -> int:
|
||||
"""Read the exact action without interpreting repeated project entries."""
|
||||
actions = [item for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32)
|
||||
if item.number == 2]
|
||||
if len(actions) != 1:
|
||||
raise ValueError("Missing or repeated management action")
|
||||
return uint({2: actions[0]}, 2)
|
||||
|
||||
|
||||
def data(fields: dict[int, ProtoField], key: int) -> bytes:
|
||||
value = fields.get(key)
|
||||
if value is None or value.wire_type != 2 or not isinstance(value.value, bytes):
|
||||
raise ValueError("Missing vendor message")
|
||||
return value.value
|
||||
|
||||
|
||||
def decode_management_response(payload: bytes, operation: str) -> dict[str, object]:
|
||||
if len(payload) > MAX_PROJECT_RESPONSE_BYTES:
|
||||
raise ValueError("Project response exceeds the bounded catalog")
|
||||
fields: dict[int, ProtoField] = {}
|
||||
projects: list[dict[str, object]] = []
|
||||
seen: set[str] = set()
|
||||
for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32):
|
||||
if item.number == 4 and operation in {"projects", "delete-projects"}:
|
||||
if not isinstance(item.value, bytes) or item.wire_type != 2:
|
||||
raise ValueError("Invalid project entry")
|
||||
project = unique_fields(item.value)
|
||||
identifier = data(project, 1).decode("utf-8")
|
||||
name = data(project, 2).decode("utf-8")
|
||||
if (not identifier or len(identifier.encode()) > 256 or len(name.encode()) > 1024
|
||||
or identifier in seen or len(projects) >= MAX_PROJECTS):
|
||||
raise ValueError("Invalid or duplicate project identity")
|
||||
seen.add(identifier)
|
||||
# URLs, directory JSON and file paths never cross the product boundary.
|
||||
projects.append({"id": identifier, "name": name})
|
||||
else:
|
||||
if item.number in fields:
|
||||
raise ValueError("Duplicate management response field")
|
||||
fields[item.number] = item
|
||||
if uint(fields, 2) != int(OPERATIONS[operation]):
|
||||
raise ValueError("Vendor response belongs to another command")
|
||||
code = uint(unique_fields(data(fields, 15)), 1)
|
||||
return {"status": "succeeded" if code == OPENAPI_SUCCESS else "rejected",
|
||||
"result_code": code, **({"projects": projects} if operation == "projects" else {})}
|
||||
|
||||
|
||||
def decode_storage_mode(payload: bytes) -> dict[str, object]:
|
||||
"""DeviceInfo owns observed mode; an accepted mode command is not evidence."""
|
||||
top = unique_fields(payload)
|
||||
if uint(unique_fields(data(top, 15)), 1) != OPENAPI_SUCCESS:
|
||||
raise ValueError("DeviceInfo rejected")
|
||||
device = unique_fields(data(top, 2))
|
||||
working = unique_fields(data(device, 7))
|
||||
mass = uint(working, 4, 0)
|
||||
if mass not in {0, 1}:
|
||||
raise ValueError("Invalid USB mode")
|
||||
storage = unique_fields(data(device, 10)) if 10 in device else {}
|
||||
storage_code = uint(storage, 1, 0)
|
||||
storage_type = (storage_code >> 1) ^ -(storage_code & 1)
|
||||
return {"usb_mode": "storage" if mass else "data",
|
||||
"storage_type": {0: "internal", 1: "microSD", 2: "external-usb"}.get(
|
||||
storage_type, "unknown") if 10 in device else "unknown"}
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Explicit maintenance work on the existing control worker, never a second client."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from .application_bootstrap import (
|
||||
DEVICE_INFO_REQUEST_TOPIC,
|
||||
ApplicationControlAuthority,
|
||||
ApplicationRequestHeader,
|
||||
LiveDeviceControlBinding,
|
||||
_bytes_field,
|
||||
_encode_header,
|
||||
)
|
||||
from .application_publish import OneShotPublishEnvelope
|
||||
from .device_management import decode_management_response, decode_storage_mode, management_envelope
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .application_mqtt import ReviewedApplicationMqttTransport
|
||||
|
||||
|
||||
@dataclass
|
||||
class MaintenanceJob:
|
||||
operation: str
|
||||
identifier: str
|
||||
project_ids: tuple[str, ...]
|
||||
generation: int
|
||||
revision: int
|
||||
deadline: float
|
||||
catalog_revision: str | None = None
|
||||
finished: threading.Event = field(default_factory=threading.Event)
|
||||
result: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class ManagementMailbox:
|
||||
def __init__(self) -> None:
|
||||
self.lock = threading.Lock()
|
||||
self.pending: MaintenanceJob | None = None
|
||||
self.block_start = False
|
||||
self.mode: dict[str, object] = {}
|
||||
self.generation = -1
|
||||
self.catalog_revision: str | None = None
|
||||
self.project_ids: set[str] = set()
|
||||
|
||||
def submit(self, job: MaintenanceJob) -> dict[str, Any]:
|
||||
with self.lock:
|
||||
if self.pending is not None:
|
||||
raise ValueError("Другая операция K1 ещё выполняется")
|
||||
self.pending = job
|
||||
if not job.finished.wait(max(0.0, job.deadline - time.monotonic()) + 1):
|
||||
# An expired queued job can never be published later. A dispatch
|
||||
# already on the wire stays unknown and is never retried here.
|
||||
return {"status": "unknown", "message": "K1 не подтвердил результат операции"}
|
||||
return job.result or {"status": "unknown"}
|
||||
|
||||
def cancel_queued(self) -> None:
|
||||
"""Called by the sole worker only after any in-flight pump has ended."""
|
||||
with self.lock:
|
||||
job, self.pending = self.pending, None
|
||||
if job is not None:
|
||||
job.result = {"status": "blocked", "message": "Управляющее соединение K1 закрыто"}
|
||||
job.finished.set()
|
||||
|
||||
def pump(
|
||||
self, transport: ReviewedApplicationMqttTransport,
|
||||
authority: ApplicationControlAuthority, binding: LiveDeviceControlBinding,
|
||||
validate: Callable[[MaintenanceJob], None],
|
||||
) -> None:
|
||||
with self.lock:
|
||||
job = self.pending
|
||||
if job is None:
|
||||
return
|
||||
dispatched = False
|
||||
deleted: list[str] = []
|
||||
try:
|
||||
validate(job)
|
||||
if time.monotonic() >= job.deadline:
|
||||
raise ValueError("Время ожидания операции истекло до отправки")
|
||||
if not transport.standby_complete(binding):
|
||||
raise ValueError("K1 не подтвердил завершение съёмки. Остановите запись")
|
||||
if job.operation == "delete-projects" and (
|
||||
job.generation != self.generation or not self.catalog_revision
|
||||
or job.catalog_revision != self.catalog_revision
|
||||
or not set(job.project_ids) <= self.project_ids
|
||||
):
|
||||
raise ValueError("Список проектов изменился. Обновите его перед удалением")
|
||||
|
||||
def expired() -> bool:
|
||||
validate(job)
|
||||
return time.monotonic() >= job.deadline
|
||||
|
||||
def mark_dispatched() -> None:
|
||||
nonlocal dispatched
|
||||
dispatched = True
|
||||
|
||||
def exchange(envelope: OneShotPublishEnvelope) -> bytes:
|
||||
return transport.exchange_batch_once(
|
||||
(envelope,), required_response_operation_keys=(envelope.operation_key,),
|
||||
dispatch_admission_deadline_reached=expired,
|
||||
dispatch_admission_commit=mark_dispatched,
|
||||
)[envelope.operation_key]
|
||||
|
||||
result: dict[str, Any]
|
||||
if job.operation == "info":
|
||||
result = {"status": "succeeded"}
|
||||
else:
|
||||
if job.operation in {"delete-projects", "format-storage"}:
|
||||
self.catalog_revision = None
|
||||
# The qualified K1 firmware accepts the singular project ID but
|
||||
# rejects the newer repeated-ID request. Keep group selection in
|
||||
# this same fenced worker and await each ordinary vendor reply.
|
||||
selections = [(value,) for value in job.project_ids] if (
|
||||
job.operation == "delete-projects"
|
||||
) else [job.project_ids]
|
||||
for index, selection in enumerate(selections):
|
||||
envelope = management_envelope(
|
||||
job.operation, f"{job.identifier}-{index}", authority, binding, selection,
|
||||
)
|
||||
result = decode_management_response(exchange(envelope), job.operation)
|
||||
if result["status"] != "succeeded":
|
||||
if job.operation == "delete-projects":
|
||||
result["message"] = (
|
||||
f"Удалено {len(deleted)} из {len(job.project_ids)}. "
|
||||
"K1 отклонил следующее удаление. Обновите список проектов."
|
||||
)
|
||||
break
|
||||
if job.operation == "delete-projects":
|
||||
deleted.extend(selection)
|
||||
if job.operation == "delete-projects":
|
||||
result["deleted_project_ids"] = deleted
|
||||
if result["status"] == "succeeded" and job.operation == "projects":
|
||||
projects = cast(list[dict[str, str]], result["projects"])
|
||||
self.project_ids = {item["id"] for item in projects}
|
||||
self.catalog_revision = hashlib.sha256(
|
||||
json.dumps([job.generation, result["projects"]], sort_keys=True).encode()
|
||||
).hexdigest()
|
||||
result["catalog_revision"] = self.catalog_revision
|
||||
if result["status"] == "succeeded" and job.operation not in {"power-off", "reboot"}:
|
||||
header = ApplicationRequestHeader("DeviceInfoRequest", authority, binding,
|
||||
context=job.identifier + "-info")
|
||||
payload = _bytes_field(1, _encode_header(header))
|
||||
envelope = OneShotPublishEnvelope(
|
||||
"management-info:" + job.identifier, DEVICE_INFO_REQUEST_TOPIC,
|
||||
payload, hashlib.sha256(payload).hexdigest(), len(payload), 2, False,
|
||||
)
|
||||
mode = decode_storage_mode(exchange(envelope))
|
||||
self.mode, self.generation = mode, job.generation
|
||||
self.block_start = mode["usb_mode"] == "storage"
|
||||
result.update(mode)
|
||||
elif result["status"] == "succeeded":
|
||||
self.block_start = True
|
||||
job.result = result
|
||||
except Exception as exc:
|
||||
if dispatched and job.operation not in {"info", "projects"}:
|
||||
self.block_start = True
|
||||
# A lost reply is not a rejected command. Never retry a write.
|
||||
job.result = {
|
||||
"status": "unknown" if dispatched else "blocked",
|
||||
"message": ("K1 не подтвердил результат. Проверьте состояние устройства."
|
||||
if dispatched else str(exc)),
|
||||
**({"deleted_project_ids": deleted} if job.operation == "delete-projects" else {}),
|
||||
}
|
||||
finally:
|
||||
with self.lock:
|
||||
self.pending = None
|
||||
job.finished.set()
|
||||
@@ -188,8 +188,8 @@ class DeviceStatusReport:
|
||||
"""Recovered acquisition subset of ``DeviceStatusReport``.
|
||||
|
||||
Vendor identity and project strings are intentionally redacted from repr.
|
||||
Nested system/RTK messages are bounded by the outer parser but are not
|
||||
interpreted by this modeling state machine.
|
||||
Storage occupancy is optional display telemetry; nested system/RTK messages
|
||||
never decide this modeling state machine.
|
||||
"""
|
||||
|
||||
header: ObservedHeader | None = field(repr=False)
|
||||
@@ -201,6 +201,7 @@ class DeviceStatusReport:
|
||||
init_ready: bool
|
||||
system_status_present: bool
|
||||
rtk_status_present: bool
|
||||
storage_used_percent: float | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -338,6 +339,7 @@ def decode_device_status_report(
|
||||
init_ready = False
|
||||
system_status_present = False
|
||||
rtk_status_present = False
|
||||
storage_used_percent = None
|
||||
seen: set[int] = set()
|
||||
try:
|
||||
for proto_field in iter_fields(payload, max_fields=64):
|
||||
@@ -366,7 +368,8 @@ def decode_device_status_report(
|
||||
init_ready = bool(raw_ready)
|
||||
elif proto_field.number == 7:
|
||||
_mark_once(seen, 7, "device_status.system_status")
|
||||
_bytes_value(proto_field, "device_status.system_status")
|
||||
system = _bytes_value(proto_field, "device_status.system_status")
|
||||
storage_used_percent = _storage_used_percent(system)
|
||||
system_status_present = True
|
||||
elif proto_field.number == 8:
|
||||
_mark_once(seen, 8, "device_status.rtk_status")
|
||||
@@ -387,9 +390,32 @@ def decode_device_status_report(
|
||||
init_ready=init_ready,
|
||||
system_status_present=system_status_present,
|
||||
rtk_status_present=rtk_status_present,
|
||||
storage_used_percent=storage_used_percent,
|
||||
)
|
||||
|
||||
|
||||
def _storage_used_percent(payload: bytes) -> float | None:
|
||||
"""Optional display telemetry from reviewed SystemStatus fields 4/5.
|
||||
|
||||
Units are not inferred; only the dimensionless ratio is exposed. Invalid
|
||||
auxiliary telemetry must not change the existing acquisition state machine.
|
||||
Proto3 may omit DiskUsed when it is zero.
|
||||
"""
|
||||
values: dict[int, int] = {}
|
||||
try:
|
||||
for field in iter_fields(payload, max_fields=64):
|
||||
if field.number in {4, 5}:
|
||||
if field.number in values:
|
||||
return None
|
||||
values[field.number] = _uint_value(
|
||||
field, "system_status.storage", max_value=(1 << 63) - 1
|
||||
)
|
||||
except ValueError:
|
||||
return None
|
||||
total, used = values.get(4, 0), values.get(5, 0)
|
||||
return 100.0 * used / total if total > 0 and used <= total else None
|
||||
|
||||
|
||||
def session_state_from_code(code: int) -> SessionState | None:
|
||||
"""Map the captured base-offset status code, preserving unknown values."""
|
||||
|
||||
|
||||
@@ -23,12 +23,12 @@ SEMANTIC_TOPOLOGY_LOCK_FILENAME = ".semantic-topology.lock"
|
||||
SEMANTIC_TOPOLOGY_MAX_BYTES = 16 * 1024
|
||||
SEMANTIC_TOPOLOGY_MAX_REVISION = (1 << 63) - 1
|
||||
|
||||
TopologyConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
|
||||
TopologyEvidenceSource = Literal["ble-post-write-status", "ble-read-only-status"]
|
||||
TopologyConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
|
||||
TopologyEvidenceSource = Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"]
|
||||
SemanticTopologyStoreStatus = Literal["empty", "available", "corrupt"]
|
||||
|
||||
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
|
||||
_EVIDENCE_SOURCES = frozenset({"ble-post-write-status", "ble-read-only-status"})
|
||||
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
|
||||
_EVIDENCE_SOURCES = frozenset({"ble-post-write-status", "ble-read-only-status", "usb-enumeration"})
|
||||
_SAFE_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:+-]{0,159}$")
|
||||
_SAFE_FIRMWARE_VERSION = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+() -]{0,63}$")
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Read-only Linux USB Ethernet discovery for the physically qualified K1.
|
||||
|
||||
Addresses come from the device's DHCP lease, never from a product default.
|
||||
Enumeration is only a candidate: the existing DeviceInfo/identity admission
|
||||
must still succeed before any acquisition command can be sent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
from .linux_host import _run, nm_fields
|
||||
|
||||
|
||||
class NetworkObservationRunner(Protocol):
|
||||
def __call__(self, args: list[str], *, timeout: float) -> str: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UsbNetworkAttachment:
|
||||
transport_ref: str
|
||||
interface: str
|
||||
peer_ipv4: str
|
||||
source_ipv4: str
|
||||
generation: str
|
||||
speed: str
|
||||
|
||||
|
||||
class LinuxK1UsbProbe:
|
||||
"""Observe an already enumerated RNDIS interface; never configure the OS."""
|
||||
|
||||
def __init__(
|
||||
self, sys_net: Path = Path("/sys/class/net"),
|
||||
runner: NetworkObservationRunner | None = None,
|
||||
) -> None:
|
||||
self.sys_net = sys_net
|
||||
self.run = runner or _run
|
||||
|
||||
def discover(self) -> tuple[UsbNetworkAttachment, ...]:
|
||||
found = []
|
||||
for interface in sorted(self.sys_net.iterdir()):
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.:-]{1,64}", interface.name):
|
||||
continue
|
||||
try:
|
||||
attachment = self._read(interface)
|
||||
except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
|
||||
continue
|
||||
if attachment is not None:
|
||||
found.append(attachment)
|
||||
# Same serial or same peer on multiple links is not an exact route.
|
||||
# Supporting those devices requires explicit routing isolation first.
|
||||
return tuple(
|
||||
item for item in found
|
||||
if sum(other.transport_ref == item.transport_ref for other in found) == 1
|
||||
and sum(other.peer_ipv4 == item.peer_ipv4 for other in found) == 1
|
||||
)
|
||||
|
||||
def require(self, transport_ref: str) -> UsbNetworkAttachment:
|
||||
matches = [item for item in self.discover() if item.transport_ref == transport_ref]
|
||||
if len(matches) != 1:
|
||||
raise OSError("USB K1 не найден. Проверьте питание и USB-кабель.")
|
||||
return matches[0]
|
||||
|
||||
def _read(self, interface: Path) -> UsbNetworkAttachment | None:
|
||||
device = (interface / "device").resolve(strict=True)
|
||||
usb = next((parent for parent in (device, *device.parents)
|
||||
if (parent / "idVendor").is_file()), None)
|
||||
if usb is None or (usb / "idVendor").read_text().strip().lower() != "2207":
|
||||
return None
|
||||
if (usb / "idProduct").read_text().strip().lower() != "0019":
|
||||
return None
|
||||
if (usb / "product").read_text().strip() != "XGRIDS Device":
|
||||
return None
|
||||
if (device / "driver").resolve(strict=True).name != "rndis_host":
|
||||
return None
|
||||
serial = (usb / "serial").read_text().strip()
|
||||
if not serial or len(serial) > 128 or (interface / "carrier").read_text().strip() != "1":
|
||||
return None
|
||||
options = self.run([
|
||||
"nmcli", "-t", "--escape", "yes", "-f", "DHCP4.OPTION",
|
||||
"device", "show", interface.name,
|
||||
], timeout=2)
|
||||
peers = set()
|
||||
for line in options.splitlines():
|
||||
fields = nm_fields(line)
|
||||
if len(fields) != 2:
|
||||
continue
|
||||
key, separator, value = fields[1].partition(" = ")
|
||||
if separator and key.strip() == "dhcp_server_identifier":
|
||||
peer = ipaddress.IPv4Address(value.strip())
|
||||
if peer.is_private and not (peer.is_loopback or peer.is_link_local
|
||||
or peer.is_multicast or peer.is_unspecified):
|
||||
peers.add(str(peer))
|
||||
if len(peers) != 1:
|
||||
return None
|
||||
peer_ipv4 = peers.pop()
|
||||
routes = json.loads(self.run(["ip", "-j", "route", "get", peer_ipv4], timeout=2))
|
||||
if not isinstance(routes, list) or len(routes) != 1:
|
||||
return None
|
||||
route = routes[0]
|
||||
if (route.get("dev") != interface.name or route.get("gateway")
|
||||
or route.get("type", "unicast") != "unicast"):
|
||||
return None
|
||||
source = str(ipaddress.IPv4Address(route["prefsrc"]))
|
||||
generation = hashlib.sha256(json.dumps([
|
||||
serial, str(usb), (usb / "busnum").read_text().strip(),
|
||||
(usb / "devnum").read_text().strip(), (interface / "ifindex").read_text().strip(),
|
||||
usb.stat().st_ino, source, peer_ipv4,
|
||||
]).encode()).hexdigest()
|
||||
return UsbNetworkAttachment(
|
||||
transport_ref="usb:" + hashlib.sha256(serial.encode()).hexdigest(),
|
||||
interface=interface.name, peer_ipv4=peer_ipv4, source_ipv4=source,
|
||||
generation=generation, speed=(usb / "speed").read_text().strip(),
|
||||
)
|
||||
@@ -13,7 +13,7 @@ from datetime import UTC, datetime
|
||||
|
||||
from .trust import PairingError
|
||||
|
||||
ACTIONS = {"scan", "networks", "connect", "verify"}
|
||||
ACTIONS = {"scan", "networks", "connect", "verify", "reset"}
|
||||
|
||||
|
||||
def validate(value):
|
||||
@@ -45,10 +45,16 @@ def validate(value):
|
||||
expected = {"device_id", "discovery_generation", "mode_revision"}
|
||||
if value["action"] == "connect":
|
||||
expected |= {"ssid", "password"}
|
||||
elif value["action"] == "reset":
|
||||
expected = {"mode_revision"}
|
||||
elif value["action"] in {"scan", "networks"}:
|
||||
expected = set()
|
||||
if not isinstance(parameters, dict) or set(parameters) != expected:
|
||||
raise PairingError("Неверные параметры подключения.")
|
||||
if value["action"] == "reset" and (
|
||||
type(parameters["mode_revision"]) is not int or parameters["mode_revision"] < 0
|
||||
):
|
||||
raise PairingError("Обновите состояние подключения.")
|
||||
if "device_id" in expected and (
|
||||
not isinstance(parameters["device_id"], str)
|
||||
or not 1 <= len(parameters["device_id"]) <= 128
|
||||
|
||||
@@ -15,6 +15,7 @@ ACTIONS = {
|
||||
"details",
|
||||
"rename",
|
||||
"verify",
|
||||
"management",
|
||||
"start",
|
||||
"replay",
|
||||
"stop",
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
"""Adaptive disposable camera preview from the acquisition's existing MP4 lease.
|
||||
|
||||
The archive and RTSP producer remain owned by acquisition. Only decoded latest
|
||||
frames cross the preview budget; network stalls cannot queue encoded capture.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import logging
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from fractions import Fraction
|
||||
from uuid import uuid4
|
||||
|
||||
import av
|
||||
from aiortc import (
|
||||
RTCConfiguration,
|
||||
RTCPeerConnection,
|
||||
RTCRtpSender,
|
||||
RTCSessionDescription,
|
||||
VideoStreamTrack,
|
||||
)
|
||||
from aiortc.mediastreams import MediaStreamError
|
||||
from missioncore_plugin_sdk.link_budget import budget_peer
|
||||
from missioncore_plugin_sdk.media_budget import adapt_peer, cap_video_sender
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def open_live_camera(reader):
|
||||
# The MP4 initialization already declares the codec. Bound stream analysis
|
||||
# so avformat does not wait for seconds of future live samples.
|
||||
return av.open(reader, format="mp4", mode="r",
|
||||
options={"probesize": "32", "analyzeduration": "1"})
|
||||
|
||||
|
||||
class LeaseReader(io.RawIOBase):
|
||||
def __init__(self, lease, stopped):
|
||||
self.lease, self.stopped, self.pending = lease, stopped, b""
|
||||
self.ended = False
|
||||
|
||||
def readable(self):
|
||||
return True
|
||||
|
||||
def read(self, size=-1):
|
||||
if self.ended:
|
||||
return b""
|
||||
if size < 0:
|
||||
size = 32768
|
||||
# A pipe read may be short. Waiting to fill FFmpeg's requested buffer
|
||||
# holds a complete live fragment until future frames arrive.
|
||||
while len(self.pending) < size and not self.stopped.is_set():
|
||||
try:
|
||||
segment = self.lease.segments.get(timeout=0 if self.pending else 0.25)
|
||||
except queue.Empty:
|
||||
if self.pending:
|
||||
break
|
||||
continue
|
||||
if segment is None:
|
||||
self.ended = True
|
||||
break
|
||||
self.pending += segment[1]
|
||||
result, self.pending = self.pending[:size], self.pending[size:]
|
||||
return result
|
||||
|
||||
|
||||
class CameraSource:
|
||||
def __init__(self, camera):
|
||||
self.camera = camera
|
||||
self.closed = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.frame = None
|
||||
self.sequence = 0
|
||||
self.observed = 0.0
|
||||
self.started = time.monotonic()
|
||||
self.thread = threading.Thread(target=self.pump, name="k1-camera-preview", daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def current(self):
|
||||
with self.lock:
|
||||
return self.sequence, self.frame, self.observed
|
||||
|
||||
def pump(self):
|
||||
while not self.closed.is_set():
|
||||
lease = None
|
||||
try:
|
||||
state = self.camera.snapshot()
|
||||
recording = state.get("recording") or {}
|
||||
if recording.get("source_end_expected"):
|
||||
break
|
||||
if not (
|
||||
recording.get("active")
|
||||
and recording.get("producer_alive")
|
||||
and recording.get("media_ready")
|
||||
and recording.get("active_epoch") == state.get("generation")
|
||||
):
|
||||
self.closed.wait(0.25)
|
||||
continue
|
||||
lease = self.camera.open_delivery(state["generation"], require_recording=True)
|
||||
with open_live_camera(LeaseReader(lease, self.closed)) as container:
|
||||
stream = container.streams.video[0]
|
||||
stream.codec_context.thread_count = 1
|
||||
for packet in container.demux(stream):
|
||||
if self.closed.is_set():
|
||||
break
|
||||
try:
|
||||
frames = packet.decode()
|
||||
except av.error.InvalidDataError:
|
||||
continue # A late observer awaits the next capture keyframe.
|
||||
for frame in frames:
|
||||
now = time.monotonic()
|
||||
if not (0 < frame.width <= 4096 and 0 < frame.height <= 2160):
|
||||
raise ValueError("Camera preview dimensions exceed bound")
|
||||
if now - self.observed < 1 / 15:
|
||||
continue
|
||||
width = min(1280, frame.width) // 2 * 2
|
||||
height = max(2, round(frame.height * width / frame.width) // 2 * 2)
|
||||
frame = frame.reformat(width=width, height=height, format="yuv420p")
|
||||
frame.pts, frame.time_base = (
|
||||
round((now - self.started) * 90000),
|
||||
Fraction(1, 90000),
|
||||
)
|
||||
with self.lock:
|
||||
self.sequence += 1
|
||||
self.frame, self.observed = frame, now
|
||||
self.camera.mark_streaming(lease)
|
||||
except (OSError, ValueError, RuntimeError, IndexError) as error:
|
||||
logger.debug("K1 camera observer awaiting producer (%s)", type(error).__name__)
|
||||
finally:
|
||||
if lease is not None:
|
||||
self.camera.release_delivery(lease, client_closed=True)
|
||||
self.closed.wait(0.25)
|
||||
self.closed.set()
|
||||
with self.lock:
|
||||
self.frame = None
|
||||
|
||||
def close(self):
|
||||
self.closed.set()
|
||||
|
||||
|
||||
class CameraTrack(VideoStreamTrack):
|
||||
def __init__(self, source, budget):
|
||||
super().__init__()
|
||||
self.source, self.budget, self.sequence, self.next_at = source, budget, 0, 0.0
|
||||
|
||||
async def recv(self):
|
||||
while self.readyState == "live" and not self.source.closed.is_set():
|
||||
await asyncio.sleep(max(0, self.next_at - time.monotonic()))
|
||||
width, fps = self.budget.video()
|
||||
sequence, frame, observed = self.source.current()
|
||||
if (
|
||||
fps
|
||||
and frame is not None
|
||||
and sequence > self.sequence
|
||||
and time.monotonic() - observed < 2
|
||||
):
|
||||
self.sequence, self.next_at = sequence, time.monotonic() + 1 / fps
|
||||
width = min(frame.width, width)
|
||||
height = max(2, round(frame.height * width / frame.width) // 2 * 2)
|
||||
resized = frame.reformat(width=width, height=height, format="yuv420p")
|
||||
# Encoder keyframe requests must not mutate a shared source frame.
|
||||
result = av.VideoFrame.from_ndarray(
|
||||
resized.to_ndarray(format="yuv420p"), format="yuv420p"
|
||||
)
|
||||
result.pts, result.time_base = frame.pts, frame.time_base
|
||||
return result
|
||||
await asyncio.sleep(0.025)
|
||||
raise MediaStreamError
|
||||
|
||||
|
||||
async def camera_offer(peers, parameters):
|
||||
from .node_media import admit_sdp
|
||||
|
||||
admit_sdp(parameters.get("sdp"), camera=True)
|
||||
if sum(entry.get("media") == "camera" for entry in peers.items.values()) >= 2:
|
||||
raise ValueError("Close another camera viewer")
|
||||
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
|
||||
identifier = "peer_" + uuid4().hex
|
||||
entry = {
|
||||
"pc": pc,
|
||||
"seen": time.monotonic(),
|
||||
"tasks": [],
|
||||
"media": "camera",
|
||||
"view_id": parameters.get("view_id"),
|
||||
}
|
||||
peers.items[identifier] = entry
|
||||
source = getattr(peers, "camera_source", None)
|
||||
if source is None or source.closed.is_set():
|
||||
source = peers.camera_source = CameraSource(peers.camera)
|
||||
entry["source"] = source
|
||||
|
||||
@pc.on("datachannel")
|
||||
def channel_open(channel):
|
||||
if channel.label != "sensor":
|
||||
channel.close()
|
||||
return
|
||||
|
||||
@channel.on("message")
|
||||
def message(value):
|
||||
if value == "keepalive":
|
||||
entry["seen"] = time.monotonic()
|
||||
|
||||
@pc.on("connectionstatechange")
|
||||
async def changed():
|
||||
if pc.connectionState in {"closed", "failed"}:
|
||||
await peers.close(identifier)
|
||||
|
||||
async def watchdog():
|
||||
while identifier in peers.items:
|
||||
if source.closed.is_set() or time.monotonic() - entry["seen"] > 30:
|
||||
await peers.close(identifier)
|
||||
return
|
||||
await asyncio.sleep(1)
|
||||
|
||||
try:
|
||||
budget = await adapt_peer(pc, "video")
|
||||
entry["budget"] = budget
|
||||
track = CameraTrack(source, budget)
|
||||
entry["track"] = track
|
||||
sender = pc.addTrack(track)
|
||||
cap_video_sender(sender, budget)
|
||||
pc.getTransceivers()[0].setCodecPreferences(
|
||||
[
|
||||
codec
|
||||
for codec in RTCRtpSender.getCapabilities("video").codecs
|
||||
if codec.mimeType.lower() in {"video/h264", "video/rtx"}
|
||||
]
|
||||
)
|
||||
await pc.setRemoteDescription(RTCSessionDescription(sdp=parameters["sdp"], type="offer"))
|
||||
budget_peer(pc, "video", producer_id=budget.id)
|
||||
await pc.setLocalDescription(await pc.createAnswer())
|
||||
entry["tasks"].append(asyncio.create_task(watchdog()))
|
||||
return {
|
||||
"peer_id": identifier,
|
||||
"sdp": pc.localDescription.sdp,
|
||||
"type": "answer",
|
||||
"transport": "webrtc-video",
|
||||
}
|
||||
except BaseException:
|
||||
await peers.close(identifier)
|
||||
raise
|
||||
@@ -109,3 +109,19 @@ def test_duplicate_id_cannot_replace_original_secret():
|
||||
duplicate["parameters"]["password"] += "changed"
|
||||
bus.submit(fleet, "vehicle", duplicate)
|
||||
assert bus.pending[("vehicle", request["operation_id"])]["payload"] == request
|
||||
|
||||
|
||||
def test_reset_accepts_only_a_mode_revision_without_credentials_or_physical_action():
|
||||
value = command()
|
||||
value.update(action="reset", parameters={"mode_revision": 7})
|
||||
validate(value)
|
||||
for parameters in (
|
||||
{},
|
||||
{"mode_revision": True},
|
||||
{"mode_revision": -1},
|
||||
{"mode_revision": "7"},
|
||||
{"mode_revision": 7, "device_id": "x"},
|
||||
{"mode_revision": 7, "password": "synthetic"},
|
||||
):
|
||||
with pytest.raises(PairingError):
|
||||
validate({**value, "parameters": parameters})
|
||||
|
||||
@@ -49,6 +49,21 @@ def test_pending_commands_still_have_the_original_32_slot_limit():
|
||||
sensors.submit(fleet, "vehicle", request())
|
||||
|
||||
|
||||
def test_k1_management_uses_existing_queue_and_deduplicates_dispatch():
|
||||
fleet = Fleet()
|
||||
value = {**request(), "action_id": "management", "parameters": {
|
||||
"operation": "projects", "control_generation": 3, "control_revision": 7,
|
||||
}}
|
||||
receipt = sensors.submit(fleet, "vehicle", value)
|
||||
assert sensors.submit(fleet, "vehicle", value) is receipt
|
||||
assert sensors.heartbeat(fleet.row, {})["sensor_commands"] == [value]
|
||||
result = sensors.heartbeat(fleet.row, {"sensor_results": [{
|
||||
"command": value, "state": "complete", "result": {"status": "succeeded", "projects": []},
|
||||
}]})
|
||||
assert result["sensor_commands"] == []
|
||||
assert result["sensor_acknowledgements"] == [value["operation_id"]]
|
||||
|
||||
|
||||
def test_receipt_storage_is_bounded_and_only_expired_terminal_receipts_are_reclaimable():
|
||||
fleet = Fleet()
|
||||
for _ in range(sensors.MAX_COMMAND_RECEIPTS):
|
||||
|
||||
@@ -97,7 +97,7 @@ def test_lost_invocation_is_observed_once_and_never_resubmitted(journaled):
|
||||
if journaled:
|
||||
current["operations"] = [
|
||||
{
|
||||
"operation_id": identifier,
|
||||
"operation_id": parameters["operation_id"],
|
||||
"status": "failed",
|
||||
"error": {"code": "k1-wifi-network-not-found"},
|
||||
}
|
||||
@@ -161,6 +161,7 @@ def test_delivery_distinguishes_pre_dispatch_rejection_from_lost_result():
|
||||
result = await bridge.deliver(request)
|
||||
assert result["command_result"] == {
|
||||
"operation_id": request["operation_id"],
|
||||
"action": "connect",
|
||||
"status": "rejected",
|
||||
"error_code": "runtime-changed",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from test_xgrids_application_mqtt import FakeControlClient, _binding
|
||||
|
||||
from k1link.device_plugins.xgrids_k1.device_management import DeviceManagementRequest
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
ApplicationControlAuthority,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
_bytes_field as blob,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
_text_field as text,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
||||
_varint_field as uint,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_mqtt import (
|
||||
ApplicationCommandOutcomeUnknown,
|
||||
ReviewedApplicationMqttTransport,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.application_session import (
|
||||
ApplicationConnectionBinding,
|
||||
InteractiveApplicationControlSession,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.device_management import (
|
||||
CONTROL_RESPONSE,
|
||||
PROJECT_RESPONSE,
|
||||
decode_management_response,
|
||||
decode_storage_mode,
|
||||
management_action,
|
||||
management_envelope,
|
||||
management_identity,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.management_mailbox import (
|
||||
MaintenanceJob,
|
||||
ManagementMailbox,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.protocol.modeling_control import OPENAPI_SUCCESS
|
||||
from k1link.device_plugins.xgrids_k1.protocol.protobuf_wire import iter_fields
|
||||
|
||||
|
||||
def envelope(operation="projects", ids=()):
|
||||
return management_envelope(operation, "synthetic-op", ApplicationControlAuthority(
|
||||
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), ids)
|
||||
|
||||
|
||||
def response(operation="projects", projects=()):
|
||||
request = envelope(operation, ("synthetic",) if operation == "delete-projects" else ())
|
||||
header = next(item.value for item in iter_fields(request.payload) if item.number == 1)
|
||||
return (blob(1, header) + uint(2, management_action(request.payload))
|
||||
+ b"".join(blob(4, text(1, ident) + text(2, name) + text(12, "private-url"))
|
||||
for ident, name in projects)
|
||||
+ blob(15, uint(1, OPENAPI_SUCCESS)))
|
||||
|
||||
|
||||
def info(*, storage=False, storage_type=1):
|
||||
return blob(2, blob(7, uint(4, int(storage))) + blob(10, uint(1, storage_type * 2))) \
|
||||
+ blob(15, uint(1, OPENAPI_SUCCESS))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation,code", [
|
||||
("usb-storage", 15), ("usb-data", 16), ("format-storage", 17),
|
||||
("power-off", 20), ("reboot", 22), ("projects", 23), ("delete-projects", 25),
|
||||
])
|
||||
def test_vendor_actions_and_exact_single_or_batch_delete(operation, code):
|
||||
request = envelope(operation, ("one",) if operation == "delete-projects" else ())
|
||||
assert management_action(request.payload) == code
|
||||
assert request.qos == 2 and not request.retain
|
||||
if operation == "delete-projects":
|
||||
assert [p.number for p in iter_fields(request.payload)] == [1, 2, 3]
|
||||
assert [p.number for p in iter_fields(envelope(operation, ("one", "two")).payload)] \
|
||||
== [1, 2, 5, 5]
|
||||
|
||||
|
||||
def test_large_catalog_retains_names_only_and_rejects_duplicate_ids():
|
||||
raw = response(projects=[(str(i), f"Проект {i}") for i in range(100)])
|
||||
assert management_identity(raw).session_id.endswith(":synthetic-op")
|
||||
result = decode_management_response(raw, "projects")
|
||||
assert len(result["projects"]) == 100
|
||||
assert result["projects"][0] == {"id": "0", "name": "Проект 0"}
|
||||
with pytest.raises(ValueError, match="duplicate"):
|
||||
decode_management_response(response(projects=[("one", "A"), ("one", "B")]), "projects")
|
||||
|
||||
|
||||
def test_mode_is_observed_and_never_inferred_from_command():
|
||||
assert decode_storage_mode(info(storage=True)) == {
|
||||
"usb_mode": "storage", "storage_type": "microSD",
|
||||
}
|
||||
assert decode_storage_mode(info())["usb_mode"] == "data"
|
||||
with pytest.raises(ValueError):
|
||||
decode_storage_mode(response("usb-storage"))
|
||||
|
||||
|
||||
def test_mismatched_action_cannot_satisfy_same_session_response():
|
||||
request = envelope("reboot")
|
||||
fake = FakeControlClient(response_topic=CONTROL_RESPONSE)
|
||||
transport = ReviewedApplicationMqttTransport("192.168.1.20", client_factory=lambda: fake)
|
||||
transport.open()
|
||||
# Same identity, wrong action: neither UI success nor control proof.
|
||||
fake.events.append(("message", (CONTROL_RESPONSE, response("power-off"))))
|
||||
with pytest.raises(ApplicationCommandOutcomeUnknown):
|
||||
transport.exchange_batch_once([request],
|
||||
required_response_operation_keys={request.operation_key})
|
||||
assert transport.snapshot().correlated_responses == 0
|
||||
|
||||
|
||||
def test_management_dispatch_commit_runs_with_physical_observer_noop():
|
||||
fake = FakeControlClient(response_topic=PROJECT_RESPONSE)
|
||||
transport = ReviewedApplicationMqttTransport("192.168.1.20", client_factory=lambda: fake)
|
||||
transport.install_evidence_observer(SimpleNamespace(
|
||||
publish_dispatching=lambda *a, **kw: None, publish_result=lambda *a, **kw: None,
|
||||
qos2_completed=lambda *a: None, application_response=lambda *a: None,
|
||||
))
|
||||
transport.open()
|
||||
commits = []
|
||||
request = envelope()
|
||||
transport.exchange_batch_once([request],
|
||||
required_response_operation_keys={request.operation_key},
|
||||
dispatch_admission_commit=lambda: commits.append(True))
|
||||
transport.close()
|
||||
assert commits == [True]
|
||||
|
||||
|
||||
class MailboxTransport:
|
||||
def __init__(self, *, standby=True, lose_reply=False):
|
||||
self.standby, self.lose_reply, self.sent = standby, lose_reply, []
|
||||
|
||||
def standby_complete(self, binding):
|
||||
return self.standby
|
||||
|
||||
def exchange_batch_once(self, batch, **kwargs):
|
||||
assert not kwargs["dispatch_admission_deadline_reached"]()
|
||||
kwargs["dispatch_admission_commit"]()
|
||||
self.sent.append(batch[0])
|
||||
if self.lose_reply:
|
||||
raise TimeoutError()
|
||||
raw = info() if batch[0].operation_key.startswith("management-info:") else response()
|
||||
return {batch[0].operation_key: raw}
|
||||
|
||||
|
||||
def pump(box, transport, operation="projects", *, stale=False, expired=False, ids=()):
|
||||
job = MaintenanceJob(operation, "synthetic-op", ids, 1, 2,
|
||||
time.monotonic() + (-1 if expired else 5))
|
||||
box.pending = job
|
||||
def validate(_job):
|
||||
if stale:
|
||||
raise ValueError("stale checkpoint")
|
||||
box.pump(transport, ApplicationControlAuthority(
|
||||
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), validate)
|
||||
assert job.finished.is_set() and box.pending is None
|
||||
return job.result
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reason", ["active", "stale", "expired", "unknown-catalog"])
|
||||
def test_no_hardware_publish_without_current_idle_admission(reason):
|
||||
box, transport = ManagementMailbox(), MailboxTransport(standby=reason != "active")
|
||||
result = pump(box, transport, "delete-projects" if reason == "unknown-catalog" else "projects",
|
||||
stale=reason == "stale", expired=reason == "expired",
|
||||
ids=("one",) if reason == "unknown-catalog" else ())
|
||||
assert result["status"] == "blocked" and not transport.sent
|
||||
|
||||
|
||||
def test_lost_write_reply_is_unknown_blocks_start_and_is_not_retried():
|
||||
box, transport = ManagementMailbox(), MailboxTransport(lose_reply=True)
|
||||
result = pump(box, transport, "usb-storage")
|
||||
assert result["status"] == "unknown" and box.block_start
|
||||
box.pump(transport, None, None, lambda job: None)
|
||||
assert len(transport.sent) == 1
|
||||
|
||||
|
||||
def test_closed_worker_cancels_queued_unpublished_job():
|
||||
box = ManagementMailbox()
|
||||
job = MaintenanceJob("projects", "synthetic-op", (), 1, 2, time.monotonic() + 5)
|
||||
box.pending = job
|
||||
box.cancel_queued()
|
||||
assert box.pending is None and job.finished.is_set() and job.result["status"] == "blocked"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", [None, "reject-second", "lose-second"])
|
||||
def test_group_deletion_uses_confirmed_single_requests_and_stops_on_failure(failure):
|
||||
class DeletingTransport(MailboxTransport):
|
||||
def exchange_batch_once(self, batch, **kwargs):
|
||||
assert not kwargs["dispatch_admission_deadline_reached"]()
|
||||
kwargs["dispatch_admission_commit"]()
|
||||
request = batch[0]
|
||||
self.sent.append(request)
|
||||
if request.operation_key.startswith("management-info:"):
|
||||
return {request.operation_key: info()}
|
||||
fields = list(iter_fields(request.payload))
|
||||
assert [p.number for p in fields] == [1, 2, 3]
|
||||
index = len(self.sent)
|
||||
if failure == "lose-second" and index == 2:
|
||||
raise TimeoutError()
|
||||
code = 839122945 if failure == "reject-second" and index == 2 else OPENAPI_SUCCESS
|
||||
raw = blob(1, fields[0].value) + uint(2, 25) + blob(15, uint(1, code))
|
||||
return {request.operation_key: raw}
|
||||
|
||||
box, transport = ManagementMailbox(), DeletingTransport()
|
||||
box.generation, box.catalog_revision, box.project_ids = 1, "catalog", {"one", "two", "three"}
|
||||
job = MaintenanceJob("delete-projects", "batch", ("one", "two", "three"), 1, 2,
|
||||
time.monotonic() + 5, catalog_revision="catalog")
|
||||
box.pending = job
|
||||
box.pump(transport, ApplicationControlAuthority(
|
||||
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), lambda _: None)
|
||||
assert job.finished.is_set()
|
||||
requests = [p for p in transport.sent if p.operation_key.startswith("management:")]
|
||||
assert len({p.operation_key for p in requests}) == len(requests)
|
||||
assert [next(f.value for f in iter_fields(p.payload) if f.number == 3) for p in requests] \
|
||||
== ([b"one", b"two"] if failure else [b"one", b"two", b"three"])
|
||||
assert job.result["deleted_project_ids"] == (["one"] if failure else ["one", "two", "three"])
|
||||
expected = {None: "succeeded", "reject-second": "rejected", "lose-second": "unknown"}
|
||||
assert job.result["status"] == expected[failure]
|
||||
assert box.block_start is (failure == "lose-second")
|
||||
|
||||
|
||||
def test_destructive_request_requires_confirmation_and_no_arbitrary_parameters():
|
||||
base = dict(operation_id="synthetic-op", expected_session_generation=1,
|
||||
expected_state_revision=2, operation="format-storage")
|
||||
with pytest.raises(ValueError):
|
||||
DeviceManagementRequest(**base)
|
||||
with pytest.raises(ValueError):
|
||||
DeviceManagementRequest(**base, operator_confirmed=True, path="/arbitrary")
|
||||
|
||||
|
||||
def test_mass_storage_cannot_remove_its_only_control_path():
|
||||
session = InteractiveApplicationControlSession(SimpleNamespace())
|
||||
session._phase = "connection-ready"
|
||||
job = MaintenanceJob("usb-storage", "synthetic-op", (), 0, 0, time.monotonic() + 5)
|
||||
for mode in ("usb", "quick-connect", "direct-connect", "bridge"):
|
||||
session._connection_binding = ApplicationConnectionBinding(
|
||||
"synthetic-intent", "synthetic-transport", 1, "192.0.2.1", 1883, mode,
|
||||
)
|
||||
if mode == "bridge":
|
||||
session._validate_management_job(job)
|
||||
else:
|
||||
with pytest.raises(ValueError, match="Bridge"):
|
||||
session._validate_management_job(job)
|
||||
assert session._management.pending is None
|
||||
@@ -158,7 +158,7 @@ def test_private_release_contains_material_only_in_root_private_member(
|
||||
position += 60 + length + length % 2
|
||||
with tarfile.open(fileobj=io.BytesIO(members["control.tar.gz"]), mode="r:gz") as archive:
|
||||
control = archive.extractfile("control").read().decode()
|
||||
assert "Depends: mission-core-node (>= 0.8.13)" in control
|
||||
assert "Depends: mission-core-node (>= 0.8.49-57)" in control
|
||||
assert "Replaces: mission-core-node (<< 0.8.0)" in control
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import asyncio
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from test_xgrids_acquisition_lifecycle import _direct_host_path, service_with_fake_runtime
|
||||
|
||||
from k1link.device_plugins.xgrids_k1 import facade as facade_module
|
||||
from k1link.device_plugins.xgrids_k1.facade import (
|
||||
ConnectionVerifyRequest,
|
||||
ConnectRequest,
|
||||
DesiredConnectionModeRequest,
|
||||
)
|
||||
from k1link.device_plugins.xgrids_k1.usb_network import LinuxK1UsbProbe, UsbNetworkAttachment
|
||||
|
||||
|
||||
def attachment():
|
||||
return UsbNetworkAttachment("usb:synthetic", "test0", "10.255.254.77",
|
||||
"10.255.254.2", "generation-one", "480")
|
||||
|
||||
|
||||
def usb_tree(tmp_path):
|
||||
usb = tmp_path / "devices" / "usb1" / "1-2"
|
||||
net = usb / "1-2:1.0" / "net" / "test0"
|
||||
net.mkdir(parents=True)
|
||||
driver = tmp_path / "drivers" / "rndis_host"
|
||||
driver.mkdir(parents=True)
|
||||
(usb / "1-2:1.0" / "driver").symlink_to(driver)
|
||||
(net / "device").symlink_to(usb / "1-2:1.0")
|
||||
sys_net = tmp_path / "class" / "net"
|
||||
sys_net.mkdir(parents=True)
|
||||
(sys_net / "test0").symlink_to(net)
|
||||
for name, value in {"idVendor": "2207", "idProduct": "0019", "serial": "synthetic",
|
||||
"product": "XGRIDS Device", "busnum": "1", "devnum": "4",
|
||||
"speed": "480"}.items():
|
||||
(usb / name).write_text(value)
|
||||
(net / "carrier").write_text("1")
|
||||
(net / "ifindex").write_text("9")
|
||||
return usb, net, sys_net
|
||||
|
||||
|
||||
def runner(args, **kwargs):
|
||||
if args[0] == "nmcli":
|
||||
return "DHCP4.OPTION[1]:dhcp_server_identifier = 10.255.254.77\n"
|
||||
assert args == ["ip", "-j", "route", "get", "10.255.254.77"]
|
||||
return json.dumps([{"dev": "test0", "prefsrc": "10.255.254.2"}])
|
||||
|
||||
|
||||
def test_discovery_uses_dhcp_not_address_default_and_keeps_identity_on_replug(tmp_path):
|
||||
usb, net, sys_net = usb_tree(tmp_path)
|
||||
probe = LinuxK1UsbProbe(sys_net, runner)
|
||||
before, = probe.discover()
|
||||
assert before.peer_ipv4 == "10.255.254.77"
|
||||
(usb / "devnum").write_text("5")
|
||||
(net / "ifindex").write_text("10")
|
||||
after, = probe.discover()
|
||||
assert after.transport_ref == before.transport_ref
|
||||
assert after.generation != before.generation
|
||||
(net / "carrier").write_text("0")
|
||||
assert probe.discover() == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fault", ["vendor", "mass-storage", "dhcp", "route", "gateway"])
|
||||
def test_unproved_usb_topology_never_becomes_candidate(tmp_path, fault):
|
||||
usb, _, sys_net = usb_tree(tmp_path)
|
||||
if fault == "vendor":
|
||||
(usb / "idVendor").write_text("1234")
|
||||
if fault == "mass-storage":
|
||||
(usb / "1-2:1.0" / "driver").unlink()
|
||||
|
||||
def broken(args, **kwargs):
|
||||
if fault == "dhcp" and args[0] == "nmcli":
|
||||
return ""
|
||||
if args[0] == "ip" and fault in {"route", "gateway"}:
|
||||
return json.dumps([{"dev": "wifi0" if fault == "route" else "test0",
|
||||
"prefsrc": "10.255.254.2", "gateway": "10.255.254.1"}])
|
||||
return runner(args, **kwargs)
|
||||
|
||||
assert LinuxK1UsbProbe(sys_net, broken).discover() == ()
|
||||
|
||||
|
||||
def test_usb_cannot_be_sent_as_wireless_provisioning():
|
||||
with pytest.raises(ValidationError):
|
||||
ConnectRequest.model_validate({"connection_mode": "usb"})
|
||||
|
||||
|
||||
def test_usb_verify_reuses_identity_admission_and_performs_no_ble(monkeypatch, tmp_path):
|
||||
service, _ = service_with_fake_runtime(tmp_path)
|
||||
live = [attachment()]
|
||||
service._usb_network_probe = SimpleNamespace(require=lambda _: live[0])
|
||||
monkeypatch.setattr(facade_module, "_inspect_host_path", _direct_host_path)
|
||||
monkeypatch.setattr(facade_module, "_control_endpoint_reachable", lambda _: True)
|
||||
|
||||
def forbidden(*args, **kwargs):
|
||||
raise AssertionError("USB must never contact BLE or mutate Wi-Fi")
|
||||
|
||||
monkeypatch.setattr(facade_module, "read_wifi_status_once", forbidden)
|
||||
monkeypatch.setattr(facade_module, "provision_wifi_once", forbidden)
|
||||
monkeypatch.setattr(service, "_borrow_network_ble_process_lease", forbidden)
|
||||
|
||||
async def verify():
|
||||
state = service.select_connection_mode(DesiredConnectionModeRequest(
|
||||
connection_mode="usb", expected_revision=0,
|
||||
))
|
||||
return await service.verify_connection(ConnectionVerifyRequest(
|
||||
device_id=live[0].transport_ref, source="usb-enumeration",
|
||||
compatibility_attestation={"firmware_version": "3.0.2", "topology": "usb-ethernet",
|
||||
"verification": "live-device-info"},
|
||||
expected_mode_revision=state["desired_connection_mode_revision"],
|
||||
))
|
||||
|
||||
try:
|
||||
state = asyncio.run(verify())
|
||||
assert state["connection_lifecycle"]["connection_ready"] is True
|
||||
assert state["active_connection_mode"] == "usb"
|
||||
assert state["acquisition"] is None
|
||||
assert state["physical_command"]["record"] is None
|
||||
assert state["semantic_topology_store"]["record"]["source"] == "usb-enumeration"
|
||||
before = service._sample_host_path(live[0].peer_ipv4)
|
||||
live[0] = replace(live[0], generation="generation-two")
|
||||
assert service._sample_host_path(live[0].peer_ipv4).fingerprint != before.fingerprint
|
||||
live[0] = replace(live[0], interface="different")
|
||||
assert service._sample_host_path(live[0].peer_ipv4).available is False
|
||||
finally:
|
||||
service.close()
|
||||
|
||||
|
||||
def test_usb_start_journal_survives_restart_without_changing_start(tmp_path):
|
||||
from test_xgrids_physical_command_ledger import _connection, _prepare_start
|
||||
|
||||
from k1link.device_plugins.xgrids_k1.physical_command_ledger import PhysicalCommandLedger
|
||||
|
||||
ledger = PhysicalCommandLedger(tmp_path)
|
||||
binding = replace(_connection(), connection_mode="usb", transport_ref="usb:synthetic")
|
||||
_prepare_start(ledger, connection=binding)
|
||||
before = ledger.snapshot().record
|
||||
after = PhysicalCommandLedger(tmp_path).snapshot().record
|
||||
assert after == before
|
||||
assert after.action == "start"
|
||||
assert after.connection.connection_mode == "usb"
|
||||
assert after.stage == "prepared"
|
||||
|
||||
|
||||
def test_hotplug_observer_only_verifies_once_per_attachment(monkeypatch):
|
||||
from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
|
||||
|
||||
calls = []
|
||||
current = {"active_connection_mode": None, "desired_connection_mode": "bridge",
|
||||
"desired_connection_mode_revision": 0, "source_mode": "idle"}
|
||||
|
||||
async def invoke(*args):
|
||||
return dict(current)
|
||||
|
||||
def select(request):
|
||||
calls.append("select")
|
||||
current.update(desired_connection_mode=request.connection_mode,
|
||||
desired_connection_mode_revision=1)
|
||||
return dict(current)
|
||||
|
||||
async def verify(request):
|
||||
calls.append(request)
|
||||
current["active_connection_mode"] = "usb"
|
||||
current["connection_lifecycle"] = {"connection_ready": True}
|
||||
|
||||
bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke,
|
||||
service=SimpleNamespace(select_connection_mode=select,
|
||||
verify_connection=verify))
|
||||
observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
|
||||
|
||||
async def observe():
|
||||
await observer.observe_once()
|
||||
await observer.observe_once()
|
||||
|
||||
asyncio.run(observe())
|
||||
assert calls[0] == "select"
|
||||
assert len(calls) == 2
|
||||
assert isinstance(calls[1], ConnectionVerifyRequest)
|
||||
assert calls[1].source == "usb-enumeration"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source,phase,retries", [
|
||||
("idle", "failed", 1),
|
||||
("idle", "completed", 1),
|
||||
("live", "failed", 0),
|
||||
("idle", "stopping", 0),
|
||||
("live", "running", 0),
|
||||
])
|
||||
def test_unchanged_usb_rechecks_retired_control_without_stealing_receiver(source, phase, retries):
|
||||
from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
|
||||
|
||||
calls = []
|
||||
current = {"active_connection_mode": None, "desired_connection_mode": "usb",
|
||||
"desired_connection_mode_revision": 2, "source_mode": source,
|
||||
"acquisition": {"state": phase}, "connection_lifecycle": {"connection_ready": False}}
|
||||
|
||||
async def invoke(*args):
|
||||
return current
|
||||
|
||||
async def verify(request):
|
||||
calls.append(request)
|
||||
|
||||
bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke,
|
||||
service=SimpleNamespace(verify_connection=verify))
|
||||
observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
|
||||
observer.accepted_generation = attachment().generation
|
||||
asyncio.run(observer.observe_once())
|
||||
assert len(calls) == retries
|
||||
if calls:
|
||||
assert calls[0].source == "usb-enumeration"
|
||||
assert calls[0].expected_mode_revision == 2
|
||||
assert calls[0].device_id == attachment().transport_ref
|
||||
|
||||
|
||||
def test_hotplug_cannot_steal_active_wireless_acquisition():
|
||||
from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
|
||||
|
||||
async def invoke(*args):
|
||||
return {"active_connection_mode": "bridge", "source_mode": "live"}
|
||||
|
||||
bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke, service=object())
|
||||
observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
|
||||
asyncio.run(observer.observe_once())
|
||||
assert observer.accepted_generation is None
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Preview decoding/adaptation never acquires a physical camera or a recorder."""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from fractions import Fraction
|
||||
from types import SimpleNamespace
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from k1link.viewer.node_camera import CameraSource, CameraTrack, LeaseReader, open_live_camera
|
||||
from k1link.viewer.node_media import admit_sdp
|
||||
|
||||
|
||||
def test_mp4_lease_decodes_to_one_latest_frame_without_network_or_capture_change():
|
||||
output = io.BytesIO()
|
||||
with av.open(
|
||||
output,
|
||||
"w",
|
||||
format="mp4",
|
||||
options={"movflags": "frag_keyframe+empty_moov+default_base_moof"},
|
||||
) as mux:
|
||||
stream = mux.add_stream("libx264", rate=15)
|
||||
stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p"
|
||||
for index in range(10):
|
||||
frame = av.VideoFrame.from_ndarray(
|
||||
np.full((48, 64, 3), index * 10, dtype=np.uint8), format="rgb24"
|
||||
)
|
||||
for packet in stream.encode(frame):
|
||||
mux.mux(packet)
|
||||
for packet in stream.encode():
|
||||
mux.mux(packet)
|
||||
segments = queue.Queue()
|
||||
data = output.getvalue()
|
||||
for offset in range(0, len(data), 113):
|
||||
segments.put(("media", data[offset : offset + 113]))
|
||||
segments.put(None)
|
||||
lease = SimpleNamespace(segments=segments)
|
||||
|
||||
class Camera:
|
||||
opened = 0
|
||||
released = 0
|
||||
streamed = 0
|
||||
|
||||
def snapshot(self):
|
||||
return {
|
||||
"generation": 7,
|
||||
"recording": {
|
||||
"source_end_expected": self.released > 0,
|
||||
"active": True,
|
||||
"producer_alive": True,
|
||||
"media_ready": True,
|
||||
"active_epoch": 7,
|
||||
},
|
||||
}
|
||||
|
||||
def open_delivery(self, generation, *, require_recording):
|
||||
assert generation == 7 and require_recording
|
||||
self.opened += 1
|
||||
return lease
|
||||
|
||||
def release_delivery(self, value, *, client_closed):
|
||||
assert value is lease and client_closed
|
||||
self.released += 1
|
||||
|
||||
def mark_streaming(self, value):
|
||||
assert value is lease
|
||||
self.streamed += 1
|
||||
|
||||
camera = Camera()
|
||||
source = CameraSource(camera)
|
||||
source.thread.join(3)
|
||||
source.close()
|
||||
source.thread.join(1)
|
||||
assert not source.thread.is_alive()
|
||||
assert source.sequence >= 1 and camera.streamed >= 1
|
||||
assert camera.opened == camera.released == 1
|
||||
|
||||
|
||||
def test_closing_consumer_unblocks_mp4_reader():
|
||||
stopped = threading.Event()
|
||||
reader = LeaseReader(SimpleNamespace(segments=queue.Queue()), stopped)
|
||||
result = []
|
||||
worker = threading.Thread(target=lambda: result.append(reader.read(12)))
|
||||
worker.start()
|
||||
stopped.set()
|
||||
worker.join(1)
|
||||
assert not worker.is_alive() and result == [b""]
|
||||
|
||||
|
||||
def test_live_fragment_is_decoded_without_waiting_for_future_frames_or_eof():
|
||||
output = io.BytesIO()
|
||||
with av.open(output, "w", format="mp4", options={
|
||||
"movflags": "empty_moov+default_base_moof+frag_every_frame",
|
||||
}) as mux:
|
||||
stream = mux.add_stream("libx264", rate=15)
|
||||
stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p"
|
||||
stream.options = {"tune": "zerolatency", "g": "1"}
|
||||
for index in range(3):
|
||||
frame = av.VideoFrame.from_ndarray(
|
||||
np.full((48, 64, 3), index * 50, dtype=np.uint8), format="rgb24"
|
||||
)
|
||||
for packet in stream.encode(frame):
|
||||
mux.mux(packet)
|
||||
# Capture while the producer remains live: no trailer or EOF.
|
||||
live = output.getvalue()
|
||||
segments = queue.Queue()
|
||||
segments.put(("media", live))
|
||||
stopped, decoded = threading.Event(), threading.Event()
|
||||
|
||||
def consume():
|
||||
reader = LeaseReader(SimpleNamespace(segments=segments), stopped)
|
||||
with open_live_camera(reader) as container:
|
||||
for _frame in container.decode(video=0):
|
||||
decoded.set()
|
||||
break
|
||||
|
||||
worker = threading.Thread(target=consume, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
assert decoded.wait(1), "live preview waited for future data or EOF"
|
||||
finally:
|
||||
stopped.set()
|
||||
worker.join(2)
|
||||
assert not worker.is_alive()
|
||||
|
||||
|
||||
def test_camera_track_obeys_shared_budget_and_never_mutates_source_frame():
|
||||
frame = av.VideoFrame(1280, 720, "yuv420p")
|
||||
frame.pts, frame.time_base = 123, Fraction(1, 90000)
|
||||
source = SimpleNamespace(closed=threading.Event(), current=lambda: (1, frame, time.monotonic()))
|
||||
budget = SimpleNamespace(video=lambda: (320, 4))
|
||||
|
||||
async def run():
|
||||
track = CameraTrack(source, budget)
|
||||
try:
|
||||
result = await asyncio.wait_for(track.recv(), 1)
|
||||
assert result.width == 320 and result.height == 180
|
||||
assert result.pts == 123 and result is not frame and frame.width == 1280
|
||||
finally:
|
||||
track.stop()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_camera_sdp_requires_exact_video_and_control_channel_and_private_ice():
|
||||
invitation = (
|
||||
"v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\n"
|
||||
"m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n"
|
||||
)
|
||||
admit_sdp(invitation, camera=True)
|
||||
with pytest.raises(ValueError):
|
||||
admit_sdp(invitation)
|
||||
with pytest.raises(ValueError):
|
||||
admit_sdp(invitation + "m=audio 9 UDP/TLS/RTP/SAVPF 0\r\n", camera=True)
|
||||
with pytest.raises(ValueError):
|
||||
admit_sdp(invitation + "a=candidate:1 1 udp 1 8.8.8.8 1234 typ host\r\n", camera=True)
|
||||
+573
-61
@@ -52,6 +52,16 @@ class Facade:
|
||||
|
||||
async def invoke(self, request):
|
||||
self.actions.append((request.action_id, copy.deepcopy(request.parameters)))
|
||||
if request.action_id == "connection.verify":
|
||||
from k1link.device_plugins.xgrids_k1.facade import ConnectionVerifyRequest
|
||||
|
||||
ConnectionVerifyRequest.model_validate(
|
||||
{
|
||||
key: value
|
||||
for key, value in request.parameters.items()
|
||||
if key != "expected_snapshot_runtime_id"
|
||||
}
|
||||
)
|
||||
if request.action_id == "application-control.workspace.enter":
|
||||
self.current["application_control_session"]["state"] = "workspace-ready"
|
||||
elif request.action_id == "acquisition.prepare":
|
||||
@@ -75,6 +85,28 @@ def bridge():
|
||||
return result
|
||||
|
||||
|
||||
def test_retired_usb_control_keeps_transport_identity_without_claiming_connection():
|
||||
snapshot = state()
|
||||
snapshot.update(active_connection_mode=None, desired_connection_mode="usb",
|
||||
selected_device_id="usb:synthetic", k1_ip="10.255.254.77",
|
||||
connection_lifecycle={"connection_ready": False, "ready_to_start": False})
|
||||
item = project_sensor(snapshot, "node-test")
|
||||
assert item["connection_mode"] == "usb"
|
||||
assert item["connection_label"] == "USB · 10.255.254.77"
|
||||
assert not item["online"] and not item["verified"]
|
||||
assert not item["control"]["can_start"]
|
||||
parameters = verification_parameters(snapshot, "verify-usb")
|
||||
assert parameters["source"] == "usb-enumeration"
|
||||
assert parameters["device_id"] == "usb:synthetic"
|
||||
assert parameters["compatibility_attestation"]["topology"] == "usb-ethernet"
|
||||
|
||||
|
||||
def test_usb_draft_does_not_replace_active_wireless_verification_target():
|
||||
snapshot = state()
|
||||
snapshot["desired_connection_mode"] = "usb"
|
||||
assert "source" not in verification_parameters(snapshot, "verify-current")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("available", [False, True])
|
||||
def test_startup_credential_check_does_not_authorize_control(monkeypatch, available):
|
||||
from k1link.device_plugins.xgrids_k1 import node_bridge
|
||||
@@ -124,9 +156,13 @@ def test_journalled_failure_logs_source_without_secret_and_does_not_repeat(caplo
|
||||
return {"operations": [{"operation_id": native, "status": "failed"}]}
|
||||
|
||||
device.invoke = invoke
|
||||
result = asyncio.run(device.invoke_journalled(
|
||||
"network.provision", {"operation_id": native, "password": secret}, identifier,
|
||||
))
|
||||
result = asyncio.run(
|
||||
device.invoke_journalled(
|
||||
"network.provision",
|
||||
{"operation_id": native, "password": secret},
|
||||
identifier,
|
||||
)
|
||||
)
|
||||
assert result["operations"][0]["status"] == "failed"
|
||||
assert calls == ["network.provision", "state.read"]
|
||||
assert "exception=BleakError" in caplog.text
|
||||
@@ -156,20 +192,28 @@ def test_real_facade_preserves_native_failure_location_in_journalled_log(caplog)
|
||||
|
||||
async def connect(self, request):
|
||||
calls.append("connect")
|
||||
self.current["operations"] = [{
|
||||
"operation_id": request.operation_id, "status": "failed",
|
||||
"error": {"code": "BleakError"},
|
||||
}]
|
||||
self.current["operations"] = [
|
||||
{
|
||||
"operation_id": request.operation_id,
|
||||
"status": "failed",
|
||||
"error": {"code": "BleakError"},
|
||||
}
|
||||
]
|
||||
raise BleakError(secret)
|
||||
|
||||
async def run():
|
||||
device = NodeBridge(Path.cwd(), service=Service())
|
||||
command = {
|
||||
"operation_id": "op_" + "c" * 32, "runtime_id": "runtime-one",
|
||||
"operation_id": "op_" + "c" * 32,
|
||||
"runtime_id": "runtime-one",
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"action": "connect", "parameters": {
|
||||
"device_id": "AA:BB:CC:DD:EE:FF", "discovery_generation": 1,
|
||||
"mode_revision": 0, "ssid": "test-network", "password": secret,
|
||||
"action": "connect",
|
||||
"parameters": {
|
||||
"device_id": "AA:BB:CC:DD:EE:FF",
|
||||
"discovery_generation": 1,
|
||||
"mode_revision": 0,
|
||||
"ssid": "test-network",
|
||||
"password": secret,
|
||||
},
|
||||
}
|
||||
result = await device.deliver(command)
|
||||
@@ -274,7 +318,9 @@ def test_node_scan_reaches_service_through_real_facade_with_runtime_fence():
|
||||
|
||||
@pytest.mark.parametrize("radio_failure", [False, True])
|
||||
def test_node_scan_real_service_preserves_operation_identity_and_replay(
|
||||
tmp_path, monkeypatch, radio_failure,
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
radio_failure,
|
||||
):
|
||||
from bleak.backends.device import BLEDevice
|
||||
from bleak.backends.scanner import AdvertisementData
|
||||
@@ -295,8 +341,13 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
|
||||
self.callback(
|
||||
BLEDevice("AA:BB:CC:DD:EE:FF", "XGR-TEST", None),
|
||||
AdvertisementData(
|
||||
local_name="XGR-TEST", manufacturer_data={}, service_data={},
|
||||
service_uuids=[], tx_power=None, rssi=-50, platform_data=(),
|
||||
local_name="XGR-TEST",
|
||||
manufacturer_data={},
|
||||
service_data={},
|
||||
service_uuids=[],
|
||||
tx_power=None,
|
||||
rssi=-50,
|
||||
platform_data=(),
|
||||
),
|
||||
)
|
||||
return self
|
||||
@@ -317,7 +368,8 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
|
||||
"operation_id": "op_" + "b" * 32,
|
||||
"runtime_id": current["runtime_id"],
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"action": "scan", "parameters": {},
|
||||
"action": "scan",
|
||||
"parameters": {},
|
||||
}
|
||||
result = await device.deliver(command)
|
||||
if not radio_failure:
|
||||
@@ -329,12 +381,16 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
|
||||
assert result["candidates"] == []
|
||||
else:
|
||||
assert result["candidates"][0]["id"] == "AA:BB:CC:DD:EE:FF"
|
||||
assert result["command_result"] == repeated["command_result"] == {
|
||||
"operation_id": command["operation_id"],
|
||||
"action": "scan",
|
||||
"status": "failed" if radio_failure else "succeeded",
|
||||
"error_code": "RuntimeError" if radio_failure else None,
|
||||
}
|
||||
assert (
|
||||
result["command_result"]
|
||||
== repeated["command_result"]
|
||||
== {
|
||||
"operation_id": command["operation_id"],
|
||||
"action": "scan",
|
||||
"status": "failed" if radio_failure else "succeeded",
|
||||
"error_code": "RuntimeError" if radio_failure else None,
|
||||
}
|
||||
)
|
||||
|
||||
try:
|
||||
asyncio.run(run())
|
||||
@@ -349,7 +405,8 @@ def test_node_attempt_projection_keeps_host_correlation_without_mutating_plugin_
|
||||
"schema_version": "missioncore.xgrids-k1-connection-attempt/v1",
|
||||
"attempt_id": plugin_operation_id(identifier),
|
||||
"recovery_operation_id": plugin_operation_id("op_" + "b" * 32),
|
||||
"status": "failed", "public_error_code": "wifi-ssid-not-found",
|
||||
"status": "failed",
|
||||
"public_error_code": "wifi-ssid-not-found",
|
||||
}
|
||||
result = NodeBridge.project(current)
|
||||
assert result["connection_attempt"]["attempt_id"] == identifier
|
||||
@@ -420,11 +477,13 @@ def test_sensor_projection_binds_native_sdk_to_board():
|
||||
def test_applied_wifi_does_not_grant_control_or_start_authority():
|
||||
current = state()
|
||||
current["connection_lifecycle"] = {
|
||||
"connection_ready": False, "ready_to_start": False,
|
||||
"connection_ready": False,
|
||||
"ready_to_start": False,
|
||||
"allowed_actions": ["verify-control-read-only"],
|
||||
}
|
||||
current["connection_attempt"] = {
|
||||
"phase": "network_applied", "public_error_code": "application_authority_unavailable",
|
||||
"phase": "network_applied",
|
||||
"public_error_code": "application_authority_unavailable",
|
||||
}
|
||||
item = project_sensor(current, "node-test")
|
||||
assert not item["online"] and not item["verified"]
|
||||
@@ -441,7 +500,8 @@ def test_applied_wifi_does_not_grant_control_or_start_authority():
|
||||
@pytest.mark.parametrize("initial_phase", ["connection-ready", "completed"])
|
||||
@pytest.mark.parametrize("pending_start", [False, True])
|
||||
def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
|
||||
initial_phase, pending_start,
|
||||
initial_phase,
|
||||
pending_start,
|
||||
):
|
||||
async def run():
|
||||
device = bridge()
|
||||
@@ -467,7 +527,8 @@ def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
|
||||
"parameters": {
|
||||
"operator_confirmed": True,
|
||||
"project_name": " Synthetic survey ",
|
||||
"mount_type": "handheld", "gnss_mode": "none",
|
||||
"mount_type": "handheld",
|
||||
"gnss_mode": "none",
|
||||
"control_generation": 1,
|
||||
"acquisition_id": None,
|
||||
},
|
||||
@@ -488,7 +549,8 @@ def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
|
||||
assert payload["mount_type"] == "handheld" and payload["gnss_mode"] == "none"
|
||||
if action in {"acquisition.prepare", "acquisition.start"}:
|
||||
row, created = journal.begin(
|
||||
action, operation_id=payload["operation_id"],
|
||||
action,
|
||||
operation_id=payload["operation_id"],
|
||||
idempotency_key=payload["idempotency_key"],
|
||||
)
|
||||
assert created
|
||||
@@ -506,6 +568,104 @@ def test_networkmanager_ssids_are_not_split_at_escaped_colons():
|
||||
assert nm_fields(r"field\:network\\name:88:WPA2") == ["field:network\\name", "88", "WPA2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("locale", ["ru_RU.UTF-8", "en_US.UTF-8"])
|
||||
def test_linux_wifi_probe_uses_stable_cli_locale_without_changing_parent(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
locale,
|
||||
):
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
from k1link.device_plugins.xgrids_k1 import linux_host
|
||||
from k1link.host_network.wifi import bind_route_fingerprint_to_wifi_association
|
||||
|
||||
(tmp_path / "wlan0" / "wireless").mkdir(parents=True)
|
||||
monkeypatch.setenv("LANG", locale)
|
||||
monkeypatch.setenv("LC_ALL", locale)
|
||||
parent_env = dict(os.environ)
|
||||
calls = []
|
||||
|
||||
def run(args, **kwargs):
|
||||
child_env = kwargs.get("env", os.environ)
|
||||
calls.append(child_env)
|
||||
active = "yes" if child_env.get("LC_ALL") == "C" else "да"
|
||||
return subprocess.CompletedProcess(
|
||||
args,
|
||||
0,
|
||||
active + r":Поле\:сеть:AA\:BB\:CC\:DD\:EE\:FF" + "\n",
|
||||
"",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(linux_host.subprocess, "run", run)
|
||||
probe = linux_host.LinuxWifiAssociationProbe(tmp_path)
|
||||
observed = probe.observe("wlan0")
|
||||
assert observed["association_state"] == "associated"
|
||||
assert observed["continuity_proven"] is True
|
||||
assert observed["reason_code"] is None
|
||||
fingerprint = bind_route_fingerprint_to_wifi_association("route", observed)
|
||||
repeated = bind_route_fingerprint_to_wifi_association("route", probe.observe("wlan0"))
|
||||
assert repeated == fingerprint
|
||||
assert all(env["LC_ALL"] == env["LANG"] == "C" for env in calls)
|
||||
assert dict(os.environ) == parent_env
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unavailable", ["empty", "inactive", "ambiguous", "command-error"])
|
||||
@pytest.mark.parametrize("fail_closed", [False, True])
|
||||
def test_linux_missing_association_reports_unavailable_without_invalid_token(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
unavailable,
|
||||
fail_closed,
|
||||
):
|
||||
from k1link.device_plugins.xgrids_k1 import facade, linux_host
|
||||
|
||||
(tmp_path / "sys-net" / "wlan0" / "wireless").mkdir(parents=True)
|
||||
probe = linux_host.LinuxWifiAssociationProbe(tmp_path / "sys-net")
|
||||
service = facade.XgridsK1CompatibilityService(
|
||||
tmp_path / "runtime",
|
||||
host_wifi_association_probe=probe,
|
||||
)
|
||||
path = facade.HostPathProbeResult(
|
||||
available=True,
|
||||
fingerprint="synthetic-route",
|
||||
interface="wlan0",
|
||||
source_ipv4="192.168.1.2",
|
||||
route_class="direct",
|
||||
reason_code=None,
|
||||
)
|
||||
monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: path)
|
||||
|
||||
def run(*_args, **_kwargs):
|
||||
if unavailable == "command-error":
|
||||
raise OSError("Network observation unavailable")
|
||||
return {
|
||||
"empty": "",
|
||||
"inactive": r"no:test:AA\:BB\:CC\:DD\:EE\:FF",
|
||||
"ambiguous": "yes:test:one\nyes:test:two\n",
|
||||
}[unavailable]
|
||||
|
||||
def forbidden(*_args, **_kwargs):
|
||||
raise AssertionError("Unobserved Wi-Fi must not authorize a TCP probe")
|
||||
|
||||
monkeypatch.setattr(linux_host, "_run", run)
|
||||
monkeypatch.setattr(facade, "_control_endpoint_reachable", forbidden)
|
||||
try:
|
||||
observed = service._sample_host_path(
|
||||
"192.168.1.7",
|
||||
fail_closed_unproven_association=fail_closed,
|
||||
)
|
||||
assert observed.available is False
|
||||
assert observed.fingerprint is None
|
||||
assert observed.kernel_route_fingerprint == path.fingerprint
|
||||
assert observed.reason_code == "host-wifi-observation-unavailable"
|
||||
endpoint = service._probe_control_endpoint("192.168.1.7")
|
||||
assert endpoint.reachable is False
|
||||
assert endpoint.reason_code == observed.reason_code
|
||||
finally:
|
||||
service.close()
|
||||
|
||||
|
||||
def test_wired_board_bridge_does_not_require_host_wifi_association(tmp_path, monkeypatch):
|
||||
from k1link.device_plugins.xgrids_k1 import linux_host
|
||||
|
||||
@@ -523,7 +683,9 @@ def test_wired_board_bridge_does_not_require_host_wifi_association(tmp_path, mon
|
||||
|
||||
@pytest.mark.parametrize("route_changes", [False, True])
|
||||
def test_wired_board_real_service_correlates_route_and_control_endpoint(
|
||||
tmp_path, monkeypatch, route_changes,
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
route_changes,
|
||||
):
|
||||
from dataclasses import replace
|
||||
|
||||
@@ -533,11 +695,16 @@ def test_wired_board_real_service_correlates_route_and_control_endpoint(
|
||||
(sys_net / "enp1s0").mkdir(parents=True)
|
||||
probe = linux_host.LinuxWifiAssociationProbe(sys_net)
|
||||
service = facade.XgridsK1CompatibilityService(
|
||||
tmp_path / "runtime", host_wifi_association_probe=probe,
|
||||
tmp_path / "runtime",
|
||||
host_wifi_association_probe=probe,
|
||||
)
|
||||
path = facade.HostPathProbeResult(
|
||||
available=True, fingerprint="synthetic-route", interface="enp1s0",
|
||||
source_ipv4="192.168.1.2", route_class="direct", reason_code=None,
|
||||
available=True,
|
||||
fingerprint="synthetic-route",
|
||||
interface="enp1s0",
|
||||
source_ipv4="192.168.1.2",
|
||||
route_class="direct",
|
||||
reason_code=None,
|
||||
)
|
||||
monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: path)
|
||||
calls = []
|
||||
@@ -545,9 +712,15 @@ def test_wired_board_real_service_correlates_route_and_control_endpoint(
|
||||
def tcp(_target):
|
||||
calls.append("tcp")
|
||||
if route_changes:
|
||||
monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: replace(
|
||||
path, fingerprint="new-route", source_ipv4="192.168.1.3",
|
||||
))
|
||||
monkeypatch.setattr(
|
||||
facade,
|
||||
"_inspect_host_path",
|
||||
lambda _target: replace(
|
||||
path,
|
||||
fingerprint="new-route",
|
||||
source_ipv4="192.168.1.3",
|
||||
),
|
||||
)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(facade, "_control_endpoint_reachable", tcp)
|
||||
@@ -649,32 +822,45 @@ def test_preview_offer_cannot_cross_acquisition_boundary(replacement):
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("draft", [
|
||||
{}, {"project_name": " "}, {"project_name": "x" * 97},
|
||||
{"project_name": "invalid\nname"}, {"project_name": "Valid", "mount_type": "uav"},
|
||||
{"project_name": "Valid", "mount_type": "handheld", "gnss_mode": "rtk"},
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"draft",
|
||||
[
|
||||
{},
|
||||
{"project_name": " "},
|
||||
{"project_name": "x" * 97},
|
||||
{"project_name": "invalid\nname"},
|
||||
{"project_name": "Valid", "mount_type": "uav"},
|
||||
{"project_name": "Valid", "mount_type": "handheld", "gnss_mode": "rtk"},
|
||||
],
|
||||
)
|
||||
def test_invalid_start_draft_dispatches_no_workspace_or_project_command(draft):
|
||||
async def run():
|
||||
device = bridge()
|
||||
item = project_sensor(state(), "node-test")
|
||||
command = {
|
||||
"operation_id": "op_" + "b" * 32, "action_id": "start",
|
||||
"operation_id": "op_" + "b" * 32,
|
||||
"action_id": "start",
|
||||
"session": {"device_id": item["id"], "session_id": "session-test"},
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"parameters": {"operator_confirmed": True, "control_generation": 1,
|
||||
"acquisition_id": None, **draft},
|
||||
"parameters": {
|
||||
"operator_confirmed": True,
|
||||
"control_generation": 1,
|
||||
"acquisition_id": None,
|
||||
**draft,
|
||||
},
|
||||
}
|
||||
with pytest.raises(ValueError):
|
||||
await NodeK1Sensor(device, None).execute(command, "node-test")
|
||||
assert all(action == "state.read" for action, _ in device.facade.actions)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_recheck_uses_only_exact_admitted_durable_bridge_target():
|
||||
current = state()
|
||||
decision = {
|
||||
"allowed": True, "requires_live_gatt_validation": False,
|
||||
"allowed": True,
|
||||
"requires_live_gatt_validation": False,
|
||||
"required_transport_ref": current["selected_device_id"],
|
||||
"required_connection_mode": "bridge",
|
||||
}
|
||||
@@ -684,16 +870,25 @@ def test_recheck_uses_only_exact_admitted_durable_bridge_target():
|
||||
assert result["device_id"] == current["selected_device_id"]
|
||||
assert result["expected_mode_revision"] == current["desired_connection_mode_revision"]
|
||||
assert "source" not in verification_parameters(
|
||||
current, "synthetic-operation", requested_device_id="other-device",
|
||||
current,
|
||||
"synthetic-operation",
|
||||
requested_device_id="other-device",
|
||||
)
|
||||
for patch in [{"allowed": False}, {"requires_live_gatt_validation": True},
|
||||
{"required_connection_mode": "quick-connect"},
|
||||
{"required_transport_ref": "other"}]:
|
||||
for patch in [
|
||||
{"allowed": False},
|
||||
{"required_connection_mode": "quick-connect"},
|
||||
{"required_transport_ref": "other"},
|
||||
]:
|
||||
decision.update(patch)
|
||||
assert "source" not in verification_parameters(current, "synthetic-operation")
|
||||
decision.update(allowed=True, requires_live_gatt_validation=False,
|
||||
required_transport_ref=current["selected_device_id"],
|
||||
required_connection_mode="bridge")
|
||||
assert "source" not in verification_parameters(
|
||||
current, "synthetic-operation", requested_device_id=current["selected_device_id"]
|
||||
)
|
||||
decision.update(
|
||||
allowed=True,
|
||||
requires_live_gatt_validation=False,
|
||||
required_transport_ref=current["selected_device_id"],
|
||||
required_connection_mode="bridge",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("requires_gatt", [False, True])
|
||||
@@ -701,23 +896,340 @@ def test_enrollment_verify_and_detail_share_durable_target_admission(requires_ga
|
||||
async def run():
|
||||
device = bridge()
|
||||
current = device.facade.current
|
||||
current["connection_policy"] = {"actions": {"observe-configured-device-network": {
|
||||
"allowed": True, "requires_live_gatt_validation": requires_gatt,
|
||||
"required_connection_mode": "bridge",
|
||||
"required_transport_ref": current["selected_device_id"],
|
||||
}}}
|
||||
current["connection_policy"] = {
|
||||
"actions": {
|
||||
"observe-configured-device-network": {
|
||||
"allowed": True,
|
||||
"requires_live_gatt_validation": requires_gatt,
|
||||
"required_connection_mode": "bridge",
|
||||
"required_transport_ref": current["selected_device_id"],
|
||||
}
|
||||
}
|
||||
}
|
||||
command = {
|
||||
"operation_id": "op_" + "d" * 32, "action": "verify", "runtime_id": "runtime-one",
|
||||
"operation_id": "op_" + "d" * 32,
|
||||
"action": "verify",
|
||||
"runtime_id": "runtime-one",
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"parameters": {"device_id": current["selected_device_id"],
|
||||
"discovery_generation": 1, "mode_revision": 0},
|
||||
"parameters": {
|
||||
"device_id": current["selected_device_id"],
|
||||
"discovery_generation": 1,
|
||||
"mode_revision": 0,
|
||||
},
|
||||
}
|
||||
await device.execute(command)
|
||||
actions = [(a, p) for a, p in device.facade.actions if a != "state.read"]
|
||||
assert len(actions) == 1 and actions[0][0] == "connection.verify"
|
||||
payload = actions[0][1]
|
||||
assert (payload.get("source") == "durable-configured-state") is not requires_gatt
|
||||
assert payload["source"] == "durable-configured-state"
|
||||
assert payload["device_id"] == current["selected_device_id"]
|
||||
assert payload["expected_discovery_generation"] == 1
|
||||
assert "expected_discovery_generation" not in payload
|
||||
assert "password" not in payload
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_explicit_fresh_selection_uses_current_scan_when_policy_admits_it():
|
||||
current = state()
|
||||
current['connection_policy'] = {'actions': {
|
||||
'observe-configured-device-network': {'allowed': True,
|
||||
'required_transport_ref': current['selected_device_id'],
|
||||
'required_connection_mode': 'bridge'},
|
||||
'observe-fresh-device-network': {'allowed': True},
|
||||
}}
|
||||
args = {'requested_device_id': current['selected_device_id']}
|
||||
assert 'source' not in verification_parameters(current, 'synthetic-operation', **args)
|
||||
durable = 'durable-configured-state'
|
||||
assert verification_parameters(current, 'synthetic-operation')['source'] == durable
|
||||
current['connection_policy']['actions']['observe-fresh-device-network']['allowed'] = False
|
||||
assert verification_parameters(current, 'synthetic-operation', **args)['source'] == durable
|
||||
current['connection_policy']['actions']['observe-fresh-device-network']['allowed'] = True
|
||||
current['devices'] = []
|
||||
assert verification_parameters(current, 'synthetic-operation', **args)['source'] == durable
|
||||
|
||||
|
||||
def test_preview_blueprint_uses_canonical_live_timeline_without_device_commands(monkeypatch):
|
||||
import base64
|
||||
|
||||
from k1link.viewer.recorded import recorded_blueprint
|
||||
from k1link.viewer.rerun_bridge import RerunSceneSettings
|
||||
|
||||
import k1link.device_plugins.xgrids_k1.node_sensor as module
|
||||
calls = []
|
||||
original = module.recorded_blueprint_rrd
|
||||
def record(*args, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return original(*args, **kwargs)
|
||||
monkeypatch.setattr(module, "recorded_blueprint_rrd", record)
|
||||
|
||||
async def run():
|
||||
device = bridge()
|
||||
item = project_sensor(device.facade.current, "node-test")
|
||||
sensor = NodeK1Sensor(device, None)
|
||||
command = {
|
||||
"operation_id": "op_" + "c" * 32,
|
||||
"action_id": "details",
|
||||
"session": {"device_id": item["id"], "session_id": "session-test"},
|
||||
"parameters": {
|
||||
"preview_blueprint": {
|
||||
"recording_id": "synthetic-recording",
|
||||
"owner": "b" * 32,
|
||||
"view": "plan",
|
||||
"follow_trajectory": True,
|
||||
"host_playback": True,
|
||||
"settings": {"accumulation_seconds": 240, "show_grid": False},
|
||||
"eye": {"position": [1, 2, 3], "lookTarget": [0, 0, 0], "eyeUp": [0, 0, 1]},
|
||||
}
|
||||
},
|
||||
}
|
||||
result = await sensor.execute(command, "node-test")
|
||||
assert base64.b64decode(result["rrd"]).startswith(b"RRF2")
|
||||
assert calls[-1]["follow_trajectory"] is True
|
||||
assert calls[-1]["initialize_playback"] is False
|
||||
assert calls[-1]["eye_position"] == (1, 2, 3)
|
||||
command["parameters"]["preview_blueprint"]["follow_trajectory"] = "true"
|
||||
with pytest.raises(ValueError, match="follow"):
|
||||
await sensor.execute(command, "node-test")
|
||||
command["parameters"]["preview_blueprint"]["release"] = True
|
||||
assert await sensor.execute(command, "node-test") == {"released": True}
|
||||
assert all(action == "state.read" for action, _ in device.facade.actions)
|
||||
|
||||
asyncio.run(run())
|
||||
blueprint = recorded_blueprint(
|
||||
RerunSceneSettings(accumulation_seconds=240, show_grid=False),
|
||||
timeline="stream_time",
|
||||
plan_view=True,
|
||||
)
|
||||
spatial = blueprint.root_container.contents[0]
|
||||
ranges = spatial.visualizer_overrides["/world/points"][-1].ranges.as_arrow_array().to_pylist()
|
||||
assert ranges == [{"timeline": "stream_time", "range": {"start": -240_000_000_000, "end": 0}}]
|
||||
assert spatial.properties["LineGrid3D"].visible.as_arrow_array().to_pylist() == [False]
|
||||
|
||||
|
||||
def cold_recovery_state():
|
||||
current = state()
|
||||
current.update(
|
||||
selected_device_id=None,
|
||||
devices=[],
|
||||
ble_discovery_generation=0,
|
||||
device_session=None,
|
||||
active_connection_mode=None,
|
||||
connection_lifecycle={
|
||||
"connection_ready": False,
|
||||
"ready_to_start": False,
|
||||
"allowed_actions": ["observe-configured-device-network"],
|
||||
},
|
||||
)
|
||||
current["connection_policy"] = {
|
||||
"actions": {
|
||||
"observe-configured-device-network": {
|
||||
"allowed": True,
|
||||
"requires_live_gatt_validation": False,
|
||||
"required_transport_ref": "AA:BB:CC:DD:EE:FF",
|
||||
"required_connection_mode": "bridge",
|
||||
"target_source": "durable-configured-state",
|
||||
}
|
||||
}
|
||||
}
|
||||
current["active_acquisition_recovery_checkpoint"] = {
|
||||
"status": "active",
|
||||
"state": "active",
|
||||
"gap_open": False,
|
||||
"restart_rehydration_phase": "inactive",
|
||||
"reason_code": None,
|
||||
"private_lineage": "must-not-cross-node-projection",
|
||||
}
|
||||
return current
|
||||
|
||||
|
||||
@pytest.mark.parametrize("requires_gatt", [False, True])
|
||||
def test_cold_board_restart_verifies_saved_target_without_discovery_or_physical_command(
|
||||
requires_gatt,
|
||||
):
|
||||
device = bridge()
|
||||
device.facade.current = cold_recovery_state()
|
||||
device.facade.current["connection_policy"]["actions"]["observe-configured-device-network"][
|
||||
"requires_live_gatt_validation"
|
||||
] = requires_gatt
|
||||
checkpoint = copy.deepcopy(device.facade.current["active_acquisition_recovery_checkpoint"])
|
||||
identifier = "op_" + "e" * 32
|
||||
|
||||
async def run():
|
||||
before = await device.state()
|
||||
assert before["connected"] is False
|
||||
assert before["candidates"] == []
|
||||
assert before["selected_device_id"] is None
|
||||
assert before["reconnect_target"]["device_id"] == "AA:BB:CC:DD:EE:FF"
|
||||
assert before["acquisition_recovery"]["state"] == "active"
|
||||
assert "private_lineage" not in before["acquisition_recovery"]
|
||||
assert device.facade.actions == [("state.read", {})]
|
||||
device.facade.actions.clear()
|
||||
await device.execute(
|
||||
{
|
||||
"operation_id": identifier,
|
||||
"runtime_id": "runtime-one",
|
||||
"action": "verify",
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"parameters": {
|
||||
"device_id": before["reconnect_target"]["device_id"],
|
||||
"discovery_generation": 0,
|
||||
"mode_revision": 0,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
assert [action for action, _ in device.facade.actions] == ["state.read", "connection.verify"]
|
||||
payload = device.facade.actions[-1][1]
|
||||
assert payload["source"] == "durable-configured-state"
|
||||
assert payload["device_id"] == "AA:BB:CC:DD:EE:FF"
|
||||
assert payload["expected_snapshot_runtime_id"] == "runtime-one"
|
||||
assert "password" not in payload and "ssid" not in payload
|
||||
assert device.facade.current["active_acquisition_recovery_checkpoint"] == checkpoint
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
"foreign-target",
|
||||
"denied-policy",
|
||||
"other-mode",
|
||||
"stale-generation",
|
||||
"stale-runtime",
|
||||
"provision",
|
||||
],
|
||||
)
|
||||
def test_saved_recovery_never_authorizes_foreign_stale_or_mutating_action(change):
|
||||
device = bridge()
|
||||
device.facade.current = cold_recovery_state()
|
||||
parameters = {"device_id": "AA:BB:CC:DD:EE:FF", "discovery_generation": 0, "mode_revision": 0}
|
||||
action, runtime = "verify", "runtime-one"
|
||||
policy = device.facade.current["connection_policy"]["actions"][
|
||||
"observe-configured-device-network"
|
||||
]
|
||||
if change == "foreign-target":
|
||||
parameters["device_id"] = "other-device"
|
||||
if change == "denied-policy":
|
||||
policy["allowed"] = False
|
||||
if change == "other-mode":
|
||||
policy["required_connection_mode"] = "quick-connect"
|
||||
if change == "stale-generation":
|
||||
parameters["discovery_generation"] = 1
|
||||
if change == "stale-runtime":
|
||||
runtime = "previous-runtime"
|
||||
if change == "provision":
|
||||
action = "connect"
|
||||
with pytest.raises(ValueError):
|
||||
asyncio.run(
|
||||
device.execute(
|
||||
{
|
||||
"operation_id": "op_" + "f" * 32,
|
||||
"runtime_id": runtime,
|
||||
"action": action,
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"parameters": parameters,
|
||||
}
|
||||
)
|
||||
)
|
||||
assert device.facade.actions == [("state.read", {})]
|
||||
|
||||
|
||||
def test_verification_failure_survives_polling_but_not_a_new_runtime():
|
||||
current = cold_recovery_state()
|
||||
current["operations"] = [
|
||||
{
|
||||
"operation_id": "op-" + str(__import__("uuid").UUID(int=123)),
|
||||
"action": "connection.verify",
|
||||
"status": "failed",
|
||||
"context": {"snapshot_runtime_id": "runtime-one"},
|
||||
"error": {
|
||||
"code": "connection-verify-device-not-rediscovered",
|
||||
"message": "private-detail",
|
||||
},
|
||||
}
|
||||
]
|
||||
projected = NodeBridge.project(current)
|
||||
assert projected["verification"]["error_code"] == "connection-verify-device-not-rediscovered"
|
||||
assert projected["connected"] is False
|
||||
assert projected["acquisition_recovery"]["state"] == "active"
|
||||
assert "private-detail" not in json.dumps(projected)
|
||||
assert "must-not-cross-node-projection" not in json.dumps(projected)
|
||||
current["snapshot_runtime_id"] = "new-runtime"
|
||||
assert NodeBridge.project(current)["verification"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("committed", [True, False])
|
||||
def test_onboard_reset_uses_real_facade_without_old_monitor_or_adapter_lock(committed):
|
||||
calls = []
|
||||
|
||||
class Service:
|
||||
def require_snapshot_runtime_id(self, expected):
|
||||
assert expected == "runtime-one"
|
||||
|
||||
def bind_runtime_event_loop(self, _loop):
|
||||
pytest.fail("local reset must not bind the old connection monitor")
|
||||
|
||||
def select_connection_mode(self, request):
|
||||
calls.append(request.model_dump())
|
||||
value = state()
|
||||
if committed:
|
||||
value["desired_connection_mode_revision"] = 1
|
||||
value["connection_scenario_reset"] = {
|
||||
"reset_id": request.reset_id,
|
||||
"revision": 1,
|
||||
"local_session_closed": True,
|
||||
}
|
||||
return value
|
||||
|
||||
async def run():
|
||||
device = NodeBridge(Path.cwd(), service=Service())
|
||||
command = {
|
||||
"operation_id": "op_" + "d" * 32,
|
||||
"runtime_id": "runtime-one",
|
||||
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
|
||||
"action": "reset",
|
||||
"parameters": {"mode_revision": 0},
|
||||
}
|
||||
async with device.lock:
|
||||
result = await asyncio.wait_for(device.execute(command), timeout=1)
|
||||
assert result["command_result"]["status"] == ("succeeded" if committed else "failed")
|
||||
assert result["can_reset"] is True
|
||||
|
||||
asyncio.run(run())
|
||||
assert calls == [{
|
||||
"connection_mode": "bridge", "expected_revision": 0,
|
||||
"reset_scenario": True, "reset_id": plugin_operation_id("op_" + "d" * 32),
|
||||
}]
|
||||
|
||||
|
||||
def test_reset_hides_previous_verify_even_after_scan_settles_reset_marker():
|
||||
current = state()
|
||||
current["connection_scenario_reset"] = {
|
||||
"active": False,
|
||||
"timing": {"completed_at_utc": "2026-11-01T12:00:00.500Z"},
|
||||
}
|
||||
old = {"operation_id": "op-old", "action": "connection.verify", "status": "failed",
|
||||
"context": {"snapshot_runtime_id": "runtime-one"},
|
||||
"accepted_at": "2026-11-01T11:59:59Z"}
|
||||
current["operations"] = [old]
|
||||
assert NodeBridge.project(current)["verification"] is None
|
||||
current["operations"].append({**old, "operation_id": "op-new",
|
||||
"accepted_at": "2026-11-01T12:00:01Z"})
|
||||
assert NodeBridge.project(current)["verification"]["operation_id"] == "op-new"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("age,connected,used,visible", [
|
||||
(1, True, 99.0, True), (1, True, 0.0, True), (1, True, 100.0, True),
|
||||
(6, True, 99.0, False), (-1, True, 99.0, False),
|
||||
(1, False, 99.0, False), (1, True, float("nan"), False),
|
||||
(1, True, 101.0, False), (1, True, True, False),
|
||||
])
|
||||
def test_storage_projection_uses_only_current_connected_status(age, connected, used, visible):
|
||||
current = state()
|
||||
current["connection_lifecycle"]["connection_ready"] = connected
|
||||
current["application_control_session"]["transport"] = {"storage_status": {
|
||||
"used_percent": used, "observed_at": (datetime.now(UTC)-timedelta(seconds=age)).isoformat(),
|
||||
}}
|
||||
result = project_sensor(current, "node-test")
|
||||
assert (result["storage_status"] is not None) is visible
|
||||
assert result["control"]["can_start"] is True # Display telemetry grants no authority.
|
||||
|
||||
@@ -11543,6 +11543,7 @@ class _ActualWorkerStopRaceExecutor:
|
||||
observed: Callable[[], bool],
|
||||
*,
|
||||
reconciled_active_observed: Callable[[], bool] | None = None,
|
||||
standby_work: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
deadline = time.monotonic() + 3.0
|
||||
while not observed():
|
||||
@@ -11550,6 +11551,8 @@ class _ActualWorkerStopRaceExecutor:
|
||||
return None
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("actual worker checkpoint was not released")
|
||||
if standby_work is not None:
|
||||
standby_work()
|
||||
threading.Event().wait(0.005)
|
||||
return None
|
||||
|
||||
@@ -15472,6 +15475,62 @@ def test_post_start_refresh_timeout_wakes_existing_read_only_recovery(
|
||||
assert service._physical_command_coordinator.snapshot() is physical # noqa: SLF001
|
||||
|
||||
|
||||
@pytest.mark.parametrize("confirmed_start", [True, False])
|
||||
@pytest.mark.parametrize("brief_gap", [True, False])
|
||||
def test_returned_host_epoch_wakes_active_recovery_with_surviving_data_socket(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
brief_gap: bool,
|
||||
confirmed_start: bool,
|
||||
) -> None:
|
||||
service, runtime = service_with_fake_runtime(tmp_path)
|
||||
control, physical = _install_composite_active_recovery_fixture(
|
||||
service, runtime, monkeypatch, runtime_phase="live", camera_phase="streaming",
|
||||
)
|
||||
if not confirmed_start:
|
||||
physical["requires_reconciliation"] = True
|
||||
supervisor = service._connection_supervisor # noqa: SLF001
|
||||
before = supervisor.snapshot()
|
||||
if brief_gap:
|
||||
supervisor.observe_host_path(HostPathProbeResult(
|
||||
available=False, fingerprint=None, interface=None, source_ipv4=None,
|
||||
route_class="unavailable", reason_code="host-route-unavailable",
|
||||
))
|
||||
supervisor.observe_host_path(HostPathProbeResult(
|
||||
available=True,
|
||||
fingerprint=before.host_path.fingerprint if brief_gap else "same-lan-new-association",
|
||||
interface=before.host_path.interface, source_ipv4=before.host_path.source_ipv4,
|
||||
route_class=before.host_path.route_class,
|
||||
kernel_route_fingerprint=before.host_path.kernel_route_fingerprint,
|
||||
))
|
||||
assert supervisor.snapshot().host_path_negative_streak == 0
|
||||
assert supervisor.snapshot().control_plane.reason_code == "host-path-epoch-changed"
|
||||
starts = list(control.start_projects)
|
||||
stops = control.stop_calls
|
||||
|
||||
state = service.state()
|
||||
service.state()
|
||||
|
||||
if not confirmed_start:
|
||||
assert runtime.recovery_requests == []
|
||||
assert control.start_projects == starts
|
||||
assert control.stop_calls == stops
|
||||
assert runtime.stop_calls == 0
|
||||
return
|
||||
assert runtime.recovery_requests == [
|
||||
("host-path-epoch-changed", runtime.producer_generation),
|
||||
]
|
||||
assert state["phase"] == "reconnecting"
|
||||
assert state["connection_recovery"]["automatic_read_only_rebind"] is True
|
||||
assert state["acquisition"]["state"] == "acquiring"
|
||||
assert state["selected_device_id"] == "test-ble-transport"
|
||||
assert control.state == "scanning"
|
||||
assert control.start_projects == starts
|
||||
assert control.stop_calls == stops
|
||||
assert runtime.stop_calls == 0
|
||||
assert service._physical_command_coordinator.snapshot() is physical # noqa: SLF001
|
||||
|
||||
|
||||
def test_incident_host_route_streak_wakes_recovery_before_binding_retirement(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@@ -34813,3 +34872,54 @@ def test_completed_acquisition_does_not_imply_control_loss(tmp_path, socket_open
|
||||
{**control, "state": "failed"}, {"source_mode": "idle"},
|
||||
)
|
||||
assert not service._connection_supervisor.snapshot().authority.control_allowed # noqa: SLF001
|
||||
|
||||
|
||||
@pytest.mark.parametrize("writer_alive", [False, True])
|
||||
def test_fresh_start_recovers_only_terminated_evidence_writer_marker(
|
||||
tmp_path: Path, writer_alive: bool,
|
||||
) -> None:
|
||||
from k1link.sessions.active import ActiveSessionLease, ActiveSessionLeaseError
|
||||
|
||||
service, runtime = service_with_fake_runtime(tmp_path)
|
||||
control = FakeInteractiveControlSession()
|
||||
service._application_control_session = control # type: ignore[assignment] # noqa: SLF001
|
||||
_seed_supervised_connection(service)
|
||||
prepared = service.prepare_acquisition(
|
||||
_prepare_request(
|
||||
project_name="LEASE_RECOVERY",
|
||||
host="192.168.1.20",
|
||||
compatibility_attestation=ATTESTATION,
|
||||
)
|
||||
)
|
||||
root = service.evidence_root
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
interrupted = root / "20260813T120000Z_viewer_live"
|
||||
interrupted.mkdir()
|
||||
original_evidence = interrupted / "preserved.raw"
|
||||
original_evidence.write_bytes(b"synthetic interrupted evidence")
|
||||
owner = ActiveSessionLease.acquire(root, interrupted) if writer_alive else None
|
||||
if owner is None:
|
||||
(root / ".current_session").write_text(interrupted.name + "\n")
|
||||
try:
|
||||
request = _start_request(
|
||||
acquisition_id=prepared["acquisition"]["acquisition_id"],
|
||||
physical_acceptance=PHYSICAL_ACCEPTANCE,
|
||||
)
|
||||
if writer_alive:
|
||||
with pytest.raises(ActiveSessionLeaseError):
|
||||
service.start_acquisition(request)
|
||||
assert runtime.start_calls == []
|
||||
assert control.start_projects == []
|
||||
assert (root / ".current_session").read_text().strip() == interrupted.name
|
||||
else:
|
||||
service.start_acquisition(request)
|
||||
assert len(runtime.start_calls) == 1
|
||||
assert control.start_projects == ["LEASE_RECOVERY"]
|
||||
assert (root / ".current_session").read_text().strip() != interrupted.name
|
||||
assert original_evidence.read_bytes() == b"synthetic interrupted evidence"
|
||||
finally:
|
||||
if owner is not None:
|
||||
owner.release()
|
||||
lease = service._acquisition_session_lease # noqa: SLF001
|
||||
if lease is not None:
|
||||
lease.release()
|
||||
|
||||
@@ -272,6 +272,11 @@ def _prepare_and_activate_checkpoint(
|
||||
service._application_control_session.snapshot = lambda: { # type: ignore[method-assign]
|
||||
"verified_control": _verified_control(connection)
|
||||
}
|
||||
# Camera admission now reads the control-only projection. Both projections
|
||||
# must observe the same synthetic dialogue, including later epoch updates.
|
||||
service._application_control_session.snapshot_control_only = ( # type: ignore[method-assign]
|
||||
lambda: service._application_control_session.snapshot() # noqa: SLF001
|
||||
)
|
||||
service._observe_start_preparation_checkpoint( # noqa: SLF001
|
||||
"prepared",
|
||||
context,
|
||||
@@ -317,9 +322,15 @@ def _prepare_and_activate_checkpoint(
|
||||
service._observe_application_scanning_checkpoint() # noqa: SLF001
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prior_rebind", [False, True])
|
||||
@pytest.mark.parametrize("standby_committed", [False, True])
|
||||
@pytest.mark.parametrize("changed_ip", [False, True])
|
||||
def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
prior_rebind: bool,
|
||||
standby_committed: bool,
|
||||
changed_ip: bool,
|
||||
) -> None:
|
||||
"""Fresh READY after Apply settles the old START and its checkpoint.
|
||||
|
||||
@@ -340,28 +351,29 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
current = ledger.snapshot().record
|
||||
assert current is not None
|
||||
|
||||
active_rebind_connection = _connection(
|
||||
control_session_id="checkpoint-reset-active-rebind-control",
|
||||
host_path_epoch=2,
|
||||
producer_generation=2,
|
||||
)
|
||||
current = ledger.rebind_resolved_active(
|
||||
current.operation_id,
|
||||
reconciliation_id="checkpoint-reset-active-rebind",
|
||||
verified_binding=PhysicalCommandVerifiedBinding(
|
||||
verification_id="checkpoint-reset-active-rebind.device-info",
|
||||
identity=current.identity,
|
||||
connection=active_rebind_connection,
|
||||
device_info_message_sha256="2" * 64,
|
||||
verified_at_utc="2026-08-13T12:01:00.000Z",
|
||||
),
|
||||
observation=_status(
|
||||
active_rebind_connection,
|
||||
"scanning",
|
||||
source="explicit-read-only-reconciliation",
|
||||
observed_at_utc="2026-08-13T12:01:01.000Z",
|
||||
),
|
||||
)
|
||||
if prior_rebind:
|
||||
active_rebind_connection = _connection(
|
||||
control_session_id="checkpoint-reset-active-rebind-control",
|
||||
host_path_epoch=2,
|
||||
producer_generation=2,
|
||||
)
|
||||
current = ledger.rebind_resolved_active(
|
||||
current.operation_id,
|
||||
reconciliation_id="checkpoint-reset-active-rebind",
|
||||
verified_binding=PhysicalCommandVerifiedBinding(
|
||||
verification_id="checkpoint-reset-active-rebind.device-info",
|
||||
identity=current.identity,
|
||||
connection=active_rebind_connection,
|
||||
device_info_message_sha256="2" * 64,
|
||||
verified_at_utc="2026-08-13T12:01:00.000Z",
|
||||
),
|
||||
observation=_status(
|
||||
active_rebind_connection,
|
||||
"scanning",
|
||||
source="explicit-read-only-reconciliation",
|
||||
observed_at_utc="2026-08-13T12:01:01.000Z",
|
||||
),
|
||||
)
|
||||
for cycle in (1, 2):
|
||||
retired = ledger.retire_unavailable_target(
|
||||
retirement_id=f"checkpoint-reset-retirement-{cycle}",
|
||||
@@ -379,7 +391,7 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
reason="reset-network-intent-read-only-settlement",
|
||||
)
|
||||
assert current.stage == "observing"
|
||||
assert current.reconciled_physical_state == "active"
|
||||
assert current.reconciled_physical_state == ("active" if prior_rebind else None)
|
||||
|
||||
# The persisted ACTIVE checkpoint belongs to the process that owned the
|
||||
# original receiver. The real failure was observed after a service
|
||||
@@ -391,6 +403,8 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
host_path_epoch=4,
|
||||
producer_generation=4,
|
||||
)
|
||||
if changed_ip:
|
||||
ready_connection = replace(ready_connection, target_ipv4="192.168.68.51")
|
||||
coordinator = service._physical_command_coordinator # noqa: SLF001
|
||||
coordinator.application_response(
|
||||
ApplicationMqttResponseEvidence(
|
||||
@@ -435,6 +449,12 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
lambda: None,
|
||||
)
|
||||
|
||||
if standby_committed:
|
||||
# The physical READY fsync survived but the checkpoint commit did not.
|
||||
coordinator.reconcile_resolved_active(reconciliation_id="checkpoint-reset-ready-verify.physical")
|
||||
service._mark_active_acquisition_checkpoint_untrusted( # noqa: SLF001
|
||||
trust="unavailable", reason_code="active-acquisition-recovery-checkpoint-error"
|
||||
)
|
||||
result = asyncio.run(
|
||||
service._reconcile_physical_command_after_verify_owned( # noqa: SLF001
|
||||
verify_operation_id="checkpoint-reset-ready-verify",
|
||||
@@ -442,8 +462,8 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
|
||||
)
|
||||
)
|
||||
|
||||
assert result["performed"] is True
|
||||
assert result["resolution"] == "physical-standby-observed"
|
||||
assert result["performed"] is (not standby_committed)
|
||||
assert result["resolution"] == (None if standby_committed else "physical-standby-observed")
|
||||
settled = ledger.snapshot().record
|
||||
assert settled is not None
|
||||
assert settled.stage == "resolved"
|
||||
@@ -1899,6 +1919,67 @@ def test_chained_stop_facade_cessation_uses_real_ledger_ancestry(
|
||||
assert checkpoint.cessation_physical_proof.operation_id == final_record.operation_id
|
||||
assert checkpoint.cessation_physical_proof.ancestor_chain == ancestry
|
||||
|
||||
# A later snapshot may revisit an already durable cessation after a
|
||||
# transient diagnostic failure. Clear only this acquisition's stale reason;
|
||||
# never mutate its journal or hide a different acquisition/trust failure.
|
||||
reason = "active-acquisition-recovery-checkpoint-cease-failed"
|
||||
service._set_active_acquisition_checkpoint_reason(reason) # noqa: SLF001
|
||||
request = dict(
|
||||
expected_acquisition_id=ACQUISITION_ID,
|
||||
expected_start_operation_id=START_OPERATION_ID,
|
||||
evidence_session_id=EVIDENCE_SESSION_ID,
|
||||
expected_stop_operation_id=FINAL_STOP_OPERATION_ID,
|
||||
)
|
||||
assert not service._cease_active_acquisition_checkpoint_from_physical_head( # noqa: SLF001
|
||||
**{**request, "expected_acquisition_id": "other-acquisition"},
|
||||
)
|
||||
assert service._active_acquisition_checkpoint_reason == reason # noqa: SLF001
|
||||
assert service._cease_active_acquisition_checkpoint_from_physical_head(**request) # noqa: SLF001
|
||||
assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
|
||||
assert ActiveAcquisitionRecoveryCheckpointStore(tmp_path).snapshot().checkpoint == checkpoint
|
||||
# Subsequent state polling runs after local receiver/evidence teardown.
|
||||
# It must recognize the same durable terminal, not reintroduce cease-failed.
|
||||
assert service._acquisition is not None # noqa: SLF001
|
||||
service._acquisition = replace(service._acquisition, state="completed") # noqa: SLF001
|
||||
service._acquisition_out_dir = None # noqa: SLF001
|
||||
service._acquisition_stop_operation_id = FINAL_STOP_OPERATION_ID # noqa: SLF001
|
||||
service._set_active_acquisition_checkpoint_reason(reason) # noqa: SLF001
|
||||
for _ in range(2):
|
||||
service._reconcile_acquisition( # noqa: SLF001
|
||||
{"phase": "idle"}, {}, {"state": "completed"},
|
||||
physical_command_proof=service._physical_command_coordinator.snapshot(), # noqa: SLF001
|
||||
)
|
||||
assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
|
||||
assert service._acquisition.state == "completed" # noqa: SLF001
|
||||
assert ActiveAcquisitionRecoveryCheckpointStore(tmp_path).snapshot().checkpoint == checkpoint
|
||||
completed_acquisition = service._acquisition # noqa: SLF001
|
||||
for acquisition_id, start_id in (
|
||||
("other-acquisition", START_OPERATION_ID),
|
||||
(ACQUISITION_ID, "other-start"),
|
||||
):
|
||||
service._acquisition = replace( # noqa: SLF001
|
||||
completed_acquisition, acquisition_id=acquisition_id,
|
||||
)
|
||||
service._acquisition_start_operation_id = start_id # noqa: SLF001
|
||||
service._reconcile_acquisition( # noqa: SLF001
|
||||
{"phase": "idle"}, {}, {"state": "completed"},
|
||||
)
|
||||
assert service._active_acquisition_checkpoint_reason == reason # noqa: SLF001
|
||||
service._acquisition = completed_acquisition # noqa: SLF001
|
||||
service._acquisition_start_operation_id = None # noqa: SLF001
|
||||
service._acquisition_stop_operation_id = None # noqa: SLF001
|
||||
service._reconcile_acquisition( # noqa: SLF001
|
||||
{"phase": "idle"}, {}, {"state": "completed"},
|
||||
)
|
||||
assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
|
||||
service._mark_active_acquisition_checkpoint_untrusted( # noqa: SLF001
|
||||
trust="unavailable", reason_code="active-acquisition-recovery-checkpoint-error",
|
||||
)
|
||||
assert service._cease_active_acquisition_checkpoint_from_physical_head(**request) # noqa: SLF001
|
||||
assert service._active_acquisition_checkpoint_reason == ( # noqa: SLF001
|
||||
"active-acquisition-recovery-checkpoint-error"
|
||||
)
|
||||
|
||||
|
||||
def test_restart_ceases_active_checkpoint_after_composite_ordinary_stop(
|
||||
tmp_path: Path,
|
||||
|
||||
@@ -1765,3 +1765,103 @@ def test_close_after_dispatch_precheck_prevents_queued_publish_after_gate_releas
|
||||
assert fake.publish_calls == []
|
||||
assert transport.snapshot().publish_attempts == 0
|
||||
assert evidence.events == []
|
||||
|
||||
|
||||
def test_observed_advisory_does_not_break_existing_control_or_grant_start() -> None:
|
||||
clock = FakeClock()
|
||||
fake = FakeControlClient(clock=clock)
|
||||
transport = ReviewedApplicationMqttTransport(
|
||||
"192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
|
||||
)
|
||||
transport.open()
|
||||
fake.events.extend([
|
||||
("message", (DEVICE_STATUS_TOPIC, _device_status(
|
||||
SessionState.SCANNING, project_bound=True, init_ready=True))),
|
||||
("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))),
|
||||
])
|
||||
transport.maintain_open_for(4.0)
|
||||
assert transport.scan_initialization_complete(_binding()) is True
|
||||
assert transport.pre_start_ready(_binding()) is False
|
||||
assert transport.standby_complete(_binding()) is False
|
||||
snapshot = transport.snapshot().as_dict()
|
||||
assert snapshot["system_error_reports"] == 1
|
||||
assert snapshot["latest_system_error_code"] == 0x12041002
|
||||
assert snapshot["publish_attempts"] == 0
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, _device_status(
|
||||
SessionState.READY, project_bound=False, init_ready=False))))
|
||||
transport.maintain_open_for(4.0)
|
||||
assert transport.standby_complete(_binding()) is True
|
||||
transport.validate_control_proof(_binding())
|
||||
proof = transport.snapshot()
|
||||
clock.now += 100.0
|
||||
fake.events.append(("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))))
|
||||
transport.maintain_open_for(1.0)
|
||||
assert transport.snapshot().control_proof_revision == proof.control_proof_revision
|
||||
with pytest.raises(ApplicationControlProofStale):
|
||||
transport.validate_control_proof(_binding())
|
||||
assert transport.snapshot().publish_attempts == 0
|
||||
transport.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", [0x32040133, 0x12041003, 0x22041002, 0])
|
||||
def test_unreviewed_or_fault_report_stays_blocking_after_advisory(code: int) -> None:
|
||||
clock = FakeClock()
|
||||
fake = FakeControlClient(clock=clock)
|
||||
transport = ReviewedApplicationMqttTransport(
|
||||
"192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
|
||||
)
|
||||
transport.open()
|
||||
fake.events.extend([
|
||||
("message", (DEVICE_STATUS_TOPIC, _device_status(
|
||||
SessionState.SCANNING, project_bound=True, init_ready=True))),
|
||||
("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, code)))),
|
||||
("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))),
|
||||
])
|
||||
transport.maintain_open_for(4.0)
|
||||
with pytest.raises(ApplicationControlDeviceFault):
|
||||
transport.validate_bound_status(_binding())
|
||||
assert transport.snapshot().as_dict()["publish_attempts"] == 0
|
||||
transport.close()
|
||||
|
||||
|
||||
def test_storage_observation_requires_fresh_nonretained_bound_identity():
|
||||
clock = FakeClock()
|
||||
fake = FakeControlClient(clock=clock)
|
||||
transport = ReviewedApplicationMqttTransport(
|
||||
"192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
|
||||
)
|
||||
transport.open()
|
||||
payload = _device_status(SessionState.READY, project_bound=False, init_ready=False)
|
||||
payload += _bytes(7, _uint(4, 1000) + _uint(5, 990))
|
||||
fake.on_message(
|
||||
fake, None, SimpleNamespace(topic=DEVICE_STATUS_TOPIC, payload=payload, retain=True)
|
||||
)
|
||||
assert transport.snapshot().storage_status is None
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, payload)))
|
||||
transport.maintain_open_for(1.0)
|
||||
assert transport.snapshot().storage_status is None
|
||||
transport.validate_control_proof(_binding())
|
||||
value = transport.snapshot().as_dict()["storage_status"]
|
||||
assert value["used_percent"] == 99.0 and value["observed_at"]
|
||||
value["used_percent"] = 0
|
||||
assert transport.snapshot().storage_status["used_percent"] == 99.0
|
||||
next_payload = _device_status(SessionState.READY, project_bound=False, init_ready=False)
|
||||
next_payload += _bytes(7, _uint(4, 1000) + _uint(5, 980))
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, next_payload)))
|
||||
transport.maintain_open_for(1.0)
|
||||
# An idle session need not re-run command admission for each display update.
|
||||
assert transport.snapshot().storage_status["used_percent"] == 98.0
|
||||
# Keep protobuf framing valid by constructing the report with a new serial.
|
||||
wrong_identity = (_bytes(1, _text(4, VENDOR_DEVICE_ID))
|
||||
+ _uint(2, MODELING_STATE_BASE + SessionState.READY)
|
||||
+ _text(3, "other-scanner") + _bytes(7, _uint(4, 1000) + _uint(5, 990)))
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, wrong_identity)))
|
||||
transport.maintain_open_for(1.0)
|
||||
assert transport.snapshot().storage_status is None
|
||||
fake.events.append(("message", (DEVICE_STATUS_TOPIC, _device_status(
|
||||
SessionState.READY, project_bound=False, init_ready=False))))
|
||||
transport.maintain_open_for(1.0)
|
||||
transport.validate_control_proof(_binding())
|
||||
assert transport.snapshot().storage_status is None
|
||||
assert transport.snapshot().publish_attempts == 0
|
||||
transport.close()
|
||||
|
||||
@@ -306,10 +306,13 @@ class FakeExecutor:
|
||||
observed: Any,
|
||||
*,
|
||||
reconciled_active_observed: Any | None = None,
|
||||
standby_work: Callable[[], None] | None = None,
|
||||
) -> str | None:
|
||||
self.records.append(f"wait:{event}")
|
||||
deadline = time.monotonic() + 2.0
|
||||
while not observed():
|
||||
if standby_work is not None:
|
||||
standby_work()
|
||||
if (
|
||||
reconciled_active_observed is not None
|
||||
and reconciled_active_observed()
|
||||
@@ -372,8 +375,12 @@ class FakeExecutor:
|
||||
def maintain_post_stop_until_standby(self) -> None:
|
||||
self.records.append("wait:device-standby")
|
||||
|
||||
def maintain_standby_until_next_acquisition(self, requested: Callable[[], bool]) -> None:
|
||||
def maintain_standby_until_next_acquisition(
|
||||
self, requested: Callable[[], bool], *, standby_work: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
while not requested():
|
||||
if standby_work is not None:
|
||||
standby_work()
|
||||
if self.transport.state == "closed":
|
||||
raise RuntimeError("test transport closed")
|
||||
if not self.transport.proof_fresh:
|
||||
|
||||
@@ -58,7 +58,10 @@ def test_xgrids_compatibility_profile_loads_exact_firmware_and_sources() -> None
|
||||
"bridge": "direct-lan",
|
||||
"direct-connect": "controller-hotspot",
|
||||
"quick-connect": "device-ap",
|
||||
"usb": "usb-ethernet",
|
||||
}
|
||||
assert LOADER.matches_target(profile, firmware="3.0.2", topology="usb-ethernet")
|
||||
assert not LOADER.matches_target(profile, firmware="3.0.3", topology="usb-ethernet")
|
||||
assert LOADER.matches_target(profile, firmware="3.0.2", topology="direct-lan")
|
||||
assert LOADER.matches_target(profile, firmware="3.0.2", topology="device-ap")
|
||||
assert LOADER.matches_target(
|
||||
|
||||
@@ -351,10 +351,14 @@ def test_cold_scenario_reset_is_local_only_and_exact_retry_converges(
|
||||
"network_write_performed": False,
|
||||
"automatic_scan": False,
|
||||
"operation_sequence": 0,
|
||||
"timing": first["connection_scenario_reset"]["timing"],
|
||||
}
|
||||
assert first["devices"] == []
|
||||
assert first["selected_device_id"] is None
|
||||
assert first["connection_attempt"] is None
|
||||
timing = first["connection_scenario_reset"]["timing"]
|
||||
assert timing["completed_at_utc"]
|
||||
assert all(value >= 0 for key, value in timing.items() if key.endswith("_ms"))
|
||||
assert first["connection_scenario_reset_pending"] is None
|
||||
assert service.state()["connection_scenario_reset_pending"] is None
|
||||
assert first["connection_policy"]["actions"]["scan-ble"]["allowed"] is True
|
||||
|
||||
@@ -343,3 +343,25 @@ def test_state_machine_surfaces_faults_without_claiming_save() -> None:
|
||||
)
|
||||
assert unknown.phase is AcquisitionPhase.UNKNOWN
|
||||
assert not unknown.durable_save_complete
|
||||
|
||||
|
||||
@pytest.mark.parametrize("system,expected", [
|
||||
(_uint(4, 1001324032) + _uint(5, 991202816), 98.9892167094218),
|
||||
(_uint(4, 1000), 0.0),
|
||||
(_uint(4, 1000) + _uint(5, 1000), 100.0),
|
||||
(b"", None),
|
||||
(_uint(4, 0) + _uint(5, 20), None),
|
||||
(_uint(4, 10) + _uint(5, 20), None),
|
||||
(_uint(4, 10) + _uint(4, 20), None),
|
||||
(_uint(4, 10) + _uint(5, (1 << 64) - 1), None),
|
||||
(_bytes(4, b"wrong-wire"), None),
|
||||
(b"\x20\x80", None),
|
||||
])
|
||||
def test_optional_storage_ratio_never_changes_modeling_state(system, expected):
|
||||
result = decode_device_status_report(_device_status(SessionState.READY) + _bytes(7, system))
|
||||
assert result.session_state is SessionState.READY
|
||||
assert result.system_status_present
|
||||
if expected is None:
|
||||
assert result.storage_used_percent is None
|
||||
else:
|
||||
assert result.storage_used_percent == pytest.approx(expected, abs=0.0001)
|
||||
|
||||
@@ -2878,6 +2878,95 @@ def test_repeated_resolved_start_retire_reopen_settles_fresh_ready_as_cessation(
|
||||
assert settled.reconciliations[-1].original_attempt.operation_id == START_OPERATION
|
||||
|
||||
|
||||
@pytest.mark.parametrize("observed_state", ["ready", "scanning"])
|
||||
@pytest.mark.parametrize("reset_count", [1, 2])
|
||||
@pytest.mark.parametrize("proof_fault", [None, "retained", "identity", "old-session"])
|
||||
def test_first_successful_start_reset_reopens_without_prior_rebind(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
observed_state: str,
|
||||
reset_count: int,
|
||||
proof_fault: str | None,
|
||||
) -> None:
|
||||
"""The first reset has no prior reconciliation to supply an active state."""
|
||||
ledger = _ledger(tmp_path, monkeypatch)
|
||||
_prepare_start(ledger)
|
||||
_complete_start(ledger)
|
||||
original = ledger.snapshot().record
|
||||
assert original is not None
|
||||
current = original
|
||||
for cycle in range(reset_count):
|
||||
retired = ledger.retire_unavailable_target(
|
||||
retirement_id=f"first-start-reset-{cycle}",
|
||||
expected_operation_id=current.operation_id,
|
||||
expected_revision=current.revision,
|
||||
expected_transport_ref=current.connection.transport_ref,
|
||||
reason="connection-scenario-reset-by-operator",
|
||||
)
|
||||
current = ledger.reopen_retired_reconciliation(
|
||||
reopening_id=f"first-start-reopen-{cycle}",
|
||||
expected_revision=retired.revision,
|
||||
expected_retirement_id=f"first-start-reset-{cycle}",
|
||||
expected_transport_ref=retired.connection.transport_ref,
|
||||
expected_discovery_generation=40 + cycle,
|
||||
reason="reset-network-intent-read-only-settlement",
|
||||
)
|
||||
assert current.stage == "observing"
|
||||
assert current.reconciled_physical_state is None
|
||||
assert current.reopened_resolved_start_requires_reconciliation
|
||||
connection = _reconciliation_connection()
|
||||
settle = (
|
||||
ledger.observe_resolved_active_standby
|
||||
if observed_state == "ready"
|
||||
else ledger.rebind_resolved_active
|
||||
)
|
||||
binding = _verified_binding(connection=connection)
|
||||
observation = _status(
|
||||
observed_state,
|
||||
connection=connection,
|
||||
source="explicit-read-only-reconciliation",
|
||||
observed_at="2026-08-07T09:34:00.000Z",
|
||||
)
|
||||
if proof_fault == "retained":
|
||||
observation = replace(observation, mqtt_retained=True)
|
||||
elif proof_fault == "identity":
|
||||
binding = replace(binding, identity=replace(IDENTITY, device_serial_sha256="9" * 64))
|
||||
elif proof_fault == "old-session":
|
||||
binding = replace(binding, connection=original.connection)
|
||||
if proof_fault is not None:
|
||||
before = ledger.path.read_bytes()
|
||||
with pytest.raises(PhysicalCommandTransitionError):
|
||||
settle(
|
||||
START_OPERATION,
|
||||
reconciliation_id="first-reset-invalid-state",
|
||||
verified_binding=binding,
|
||||
observation=observation,
|
||||
)
|
||||
assert ledger.path.read_bytes() == before
|
||||
return
|
||||
settled = settle(
|
||||
START_OPERATION,
|
||||
reconciliation_id="first-reset-fresh-state",
|
||||
verified_binding=binding,
|
||||
observation=observation,
|
||||
)
|
||||
assert settled.stage == "resolved"
|
||||
assert settled.resolution == "start-active-observed"
|
||||
assert settled.original_command_outcome == "succeeded"
|
||||
assert settled.reconciled_physical_state == (
|
||||
"standby" if observed_state == "ready" else "active"
|
||||
)
|
||||
assert settled.reconciliations[-1].kind == (
|
||||
"resolved-active-cessation" if observed_state == "ready" else "resolved-active-rebind"
|
||||
)
|
||||
assert settled.operator_retirements[0].original_attempt.as_dict() == (
|
||||
settled.reconciliations[-1].original_attempt.as_dict()
|
||||
)
|
||||
assert settled.application_response == original.application_response
|
||||
assert settled.payload_sha256 == original.payload_sha256
|
||||
assert PhysicalCommandLedger(tmp_path / "repository", clock=_clock).snapshot().record == settled
|
||||
|
||||
|
||||
def test_legacy_v1_unresolved_attempt_retires_atomically_into_strict_v2(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
Reference in New Issue
Block a user