"""Read-only preview timing. Never starts acquisition or changes preview settings.""" import argparse import json import re import statistics import time import urllib.request from pathlib import Path from verify_cmvr_native import Client,TargetReadOnlyDb ROOT=Path(__file__).resolve().parents[1] def measure(url,headers,seconds): started=time.perf_counter();arrivals=[];sizes=[];sequences=[] try: with urllib.request.urlopen(urllib.request.Request(url,headers=headers),timeout=5) as response: if 'multipart/x-mixed-replace' not in response.headers.get('content-type',''): return dict(error='Not an MJPEG response',httpStatus=response.status) while time.perf_counter()-started8*1024*1024:raise ValueError('Invalid frame size') payload=response.read(size) if len(payload)!=size:raise EOFError('Incomplete JPEG') arrivals.append(time.perf_counter());sizes.append(size);sequences.append(fields.get('x-frame-sequence')) except Exception as error: if not arrivals:return dict(error=type(error).__name__+': '+str(error)) elapsed=time.perf_counter()-started intervals=[(b-a)*1000 for a,b in zip(arrivals,arrivals[1:])] return dict(frames=len(arrivals),uniqueSequences=len(set(sequences)),elapsedSeconds=round(elapsed,2), firstFrameMs=round((arrivals[0]-started)*1000,1) if arrivals else None, steadyFps=round((len(arrivals)-1)/(arrivals[-1]-arrivals[0]),2) if len(arrivals)>1 else 0, meanJpegBytes=round(statistics.mean(sizes)) if sizes else 0, intervalMedianMs=round(statistics.median(intervals),1) if intervals else None, intervalP95Ms=round(sorted(intervals)[min(len(intervals)-1,int(len(intervals)*.95))],1) if intervals else None) def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--seconds',type=int,default=6,choices=range(2,16)) args=parser.parse_args();client=Client().login();config=client.native('GET','/scanner/configuration')['data'] private=(ROOT/'.local/scanner-private.yaml').read_text(encoding='utf-8-sig') key=re.search(r'(?m)^\s*api-key:\s*(.+?)\s*$',private)[1].strip('\"\'') origin=f"http://{config['host']}:{config['port']}" vendor_headers={'Authorization':'Bearer '+key} app_headers={'Authorization':'Bearer '+client._token,'tenant-id':'1'} timings=[] for _ in range(4): started=time.perf_counter() with urllib.request.urlopen(urllib.request.Request(origin+'/api/v1/status',headers=vendor_headers),timeout=5) as response:status=json.loads(response.read()) timings.append(round((time.perf_counter()-started)*1000,1)) with urllib.request.urlopen(urllib.request.Request(origin+'/api/v1/preview/metrics',headers=vendor_headers),timeout=5) as response:metrics=json.loads(response.read()) db=TargetReadOnlyDb(client) active=db.select("SELECT id,execution_no FROM lab_execution WHERE status IN ('RUNNING','PAUSED') AND deleted=0 ORDER BY id DESC") db.close() report=dict(physicalControlRequests=0,status={k:status.get(k) for k in ['scanning','previewEnabled','busy','projectReady']},vendorStatusMs=timings, previewMetrics=metrics,stages={}) stages=[('vendor',origin+'/api/v1/preview/stream',vendor_headers),('backendRaw',client.base_url+'/admin-api/cmvr/scanner/preview/stream',app_headers)] if active: execution=str(active[0]['id']);report['executionNo']=active[0]['execution_no'] path='/admin-api/lab/execution/scanner-view/stream?executionId='+execution stages.extend([('backendBusiness',client.base_url+path,app_headers),('frontendProxy','http://192.168.0.222:5180'+path,app_headers)]) for name,url,headers in stages: result=measure(url,headers,args.seconds);report['stages'][name]=result print(json.dumps(dict(stage=name,**result),ensure_ascii=False),flush=True) (ROOT/'.local/scanner-preview-diagnostic-20261026.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') print(json.dumps(dict(status=report['status'],vendorStatusMs=timings,previewMetrics=metrics),ensure_ascii=False),flush=True) if __name__=='__main__':main()