SouthEugeneRoboticsTeam / sertain

Framework for programming FRC robots, inspired by Sertain Legacy and Meanlib
6 stars 0 forks source link

Util reforms #70

Closed gnawinganimal closed 4 years ago

gnawinganimal commented 4 years ago

Some reforms, making the utils easier to use.

periodic

The first change is that periodic now takes a third parameter time of type MetricValue<Chronic>. The function will cancel itself after the specified time. Here's an example:

suspend fun moveArm() = arm {
    periodic(time = 5.s) {
        it.move()
    }
    it.stop()
}

In past versions of sertain, this would have been written as:

suspend fun moveArm() = arm {
    try {
        onTick {
            it.move()
        }
        delay(5.s)
        cancel()
    } finally {
        it.stop()
    }
}

The first has the clear advantage of being less verbose, but it has a few other perks to it as well. For one thing, it will return a Success rather than a Failure. This is useful for if you need to return a value, because no value can be returned from a Failure. Another advantage is that everything happens within the scope of the command. In the latter example, the finally block would run after the command has already ended, but in the prior, all wrap-up code is invoked within the command, meaning that there is no potential for overlap between commands.

timer

The other change is that timer now passes it's action a MetricValue<Chronic> rather than a Long. This means that you can use from to convert it to whatever unit you want, like so:

timer {
    val time = it.from(seconds)
    // use time here
}

You can also specify the unit as a parameter instead, and you will be passed a Double:

timer(unit = seconds) { time ->
    // use time here
}