canlink-hal 0.3.2

Hardware abstraction layer for CAN bus interfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Periodic message scheduler.

use super::{PeriodicMessage, PeriodicStats};
use crate::{CanBackendAsync, CanError};
use std::collections::{BinaryHeap, HashMap};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use tokio::time::Instant;

/// Commands for controlling the scheduler.
#[derive(Debug)]
pub enum SchedulerCommand {
    /// Add a new periodic message
    Add {
        /// The message to add
        message: PeriodicMessage,
        /// Reply channel for the assigned ID
        reply: oneshot::Sender<Result<u32, CanError>>,
    },
    /// Remove a periodic message
    Remove {
        /// ID of the message to remove
        id: u32,
        /// Reply channel
        reply: oneshot::Sender<Result<(), CanError>>,
    },
    /// Update message data
    UpdateData {
        /// ID of the message to update
        id: u32,
        /// New data
        data: Vec<u8>,
        /// Reply channel
        reply: oneshot::Sender<Result<(), CanError>>,
    },
    /// Update send interval
    UpdateInterval {
        /// ID of the message to update
        id: u32,
        /// New interval
        interval: Duration,
        /// Reply channel
        reply: oneshot::Sender<Result<(), CanError>>,
    },
    /// Enable or disable a message
    SetEnabled {
        /// ID of the message
        id: u32,
        /// Whether to enable
        enabled: bool,
        /// Reply channel
        reply: oneshot::Sender<Result<(), CanError>>,
    },
    /// Get statistics for a message
    GetStats {
        /// ID of the message
        id: u32,
        /// Reply channel
        reply: oneshot::Sender<Option<PeriodicStats>>,
    },
    /// List all message IDs
    ListIds {
        /// Reply channel
        reply: oneshot::Sender<Vec<u32>>,
    },
    /// Shutdown the scheduler
    Shutdown,
}

/// Entry in the scheduling priority queue.
#[derive(Debug, Clone, Eq, PartialEq)]
struct ScheduledEntry {
    /// Next send time
    next_send: Instant,
    /// Message ID
    message_id: u32,
}

impl Ord for ScheduledEntry {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Reverse ordering for min-heap behavior
        other.next_send.cmp(&self.next_send)
    }
}

impl PartialOrd for ScheduledEntry {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Internal scheduler state.
struct SchedulerState {
    /// Message configurations
    messages: HashMap<u32, PeriodicMessage>,
    /// Statistics per message
    stats: HashMap<u32, PeriodicStats>,
    /// Priority queue for scheduling
    schedule: BinaryHeap<ScheduledEntry>,
    /// Next message ID to assign
    next_id: u32,
    /// Maximum capacity
    capacity: usize,
}

impl SchedulerState {
    fn new(capacity: usize) -> Self {
        Self {
            messages: HashMap::new(),
            stats: HashMap::new(),
            schedule: BinaryHeap::new(),
            next_id: 1,
            capacity,
        }
    }

    fn add(&mut self, mut message: PeriodicMessage) -> Result<u32, CanError> {
        if self.messages.len() >= self.capacity {
            return Err(CanError::InsufficientResources {
                resource: format!(
                    "periodic message capacity exceeded (max: {})",
                    self.capacity
                ),
            });
        }

        let id = self.next_id;
        self.next_id += 1;
        message.set_id(id);

        let interval = message.interval();
        self.messages.insert(id, message);
        self.stats.insert(id, PeriodicStats::new());

        // Schedule first send
        self.schedule.push(ScheduledEntry {
            next_send: Instant::now() + interval,
            message_id: id,
        });

        Ok(id)
    }

