Event
Larry now has his distance sensor sorted out, but he’s still clumsy. We’ll add two more sensors:
- A battery sensor that warns the system health monitor when juice is running low.
- A bump sensor that tattles when Larry walks into a wall.
This is where the event messaging pattern comes in. Instead of streaming values, a participant can send a one-off notification through a notifier port to another participant that is sleeping on a listener port. The listener wakes up only when something worth caring about happens.
In our case: low battery or wall collision. The health monitor reacts by lighting up the battery LED or going into a parking position.
Before diving into code, let’s clear up two terms:
- State: the current facts in memory (e.g. the battery is low or normal).
- Event: the notification that state changed.
If we hammer the listener with “battery low” notifications, it will still only see one event until it wakes up and resets the flag. This prevents events from being lost, but also means they don’t queue up like publish-subscribe messages. Order is undefined; you only know that at least once someone signaled a state change.
Notifier
As usual, everything begins with a node and a service, but this time we create an event service:
var Node := TNodeBuilder.New
.Create(TServiceType.Ipc)
.Value;
var Service := Node
.ServiceBuilder(TServiceName.Create('system_health_events').Value)
.Event
.OpenOrCreate
.Value;
Now we create the notifier port, which sends notifications:
We want to notify about two distinct things: wall collisions and low battery. So we define two event IDs:
Checking the sensors every second is good enough for health monitoring, so we send notifications only when something changes:
while (Node.Wait(TDuration.FromSecs(1)).HasValue) do
begin
if (BumpSensorWasActivated) then
Notifier.NotifyWithCustomEvent(WallWasHit).Value;
if (BatteryState < BatteryThreshold) then
Notifier.NotifyWithCustomEvent(BatteryIsLow).Value;
end;
Listener
On the other side, the listener is the participant waiting for the health events. First, create the node and open the event service:
var Node := TNodeBuilder.New
.Create(TServiceType.Ipc)
.Value;
var Service := Node
.ServiceBuilder(TServiceName.Create('system_health_events').Value)
.Event
.OpenOrCreate
.Value;
Now we create the listener port:
Each event maps to an action. We wrap that in a small closure:
var ReactToEvent :=
procedure(const AEvent: TEventActivation)
begin
if (AEvent.Id = BatteryIsLow) then
ActivateBatteryWarningLight;
if (AEvent.Id = WallWasHit) then
GoIntoParkingPosition;
end;
This participant doesn’t need to poll. It just blocks until an event arrives, then runs the handler for each pending notification: