PYTHON · Code cell
# =====================================================================
# K02 | Code cell 01 | K02 · Local broker & service inventory
# Purpose: 1. Define the experiment mechanism and inputs
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import contextlib, json, socket, socketserver, ssl, struct, threading, uuid
# Define the reusable operation check; keep its logic separate from the trial.
def check(condition, message):
if not condition: raise RuntimeError(message)
# Define the reusable operation u16; keep its logic separate from the trial.
def u16(n): return struct.pack('!H', n)
# Define the reusable operation string; keep its logic separate from the trial.
def string(s):
b=s.encode('utf-8');return u16(len(b))+b
# Define the reusable operation exact; keep its logic separate from the trial.
def exact(s,n):
b=bytearray()
while len(b)<n:
c=s.recv(n-len(b))
if not c: raise EOFError('peer closed')
b.extend(c)
return bytes(b)
# Define the reusable operation packet; keep its logic separate from the trial.
def packet(s,head,body=b''):
n=len(body);out=bytearray([head])
while True:
digit=n%128;n//=128;out.append(digit|(128 if n else 0))
if not n: break
s.sendall(out+body)
# Define the reusable operation read packet; keep its logic separate from the trial.
def read_packet(s):
h=exact(s,1)[0];n=0;mul=1
for _ in range(4):
b=exact(s,1)[0];n+=(b&127)*mul
if not b&128:break
mul*=128
else:raise ValueError('invalid MQTT length')
check(n<=65536,'packet too large for lab');return h,exact(s,n)
# Define the reusable operation split string; keep its logic separate from the trial.
def split_string(b):
check(len(b)>=2,'truncated MQTT field');n=int.from_bytes(b[:2],'big');check(len(b)>=2+n,'truncated MQTT string');return b[2:2+n].decode(),b[2+n:]
# Small synchronous teaching client: clean session, exact-topic QoS 1.
class MQTT:
"""Small synchronous teaching client: clean session, exact-topic QoS 1.
Separate publisher/subscriber sockets; no reconnect, keepalive or wildcard API.
"""
def __init__(self,host,port,tls=False):
s=socket.create_connection((host,port),timeout=8);s.settimeout(8)
try:
if tls:s=ssl.create_default_context().wrap_socket(s,server_hostname=host)
self.s=s;self.pid=0
packet(s,0x10,string('MQTT')+b'\x04\x02'+u16(60)+string('psut-'+uuid.uuid4().hex[:16]))
h,b=read_packet(s);check(h==0x20 and b==b'\x00\x00','CONNACK failed')
except BaseException:s.close();raise
def next_id(self):self.pid=self.pid%65535+1;return u16(self.pid)
def subscribe(self,topic):
pid=self.next_id();packet(self.s,0x82,pid+string(topic)+b'\x01');h,b=read_packet(self.s);check(h==0x90 and b==pid+b'\x01','QoS 1 SUBACK not granted')
def publish(self,topic,payload):
pid=self.next_id();packet(self.s,0x32,string(topic)+pid+payload);h,b=read_packet(self.s);check(h==0x40 and b==pid,'PUBACK mismatch')
def receive(self):
h,b=read_packet(self.s);check(h>>4==3 and ((h>>1)&3)==1,'expected QoS 1 PUBLISH');topic,rest=split_string(b);check(len(rest)>=2,'missing packet ID');packet(self.s,0x40,rest[:2]);return topic,rest[2:]
def close(self):
try:packet(self.s,0xe0)
except OSError:pass
self.s.close()
def __enter__(self):return self
def __exit__(self,*args):self.close()
# Encapsulate state and operations for Peer; keep its logic separate from the trial.
class Peer(socketserver.BaseRequestHandler):
def handle(self):
s=self.request;s.settimeout(15);server=self.server
try:
h,b=read_packet(s);proto,b=split_string(b);check(h==0x10 and proto=='MQTT' and b[:2]==b'\x04\x02','unsupported CONNECT');packet(s,0x20,b'\x00\x00')
while True:
h,b=read_packet(s)
if h==0x82:
topic,tail=split_string(b[2:]);check(tail==b'\x01' and '+' not in topic and '#' not in topic,'exact QoS1 only')
with server.lock:server.subs.setdefault(topic,set()).add(s)
packet(s,0x90,b[:2]+b'\x01')
elif h==0x32:
topic,tail=split_string(b);check(len(tail)>=2,'missing packet ID')
with server.lock:
for target in list(server.subs.get(topic,())):
server.seq=server.seq%65535+1
try:packet(target,0x32,string(topic)+u16(server.seq)+tail[2:])
except OSError:server.subs[topic].discard(target)
packet(s,0x40,tail[:2])
elif h==0x40:continue # no retransmission in this restricted fixture
elif h==0xc0:packet(s,0xd0)
elif h==0xe0:break
else:raise ValueError('unsupported packet')
except (EOFError,OSError,ValueError,RuntimeError):pass
finally:
with server.lock:
for targets in server.subs.values():targets.discard(s)
# Encapsulate state and operations for LoopbackPeer; keep its logic separate from the trial.
class LoopbackPeer(socketserver.ThreadingTCPServer):
daemon_threads=True
def __init__(self):
self.lock=threading.Lock();self.subs={};self.seq=0;super().__init__(('127.0.0.1',0),Peer)
# Define the reusable operation endpoint; keep its logic separate from the trial.
@contextlib.contextmanager
def endpoint(mode):
if mode=='hivemq':
yield 'broker.hivemq.com',8883,True
elif mode=='local':
with LoopbackPeer() as p:
t=threading.Thread(target=p.serve_forever,daemon=True);t.start()
try:yield '127.0.0.1',p.server_address[1],False
finally:p.shutdown();t.join(3)
else:raise ValueError('Choose local or hivemq explicitly')