    fn remove(&mut self, id: u32) -> Result<(), CanError> {
        if self.messages.remove(&id).is_none() {
            return Err(CanError::InvalidParameter {
                parameter: "id".to_string(),
                reason: format!("periodic message with id {id} not found"),
            });
        }
        self.stats.remove(&id);
        // Note: Entry will be cleaned up when it's popped from the queue
        Ok(())
    }
}

/// Handle for controlling a periodic scheduler.
///
/// This handle can be cloned and shared across tasks to control the scheduler.
/// The actual scheduler loop runs separately via [`run_scheduler`].
///
/// # Example
///
/// ```rust,ignore
/// use canlink_hal::periodic::{PeriodicScheduler, PeriodicMessage, run_scheduler};
/// use canlink_mock::MockBackend;
/// use tokio::task::LocalSet;
///
/// let local = LocalSet::new();
/// local.run_until(async {
///     let (scheduler, command_rx) = PeriodicScheduler::new(32);
///
///     // Spawn the scheduler loop locally (doesn't require Send)
///     tokio::task::spawn_local(run_scheduler(backend, command_rx, 32));
///
///     // Use the scheduler handle
///     let id = scheduler.add(periodic_message).await?;
/// }).await;
/// ```
#[derive(Clone)]
pub struct PeriodicScheduler {
    /// Command sender
    command_tx: mpsc::Sender<SchedulerCommand>,
}

impl PeriodicScheduler {
    /// Create a new scheduler handle and command receiver.
    ///
    /// Returns a tuple of (handle, receiver). The receiver should be passed to
    /// [`run_scheduler`] which runs the actual scheduling loop.
    ///
    /// # Arguments
    ///
    /// * `channel_size` - Size of the command channel buffer (typically 64)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let (scheduler, command_rx) = PeriodicScheduler::new(64);
    /// tokio::task::spawn_local(run_scheduler(backend, command_rx, 32));
    /// ```
    #[must_use]
    pub fn new(channel_size: usize) -> (Self, mpsc::Receiver<SchedulerCommand>) {
        let (command_tx, command_rx) = mpsc::channel(channel_size);
        (Self { command_tx }, command_rx)
    }

    /// Add a periodic message.
    ///
    /// # Returns
    ///
    /// The unique ID assigned to the message.
    ///
    /// # Errors
    ///
    /// Returns an error if the capacity is exceeded or the scheduler is shut down.
    pub async fn add(&self, message: PeriodicMessage) -> Result<u32, CanError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SchedulerCommand::Add {
                message,
                reply: reply_tx,
            })
            .await
            .map_err(|_| CanError::Other {
                message: "scheduler channel closed".to_string(),
            })?;

