Search code examples
c#.netstate-machinestateless-state-machine

Stateless library - PermitIf usage with SetTriggerParameters<T>


How do I use PermitIf with SetTriggerParameters?

In this example I'm modelling a motor, which can go forward, backwards, or off (not moving). Forwards and backwards can be a double speed, so therefore I need SetTriggerParameters<double>. Setting the speed to 0, however, turns the motor off.

I wish to disallow being able to trigger TurnOnForwards or TurnOnBackwards with an argument of 0 - I want the TurnOff trigger to be explicitly the way to turn the motor off. Otherwise, you arrive at the situation where the current state is Forwards/Backwards but with a speed of 0.

This is the error I get:

CS1503 Argument 1: cannot convert from 'UserQuery.Triggers' to 'Stateless.StateMachine<UserQuery.State, UserQuery.Triggers>.TriggerWithParameters'

public enum State
{
    Off,
    Forwards,
    Backwards
}

public enum Triggers
{
    TurnOff,
    TurnOnForwards,
    TurnOnBackwards,
}

var machine = new StateMachine<State, Triggers>(State.Off);

var forwardsTrigger = machine.SetTriggerParameters<double>(Triggers.TurnOnForwards);
var backwardsTrigger = machine.SetTriggerParameters<double>(Triggers.TurnOnBackwards);

machine.Configure(State.Off)
    .PermitIf<double>(Triggers.TurnOnForwards, State.Forwards, (speed) => speed > 0) // error
    .PermitIf<double>(Triggers.TurnOnBackwards, State.Forwards, (speed) => speed < 0) // error
    .Permit(Triggers.TurnOnForwards, State.Forwards)
    .Permit(Triggers.TurnOnBackwards, State.Backwards);

machine.Configure(State.Forwards)
    .Permit(Triggers.TurnOnBackwards, State.Backwards)
    .Permit(Triggers.TurnOff, State.Off);

machine.Configure(State.Backwards)
    .Permit(Triggers.TurnOnForwards, State.Forwards)
    .Permit(Triggers.TurnOff, State.Off);


machine.Fire(Triggers.TurnOnForwards);
machine.Fire(Triggers.TurnOff);

machine.Fire(Triggers.TurnOnBackwards);
machine.Fire(Triggers.TurnOff);

Is this possible?


Solution

  • You've probably figured it out by now, but if you use the parameterized trigger it will compile:

        machine.Configure(State.Off)
            .PermitIf(forwardsTrigger, State.Forwards, (speed) => speed > 0) // no error 
            .PermitIf(backwardsTrigger, State.Forwards, (speed) => speed < 0) // no error
            .Permit(Triggers.TurnOnForwards, State.Forwards)
            .Permit(Triggers.TurnOnBackwards, State.Backwards);