-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathobservables.rs
307 lines (269 loc) · 7.24 KB
/
observables.rs
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
//! Example: processor with observable states.
//!
//! This example demonstrates in particular:
//!
//! * the use of observable states,
//! * state machine with delays.
//!
//! ```text
//! ┌───────────┐
//! Switch ON/OFF ●────►│ ├────► Mode
//! │ Processor │
//! Process data ●────►│ ├────► Value
//! │ │
//! │ ├────► House Keeping
//! └───────────┘
//! ```
use std::time::Duration;
use nexosim::model::{Context, InitializedModel, Model};
use nexosim::ports::{EventBuffer, Output};
use nexosim::simulation::{AutoActionKey, Mailbox, SimInit, SimulationError};
use nexosim::time::MonotonicTime;
use nexosim_util::observables::{Observable, ObservableState, ObservableValue};
/// House keeping TM.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Hk {
pub voltage: f64,
pub current: f64,
}
impl Default for Hk {
fn default() -> Self {
Self {
voltage: 0.0,
current: 0.0,
}
}
}
/// Processor mode ID.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ModeId {
Off,
Idle,
Processing,
}
/// Processor state.
pub enum State {
Off,
Idle,
Processing(AutoActionKey),
}
impl Default for State {
fn default() -> Self {
State::Off
}
}
impl Observable<ModeId> for State {
fn observe(&self) -> ModeId {
match *self {
State::Off => ModeId::Off,
State::Idle => ModeId::Idle,
State::Processing(_) => ModeId::Processing,
}
}
}
/// Processor model.
pub struct Processor {
/// Mode output.
pub mode: Output<ModeId>,
/// Calculated value output.
pub value: Output<u16>,
/// HK output.
pub hk: Output<Hk>,
/// Internal state.
state: ObservableState<State, ModeId>,
/// Accumulator.
acc: ObservableValue<u16>,
/// Electrical data.
elc: ObservableValue<Hk>,
}
impl Processor {
/// Create a new processor.
pub fn new() -> Self {
let mode = Output::new();
let value = Output::new();
let hk = Output::new();
Self {
mode: mode.clone(),
value: value.clone(),
hk: hk.clone(),
state: ObservableState::new(mode),
acc: ObservableValue::new(value),
elc: ObservableValue::new(hk),
}
}
/// Switch processor ON/OFF.
pub async fn switch_power(&mut self, on: bool) {
if on {
self.state.set(State::Idle).await;
self.elc
.set(Hk {
voltage: 5.5,
current: 0.1,
})
.await;
self.acc.set(0).await;
} else {
self.state.set(State::Off).await;
self.elc.set(Hk::default()).await;
self.acc.set(0).await;
}
}
/// Process data for dt milliseconds.
pub async fn process(&mut self, dt: u64, cx: &mut Context<Self>) {
if matches!(self.state.observe(), ModeId::Idle | ModeId::Processing) {
self.state
.set(State::Processing(
cx.schedule_keyed_event(Duration::from_millis(dt), Self::finish_processing, ())
.unwrap()
.into_auto(),
))
.await;
self.elc.modify(|hk| hk.current = 1.0).await;
}
}
/// Finish processing.
async fn finish_processing(&mut self) {
self.state.set(State::Idle).await;
self.acc.modify(|a| *a += 1).await;
self.elc.modify(|hk| hk.current = 0.1).await;
}
}
impl Model for Processor {
/// Propagate all internal states.
async fn init(mut self, _: &mut Context<Self>) -> InitializedModel<Self> {
self.state.propagate().await;
self.acc.propagate().await;
self.elc.propagate().await;
self.into()
}
}
fn main() -> Result<(), SimulationError> {
// ---------------
// Bench assembly.
// ---------------
// Models.
let mut proc = Processor::new();
// Mailboxes.
let proc_mbox = Mailbox::new();
// Model handles for simulation.
let mut mode = EventBuffer::new();
let mut value = EventBuffer::new();
let mut hk = EventBuffer::new();
proc.mode.connect_sink(&mode);
proc.value.connect_sink(&value);
proc.hk.connect_sink(&hk);
let proc_addr = proc_mbox.address();
// Start time (arbitrary since models do not depend on absolute time).
let t0 = MonotonicTime::EPOCH;
// Assembly and initialization.
let mut simu = SimInit::new()
.add_model(proc, proc_mbox, "proc")
.init(t0)?
.0;
// ----------
// Simulation.
// ----------
// Initial state.
expect(
&mut mode,
Some(ModeId::Off),
&mut value,
Some(0),
&mut hk,
0.0,
0.0,
);
// Switch processor on.
simu.process_event(Processor::switch_power, true, &proc_addr)?;
expect(
&mut mode,
Some(ModeId::Idle),
&mut value,
Some(0),
&mut hk,
5.5,
0.1,
);
// Trigger processing.
simu.process_event(Processor::process, 100, &proc_addr)?;
expect(
&mut mode,
Some(ModeId::Processing),
&mut value,
None,
&mut hk,
5.5,
1.0,
);
// All data processed.
simu.step_until(Duration::from_millis(101))?;
expect(
&mut mode,
Some(ModeId::Idle),
&mut value,
Some(1),
&mut hk,
5.5,
0.1,
);
// Trigger long processing.
simu.process_event(Processor::process, 100, &proc_addr)?;
expect(
&mut mode,
Some(ModeId::Processing),
&mut value,
None,
&mut hk,
5.5,
1.0,
);
// Trigger short processing, it cancels the previous one.
simu.process_event(Processor::process, 10, &proc_addr)?;
expect(
&mut mode,
Some(ModeId::Processing),
&mut value,
None,
&mut hk,
5.5,
1.0,
);
// Wait for short processing to finish, check results.
simu.step_until(Duration::from_millis(11))?;
expect(
&mut mode,
Some(ModeId::Idle),
&mut value,
Some(2),
&mut hk,
5.5,
0.1,
);
// Wait long enough, no state change as the long processing has been
// cancelled.
simu.step_until(Duration::from_millis(100))?;
assert_eq!(mode.next(), None);
assert_eq!(value.next(), None);
assert_eq!(hk.next(), None);
Ok(())
}
// Check observable state.
fn expect(
mode: &mut EventBuffer<ModeId>,
mode_ex: Option<ModeId>,
value: &mut EventBuffer<u16>,
value_ex: Option<u16>,
hk: &mut EventBuffer<Hk>,
voltage_ex: f64,
current_ex: f64,
) {
assert_eq!(mode.next(), mode_ex);
assert_eq!(value.next(), value_ex);
let hk_value = hk.next().unwrap();
assert!(same(hk_value.voltage, voltage_ex));
assert!(same(hk_value.current, current_ex));
}
// Compare two voltages or currents.
fn same(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-12
}