Serve an on-box web UI backed by the JSON API
source-pr / source (pull_request) Successful in 12s

The miner now serves a single page that polls /api/hardware and shows profile,
chip, PSU, operating point, chains and EEPROM state, active chains, target and
whether hashing stopped. The page is a convenience; the API routes it uses are
the interface of record, so a JSON-only client loses nothing.

No framework and no new dependency: the request parser is bounded, only GET is
accepted, responses close the connection and are not cached. MiningStatus now
exposes its hardware and summary documents so the UI and the cgminer-style
server build them once, in one place.
This commit is contained in:
2026-10-22 10:38:07 -06:00
parent 914fb8bef7
commit b25d6b2a71
3 changed files with 259 additions and 0 deletions
+1
View File
@@ -27,6 +27,7 @@ pub mod stratum_v2_session;
pub mod stratum_wire;
pub mod stratum_work;
pub mod tuning;
pub mod web;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Vendor {
+10
View File
@@ -60,6 +60,16 @@ impl MiningStatus {
}
}
/// The `hardware` document, for the on-box UI and local clients.
pub fn hardware_document(&self) -> Value {
hardware_json(self.hardware())
}
/// The `summary` document, for the on-box UI and local clients.
pub fn summary_document(&self) -> Value {
self.response("summary")
}
fn hardware(&self) -> Option<HardwareSnapshot> {
self.hardware.lock().ok().and_then(|slot| slot.clone())
}
+248
View File
@@ -0,0 +1,248 @@
// SPDX-License-Identifier: MIT
//! On-box web UI.
//!
//! A small HTTP surface served by the miner itself: a single page that polls the JSON API, plus
//! the API routes it uses. The API stays the interface of record; the page is a convenience, so a
//! client that only speaks JSON loses nothing.
//!
//! No framework and no dependency: the request parser is bounded, only `GET` is accepted, and every
//! response closes the connection.
use crate::management::MiningStatus;
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::Arc;
use std::time::Duration;
const MAX_REQUEST_BYTES: usize = 2048;
const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
const PAGE: &str = r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Alkane miner</title>
<style>
body{font:14px/1.4 system-ui,sans-serif;margin:2rem;color:#1b1b1b}
h1{font-size:1.2rem;margin:0 0 1rem}
table{border-collapse:collapse;min-width:28rem}
th,td{text-align:left;padding:.35rem .6rem;border-bottom:1px solid #ddd}
th{width:11rem;color:#555;font-weight:600}
.bad{color:#a11}
</style>
</head>
<body>
<h1>Alkane miner</h1>
<table id="t"><tbody><tr><td>loading</td><td></td></tr></tbody></table>
<script>
async function refresh(){
const t=document.getElementById('t').tBodies[0];
try{
const h=await (await fetch('/api/hardware')).json();
const d=h.HARDWARE[0];
if(!d.available){t.innerHTML='<tr><td>hardware</td><td class="bad">not detected yet</td></tr>';return}
const rows=[
['profile',d.profile],['chip',d.chip],['PSU',d.psu],
['frequency',d.frequency_mhz+' MHz'],
['voltage',d.operating_point.voltage_mv+' mV'],
['confirmed',d.operating_point.confirmed?'yes':'no (conservative)'],
['chains',d.chains.length],['active chains',d.active_chains.length],
['target',d.target],
['stopped',d.stopped||'no']
];
t.innerHTML=rows.map(r=>'<tr><th>'+r[0]+'</th><td>'+r[1]+'</td></tr>').join('')
+d.chains.map(c=>'<tr><th>chain '+c.index+'</th><td>'+c.chip+', '+c.chips_found+
' chips, EEPROM '+c.eeprom.state+'</td></tr>').join('');
}catch(e){t.innerHTML='<tr><td>error</td><td class="bad">'+e+'</td></tr>'}
}
refresh();setInterval(refresh,5000);
</script>
</body>
</html>
"#;
/// Bind and serve until the listener fails.
pub fn serve(bind: SocketAddr, status: Arc<MiningStatus>) -> io::Result<()> {
let listener = TcpListener::bind(bind)?;
serve_listener(listener, status)
}
/// Serve on an already-bound listener.
pub fn serve_listener(listener: TcpListener, status: Arc<MiningStatus>) -> io::Result<()> {
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let status = Arc::clone(&status);
// Each connection is short, bounded and closes itself.
std::thread::spawn(move || {
let _ = handle(stream, &status);
});
}
Ok(())
}
/// Handle one HTTP request.
pub fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> {
stream.set_read_timeout(Some(CLIENT_TIMEOUT))?;
stream.set_write_timeout(Some(CLIENT_TIMEOUT))?;
let mut request = Vec::new();
let mut chunk = [0_u8; 512];
loop {
let count = stream.read(&mut chunk)?;
if count == 0 {
break;
}
request.extend_from_slice(&chunk[..count]);
if request.len() > MAX_REQUEST_BYTES {
return respond(&mut stream, 431, "text/plain", b"request too large");
}
if request.windows(4).any(|window| window == b"\r\n\r\n") {
break;
}
}
let head = String::from_utf8_lossy(&request);
let mut parts = head.lines().next().unwrap_or("").split_whitespace();
let method = parts.next().unwrap_or("");
let path = parts.next().unwrap_or("");
if method != "GET" {
return respond(&mut stream, 405, "text/plain", b"method not allowed");
}
match path {
"/" | "/index.html" => respond(
&mut stream,
200,
"text/html; charset=utf-8",
PAGE.as_bytes(),
),
"/api/hardware" => {
let body = status.hardware_document().to_string();
respond(&mut stream, 200, "application/json", body.as_bytes())
}
"/api/summary" => {
let body = status.summary_document().to_string();
respond(&mut stream, 200, "application/json", body.as_bytes())
}
_ => respond(&mut stream, 404, "text/plain", b"not found"),
}
}
fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> io::Result<()> {
let reason = match code {
200 => "OK",
404 => "Not Found",
405 => "Method Not Allowed",
431 => "Request Header Fields Too Large",
_ => "Error",
};
let header = format!(
"HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n",
body.len()
);
stream.write_all(header.as_bytes())?;
stream.write_all(body)?;
stream.flush()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::{
ChainReport, ChipModel, EepromState, Envelope, HardwarePlan, OperatingPoint,
};
use crate::management::HardwareSnapshot;
use std::net::TcpStream as Client;
fn status() -> Arc<MiningStatus> {
let status = MiningStatus::new();
status.set_hardware(HardwareSnapshot {
plan: HardwarePlan {
profile: "s19jpro-bm1362-pic".into(),
chip: ChipModel::Bm1362,
chains: vec![ChainReport {
index: 0,
chip: ChipModel::Bm1362,
chips_found: 126,
eeprom: EepromState::Absent,
response_per_mille: Some(950),
}],
envelope: Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
},
operating_point: OperatingPoint {
voltage_mv: 1200,
frequency_mhz: 500,
confirmed: false,
},
psu: "APW12".into(),
fan_zones: Vec::new(),
},
active_chains: vec![0],
stopped: None,
frequency_mhz: 512,
target: "power:3000".into(),
});
Arc::new(status)
}
fn request(path: &str) -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
let status = status();
let worker = std::thread::spawn(move || {
let (stream, _) = listener.accept().expect("accept");
handle(stream, &status).expect("handle");
});
let mut client = Client::connect(address).expect("connect");
client
.write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes())
.expect("write");
let mut reply = String::new();
client.read_to_string(&mut reply).expect("read");
worker.join().expect("join");
reply
}
#[test]
fn the_page_is_served_at_root() {
let reply = request("/");
assert!(reply.starts_with("HTTP/1.1 200 OK"));
assert!(reply.contains("text/html"));
assert!(reply.contains("Alkane miner"));
}
#[test]
fn the_api_returns_the_hardware_document() {
let reply = request("/api/hardware");
assert!(reply.starts_with("HTTP/1.1 200 OK"));
assert!(reply.contains("application/json"));
assert!(reply.contains("s19jpro-bm1362-pic"));
assert!(reply.contains("bm1362"));
}
#[test]
fn unknown_paths_are_404() {
let reply = request("/nope");
assert!(reply.starts_with("HTTP/1.1 404 Not Found"));
}
#[test]
fn only_get_is_accepted() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
let status = status();
let worker = std::thread::spawn(move || {
let (stream, _) = listener.accept().expect("accept");
handle(stream, &status).expect("handle");
});
let mut client = Client::connect(address).expect("connect");
client
.write_all(b"POST / HTTP/1.1\r\nHost: miner\r\nContent-Length: 0\r\n\r\n")
.expect("write");
let mut reply = String::new();
client.read_to_string(&mut reply).expect("read");
worker.join().expect("join");
assert!(reply.starts_with("HTTP/1.1 405 Method Not Allowed"));
}
}