nodo 0.18.5

A realtime framework for robotics
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
// Copyright 2023 David Weikersdorfer

use crate::{
    channels::{FlushResult, RxBundle, SyncResult, TxBundle},
    codelet::{
        Codelet, CodeletPulse, CodeletStatus, Context, Lifecycle, LifecycleStatus, Statistics,
        TaskClocks, Transition,
    },
    config::{Config, ConfigAux},
    core::*,
    monitors::SharedAppMonitor,
    signals::Signals,
};
use eyre::{eyre, Result};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};

/// Unique identifier of a node across the app
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NodeId(pub usize);

#[derive(Clone)]
pub struct SharedNodeCrumbs {
    inner: Arc<RwLock<Option<NodeCrumbs>>>,
}

impl SharedNodeCrumbs {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(None)),
        }
    }

    pub fn on_begin(&self, time: Pubtime, node_id: NodeId, transition: Transition) {
        // SAFETY: cannot panic during write
        *self.inner.write().unwrap() = Some(NodeCrumbs {
            time,
            node_id,
            transition,
        });
    }

    pub fn on_end(&self) {
        // SAFETY: cannot panic during write
        *self.inner.write().unwrap() = None;
    }

    pub fn read(&self) -> Option<NodeCrumbs> {
        // SAFETY: cannot panic during write
        self.inner.read().unwrap().clone()
    }
}

#[derive(Clone)]
pub struct NodeCrumbs {
    pub time: Pubtime,
    pub node_id: NodeId,
    pub transition: Transition,
}

/// Named instance of a codelet with configuration and channel bundels
pub struct CodeletInstance<C: Codelet> {
    pub id: Option<NodeId>,
    pub crumbs: Option<SharedNodeCrumbs>,

    pub name: String,
    pub state: C,
    pub config: C::Config,
    pub config_aux: <C::Config as Config>::Aux,
    pub rx: C::Rx,
    pub tx: C::Tx,

    pub(crate) clocks: Option<TaskClocks>,
    pub(crate) pulse: CodeletPulse,
    pub(crate) is_scheduled: bool,
    pub(crate) rx_sync_results: Vec<SyncResult>,
    pub(crate) tx_flush_results: Vec<FlushResult>,

    pub(crate) lifecycle_status: LifecycleStatus,
    pub(crate) status: Option<C::Status>,

    pub(crate) statistics: Statistics,

    pub(crate) signals: C::Signals,

    pub(crate) monitor: Option<SharedAppMonitor>,
}

impl<C: Codelet> Drop for CodeletInstance<C> {
    fn drop(&mut self) {
        if !self.is_scheduled {
            log::warn!(
                "Codelet instance `{}` was created and destroyed without every being scheduled",
                self.name
            );
        }
    }
}

impl<C: Codelet> CodeletInstance<C> {
    /// Creates a new instance with given state and config
    pub(crate) fn new<S: Into<String>>(name: S, state: C, config: C::Config) -> Self {
        let (rx, tx) = C::build_bundles(&config);
        let rx_count = rx.channel_count();
        let tx_count = tx.channel_count();
        Self {
            id: None,
            crumbs: None,
            name: name.into(),
            state,
            config,
            config_aux: <C::Config as Config>::Aux::default(),
            clocks: None,
            pulse: CodeletPulse::new(),
            is_scheduled: false,
            rx_sync_results: vec![SyncResult::ZERO; rx_count],
            tx_flush_results: vec![FlushResult::ZERO; tx_count],
            lifecycle_status: LifecycleStatus::Inactive,
            status: None,
            statistics: Statistics {
                rx_available_messages_count: vec![0; rx_count],
                tx_published_message_count: vec![0; tx_count],
                tx_last_pubtime: vec![None; tx_count],
                ..Default::default()
            },
            signals: Default::default(),
            monitor: None,
            rx,
            tx,
        }
    }

    pub fn type_name(&self) -> &str {
        std::any::type_name::<C>()
    }

