feat(node): add confirmed board shutdown with expiring commands
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import {useEffect, useRef, useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
|
||||
export interface BoardPowerView {
|
||||
available:boolean; epoch:string|null; reason:string;
|
||||
operation:{id:string;state:string;message:string}|null;
|
||||
}
|
||||
export function useBoardPower(vehicleId:string) {
|
||||
const [value,setValue]=useState<BoardPowerView|null>(null);
|
||||
const [error,setError]=useState('');
|
||||
const [busy,setBusy]=useState(false);
|
||||
const sending=useRef(false);
|
||||
useEffect(()=>{
|
||||
let active=true; let timer:ReturnType<typeof setTimeout>;
|
||||
const controller=new AbortController();
|
||||
setValue(null);setError('');
|
||||
const poll=async()=>{
|
||||
try {const next=await fleetRequest<BoardPowerView>(`/${encodeURIComponent(vehicleId)}/power`,'GET',undefined,8000,controller.signal);if(active)setValue(next);}
|
||||
catch {if(active)setValue(current=>current?{...current,available:false,reason:'Состояние борта недоступно.'}:null);}
|
||||
finally {if(active)timer=setTimeout(poll,1000);}
|
||||
};
|
||||
void poll(); return()=>{active=false;controller.abort();clearTimeout(timer);};
|
||||
},[vehicleId]);
|
||||
const shutdown=async(expectedEpoch:string)=>{
|
||||
if(sending.current)return false;
|
||||
sending.current=true;setBusy(true);setError('');
|
||||
try {
|
||||
const next=await fleetRequest<BoardPowerView>(`/${encodeURIComponent(vehicleId)}/power/shutdown`,'POST',{expected_epoch:expectedEpoch,request_id:crypto.randomUUID()});
|
||||
setValue(next);return true;
|
||||
} catch(e) {setError(e instanceof Error?e.message:'Не удалось передать команду.');return false;}
|
||||
finally {sending.current=false;setBusy(false);}
|
||||
};
|
||||
return {value,error,busy,shutdown};
|
||||
}
|
||||
Reference in New Issue
Block a user