Creating SHA-256 values from the timing variation of neon discharge events

There is something hella cool to me about making a modern digital output from an old physical phenomenon. This project began with that vibe: instead of taking randomness from software alone, I wanted to build a machine that observes the irregular behavior of small neon lamps and turns that behavior into a usable digital artifact.
The result is a Neon Entropy (Pseudo!) Random Number Generator: a hardware system that watches neon discharge events across multiple channels, extracts timing variation from those events, accumulates accepted bits, and periodically emits a SHA-256 value derived from that physical process.
This is not presented as a certified cryptographic product (ergo me insisting that it is pseudo as I do not want to be bashed by cryptographic experts and keyboard warriors!). It is, however, a proof-of-concept hardware entropy instrument and a demonstration of how an unpredictable analog process can be conditioned into a clean digital output.
Concept
At a high level, the project works like this:
- three matched neon relaxation oscillator channels produce firing events
- a Raspberry Pi Pico W monitors those channels through its three ADC inputs
- the firmware detects event activity and timestamps it at microsecond scale
- several timing relationships are extracted from each event, including same-channel interval, change in interval, and interval relative to any event
- those measured quantities are converted into candidate raw bits
- the candidate bits are passed through a Von Neumann-style debiasing step, where opposite bit pairs are accepted and matching pairs are discarded
- only the accepted bits are accumulated into a fixed pool
- once that pool reaches its target size, the accepted bits are packed into raw bytes
- that byte pool is hashed with SHA-256
- the resulting 256-bit digest is then displayed, logged, and independently audit-checked by the Python dashboard
That is the conceptual flow, but the important point is what the system is not doing. It is not simply taking a software random number and dressing it up with neon-themed presentation. Nor is it hashing an unchecked raw stream. The project begins with real measured behavior from three physical oscillator channels, derives timing-based binary candidates from that behavior, applies a debiasing stage, and only then hashes the conditioned pool into a final digest.
The end result is a 64-character hexadecimal SHA-256 value, but the real interest lies in the chain that produced it: a visible and measurable physical process feeding a modern digital conditioning pipeline. The machine therefore functions not just as an output generator, but as an instrument for observing how analog irregularity can be transformed into structured data.
Why neon?
Neon lamps are a compelling medium because they sit at the boundary between the physical and the electronic. They are old technology, visually evocative (one of my usual motivators), and their behavior is not perfectly regular. That makes them interesting as a source of timing variation— they go blink at a microscopically unsure timing intervals despite being turned on at t=0.
Rather than simply blinking a single lamp and pretending that is randomness, this project measures the microsecond-scale spacing and differences between events. The goal is not the lamp as an ornament (as you cannot even see them encapsulated in their optocoupled tunnels), but the lamp as a physical source whose irregularities can be observed and quantified.
Hardware structure
The hardware is built around three neon relaxation oscillator channels, each observed independently by the microcontroller through its own sensing path. I chose the Raspberry Pi Pico W in part because it already provides three convenient ADC inputs on-board, which made it a natural fit for a three-channel design without needing additional external analog acquisition hardware.
In the current build, those three channels are:
GP26_4.60uFGP27_4.60uFGP28_4.60uF
Each channel consists of a classic neon relaxation oscillator circuit built to the same intended capacitance value: 4.60 µF. Importantly, the capacitors were not assumed to match simply because of their printed markings. They were measured and selected so that the three oscillator channels would be as electrically similar as practical. The point of that matching was to make the channels theoretically comparable, so that differences in behavior would be more meaningful and less obviously attributable to gross component mismatch.

To observe the neon firing events, the project uses TEPT4400 ambient light sensors as the optical sensing element for each channel. Rather than probing the high-voltage neon behavior directly, each TEPT4400 watches the light output of its corresponding neon lamp and converts those flashes into an analog signal that the Pico W can sample on its ADC input. This keeps the measurement side cleanly separated from the oscillator itself and turns each neon flash into something the microcontroller can safely and repeatedly observe.

In an idealized sense, if all three oscillator channels were perfectly identical, one would expect them to behave very similarly and to tend toward the same firing rhythm. In practice, however, they do not fire in perfectly locked unison. Small physical differences, analog noise, threshold behavior, optical sensing variation, and discharge variability all introduce slight divergences in timing. Those divergences are exactly what the project is interested in capturing.
The firmware watches these three ADC channels and emits serial telemetry for each detected event, including:
- event sequence number
- timestamp
- channel
- ADC value
- same-channel interval
- change in same-channel interval
- interval relative to any event
That produces a live stream of measured physical behavior rather than a black-box “random number.” The Pico W is therefore not just acting as a generic controller here; its three existing ADC channels directly support the project’s core architecture by allowing three matched neon oscillator circuits, sensed optically through TEPT4400 detectors, to be observed simultaneously.
From events to bits

