embassy-rs / embassy

Modern embedded framework, using Rust and async.
https://embassy.dev
Apache License 2.0
5.44k stars 752 forks source link

embassy_sync::watch default values #3417

Open Gibbz opened 1 week ago

Gibbz commented 1 week ago

It would be nice to be able to supply default values for the new watch module. https://docs.embassy.dev/embassy-sync/git/default/watch/index.html

Currently I have something like this to setup default:

// default values
pub fn init() {
    CLOCK_HOURS_WATCH.dyn_sender().send_if_modified(|value| { *value = Some(0u8); false });
    CLOCK_MINUTES_WATCH.dyn_sender().send_if_modified(|value| { *value = Some(0u8); false });
}

pub static CLOCK_HOURS_WATCH: Watch<WatchMutex, u8, 1> = Watch::new();
pub static CLOCK_MINUTES_WATCH: Watch<WatchMutex, u8, 1> = Watch::new();

It could be much neater if we could simply include the default in the new:

pub static CLOCK_HOURS_WATCH: Watch<WatchMutex, u8, 1> = Watch::new(0u8);
pub static CLOCK_MINUTES_WATCH: Watch<WatchMutex, u8, 1> = Watch::new(0u8);
peterkrull commented 1 week ago

Adding a new_with(init: T) would be an option. Though when I use the Watch, I rarely experience that it makes sense to give them a value at compile-time. In your code, I would assume some task gets the responsibility of updating these clock watches at runtime. And if the value is not set and does not get updated, it is a good indicator that the responsible task is not alive. Do you have a another example of when this could be useful?

Gibbz commented 1 week ago
  1. I have some watches that I use for Async and in loops that I'm polling like a mutex. So in that case I don't want to have an uninitialised value.

  2. I'm storing a lot of settings, which need an initial state stored in them.

They're my main use cases in my project.