-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
361 lines (310 loc) · 12.8 KB
/
main.rs
File metadata and controls
361 lines (310 loc) · 12.8 KB
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
#![no_main]
#![no_std]
use arplus_firmware as _; // Global logger and panicking behavior.
#[rtic::app(device = stm32h7xx_hal::pac, peripherals = true, dispatchers = [EXTI0, EXTI1, EXTI2])]
mod app {
use core::mem::MaybeUninit;
use arplus_firmware::random_generator::RandomGenerator;
use fugit::ExtU64;
use heapless::spsc::{Consumer, Producer, Queue};
use systick_monotonic::Systick;
use arplus_control::{ControlInputSnapshot, Controller, Save};
use arplus_dsp::{Attributes as DspAttributes, Dsp, MemoryManager};
use arplus_firmware::audio::{AudioInterface, SAMPLE_RATE};
use arplus_firmware::audio_probe::AudioProbeInterface;
use arplus_firmware::control_input::ControlInputInterface;
use arplus_firmware::control_output::ControlOutputInterface;
use arplus_firmware::flash_memory::FlashMemoryInterface;
use arplus_firmware::queue_utils;
use arplus_firmware::startup_sequence;
use arplus_firmware::system::System;
use arplus_firmware::version_indicator::VersionIndicator;
// Blinks on the PCB's LED signalize the current revision.
const BLINKS: u8 = 1;
#[link_section = ".sram"]
static mut MEMORY: [MaybeUninit<u32>; 96 * 1024] =
unsafe { MaybeUninit::uninit().assume_init() };
// 1 kHz granularity for task scheduling.
#[monotonic(binds = SysTick, default = true)]
type Mono = Systick<1000>;
#[shared]
struct Shared {
save_cache: Option<Save>,
}
#[local]
struct Local {
audio_interface: AudioInterface,
random_generator: RandomGenerator,
flash_memory_interface: FlashMemoryInterface,
control_input_interface: ControlInputInterface,
control_output_interface: ControlOutputInterface,
audio_probe_interface: AudioProbeInterface,
dsp: Dsp,
controller: Controller,
version_indicator: VersionIndicator,
dsp_attributes_producer: Producer<'static, DspAttributes, 8>,
dsp_attributes_consumer: Consumer<'static, DspAttributes, 8>,
control_input_snapshot_producer: Producer<'static, ControlInputSnapshot, 8>,
control_input_snapshot_consumer: Consumer<'static, ControlInputSnapshot, 8>,
save_producer: Producer<'static, Save, 8>,
save_consumer: Consumer<'static, Save, 8>,
}
#[init(
local = [
dsp_attributes_queue: Queue<DspAttributes, 8> = Queue::new(),
input_snapshot_queue: Queue<ControlInputSnapshot, 8> = Queue::new(),
save_queue: Queue<Save, 8> = Queue::new(),
]
)]
fn init(mut cx: init::Context) -> (Shared, Local, init::Monotonics) {
defmt::info!("Starting the firmware, initializing resources");
if cfg!(feature = "idle-measuring") {
cx.core.DCB.enable_trace();
cx.core.DWT.enable_cycle_counter();
}
let (dsp_attributes_producer, dsp_attributes_consumer) =
cx.local.dsp_attributes_queue.split();
let (control_input_snapshot_producer, control_input_snapshot_consumer) =
cx.local.input_snapshot_queue.split();
let (save_producer, save_consumer) = cx.local.save_queue.split();
let system = System::init(cx.core, cx.device);
let mono = system.mono;
let mut random_generator = system.random_generator;
let mut audio_interface = system.audio_interface;
let mut flash_memory_interface = system.flash_memory_interface;
let mut control_input_interface = system.control_input_interface;
let control_output_interface = system.control_output_interface;
let audio_probe_interface = system.audio_probe_interface;
startup_sequence::warm_up_control_input(&mut control_input_interface);
let save = startup_sequence::retrieve_save(
&mut control_input_interface,
&mut flash_memory_interface,
);
let seed = u64::from_be_bytes(unsafe {
// PANIC: This may fail in case the HAL fails to generate a random
// number. In which case, it is ok to fail early here. So far that
// never happened to me.
core::mem::transmute::<[[u8; 2]; 4], [u8; 8]>([
random_generator.u16().unwrap().to_be_bytes(),
random_generator.u16().unwrap().to_be_bytes(),
random_generator.u16().unwrap().to_be_bytes(),
random_generator.u16().unwrap().to_be_bytes(),
])
});
defmt::debug!("Using seed={:?}", seed);
let controller = Controller::new(seed, save);
let mut stack_manager = MemoryManager::from(unsafe { &mut MEMORY[..] });
let dsp = Dsp::new(SAMPLE_RATE as f32, &mut stack_manager);
let version_indicator = VersionIndicator::new(BLINKS, system.status_led);
defmt::info!("Spawning tasks");
audio_interface.spawn();
version_indicator_loop::spawn().unwrap();
control_loop::spawn().unwrap();
input_collection_loop::spawn().unwrap();
save_caching_loop::spawn().unwrap();
save_pacing_loop::spawn().unwrap();
(
Shared { save_cache: None },
Local {
audio_interface,
random_generator,
flash_memory_interface,
control_input_interface,
control_output_interface,
audio_probe_interface,
dsp,
controller,
version_indicator,
dsp_attributes_producer,
dsp_attributes_consumer,
control_input_snapshot_producer,
control_input_snapshot_consumer,
save_producer,
save_consumer,
},
init::Monotonics(mono),
)
}
#[task(
local = [
control_input_interface,
control_input_snapshot_producer,
],
priority = 2,
)]
fn input_collection_loop(cx: input_collection_loop::Context) {
let control_input_interface = cx.local.control_input_interface;
let control_input_snapshot_producer = cx.local.control_input_snapshot_producer;
control_input_interface.sample();
let _ = control_input_snapshot_producer.enqueue(control_input_interface.snapshot());
// NOTE: This must be timed at the end. Otherwise, this task may get an interrupt
// during sampling, which would then follow by immediate second execution of this
// task, not giving enough time for the probe signal to propagate.
input_collection_loop::spawn_after(1.millis()).ok().unwrap();
}
#[task(
local = [
controller,
control_output_interface,
dsp_attributes_producer,
control_input_snapshot_consumer,
save_producer,
],
priority = 3,
)]
fn control_loop(cx: control_loop::Context) {
control_loop::spawn_after(1.millis()).ok().unwrap();
let controller = cx.local.controller;
let control_output_interface = cx.local.control_output_interface;
let dsp_attributes_producer = cx.local.dsp_attributes_producer;
let control_input_snapshot_consumer = cx.local.control_input_snapshot_consumer;
let save_producer = cx.local.save_producer;
queue_utils::warn_about_capacity("input_snapshot", control_input_snapshot_consumer);
if let Some(snapshot) = queue_utils::dequeue_last(control_input_snapshot_consumer) {
let result = controller.apply_input_snapshot(snapshot);
if let Some(save) = result.save {
let _ = save_producer.enqueue(save);
}
let _ = dsp_attributes_producer.enqueue(result.dsp_attributes);
}
let desired_output_state = controller.tick();
control_output_interface.set_state(&desired_output_state);
}
#[task(
binds = DMA1_STR1,
local = [
audio_interface,
audio_probe_interface,
random_generator,
dsp,
dsp_attributes_consumer,
],
priority = 4,
)]
fn dsp_loop(cx: dsp_loop::Context) {
let audio_interface = cx.local.audio_interface;
let audio_probe_interface = cx.local.audio_probe_interface;
let random_generator = cx.local.random_generator;
let dsp = cx.local.dsp;
let dsp_attributes_consumer = cx.local.dsp_attributes_consumer;
queue_utils::warn_about_capacity("dsp_attributes", dsp_attributes_consumer);
// XXX: Selection happens already here to put as much distance between
// the setting and reading in the next DSP cycle.
audio_probe_interface.broadcaster.tick();
if let Some(attributes) = queue_utils::dequeue_last(dsp_attributes_consumer) {
dsp.set_attributes(attributes, random_generator);
}
audio_interface.update_buffer(|buffer| {
audio_probe_interface.detector.write_from_left(buffer);
let input_connected = !audio_probe_interface.detector.detected();
dsp.process(buffer, input_connected, random_generator);
});
}
#[task(
local = [
save_consumer,
],
shared = [
save_cache,
],
priority = 3,
)]
fn save_caching_loop(cx: save_caching_loop::Context) {
save_caching_loop::spawn_after(1.millis()).ok().unwrap();
let save_consumer = cx.local.save_consumer;
let mut save_cache = cx.shared.save_cache;
queue_utils::warn_about_capacity("save_consumer", save_consumer);
if let Some(save) = queue_utils::dequeue_last(save_consumer) {
save_cache.lock(|save_cache| {
*save_cache = Some(save);
});
}
}
#[task(
shared = [
save_cache,
],
priority = 3,
)]
fn save_pacing_loop(mut cx: save_pacing_loop::Context) {
save_pacing_loop::spawn_after(10.secs()).ok().unwrap();
cx.shared.save_cache.lock(|save_cache| {
if let Some(save) = save_cache.take() {
// NOTE: Lazy evalutation to avoid expensive logging
#[allow(clippy::unnecessary_lazy_evaluations)]
save_coroutine::spawn(save)
.unwrap_or_else(|_| defmt::warn!("Failed issuing store request"));
}
});
}
#[task(
local = [
flash_memory_interface
]
)]
fn save_coroutine(cx: save_coroutine::Context, save: Save) {
let flash_memory_interface = cx.local.flash_memory_interface;
flash_memory_interface.save(save);
}
#[task(
local = [
version_indicator
]
)]
fn version_indicator_loop(cx: version_indicator_loop::Context) {
let version_indicator = cx.local.version_indicator;
let required_sleep = version_indicator.cycle();
version_indicator_loop::spawn_after(required_sleep).unwrap();
}
#[idle(local = [idling: u32 = 0, start: u32 = 0])]
fn idle(cx: idle::Context) -> ! {
if cfg!(feature = "idle-measuring") {
use core::sync::atomic::{self, Ordering};
use daisy::pac::DWT;
const USECOND: u32 = 480;
const TIME_LIMIT: u32 = USECOND * 10_000; // 0.01 second
defmt::info!("Idle measuring is enabled");
let idling: &'static mut u32 = cx.local.idling;
let start: &'static mut u32 = cx.local.start;
atomic::compiler_fence(Ordering::Acquire);
*start = DWT::cycle_count();
loop {
cortex_m::interrupt::free(|_cs| {
cortex_m::asm::delay(USECOND);
*idling += USECOND;
});
if *idling >= TIME_LIMIT {
let now = DWT::cycle_count();
atomic::compiler_fence(Ordering::Release);
let elapsed = calculate_elapsed_dwt_ticks(now, start);
#[allow(clippy::cast_precision_loss)]
let idling_relative = *idling as f32 / elapsed as f32;
log_idle_time(idling_relative);
atomic::compiler_fence(Ordering::Acquire);
*start = DWT::cycle_count();
*idling = 0;
}
}
} else {
loop {
cortex_m::asm::nop();
}
}
}
fn calculate_elapsed_dwt_ticks(now: u32, start: &mut u32) -> u32 {
if now >= *start {
now - *start
} else {
now + (u32::MAX - *start)
}
}
fn log_idle_time(idling_relative: f32) {
const IDLE_LIMIT: f32 = 0.1;
let idling_percent = idling_relative * 100.0;
if idling_relative < IDLE_LIMIT {
defmt::warn!("Idle time={}% is below the limit", idling_percent);
} else {
defmt::debug!("Idle time={}%", idling_percent);
}
}
}