main
John Lauer
Save native two-sided contact artwork and recorded GLB material correction; qualification remains open
57e2489
#!/usr/bin/env python3
"""Create/check/render isolated front legends; keep the live board unchanged."""
import json,hashlib,uuid,shutil,subprocess,re,math,copy
from pathlib import Path
from sexp import parse,find,first
R=Path(__file__).resolve().parents[1];O=R/'design/silkscreen-review/front-contacts';a=json.loads((O/'artwork.json').read_text());assert not a['findings'];source=R/'kicad/adom-custom-electronic-load.kicad_pcb';raw=source.read_bytes();assert hashlib.sha256(raw).hexdigest()==a['boardSha256'];text=raw.decode();original=parse(text);nodes=[]
move=a['fieldMoves'][0];fp=next(f for f in find(original,'footprint') if any(p[1:3]==['Reference','J8'] for p in find(f,'property')));prop=next(p for p in find(fp,'property') if p[1]=='Reference');field_id=first(prop,'uuid')[1];at=first(fp,'at');theta=math.radians(float(at[3]) if len(at)>3 else 0);dx=move['after'][0]-float(at[1]);dy=move['after'][1]-float(at[2]);lx=dx*math.cos(theta)-dy*math.sin(theta);ly=dx*math.sin(theta)+dy*math.cos(theta);rotation=first(prop,'at')[3]
stack=[];matched=0
for m in re.finditer(r'"(?:\\.|[^"\\])*"|[()]',text):
if m.group()=='(':stack.append(m.start())
elif m.group()==')':
start=stack.pop()
if text.startswith('(property ',start) and field_id in text[start:m.end()]:
fragment=text[start:m.end()];fragment,n=re.subn(r'\(at\s+[^()]+\)',f'(at {lx:.9g} {ly:.9g} {rotation})',fragment,count=1);assert n==1;text=text[:start]+fragment+text[m.end():];matched+=1;break
assert matched==1
for t in a['texts']:
size=t['size'];nodes.append(f'(gr_text {json.dumps(t["text"])} (at {t["x"]:.9f} {t["y"]:.9f} {t.get("angle",0)}) (layer "F.SilkS") (uuid "{uuid.uuid4()}") (effects (font (size {size} {size}) (thickness {t["stroke"]}))))')
for g in a['graphics']:
(x,y),(X,Y)=g['points'];nodes.append(f'(gr_line (start {x:.9f} {y:.9f}) (end {X:.9f} {Y:.9f}) (stroke (width {g["stroke"]}) (type solid)) (layer "F.SilkS") (uuid "{uuid.uuid4()}"))')
pos=text.rfind(')');new=text[:pos]+'\n'+'\n'.join(nodes)+'\n'+text[pos:];assert parse(new)[:-len(nodes)]==parse(text)
def neutralize(v):
v=copy.deepcopy(v)
for f in find(v,'footprint'):
for p in find(f,'property'):
if first(p,'uuid')==['uuid',field_id]:p[:]=['reviewed-reference',field_id]
return v
assert neutralize(parse(text))==neutralize(original),'Unrelated data changed'
candidate=R/'kicad/front-contact-candidate.kicad_pcb';candidate.write_bytes(new.encode())
for ext in ['.kicad_pro','.kicad_dru']:shutil.copyfile(source.with_suffix(ext),candidate.with_suffix(ext))
report=dict(status='isolated candidate',sourceSha256=a['boardSha256'],candidateSha256=hashlib.sha256(new.encode()).hexdigest(),texts=len(a['texts']),graphics=len(a['graphics']),allPreviousParsedBoardDataUnchangedExceptJ8Reference=True,referenceMove=move,referenceFieldId=field_id);(O/'candidate-review.json').write_text(json.dumps(report,indent=2)+'\n')
host='C:/Users/john/adom-projects/adom-custom-electronic-load/kicad';cli='C:/Users/john/AppData/Local/Programs/KiCad/10.0/bin/kicad-cli.exe'
def call(v,p,label):
r=json.loads(subprocess.check_output(['adom-bridge','--target','AdomLapper','--ai-thread','adom-custom-load',v,json.dumps(p)],text=True));(O/(label+'.json')).write_text(json.dumps(r,indent=2)+'\n');assert r.get('success',r.get('ok')) and r.get('exitCode',0)==0,r;return r
call('send_files',dict(filePaths=[str(candidate.with_suffix(e)) for e in ['.kicad_pcb','.kicad_pro','.kicad_dru']],dest=host,reason='Check isolated front contact legends without changing the live board'),'send')
r=call('shell_execute',dict(command=f'"{cli}" pcb drc --format json --output "{host}/front-contact-drc.json" "{host}/front-contact-candidate.kicad_pcb"',timeoutSeconds=120,reason='Native project-aware DRC for front contact legends'),'drc-command');print(r['stdout'],flush=True)
call('pull_file',dict(filePaths=[host+'/front-contact-drc.json'],saveTo=str(O)),'drc-pull');d=json.loads((O/'front-contact-drc.json').read_text());assert not d['violations'] and not d['unconnected_items']
call('shell_execute',dict(command=f'"{cli}" pcb render --side top --width 1800 --height 2000 --quality high --output "{host}/front-contact-candidate.png" "{host}/front-contact-candidate.kicad_pcb"',timeoutSeconds=120,reason='Inspect front legends against the fitted components in native KiCad'),'render-command')
call('pull_file',dict(filePaths=[host+'/front-contact-candidate.png'],saveTo=str(O)),'render-pull');print('Front candidate DRC clean and native render ready',flush=True)