quality baseline

This commit is contained in:
2026-03-24 13:40:35 +00:00
parent e2a970e69c
commit c7786fa8b0
90 changed files with 3076 additions and 1334 deletions
@@ -1,10 +1,10 @@
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use prometeu_drivers::{AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
use ringbuf::traits::{Consumer, Producer, Split};
use prometeu_hal::LoopMode;
use ringbuf::HeapRb;
use ringbuf::traits::{Consumer, Producer, Split};
use std::sync::Arc;
use std::time::Duration;
use prometeu_hal::LoopMode;
pub struct HostAudio {
pub producer: Option<ringbuf::wrap::CachingProd<Arc<HeapRb<AudioCommand>>>>,
@@ -14,18 +14,12 @@ pub struct HostAudio {
impl HostAudio {
pub fn new() -> Self {
Self {
producer: None,
perf_consumer: None,
_stream: None,
}
Self { producer: None, perf_consumer: None, _stream: None }
}
pub fn init(&mut self) {
let host = cpal::default_host();
let device = host
.default_output_device()
.expect("no output device available");
let device = host.default_output_device().expect("no output device available");
let config = cpal::StreamConfig {
channels: 2,
@@ -94,26 +88,17 @@ pub struct AudioMixer {
impl AudioMixer {
pub fn new() -> Self {
Self {
voices: Default::default(),
last_processing_time: Duration::ZERO,
paused: false,
}
Self { voices: Default::default(), last_processing_time: Duration::ZERO, paused: false }
}
pub fn process_command(&mut self, cmd: AudioCommand) {
match cmd {
AudioCommand::Play {
sample,
voice_id,
volume,
pan,
pitch,
priority,
loop_mode,
} => {
AudioCommand::Play { sample, voice_id, volume, pan, pitch, priority, loop_mode } => {
if voice_id < MAX_CHANNELS {
println!("[AudioMixer] Playing voice {}: vol={}, pitch={}, loop={:?}", voice_id, volume, pitch, loop_mode);
println!(
"[AudioMixer] Playing voice {}: vol={}, pitch={}, loop={:?}",
voice_id, volume, pitch, loop_mode
);
self.voices[voice_id] = Channel {
sample: Some(sample),
active: true,
@@ -212,7 +197,8 @@ impl AudioMixer {
voice.pos += step;
let end_pos = sample_data.loop_end.map(|e| e as f64).unwrap_or(sample_data.data.len() as f64);
let end_pos =
sample_data.loop_end.map(|e| e as f64).unwrap_or(sample_data.data.len() as f64);
if voice.pos >= end_pos {
if voice.loop_mode == LoopMode::On {
@@ -2,16 +2,17 @@ use prometeu_hal::telemetry::CertificationConfig;
pub fn load_cap_config(path: &str) -> Option<CertificationConfig> {
let content = std::fs::read_to_string(path).ok()?;
let mut config = CertificationConfig {
enabled: true,
..Default::default()
};
let mut config = CertificationConfig { enabled: true, ..Default::default() };
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') { continue; }
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split('=').collect();
if parts.len() != 2 { continue; }
if parts.len() != 2 {
continue;
}
let key = parts[0].trim();
let val = parts[1].trim();
@@ -1,15 +1,15 @@
use prometeu_hal::debugger_protocol::*;
use prometeu_drivers::hardware::Hardware;
use prometeu_firmware::{BootTarget, Firmware};
use prometeu_hal::cartridge_loader::CartridgeLoader;
use prometeu_hal::debugger_protocol::*;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use prometeu_drivers::hardware::Hardware;
use prometeu_hal::cartridge_loader::CartridgeLoader;
/// Host-side implementation of the PROMETEU DevTools Protocol.
///
///
/// This component acts as a TCP server that allows external tools (like the
/// Prometeu Debugger) to observe and control the execution of the virtual machine.
///
///
/// Communication is based on JSONL (JSON lines) over TCP.
pub struct HostDebugger {
/// If true, the VM will not start execution until a 'start' command is received.
@@ -42,12 +42,12 @@ impl HostDebugger {
if let BootTarget::Cartridge { path, debug: true, debug_port } = boot_target {
self.waiting_for_start = true;
// Pre-load cartridge metadata so the Handshake message can contain
// Pre-load cartridge metadata so the Handshake message can contain
// valid information about the App being debugged.
if let Ok(cartridge) = CartridgeLoader::load(path) {
firmware.os.initialize_vm(&mut firmware.vm, &cartridge);
}
match TcpListener::bind(format!("127.0.0.1:{}", debug_port)) {
Ok(listener) => {
// Set listener to non-blocking so it doesn't halt the main loop.
@@ -59,7 +59,7 @@ impl HostDebugger {
eprintln!("[Debugger] Failed to bind to port {}: {}", debug_port, e);
}
}
println!("[Debugger] (Or press D to start execution)");
}
}
@@ -94,9 +94,9 @@ impl HostDebugger {
if self.stream.is_none() {
println!("[Debugger] Connection received!");
stream.set_nonblocking(true).expect("Cannot set non-blocking on stream");
self.stream = Some(stream);
// Immediately send the Handshake message to identify the Runtime and App.
let handshake = DebugResponse::Handshake {
protocol_version: DEVTOOLS_PROTOCOL_VERSION,
@@ -130,13 +130,15 @@ impl HostDebugger {
Ok(n) => {
let data = &buf[..n];
let msg = String::from_utf8_lossy(data);
self.stream = Some(stream);
// Support multiple JSON messages in a single TCP packet.
for line in msg.lines() {
let trimmed = line.trim();
if trimmed.is_empty() { continue; }
if trimmed.is_empty() {
continue;
}
if let Ok(cmd) = serde_json::from_str::<DebugCommand>(trimmed) {
self.handle_command(cmd, firmware, hardware);
}
@@ -154,7 +156,7 @@ impl HostDebugger {
}
}
}
// 3. Push events (logs, telemetry) to the client.
if self.stream.is_some() {
self.stream_events(firmware);
@@ -162,7 +164,12 @@ impl HostDebugger {
}
/// Dispatches a specific DebugCommand to the system components.
fn handle_command(&mut self, cmd: DebugCommand, firmware: &mut Firmware, hardware: &mut Hardware) {
fn handle_command(
&mut self,
cmd: DebugCommand,
firmware: &mut Firmware,
hardware: &mut Hardware,
) {
match cmd {
DebugCommand::Ok | DebugCommand::Start => {
if self.waiting_for_start {
@@ -189,9 +196,8 @@ impl HostDebugger {
}
DebugCommand::GetState => {
// Return detailed VM register and stack state.
let stack_top = firmware.vm.operand_stack.iter()
.rev().take(10).cloned().collect();
let stack_top = firmware.vm.operand_stack.iter().rev().take(10).cloned().collect();
let resp = DebugResponse::GetState {
pc: firmware.vm.pc,
stack_top,
@@ -219,13 +225,13 @@ impl HostDebugger {
let new_events = firmware.os.log_service.get_after(self.last_log_seq);
for event in new_events {
self.last_log_seq = event.seq;
// Map specific internal log tags to protocol events.
if event.tag == 0xDEB1 {
self.send_event(DebugEvent::BreakpointHit {
pc: firmware.vm.pc,
frame_index: firmware.os.logical_frame_index,
});
self.send_event(DebugEvent::BreakpointHit {
pc: firmware.vm.pc,
frame_index: firmware.os.logical_frame_index,
});
}
// Map Certification tags (0xCA01-0xCA03) to 'Cert' protocol events.
@@ -266,27 +272,27 @@ impl HostDebugger {
msg: event.msg.clone(),
});
}
// 2. Send telemetry snapshots at the completion of every frame.
let current_frame = firmware.os.logical_frame_index;
if current_frame > self.last_telemetry_frame {
let tel = &firmware.os.telemetry_last;
self.send_event(DebugEvent::Telemetry {
frame_index: tel.frame_index,
vm_steps: tel.vm_steps,
syscalls: tel.syscalls,
cycles: tel.cycles_used,
cycles_budget: tel.cycles_budget,
host_cpu_time_us: tel.host_cpu_time_us,
violations: tel.violations,
gfx_used_bytes: tel.gfx_used_bytes,
gfx_inflight_bytes: tel.gfx_inflight_bytes,
gfx_slots_occupied: tel.gfx_slots_occupied,
audio_used_bytes: tel.audio_used_bytes,
audio_inflight_bytes: tel.audio_inflight_bytes,
audio_slots_occupied: tel.audio_slots_occupied,
});
self.last_telemetry_frame = current_frame;
let tel = &firmware.os.telemetry_last;
self.send_event(DebugEvent::Telemetry {
frame_index: tel.frame_index,
vm_steps: tel.vm_steps,
syscalls: tel.syscalls,
cycles: tel.cycles_used,
cycles_budget: tel.cycles_budget,
host_cpu_time_us: tel.host_cpu_time_us,
violations: tel.violations,
gfx_used_bytes: tel.gfx_used_bytes,
gfx_inflight_bytes: tel.gfx_inflight_bytes,
gfx_slots_occupied: tel.gfx_slots_occupied,
audio_used_bytes: tel.audio_used_bytes,
audio_inflight_bytes: tel.audio_inflight_bytes,
audio_slots_occupied: tel.audio_slots_occupied,
});
self.last_telemetry_frame = current_frame;
}
}
}
@@ -1,6 +1,6 @@
use prometeu_system::fs::{FsBackend, FsEntry, FsError};
use std::fs;
use std::path::PathBuf;
use prometeu_system::fs::{FsBackend, FsEntry, FsError};
pub struct HostDirBackend {
root: PathBuf,
@@ -90,7 +90,11 @@ mod tests {
fn get_temp_dir(name: &str) -> PathBuf {
let mut path = env::temp_dir();
path.push(format!("prometeu_host_test_{}_{}", name, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
path.push(format!(
"prometeu_host_test_{}_{}",
name,
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
));
fs::create_dir_all(&path).unwrap();
path
}
@@ -99,14 +103,14 @@ mod tests {
fn test_host_dir_backend_mount_and_dirs() {
let root = get_temp_dir("mount");
let mut backend = HostDirBackend::new(root.clone());
backend.mount().unwrap();
assert!(root.join("system").is_dir());
assert!(root.join("apps").is_dir());
assert!(root.join("media").is_dir());
assert!(root.join("user").is_dir());
let _ = fs::remove_dir_all(root);
}
}
@@ -1,8 +1,8 @@
use prometeu_drivers::hardware::Hardware;
use prometeu_hal::InputSignals;
use winit::event::{ElementState, MouseButton, WindowEvent};
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::Window;
use prometeu_drivers::hardware::Hardware;
use prometeu_hal::InputSignals;
pub struct HostInputHandler {
pub signals: InputSignals,
@@ -10,9 +10,7 @@ pub struct HostInputHandler {
impl HostInputHandler {
pub fn new() -> Self {
Self {
signals: InputSignals::default(),
}
Self { signals: InputSignals::default() }
}
pub fn handle_event(&mut self, event: &WindowEvent, window: &Window) {
@@ -35,7 +33,9 @@ impl HostInputHandler {
KeyCode::KeyE => self.signals.r_signal = is_down,
KeyCode::KeyZ => self.signals.start_signal = is_down,
KeyCode::ShiftLeft | KeyCode::ShiftRight => self.signals.select_signal = is_down,
KeyCode::ShiftLeft | KeyCode::ShiftRight => {
self.signals.select_signal = is_down
}
_ => {}
}
@@ -1,11 +1,11 @@
pub mod audio;
pub mod runner;
pub mod fs_backend;
pub mod log_sink;
pub mod debugger;
pub mod stats;
pub mod input;
pub mod cap;
pub mod debugger;
pub mod fs_backend;
pub mod input;
pub mod log_sink;
pub mod runner;
pub mod stats;
pub mod utilities;
use cap::load_cap_config;
@@ -45,17 +45,9 @@ pub fn run() -> Result<(), Box<dyn std::error::Error>> {
let cap_config = cli.cap.as_ref().and_then(|path| load_cap_config(path));
let boot_target = if let Some(path) = cli.debug {
BootTarget::Cartridge {
path,
debug: true,
debug_port: cli.port,
}
BootTarget::Cartridge { path, debug: true, debug_port: cli.port }
} else if let Some(path) = cli.run {
BootTarget::Cartridge {
path,
debug: false,
debug_port: 7777,
}
BootTarget::Cartridge { path, debug: false, debug_port: 7777 }
} else {
BootTarget::Hub
};
@@ -35,7 +35,7 @@ impl HostConsoleSink {
"[{:06}ms][{}][{}][{}] {}",
event.ts_ms, event.frame, level_str, source_str, event.msg
);
self.last_seq = Some(event.seq);
}
}
@@ -1,3 +1,3 @@
fn main() -> Result<(), Box<dyn std::error::Error>> {
prometeu_host_desktop_winit::run()
}
}
@@ -7,7 +7,11 @@ use crate::stats::HostStats;
use crate::utilities::draw_rgb565_to_rgba8;
use pixels::wgpu::PresentMode;
use pixels::{Pixels, PixelsBuilder, SurfaceTexture};
use prometeu_drivers::AudioCommand;
use prometeu_drivers::hardware::Hardware;
use prometeu_firmware::{BootTarget, Firmware};
use prometeu_hal::color::Color;
use prometeu_hal::telemetry::CertificationConfig;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
@@ -15,14 +19,10 @@ use winit::event::{ElementState, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow};
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::{Window, WindowAttributes, WindowId};
use prometeu_hal::telemetry::CertificationConfig;
use prometeu_drivers::hardware::Hardware;
use prometeu_drivers::AudioCommand;
use prometeu_hal::color::Color;
/// The Desktop implementation of the PROMETEU Runtime.
///
/// This struct acts as the physical "chassis" of the virtual console. It is
///
/// This struct acts as the physical "chassis" of the virtual console. It is
/// responsible for:
/// - Creating and managing the OS window (via `winit`).
/// - Initializing the GPU-accelerated framebuffer (via `pixels`).
@@ -130,8 +130,18 @@ impl HostRunner {
let color_warn = Color::RED;
self.hardware.gfx.fill_rect(5, 5, 175, 100, color_bg);
self.hardware.gfx.draw_text(10, 10, &format!("FPS: {:.1}", self.stats.current_fps), color_text);
self.hardware.gfx.draw_text(10, 18, &format!("HOST: {:.2}MS", tel.host_cpu_time_us as f64 / 1000.0), color_text);
self.hardware.gfx.draw_text(
10,
10,
&format!("FPS: {:.1}", self.stats.current_fps),
color_text,
);
self.hardware.gfx.draw_text(
10,
18,
&format!("HOST: {:.2}MS", tel.host_cpu_time_us as f64 / 1000.0),
color_text,
);
self.hardware.gfx.draw_text(10, 26, &format!("STEPS: {}", tel.vm_steps), color_text);
self.hardware.gfx.draw_text(10, 34, &format!("SYSC: {}", tel.syscalls), color_text);
@@ -140,25 +150,60 @@ impl HostRunner {
} else {
0.0
};
self.hardware.gfx.draw_text(10, 42, &format!("CYC: {}/{} ({:.1}%)", tel.cycles_used, tel.cycles_budget, cycles_pct), color_text);
self.hardware.gfx.draw_text(
10,
42,
&format!("CYC: {}/{} ({:.1}%)", tel.cycles_used, tel.cycles_budget, cycles_pct),
color_text,
);
self.hardware.gfx.draw_text(10, 50, &format!("GFX: {}K/16M ({}S)", tel.gfx_used_bytes / 1024, tel.gfx_slots_occupied), color_text);
self.hardware.gfx.draw_text(
10,
50,
&format!("GFX: {}K/16M ({}S)", tel.gfx_used_bytes / 1024, tel.gfx_slots_occupied),
color_text,
);
if tel.gfx_inflight_bytes > 0 {
self.hardware.gfx.draw_text(10, 58, &format!("LOAD GFX: {}KB", tel.gfx_inflight_bytes / 1024), color_warn);
self.hardware.gfx.draw_text(
10,
58,
&format!("LOAD GFX: {}KB", tel.gfx_inflight_bytes / 1024),
color_warn,
);
}
self.hardware.gfx.draw_text(10, 66, &format!("AUD: {}K/32M ({}S)", tel.audio_used_bytes / 1024, tel.audio_slots_occupied), color_text);
self.hardware.gfx.draw_text(
10,
66,
&format!("AUD: {}K/32M ({}S)", tel.audio_used_bytes / 1024, tel.audio_slots_occupied),
color_text,
);
if tel.audio_inflight_bytes > 0 {
self.hardware.gfx.draw_text(10, 74, &format!("LOAD AUD: {}KB", tel.audio_inflight_bytes / 1024), color_warn);
self.hardware.gfx.draw_text(
10,
74,
&format!("LOAD AUD: {}KB", tel.audio_inflight_bytes / 1024),
color_warn,
);
}
let cert_color = if tel.violations > 0 { color_warn } else { color_text };
self.hardware.gfx.draw_text(10, 82, &format!("CERT LAST: {}", tel.violations), cert_color);
if tel.violations > 0 {
if let Some(event) = self.firmware.os.log_service.get_recent(10).into_iter().rev().find(|e| e.tag >= 0xCA01 && e.tag <= 0xCA03) {
if let Some(event) = self
.firmware
.os
.log_service
.get_recent(10)
.into_iter()
.rev()
.find(|e| e.tag >= 0xCA01 && e.tag <= 0xCA03)
{
let mut msg = event.msg.clone();
if msg.len() > 30 { msg.truncate(30); }
if msg.len() > 30 {
msg.truncate(30);
}
self.hardware.gfx.draw_text(10, 90, &msg, color_warn);
}
}
@@ -183,11 +228,12 @@ impl ApplicationHandler for HostRunner {
let size = window.inner_size();
let surface_texture = SurfaceTexture::new(size.width, size.height, window);
let mut pixels = PixelsBuilder::new(Hardware::W as u32, Hardware::H as u32, surface_texture)
.present_mode(PresentMode::Fifo) // activate vsync
.build()
.expect("failed to create Pixels");
let mut pixels =
PixelsBuilder::new(Hardware::W as u32, Hardware::H as u32, surface_texture)
.present_mode(PresentMode::Fifo) // activate vsync
.build()
.expect("failed to create Pixels");
pixels.frame_mut().fill(0);
self.pixels = Some(pixels);
@@ -197,7 +243,6 @@ impl ApplicationHandler for HostRunner {
event_loop.set_control_flow(ControlFlow::Poll);
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
self.input.handle_event(&event, self.window());
@@ -232,7 +277,6 @@ impl ApplicationHandler for HostRunner {
}
}
WindowEvent::KeyboardInput { event, .. } => {
if let PhysicalKey::Code(code) = event.physical_key {
let is_down = event.state == ElementState::Pressed;
@@ -270,13 +314,13 @@ impl ApplicationHandler for HostRunner {
}
// 3. Timing Management (The heart of determinism).
// We measure the elapsed time since the last iteration and add it to an
// accumulator. We then execute exactly as many 60Hz slices as the
// We measure the elapsed time since the last iteration and add it to an
// accumulator. We then execute exactly as many 60Hz slices as the
// accumulator allows.
let now = Instant::now();
let mut frame_delta = now.duration_since(self.last_frame_time);
// Safety cap: if the OS freezes or we fall behind too much, we don't try
// Safety cap: if the OS freezes or we fall behind too much, we don't try
// to catch up indefinitely (avoiding the "death spiral").
if frame_delta > Duration::from_millis(100) {
frame_delta = Duration::from_millis(100);
@@ -293,16 +337,13 @@ impl ApplicationHandler for HostRunner {
}
// Sync pause state with audio.
// We do this AFTER firmware.tick to avoid MasterPause/Resume commands
// We do this AFTER firmware.tick to avoid MasterPause/Resume commands
// being cleared by the OS if a new logical frame starts in this tick.
let is_paused = self.firmware.os.paused || self.debugger.waiting_for_start;
if is_paused != self.last_paused_state {
self.last_paused_state = is_paused;
let cmd = if is_paused {
AudioCommand::MasterPause
} else {
AudioCommand::MasterResume
};
let cmd =
if is_paused { AudioCommand::MasterPause } else { AudioCommand::MasterResume };
self.hardware.audio.commands.push(cmd);
}
@@ -331,7 +372,7 @@ impl ApplicationHandler for HostRunner {
// 5. Rendering the Telemetry Overlay (if enabled).
if self.overlay_enabled {
// We temporarily swap buffers to draw over the current image.
self.hardware.gfx.present();
self.hardware.gfx.present();
self.display_dbg_overlay();
self.hardware.gfx.present();
}
@@ -345,9 +386,9 @@ impl ApplicationHandler for HostRunner {
mod tests {
use super::*;
use prometeu_firmware::BootTarget;
use prometeu_hal::debugger_protocol::DEVTOOLS_PROTOCOL_VERSION;
use std::io::{Read, Write};
use std::net::TcpStream;
use prometeu_hal::debugger_protocol::DEVTOOLS_PROTOCOL_VERSION;
#[test]
fn test_debug_port_opens() {
@@ -364,10 +405,11 @@ mod tests {
// Check if we can connect
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
let mut stream =
TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
// Short sleep to ensure the OS processes
std::thread::sleep(std::time::Duration::from_millis(100));
// Simulates the loop to accept the connection
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some(), "Stream should have been kept open");
@@ -375,24 +417,36 @@ mod tests {
// Handshake Check
let mut buf = [0u8; 2048];
let n = stream.read(&mut buf).expect("Should read handshake");
let resp: serde_json::Value = serde_json::from_slice(&buf[..n]).expect("Handshake should be valid JSON");
let resp: serde_json::Value =
serde_json::from_slice(&buf[..n]).expect("Handshake should be valid JSON");
assert_eq!(resp["type"], "handshake");
assert_eq!(resp["protocol_version"], DEVTOOLS_PROTOCOL_VERSION);
// Send start via JSON
stream.write_all(b"{\"type\":\"start\"}\n").expect("Connection should be open for writing");
stream
.write_all(b"{\"type\":\"start\"}\n")
.expect("Connection should be open for writing");
std::thread::sleep(std::time::Duration::from_millis(50));
// Process the received command
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(!runner.debugger.waiting_for_start, "Execution should have started after start command");
assert!(runner.debugger.listener.is_some(), "Listener should remain open for reconnections");
assert!(
!runner.debugger.waiting_for_start,
"Execution should have started after start command"
);
assert!(
runner.debugger.listener.is_some(),
"Listener should remain open for reconnections"
);
}
// Now that the stream is out of the test scope, the runner should detect closure on next check
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_none(), "Stream should have been closed after client disconnected");
assert!(
runner.debugger.stream.is_none(),
"Stream should have been closed after client disconnected"
);
}
#[test]
@@ -407,7 +461,8 @@ mod tests {
// 1. Connect and start
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 1");
let mut stream =
TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 1");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some());
@@ -427,10 +482,13 @@ mod tests {
// 3. Try to reconnect - SHOULD FAIL currently, but we want it to WORK
let stream2 = TcpStream::connect(format!("127.0.0.1:{}", port));
assert!(stream2.is_ok(), "Should accept new connection even after start");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some(), "Stream should have been accepted on reconnection");
assert!(
runner.debugger.stream.is_some(),
"Stream should have been accepted on reconnection"
);
}
#[test]
@@ -444,22 +502,27 @@ mod tests {
});
// 1. First connection
let mut _stream1 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 1");
let mut _stream1 =
TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 1");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some());
// 2. Second connection
let mut stream2 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 2 (OS accepts)");
let mut stream2 = TcpStream::connect(format!("127.0.0.1:{}", port))
.expect("Should connect 2 (OS accepts)");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware); // Should accept and close stream2
// Check if stream2 was closed by the server
let mut buf = [0u8; 10];
stream2.set_read_timeout(Some(std::time::Duration::from_millis(100))).unwrap();
let res = stream2.read(&mut buf);
assert!(matches!(res, Ok(0)) || res.is_err(), "Second connection should be closed by server");
assert!(
matches!(res, Ok(0)) || res.is_err(),
"Second connection should be closed by server"
);
assert!(runner.debugger.stream.is_some(), "First connection should continue active");
}
@@ -479,7 +542,7 @@ mod tests {
use std::io::BufRead;
let mut reader = std::io::BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).expect("Should read handshake");
assert!(line.contains("handshake"));
@@ -487,15 +550,17 @@ mod tests {
// Send getState
reader.get_mut().write_all(b"{\"type\":\"getState\"}\n").expect("Should write getState");
std::thread::sleep(std::time::Duration::from_millis(100));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
// Check if response received (may have events/logs before)
loop {
line.clear();
reader.read_line(&mut line).expect("Should read line");
if line.is_empty() { break; }
if line.is_empty() {
break;
}
if let Ok(resp) = serde_json::from_str::<serde_json::Value>(&line) {
if resp["type"] == "getState" {
return;
@@ -517,10 +582,11 @@ mod tests {
// 1. Connect and pause
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
let mut stream =
TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
stream.write_all(b"{\"type\":\"pause\"}\n").expect("Should write pause");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
@@ -530,7 +596,7 @@ mod tests {
// 2. Disconnect (stream goes out of scope)
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
// 3. Check if unpaused
assert!(!runner.firmware.os.paused, "VM should have unpaused after disconnect");
assert!(!runner.debugger.waiting_for_start, "VM should have left waiting_for_start state");
@@ -1,7 +1,7 @@
use prometeu_drivers::hardware::Hardware;
use prometeu_firmware::Firmware;
use std::time::{Duration, Instant};
use winit::window::Window;
use prometeu_drivers::hardware::Hardware;
pub struct HostStats {
pub last_stats_update: Instant,
@@ -31,15 +31,22 @@ impl HostStats {
self.audio_load_samples += 1;
}
pub fn update(&mut self, now: Instant, window: Option<&Window>, _hardware: &Hardware, firmware: &Firmware) {
pub fn update(
&mut self,
now: Instant,
window: Option<&Window>,
_hardware: &Hardware,
firmware: &Firmware,
) {
let stats_elapsed = now.duration_since(self.last_stats_update);
if stats_elapsed >= Duration::from_secs(1) {
self.current_fps = self.frames_since_last_update as f64 / stats_elapsed.as_secs_f64();
if let Some(window) = window {
// Fixed comparison always against 60Hz, keep even when doing CPU stress tests
let frame_budget_us = 16666.0;
let cpu_load_core = (firmware.os.last_frame_cpu_time_us as f64 / frame_budget_us) * 100.0;
let cpu_load_core =
(firmware.os.last_frame_cpu_time_us as f64 / frame_budget_us) * 100.0;
let cpu_load_audio = if self.audio_load_samples > 0 {
(self.audio_load_accum_us as f64 / stats_elapsed.as_micros() as f64) * 100.0
@@ -49,7 +56,12 @@ impl HostStats {
let title = format!(
"PROMETEU | GFX: {:.1} KB | FPS: {:.1} | Load: {:.1}% (C) + {:.1}% (A) | Frame: tick {} logical {}",
0, self.current_fps, cpu_load_core, cpu_load_audio, firmware.os.tick_index, firmware.os.logical_frame_index
0,
self.current_fps,
cpu_load_core,
cpu_load_audio,
firmware.os.tick_index,
firmware.os.logical_frame_index
);
window.set_title(&title);
}