Skip to content

Commit 9fc820a

Browse files
committed
start system daemon after constructors are run
1 parent 0a6c0e8 commit 9fc820a

2 files changed

Lines changed: 34 additions & 18 deletions

File tree

src/system/startup.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
#include <cstdlib>
2323
#include <sys/unistd.h>
2424

25-
2625
extern "C" {
2726
// Initialization routines provided elsewhere
2827
void rtos_initialize();
@@ -50,6 +49,8 @@ static void pros_init() {
5049
vfs_initialize();
5150
}
5251

52+
// forward-declare system daemon initialization function
53+
void initialize_system_daemon();
5354
// forward-declare main function
5455
int main();
5556

@@ -73,6 +74,9 @@ void _start() {
7374
// call global constructors
7475
__libc_init_array();
7576

77+
// initialize the system daemon
78+
initialize_system_daemon();
79+
7680
// start main task
7781
// these pragmas are needed to silence the same warning on clang and gcc
7882
// normally you aren't supposed to reference the main function

src/system/system_daemon.cpp

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,36 @@ namespace zest {
1111

1212
// This task runs for the lifetime of the program.
1313
// It periodically calls vexTasksRun, which copies shared memory to/from vexOS.
14-
static pros::Task system_daemon([]() {
15-
while (true) {
16-
// lock all smart port mutexes
17-
Brain::smart_port_mutex_lock_all();
18-
// flush serial output
19-
ser_output_flush();
20-
// suspend all tasks
21-
rtos_suspend_all();
22-
// copy shared memory
23-
vexTasksRun();
24-
// resume all tasks
25-
rtos_resume_all();
26-
// unlock all smart port mutexes
27-
zest::Brain::smart_port_mutex_unlock_all();
14+
// it's wrapped in an optional, because we only want to start it after all constructors are run.
15+
// This means it needs to be initialized by the _start function in startup.cpp
16+
static std::optional<pros::Task> system_daemon;
2817

29-
// delay to save resources
30-
pros::delay(2);
18+
/**
19+
* @brief Initialize the system daemon task
20+
*
21+
*/
22+
void initialize_system_daemon() {
23+
if (!system_daemon) {
24+
system_daemon = pros::Task::create([]() {
25+
while (true) {
26+
// lock all smart port mutexes
27+
Brain::smart_port_mutex_lock_all();
28+
// flush serial output
29+
ser_output_flush();
30+
// suspend all tasks
31+
rtos_suspend_all();
32+
// copy shared memory
33+
vexTasksRun();
34+
// resume all tasks
35+
rtos_resume_all();
36+
// unlock all smart port mutexes
37+
zest::Brain::smart_port_mutex_unlock_all();
38+
39+
// delay to save resources
40+
pros::delay(2);
41+
}
42+
}, TASK_PRIORITY_MAX);
3143
}
32-
}, TASK_PRIORITY_MAX);
44+
}
3345

3446
} // namespace zest

0 commit comments

Comments
 (0)