State management
#
Get current stateNetDaemon keeps track of states in the background. Getting state is not doing a networking call. States are dynamic values calculated from origin value like double->int->bool->string... The "unavailable" state are null value of the State.
#
State changesThe API let you manage state very easy. This is based on the System.Reactive. I will only do basic things here but please read up on System.Reactive to learn the true power of this way of handling events.
Let´s start with a very basic example. If the motion sensors state turns to "on", turn on the light.light1
light. .
So what is going on here? First statement, Entity("binary_sensor.my_motion_sensor")
selects the entity you want track changes from. The Where(e.New?.State == "on")
tracks state changes for new events that are getting the state on
. And finally, Subscribe(e => Entity("light.light1").TurnOn()
subscribes to the changes and calls the code if the where clause is met. In this case it calls turn on service on the light entity. StateChanges
checks if the New.State != Old.State
. To get all changes including the attribute changes, please use StateAllChanges
instead of StateChanges
.
If the from
state is important then use it like:
Or even more advanced example. You can use any combination of state and attributes or even external methods in the lambda expressions. Here is an example: When sun elevation below 3.0 and not rising and old state elevation is above 3.0 then we should turn on light. This uses the StateAllChanges
since we want all changes to the elevation attribute.
#
Use the observable stream directlyThe Entity/Entities
notation is just a shortcut for the observable stream of state changes. You can use the observable directly. Like this example, selects all events where any entity is turned on.
#
Wait for state in blocking modeSometimes you want to control the flow in a blocking way to manage a sequence of events. Then we have the NDFirstOrTimeout
extension method on Observalbe.
The snippet below waits for the first occurence of binary_sensor.pir
to change any state but times out if it does not change state within 300ms. Remember that you cannot use blocking functions in Initialize function directly. In most cases that would not make sense anyway.
#
Set state of custom entitiesIt is possible to set state of entities that are not in Home Assistant. If the entity does not exist, Home Assistant will create it. Note that these are not real entities and they will not persist during restarts of HA.
#
Using AreasNetDaemon does match the area where the entity´s device is configured. This means it is very easy to do selections on what area that matches.
All binary sensors (PIRS) in the kitchen turn on the light: