fix(vesc): recover cancelled controller preparation without rearming
This commit is contained in:
@@ -6,8 +6,9 @@ from .release_observation import ReleaseObservation
|
||||
|
||||
|
||||
class PreflightRecovery:
|
||||
def __init__(self, profile):
|
||||
def __init__(self, profile, *, cancelled=False):
|
||||
self.profile = copy.deepcopy(profile)
|
||||
self.cancelled = cancelled
|
||||
self.proof = None
|
||||
|
||||
def reset(self):
|
||||
|
||||
@@ -240,9 +240,9 @@ class RemoteControl:
|
||||
self.pending_release = ReleaseObservation(devices, time.monotonic())
|
||||
|
||||
def _reconcile_preflight(self, devices):
|
||||
# Only the missing-device preflight path creates this observer. No
|
||||
# motor output/configuration was attempted, so it cannot invent a
|
||||
# historical release ACK or clear an unrelated execution fault.
|
||||
# Missing-device failures and cancelled preparation both reuse passive
|
||||
# whole-profile proof. Neither path revives a retired input lease;
|
||||
# historical hardware faults remain terminal in last_stop.
|
||||
with self.lock:
|
||||
pending = self.pending_availability
|
||||
if pending is None:
|
||||
@@ -253,9 +253,23 @@ class RemoteControl:
|
||||
or self.service.motor.active or firmware_active):
|
||||
pending.reset()
|
||||
return
|
||||
if not pending.check(self.service.drive.value, devices, time.monotonic(),
|
||||
self.service.motor.receiver_active, self.service.motor.limits.pending):
|
||||
ready = pending.check(self.service.drive.value, devices, time.monotonic(),
|
||||
self.service.motor.receiver_active, self.service.motor.limits.pending)
|
||||
if (pending.cancelled and self.state == "stopping" and pending.proof is not None
|
||||
and pending.proof.faulted(devices, time.monotonic())):
|
||||
self.state = "fault"
|
||||
self.message = "VESC сообщил об ошибке. Проверьте состояние перед включением."
|
||||
if self.last_stop is not None:
|
||||
self.last_stop.update(state="fault", message=self.message)
|
||||
self.trace.add("preparation_recovery_fault", session_id=self.lease.id)
|
||||
if not ready:
|
||||
return
|
||||
if pending.cancelled:
|
||||
# Current neutral proof, not an invented ACK for an output that
|
||||
# was never claimed. Limits must already be restored by owner.
|
||||
self.release_confirmed = True
|
||||
self.trace.add("preparation_neutral_confirmed", session_id=self.lease.id,
|
||||
attachments=pending.proof.attachments, samples=pending.proof.count)
|
||||
self.pending_availability = None
|
||||
self.state, self.message = "stopped", None
|
||||
if self.last_stop is not None:
|
||||
@@ -313,6 +327,7 @@ class RemoteControl:
|
||||
owner = self.service.motor
|
||||
acquired = False
|
||||
devices = []
|
||||
profile = copy.deepcopy(self.service.drive.value)
|
||||
try:
|
||||
# Observation also owns this lock. A nonblocking attempt made
|
||||
# arming depend on which thread happened to read first. Wait only
|
||||
@@ -326,7 +341,7 @@ class RemoteControl:
|
||||
acquired = self.service.operation_lock.acquire(timeout=min(.02, remaining))
|
||||
self.ensure_live()
|
||||
with self.service.lock: devices = list(self.service.devices.values())
|
||||
profile = self.service.drive.value
|
||||
profile = copy.deepcopy(self.service.drive.value)
|
||||
slots = LAYOUTS.get(profile["layout"], ())
|
||||
if not slots or set(profile["bindings"]) != set(slots):
|
||||
raise ValueError("Назначьте все моторы в настройках борта.")
|
||||
@@ -352,7 +367,18 @@ class RemoteControl:
|
||||
# drive() classifies only successful, finite release readback
|
||||
# as pending. Keep that state while the passive observer proves
|
||||
# standstill; an expired input is never granted more lifetime.
|
||||
if self.state != "stopping" or not settlement_pending(self.release_evidence):
|
||||
if (self.release_confirmed is None and self.message is None
|
||||
and self.pending_release is None):
|
||||
# Input may expire before acquiring the operation lock, in
|
||||
# preflight, or before drive claims output. A null release
|
||||
# must not leave Core waiting forever. Reuse passive proof
|
||||
# of the exact bound profile; never grant/replay input here.
|
||||
self.pending_availability = PreflightRecovery(profile, cancelled=True)
|
||||
self.state = "stopping"
|
||||
self.trace.add("preparation_cancelled_waiting", session_id=envelope["id"],
|
||||
reason=str(error), operation_acquired=acquired,
|
||||
waiting_for="fresh_neutral_pair_and_restored_limits")
|
||||
elif self.state != "stopping" or not settlement_pending(self.release_evidence):
|
||||
self.state = "fault" if self.message or self.release_confirmed is False else "stopped"
|
||||
except (OSError, ValueError, TimeoutError, KeyError) as error:
|
||||
with self.lock:
|
||||
@@ -378,7 +404,8 @@ class RemoteControl:
|
||||
with self.lock:
|
||||
if not self.lease.live():
|
||||
self.trace.add("lease_expired",session_id=self.lease.id,sequence=self.lease.sequence,
|
||||
remaining_ms=(self.lease.until-time.monotonic())*1000)
|
||||
reason="withdrawn" if self.lease.until == 0 else "deadline_expired",
|
||||
remaining_ms=max(0,(self.lease.until-time.monotonic())*1000))
|
||||
raise ControlEnded("Управление остановлено: команда больше не подтверждается.")
|
||||
|
||||
def drive(self, owner, command, devices, moving, originals, unchanged):
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Real recovery owner, synthetic transport only: never issue motor commands."""
|
||||
import copy
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from runtime.remote_control import ControlEnded, RemoteControl
|
||||
from test_preflight_recovery import observe
|
||||
|
||||
|
||||
def cancelled(stage='preflight'):
|
||||
bindings = {side+'.1': {'device_id': side, 'uuid': str(i)*24}
|
||||
for i, side in enumerate(('left', 'right'), 1)}
|
||||
profile = {'layout': '1x1', 'revision': 2, 'bindings': bindings}
|
||||
devices = [SimpleNamespace(id=b['device_id'], identity={'uuid': b['uuid']},
|
||||
session=b['device_id']+'-live', identified_session=b['device_id']+'-live',
|
||||
link=SimpleNamespace(alive=True), sample=None) for b in bindings.values()]
|
||||
motor = SimpleNamespace(active=False, receiver_active=lambda _, v: abs(v)>.15,
|
||||
limits=SimpleNamespace(pending=lambda _: False), latched=True,
|
||||
run=Mock(side_effect=ControlEnded('input transport gap')))
|
||||
service = SimpleNamespace(motor=motor, lock=threading.RLock(), operation_lock=threading.Lock(),
|
||||
devices={d.id:d for d in devices}, drive=SimpleNamespace(value=profile),
|
||||
firmware_update=SimpleNamespace(lock=threading.Lock(), active=None))
|
||||
remote = RemoteControl(service)
|
||||
remote.trace = SimpleNamespace(add=Mock())
|
||||
remote.lease.id = 'a'*32
|
||||
remote.ensure_live = Mock(side_effect=ControlEnded('expired before ownership') if stage=='lock' else None)
|
||||
remote._prepare({'id':'a'*32, 'settings': {'current_a':30, 'max_erpm':1000}})
|
||||
return remote, devices
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stage', ['lock', 'preflight'])
|
||||
def test_cancelled_preparation_recovers_from_new_neutral_samples_without_output(stage):
|
||||
remote, devices = cancelled(stage)
|
||||
assert remote.state == 'stopping' and remote.release_confirmed is None
|
||||
history = copy.deepcopy(remote.last_stop)
|
||||
for at in (10.,10.2,10.4):
|
||||
observe(remote, devices, at)
|
||||
assert remote.release_confirmed is None
|
||||
observe(remote, devices, 10.6)
|
||||
assert remote.state == 'stopped' and remote.release_confirmed is True
|
||||
assert remote.pending_availability is None
|
||||
assert remote.last_stop['release_confirmed'] is None # Keep historical truth.
|
||||
assert remote.last_stop['state'] == history['state'] == 'stopping'
|
||||
assert 'recovered_at' in remote.last_stop
|
||||
assert not remote.lease.live() and 'a'*32 in remote.lease.retired
|
||||
assert remote.service.motor.latched
|
||||
assert remote.service.motor.run.call_count == (0 if stage=='lock' else 1)
|
||||
assert any(c.args[0]=='preparation_neutral_confirmed' for c in remote.trace.add.call_args_list)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['missing','uuid','unverified','profile','limits','motor','firmware'])
|
||||
def test_cancellation_cannot_bypass_interlocks(case):
|
||||
remote, devices = cancelled()
|
||||
if case == 'missing': devices=devices[:1]
|
||||
if case == 'uuid': devices[0].identity['uuid']='f'*24
|
||||
if case == 'unverified': devices[0].identified_session='old'
|
||||
if case == 'profile': remote.service.drive.value['revision']+=1
|
||||
if case == 'limits': remote.service.motor.limits.pending=lambda _:True
|
||||
if case == 'motor': remote.service.motor.active=True
|
||||
if case == 'firmware': remote.service.firmware_update.active={'device_id':'left'}
|
||||
for at in (10.,10.2,10.4,10.6,10.8): observe(remote, devices, at)
|
||||
assert remote.state == 'stopping' and remote.release_confirmed is None
|
||||
assert not remote.lease.live()
|
||||
|
||||
|
||||
def test_real_fault_during_wait_remains_terminal_even_when_it_clears():
|
||||
remote, devices = cancelled()
|
||||
observe(remote, devices, 10.)
|
||||
devices[0].sample['values']['fault_code']=1
|
||||
for d in devices: d.sample['sampled_at']=10.2
|
||||
with patch('runtime.remote_control.time.monotonic', return_value=10.2):
|
||||
remote._reconcile_preflight(devices)
|
||||
assert remote.last_stop['state']=='fault'
|
||||
for at in (10.4,10.6,10.8,11.): observe(remote, devices, at)
|
||||
assert remote.state == 'stopped' and remote.release_confirmed is True
|
||||
assert remote.last_stop['state']=='fault' # Core must require explicit new arm.
|
||||
assert not remote.lease.live()
|
||||
|
||||
|
||||
def test_cancelled_neutral_drive_before_output_claim_also_has_a_recovery_observer():
|
||||
from test_remote_control import DriveBoundaryTests
|
||||
log, restored, remote, owner, error = DriveBoundaryTests().run_drive(
|
||||
'expire-before-claim', through_prepare=True, neutral_only=True)
|
||||
assert not log and error is None
|
||||
assert set(restored)=={'left','right'}
|
||||
assert remote.state=='stopping' and remote.release_confirmed is None
|
||||
assert remote.pending_availability.cancelled and not remote.lease.live()
|
||||
@@ -93,7 +93,9 @@ class PreparationHandoffTests(unittest.TestCase):
|
||||
self.assertEqual(self.calls, [])
|
||||
self.finish()
|
||||
self.assertEqual(self.calls, ['prepare'])
|
||||
self.assertEqual(self.remote.state, 'stopped')
|
||||
self.assertEqual(self.remote.state, 'stopping')
|
||||
self.assertIsNone(self.remote.release_confirmed)
|
||||
self.assertTrue(self.remote.pending_availability.cancelled)
|
||||
self.assertFalse(self.operation.locked())
|
||||
|
||||
def test_new_lease_does_not_inherit_failed_release_or_claim_success(self):
|
||||
@@ -127,7 +129,9 @@ class PreparationHandoffTests(unittest.TestCase):
|
||||
self.remote.feed({'watch': True, 'command': None, 'relay_id': self.relay})
|
||||
self.finish()
|
||||
self.assertEqual(self.calls, [])
|
||||
self.assertEqual(self.remote.state, 'stopped')
|
||||
self.assertEqual(self.remote.state, 'stopping')
|
||||
self.assertIsNone(self.remote.release_confirmed)
|
||||
self.assertTrue(self.remote.pending_availability.cancelled)
|
||||
|
||||
def test_expired_input_does_not_start_when_lock_is_released(self):
|
||||
self.start()
|
||||
@@ -213,6 +217,13 @@ class DriveBoundaryTests(unittest.TestCase):
|
||||
owner.receiver_active=lambda _,level:abs(level)>.15
|
||||
owner.limits=SimpleNamespace(apply=lambda d,*a:dict(l_abs_current_max=160,l_current_max=35,l_max_erpm=100000,l_min_erpm=-100000,l_max_duty=.95,
|
||||
s_pid_min_erpm=minimum_erpm[d.id] if isinstance(minimum_erpm,dict) else minimum_erpm),restore=lambda d:restored.append(d.id))
|
||||
if scenario == 'expire-before-claim':
|
||||
original_apply = owner.limits.apply
|
||||
def expire_after_limit(d, *args):
|
||||
result = original_apply(d, *args)
|
||||
remote.lease.stop()
|
||||
return result
|
||||
owner.limits.apply = expire_after_limit
|
||||
def sleep(delta):
|
||||
now[0]+=delta
|
||||
if now[0]>=(3 if scenario=='right-only-braking' else 2):owner.stop.set()
|
||||
|
||||
Reference in New Issue
Block a user