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/// Function blocks for control programs (IEC 61131-3 inspired).
206pub mod fb;
207
208/// Interface protocols for communication between control programs and external sources.
209pub mod iface;
210
211/// Client for sending IPC commands to external modules via WebSocket.
212pub mod command_client;
213pub use command_client::CommandClient;
214
215/// Shared memory utilities for external modules.
216pub mod shm;
217
218// ============================================================================
219// Core Framework
220// ============================================================================
221
222/// Marker trait for generated GlobalMemory structs.
223///
224/// This trait is implemented by the auto-generated `GlobalMemory` struct
225/// that represents the shared memory layout. It serves as a marker for
226/// type safety in the control framework.
227///
228/// You don't need to implement this trait yourself - it's automatically
229/// implemented by the code generator.
230pub trait AutoCoreMemory {}
231
232/// Trait for detecting changes in memory structures.
233pub trait ChangeTracker {
234    /// Compare self with a previous state and return a list of changed fields.
235    /// Returns a vector of (field_name, new_value).
236    fn get_changes(&self, prev: &Self) -> Vec<(&'static str, serde_json::Value)>;
237}
238
239/// Per-tick context passed to the control program by the framework.
240///
241/// `TickContext` bundles all per-cycle data into a single struct so that the
242/// [`ControlProgram::process_tick`] signature stays stable as new fields are
243/// added in the future (e.g., delta time, diagnostics).
244///
245/// The framework constructs a fresh `TickContext` each cycle, calls
246/// [`CommandClient::poll`] before handing it to the program, and writes
247/// the memory back to shared memory after `process_tick` returns.
248pub struct TickContext<'a, M> {
249    /// Mutable reference to the local shared memory copy.
250    pub gm: &'a mut M,
251    /// IPC command client for communicating with external modules.
252    pub client: &'a mut CommandClient,
253    /// Current cycle number (starts at 1, increments each tick).
254    pub cycle: u64,
255}
256
257/// The trait that defines a control program's logic.
258///
259/// Implement this trait to create your control program. The associated `Memory`
260/// type should be the generated `GlobalMemory` struct from your project.
261///
262/// # Memory Type Requirements
263///
264/// The `Memory` type must implement `Copy` to allow efficient synchronization
265/// between shared memory and local buffers. This is automatically satisfied
266/// by the generated `GlobalMemory` struct.
267///
268/// # Lifecycle
269///
270/// 1. `initialize` is called once at startup
271/// 2. `process_tick` is called repeatedly in the control loop with a
272///    [`TickContext`] that provides shared memory, the IPC client, and the
273///    current cycle number.
274///
275/// # Example
276///
277/// ```ignore
278/// use autocore_std::{ControlProgram, TickContext};
279///
280/// mod gm;
281/// use gm::GlobalMemory;
282///
283/// pub struct MyController {
284///     cycle_counter: u64,
285/// }
286///
287/// impl MyController {
288///     pub fn new() -> Self {
289///         Self { cycle_counter: 0 }
290///     }
291/// }
292///
293/// impl ControlProgram for MyController {
294///     type Memory = GlobalMemory;
295///
296///     fn initialize(&mut self, mem: &mut GlobalMemory) {
297///         // Set initial output states
298///         mem.outputs.ready = true;
299///         log::info!("Controller initialized");
300///     }
301///
302///     fn process_tick(&mut self, ctx: &mut TickContext<Self::Memory>) {
303///         self.cycle_counter = ctx.cycle;
304///
305///         // Your control logic here
306///         if ctx.gm.inputs.start && !ctx.gm.inputs.estop {
307///             ctx.gm.outputs.running = true;
308///         }
309///     }
310/// }
311/// ```
312pub trait ControlProgram {
313    /// The shared memory structure type (usually the generated `GlobalMemory`).
314    ///
315    /// Must implement `Copy` to allow efficient memory synchronization.
316    type Memory: Copy + ChangeTracker;
317
318    /// Called once when the control program starts.
319    ///
320    /// Use this to initialize output states, reset counters, or perform
321    /// any one-time setup. The default implementation does nothing.
322    ///
323    /// # Arguments
324    ///
325    /// * `mem` - Mutable reference to the shared memory. Changes are written
326    ///           back to shared memory after this method returns.
327    fn initialize(&mut self, _mem: &mut Self::Memory) {}
328
329    /// The main control loop - called once per scan cycle.
330    ///
331    /// This is where your control logic lives. Read inputs from `ctx.gm`,
332    /// perform calculations, and write outputs back to `ctx.gm`. Use
333    /// `ctx.client` for IPC commands and `ctx.cycle` for the current cycle
334    /// number.
335    ///
336    /// The framework calls [`CommandClient::poll`] before each invocation,
337    /// so incoming responses are already buffered when your code runs.
338    ///
339    /// # Arguments
340    ///
341    /// * `ctx` - A [`TickContext`] containing the local shared memory copy,
342    ///           the IPC command client, and the current cycle number.
343    ///
344    /// # Timing
345    ///
346    /// This method should complete within the scan cycle time. Long-running
347    /// operations will cause cycle overruns.
348    fn process_tick(&mut self, ctx: &mut TickContext<Self::Memory>);
349}
350
351/// Configuration for the [`ControlRunner`].
352///
353/// Specifies connection parameters, shared memory names, and logging settings.
354/// Use [`Default::default()`] for typical configurations.
355///
356/// # Example
357///
358/// ```
359/// use autocore_std::RunnerConfig;
360/// use log::LevelFilter;
361///
362/// let config = RunnerConfig {
363///     server_host: "192.168.1.100".to_string(),
364///     module_name: "my_controller".to_string(),
365///     shm_name: "my_project_shm".to_string(),
366///     tick_signal_name: "tick".to_string(),
367///     busy_signal_name: Some("busy".to_string()),
368///     log_level: LevelFilter::Debug,
369///     ..Default::default()
370/// };
371/// ```
372#[derive(Debug, Clone)]
373pub struct RunnerConfig {
374    /// Server host address (default: "127.0.0.1")
375    pub server_host: String,
376    /// WebSocket port for commands (default: 11969)
377    pub ws_port: u16,
378    /// Module name for identification (default: "control")
379    pub module_name: String,
380    /// Shared memory segment name (must match server configuration)
381    pub shm_name: String,
382    /// Name of the tick signal in shared memory (triggers each scan cycle)
383    pub tick_signal_name: String,
384    /// Optional name of the busy signal (set when cycle completes)
385    pub busy_signal_name: Option<String>,
386    /// Minimum log level to send to the server (default: Info)
387    pub log_level: LevelFilter,
388    /// UDP port for sending logs to the server (default: 39101)
389    pub log_udp_port: u16,
390}
391
392/// Default WebSocket port for autocore-server
393pub const DEFAULT_WS_PORT: u16 = 11969;
394
395impl Default for RunnerConfig {
396    fn default() -> Self {
397        Self {
398            server_host: "127.0.0.1".to_string(),
399            ws_port: DEFAULT_WS_PORT,
400            module_name: "control".to_string(),
401            shm_name: "autocore_cyclic".to_string(),
402            tick_signal_name: "tick".to_string(),
403            busy_signal_name: None,
404            log_level: LevelFilter::Info,
405            log_udp_port: logger::DEFAULT_LOG_UDP_PORT,
406        }
407    }
408}
409
410
411/// The main execution engine for control programs.
412///
413/// `ControlRunner` handles all the infrastructure required to run a control program:
414///
415/// - Reading memory layout from the server's layout file
416/// - Opening and mapping shared memory
417/// - Setting up synchronization signals
418/// - Running the real-time control loop
419/// - Sending log messages to the server
420///
421/// # Usage
422///
423/// ```ignore
424/// use autocore_std::{ControlRunner, RunnerConfig};
425///
426/// let config = RunnerConfig {
427///     shm_name: "my_project_shm".to_string(),
428///     tick_signal_name: "tick".to_string(),
429///     ..Default::default()
430/// };
431///
432/// ControlRunner::new(MyProgram::new())
433///     .config(config)
434///     .run()?;  // Blocks forever
435/// ```
436///
437/// # Control Loop
438///
439/// The runner executes a synchronous control loop:
440///
441/// 1. **Wait** - Blocks until the tick signal is set by the server
442/// 2. **Read** - Copies shared memory to a local buffer (acquire barrier)
443/// 3. **Execute** - Calls your `process_tick` method
444/// 4. **Write** - Copies local buffer back to shared memory (release barrier)
445/// 5. **Signal** - Sets the busy signal (if configured) to indicate completion
446///
447/// This ensures your code always sees a consistent snapshot of the data
448/// and that your writes are atomically visible to other processes.
449pub struct ControlRunner<P: ControlProgram> {
450    config: RunnerConfig,
451    program: P,
452}
453
454impl<P: ControlProgram> ControlRunner<P> {
455    /// Creates a new runner for the given control program.
456    ///
457    /// Uses default configuration. Call [`.config()`](Self::config) to customize.
458    ///
459    /// # Arguments
460    ///
461    /// * `program` - Your control program instance
462    ///
463    /// # Example
464    ///
465    /// ```ignore
466    /// let runner = ControlRunner::new(MyProgram::new());
467    /// ```
468    pub fn new(program: P) -> Self {
469        Self {
470            config: RunnerConfig::default(),
471            program,
472        }
473    }
474
475    /// Sets the configuration for this runner.
476    ///
477    /// # Arguments
478    ///
479    /// * `config` - The configuration to use
480    ///
481    /// # Example
482    ///
483    /// ```ignore
484    /// ControlRunner::new(MyProgram::new())
485    ///     .config(RunnerConfig {
486    ///         shm_name: "custom_shm".to_string(),
487    ///         ..Default::default()
488    ///     })
489    ///     .run()?;
490    /// ```
491    pub fn config(mut self, config: RunnerConfig) -> Self {
492        self.config = config;
493        self
494    }
495
496    /// Starts the control loop.
497    ///
498    /// This method blocks indefinitely, running the control loop until
499    /// an error occurs or the process is terminated.
500    ///
501    /// # Returns
502    ///
503    /// Returns `Ok(())` only if the loop exits cleanly (which typically
504    /// doesn't happen). Returns an error if:
505    ///
506    /// - IPC connection fails
507    /// - Shared memory cannot be opened
508    /// - Signal offsets cannot be found
509    /// - A critical error occurs during execution
510    ///
511    /// # Example
512    ///
513    /// ```ignore
514    /// fn main() -> anyhow::Result<()> {
515    ///     ControlRunner::new(MyProgram::new())
516    ///         .config(config)
517    ///         .run()
518    /// }
519    /// ```
520    pub fn run(mut self) -> Result<()> {
521        // Initialize UDP logger FIRST (before any log statements)
522        if let Err(e) = logger::init_udp_logger(
523            &self.config.server_host,
524            self.config.log_udp_port,
525            self.config.log_level,
526            "control",
527        ) {
528            eprintln!("Warning: Failed to initialize UDP logger: {}", e);
529            // Continue anyway - logging will just go nowhere
530        }
531
532        // Multi-threaded runtime so spawned WS read/write tasks can run
533        // alongside the synchronous control loop.
534        let rt = tokio::runtime::Builder::new_multi_thread()
535            .worker_threads(2)
536            .enable_all()
537            .build()?;
538
539        rt.block_on(async {
540            log::info!("AutoCore Control Runner Starting...");
541
542            // 1. Connect to server via WebSocket and get layout
543            let ws_url = format!("ws://{}:{}/ws/", self.config.server_host, self.config.ws_port);
544            log::info!("Connecting to server at {}", ws_url);
545
546            let (ws_stream, _) = connect_async(&ws_url).await
547                .map_err(|e| anyhow!("Failed to connect to server at {}: {}", ws_url, e))?;
548
549            let (mut write, mut read) = ws_stream.split();
550
551            // Send gm.get_layout request
552            let request = CommandMessage::request("gm.get_layout", serde_json::Value::Null);
553            let transaction_id = request.transaction_id;
554            let request_json = serde_json::to_string(&request)?;
555
556            write.send(Message::Text(request_json)).await
557                .map_err(|e| anyhow!("Failed to send layout request: {}", e))?;
558
559            // Wait for response with matching transaction_id
560            let timeout = Duration::from_secs(10);
561            let start = std::time::Instant::now();
562            let mut layout: Option<HashMap<String, serde_json::Value>> = None;
563
564            while start.elapsed() < timeout {
565                match tokio::time::timeout(Duration::from_secs(1), read.next()).await {
566                    Ok(Some(Ok(Message::Text(text)))) => {
567                        if let Ok(response) = serde_json::from_str::<CommandMessage>(&text) {
568                            if response.transaction_id == transaction_id {
569                                if !response.success {
570                                    return Err(anyhow!("Server error: {}", response.error_message));
571                                }
572                                layout = Some(serde_json::from_value(response.data)?);
573                                break;
574                            }
575                            // Skip broadcasts and other messages
576                            if response.message_type == MessageType::Broadcast {
577                                continue;
578                            }
579                        }
580                    }
581                    Ok(Some(Ok(_))) => continue,
582                    Ok(Some(Err(e))) => return Err(anyhow!("WebSocket error: {}", e)),
583                    Ok(None) => return Err(anyhow!("Server closed connection")),
584                    Err(_) => continue, // Timeout on single read, keep trying
585                }
586            }
587
588            let layout = layout.ok_or_else(|| anyhow!("Timeout waiting for layout response"))?;
589            log::info!("Layout received with {} entries.", layout.len());
590
591            // Set up channels and background tasks for shared WebSocket access.
592            // This allows both the control loop (gm.write) and CommandClient (IPC
593            // commands) to share the write half, while routing incoming responses
594            // to the CommandClient.
595            let (ws_write_tx, mut ws_write_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
596            let (response_tx, response_rx) = tokio::sync::mpsc::unbounded_channel::<CommandMessage>();
597
598            // Background task: WS write loop
599            // Reads serialized messages from ws_write_rx and sends them over the WebSocket.
600            tokio::spawn(async move {
601                while let Some(msg_json) = ws_write_rx.recv().await {
602                    if let Err(e) = write.send(Message::Text(msg_json)).await {
603                        log::error!("WebSocket write error: {}", e);
604                        break;
605                    }
606                }
607            });
608
609            // Background task: WS read loop
610            // Reads all incoming WebSocket messages. Routes Response messages to
611            // response_tx for the CommandClient; ignores broadcasts and others.
612            tokio::spawn(async move {
613                while let Some(result) = read.next().await {
614                    match result {
615                        Ok(Message::Text(text)) => {
616                            if let Ok(msg) = serde_json::from_str::<CommandMessage>(&text) {
617                                if msg.message_type == MessageType::Response {
618                                    if response_tx.send(msg).is_err() {
619                                        break; // receiver dropped
620                                    }
621                                }
622                                // Broadcasts and other message types are ignored
623                            }
624                        }
625                        Ok(Message::Close(_)) => {
626                            log::info!("WebSocket closed by server");
627                            break;
628                        }
629                        Err(e) => {
630                            log::error!("WebSocket read error: {}", e);
631                            break;
632                        }
633                        _ => {} // Ping/Pong/Binary - ignore
634                    }
635                }
636            });
637
638            // Construct CommandClient — owned by the runner, passed to the
639            // program via TickContext each cycle.
640            let mut command_client = CommandClient::new(ws_write_tx.clone(), response_rx);
641
642            // 2. Find Signal Offsets
643            let tick_offset = self.find_offset(&layout, &self.config.tick_signal_name)?;
644            let busy_offset = if let Some(name) = &self.config.busy_signal_name {
645                Some(self.find_offset(&layout, name)?)
646            } else {
647                None
648            };
649
650            // 4. Open Shared Memory
651            let shmem = ShmemConf::new().os_id(&self.config.shm_name).open()?;
652            let base_ptr = shmem.as_ptr();
653            log::info!("Shared Memory '{}' mapped.", self.config.shm_name);
654
655            // 5. Setup Pointers
656            // SAFETY: We trust the server's layout matches the generated GlobalMemory struct.
657            let gm = unsafe { &mut *(base_ptr as *mut P::Memory) };
658
659            // Get tick event from shared memory
660            log::info!("Setting up tick event at offset {} (base_ptr: {:p})", tick_offset, base_ptr);
661            let (tick_event, _) = unsafe {
662                Event::from_existing(base_ptr.add(tick_offset))
663            }.map_err(|e| anyhow!("Failed to open tick event: {:?}", e))?;
664            log::info!("Tick event ready");
665
666            // Busy signal event (optional)
667            let busy_event = busy_offset.map(|offset| {
668                unsafe { Event::from_existing(base_ptr.add(offset)) }
669                    .map(|(event, _)| event)
670                    .ok()
671            }).flatten();
672
673            // 6. Initialize local memory buffer and user program
674            // We use a local copy for the control loop to ensure:
675            // - Consistent snapshot of inputs at start of cycle
676            // - Atomic commit of outputs at end of cycle
677            // - Proper memory barriers for cross-process visibility
678            let mut local_mem: P::Memory = unsafe { std::ptr::read_volatile(gm) };
679            let mut prev_mem: P::Memory = local_mem; // Snapshot for change detection
680
681            fence(Ordering::Acquire); // Ensure we see all prior writes from other processes
682
683            self.program.initialize(&mut local_mem);
684
685            // Write back any changes from initialize
686            fence(Ordering::Release);
687            unsafe { std::ptr::write_volatile(gm, local_mem) };
688
689            // Set up signal handler for graceful shutdown
690            let running = Arc::new(AtomicBool::new(true));
691            let r = running.clone();
692            
693            // Only set handler if not already set
694            if let Err(e) = ctrlc::set_handler(move || {
695                r.store(false, Ordering::SeqCst);
696            }) {
697                log::warn!("Failed to set signal handler: {}", e);
698            }
699
700            log::info!("Entering Control Loop - waiting for first tick...");
701            let mut cycle_count: u64 = 0;
702
703            while running.load(Ordering::SeqCst) {
704                // Wait for Tick - Event-based synchronization
705                // Use a timeout (1s) to allow checking the running flag periodically
706                match tick_event.wait(Timeout::Val(Duration::from_secs(1))) {
707                    Ok(_) => {},
708                    Err(e) => {
709                        // Check for timeout
710                        let err_str = format!("{:?}", e);
711                        if err_str.contains("Timeout") {
712                            continue;
713                        }
714                        return Err(anyhow!("Tick wait failed: {:?}", e));
715                    }
716                }
717
718                if !running.load(Ordering::SeqCst) {
719                    log::info!("Shutdown signal received, exiting control loop.");
720                    break;
721                }
722
723                cycle_count += 1;
724                if cycle_count == 1 {
725                    log::info!("First tick received!");
726                }
727
728                // === INPUT PHASE ===
729                // Read all variables from shared memory into local buffer.
730                // This gives us a consistent snapshot of inputs for this cycle.
731                // Acquire fence ensures we see all writes from other processes (server, modules).
732                local_mem = unsafe { std::ptr::read_volatile(gm) };
733                
734                // Update prev_mem before execution to track changes made IN THIS CYCLE
735                // Actually, we want to know what changed in SHM relative to what we last knew,
736                // OR what WE changed relative to what we read?
737                // The user wants "writes on shared variables" to be broadcast.
738                // Typically outputs.
739                // If inputs changed (from other source), broadcasting them again is fine too.
740                // Let's capture state BEFORE execution (which is what we just read from SHM).
741                prev_mem = local_mem;
742
743                fence(Ordering::Acquire);
744
745                // === EXECUTE PHASE ===
746                // Poll IPC responses so they are available during process_tick.
747                command_client.poll();
748
749                // Execute user logic on the local copy.
750                // All reads/writes during process_tick operate on local_mem.
751                let mut ctx = TickContext {
752                    gm: &mut local_mem,
753                    client: &mut command_client,
754                    cycle: cycle_count,
755                };
756                self.program.process_tick(&mut ctx);
757
758                // === OUTPUT PHASE ===
759                // Write all variables from local buffer back to shared memory.
760                // Release fence ensures our writes are visible to other processes.
761                fence(Ordering::Release);
762                unsafe { std::ptr::write_volatile(gm, local_mem) };
763
764                // === CHANGE DETECTION & NOTIFICATION ===
765                let changes = local_mem.get_changes(&prev_mem);
766                if !changes.is_empty() {
767                    // Construct bulk write message
768                    let mut data_map = serde_json::Map::new();
769                    for (key, val) in changes {
770                        data_map.insert(key.to_string(), val);
771                    }
772                    
773                    let msg = CommandMessage::request("gm.write", serde_json::Value::Object(data_map));
774                    let msg_json = serde_json::to_string(&msg).unwrap_or_default();
775
776                    // Send via the shared write channel (non-blocking)
777                    if let Err(e) = ws_write_tx.send(msg_json) {
778                        log::error!("Failed to send updates: {}", e);
779                    }
780                }
781
782                // Signal Busy/Done event
783                if let Some(ref busy_ev) = busy_event {
784                    let _ = busy_ev.set(EventState::Signaled);
785                }
786            }
787
788            Ok(())
789        })
790    }
791
792    fn find_offset(&self, layout: &HashMap<String, serde_json::Value>, name: &str) -> Result<usize> {
793        let info = layout.get(name).ok_or_else(|| anyhow!("Signal '{}' not found in layout", name))?;
794        info.get("offset")
795            .and_then(|v| v.as_u64())
796            .map(|v| v as usize)
797            .ok_or_else(|| anyhow!("Invalid offset for '{}'", name))
798    }
799}
800
801/// Generates the standard `main` function for a control program.
802///
803/// This macro reduces boilerplate by creating a properly configured `main`
804/// function that initializes and runs your control program.
805///
806/// # Arguments
807///
808/// * `$prog_type` - The type of your control program (must implement [`ControlProgram`])
809/// * `$shm_name` - The shared memory segment name (string literal)
810/// * `$tick_signal` - The tick signal name in shared memory (string literal)
811///
812/// # Example
813///
814/// ```ignore
815/// mod gm;
816/// use gm::GlobalMemory;
817///
818/// pub struct MyProgram;
819///
820/// impl MyProgram {
821///     pub fn new() -> Self { Self }
822/// }
823///
824/// impl autocore_std::ControlProgram for MyProgram {
825///     type Memory = GlobalMemory;
826///
827///     fn process_tick(&mut self, ctx: &mut autocore_std::TickContext<Self::Memory>) {
828///         // Your logic here
829///     }
830/// }
831///
832/// // This generates the main function
833/// autocore_std::autocore_main!(MyProgram, "my_project_shm", "tick");
834/// ```
835///
836/// # Generated Code
837///
838/// The macro expands to:
839///
840/// ```ignore
841/// fn main() -> anyhow::Result<()> {
842///     let config = autocore_std::RunnerConfig {
843///         server_host: "127.0.0.1".to_string(),
844///         ws_port: autocore_std::DEFAULT_WS_PORT,
845///         module_name: "control".to_string(),
846///         shm_name: "my_project_shm".to_string(),
847///         tick_signal_name: "tick".to_string(),
848///         busy_signal_name: None,
849///         log_level: log::LevelFilter::Info,
850///         log_udp_port: autocore_std::logger::DEFAULT_LOG_UDP_PORT,
851///     };
852///
853///     autocore_std::ControlRunner::new(MyProgram::new())
854///         .config(config)
855///         .run()
856/// }
857/// ```
858#[macro_export]
859macro_rules! autocore_main {
860    ($prog_type:ty, $shm_name:expr, $tick_signal:expr) => {
861        fn main() -> anyhow::Result<()> {
862            let config = autocore_std::RunnerConfig {
863                server_host: "127.0.0.1".to_string(),
864                ws_port: autocore_std::DEFAULT_WS_PORT,
865                module_name: "control".to_string(),
866                shm_name: $shm_name.to_string(),
867                tick_signal_name: $tick_signal.to_string(),
868                busy_signal_name: None,
869                log_level: log::LevelFilter::Info,
870                log_udp_port: autocore_std::logger::DEFAULT_LOG_UDP_PORT,
871            };
872
873            autocore_std::ControlRunner::new(<$prog_type>::new())
874                .config(config)
875                .run()
876        }
877    };
878}
879