        reply_rx.await.map_err(|_| CanError::Other {
            message: "scheduler reply channel closed".to_string(),
        })?
    }

    /// Remove a periodic message.
    ///
    /// # Errors
    ///
    /// Returns an error if the message ID is not found or the scheduler is shut down.
    pub async fn remove(&self, id: u32) -> Result<(), CanError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SchedulerCommand::Remove {
                id,
                reply: reply_tx,
            })
            .await
            .map_err(|_| CanError::Other {
                message: "scheduler channel closed".to_string(),
            })?;

        reply_rx.await.map_err(|_| CanError::Other {
            message: "scheduler reply channel closed".to_string(),
        })?
    }

    /// Update message data.
    ///
    /// # Errors
    ///
    /// Returns an error if the message ID is not found, the data is invalid,
    /// or the scheduler is shut down.
    pub async fn update_data(&self, id: u32, data: Vec<u8>) -> Result<(), CanError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SchedulerCommand::UpdateData {
                id,
                data,
                reply: reply_tx,
            })
            .await
            .map_err(|_| CanError::Other {
                message: "scheduler channel closed".to_string(),
            })?;

        reply_rx.await.map_err(|_| CanError::Other {
            message: "scheduler reply channel closed".to_string(),
        })?
    }

    /// Update send interval.
    ///
    /// # Errors
    ///
    /// Returns an error if the message ID is not found, the interval is invalid,
    /// or the scheduler is shut down.
    pub async fn update_interval(&self, id: u32, interval: Duration) -> Result<(), CanError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SchedulerCommand::UpdateInterval {
                id,
                interval,
                reply: reply_tx,
            })
            .await
            .map_err(|_| CanError::Other {
                message: "scheduler channel closed".to_string(),
            })?;

        reply_rx.await.map_err(|_| CanError::Other {
            message: "scheduler reply channel closed".to_string(),
        })?
    }

    /// Enable or disable a message.
    ///
    /// # Errors
    ///
    /// Returns an error if the message ID is not found or the scheduler is shut down.
    pub async fn set_enabled(&self, id: u32, enabled: bool) -> Result<(), CanError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SchedulerCommand::SetEnabled {
                id,
                enabled,
                reply: reply_tx,
            })
            .await
            .map_err(|_| CanError::Other {
                message: "scheduler channel closed".to_string(),
            })?;

        reply_rx.await.map_err(|_| CanError::Other {
            message: "scheduler reply channel closed".to_string(),
        })?
    }

    /// Get statistics for a message.
    ///
    /// # Returns
    ///
    /// `Some(stats)` if the message exists, `None` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if the scheduler is shut down.
    pub async fn get_stats(&self, id: u32) -> Result<Option<PeriodicStats>, CanError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SchedulerCommand::GetStats {
                id,
                reply: reply_tx,
            })
            .await
            .map_err(|_| CanError::Other {
                message: "scheduler channel closed".to_string(),
            })?;

        reply_rx.await.map_err(|_| CanError::Other {
            message: "scheduler reply channel closed".to_string(),
        })
    }

    /// List all message IDs.
    ///
    /// # Errors
    ///
    /// Returns an error if the scheduler is shut down.
    pub async fn list_ids(&self) -> Result<Vec<u32>, CanError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.command_tx
            .send(SchedulerCommand::ListIds { reply: reply_tx })
            .await
            .map_err(|_| CanError::Other {
                message: "scheduler channel closed".to_string(),
            })?;

        reply_rx.await.map_err(|_| CanError::Other {
            message: "scheduler reply channel closed".to_string(),
        })
    }

    /// Shutdown the scheduler.
    ///
    /// This sends a shutdown command to the scheduler loop. The loop will
    /// finish processing any pending commands and then exit.
    ///
    /// # Errors
    ///
    /// Returns an error if the scheduler is already shut down.
    pub async fn shutdown(&self) -> Result<(), CanError> {
        self.command_tx
            .send(SchedulerCommand::Shutdown)
            .await
            .map_err(|_| CanError::Other {
                message: "scheduler channel closed".to_string(),
            })
    }
}

