main
John Lauer
Verified thermal vias with ground continuity; device protocol and host interoperability tests; no thermal or fabricatio…
8082416
"""Local HOST SIMULATION. Fixed requests to the compiled C protocol; no hardware."""
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
import subprocess
import selectors
import argparse
root = Path(__file__).parent
owner = '0123456789abcdef01234567'
class Demo:
def __init__(self, binary): self.binary, self.peer = binary, None; self.reset()
def reset(self):
if self.peer:
self.peer.stdin.close(); self.peer.wait(timeout=3); self.peer.stdout.close()
self.peer = subprocess.Popen([self.binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
self.index = 0
def step(self):
packets = [dict(id=1,cmd='identify'), dict(id=2,cmd='claim'), dict(id=3,cmd='off'), dict(id=4,cmd='set_current',amps=.4), dict(id=5,cmd='arm'), dict(id=5,cmd='arm'), dict(id=6,cmd='heartbeat'), dict(id=7,cmd='clear_fault')]
if self.index == len(packets): return {'done':True}
q = packets[self.index]; self.index += 1
if q['cmd'] != 'identify': q.update(boot='simboot01',owner=owner)
self.peer.stdin.write(json.dumps(q,separators=(',',':')).encode()+b'\n'); self.peer.stdin.flush()
with selectors.DefaultSelector() as selector:
selector.register(self.peer.stdout,selectors.EVENT_READ)
if not selector.select(3): raise TimeoutError('C peer did not reply')
response = json.loads(self.peer.stdout.readline(2048))
return {'request':q,'response':response,'step':self.index,'total':len(packets),'simulation':True}
class Handler(BaseHTTPRequestHandler):
def log_message(self,*args): pass
def do_GET(self):
if self.path not in ('/','/index.html'): self.send_error(404); return
data=(root/'index.html').read_bytes();self.send_response(200);self.send_header('Content-Type','text/html');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
def do_POST(self):
try:
if self.path=='/reset':demo.reset();result={'ok':True}
elif self.path=='/step':result=demo.step()
else:self.send_error(404);return
data=json.dumps(result).encode();self.send_response(200);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
except Exception as exc:
self.send_error(500,str(exc))
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--peer',required=True);parser.add_argument('--port',type=int,default=45956);args=parser.parse_args();demo=Demo(args.peer)
print('Host C protocol simulation on 127.0.0.1:'+str(args.port),flush=True)
HTTPServer(('127.0.0.1',args.port),Handler).serve_forever()