Files
ats-native-fsd/tools/measure_stationary_steering_response.py
2026-10-06 18:11:59 +00:00

191 lines
11 KiB
Python

"""Bounded parked vJoy steering response measurement; actual steering-only input.
The CLI commands neutral,+.1,neutral,-.1,neutral for at most.6s each, with
20ms guards. It never invokes reset/camera keys or throttle/brake steps. The
measurement is stationary normalized SDK input/steering response, not wheel
angle calibration, moving yaw delay, or Pop control approval.
"""
import argparse
import json
import math
from pathlib import Path
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT))
from control.verify_vjoy import parked_reason
from control.windows_input import ATSWindow,KeyboardInput
from control.fsd_controller import FSDController
from telemetry.ats_telemetry import ATSTelemetry
def finite(value):
return not isinstance(value,bool) and isinstance(value,(int,float)) and math.isfinite(value)
def guard_reason(foreground,data,*,baseline=False,fault=None):
if not finite(data.get('speed_mps')):return 'Finite stationary SDK speed required'
reason=parked_reason(foreground,data)
if reason:return reason
if data.get('paused') is not False:return 'Unpaused driving telemetry required'
if data.get('gear')!=0:return 'Neutral is required for stationary steering response'
if fault:return 'Controller fault: '+str(fault)
for field in ('steering','user_steering','user_throttle','user_brake'):
if not finite(data.get(field)):return 'Finite SDK '+field+' required'
if any(abs(data[k])>.02 for k in ('user_throttle','user_brake')):
return 'Release manual pedals before stationary steering response'
if baseline and abs(data['user_steering'])>.02:
return 'Release manual steering before device acquisition'
if not baseline and abs(data['user_steering'])>.14:
return 'SDK steering input exceeds the bounded test range'
if not isinstance(data.get('timestamp'),int) or data['timestamp']<=0:
return 'Distinct positive SDK timestamps required'
return ''
def response_metrics(samples,command_time,baseline,target,field):
"""Observed threshold brackets; no invented latency if target not reached."""
post=[s for s in samples if s['sample_monotonic']>=command_time and finite(s.get(field))]
delta=target-baseline
result=dict(field=field,baseline=baseline,target=target,
observation_window_s=post[-1]['sample_monotonic']-command_time if post else 0.,
first50_percent=None,first90_percent=None,settling=None,
clock='Host observation time minus controller command enqueue time; includes feeder/SDK/sampling latency',
available=False)
if abs(delta)<.02:
result['reason']='No measurable commanded transition for this field'
return result
for threshold,label in ((.5,'first50_percent'),(.9,'first90_percent')):
previous_time=command_time
for sample in post:
fraction=(sample[field]-baseline)/delta
if fraction>=threshold:
result[label]=dict(lower_s=max(0.,previous_time-command_time),
upper_s=sample['sample_monotonic']-command_time,sdk_timestamp=sample['sdk_timestamp'])
break
previous_time=sample['sample_monotonic']
tolerance=max(.01,abs(delta)*.1)
for index,sample in enumerate(post):
tail=post[index:]
if (len(tail)>=3 and tail[-1]['sample_monotonic']-sample['sample_monotonic']>=.1
and all(abs(item[field]-target)<=tolerance for item in tail)):
result['settling']=dict(first_observed_s=sample['sample_monotonic']-command_time,
held_through_s=tail[-1]['sample_monotonic']-command_time,tolerance=tolerance,
stable_distinct_samples=len(tail))
break
result['available']=result['first50_percent'] is not None
result['reason']='Observed stationary transition' if result['available'] else 'Target threshold not reached; latency unavailable'
return result
def run_check(*,window=None,reader=None,controller_factory=None,clock=time.monotonic,sleep=time.sleep,step_s=.6):
if not finite(step_s) or not .2<=step_s<=.6:raise ValueError('Step duration must be within.2.. .6seconds')
window=window or ATSWindow();reader=reader or ATSTelemetry();controller=None
report=dict(completed=False,device_acquired=False,error=None,steps=[],guard_checks=0,
stationary_response_only=True,steering_angle_calibration=False,moving_yaw_delay_validated=False,
physical_calibration_validated=False,pop_control_eligible=False,pedal_steps=False,
bounds=dict(axis_amplitude=.1,step_max_s=.6,guard_period_s=.02,stale_distinct_sdk_limit_s=.1),
limitations=['SDK user_steering includes the vJoy command; simultaneous human steering cannot be isolated.',
'SDK steering is a normalized simulator steering field, not measured physical road-wheel angle.',
'Observer latency includes controller worker scheduling, vJoy, game update and SDK sampling.',
'Stationary response does not establish moving yaw delay, Pop delays, or permission for driving.'])
last_sdk=None;last_distinct=None
def observe(baseline=False,check_fault=True):
nonlocal last_sdk,last_distinct
data=reader.get_data();now=clock();report['guard_checks']+=1
reason=guard_reason(window.foreground(),data,baseline=baseline,
fault=getattr(controller,'fault',None) if check_fault else None)
if reason:raise RuntimeError(reason)
timestamp=data['timestamp']
if last_sdk is not None and timestamp<last_sdk:raise RuntimeError('SDK timestamp reset during stationary check')
distinct=timestamp!=last_sdk
if distinct:last_sdk=timestamp;last_distinct=now
elif last_distinct is not None and now-last_distinct>.1:
raise RuntimeError('SDK distinct sample stalled for over100ms')
return data,now,distinct
try:
# Establish freshness before acquiring or altering any virtual device.
reader.get_data();sleep(.02)
deadline=clock()+.5;baseline_samples=[]
while clock()<deadline:
data,now,distinct=observe(baseline=True)
if distinct:baseline_samples.append((now,data['timestamp']))
if len(baseline_samples)>=3 and now-baseline_samples[0][0]>=.04:break
sleep(.02)
else:raise RuntimeError('Could not establish three distinct fresh parked SDK samples')
report['pre_acquisition_baseline']={k:data[k] for k in
('timestamp','speed_mps','gear','park_brake','steering','user_steering','user_throttle','user_brake')}
if controller_factory is None:
controller_factory=lambda:FSDController(mode='vjoy',keyboard=KeyboardInput(window),camera_view='auxiliary',driving_mode='manual')
controller=controller_factory();report['device_acquired']=True
for name,target in (('initial_neutral',0.),('positive',.1),('neutral_between',0.),('negative',-.1),('final_neutral',0.)):
data,_,_=observe()
if target and any(abs(data[k])>.02 for k in ('user_steering','steering')):
raise RuntimeError('Neutral SDK input/steering did not settle before the next bounded step')
baseline={k:data[k] for k in ('user_steering','steering')}
command_time=clock();controller.apply_controls(target,'coast',0.,data['steering']);enqueue_completed=clock()
step=dict(name=name,desired_axis=target,command_monotonic=command_time,
command_enqueue_completed_monotonic=enqueue_completed,baseline=baseline,samples=[],completed=False)
report['steps'].append(step);deadline=command_time+step_s
while clock()<deadline:
sleep(min(.02,max(0.,deadline-clock())))
data,now,distinct=observe()
if distinct:
step['samples'].append(dict(sample_monotonic=now,sdk_timestamp=data['timestamp'],
desired_axis=target,**{k:data[k] for k in ('user_steering','steering','user_throttle','user_brake','speed_mps')}))
if clock()<deadline:controller.apply_controls(target,'coast',0.,data['steering'])
# Neutralize before analysis or the next phase; timing is measured,
# not assumed from the requested duration on a non-realtime host.
step['release_monotonic']=clock()
controller.release_all_controls()
step['observed_command_hold_s']=step['release_monotonic']-command_time
step['completed']=True
for field in ('user_steering','steering'):
step[field+'_response']=response_metrics(step['samples'],command_time,baseline[field],target,field)
report['completed']=True
except Exception as exc:
report['error']=str(exc)
finally:
shutdown_error=None
if controller is not None:
try:controller.release_all_controls()
except Exception as exc:shutdown_error='Could not release steering: '+str(exc)
try:controller.close()
except Exception as exc:shutdown_error=(shutdown_error+'; ' if shutdown_error else '')+'Could not close device: '+str(exc)
# Verify release from distinct SDK observations after relinquishment,
# even after early guard failure; never reacquire or refocus.
neutral_samples=[];deadline=clock()+.4;neutral_reason='No fresh neutral SDK sample after shutdown'
while clock()<deadline:
sleep(.02)
try:
data,now,distinct=observe(baseline=True,check_fault=False)
if distinct and abs(data['steering'])<=.02:
neutral_samples.append(dict(sample_monotonic=now,sdk_timestamp=data['timestamp'],
**{k:data[k] for k in ('steering','user_steering','user_throttle','user_brake')}))
if len(neutral_samples)>=2:
neutral_reason='';break
except Exception as exc:
neutral_reason=str(exc);break
report['after_shutdown']=dict(neutral_verified=len(neutral_samples)>=2,samples=neutral_samples,reason=neutral_reason)
if neutral_reason:shutdown_error=(shutdown_error+'; ' if shutdown_error else '')+neutral_reason
if shutdown_error:
report['completed']=False;report['shutdown_error']=shutdown_error
reader.close()
return report
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output',type=Path,default=ROOT/'diagnostics/stationary-steering-response-20261003.json')
args=parser.parse_args();report=run_check()
args.output.write_text(json.dumps(report,indent=2,allow_nan=False)+'\n')
summary={key:report.get(key) for key in
('completed','device_acquired','error','shutdown_error','stationary_response_only','pop_control_eligible')}
summary['report_path']=str(args.output.resolve())
summary['neutral_verified']=report.get('after_shutdown',{}).get('neutral_verified',False)
summary['steps']=[{key:step.get(key) for key in
('name','desired_axis','completed','observed_command_hold_s','user_steering_response','steering_response')}
for step in report['steps'] if step['desired_axis']]
print(json.dumps(summary,indent=2));raise SystemExit(0 if report['completed'] else 1)