/// Run the periodic scheduler loop.
///
/// This function runs the main scheduling loop that sends periodic messages.
/// It should be spawned as a task (using `spawn_local` for non-Send backends
/// or `spawn` for Send backends).
///
/// # Arguments
///
/// * `backend` - The CAN backend to use for sending messages
/// * `command_rx` - Command receiver from [`PeriodicScheduler::new`]
/// * `capacity` - Maximum number of periodic messages (typically 32)
///
/// # Example
///
/// ```rust,ignore
/// use canlink_hal::periodic::{PeriodicScheduler, run_scheduler};
/// use tokio::task::LocalSet;
///
/// // For non-Send backends, use LocalSet
/// let local = LocalSet::new();
/// local.run_until(async {
///     let (scheduler, command_rx) = PeriodicScheduler::new(64);
///     tokio::task::spawn_local(run_scheduler(backend, command_rx, 32));
///     // ... use scheduler
/// }).await;
///
/// // For Send backends, use regular spawn
/// let (scheduler, command_rx) = PeriodicScheduler::new(64);
/// tokio::spawn(run_scheduler(send_backend, command_rx, 32));
/// ```
#[allow(clippy::too_many_lines)]
pub async fn run_scheduler<B>(
    mut backend: B,
    mut command_rx: mpsc::Receiver<SchedulerCommand>,
    capacity: usize,
) where
    B: CanBackendAsync,
{
    let mut state = SchedulerState::new(capacity);

    loop {
        // Calculate sleep duration until next scheduled send
        let sleep_duration = state
            .schedule
            .peek()
            .map_or(Duration::from_secs(1), |entry| {
                let now = Instant::now();
                if entry.next_send > now {
                    entry.next_send - now
                } else {
                    Duration::ZERO
                }
            });

        tokio::select! {
            // Handle commands
            Some(cmd) = command_rx.recv() => {
                match cmd {
                    SchedulerCommand::Add { message, reply } => {
                        let _ = reply.send(state.add(message));
                    }
                    SchedulerCommand::Remove { id, reply } => {
                        let _ = reply.send(state.remove(id));
                    }
                    SchedulerCommand::UpdateData { id, data, reply } => {
                        let result = if let Some(msg) = state.messages.get_mut(&id) {
                            msg.update_data(data)
                        } else {
                            Err(CanError::InvalidParameter {
                                parameter: "id".to_string(),
                                reason: format!("periodic message with id {id} not found"),
                            })
                        };
                        let _ = reply.send(result);
                    }
                    SchedulerCommand::UpdateInterval { id, interval, reply } => {
                        let result = if let Some(msg) = state.messages.get_mut(&id) {
                            msg.set_interval(interval)
                        } else {
                            Err(CanError::InvalidParameter {
                                parameter: "id".to_string(),
                                reason: format!("periodic message with id {id} not found"),
                            })
                        };
                        let _ = reply.send(result);
                    }
                    SchedulerCommand::SetEnabled { id, enabled, reply } => {
                        let result = if let Some(msg) = state.messages.get_mut(&id) {
                            msg.set_enabled(enabled);
                            Ok(())
                        } else {
                            Err(CanError::InvalidParameter {
                                parameter: "id".to_string(),
                                reason: format!("periodic message with id {id} not found"),
                            })
                        };
                        let _ = reply.send(result);
                    }
                    SchedulerCommand::GetStats { id, reply } => {
                        let message_stats = state.stats.get(&id).cloned();
                        let _ = reply.send(message_stats);
                    }
                    SchedulerCommand::ListIds { reply } => {
                        let ids: Vec<u32> = state.messages.keys().copied().collect();
                        let _ = reply.send(ids);
                    }
                    SchedulerCommand::Shutdown => {
                        break;
                    }
                }
            }

            // Handle scheduled sends
            () = tokio::time::sleep(sleep_duration) => {
                let now = Instant::now();

                // Process all due entries
                while let Some(entry) = state.schedule.peek() {
                    if entry.next_send > now {
                        break;
                    }

                    let Some(entry) = state.schedule.pop() else {
                        break;
                    };
                    let id = entry.message_id;

                    // Check if message still exists and is enabled
                    if let Some(msg) = state.messages.get(&id) {
                        if msg.is_enabled() {
                            // Send the message
                            let send_result = backend.send_message_async(msg.message()).await;

                            // Record statistics
                            if let Some(stats) = state.stats.get_mut(&id) {
                                stats.record_send(now.into());
                            }

                            // Log errors but continue (FR-006: skip on failure)
                            if let Err(e) = send_result {
                                #[cfg(feature = "tracing")]
                                tracing::warn!(
                                    "Periodic send failed for message {}: {}",
                                    id,
                                    e
                                );
                                let _ = e; // Suppress unused warning when tracing is disabled
                            }
                        }

                        // Reschedule (use current interval in case it was updated)
                        if let Some(msg) = state.messages.get(&id) {
                            state.schedule.push(ScheduledEntry {
                                next_send: now + msg.interval(),
                                message_id: id,
                            });
                        }
                    }
                    // If message was removed, don't reschedule
                }
            }
        }
    }
}