    pub fn modify_state_with<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut C) -> (),
    {
        f(&mut self.state);
        self
    }

    pub fn start(&mut self) -> Result<C::Status> {
        profiling::scope!(&format!("{}_start", self.name));
        log::trace!("'{}' start begin", self.name);

        self.on_pre_start()?;

        let status = self.state.start(
            Context {
                clocks: &self.clocks.as_ref().unwrap(),
                config: &self.config,
                config_aux: &self.config_aux,
                pulse: &self.pulse,
                signals: &mut self.signals,
            },
            &mut self.rx,
            &mut self.tx,
        )?;

        self.on_post_start()?;

        log::trace!("'{}' start end ({})", self.name, status.label());
        Ok(status)
    }

    pub fn stop(&mut self) -> Result<C::Status> {
        profiling::scope!(&format!("{}_stop", self.name));
        log::trace!("'{}' stop begin", self.name);

        self.on_pre_stop()?;

        let status = self.state.stop(
            Context {
                clocks: &self.clocks.as_ref().unwrap(),
                config: &self.config,
                config_aux: &self.config_aux,
                pulse: &self.pulse,
                signals: &mut self.signals,
            },
            &mut self.rx,
            &mut self.tx,
        )?;

        self.on_post_stop()?;

        log::trace!("'{}' stop end ({})", self.name, status.label());
        Ok(status)
    }

    pub fn step(&mut self) -> Result<C::Status> {
        profiling::scope!(&format!("{}_step", self.name));
        log::trace!("'{}' step begin", self.name);

        self.on_pre_step()?;

        let status = self.state.step(
            Context {
                clocks: &self.clocks.as_ref().unwrap(),
                config: &self.config,
                config_aux: &self.config_aux,
                pulse: &self.pulse,
                signals: &mut self.signals,
            },
            &mut self.rx,
            &mut self.tx,
        )?;

        self.on_post_step()?;

        log::trace!("'{}' step end ({})", self.name, status.label());
        Ok(status)
    }

    pub fn pause(&mut self) -> Result<C::Status> {
        self.state.pause()
    }

    pub fn resume(&mut self) -> Result<C::Status> {
        self.state.resume()
    }

    fn on_pre_start(&mut self) -> Result<()> {
        self.lifecycle_status = LifecycleStatus::Starting;

        let cc = self.rx.check_connection();
        if !cc.is_fully_connected() {
            log::warn!(
                "codelet '{}' (type={}) has unconnected RX channels: {}",
                self.name,
                self.type_name(),
                cc.list_unconnected()
                    .iter()
                    .map(|&i| format!("[{i}] {}", self.rx.name(i)))
                    .collect::<Vec<String>>()
                    .join(", ")
            );
        }

        let cc = self.tx.check_connection();
        if !cc.is_fully_connected() {
            log::warn!(
                "codelet '{}' (type={}) has unconnected TX channels: {}",
                self.name,
                self.type_name(),
                cc.list_unconnected()
                    .iter()
                    .map(|&i| format!("[{i}] {}", self.tx.name(i)))
                    .collect::<Vec<String>>()
                    .join(", ")
            );
        }

        self.initialize_statistics();

        self.sync()?;

        self.clocks.as_mut().unwrap().on_codelet_start();

        self.update_statistics_rx_available_message_counts();

        Ok(())
    }

    fn on_post_start(&mut self) -> Result<()> {
        self.update_statistics_tx_published_message_count();

        self.flush()?;

        self.update_monitor()?;

        self.lifecycle_status = LifecycleStatus::Running;

        Ok(())
    }

    fn on_pre_stop(&mut self) -> Result<()> {
        self.lifecycle_status = LifecycleStatus::Stopping;

        self.sync()?;

        self.clocks.as_mut().unwrap().on_codelet_stop();

        self.update_statistics_rx_available_message_counts();

        Ok(())
    }

    fn on_post_stop(&mut self) -> Result<()> {
        self.update_statistics_tx_published_message_count();

        self.flush()?;

        self.update_monitor()?;

        self.lifecycle_status = LifecycleStatus::Inactive;

        Ok(())
    }

    fn on_pre_step(&mut self) -> Result<()> {
        self.sync()?;

        self.clocks.as_mut().unwrap().on_codelet_step();

        self.update_statistics_rx_available_message_counts();

        Ok(())
    }

    fn on_post_step(&mut self) -> Result<()> {
        self.update_statistics_tx_published_message_count();

        self.pulse.on_step_post();

        self.config_aux.on_post_step();

        self.flush()?;

        self.update_monitor()?;

        Ok(())
    }

    fn sync(&mut self) -> Result<()> {
        // For some codelets the TX channel count might change dynamically
        self.rx_sync_results
            .resize(self.rx.channel_count(), SyncResult::ZERO);

        self.rx.sync_all(self.rx_sync_results.as_mut_slice());

        for result in self.rx_sync_results.iter() {
            if result.enforce_empty_violation {
                return Err(eyre!("'{}': sync error (EnforceEmpty violated)", self.name,));
            }
        }

        Ok(())
    }

    fn flush(&mut self) -> Result<()> {
        // For some codelets the TX channel count might change dynamically
        self.tx_flush_results
            .resize(self.tx.channel_count(), FlushResult::ZERO);

        self.tx.flush_all(self.tx_flush_results.as_mut_slice());

        for result in self.tx_flush_results.iter() {
            if result.error_indicator.is_err() {
                return Err(eyre!(
                    "'{}': flush error {}",
                    self.name,
                    result.error_indicator
                ));
            }
        }

        Ok(())
    }

    fn update_monitor(&mut self) -> Result<()> {
        let step_time = self.clocks.as_ref().unwrap().codelet.step_time();
        self.signals.on_post_execute(step_time);

        self.monitor
            .as_ref()
            .unwrap()
            .update_node(self.clocks.as_ref().unwrap().app_mono.now(), self)?;

        Ok(())
    }

    fn initialize_statistics(&mut self) {
        self.statistics
            .rx_available_messages_count
            .resize(self.rx.channel_count(), 0);

        self.statistics
            .tx_published_message_count
            .resize(self.tx.channel_count(), 0);

        self.statistics
            .tx_last_pubtime
            .resize(self.tx.channel_count(), None);
    }

    fn update_statistics_rx_available_message_counts(&mut self) {
        for index in 0..self.rx.channel_count() {
            self.statistics.rx_available_messages_count[index] = self.rx.inbox_message_count(index);
        }
    }

    fn update_statistics_tx_published_message_count(&mut self) {
        // TODO this is not the pubtime of the message ..
        let codelet_step_time = self.clocks.as_ref().unwrap().app_mono.now();

        for index in 0..self.tx.channel_count() {
            let n = self.tx.outbox_message_count(index);
            self.statistics.tx_published_message_count[index] += n;
            if n > 0 {
                self.statistics.tx_last_pubtime[index] = Some(codelet_step_time);
            }
        }
    }

    fn on_cycle_begin(&mut self, transition: Transition) {
        let now = self
            .clocks
            .as_ref()
            .expect("internal error: clocks must be set")
            .app_mono
            .now();

        self.crumbs
            .as_ref()
            .expect("internal error: crumbs must be set")
            .on_begin(
                now,
                self.id.expect("internal error: id must be set"),
                transition,
            );

        self.statistics.transitions[transition].begin(now);
    }

    fn on_cycle_end(&mut self, transition: Transition, skipped: bool) {
        let now = self
            .clocks
            .as_ref()
            .expect("internal error: clocks must be set")
            .app_mono
            .now();

        self.statistics.transitions[transition].end(now, skipped);

        self.crumbs
            .as_ref()
            .expect("internal error: crumbs must be set")
            .on_end();
    }
}

impl<C: Codelet> Lifecycle for CodeletInstance<C> {
    fn cycle(&mut self, transition: Transition) -> Result<DefaultStatus> {
        self.on_cycle_begin(transition);

        let status = match transition {
            Transition::Start => self.start(),
            Transition::Step => self.step(),
            Transition::Stop => self.stop(),
            Transition::Pause => self.pause(),
            Transition::Resume => self.resume(),
        }?;
        let simplified_status = status.as_default_status();
        self.status = Some(status);

        let skipped = simplified_status == OutcomeKind::Skipped;
        self.on_cycle_end(transition, skipped);

        Ok(simplified_status)
    }
}