The heart of the project is not merely counting pulses, but converting measured event behavior into a conditioned bitstream. Each neon event contributes several timing-related values, such as same-channel interval, change in interval, cross-event timing, channel identity, and low ADC information. From those measurements, the firmware derives candidate raw bits.
Those candidate bits are not accepted directly into the final pool. Instead, they pass through a Von Neumann-style debiasing step. The firmware examines raw bits in pairs: opposite pairs are accepted as output bits, while matching pairs are discarded. In the present implementation, 01 is accepted as one output value, 10 as the other, and 00 and 11 are rejected. This helps reduce simple first-order bias before any hashing takes place.
The system keeps track of:
- candidate bits
- accepted bits
- rejected pairs
- per-channel event totals
Only the accepted debiased bits are accumulated into a fixed pool. The dashboard shows progress toward the target bit count as a running percentage. When that pool is full, the accepted bits are packed into raw bytes and passed to SHA-256.
In the search for true randomness validity (as best as I can do in the hobby sense), the project is not simply hashing an unchecked raw stream, nor is it inventing a software random number. It is observing physical timing behavior from the neon channels, deriving candidate binary outcomes from that behavior, applying a Von Neumann-style extraction stage, and only then hashing the resulting conditioned pool into a clean 256-bit digest.
Why SHA-256?
SHA-256 was chosen because it provides a standard, fixed-length representation of the collected pool.
That gives several benefits:
- the output is always the same size
- the result is easy to display and log
- small changes in the input create a very different output
- the resulting value can be reused as a seed, token, or identity
A SHA-256 hash is not reversible. You cannot take the final digest and recover the input pool from it. That is one reason the project later gained an audit mode, described below.
Firmware output and telemetry
The device emits several serial record types:
EVENTSTATUSRESULTAUDIT
These make the machine inspectable.
EVENT lines provide the raw stream of sensed activity.STATUS lines report the current pool state and channel counts.RESULT lines announce a completed SHA-256 cycle.AUDIT lines provide the exact pre-hash byte pool in hex along with the resulting digest.
This means the project is not only generating outputs, but also exposing enough internal state to verify what it is doing.
Dashboard software
A custom Python dashboard was built to turn the device into a proper instrument rather than just a serial console stream.
The dashboard:
- connects over serial
- logs all data to CSV
- shows source health
- displays rolling event counts per channel
- shows timing statistics over a moving window
- displays entropy accumulation progress
- displays the current SHA-256 output
- provides a one-click clipboard copy button
- recomputes audit hashes independently for verification
The aesthetic direction was deliberately more attractive than a plain developer utility. The interface presents the machine as an instrument: part lab monitor, part mission-console display.
Source health and live-state behavior
One of the interesting design lessons in the software was the difference between historical quality and live activity.
Originally, the dashboard’s “source health” score was based only on a rolling 30-minute event window. That meant if the neon sources were turned off, the event counts in the window would slowly decrease, but source health could remain high for too long because it still reflected the recent past.
That was corrected by adding a separate live-state model:
LIVEWARNSTALEIDLE
The dashboard now tracks the age of the most recent event globally and by channel. If the source stops producing events, the health score is capped or collapsed quickly, even if the historical window still contains earlier good data.
This was an important refinement because it turned “source health” into something more truthful: not just how interesting the source was over the past half hour, but whether it is alive now.
Hash audit verification
One of the most useful improvements to the project was the addition of an AUDIT record.
This was added for a specific reason: a SHA-256 hash is one-way. If the device only prints the final digest, there is no way to reverse it and prove exactly what raw bytes were hashed.
The solution I managed is thus:
- print the exact pre-hash byte pool as
RAWHEX - print the resulting SHA-256 digest
- have the Python software independently recompute SHA-256 from
RAWHEX - compare the recomputed digest with the device’s reported digest
When the two match, the dashboard shows a PASS.
What this proves is limited but important: it confirms that the displayed SHA-256 output really corresponds to the emitted raw byte pool.
It does not prove that the source is cryptographically strong, unbiased, or production-grade. It proves the integrity of the hashing step and the honesty of the reporting pipeline. (Again, don’t shoot me cryptography dudes!!)
What the project is — and is not
This project is best understood as:
- a hardware entropy experiment
- a serial telemetry instrument
- a conditioning pipeline from analog irregularity to digital output
- a proof-of-concept physical seed generator
It is not yet a certified hardware random number generator for serious cryptographic deployment. That would require far more work in entropy characterization, statistical testing, failure analysis, and expert review. These are not paths I seek to traverse at present.
But as a working system, it already demonstrates something meaningful: an old-world physical behavior can be sensed, quantified, accumulated, hashed, logged, audited, and displayed as a modern digital value.
Potential uses
Even without claiming formal cryptographic readiness, the outputs are still useful for a number of applications:
- seed generation for procedural art (pretty cool)
- seed generation for simulations or generative systems
- unique identity or token creation
- hardware-driven visual or sound projects
- educational demonstrations of entropy and hashing
- experimentation with physical randomness sources
The project’s SHA-256 output is especially appealing because it can be treated as a stable 256-bit descriptor. It can seed software, drive visual systems, or serve as the core output of a standalone console.
Why this project matters to me
Part of the appeal of this build is aesthetic, but part of it is philosophical. Much of modern computing is abstracted into invisible layers. A project like this puts a physical process back in the chain. You can watch the source go alive or idle. You can watch accumulation stop when the neons are powered down. You can inspect the raw records. You can verify the digest independently.
That makes the result feel tangible. Most especially when I can combine my love for vacuum tube tech with a useful modern digital output. That bridge seems especially poignant.
Instead of asking software for a random value and accepting it on faith, this project invites the user to observe how a physical source is transformed into a digital output step by step.
Where it could go next
The present build already functions as a dashboarded entropy instrument, but there are several compelling directions for future development:
- a standalone enclosure with display and controls
- a hardware “generate” button and export workflow
- one of those POS thermal-printer outputs
- USB seed appliance mode
- integration with generative art or sound systems
- deeper statistical analysis of the raw pools
- more formal entropy testing and health checks
In other words, this is not the end of the project. It is the point where the machine became real enough to use.
Closing
The Neon Entropy (Pseudo) Random Number Generator takes an unpredictable physical behavior, turns it into structured data, conditions it with SHA-256, and presents the result through a purpose-built dashboard and audit system.
It is part experiment, part instrument, and part personal philosophical inquiry into the nature of randomness itself. Physical phenomena still have something to say to digital systems, and this project is an attempt to let them speak in a form a computer can actually use.
There is also something especially compelling about drawing that result from glowing neon hardware. These are devices tied to electrical traditions that reach back into the 19th century, yet here they are participating in a thoroughly modern process: feeding timing variation into a microcontroller, undergoing debiasing and hashing, and emerging as a 256-bit digital artifact. That contrast is a large part of what makes the project so satisfying to me.
In the end, this machine is not only about generating values. It is about watching old physical processes cross over into the digital world and still retain some of their mystery. That is what keeps the project interesting: the sense that even in an age of abstraction, a few flickering gas-discharge lamps can still produce something worth measuring, questioning, and using.

