PYTHON DESKTOP EXAMPLE / VERSION 0.3.0
A device to test.
No board required.
Run a virtual embedded device on your PC. Watch its logs, inspect telemetry and send commands from MangoLink on your phone. Read the Python source and use it as a starting point for your own integration.
ZIP · 27 KB · Python 3.10+ · Windows, Linux and macOS with Tk · No GitHub sign-in needed
Desktop setup · Pair your phone · Source code · Headless server
1 / DESKTOP SETUP
Extract. Install. Run.
Install Python 3.10 or newer with Tcl/Tk support, download the ZIP and extract the entire folder. Open a terminal in the extracted folder containing mangolink_simulator.py. Run the commands for your system:
Windows PowerShell
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-tls.txt -r requirements-qr.txt
.\.venv\Scripts\python.exe mangolink_simulator.py
Use the last command to open it again. No activation script or administrator access is needed.
Linux / macOS
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements-tls.txt -r requirements-qr.txt
.venv/bin/python mangolink_simulator.py
The desktop window needs Tk and a display. If tkinter is missing, install your operating system’s Python Tk package.
The requirements files install cryptography for local certificate generation and qrcode for QR display. Dependencies are downloaded when you install them; pairing itself uses no cloud QR service.
2 / PAIR YOUR PHONE
One QR. All four fields.
- Create the TLS identity. Keep TLS selected on port
8766. Press Create TLS certificate once, or Browse to an existing certificate and key. The default Windows folder is%LOCALAPPDATA%\MangoJuiceTech\MangoLinkSimulator\certs. Use Choose certificate folder… if another writable location is needed. - Start the server. Press Start server, then Show pairing QR…. Enter your PC’s LAN IP and generate the QR. Find the IP using
ipconfigon Windows.0.0.0.0is a bind address, not the phone’s destination. - Scan with MangoLink 0.3.0. Put phone and PC on the same LAN. Open Connection settings → Scan simulator QR code and allow camera access. The QR fills the host, port, certificate SHA-256 fingerprint and session token. Review the details and tap Connect.
- Try a command. Send
status,sensors,led onorled off. Inject a warning from the desktop and find it in the phone log viewer. All device readings and LED state are simulated.
Keep the QR private. The token is included by default; uncheck Include session token to type it manually instead. The private key stays on the PC. Closing the QR window does not revoke its token.
Scanning fills fields without connecting automatically. TLS still verifies the certificate before sending the token. Manual entry remains available if camera access is unavailable. On the standard Android emulator, use 10.0.2.2 to reach the PC.
3 / READ & ADAPT
The Python behind the window.
Download the whole ZIP to run the example; these files import each other. Open a file below to inspect its complete source. In server.py, Simulator.tick() produces sample logs and telemetry, while Simulator.command() handles commands. Keep authentication and frame limits when adapting the example.
mangolink_simulator.py — Native desktop window and server controls
Download mangolink_simulator.py
"""Native desktop control panel. Tkinter is bundled with standard Windows Python."""
import asyncio
import queue
import threading
import tkinter as tk
from pathlib import Path
from tkinter import ttk, filedialog
from tkinter.scrolledtext import ScrolledText
from server import Simulator
from pairing import PairingDialog
from tls_support import DEFAULT_CERT, DEFAULT_KEY, certificate_fingerprint, create_certificate, new_token, server_context
TLS_MODE = "TLS · Encrypted"
TCP_MODE = "TCP · Unencrypted"
class App:
def __init__(self, root):
self.root = root
self.loop = asyncio.new_event_loop()
self.thread = threading.Thread(target=self.loop.run_forever, daemon=True)
self.thread.start()
self.events = queue.Queue(maxsize=1000)
self.sim = None
self.busy = False
root.title("MangoLink Simulator 0.3.0 — Mango Juice Tech")
root.geometry("960x800")
root.minsize(780, 700)
style = ttk.Style()
style.theme_use("clam")
style.configure("TButton", padding=8)
style.configure("Title.TLabel", font=("Segoe UI", 22, "bold"), foreground="#bf5700")
body = ttk.Frame(root, padding=20)
body.pack(fill="both", expand=True)
ttk.Label(body, text="MangoLink Simulator", style="Title.TLabel").pack(anchor="w")
ttk.Label(body, text="A virtual embedded device for logs, telemetry and commands.").pack(anchor="w", pady=(4, 16))
row = ttk.Frame(body)
row.pack(fill="x")
self.host = tk.StringVar(value="0.0.0.0")
self.port = tk.StringVar(value="8766")
self.token = tk.StringVar(value=new_token())
self.inputs = []
for label, var, width in [("Bind address", self.host, 16), ("Port", self.port, 7), ("Session token", self.token, 22)]:
cell = ttk.Frame(row)
cell.pack(side="left", padx=(0, 12))
ttk.Label(cell, text=label).pack(anchor="w")
entry = ttk.Entry(cell, textvariable=var, width=width)
entry.pack()
self.inputs.append(entry)
mode_row = ttk.Frame(body)
mode_row.pack(fill="x", pady=(12, 8))
ttk.Label(mode_row, text="Connection mode").pack(side="left", padx=(0, 12))
self.mode = tk.StringVar(value=TLS_MODE)
self.mode_combo = ttk.Combobox(mode_row, textvariable=self.mode, values=[TLS_MODE, TCP_MODE], state="readonly", width=24)
self.mode_combo.pack(side="left")
self.mode_combo.bind("<<ComboboxSelected>>", lambda _: self.mode_changed())
self.cert = tk.StringVar(value=str(DEFAULT_CERT))
self.key = tk.StringVar(value=str(DEFAULT_KEY))
self.file_buttons = []
for label, variable in [("TLS certificate", self.cert), ("Private key", self.key)]:
row = ttk.Frame(body)
row.pack(fill="x", pady=3)
ttk.Label(row, text=label, width=16).pack(side="left")
entry = ttk.Entry(row, textvariable=variable)
entry.pack(side="left", fill="x", expand=True, padx=(0, 8))
self.inputs.append(entry)
button = ttk.Button(row, text="Browse…", command=lambda v=variable: self.browse_file(v))
button.pack(side="right")
self.file_buttons.append(button)
cert_actions = ttk.Frame(body)
cert_actions.pack(fill="x", pady=6)
self.create_button = ttk.Button(cert_actions, text="Create TLS certificate", command=self.generate_certificate)
self.create_button.pack(side="left", padx=(0, 12))
folder_button = ttk.Button(cert_actions, text="Choose certificate folder…", command=self.choose_certificate_folder)
folder_button.pack(side="left")
self.file_buttons.append(folder_button)
ttk.Label(body, text="Certificate SHA-256 — copy into MangoLink:").pack(anchor="w")
self.fingerprint = tk.StringVar()
ttk.Entry(body, textvariable=self.fingerprint, state="readonly", font=("Consolas", 10)).pack(fill="x")
self.mode_notice = tk.StringVar()
ttk.Label(body, textvariable=self.mode_notice, foreground="#a33c00", wraplength=880).pack(anchor="w", pady=(8, 0))
self.refresh_fingerprint()
self.mode_changed()
self.status = tk.StringVar(value="Stopped")
ttk.Label(body, textvariable=self.status).pack(anchor="w", pady=12)
buttons = ttk.Frame(body)
buttons.pack(fill="x")
self.start_button = ttk.Button(buttons, text="Start server", command=self.start)
self.start_button.pack(side="left", padx=(0, 8))
self.stop_button = ttk.Button(buttons, text="Stop server", command=self.stop, state="disabled")
self.stop_button.pack(side="left", padx=(0, 8))
self.pair_button = ttk.Button(buttons, text="Show pairing QR…", command=self.show_pairing, state="disabled")
self.pair_button.pack(side="left")
self.actions = []
action_grid = ttk.Frame(body)
action_grid.pack(fill="x", pady=(8, 0))
action_grid.columnconfigure((0, 1), weight=1)
for index, (label, factory) in enumerate([("Inject warning", lambda: self.sim.log("WARN", "Desktop warning event")),
("Inject error", lambda: self.sim.log("ERROR", "Desktop error event")),
("Drop clients", lambda: self.sim.disconnect_all()),
("Simulate reboot", lambda: self.sim.reboot())]):
button = ttk.Button(action_grid, text=label, command=lambda f=factory: self.action(f), state="disabled")
button.grid(row=index // 2, column=index % 2, sticky="ew", padx=(0, 8), pady=(0, 6))
self.actions.append(button)
self.console = ScrolledText(body, height=8, bg="#152019", fg="#e4f0e8", font=("Consolas", 10), state="disabled")
self.console.pack(fill="both", expand=True, pady=12)
ttk.Label(body, text="Phone: use this PC's LAN IP, port and token. 0.0.0.0 is a bind address, not the phone's destination.", wraplength=740).pack(anchor="w")
ttk.Label(body, text="Keep the private key on this PC. Share only the certificate fingerprint. TLS failures never fall back to TCP.", wraplength=880).pack(anchor="w", pady=(8, 0))
root.protocol("WM_DELETE_WINDOW", self.close)
self.poll_id = root.after(100, self.poll)
def show_pairing(self):
if self.busy or not self.sim or self.sim.mode != "TLS":
return
PairingDialog(self.root, self.host.get().strip(), self.sim.port,
self.serving_fingerprint, self.sim.token)
def mode_changed(self):
tls = self.mode.get() == TLS_MODE
if self.port.get() in ("8765", "8766"):
self.port.set("8766" if tls else "8765")
self.mode_notice.set("TLS encrypts traffic. Verify the displayed fingerprint on the phone before connecting."
if tls else "UNENCRYPTED TCP: token, commands and logs are readable on the network. Trusted lab LAN only.")
def refresh_fingerprint(self):
try:
self.fingerprint.set(certificate_fingerprint(self.cert.get()))
except Exception:
self.fingerprint.set("Create or choose a certificate for TLS.")
def browse_file(self, variable):
if self.sim or self.busy:
return
path = filedialog.askopenfilename(title="Choose TLS file")
if path:
variable.set(path)
self.refresh_fingerprint()
def choose_certificate_folder(self):
if self.sim or self.busy:
return
folder = filedialog.askdirectory(title="Choose a writable TLS certificate folder")
if folder:
directory = Path(folder).expanduser().resolve()
self.cert.set(str(directory / "server-cert.pem"))
self.key.set(str(directory / "server-key.pem"))
self.refresh_fingerprint()
def generate_certificate(self):
if self.sim or self.busy:
return
try:
cert, key = create_certificate(Path(self.cert.get()).parent)
self.cert.set(str(cert))
self.key.set(str(key))
self.refresh_fingerprint()
self.emit("Created a new TLS identity. Keep the private key on the PC; pair the displayed fingerprint on your phone.")
except Exception as exc:
self.emit(str(exc))
def emit(self, message):
try:
self.events.put_nowait(("log", message))
except queue.Full:
pass
def submit(self, coro, event):
future = asyncio.run_coroutine_threadsafe(coro, self.loop)
def done(f):
try:
f.result()
self.events.put((event, None))
except Exception as exc:
self.events.put(("failure", str(exc)))
future.add_done_callback(done)
def start(self):
if self.busy or self.sim:
return
try:
port = int(self.port.get())
if not 1 <= port <= 65535:
raise ValueError("Port must be 1..65535")
tls = self.mode.get() == TLS_MODE
context = server_context(self.cert.get(), self.key.get()) if tls else None
self.serving_fingerprint = certificate_fingerprint(self.cert.get()) if tls else ""
self.refresh_fingerprint()
self.sim = Simulator(token=self.token.get(), event=self.emit)
self.busy = True
self.start_button.config(state="disabled")
self.mode_combo.config(state="disabled")
self.create_button.config(state="disabled")
for widget in self.inputs:
widget.config(state="readonly")
for button in self.file_buttons:
button.config(state="disabled")
self.submit(self.sim.start(self.host.get().strip(), port, ssl_context=context), "started")
except (ValueError, OSError, RuntimeError) as exc:
self.sim = None
self.emit(str(exc))
def stop(self):
if self.sim and not self.busy:
self.busy = True
self.stop_button.config(state="disabled")
self.pair_button.config(state="disabled")
for b in self.actions:
b.config(state="disabled")
self.submit(self.sim.stop(), "stopped")
def action(self, factory):
if self.sim and not self.busy:
self.submit(factory(), "action")
def poll(self):
for _ in range(200):
try:
kind, message = self.events.get_nowait()
except queue.Empty:
break
if kind == "started":
self.busy = False
self.status.set(f"Listening on {self.host.get()}:{self.port.get()} · {self.mode.get()}")
self.stop_button.config(state="normal")
self.pair_button.config(state="normal" if self.sim.mode == "TLS" else "disabled")
self.mode_combo.config(state="disabled")
self.create_button.config(state="disabled")
for button in self.file_buttons:
button.config(state="disabled")
for widget in self.inputs:
widget.config(state="readonly")
for b in self.actions:
b.config(state="normal")
elif kind in ("stopped", "failure"):
if kind == "failure":
self.emit(message)
if self.sim:
asyncio.run_coroutine_threadsafe(self.sim.stop(), self.loop)
self.busy = False
self.sim = None
self.status.set("Stopped")
self.start_button.config(state="normal")
self.mode_combo.config(state="readonly")
self.create_button.config(state="normal")
for button in self.file_buttons:
button.config(state="normal")
self.stop_button.config(state="disabled")
self.pair_button.config(state="disabled")
for widget in self.inputs:
widget.config(state="normal")
for b in self.actions:
b.config(state="disabled")
elif kind == "log":
self.console.config(state="normal")
self.console.insert("end", message + "\n")
if int(self.console.index("end-1c").split(".")[0]) > 1000:
self.console.delete("1.0", "101.0")
self.console.see("end")
self.console.config(state="disabled")
self.poll_id = self.root.after(100, self.poll)
def close(self):
self.root.after_cancel(self.poll_id)
async def shutdown():
if self.sim:
await self.sim.stop()
try:
asyncio.run_coroutine_threadsafe(shutdown(), self.loop).result(timeout=3)
except Exception:
pass
self.loop.call_soon_threadsafe(self.loop.stop)
self.thread.join(timeout=1)
if not self.thread.is_alive():
self.loop.close()
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
App(root)
root.mainloop()
server.py — Protocol 1 server, sample telemetry and commands
"""MangoLink Simulator: standard-library TCP device simulator (Python 3.10+)."""
import argparse
import asyncio
import contextlib
import hmac
import json
import math
import time
from tls_support import DEFAULT_CERT, DEFAULT_KEY, certificate_fingerprint, new_token, server_context
MAX_FRAME = 8192
class Simulator:
def __init__(self, token=None, event=None, interval=1.0):
if token is None:
token = new_token()
if not token:
raise ValueError("A session token is required")
self.token = token
self.event = event or (lambda message: None)
self.interval = max(0.1, interval)
self.clients = set()
self.handlers = set()
self.listener = None
self.ticker = None
self.started = time.monotonic()
self.boot = 1
self.sequence = 0
self.led = False
async def start(self, host="127.0.0.1", port=8765, ssl_context=None):
options = {"ssl": ssl_context, "ssl_handshake_timeout": 5} if ssl_context else {}
self.listener = await asyncio.start_server(self.handle, host, port, limit=MAX_FRAME, **options)
self.port = self.listener.sockets[0].getsockname()[1]
self.ticker = asyncio.create_task(self.tick())
self.mode = "TLS" if ssl_context else "TCP · UNENCRYPTED"
self.event(f"Listening on {host}:{self.port} · {self.mode}")
async def stop(self):
if self.listener:
self.listener.close()
if self.ticker:
self.ticker.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self.ticker
await self.disconnect_all()
tasks = list(self.handlers)
for task in tasks:
task.cancel()
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
if self.listener:
await self.listener.wait_closed()
self.event("Server stopped")
async def send(self, writer, message):
data = (json.dumps(message, separators=(",", ":"), ensure_ascii=False) + "\n").encode()
if len(data) - 1 > MAX_FRAME:
raise ValueError("Outgoing frame exceeds protocol limit")
writer.write(data)
await asyncio.wait_for(writer.drain(), timeout=1.0)
async def broadcast(self, message):
async def deliver(writer):
try:
await self.send(writer, message)
except (ConnectionError, OSError, asyncio.TimeoutError):
self.clients.discard(writer)
writer.close()
await asyncio.gather(*(deliver(w) for w in list(self.clients)))
def values(self):
uptime = time.monotonic() - self.started
return {"uptime_s": round(uptime, 1), "temperature_c": round(35 + 4 * math.sin(uptime / 12), 2),
"voltage_v": round(3.3 + 0.02 * math.sin(uptime / 3), 3), "led": self.led,
"boot": self.boot}
async def log(self, level, text, tag="SIM"):
self.sequence += 1
message = {"v": 1, "type": "log", "seq": self.sequence, "boot": self.boot,
"uptime_ms": int((time.monotonic() - self.started) * 1000),
"level": level, "tag": tag, "text": text}
await self.broadcast(message)
self.event(f"{level} {tag}: {text}")
async def tick(self):
while True:
await asyncio.sleep(self.interval)
if self.clients:
await self.log("INFO", "Control loop healthy", "SYSTEM")
await self.broadcast({"v": 1, "type": "telemetry", **self.values()})
async def disconnect_all(self):
writers = list(self.clients)
self.clients.clear()
for writer in writers:
writer.close()
for writer in writers:
with contextlib.suppress(ConnectionError, OSError):
await writer.wait_closed()
self.event("Clients disconnected")
async def reboot(self):
await self.log("WARN", "Simulated reboot requested")
self.boot += 1
self.started = time.monotonic()
self.sequence = 0
self.led = False
await self.disconnect_all()
async def command(self, writer, frame):
request_id = frame.get("id")
if not isinstance(request_id, str) or not 1 <= len(request_id) <= 64:
raise ValueError("Command needs a string id (1..64 characters)")
text = frame.get("command")
if not isinstance(text, str) or not 1 <= len(text) <= 256:
raise ValueError("Command must contain 1..256 characters")
text = text.strip()
ok, result = True, ""
if text == "help":
result = "help | status | sensors | led on | led off | warn | error | disconnect | reboot"
elif text in ("status", "sensors"):
result = json.dumps(self.values())
elif text in ("led on", "led off"):
self.led = text == "led on"
result = "LED ON" if self.led else "LED OFF"
elif text in ("warn", "error"):
await self.log(text.upper(), "Injected test event")
result = "Event injected"
elif text in ("disconnect", "reboot"):
result = "Accepted; connection will close"
else:
ok, result = False, "Unknown command; send help"
self.event(f"Command {request_id}: {text}")
await self.send(writer, {"v": 1, "type": "response", "id": request_id,
"ok": ok, "text": result})
if text == "disconnect":
writer.close()
elif text == "reboot":
await self.reboot()
async def read_frame(self, reader, timeout=None):
raw = await asyncio.wait_for(reader.readline(), timeout=timeout)
if not raw:
return None
if not raw.endswith(b"\n") or len(raw) - 1 > MAX_FRAME:
raise ValueError("Incomplete or oversized frame")
frame = json.loads(raw.decode("utf-8"))
if not isinstance(frame, dict) or type(frame.get("v")) is not int or frame["v"] != 1:
raise ValueError("Expected protocol version 1 object")
return frame
async def handle(self, reader, writer):
task = asyncio.current_task()
self.handlers.add(task)
peer = writer.get_extra_info("peername")
try:
auth = await self.read_frame(reader, timeout=5)
token = auth.get("token") if auth else None
if (not auth or auth.get("type") != "auth" or not isinstance(token, str)
or not hmac.compare_digest(token.encode(), self.token.encode())):
await self.send(writer, {"v": 1, "type": "error", "text": "Authentication failed"})
return
await self.send(writer, {"v": 1, "type": "hello", "device": "MangoLink Simulator",
"firmware": "0.3.0", "boot": self.boot,
"capabilities": ["logs", "commands", "telemetry"]})
self.clients.add(writer)
self.event(f"Client authenticated: {peer}")
while not writer.is_closing():
frame = await self.read_frame(reader)
if frame is None:
break
if frame.get("type") != "command":
raise ValueError("Expected a command frame")
await self.command(writer, frame)
except (ValueError, UnicodeError) as exc:
with contextlib.suppress(ConnectionError, OSError, asyncio.TimeoutError):
await self.send(writer, {"v": 1, "type": "error", "text": str(exc)[:160]})
except (ConnectionError, OSError, asyncio.TimeoutError):
pass
finally:
self.clients.discard(writer)
writer.close()
with contextlib.suppress(ConnectionError, OSError):
await writer.wait_closed()
self.handlers.discard(task)
self.event(f"Client closed: {peer}")
async def run_cli(args):
sim = Simulator(token=args.token, event=print)
context = server_context(args.cert, args.key) if args.mode == "tls" else None
await sim.start(args.host, args.port or (8766 if context else 8765), ssl_context=context)
if context:
print(f"Certificate SHA-256: {certificate_fingerprint(args.cert)}")
else:
print("UNENCRYPTED: logs, commands and token are readable on the network. Trusted lab LAN only.")
print(f"Session token (enter on your phone): {sim.token}")
try:
await asyncio.Event().wait()
finally:
await sim.stop()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="MangoLink Simulator TCP server")
parser.add_argument("--host", default="127.0.0.1", help="Use 0.0.0.0 to allow LAN clients")
parser.add_argument("--port", type=int, help="Default: 8766 TLS, 8765 TCP")
parser.add_argument("--mode", choices=["tls", "tcp"], default="tls")
parser.add_argument("--cert", default=str(DEFAULT_CERT))
parser.add_argument("--key", default=str(DEFAULT_KEY))
parser.add_argument("--token", help="Optional token; generated randomly if omitted. CLI arguments may be visible to local users.")
try:
asyncio.run(run_cli(parser.parse_args()))
except KeyboardInterrupt:
pass
except (OSError, ValueError) as exc:
raise SystemExit(f"Server setup failed: {exc}\nFor TLS, create a certificate with python tls_support.py first; choose --mode tcp explicitly for unencrypted hardware.")
tls_support.py — TLS certificate generation and configuration
"""TLS configuration and local certificate creation. Never learns trust over the network."""
import argparse
import hashlib
import ipaddress
import os
import secrets
import ssl
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
def certificate_directory():
"""Per-user identity storage, independent of the launch working directory."""
if sys.platform == "win32":
base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
elif sys.platform == "darwin":
base = Path.home() / "Library" / "Application Support"
else:
base = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share")
# Ignore a malformed relative environment value rather than using the launch folder.
if not base.is_absolute():
base = Path.home() / ("AppData/Local" if sys.platform == "win32" else ".local/share")
return base / "MangoJuiceTech" / "MangoLinkSimulator" / "certs"
DEFAULT_CERT = certificate_directory() / "server-cert.pem"
DEFAULT_KEY = certificate_directory() / "server-key.pem"
def server_context(cert, key):
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.minimum_version = ssl.TLSVersion.TLSv1_2
# No interactive OpenSSL password prompt in a desktop event handler.
context.load_cert_chain(str(cert), str(key), password=lambda: "")
return context
def certificate_fingerprint(cert):
pem = Path(cert).read_text(encoding="ascii")
der = ssl.PEM_cert_to_DER_cert(pem)
return hashlib.sha256(der).hexdigest().upper()
def new_token():
return secrets.token_urlsafe(24)
def create_certificate(directory=None, addresses=None):
try:
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
except ImportError as exc:
raise RuntimeError("Certificate generation requires: python -m pip install -r requirements-tls.txt") from exc
directory = Path(directory if directory is not None else certificate_directory()).expanduser().resolve()
try:
return _create_certificate(directory, addresses, x509, hashes, serialization, ec, ExtendedKeyUsageOID, NameOID)
except PermissionError as exc:
raise PermissionError(
f"Cannot write TLS files in '{directory}'. Choose a writable folder with "
"'Choose certificate folder…', then try again (CLI: --directory PATH)."
) from exc
def _create_certificate(directory, addresses, x509, hashes, serialization, ec, ExtendedKeyUsageOID, NameOID):
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
cert_path, key_path = directory / "server-cert.pem", directory / "server-key.pem"
if cert_path.exists() or key_path.exists():
raise FileExistsError("Certificate/key already exist. Choose a new folder to create a different device identity.")
key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "MangoLink Simulator")])
names = []
for address in dict.fromkeys(addresses or ["localhost", "127.0.0.1", "10.0.2.2"]):
try:
names.append(x509.IPAddress(ipaddress.ip_address(address)))
except ValueError:
names.append(x509.DNSName(address))
now = datetime.now(timezone.utc)
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now - timedelta(minutes=5)).not_valid_after(now + timedelta(days=365))
.add_extension(x509.SubjectAlternativeName(names), critical=False)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
.sign(key, hashes.SHA256()))
created = []
try:
# O_EXCL prevents accidental replacement. Restrictive permissions on systems that support them.
for path, data, mode in [
(key_path, key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
serialization.NoEncryption()), 0o600),
(cert_path, cert.public_bytes(serialization.Encoding.PEM), 0o644),
]:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
created.append(path)
with os.fdopen(fd, "wb") as output:
output.write(data)
except Exception:
for path in created:
path.unlink(missing_ok=True)
raise
return cert_path, key_path
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create a local MangoLink TLS certificate")
parser.add_argument("--directory", help=f"Certificate folder (default: {certificate_directory()})")
parser.add_argument("--address", action="append", help="Optional certificate DNS name/IP; repeat for multiple")
args = parser.parse_args()
try:
cert, key = create_certificate(args.directory, args.address)
except (OSError, RuntimeError, ValueError) as exc:
parser.exit(1, f"Certificate creation failed: {exc}\n")
print(f"Certificate: {cert}\nPrivate key (keep on PC): {key}")
print(f"Certificate SHA-256: {certificate_fingerprint(cert)}")
pairing.py — Local QR generation and pairing dialog
"""Local-only TLS pairing QR. No key files, network calls or persistent QR images."""
import re
import tkinter as tk
from tkinter import ttk
from urllib.parse import urlencode
def pairing_payload(host, port, fingerprint, token=None):
host = host.strip()
if (not 1 <= len(host) <= 253 or not re.fullmatch(r"[A-Za-z0-9._:%-]+", host)
or host in ("0.0.0.0", "::", "0:0:0:0:0:0:0:0")):
raise ValueError("Enter this PC's LAN IP or hostname, not 0.0.0.0. For the Android emulator use 10.0.2.2.")
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
raise ValueError("Port must be 1..65535")
fingerprint = fingerprint.upper()
if not re.fullmatch(r"[0-9A-F]{64}", fingerprint):
raise ValueError("A valid certificate SHA-256 fingerprint is required")
fields = dict(v="1", mode="tls", host=host, port=str(port), sha256=fingerprint)
if token is not None:
if len(token) > 256 or any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in token):
raise ValueError("Token must be at most 256 characters with no control characters")
fields["token"] = token
payload = "mangolink://pair?" + urlencode(fields)
if len(payload) > 2048:
raise ValueError("Pairing details are too long")
return payload
def qr_matrix(payload):
try:
import qrcode
except ImportError as exc:
raise RuntimeError("QR pairing requires: py -3 -m pip install -r requirements-qr.txt") from exc
code = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, border=4, box_size=1)
code.add_data(payload)
code.make(fit=True)
return code.get_matrix()
class PairingDialog(tk.Toplevel):
def __init__(self, parent, host, port, fingerprint, token):
super().__init__(parent)
self.title("Pair MangoLink over TLS")
self.transient(parent)
self.grab_set()
self.port, self.fingerprint, self.token = port, fingerprint, token
self.image = None
self.payload = None
body = ttk.Frame(self, padding=16)
body.pack(fill="both", expand=True)
ttk.Label(body, text="Scan this screen in MangoLink → Connection settings.", wraplength=460).pack(anchor="w")
ttk.Label(body, text="PC LAN IP / hostname (Android emulator: 10.0.2.2)").pack(anchor="w", pady=(12, 0))
self.host = tk.StringVar(value=host if host not in ("0.0.0.0", "::") else "")
ttk.Entry(body, textvariable=self.host, width=48).pack(fill="x")
self.include_token = tk.BooleanVar(value=True)
ttk.Checkbutton(body, text="Include session token", variable=self.include_token).pack(anchor="w", pady=8)
ttk.Label(body, text="Includes the public certificate fingerprint. Keep this QR private when it includes the token.",
wraplength=460).pack(anchor="w")
ttk.Button(body, text="Generate / update QR code", command=self.generate).pack(pady=8)
self.display = ttk.Label(body, text="Enter the PC LAN IP, then generate the QR code.", anchor="center")
self.display.pack(fill="both", expand=True)
ttk.Label(body, text="On the phone: review the details, then tap Connect. The private key stays on the PC.",
wraplength=460).pack(anchor="w", pady=8)
ttk.Button(body, text="Close", command=self.destroy).pack()
self.host.trace_add("write", self.invalidate)
self.include_token.trace_add("write", self.invalidate)
if self.host.get():
self.generate()
def invalidate(self, *_):
self.payload = None
self.image = None
self.display.config(image="", text="Details changed. Generate an updated QR code.")
def generate(self):
self.invalidate()
try:
payload = pairing_payload(self.host.get(), self.port, self.fingerprint,
self.token if self.include_token.get() else None)
matrix = qr_matrix(payload)
size = len(matrix)
image = tk.PhotoImage(master=self, width=size, height=size)
image.put(" ".join("{" + " ".join("black" if cell else "white" for cell in row) + "}" for row in matrix))
self.image = image.zoom(max(2, 420 // size))
self.display.config(image=self.image, text="")
self.payload = payload
except (ValueError, RuntimeError) as exc:
self.display.config(text=str(exc), wraplength=460)
Also included: quick-start README, Protocol 1 specification, QR pairing format, dependency lists and test files. An IP address alone does not make hardware compatible; its firmware must implement the protocol.
4 / TERMINAL MODE
The same server, without the GUI.
After the Windows setup above, generate a certificate once and start the TLS server:
.\.venv\Scripts\python.exe tls_support.py
.\.venv\Scripts\python.exe server.py --host 0.0.0.0 --port 8766
If you already created a certificate in the default folder, skip the first command. The CLI prints the fingerprint and token for manual phone setup; QR display belongs to the desktop GUI. On Linux/macOS replace .\.venv\Scripts\python.exe with .venv/bin/python.
Use unencrypted TCP for a trusted lab test
.\.venv\Scripts\python.exe server.py --mode tcp --host 0.0.0.0 --port 8765
Select TCP and the same port on the phone. This exposes the token, logs and commands in readable form on the network. TLS failures never switch to TCP automatically.
DEVELOPER PREVIEW
What this example covers.
Source 0.3.0 passed 24 server/TLS/pairing tests and 4 GUI tests on Windows and Linux. Physical-phone scanning still needs testing. The app is currently for foreground monitoring; screen-off/background continuity, automatic reconnect, durable history, cloud relay and ESP32 firmware are not implemented.
Keep the PC awake and use a trusted LAN. A private-network firewall rule may be needed for Python; guest-network isolation and VPNs can block local connections. This is a development example, not a public internet remote-access service.
Read the privacy policy for camera, connection settings and token handling.
Download checksum and source version
Source snapshot: c37e77dcf903fea89019826d9a345a44fb92d5cf. The ZIP includes a source manifest and file checksums, with no certificates, private keys or real session credentials.
Archive SHA-256 (download checksum, separate from the TLS certificate fingerprint):
72520a3adf6a5a5d0b50b2d485d09a8afa7ecdf9f7f6cd1ee9d5dc6545696637
Need help? [email protected]
Mango Juice Tech