FluenTech / embedded-time

Time(ing) library (Instant/Duration/Clock/Timer/Period/Frequency) for bare-metal embedded systems
Apache License 2.0
87 stars 17 forks source link

Generically take any duration? #92

Closed korken89 closed 2 years ago

korken89 commented 3 years ago

Hi, I have issues with getting the following code to compile as I am unable to get the correct traits needed. Could you assist here @PTaylor-us ?

pub fn spawn_after<D: embedded_time::duration::Duration>(duration: D) -> Result<(), ()> {
    let instant = <MyClock as rtic::Monotonic>::now(); // Return an Instant<MyClock>

    // This addition seems to be the issue
    spawn_at(instant + duration, #(,#untupled)*)
}
korken89 commented 3 years ago

We found the correct traits that were needed eventually. Would there be any way to make this simpler?

Solution:

pub fn spawn_after<D>(duration: D) -> Result<(), ()>
    where D: embedded_time::duration::Duration + embedded_time::fixed_point::FixedPoint,
       D::T: Into<<MyClock as embedded_time::Clock>::T>,
{
    let instant = <MyClock as rtic::Monotonic>::now();

    spawn_at(instant + duration, #(,#untupled)*)
}
wbuck commented 3 years ago

I did have a some what similar request. Would it be possible to export the TimeInt trait?

It would be beneficial when trying to create a custom type, i.e Rpm.

PTaylor-us commented 3 years ago

I want to allow easy generic usage of any Duration/Rate (including Generic) with only a embedded_time::Duration where clause. I'm assuming this is not possible because the Add implementation for Instant requires that the Duration impl FixedPoint. This will probably take me some time to figure out unless anyone can help me out. I feel like there's a trait pattern that is missing.

PTaylor-us commented 2 years ago

Proposed Solution

This should allow this (eliminate the need to bind FixedPoint:

pub fn spawn_after<D>(duration: D) -> Result<(), ()>
    where D: embedded_time::duration::Duration,
       D::T: Into<<MyClock as embedded_time::Clock>::T>,
{
    let instant = <MyClock as rtic::Monotonic>::now();

    spawn_at(instant + duration, #(,#untupled)*)
}

@korken89 I'm not seeing a good way to eliminate the need for the Into binding, though.

PTaylor-us commented 2 years ago

This may not work fully. I wanted to move the const SCALING_FACTOR out of FixedPoint so Generic could also implement FixedPoint, but obviously, the scaling factor of the FixedPoint number must be accessible by the FixedPoint concrete type.

PTaylor-us commented 2 years ago

Current plan is to bind FixedPoint to Duration and Rate. Then I will remove the Duration and Rate implementations for the Generic versions.

korken89 commented 2 years ago

Sounds interesting, I'll be lurking. :)

PTaylor-us commented 2 years ago

Completed for v0.13.0 release PR