#!/usr/bin/env python3from __future__ import annotationsimport argparseimport csvimport hashlibimport queueimport signalimport statisticsimport threadingimport timefrom collections import defaultdict, dequefrom dataclasses import dataclass, fieldfrom datetime import datetimefrom pathlib import Pathfrom typing import Deque, Dict, List, Optionalimport serial # type: ignoreimport serial.tools.list_ports # type: ignoreimport tkinter as tkfrom tkinter import ttkTITLE = "Neon Entropy Random Number Generator"SUBTITLE = "Creates SHA-256 values from extracted timing variation in neon discharge events"SIGNATURE = "joshuacolemanmakes.wordpress.com"CHANNEL_NAMES = {0: "GP26_4.60uF", 1: "GP27_4.60uF", 2: "GP28_4.60uF"}WINDOW_SECONDS = 30 * 60UI_REFRESH_MS = 500LIVE_WARN_SECONDS = 2.0LIVE_STALE_SECONDS = 5.0LIVE_IDLE_SECONDS = 10.0PALETTE = { "bg": "#0B0E12", "panel": "#131922", "panel2": "#0F141C", "line": "#2B3544", "text": "#D9E2F1", "muted": "#92A0B3", "accent": "#D6A75A", "accent2": "#80C0A8",}dataclassclass EventRecord: seq: int micros: int channel: int channel_name: str adc: int dt_same_us: int ddt_same_us: int dt_any_us: int rtc_epoch: int rtc_iso: str temp_c: float wall_time: floatdataclassclass StatusRecord: rtc_epoch: int rtc_iso: str temp_c: float pool_bits: int target_bits: int progress_pct: float candidate_bits: int accepted_bits: int rejected_pairs: int ch0_events: int ch1_events: int ch2_events: intdataclassclass ResultRecord: cycle: int rtc_epoch: int rtc_iso: str temp_c: float elapsed_ms: int candidate_bits: int accepted_bits: int rejected_pairs: int ch0_events: int ch1_events: int ch2_events: int sha256_hex: str wall_time: floatdataclassclass AuditRecord: cycle: int rtc_epoch: int rtc_iso: str temp_c: float elapsed_ms: int candidate_bits: int accepted_bits: int rejected_pairs: int pool_bytes: int raw_hex: str sha256_hex: str verified: bool recomputed_sha256_hex: str wall_time: floatdataclassclass AppState: all_events: int = 0 start_time: float = field(default_factory=time.time) recent_events: Deque[EventRecord] = field(default_factory=deque) recent_temps: Deque[tuple[float, float]] = field(default_factory=deque) last_status: Optional[StatusRecord] = None last_result: Optional[ResultRecord] = None last_audit: Optional[AuditRecord] = None by_channel_counts_total: Dict[int, int] = field(default_factory=lambda: defaultdict(int)) last_event_wall_time: Optional[float] = None last_event_wall_time_by_channel: Dict[int, Optional[float]] = field(default_factory=lambda: {0: None, 1: None, 2: None}) logfile_path: Optional[Path] = None stop_requested: bool = False def prune(self) -> None: cutoff = time.time() - WINDOW_SECONDS while self.recent_events and self.recent_events[0].wall_time < cutoff: self.recent_events.popleft() while self.recent_temps and self.recent_temps[0][0] < cutoff: self.recent_temps.popleft()class SerialWorker(threading.Thread): def __init__(self, port: str, baud: int, out_queue: "queue.Queue[tuple[str, object]]", logfile: Path): super().__init__(daemon=True) self.port = port self.baud = baud self.out_queue = out_queue self.logfile = logfile self._stop = threading.Event() def stop(self) -> None: self._stop.set() def run(self) -> None: self.logfile.parent.mkdir(parents=True, exist_ok=True) with self.logfile.open("a", newline="") as f: writer = csv.writer(f) if self.logfile.stat().st_size == 0: writer.writerow([ "wall_time_iso","wall_time_unix","record_type","seq","micros","channel","channel_name","adc", "dt_same_us","ddt_same_us","dt_any_us","rtc_epoch","rtc_iso","temp_c", "status_pool_bits","status_target_bits","status_progress_pct","status_candidate_bits","status_accepted_bits","status_rejected_pairs", "status_ch0_events","status_ch1_events","status_ch2_events", "result_cycle","result_elapsed_ms","result_candidate_bits","result_accepted_bits","result_rejected_pairs", "result_ch0_events","result_ch1_events","result_ch2_events","result_sha256_hex", "audit_cycle","audit_elapsed_ms","audit_candidate_bits","audit_accepted_bits","audit_rejected_pairs","audit_pool_bytes","audit_raw_hex","audit_sha256_hex","audit_verified","raw_line" ]) f.flush() with serial.Serial(self.port, self.baud, timeout=1) as ser: time.sleep(2) ser.reset_input_buffer() while not self._stop.is_set(): raw = ser.readline() if not raw: continue wall = time.time() line = raw.decode("utf-8", errors="replace").strip() self.out_queue.put(("line", line)) row = [datetime.fromtimestamp(wall).isoformat(timespec="seconds"), f"{wall:.6f}"] if line.startswith("EVENT,"): p = line.split(",") if len(p) == 12: writer.writerow(row + ["EVENT", p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9],p[10],p[11], "","","","","","","","","","","","","","","","","","", line]) f.flush() elif line.startswith("STATUS,"): p = line.split(",") if len(p) == 13: writer.writerow(row + ["STATUS","","","","","","","","",p[1],p[2],p[3], p[4],p[5],p[6],p[7],p[8],p[9],p[10],p[11],p[12], "","","","","","","","","", line]) f.flush() elif line.startswith("RESULT,"): p = line.split(",") if len(p) == 14 and p[12] == "SHA256": writer.writerow(row + ["RESULT","","","","","","","","",p[2],p[3],p[4], "","","","","","","","","", p[1],p[5],p[6],p[7],p[8],p[9],p[10],p[11],p[13], "","","","","","","","","", line]) f.flush() elif line.startswith("AUDIT,"): p = line.split(",") if len(p) == 14 and p[10] == "RAWHEX" and p[12] == "SHA256": raw_hex = p[11].upper() sha256_hex = p[13].upper() verified = hashlib.sha256(bytes.fromhex(raw_hex)).hexdigest().upper() == sha256_hex writer.writerow(row + ["AUDIT","","","","","","","","",p[2],p[3],p[4], "","","","","","","","","", "","","","","","","","", p[1],p[5],p[6],p[7],p[8],p[9],raw_hex,sha256_hex,str(verified), line]) f.flush()def parse_event_line(line: str) -> Optional[EventRecord]: p = line.split(",") if len(p) != 12 or p[0] != "EVENT": return None try: return EventRecord( seq=int(p[1]), micros=int(p[2]), channel=int(p[3]), channel_name=p[4], adc=int(p[5]), dt_same_us=int(p[6]), ddt_same_us=int(p[7]), dt_any_us=int(p[8]), rtc_epoch=int(p[9]), rtc_iso=p[10], temp_c=float(p[11]), wall_time=time.time() ) except ValueError: return Nonedef parse_status_line(line: str) -> Optional[StatusRecord]: p = line.split(",") if len(p) != 13 or p[0] != "STATUS": return None try: return StatusRecord( rtc_epoch=int(p[1]), rtc_iso=p[2], temp_c=float(p[3]), pool_bits=int(p[4]), target_bits=int(p[5]), progress_pct=float(p[6]), candidate_bits=int(p[7]), accepted_bits=int(p[8]), rejected_pairs=int(p[9]), ch0_events=int(p[10]), ch1_events=int(p[11]), ch2_events=int(p[12]) ) except ValueError: return Nonedef parse_result_line(line: str) -> Optional[ResultRecord]: p = line.split(",") if len(p) != 14 or p[0] != "RESULT" or p[12] != "SHA256": return None try: return ResultRecord( cycle=int(p[1]), rtc_epoch=int(p[2]), rtc_iso=p[3], temp_c=float(p[4]), elapsed_ms=int(p[5]), candidate_bits=int(p[6]), accepted_bits=int(p[7]), rejected_pairs=int(p[8]), ch0_events=int(p[9]), ch1_events=int(p[10]), ch2_events=int(p[11]), sha256_hex=p[13], wall_time=time.time() ) except ValueError: return Nonedef parse_audit_line(line: str) -> Optional[AuditRecord]: p = line.split(",") if len(p) != 14 or p[0] != "AUDIT" or p[10] != "RAWHEX" or p[12] != "SHA256": return None try: raw_hex = p[11].upper() sha256_hex = p[13].upper() recomputed = hashlib.sha256(bytes.fromhex(raw_hex)).hexdigest().upper() return AuditRecord( cycle=int(p[1]), rtc_epoch=int(p[2]), rtc_iso=p[3], temp_c=float(p[4]), elapsed_ms=int(p[5]), candidate_bits=int(p[6]), accepted_bits=int(p[7]), rejected_pairs=int(p[8]), pool_bytes=int(p[9]), raw_hex=raw_hex, sha256_hex=sha256_hex, verified=(recomputed == sha256_hex), recomputed_sha256_hex=recomputed, wall_time=time.time() ) except ValueError: return Nonedef compute_metrics(state: AppState) -> Dict[str, object]: now = time.time() state.prune() events = list(state.recent_events) by_channel: Dict[int, List[EventRecord]] = {0: [], 1: [], 2: []} for e in events: by_channel[e.channel].append(e) seconds_since_last_event = None if state.last_event_wall_time is None else (now - state.last_event_wall_time) seconds_since_last_event_by_channel: Dict[int, Optional[float]] = {} for ch in (0, 1, 2): last_t = state.last_event_wall_time_by_channel.get(ch) seconds_since_last_event_by_channel[ch] = None if last_t is None else (now - last_t) metrics: Dict[str, object] = { "window_event_count": len(events), "uptime_s": now - state.start_time, "channel_stats": {}, "score": 1, "score_reason": "Insufficient data", "live_state": "IDLE", "live_reason": "No events received yet", "seconds_since_last_event": seconds_since_last_event, "seconds_since_last_event_by_channel": seconds_since_last_event_by_channel, } live_state = "LIVE" live_reasons: List[str] = [] if seconds_since_last_event is None: live_state = "IDLE" live_reasons.append("no events received yet") elif seconds_since_last_event > LIVE_IDLE_SECONDS: live_state = "IDLE" live_reasons.append(f"no events for {seconds_since_last_event:.1f}s") elif seconds_since_last_event > LIVE_STALE_SECONDS: live_state = "STALE" live_reasons.append(f"last event {seconds_since_last_event:.1f}s ago") elif seconds_since_last_event > LIVE_WARN_SECONDS: live_state = "WARN" live_reasons.append(f"event cadence slowed ({seconds_since_last_event:.1f}s since last event)") else: live_reasons.append("events arriving now") silent_channels: List[int] = [] for ch in (0, 1, 2): age = seconds_since_last_event_by_channel[ch] if age is None or age > LIVE_IDLE_SECONDS: silent_channels.append(ch) if silent_channels: channel_names = ", ".join(CHANNEL_NAMES[ch] for ch in silent_channels) if len(silent_channels) == 3: live_state = "IDLE" live_reasons.append("all channels silent") elif live_state == "LIVE": live_state = "WARN" live_reasons.append(f"silent channels: {channel_names}") metrics["live_state"] = live_state metrics["live_reason"] = "; ".join(live_reasons) valid_channels = 0 dt_avgs, event_counts, span_avgs, abs_ddt_avgs = [], [], [], [] channel_stats: Dict[int, Dict[str, float]] = {} for ch in (0, 1, 2): arr = by_channel[ch] dt_vals = [e.dt_same_us for e in arr if e.dt_same_us > 0] ddt_vals = [abs(e.ddt_same_us) for e in arr if e.dt_same_us > 0] if dt_vals: stats = { "count": float(len(arr)), "dt_avg": float(statistics.mean(dt_vals)), "dt_min": float(min(dt_vals)), "dt_max": float(max(dt_vals)), "dt_span": float(max(dt_vals) - min(dt_vals)), "ddt_abs_avg": float(statistics.mean(ddt_vals)) if ddt_vals else 0.0, } valid_channels += 1 dt_avgs.append(stats["dt_avg"]) event_counts.append(stats["count"]) span_avgs.append(stats["dt_span"]) abs_ddt_avgs.append(stats["ddt_abs_avg"]) else: stats = {"count": 0.0, "dt_avg": 0.0, "dt_min": 0.0, "dt_max": 0.0, "dt_span": 0.0, "ddt_abs_avg": 0.0} channel_stats[ch] = stats metrics["channel_stats"] = channel_stats score = 1 reasons = [] if valid_channels == 3: score += 2; reasons.append("all 3 channels active in rolling window") elif valid_channels == 2: score += 1; reasons.append("2 channels active in rolling window") if len(events) >= 30: score += 1; reasons.append("enough recent events") if span_avgs: mean_span = statistics.mean(span_avgs) if mean_span > 120000: score += 2; reasons.append("strong timing span") elif mean_span > 70000: score += 1; reasons.append("moderate timing span") if abs_ddt_avgs: mean_ddt = statistics.mean(abs_ddt_avgs) if mean_ddt > 30000: score += 2; reasons.append("strong interval variation") elif mean_ddt > 15000: score += 1; reasons.append("moderate interval variation") if len(dt_avgs) == 3 and (max(dt_avgs) - min(dt_avgs)) > 100000: score += 1; reasons.append("channels differentiated") if len(event_counts) == 3: mn = min(event_counts); mx = max(event_counts) if mn > 0 and (mx / mn) < 2.5: score += 1; reasons.append("no channel collapse") if live_state == "WARN": score = min(score, 5) reasons.append("live penalty: source slowing or one channel silent") elif live_state == "STALE": score = min(score, 3) reasons.append("live penalty: stale source") elif live_state == "IDLE": score = 1 reasons.append("live penalty: source idle") metrics["score"] = max(1, min(10, score)) metrics["score_reason"] = "; ".join(reasons) if reasons else "Insufficient data" return metricsclass Dashboard: def __init__(self, root: tk.Tk, state: AppState): self.root = root self.state = state self.root.title(TITLE) self.root.geometry("1180x820") self.root.configure(bg=PALETTE["bg"]) style = ttk.Style() try: style.theme_use("clam") except Exception: pass style.configure("TFrame", background=PALETTE["bg"]) style.configure("Panel.TLabelframe", background=PALETTE["panel"], foreground=PALETTE["accent"]) style.configure("Panel.TLabelframe.Label", background=PALETTE["panel"], foreground=PALETTE["accent"]) style.configure("Panel.TLabel", background=PALETTE["panel"], foreground=PALETTE["text"]) style.configure("Muted.TLabel", background=PALETTE["bg"], foreground=PALETTE["muted"]) style.configure("Header.TLabel", background=PALETTE["bg"], foreground=PALETTE["accent"]) style.configure("Big.TLabel", background=PALETTE["panel"], foreground=PALETTE["accent2"]) style.configure("Apollo.Horizontal.TProgressbar", troughcolor=PALETTE["panel2"], background=PALETTE["accent"]) self.score_var = tk.StringVar(value="1 / 10") self.reason_var = tk.StringVar(value="Waiting for data") self.live_var = tk.StringVar(value="IDLE") self.live_reason_var = tk.StringVar(value="No events received yet") self.last_event_age_var = tk.StringVar(value="No events yet") self.logfile_var = tk.StringVar(value="") self.uptime_var = tk.StringVar(value="0 s") self.total_events_var = tk.StringVar(value="0") self.window_events_var = tk.StringVar(value="0") self.status_var = tk.StringVar(value="No STATUS line yet") self.rtc_var = tk.StringVar(value="No RTC yet") self.temp_var = tk.StringVar(value="No temp yet") self.sha_var = tk.StringVar(value="Awaiting first SHA-256 result...") self.cycle_var = tk.StringVar(value="Cycle 0") self.elapsed_var = tk.StringVar(value="Elapsed: NA") self.audit_var = tk.StringVar(value="No AUDIT line yet") self.progress_var = tk.StringVar(value="0 / 512 bits") self.progress_pct_var = tk.StringVar(value="0.0 %") self.channel_vars: Dict[int, Dict[str, tk.StringVar]] = {} self._build() self._refresh() def copy_hash(self): value = self.sha_var.get().strip() if value and value != "Awaiting first SHA-256 result...": self.root.clipboard_clear() self.root.clipboard_append(value) self.root.update() def _build(self): frm = ttk.Frame(self.root, padding=14) frm.pack(fill="both", expand=True) ttk.Label(frm, text=TITLE, style="Header.TLabel", font=("Menlo", 22, "bold")).pack(anchor="w") ttk.Label(frm, text=SUBTITLE, style="Muted.TLabel", font=("Menlo", 11)).pack(anchor="w", pady=(0, 10)) top = ttk.Frame(frm) top.pack(fill="x", pady=(0, 12)) left = ttk.LabelFrame(top, text="SOURCE HEALTH", style="Panel.TLabelframe") left.pack(side="left", fill="y", padx=(0, 12)) ttk.Label(left, textvariable=self.score_var, style="Big.TLabel", font=("Menlo", 26, "bold")).pack(anchor="w", padx=12, pady=(10, 2)) self.pb_score = ttk.Progressbar(left, style="Apollo.Horizontal.TProgressbar", orient="horizontal", length=260, mode="determinate", maximum=10) self.pb_score.pack(padx=12, pady=(0, 8)) ttk.Label(left, textvariable=self.live_var, style="Panel.TLabel", font=("Menlo", 13, "bold")).pack(anchor="w", padx=12, pady=(0, 2)) ttk.Label(left, textvariable=self.live_reason_var, style="Panel.TLabel", wraplength=320).pack(anchor="w", padx=12, pady=(0, 8)) ttk.Label(left, textvariable=self.reason_var, style="Panel.TLabel", wraplength=320).pack(anchor="w", padx=12, pady=(0, 12)) right = ttk.LabelFrame(top, text="SHA-256 OUTPUT", style="Panel.TLabelframe") right.pack(side="left", fill="both", expand=True) ttk.Label(right, textvariable=self.cycle_var, style="Panel.TLabel", font=("Menlo", 12, "bold")).pack(anchor="w", padx=12, pady=(10, 0)) ttk.Label(right, textvariable=self.elapsed_var, style="Panel.TLabel", font=("Menlo", 11)).pack(anchor="w", padx=12, pady=(0, 8)) hash_frame = ttk.Frame(right) hash_frame.pack(fill="x", padx=12, pady=(0, 10)) hash_label = tk.Label(hash_frame, textvariable=self.sha_var, bg=PALETTE["panel2"], fg=PALETTE["text"], font=("Menlo", 13, "bold"), justify="left", anchor="w", wraplength=700, padx=10, pady=10) hash_label.pack(side="left", fill="x", expand=True) ttk.Button(hash_frame, text="Copy to Clipboard", command=self.copy_hash).pack(side="left", padx=(10, 0)) prog = ttk.LabelFrame(frm, text="ENTROPY ACCUMULATION", style="Panel.TLabelframe") prog.pack(fill="x", pady=(0, 12)) ttk.Label(prog, textvariable=self.progress_var, style="Panel.TLabel", font=("Menlo", 12, "bold")).pack(anchor="w", padx=12, pady=(10, 0)) ttk.Label(prog, textvariable=self.progress_pct_var, style="Panel.TLabel", font=("Menlo", 11)).pack(anchor="w", padx=12, pady=(0, 6)) self.pb_pool = ttk.Progressbar(prog, style="Apollo.Horizontal.TProgressbar", orient="horizontal", length=1000, mode="determinate", maximum=100) self.pb_pool.pack(fill="x", padx=12, pady=(0, 12)) info = ttk.LabelFrame(frm, text="RUN TELEMETRY", style="Panel.TLabelframe") info.pack(fill="x", pady=(0, 12)) for label, var in [ ("Log file", self.logfile_var), ("Uptime", self.uptime_var), ("Last event age", self.last_event_age_var), ("Total events", self.total_events_var), ("Rolling-window events", self.window_events_var), ("Last STATUS", self.status_var), ("RTC time", self.rtc_var), ("Temp (rolling)", self.temp_var), ("Hash audit", self.audit_var), ]: row = ttk.Frame(info) row.pack(fill="x", padx=10, pady=4) ttk.Label(row, text=f"{label}:", style="Panel.TLabel", width=18).pack(side="left") ttk.Label(row, textvariable=var, style="Panel.TLabel").pack(side="left") grid = ttk.Frame(frm) grid.pack(fill="both", expand=True) for ch in (0, 1, 2): box = ttk.LabelFrame(grid, text=CHANNEL_NAMES[ch], style="Panel.TLabelframe") box.grid(row=0, column=ch, sticky="nsew", padx=6, pady=6) grid.columnconfigure(ch, weight=1) vars_for_ch = { "count": tk.StringVar(value="0"), "dt_avg": tk.StringVar(value="NA"), "dt_min": tk.StringVar(value="NA"), "dt_max": tk.StringVar(value="NA"), "dt_span": tk.StringVar(value="NA"), "ddt_abs_avg": tk.StringVar(value="NA"), } self.channel_vars[ch] = vars_for_ch for label, key in [ ("Events in window", "count"), ("Avg dt (us)", "dt_avg"), ("Min dt (us)", "dt_min"), ("Max dt (us)", "dt_max"), ("Span (us)", "dt_span"), ("Avg |ddt| (us)", "ddt_abs_avg"), ]: row = ttk.Frame(box) row.pack(fill="x", padx=10, pady=4) ttk.Label(row, text=f"{label}:", style="Panel.TLabel", width=16).pack(side="left") ttk.Label(row, textvariable=vars_for_ch[key], style="Panel.TLabel").pack(side="left") ttk.Label(frm, text=SIGNATURE, style="Muted.TLabel", font=("Menlo", 10, "italic")).pack(anchor="e", pady=(6, 0)) def _refresh(self): metrics = compute_metrics(self.state) self.score_var.set(f"{metrics['score']} / 10") self.pb_score["value"] = metrics["score"] self.live_var.set(f"LIVE STATE: {metrics['live_state']}") self.live_reason_var.set(str(metrics["live_reason"])) self.reason_var.set(str(metrics["score_reason"])) self.logfile_var.set(str(self.state.logfile_path) if self.state.logfile_path else "") self.uptime_var.set(f"{int(metrics['uptime_s'])} s") if metrics["seconds_since_last_event"] is None: self.last_event_age_var.set("No events yet") else: self.last_event_age_var.set(f"{metrics['seconds_since_last_event']:.1f} s") self.total_events_var.set(str(self.state.all_events)) self.window_events_var.set(str(metrics["window_event_count"])) self.status_var.set(str(self.state.last_status) if self.state.last_status else "No STATUS line yet") if self.state.last_status: s = self.state.last_status self.rtc_var.set(s.rtc_iso) self.progress_var.set(f"{s.pool_bits} / {s.target_bits} bits") self.progress_pct_var.set(f"{s.progress_pct:.1f} %") self.pb_pool["value"] = s.progress_pct temps = [t for _, t in self.state.recent_temps] if temps: self.temp_var.set(f"avg={statistics.mean(temps):.2f} C min={min(temps):.2f} max={max(temps):.2f}") else: self.temp_var.set("No temp yet") if self.state.last_result: r = self.state.last_result self.sha_var.set(r.sha256_hex) self.cycle_var.set(f"Cycle {r.cycle}") self.elapsed_var.set(f"Elapsed: {r.elapsed_ms/1000:.1f} s Accepted bits: {r.accepted_bits} Candidate bits: {r.candidate_bits}") else: self.sha_var.set("Awaiting first SHA-256 result...") if self.state.last_audit: a = self.state.last_audit state_text = "PASS" if a.verified else "FAIL" self.audit_var.set(f"{state_text} cycle={a.cycle} bytes={a.pool_bytes} recomputed={a.recomputed_sha256_hex[:16]}...") else: self.audit_var.set("No AUDIT line yet") channel_stats: Dict[int, Dict[str, float]] = metrics["channel_stats"] # type: ignore for ch, stats in channel_stats.items(): vars_for_ch = self.channel_vars[ch] vars_for_ch["count"].set(str(int(stats["count"]))) for key in ("dt_avg", "dt_min", "dt_max", "dt_span", "ddt_abs_avg"): value = stats[key] vars_for_ch[key].set("NA" if value == 0.0 else str(int(value))) if not self.state.stop_requested: self.root.after(UI_REFRESH_MS, self._refresh)def main() -> int: parser = argparse.ArgumentParser(description="Neon RNG logger/dashboard") parser.add_argument("--port", help="Serial port, e.g. /dev/cu.usbmodem1101") parser.add_argument("--baud", type=int, default=115200) parser.add_argument("--outdir", type=Path, required=True) args = parser.parse_args() if not args.port: ports = [p.device for p in serial.tools.list_ports.comports()] print("Available serial ports:") for p in ports: print(f" {p}") print("\nRun again with --port <device>") return 1 outdir = args.outdir.expanduser().resolve() outdir.mkdir(parents=True, exist_ok=True) logfile = outdir / f"neon_rng_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv" state = AppState(logfile_path=logfile) q: "queue.Queue[tuple[str, object]]" = queue.Queue() worker = SerialWorker(args.port, args.baud, q, logfile) worker.start() root = tk.Tk() Dashboard(root, state) def handle_sigint(signum, frame): state.stop_requested = True worker.stop() try: root.destroy() except Exception: pass signal.signal(signal.SIGINT, handle_sigint) def drain_queue(): try: while True: kind, payload = q.get_nowait() if kind != "line": continue line = str(payload) if line.startswith("EVENT,"): event = parse_event_line(line) if event: state.all_events += 1 state.by_channel_counts_total[event.channel] += 1 state.last_event_wall_time = event.wall_time state.last_event_wall_time_by_channel[event.channel] = event.wall_time state.recent_events.append(event) state.recent_temps.append((event.wall_time, event.temp_c)) elif line.startswith("STATUS,"): status = parse_status_line(line) if status: state.last_status = status state.recent_temps.append((time.time(), status.temp_c)) elif line.startswith("RESULT,"): result = parse_result_line(line) if result: state.last_result = result state.recent_temps.append((result.wall_time, result.temp_c)) elif line.startswith("AUDIT,"): audit = parse_audit_line(line) if audit: state.last_audit = audit state.recent_temps.append((audit.wall_time, audit.temp_c)) except queue.Empty: pass if not state.stop_requested: root.after(200, drain_queue) root.after(200, drain_queue) try: root.mainloop() finally: state.stop_requested = True worker.stop() worker.join(timeout=2) return 0if __name__ == "__main__": raise SystemExit(main())
Leave a Reply