Table of Contents

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

connection HaMqttConnection
config SwitchConfig
onCommand Func<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

bool

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

payload string

Returns

Task

PublishStateAsync(bool, bool, CancellationToken)

Publishes the switch's current on/off state.

public Task PublishStateAsync(bool isOn, bool retain = true, CancellationToken cancellationToken = default)

Parameters

isOn bool
retain bool
cancellationToken CancellationToken

Returns

Task

Events

CommandReceived

Raised when Home Assistant sends a command to turn this switch on or off.

public event Func<bool, Task>? CommandReceived

Event Type

Func<bool, Task>