Checked Properties Example¶
Prerequisites: 1 - Calculators (basic properties and functions).
This example shows how to use checked properties.
Interface¶
We model a Timer that holds two writable properties. One is called program ad the other is called state.
package timer;
enum RunningState: u8 { off, on }
class Timer
{
// Timer state (on/off).
var state : RunningState [writable];
// Can be set only if the timer is off.
var program : Duration [writable];
// Remaining time.
var countdown : Duration;
// Emitted when the countdown transitions to 0.
event timeout();
}
This property called program is "checked". We only accept sets to program when stateis off.
The codegen_settings.json file tells the Sen code generator to mark the program property as checked. A checked property requires the object to implement programAcceptsSet(), which is called before any external set is applied. If it returns false, the new value is rejected. This lets you enforce invariants (for example: a running timer cannot have its program swapped out).
Implementation¶
We mark the program property as "checked" using the code generation settings:
Now that the property is "checked", we need to implement the following function:
bool programAcceptsSet(sen::Duration /*val*/) const override
{
if (getState() == RunningState::off)
{
std::cout << "Timer is off! Switch it on to start running." << std::endl;
return true;
}
std::cout << "Timer is running! cannot change the program." << std::endl;
return false;
}
How to run it¶
This will open a shell and tell Sen to instantiate the implementations in the my.tutorial bus.
You can set the initial timer seconds by:
Note that the timer will not start running until it is On. You can turn on / off the Timer by:
Once the timer is running, it is not possible to edit its program property until it reaches the end.
You would need to turn the timer off or wait until it times out.