Skip to main content

autocore_std/
lib.rs

1//! # AutoCore Standard Library
2//!
3//! The standard library for writing AutoCore control programs. This crate provides
4//! everything you need to build real-time control applications that integrate with
5//! the AutoCore server ecosystem.
6//!
7//! ## Overview
8//!
9//! AutoCore control programs run as separate processes that communicate with the
10//! autocore-server via shared memory and IPC. This library handles all the low-level
11//! details, allowing you to focus on your control logic.
12//!
13//! ```text
14//! ┌─────────────────────────┐     ┌─────────────────────────┐
15//! │   autocore-server       │     │   Your Control Program  │
16//! │                         │     │                         │
17//! │  ┌─────────────────┐    │     │  ┌─────────────────┐    │
18//! │  │ Shared Memory   │◄───┼─────┼──│ ControlRunner   │    │
19//! │  │ (GlobalMemory)  │    │     │  │                 │    │
20//! │  └─────────────────┘    │     │  │ ┌─────────────┐ │    │
21//! │                         │     │  │ │ Your Logic  │ │    │
22//! │  ┌─────────────────┐    │     │  │ └─────────────┘ │    │
23//! │  │ Tick Signal     │────┼─────┼──│                 │    │
24//! │  └─────────────────┘    │     │  └─────────────────┘    │
25//! └─────────────────────────┘     └─────────────────────────┘
26//! ```
27//!
28//! ## Quick Start
29//!
30//! 1. Create a new control project using `acctl`:
31//!    ```bash
32//!    acctl clone <server-ip> <project-name>
33//!    ```
34//!
35//! 2. Implement the [`ControlProgram`] trait:
36//!    ```ignore
37//!    use autocore_std::{ControlProgram, TickContext};
38//!    use autocore_std::fb::RTrig;
39//!
40//!    // GlobalMemory is generated from your project.json
41//!    mod gm;
42//!    use gm::GlobalMemory;
43//!
44//!    pub struct MyProgram {
45//!        start_button: RTrig,
46//!    }
47//!
48//!    impl MyProgram {
49//!        pub fn new() -> Self {
50//!            Self {
51//!                start_button: RTrig::new(),
52//!            }
53//!        }
54//!    }
55//!
56//!    impl ControlProgram for MyProgram {
57//!        type Memory = GlobalMemory;
58//!
59//!        fn process_tick(&mut self, ctx: &mut TickContext<Self::Memory>) {
60//!            // Detect rising edge on start button
61//!            if self.start_button.call(ctx.gm.inputs.start_button) {
62//!                ctx.gm.outputs.motor_running = true;
63//!                autocore_std::log::info!("Motor started!");
64//!            }
65//!        }
66//!    }
67//!    ```
68//!
69//! 3. Use the [`autocore_main!`] macro for the entry point:
70//!    ```ignore
71//!    autocore_std::autocore_main!(MyProgram, "my_project_shm", "tick");
72//!    ```
73//!
74//! ## Function Blocks (IEC 61131-3 Inspired)
75//!
76//! This library includes standard function blocks commonly used in PLC programming:
77//!
78//! - [`fb::RTrig`] - Rising edge detector (false→true transition)
79//! - [`fb::FTrig`] - Falling edge detector (true→false transition)
80//! - [`fb::Ton`] - Timer On Delay (output after delay)
81//! - [`fb::BitResetOnDelay`] - Resets a boolean after it has been true for a duration
82//! - [`fb::SimpleTimer`] - Simple one-shot timer (NOT IEC 61131-3, for imperative use)
83//! - [`fb::StateMachine`] - State machine helper with automatic timer management
84//! - [`fb::RunningAverage`] - Accumulates values and computes their arithmetic mean
85//! - [`fb::Beeper`] - Audible beeper controller with configurable beep sequences
86//! - [`fb::Heartbeat`] - Monitors a remote heartbeat counter for connection loss
87//!
88//! ### Example: Edge Detection
89//!
90//! ```
91//! use autocore_std::fb::RTrig;
92//!
93//! let mut trigger = RTrig::new();
94//!
95//! // First call with false - no edge
96//! assert_eq!(trigger.call(false), false);
97//!
98//! // Rising edge detected!
99//! assert_eq!(trigger.call(true), true);
100//!
101//! // Still true, but no edge (already high)
102//! assert_eq!(trigger.call(true), false);
103//!
104//! // Back to false
105//! assert_eq!(trigger.call(false), false);
106//!
107//! // Another rising edge
108//! assert_eq!(trigger.call(true), true);
109//! ```
110//!
111//! ### Example: Timer
112//!
113//! ```
114//! use autocore_std::fb::Ton;
115//! use std::time::Duration;
116//!
117//! let mut timer = Ton::new();
118//! let delay = Duration::from_millis(100);
119//!
120//! // Timer not enabled - output is false
121//! assert_eq!(timer.call(false, delay), false);
122//!
123//! // Enable timer - starts counting
124//! assert_eq!(timer.call(true, delay), false);
125//!
126//! // Still counting...
127//! std::thread::sleep(Duration::from_millis(50));
128//! assert_eq!(timer.call(true, delay), false);
129//! assert!(timer.et < delay); // Elapsed time < preset
130//!
131//! // After delay elapsed
132//! std::thread::sleep(Duration::from_millis(60));
133//! assert_eq!(timer.call(true, delay), true); // Output is now true!
134//! ```
135//!
136//! ## Logging
137//!
138//! Control programs can send log messages to the autocore-server for display in the
139//! web console. Logging is handled automatically when using [`ControlRunner`].
140//!
141//! ```ignore
142//! use autocore_std::log;
143//!
144//! log::trace!("Detailed trace message");
145//! log::debug!("Debug information");
146//! log::info!("Normal operation message");
147//! log::warn!("Warning condition detected");
148//! log::error!("Error occurred!");
149//! ```
150//!
151//! See the [`logger`] module for advanced configuration.
152//!
153//! ## Memory Synchronization
154//!
155//! The [`ControlRunner`] handles all shared memory synchronization automatically:
156//!
157//! 1. **Wait for tick** - Blocks until the server signals a new cycle
158//! 2. **Read inputs** - Copies shared memory to local buffer (atomic snapshot)
159//! 3. **Execute logic** - Your `process_tick` runs on the local buffer
160//! 4. **Write outputs** - Copies local buffer back to shared memory
161//!
162//! This ensures your control logic always sees a consistent view of the data,
163//! even when other processes are modifying shared memory.
164
165#![warn(missing_docs)]
166#![warn(rustdoc::missing_crate_level_docs)]
167#![doc(html_root_url = "https://docs.rs/autocore-std/3.3.0")]
168
169use anyhow::{anyhow, Result};
170use futures_util::{SinkExt, StreamExt};
171use log::LevelFilter;
172use mechutil::ipc::{CommandMessage, MessageType};
173use raw_sync::events::{Event, EventInit, EventState};
174use raw_sync::Timeout;
175use shared_memory::ShmemConf;
176use std::collections::HashMap;
177use std::sync::atomic::{fence, Ordering, AtomicBool};
178use std::sync::Arc;
179use std::time::Duration;
180use tokio_tungstenite::{connect_async, tungstenite::Message};
181
182/// UDP logger for sending log messages to autocore-server.
183///
184/// This module provides a non-blocking logger implementation that sends log messages
185/// via UDP to the autocore-server. Messages are batched and sent asynchronously to
186/// avoid impacting the control loop timing.
187///
188/// # Example
189///
190/// ```ignore
191/// use autocore_std::logger;
192/// use log::LevelFilter;
193///
194/// // Initialize the logger (done automatically by ControlRunner)
195/// logger::init_udp_logger("127.0.0.1", 39101, LevelFilter::Info, "control")?;
196///
197/// // Now you can use the log macros
198/// log::info!("System initialized");
199/// ```
200pub mod logger;
201
202// Re-export log crate for convenience - control programs can use autocore_std::log::info!() etc.
203pub use log;
204
205// Re-export `paste` so the exported view macros (e.g. `wls15_run_mode_view!`,
206// `el3356_view!`) can reference it via `$crate::paste` and work in any consumer
207// crate without that crate having to depend on `paste` itself.
208#[doc(hidden)]
209pub use paste;
210
211/// Function blocks for control programs (IEC 61131-3 inspired).
212pub mod fb;
213
214/// Interface protocols for communication between control programs and external sources.
215pub mod iface;
216
217/// Client for sending IPC commands to external modules via WebSocket.
218pub mod command_client;
219pub use command_client::CommandClient;
220
221/// Test Information System (TIS) producer helpers — conveniences over the
222/// `tis.*` IPC commands, e.g. attaching chart region bands to a cycle.
223pub mod tis;
224
225/// Subscription helper for `ams.asset_updated.<location>` broadcasts.
226/// Control programs use this to drive EL3356 SDO writes (and similar)
227/// when a load cell asset is registered, recalibrated, or retired.
228pub mod asset_watch;
229pub use asset_watch::{AssetUpdate, AssetWatch, AssetWatchStatus, AssetWatchTrigger};
230
231/// EtherCAT utilities (SDO client, etc.).
232pub mod ethercat;
233
234/// CiA 402 motion control: axis abstraction, traits, and types.
235pub mod motion;
236
237/// Shared memory utilities for external modules.
238pub mod shm;
239
240/// Lightweight process diagnostics (FD count, RSS).
241pub mod diagnostics;
242
243/// Banner Engineering device helpers (WLS15 IO-Link light strip, etc.).
244pub mod banner;
245
246/// Fixed-length string type for shared memory variables.
247pub mod fixed_string;
248pub use fixed_string::FixedString;
249
250/// Zero-phase Butterworth low-pass filtering for captured signal traces.
251pub mod butterworth;
252
253// ============================================================================
254// Core Framework
255// ============================================================================
256
257/// Marker trait for generated GlobalMemory structs.
258///
259/// This trait is implemented by the auto-generated `GlobalMemory` struct
260/// that represents the shared memory layout. It serves as a marker for
261/// type safety in the control framework.
262///
263/// You don't need to implement this trait yourself - it's automatically
264/// implemented by the code generator.
265pub trait AutoCoreMemory {}
266
267/// Trait for detecting changes in memory structures.
268pub trait ChangeTracker {
269    /// Compare self with a previous state and return a list of changed fields.
270    /// Returns a vector of (field_name, new_value).
271    fn get_changes(&self, prev: &Self) -> Vec<(&'static str, serde_json::Value)>;
272
273    /// Unpack bit-mapped variables from their source words.
274    /// Called automatically after reading shared memory, before `process_tick`.
275    /// Auto-generated by codegen when bit-mapped variables exist; default is no-op.
276    fn unpack_bits(&mut self) {}
277
278    /// Pack bit-mapped variables back into their source words.
279    /// Called automatically after `process_tick`, before writing shared memory.
280    /// Only packs sources where at least one mapped bool changed since `pre_tick`.
281    /// Auto-generated by codegen when bit-mapped variables exist; default is no-op.
282    fn pack_bits(&mut self, _pre_tick: &Self) {}
283}
284
285/// A neutral, typed value for a single GlobalMemory field.
286///
287/// This is the lingua franca for *generic* GM field access ([`GmAccess`]): it
288/// lets tooling read/write GM fields by name or id without knowing the concrete
289/// generated struct. Values are widened to the broadest type per category (all
290/// integer widths as `i64`, all floats as `f64`).
291#[derive(Clone, Debug, PartialEq)]
292pub enum FieldValue {
293    /// A boolean field.
294    Bool(bool),
295    /// Any integer field, widened to `i64`.
296    Int(i64),
297    /// Any float field, widened to `f64`.
298    Float(f64),
299    /// A fixed-string field, as an owned `String`.
300    Text(String),
301}
302
303impl FieldValue {
304    /// Interpret as a boolean (non-zero integers are `true`).
305    pub fn as_bool(&self) -> Option<bool> {
306        match self {
307            FieldValue::Bool(b) => Some(*b),
308            FieldValue::Int(i) => Some(*i != 0),
309            _ => None,
310        }
311    }
312    /// Interpret as an `i64` (floats truncate, bools map to 0/1).
313    pub fn as_i64(&self) -> Option<i64> {
314        match self {
315            FieldValue::Int(i) => Some(*i),
316            FieldValue::Float(f) => Some(*f as i64),
317            FieldValue::Bool(b) => Some(*b as i64),
318            _ => None,
319        }
320    }
321    /// Interpret as an `f64` (ints/bools promote).
322    pub fn as_f64(&self) -> Option<f64> {
323        match self {
324            FieldValue::Float(f) => Some(*f),
325            FieldValue::Int(i) => Some(*i as f64),
326            FieldValue::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
327            _ => None,
328        }
329    }
330    /// Borrow as text, if this is a `Text` value.
331    pub fn as_str(&self) -> Option<&str> {
332        match self {
333            FieldValue::Text(s) => Some(s.as_str()),
334            _ => None,
335        }
336    }
337}
338
339/// Generic, module-agnostic access to `GlobalMemory` fields by name or id.
340///
341/// This is the inverse of the [`ChangeTracker`] field table, and like it, it is
342/// **auto-generated by the code generator** — you don't implement it by hand.
343/// It exists so that *any* consumer — the IDE, debuggers, name-keyed IPC, the
344/// autocore-seq sequencer — can read and write GM fields generically, without
345/// the framework knowing about those consumers. `field_id` is resolved once
346/// (off the hot path); `read_field` / `write_field` are O(1).
347pub trait GmAccess {
348    /// Resolve a field name to a stable id. `None` if there is no such field.
349    fn field_id(name: &str) -> Option<u32>
350    where
351        Self: Sized;
352    /// Read a field by id. `None` if the id is out of range.
353    fn read_field(&self, id: u32) -> Option<FieldValue>;
354    /// Write a field by id. Returns `false` if the id is unknown or the value
355    /// is type-incompatible (e.g. text into a numeric field).
356    fn write_field(&mut self, id: u32, value: &FieldValue) -> bool;
357}
358
359/// Per-tick context passed to the control program by the framework.
360///
361/// `TickContext` bundles all per-cycle data into a single struct so that the
362/// [`ControlProgram::process_tick`] signature stays stable as new fields are
363/// added in the future (e.g., delta time, diagnostics).
364///
365/// The framework constructs a fresh `TickContext` each cycle, calls
366/// [`CommandClient::poll`] before handing it to the program, and writes
367/// the memory back to shared memory after `process_tick` returns.
368pub struct TickContext<'a, M> {
369    /// Mutable reference to the local shared memory copy.
370    pub gm: &'a mut M,
371    /// IPC command client for communicating with external modules.
372    pub client: &'a mut CommandClient,
373    /// Current cycle number (starts at 1, increments each tick).
374    pub cycle: u64,
375}
376
377/// The trait that defines a control program's logic.
378///
379/// Implement this trait to create your control program. The associated `Memory`
380/// type should be the generated `GlobalMemory` struct from your project.
381///
382/// # Memory Type Requirements
383///
384/// The `Memory` type must implement `Copy` to allow efficient synchronization
385/// between shared memory and local buffers. This is automatically satisfied
386/// by the generated `GlobalMemory` struct.
387///
388/// # Lifecycle
389///
390/// 1. `initialize` is called once at startup
391/// 2. `process_tick` is called repeatedly in the control loop with a
392///    [`TickContext`] that provides shared memory, the IPC client, and the
393///    current cycle number.
394///
395/// # Example
396///
397/// ```ignore
398/// use autocore_std::{ControlProgram, TickContext};
399///
400/// mod gm;
401/// use gm::GlobalMemory;
402///
403/// pub struct MyController {
404///     cycle_counter: u64,
405/// }
406///
407/// impl MyController {
408///     pub fn new() -> Self {
409///         Self { cycle_counter: 0 }
410///     }
411/// }
412///
413/// impl ControlProgram for MyController {
414///     type Memory = GlobalMemory;
415///
416///     fn initialize(&mut self, mem: &mut GlobalMemory) {
417///         // Set initial output states
418///         mem.outputs.ready = true;
419///         log::info!("Controller initialized");
420///     }
421///
422///     fn process_tick(&mut self, ctx: &mut TickContext<Self::Memory>) {
423///         self.cycle_counter = ctx.cycle;
424///
425///         // Your control logic here
426///         if ctx.gm.inputs.start && !ctx.gm.inputs.estop {
427///             ctx.gm.outputs.running = true;
428///         }
429///     }
430/// }
431/// ```
432/// Compatibility constants for the GM segment a control program was generated
433/// against. Code-generated `gm.rs` implements this for `GlobalMemory`, so every
434/// control program carries the fingerprint of the exact layout it was built
435/// for. The runner checks these against the server's SHM header before reading
436/// a single byte of the variable region (see [`ControlRunner::run`]).
437pub trait GmCompat {
438    /// Fingerprint of the GM layout (must equal the server's SHM header hash).
439    const LAYOUT_HASH: u64;
440    /// Total GM segment size in bytes, including the header.
441    const TOTAL_SIZE: usize;
442}
443
444pub trait ControlProgram {
445    /// The shared memory structure type (usually the generated `GlobalMemory`).
446    ///
447    /// Must implement `Copy` to allow efficient memory synchronization, and
448    /// `GmCompat` so the runner can verify it matches the live segment.
449    type Memory: Copy + ChangeTracker + GmCompat;
450
451    /// Called once when the control program starts.
452    ///
453    /// Use this to initialize output states, reset counters, or perform
454    /// any one-time setup. The default implementation does nothing.
455    ///
456    /// # Arguments
457    ///
458    /// * `mem` - Mutable reference to the shared memory. Changes are written
459    ///           back to shared memory after this method returns.
460    fn initialize(&mut self, _mem: &mut Self::Memory) {}
461
462    /// The main control loop - called once per scan cycle.
463    ///
464    /// This is where your control logic lives. Read inputs from `ctx.gm`,
465    /// perform calculations, and write outputs back to `ctx.gm`. Use
466    /// `ctx.client` for IPC commands and `ctx.cycle` for the current cycle
467    /// number.
468    ///
469    /// The framework calls [`CommandClient::poll`] before each invocation,
470    /// so incoming responses are already buffered when your code runs.
471    ///
472    /// # Arguments
473    ///
474    /// * `ctx` - A [`TickContext`] containing the local shared memory copy,
475    ///           the IPC command client, and the current cycle number.
476    ///
477    /// # Timing
478    ///
479    /// This method should complete within the scan cycle time. Long-running
480    /// operations will cause cycle overruns.
481    fn process_tick(&mut self, ctx: &mut TickContext<Self::Memory>);
482}
483
484/// Configuration for the [`ControlRunner`].
485///
486/// Specifies connection parameters, shared memory names, and logging settings.
487/// Use [`Default::default()`] for typical configurations.
488///
489/// # Example
490///
491/// ```
492/// use autocore_std::RunnerConfig;
493/// use log::LevelFilter;
494///
495/// let config = RunnerConfig {
496///     server_host: "192.168.1.100".to_string(),
497///     module_name: "my_controller".to_string(),
498///     shm_name: "my_project_shm".to_string(),
499///     tick_signal_name: "tick".to_string(),
500///     busy_signal_name: Some("busy".to_string()),
501///     log_level: LevelFilter::Debug,
502///     ..Default::default()
503/// };
504/// ```
505#[derive(Debug, Clone)]
506pub struct RunnerConfig {
507    /// Server host address (default: "127.0.0.1")
508    pub server_host: String,
509    /// WebSocket port for commands (default: 11969)
510    pub ws_port: u16,
511    /// Module name for identification (default: "control")
512    pub module_name: String,
513    /// Shared memory segment name (must match server configuration)
514    pub shm_name: String,
515    /// Name of the tick signal in shared memory (triggers each scan cycle)
516    pub tick_signal_name: String,
517    /// Optional name of the busy signal (set when cycle completes)
518    pub busy_signal_name: Option<String>,
519    /// Minimum log level to send to the server (default: Info)
520    pub log_level: LevelFilter,
521    /// UDP port for sending logs to the server (default: 39101)
522    pub log_udp_port: u16,
523}
524
525/// Default WebSocket port for autocore-server
526pub const DEFAULT_WS_PORT: u16 = 11969;
527
528impl Default for RunnerConfig {
529    fn default() -> Self {
530        Self {
531            server_host: "127.0.0.1".to_string(),
532            ws_port: DEFAULT_WS_PORT,
533            module_name: "control".to_string(),
534            shm_name: "autocore_cyclic".to_string(),
535            tick_signal_name: "tick".to_string(),
536            busy_signal_name: None,
537            log_level: LevelFilter::Info,
538            log_udp_port: logger::DEFAULT_LOG_UDP_PORT,
539        }
540    }
541}
542
543
544/// The main execution engine for control programs.
545///
546/// `ControlRunner` handles all the infrastructure required to run a control program:
547///
548/// - Reading memory layout from the server's layout file
549/// - Opening and mapping shared memory
550/// - Setting up synchronization signals
551/// - Running the real-time control loop
552/// - Sending log messages to the server
553///
554/// # Usage
555///
556/// ```ignore
557/// use autocore_std::{ControlRunner, RunnerConfig};
558///
559/// let config = RunnerConfig {
560///     shm_name: "my_project_shm".to_string(),
561///     tick_signal_name: "tick".to_string(),
562///     ..Default::default()
563/// };
564///
565/// ControlRunner::new(MyProgram::new())
566///     .config(config)
567///     .run()?;  // Blocks forever
568/// ```
569///
570/// # Control Loop
571///
572/// The runner executes a synchronous control loop:
573///
574/// 1. **Wait** - Blocks until the tick signal is set by the server
575/// 2. **Read** - Copies shared memory to a local buffer (acquire barrier)
576/// 3. **Execute** - Calls your `process_tick` method
577/// 4. **Write** - Copies local buffer back to shared memory (release barrier)
578/// 5. **Signal** - Sets the busy signal (if configured) to indicate completion
579///
580/// This ensures your code always sees a consistent snapshot of the data
581/// and that your writes are atomically visible to other processes.
582pub struct ControlRunner<P: ControlProgram> {
583    config: RunnerConfig,
584    program: P,
585}
586
587impl<P: ControlProgram> ControlRunner<P> {
588    /// Creates a new runner for the given control program.
589    ///
590    /// Uses default configuration. Call [`.config()`](Self::config) to customize.
591    ///
592    /// # Arguments
593    ///
594    /// * `program` - Your control program instance
595    ///
596    /// # Example
597    ///
598    /// ```ignore
599    /// let runner = ControlRunner::new(MyProgram::new());
600    /// ```
601    pub fn new(program: P) -> Self {
602        Self {
603            config: RunnerConfig::default(),
604            program,
605        }
606    }
607
608    /// Sets the configuration for this runner.
609    ///
610    /// # Arguments
611    ///
612    /// * `config` - The configuration to use
613    ///
614    /// # Example
615    ///
616    /// ```ignore
617    /// ControlRunner::new(MyProgram::new())
618    ///     .config(RunnerConfig {
619    ///         shm_name: "custom_shm".to_string(),
620    ///         ..Default::default()
621    ///     })
622    ///     .run()?;
623    /// ```
624    pub fn config(mut self, config: RunnerConfig) -> Self {
625        self.config = config;
626        self
627    }
628
629    /// Starts the control loop.
630    ///
631    /// This method blocks indefinitely, running the control loop until
632    /// an error occurs or the process is terminated.
633    ///
634    /// # Returns
635    ///
636    /// Returns `Ok(())` only if the loop exits cleanly (which typically
637    /// doesn't happen). Returns an error if:
638    ///
639    /// - IPC connection fails
640    /// - Shared memory cannot be opened
641    /// - Signal offsets cannot be found
642    /// - A critical error occurs during execution
643    ///
644    /// # Example
645    ///
646    /// ```ignore
647    /// fn main() -> anyhow::Result<()> {
648    ///     ControlRunner::new(MyProgram::new())
649    ///         .config(config)
650    ///         .run()
651    /// }
652    /// ```
653    pub fn run(mut self) -> Result<()> {
654        // Fast path: report this binary's build-time compatibility info as JSON
655        // and exit. `acctl push control` uses this to compare the freshly built
656        // control program against the running server without attaching.
657        if std::env::args().any(|a| a == "--print-compat") {
658            println!("{}", serde_json::json!({
659                "format_version": mechutil::shm_header::SHM_FORMAT_VERSION,
660                "shm_abi_version": mechutil::SHM_ABI_VERSION,
661                "mechutil_version": mechutil::VERSION,
662                "layout_hash": format!("{:#018x}", <P::Memory as GmCompat>::LAYOUT_HASH),
663                "total_size": <P::Memory as GmCompat>::TOTAL_SIZE,
664            }));
665            return Ok(());
666        }
667
668        // Initialize UDP logger FIRST (before any log statements)
669        if let Err(e) = logger::init_udp_logger(
670            &self.config.server_host,
671            self.config.log_udp_port,
672            self.config.log_level,
673            "control",
674        ) {
675            eprintln!("Warning: Failed to initialize UDP logger: {}", e);
676            // Continue anyway - logging will just go nowhere
677        }
678
679        // Multi-threaded runtime so spawned WS read/write tasks can run
680        // alongside the synchronous control loop.
681        let rt = tokio::runtime::Builder::new_multi_thread()
682            .worker_threads(2)
683            .enable_all()
684            .build()?;
685
686        rt.block_on(async {
687            log::info!("AutoCore Control Runner Starting...");
688
689            // 1. Connect to server via WebSocket and get layout
690            let ws_url = format!("ws://{}:{}/ws/", self.config.server_host, self.config.ws_port);
691            log::info!("Connecting to server at {}", ws_url);
692
693            let (ws_stream, _) = connect_async(&ws_url).await
694                .map_err(|e| anyhow!("Failed to connect to server at {}: {}", ws_url, e))?;
695
696            let (mut write, mut read) = ws_stream.split();
697
698            // Send gm.get_layout request
699            let request = CommandMessage::request("gm.get_layout", serde_json::Value::Null);
700            let transaction_id = request.transaction_id;
701            let request_json = serde_json::to_string(&request)?;
702
703            write.send(Message::Text(request_json)).await
704                .map_err(|e| anyhow!("Failed to send layout request: {}", e))?;
705
706            // Wait for response with matching transaction_id
707            let timeout = Duration::from_secs(10);
708            let start = std::time::Instant::now();
709            let mut layout: Option<HashMap<String, serde_json::Value>> = None;
710
711            while start.elapsed() < timeout {
712                match tokio::time::timeout(Duration::from_secs(1), read.next()).await {
713                    Ok(Some(Ok(Message::Text(text)))) => {
714                        if let Ok(response) = serde_json::from_str::<CommandMessage>(&text) {
715                            if response.transaction_id == transaction_id {
716                                if !response.success {
717                                    return Err(anyhow!("Server error: {}", response.error_message));
718                                }
719                                layout = Some(serde_json::from_value(response.data)?);
720                                break;
721                            }
722                            // Skip broadcasts and other messages
723                            if response.message_type == MessageType::Broadcast {
724                                continue;
725                            }
726                        }
727                    }
728                    Ok(Some(Ok(_))) => continue,
729                    Ok(Some(Err(e))) => return Err(anyhow!("WebSocket error: {}", e)),
730                    Ok(None) => return Err(anyhow!("Server closed connection")),
731                    Err(_) => continue, // Timeout on single read, keep trying
732                }
733            }
734
735            let layout = layout.ok_or_else(|| anyhow!("Timeout waiting for layout response"))?;
736            log::info!("Layout received with {} entries.", layout.len());
737
738            // Set up channels and background tasks for shared WebSocket access.
739            // This allows both the control loop (gm.write) and CommandClient (IPC
740            // commands) to share the write half, while routing incoming responses
741            // to the CommandClient.
742            let (ws_write_tx, mut ws_write_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
743            let (response_tx, response_rx) = tokio::sync::mpsc::unbounded_channel::<CommandMessage>();
744
745            // Background task: WS write loop
746            // Reads serialized messages from ws_write_rx and sends them over the WebSocket.
747            tokio::spawn(async move {
748                while let Some(msg_json) = ws_write_rx.recv().await {
749                    if let Err(e) = write.send(Message::Text(msg_json)).await {
750                        log::error!("WebSocket write error: {}", e);
751                        break;
752                    }
753                }
754            });
755
756            // Background task: WS read loop
757            // Reads all incoming WebSocket messages. Routes Response and
758            // Broadcast messages to response_tx; CommandClient dispatches
759            // them onward (responses by transaction_id, broadcasts by
760            // topic into per-topic buffers that subscribers drain via
761            // `take_broadcasts`).
762            tokio::spawn(async move {
763                while let Some(result) = read.next().await {
764                    match result {
765                        Ok(Message::Text(text)) => {
766                            if let Ok(msg) = serde_json::from_str::<CommandMessage>(&text) {
767                                if matches!(
768                                    msg.message_type,
769                                    MessageType::Response | MessageType::Broadcast,
770                                ) {
771                                    if response_tx.send(msg).is_err() {
772                                        break; // receiver dropped
773                                    }
774                                }
775                                // Other message types are ignored
776                            }
777                        }
778                        Ok(Message::Close(_)) => {
779                            log::info!("WebSocket closed by server");
780                            break;
781                        }
782                        Err(e) => {
783                            log::error!("WebSocket read error: {}", e);
784                            break;
785                        }
786                        _ => {} // Ping/Pong/Binary - ignore
787                    }
788                }
789            });
790
791            // Construct CommandClient — owned by the runner, passed to the
792            // program via TickContext each cycle.
793            let mut command_client = CommandClient::new(ws_write_tx.clone(), response_rx);
794
795            // 2. Find Signal Offsets
796            let tick_offset = self.find_offset(&layout, &self.config.tick_signal_name)?;
797            let busy_offset = if let Some(name) = &self.config.busy_signal_name {
798                Some(self.find_offset(&layout, name)?)
799            } else {
800                None
801            };
802
803            // 4. Open Shared Memory
804            let shmem = ShmemConf::new().os_id(&self.config.shm_name).open()?;
805            let base_ptr = shmem.as_ptr();
806            log::info!("Shared Memory '{}' mapped.", self.config.shm_name);
807
808            // 4b. Validate the segment header BEFORE trusting any of its bytes.
809            // The server writes a self-describing header at offset 0; if the
810            // layout/ABI this program was built against doesn't match the live
811            // segment, refuse to run rather than read/write mismapped memory.
812            {
813                use mechutil::shm_header::{ShmHeader, SHM_HEADER_SIZE, SHM_MAGIC, SHM_FORMAT_VERSION};
814                if shmem.len() < SHM_HEADER_SIZE {
815                    anyhow::bail!(
816                        "GM segment '{}' is {} bytes, smaller than the {}-byte header — \
817                         server is too old or the segment is corrupt.",
818                        self.config.shm_name, shmem.len(), SHM_HEADER_SIZE);
819                }
820                let header: ShmHeader =
821                    unsafe { std::ptr::read_volatile(base_ptr as *const ShmHeader) };
822                if header.magic != SHM_MAGIC {
823                    anyhow::bail!(
824                        "GM segment '{}' has bad magic 0x{:016x} (expected 0x{:016x}) — \
825                         not an autocore segment, or an incompatible server.",
826                        self.config.shm_name, header.magic, SHM_MAGIC);
827                }
828                if header.format_version != SHM_FORMAT_VERSION {
829                    anyhow::bail!(
830                        "INCOMPATIBLE GM segment: header format v{} but this control program \
831                         expects v{}. Rebuild server and control against the same mechutil.",
832                        header.format_version, SHM_FORMAT_VERSION);
833                }
834                if header.shm_abi_version != mechutil::SHM_ABI_VERSION {
835                    anyhow::bail!(
836                        "INCOMPATIBLE GM segment: server SHM ABI v{} but this control program was \
837                         built against mechutil ABI v{} ({}). Rebuild the control program against \
838                         the server's mechutil version.",
839                        header.shm_abi_version, mechutil::SHM_ABI_VERSION, mechutil::VERSION);
840                }
841                if header.layout_hash != <P::Memory as GmCompat>::LAYOUT_HASH {
842                    anyhow::bail!(
843                        "INCOMPATIBLE GM layout: server segment hash 0x{:016x} != control hash \
844                         0x{:016x}. The server is serving a stale layout — RESTART autocore-server \
845                         to apply the pushed control program.",
846                        header.layout_hash, <P::Memory as GmCompat>::LAYOUT_HASH);
847                }
848                if header.total_size as usize != <P::Memory as GmCompat>::TOTAL_SIZE {
849                    anyhow::bail!(
850                        "INCOMPATIBLE GM size: server segment {} bytes != control {} bytes — \
851                         rebuild/restart required.",
852                        header.total_size, <P::Memory as GmCompat>::TOTAL_SIZE);
853                }
854                log::info!(
855                    "GM compatibility OK (layout 0x{:016x}, abi {}, {} bytes).",
856                    header.layout_hash, header.shm_abi_version, header.total_size);
857            }
858
859            // Wait for the server to finish applying initial values before we
860            // read SHM. Without this, our startup read can race with the
861            // server's initial-value writes; we would then clobber any
862            // initials when we write local_mem back below.
863            if let Some(ready_info) = layout.get("__ready__") {
864                let ready_offset = ready_info.get("offset")
865                    .and_then(|v| v.as_u64())
866                    .ok_or_else(|| anyhow!("__ready__ layout entry has no offset"))? as usize;
867                let ready_ptr = unsafe { base_ptr.add(ready_offset) as *const u32 };
868                let start = std::time::Instant::now();
869                let timeout = Duration::from_secs(10);
870                loop {
871                    let val = unsafe { std::ptr::read_volatile(ready_ptr) };
872                    if val == 1 {
873                        fence(Ordering::Acquire);
874                        log::info!("Server ready flag observed after {:?}", start.elapsed());
875                        break;
876                    }
877                    if start.elapsed() > timeout {
878                        log::warn!("Timed out waiting for server ready flag; proceeding anyway (initials may be zeroed)");
879                        break;
880                    }
881                    std::thread::sleep(Duration::from_millis(5));
882                }
883            } else {
884                log::warn!("No __ready__ flag in layout; server may predate ready-flag protocol. Initial values may race.");
885            }
886
887            // 5. Setup Pointers
888            // SAFETY: header validated above — the variable region begins at
889            // SHM_HEADER_SIZE and matches the generated GlobalMemory struct.
890            let gm = unsafe {
891                &mut *(base_ptr.add(mechutil::shm_header::SHM_HEADER_SIZE) as *mut P::Memory)
892            };
893
894            // Get tick event from shared memory
895            log::info!("Setting up tick event at offset {} (base_ptr: {:p})", tick_offset, base_ptr);
896            let (tick_event, _) = unsafe {
897                Event::from_existing(base_ptr.add(tick_offset))
898            }.map_err(|e| anyhow!("Failed to open tick event: {:?}", e))?;
899            log::info!("Tick event ready");
900
901            // Busy signal event (optional)
902            let busy_event = busy_offset.map(|offset| {
903                unsafe { Event::from_existing(base_ptr.add(offset)) }
904                    .map(|(event, _)| event)
905                    .ok()
906            }).flatten();
907
908            // 6. Initialize local memory buffer and user program
909            // We use a local copy for the control loop to ensure:
910            // - Consistent snapshot of inputs at start of cycle
911            // - Atomic commit of outputs at end of cycle
912            // - Proper memory barriers for cross-process visibility
913            let mut local_mem: P::Memory = unsafe { std::ptr::read_volatile(gm) };
914            let mut prev_mem: P::Memory = local_mem; // Snapshot for change detection
915
916            fence(Ordering::Acquire); // Ensure we see all prior writes from other processes
917
918            self.program.initialize(&mut local_mem);
919
920            // Write back any changes from initialize
921            fence(Ordering::Release);
922            unsafe { std::ptr::write_volatile(gm, local_mem) };
923
924            // Set up signal handler for graceful shutdown
925            let running = Arc::new(AtomicBool::new(true));
926            let r = running.clone();
927            
928            // Only set handler if not already set
929            if let Err(e) = ctrlc::set_handler(move || {
930                r.store(false, Ordering::SeqCst);
931            }) {
932                log::warn!("Failed to set signal handler: {}", e);
933            }
934
935            log::info!("Entering Control Loop - waiting for first tick...");
936            let mut cycle_count: u64 = 0;
937            let mut consecutive_timeouts: u32 = 0;
938
939            while running.load(Ordering::SeqCst) {
940                // Wait for Tick - Event-based synchronization
941                // Use a timeout (1s) to allow checking the running flag periodically
942                match tick_event.wait(Timeout::Val(Duration::from_secs(1))) {
943                    Ok(_) => {
944                        consecutive_timeouts = 0;
945                    },
946                    Err(e) => {
947                        // Check for timeout
948                        let err_str = format!("{:?}", e);
949                        if err_str.contains("Timeout") {
950                            consecutive_timeouts += 1;
951                            if consecutive_timeouts == 10 {
952                                log::error!(
953                                    "TICK STALL: {} consecutive timeouts! cycle={} pending={} responses={} fds={} rss_kb={}",
954                                    consecutive_timeouts,
955                                    cycle_count,
956                                    command_client.pending_count(),
957                                    command_client.response_count(),
958                                    diagnostics::count_open_fds(),
959                                    diagnostics::get_rss_kb(),
960                                );
961                            }
962                            if consecutive_timeouts > 10 && consecutive_timeouts % 60 == 0 {
963                                log::error!(
964                                    "TICK STALL continues: {} consecutive timeouts, cycle={}",
965                                    consecutive_timeouts,
966                                    cycle_count,
967                                );
968                            }
969                            continue;
970                        }
971                        return Err(anyhow!("Tick wait failed: {:?}", e));
972                    }
973                }
974
975                if !running.load(Ordering::SeqCst) {
976                    log::info!("Shutdown signal received, exiting control loop.");
977                    break;
978                }
979
980                cycle_count += 1;
981                if cycle_count == 1 {
982                    log::info!("First tick received!");
983                }
984
985                // // Periodic diagnostics (every 30s at 100 Hz)
986                // if cycle_count % 3000 == 0 {
987                //     log::info!(
988                //         "DIAG cycle={} pending={} responses={} fds={} rss_kb={}",
989                //         cycle_count,
990                //         command_client.pending_count(),
991                //         command_client.response_count(),
992                //         diagnostics::count_open_fds(),
993                //         diagnostics::get_rss_kb(),
994                //     );
995                // }
996
997                // === INPUT PHASE ===
998                // Read all variables from shared memory into local buffer.
999                // This gives us a consistent snapshot of inputs for this cycle.
1000                // Acquire fence ensures we see all writes from other processes (server, modules).
1001                local_mem = unsafe { std::ptr::read_volatile(gm) };
1002                
1003                // Update prev_mem before execution to track changes made IN THIS CYCLE
1004                // Actually, we want to know what changed in SHM relative to what we last knew,
1005                // OR what WE changed relative to what we read?
1006                // The user wants "writes on shared variables" to be broadcast.
1007                // Typically outputs.
1008                // If inputs changed (from other source), broadcasting them again is fine too.
1009                // Let's capture state BEFORE execution (which is what we just read from SHM).
1010                prev_mem = local_mem;
1011
1012                fence(Ordering::Acquire);
1013
1014                // Unpack bit-mapped variables from their source words.
1015                local_mem.unpack_bits();
1016
1017                // Snapshot after unpack — used by pack_bits to detect which
1018                // bools the control program actually changed.
1019                let pre_tick = local_mem;
1020
1021                // === EXECUTE PHASE ===
1022                // Poll IPC responses so they are available during process_tick.
1023                command_client.poll();
1024
1025                // Execute user logic on the local copy.
1026                // All reads/writes during process_tick operate on local_mem.
1027                let mut ctx = TickContext {
1028                    gm: &mut local_mem,
1029                    client: &mut command_client,
1030                    cycle: cycle_count,
1031                };
1032                self.program.process_tick(&mut ctx);
1033
1034                // === OUTPUT PHASE ===
1035                // Pack bit-mapped variables back into their source words,
1036                // but only for sources where a mapped bool actually changed.
1037                local_mem.pack_bits(&pre_tick);
1038
1039                // Write all variables from local buffer back to shared memory.
1040                // Release fence ensures our writes are visible to other processes.
1041                fence(Ordering::Release);
1042                unsafe { std::ptr::write_volatile(gm, local_mem) };
1043
1044                // === CHANGE DETECTION & NOTIFICATION ===
1045                let changes = local_mem.get_changes(&prev_mem);
1046                if !changes.is_empty() {
1047                    // Construct bulk write message
1048                    let mut data_map = serde_json::Map::new();
1049                    for (key, val) in changes {
1050                        data_map.insert(key.to_string(), val);
1051                    }
1052                    
1053                    let msg = CommandMessage::request("gm.write", serde_json::Value::Object(data_map));
1054                    let msg_json = serde_json::to_string(&msg).unwrap_or_default();
1055
1056                    // Send via the shared write channel (non-blocking)
1057                    if let Err(e) = ws_write_tx.send(msg_json) {
1058                        log::error!("Failed to send updates: {}", e);
1059                    }
1060                }
1061
1062                // Signal Busy/Done event
1063                if let Some(ref busy_ev) = busy_event {
1064                    let _ = busy_ev.set(EventState::Signaled);
1065                }
1066            }
1067
1068            Ok(())
1069        })
1070    }
1071
1072    fn find_offset(&self, layout: &HashMap<String, serde_json::Value>, name: &str) -> Result<usize> {
1073        let info = layout.get(name).ok_or_else(|| anyhow!("Signal '{}' not found in layout", name))?;
1074        info.get("offset")
1075            .and_then(|v| v.as_u64())
1076            .map(|v| v as usize)
1077            .ok_or_else(|| anyhow!("Invalid offset for '{}'", name))
1078    }
1079}
1080
1081/// Generates the standard `main` function for a control program.
1082///
1083/// This macro reduces boilerplate by creating a properly configured `main`
1084/// function that initializes and runs your control program.
1085///
1086/// # Arguments
1087///
1088/// * `$prog_type` - The type of your control program (must implement [`ControlProgram`])
1089/// * `$shm_name` - The shared memory segment name (string literal)
1090/// * `$tick_signal` - The tick signal name in shared memory (string literal)
1091///
1092/// # Example
1093///
1094/// ```ignore
1095/// mod gm;
1096/// use gm::GlobalMemory;
1097///
1098/// pub struct MyProgram;
1099///
1100/// impl MyProgram {
1101///     pub fn new() -> Self { Self }
1102/// }
1103///
1104/// impl autocore_std::ControlProgram for MyProgram {
1105///     type Memory = GlobalMemory;
1106///
1107///     fn process_tick(&mut self, ctx: &mut autocore_std::TickContext<Self::Memory>) {
1108///         // Your logic here
1109///     }
1110/// }
1111///
1112/// // This generates the main function
1113/// autocore_std::autocore_main!(MyProgram, "my_project_shm", "tick");
1114/// ```
1115///
1116/// # Generated Code
1117///
1118/// The macro expands to:
1119///
1120/// ```ignore
1121/// fn main() -> anyhow::Result<()> {
1122///     let config = autocore_std::RunnerConfig {
1123///         server_host: "127.0.0.1".to_string(),
1124///         ws_port: autocore_std::DEFAULT_WS_PORT,
1125///         module_name: "control".to_string(),
1126///         shm_name: "my_project_shm".to_string(),
1127///         tick_signal_name: "tick".to_string(),
1128///         busy_signal_name: None,
1129///         log_level: log::LevelFilter::Info,
1130///         log_udp_port: autocore_std::logger::DEFAULT_LOG_UDP_PORT,
1131///     };
1132///
1133///     autocore_std::ControlRunner::new(MyProgram::new())
1134///         .config(config)
1135///         .run()
1136/// }
1137/// ```
1138#[macro_export]
1139macro_rules! autocore_main {
1140    ($prog_type:ty, $shm_name:expr, $tick_signal:expr) => {
1141        fn main() -> anyhow::Result<()> {
1142            let config = autocore_std::RunnerConfig {
1143                server_host: "127.0.0.1".to_string(),
1144                ws_port: autocore_std::DEFAULT_WS_PORT,
1145                module_name: "control".to_string(),
1146                shm_name: $shm_name.to_string(),
1147                tick_signal_name: $tick_signal.to_string(),
1148                busy_signal_name: None,
1149                log_level: log::LevelFilter::Info,
1150                log_udp_port: autocore_std::logger::DEFAULT_LOG_UDP_PORT,
1151            };
1152
1153            autocore_std::ControlRunner::new(<$prog_type>::new())
1154                .config(config)
1155                .run()
1156        }
1157    };
1158}
1159