Class Switch
- Namespace
- HaMqttDiscoverable.Entities
- Assembly
- HaMqttDiscoverable.dll
A simple on/off control, e.g. a relay or a smart plug.
public sealed class Switch : HaEntity<SwitchConfig>, IAsyncDisposable
- Inheritance
-
Switch
- Implements
- Inherited Members
Examples
var mySwitch = new Switch(connection, new SwitchConfig
{
Name = "Relay",
UniqueId = "garage-relay",
Device = device,
});
mySwitch.CommandReceived += async isOn =>
{
SetRelay(isOn);
await mySwitch.PublishStateAsync(isOn);
};
await mySwitch.PublishDiscoveryAsync();
Constructors
Switch(HaMqttConnection, SwitchConfig, Func<bool, Task>?)
Creates a switch from the given config, optionally subscribing onCommand to CommandReceived.
public Switch(HaMqttConnection connection, SwitchConfig config, Func<bool, Task>? onCommand = null)
Parameters
connectionHaMqttConnectionconfigSwitchConfigonCommandFunc<bool, Task>
Properties
SupportsCommands
Whether this entity type accepts commands from Home Assistant (e.g. switches, numbers). Sensors are read-only and return false.
protected override bool SupportsCommands { get; }
Property Value
Methods
OnCommandReceivedAsync(string)
Called with the raw payload every time a message arrives on CommandTopic. Overridden by controllable entity types.
protected override Task OnCommandReceivedAsync(string payload)
Parameters
payloadstring
Returns
PublishStateAsync(bool, bool, CancellationToken)
Publishes the switch's current on/off state.
public Task PublishStateAsync(bool isOn, bool retain = true, CancellationToken cancellationToken = default)
Parameters
isOnboolretainboolcancellationTokenCancellationToken
Returns
Events
CommandReceived
Raised when Home Assistant sends a command to turn this switch on or off.
public event Func<bool, Task>? CommandReceived