Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/build-github.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ jobs:
- name: 2) Setup .NET SDK
uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x' # Change to your target version
# Match the target frameworks in Directory.Build.props.
dotnet-version: |
10.0.x
11.0.x

# 3. Restore dependencies
- name: 3) Restore dependencies
Expand Down
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFrameworks>net10.0;net11.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>

<AssemblyVersion>2.4.1</AssemblyVersion>
<AssemblyVersion>2.4.2</AssemblyVersion>

<BaseOutputPath>../../output/$(MSBuildProjectName)</BaseOutputPath>
<Deterministic>true</Deterministic>
Expand Down
3 changes: 2 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<!--<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>-->
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Lite.EventIpc" Version="1.3.2" />
<PackageVersion Include="DryIoc" Version="5.4.3" />
<PackageVersion Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="5.0.0-1.25277.114" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.1" />
Expand All @@ -21,4 +22,4 @@
<PackageVersion Include="MSTest.TestFramework" Version="4.0.2" />
-->
</ItemGroup>
</Project>
</Project>
20 changes: 10 additions & 10 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ _Thread safe and most customizations can be set on-the-fly!_
* Allows users to hook to external messaging services (TCP/IP, RabbitMQ, DBus, etc.)
* State Transition Triggers:
* Transitions are triggered by setting the context's next state result:
* On Success: `context.NextState(Result.Ok);`
* On Success: `context.NextState(Result.Success);`
* On Error: `context.NextState(Result.Error);`
* On Failure: : `context.NextState(Result.Failure);`
* State Handlers:
Expand Down Expand Up @@ -115,7 +115,7 @@ public class BasicState1() : BaseState
public async Task OnEnter(Context<BasicStateId> context)
{
await Task.Yield(); // Your async work here...
context.NextState(Result.Ok);
context.NextState(Result.Success);
}
}

Expand All @@ -124,7 +124,7 @@ public class BasicState2() : BaseState
public Task OnEnter(Context<StateId> context)
{
// Notice, we did not async/await this method
context.NextState(Result.Ok);
context.NextState(Result.Success);
return Task.CompletedTask;
}
}
Expand All @@ -133,7 +133,7 @@ public class BasicState3() : BaseState
{
public Task OnEnter(Context<StateId> context)
{
context.NextState(Result.Ok);
context.NextState(Result.Success);
return Task.CompletedTask;
}
}
Expand Down Expand Up @@ -190,7 +190,7 @@ public class Composite_State1() : BaseState
var cnt = context.ParameterAsInt(ParameterType.Counter);
var blank = context.ParameterAsBool(ParameterType.DummyBool);

context.NextState(Result.Ok);
context.NextState(Result.Success);
return Task.CompletedTask;
}
}
Expand All @@ -200,14 +200,14 @@ public class Composite_State2() : BaseState
public override Task OnEnter(Context<CompositeL1StateId> context)
{
// Signify we're ready to go to sub-states
context.NextState(Result.Ok);
context.NextState(Result.Success);
return Task.CompletedTask;
}

public override Task OnExit(Context<CompositeL1StateId> context)
{
// Signify we're ready to go to next state after composite
context.NextState(Result.Ok);
context.NextState(Result.Success);
return Task.CompletedTask;
}
}
Expand All @@ -219,7 +219,7 @@ public class Composite_State2_Sub1() : BaseState
// Safely add/update key-value in Context
context.Parameters.SafeAdd("StringBasedParamKey", SUCCESS);

context.NextState(Result.Ok);
context.NextState(Result.Success);
return Task.CompletedTask;
}
}
Expand All @@ -228,7 +228,7 @@ public class Composite_State2_Sub2() : BaseState
{
public override Task OnEnter(Context<CompositeL1StateId> context)
{
context.NextState(Result.Ok);
context.NextState(Result.Success);
return Task.CompletedTask;
}
}
Expand All @@ -237,7 +237,7 @@ public class Composite_State3() : BaseState
{
public override Task OnEnter(Context<CompositeL1StateId> context)
{
context.NextState(Result.Ok);
context.NextState(Result.Success);
return Task.CompletedTask;
}
}
Expand Down
145 changes: 143 additions & 2 deletions samples/Sample05.CommandStates/Program.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,153 @@
// Copyright Xeno Innovations, Inc. 2026
// See the LICENSE file in the project root for more information.

using Lite.StateMachine;

namespace Sample05.CommandStates;

/// <summary>
/// Demonstrates command states that request simulated device actions and wait
/// for their results in OnMessage before choosing the next state.
/// </summary>
/// <remarks>
/// State1 connects successfully;
/// State2 deliberately fails to start the device;
/// State3 recovers by closing its safety door;
/// State4 simulates a sensor error;
/// and State5 cleans up and disconnects.
///
/// Console output explains each action, result, and transition
/// through the success, failure, and error paths.
///
/// All states and the simulated worker are defined in this file; no hardware is required.
/// </remarks>
internal class Program
{
private static void Main(string[] args)
private enum StateId
{
State1,
State2,
State3,
State4,
State5,
}

private static async Task Main()
{
Console.WriteLine("Command states: perform actions and follow their results.");
Console.WriteLine("Expected: State1 --Success--> State2 --Failure--> State3 --Success--> State4 --Error--> State5.");
var events = new EventAggregator();

// A stand-in for a device or application service. Failures are deliberate
// so every run demonstrates success, expected failure, and error handling.
using var worker = events.Subscribe(message =>
{
if (message is not ActionCommand command)
return;

var result = command.State switch
{
StateId.State2 => Result.Failure,
StateId.State4 => Result.Error,
_ => Result.Success,
};
Console.WriteLine($" Worker: {command.Action} => {result}");
events.Publish(new ActionCompleted(command.State, result));
},
typeof(ActionCommand));

var machine = new StateMachine<StateId>(eventAggregator: events)
.RegisterState<State1>(StateId.State1, onSuccess: StateId.State2)
.RegisterState<State2>(StateId.State2, onFailure: StateId.State3)
.RegisterState<State3>(StateId.State3, onSuccess: StateId.State4)
.RegisterState<State4>(StateId.State4, onError: StateId.State5)
.RegisterState<State5>(StateId.State5);

using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await machine.RunAsync(StateId.State1, cancellation.Token);

if (machine.Context.CurrentStateId != StateId.State5 ||
!machine.Context.ParameterAsBool("Completed"))
{
throw new InvalidOperationException("The sample did not complete its expected actions.");
}

Console.WriteLine("Done: success, failure recovery, and error cleanup were demonstrated.");
}

private sealed record ActionCommand(StateId State, string Action);

private sealed record ActionCompleted(StateId State, Result Result);

// Shared command plumbing; each numbered state below defines its action.
private abstract class CommandState : ICommandState<StateId>
{
public IReadOnlyCollection<Type> SubscribedMessageTypes => [typeof(ActionCompleted)];

protected abstract string Action { get; }

public Task OnEnter(Context<StateId> context)
{
Console.WriteLine($"{context.CurrentStateId}: requesting '{Action}'. Waiting for ActionCompleted in OnMessage.");
context.EventAggregator!.Publish(new ActionCommand(context.CurrentStateId, Action));

// Returning from OnEnter does not advance a command state.
// OnMessage must call NextState after receiving the action's result.
return Task.CompletedTask;
}

public Task OnEntering(Context<StateId> context) => Task.CompletedTask;

public Task OnExit(Context<StateId> context)
{
Console.WriteLine($"{context.CurrentStateId}: exiting.");
return Task.CompletedTask;
}

public Task OnMessage(Context<StateId> context, object message)
{
if (message is ActionCompleted completed && completed.State == context.CurrentStateId)
{
Console.WriteLine($"{context.CurrentStateId}.OnMessage: action returned {completed.Result}.");
if (context.CurrentStateId == StateId.State5 && completed.Result == Result.Success)
context.Parameters["Completed"] = true;

context.NextState(completed.Result);
}

return Task.CompletedTask;
}

public Task OnTimeout(Context<StateId> context)
{
Console.WriteLine($"{context.CurrentStateId}: no action result arrived; ending with Error.");
context.NextState(Result.Error);
return Task.CompletedTask;
}
}

private sealed class State1 : CommandState
{
protected override string Action => "Connect to the device (success expected)";
}

private sealed class State2 : CommandState
{
protected override string Action => "Start the device while its safety door is open (failure expected)";
}

private sealed class State3 : CommandState
{
protected override string Action => "Recover from State2's failure by closing the safety door (success expected)";
}

private sealed class State4 : CommandState
{
protected override string Action => "Read a sensor with a simulated communication fault (error expected)";
}

private sealed class State5 : CommandState
{
Console.WriteLine("Coming Soon!");
protected override string Action => "Clean up after State4's error and disconnect (success expected)";
}
}
6 changes: 5 additions & 1 deletion samples/Sample05.CommandStates/Sample05.CommandStates.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
Expand All @@ -7,4 +7,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="../../source/Lite.StateMachine/Lite.StateMachine.csproj" />
</ItemGroup>

</Project>
30 changes: 28 additions & 2 deletions samples/Sample05.CommandStates/readme.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
# Sample 05 - Command States

_Coming Soon_
All states (`State1` through `State5`), messages, and the simulated worker are in
`Program.cs`. Each state implements `ICommandState<StateId>` through a small shared
`CommandState` base class that handles subscriptions, results, and timeouts.

See, Unit Tests, for an example of how to use Command States for now.
Run from the repository root:

```powershell
dotnet run --project samples/Sample05.CommandStates --framework net10.0
```

| State | Intended action | Result | Next state |
| --- | --- | --- | --- |
| State1 | Connect to a device | Success | State2 |
| State2 | Try starting with the safety door open | Failure | State3 |
| State3 | Recover by closing the door | Success | State4 |
| State4 | Read a sensor with a simulated communication fault | Error | State5 |
| State5 | Clean up and disconnect | Success | End |

`OnEnter` publishes an `ActionCommand` to a simulated device service using the
built-in event aggregator. The service prints its action and publishes an
`ActionCompleted` result. The active state's `OnMessage` checks the state ID and
calls `context.NextState(result)` to select `onSuccess`, `onFailure`, or `onError`.
Returning from `OnEnter` alone does not advance a command state.

The worker deliberately returns `Failure` for State2 and `Error` for State4 so
every run demonstrates all three outcomes. No hardware or external service is
required. Each state logs its request, received result, and exit. Missing results
use the machine's default command timeout; the executable also has a ten-second
cancellation guard and verifies that cleanup completed.
Loading
Loading