Repository navigation
Worker Service
A long-running service can bridge Xiaomi/Aqara devices to MQTT or Home Assistant, send notifications, or feed a dashboard, including on a Raspberry Pi. Hosted services construct their gateways at startup, discover devices once, and dispose the gateways asynchronously on shutdown. Constructors in MiHomeLib 4.0 make no network requests, so they can run directly in ExecuteAsync without Task.Run.
dotnet new worker -n MyHome
cd MyHome
dotnet add package MiHomeLib --version 4.0.0Configure gateways in appsettings.json. Each entry binds directly to the MiHomeLib option objects:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"MiHomeLib": "Warning"
}
},
"MiHome": {
"Gateways": [
{
"Name": "home",
"Kind": "XiaomiGateway2",
"Gateway2": {
"Ip": "192.168.1.10",
"Token": "<32 hex characters>"
}
},
{
"Name": "hub",
"Kind": "MultimodeGateway",
"Mqtt": {
"Ip": "192.168.1.11",
"Token": "<32 hex characters>",
"Did": ""
}
}
]
}
}| Field | Required for |
|---|---|
Name |
Every gateway; identifies it in GatewayRegistry. |
Kind |
Every gateway: XiaomiGateway2, MultimodeGateway, MultimodeGateway2China, MultimodeGateway2Global, or AqaraHubE1China. |
Gateway2 |
XiaomiGateway2; binds to Gateway2Options (Ip, Token, optional GatewaySid, timeouts). |
Mqtt |
MQTT gateways; binds to MqttGatewayOptions (Ip, Token, Did, optional MqttPort and ReconnectDelays). |
Do not commit real gateway tokens. Use .NET user secrets or environment variables such as MiHome__Gateways__0__Gateway2__Token. See the Gateway Setup guide for how to obtain a token and prepare a gateway.
// doc:skip — one file of the multi-file sample; build samples/MiHomeWorkerService instead
using System.Collections.Generic;
using MiHomeLib;
namespace MiHomeWorkerService;
public enum GatewayKind
{
XiaomiGateway2,
MultimodeGateway,
MultimodeGateway2China,
MultimodeGateway2Global,
AqaraHubE1China,
}
/// <summary>
/// One entry of the "MiHome:Gateways" array. The connection settings are the library option
/// objects, so the configuration binds directly to their properties.
/// </summary>
public sealed class GatewayRegistration
{
public string Name { get; set; } = "";
public GatewayKind Kind { get; set; }
public Gateway2Options Gateway2 { get; set; } = new();
public MqttGatewayOptions Mqtt { get; set; } = new();
}
public sealed class MiHomeOptions
{
public List<GatewayRegistration> Gateways { get; set; } = new();
}// doc:skip — one file of the multi-file sample; build samples/MiHomeWorkerService instead
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MiHomeLib.Devices;
using MiHomeLib.MqttGateway;
using MiHomeLib.XiaomiGateway2;
namespace MiHomeWorkerService;
public sealed class GatewayRegistry
{
private readonly ConcurrentDictionary<string, IAsyncDisposable> _gateways = new(StringComparer.Ordinal);
public event Func<string, DeviceEvent, Task> OnDeviceEventAsync;
public IReadOnlyCollection<string> Names => _gateways.Keys.OrderBy(name => name, StringComparer.Ordinal).ToArray();
internal void Add(string name, IAsyncDisposable gateway)
{
if (!_gateways.TryAdd(name, gateway))
throw new InvalidOperationException($"A gateway named '{name}' is already registered.");
}
public XiaomiGateway2 GetXiaomiGateway2(string name)
{
var gateway = GetGateway(name);
return gateway as XiaomiGateway2 ??
throw new InvalidOperationException($"Gateway '{name}' is not a Xiaomi Gateway 2.");
}
public MqttGatewayBase GetMqttGateway(string name)
{
var gateway = GetGateway(name);
return gateway as MqttGatewayBase ??
throw new InvalidOperationException($"Gateway '{name}' is not an MQTT gateway.");
}
internal IAsyncDisposable[] GetAllGateways() => _gateways.Values.ToArray();
internal Task ForwardDeviceEventAsync(string name, DeviceEvent deviceEvent)
{
var handlers = OnDeviceEventAsync;
if (handlers is null) return Task.CompletedTask;
return Task.WhenAll(handlers.GetInvocationList()
.Cast<Func<string, DeviceEvent, Task>>()
.Select(handler => handler(name, deviceEvent)));
}
private IAsyncDisposable GetGateway(string name)
{
if (name is null || !_gateways.TryGetValue(name, out var gateway))
throw new KeyNotFoundException($"Gateway '{name}' was not found.");
return gateway;
}
}// doc:skip — one file of the multi-file sample; build samples/MiHomeWorkerService instead
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MiHomeLib;
using MiHomeLib.Devices;
using MiHomeLib.MqttGateway;
using MiHomeLib.XiaomiGateway2;
namespace MiHomeWorkerService;
public sealed class GatewayHostedService : BackgroundService
{
private readonly MiHomeOptions _options;
private readonly GatewayRegistry _registry;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger<GatewayHostedService> _logger;
public GatewayHostedService(IOptions<MiHomeOptions> options, GatewayRegistry registry,
ILoggerFactory loggerFactory, ILogger<GatewayHostedService> logger)
{
_options = options.Value;
_registry = registry;
_loggerFactory = loggerFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var startups = _options.Gateways.Select(gateway =>
InitializeGatewayAsync(gateway, stoppingToken));
await Task.WhenAll(startups).ConfigureAwait(false);
await Task.Delay(Timeout.Infinite, stoppingToken).ConfigureAwait(false);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken).ConfigureAwait(false);
await Task.WhenAll(_registry.GetAllGateways()
.Select(gateway => gateway.DisposeAsync().AsTask())).ConfigureAwait(false);
}
private async Task InitializeGatewayAsync(GatewayRegistration registration, CancellationToken stoppingToken)
{
IAsyncDisposable gateway = null;
try
{
stoppingToken.ThrowIfCancellationRequested();
gateway = CreateGateway(registration);
SubscribeToEvents(registration.Name, gateway);
await DiscoverDevicesAsync(gateway, stoppingToken).ConfigureAwait(false);
stoppingToken.ThrowIfCancellationRequested();
_registry.Add(registration.Name, gateway);
gateway = null;
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
if (gateway is not null) await gateway.DisposeAsync().ConfigureAwait(false);
}
catch (Exception exception)
{
_logger.LogError(exception, "Failed to initialize gateway '{GatewayName}'.", registration.Name);
if (gateway is not null)
{
try { await gateway.DisposeAsync().ConfigureAwait(false); }
catch (Exception disposalException)
{
_logger.LogError(disposalException, "Failed to dispose gateway '{GatewayName}' after initialization failed.", registration.Name);
}
}
}
}
private IAsyncDisposable CreateGateway(GatewayRegistration registration) =>
registration.Kind switch
{
GatewayKind.XiaomiGateway2 =>
new XiaomiGateway2(WithLogger(registration.Gateway2)),
GatewayKind.MultimodeGateway =>
new MultimodeGateway(WithLogger(registration.Mqtt)),
GatewayKind.MultimodeGateway2China =>
new MultimodeGateway2China(WithLogger(registration.Mqtt)),
GatewayKind.MultimodeGateway2Global =>
new MultimodeGateway2Global(WithLogger(registration.Mqtt)),
GatewayKind.AqaraHubE1China =>
new AqaraHubE1China(WithLogger(registration.Mqtt)),
_ => throw new ArgumentOutOfRangeException(nameof(registration.Kind), registration.Kind, "Unsupported gateway kind."),
};
private Gateway2Options WithLogger(Gateway2Options options) => new()
{
Ip = options.Ip,
Token = options.Token,
GatewaySid = options.GatewaySid,
DiscoveryTimeout = options.DiscoveryTimeout,
MiioResponseTimeout = options.MiioResponseTimeout,
LoggerFactory = _loggerFactory
};
private MqttGatewayOptions WithLogger(MqttGatewayOptions options) => new()
{
Ip = options.Ip,
Token = options.Token,
Did = options.Did,
MqttPort = options.MqttPort,
MiioResponseTimeout = options.MiioResponseTimeout,
ReconnectDelays = options.ReconnectDelays,
LoggerFactory = _loggerFactory
};
private void SubscribeToEvents(string name, IAsyncDisposable gateway)
{
if (gateway is XiaomiGateway2 gateway2)
{
gateway2.OnDeviceDiscoveredAsync += LogDiscoveredDeviceAsync;
gateway2.OnDeviceEventAsync += deviceEvent => _registry.ForwardDeviceEventAsync(name, deviceEvent);
}
else if (gateway is MqttGatewayBase mqttGateway)
{
mqttGateway.OnDeviceDiscoveredAsync += LogDiscoveredDeviceAsync;
mqttGateway.OnDeviceEventAsync += deviceEvent => _registry.ForwardDeviceEventAsync(name, deviceEvent);
}
else
{
throw new InvalidOperationException($"Unsupported gateway implementation '{gateway.GetType().FullName}'.");
}
}
private Task LogDiscoveredDeviceAsync(GatewaySubDeviceBase device)
{
_logger.LogInformation("Discovered {Device}", device.ToString());
return Task.CompletedTask;
}
private static Task DiscoverDevicesAsync(IAsyncDisposable gateway, CancellationToken cancellationToken) =>
gateway switch
{
XiaomiGateway2 gateway2 => gateway2.DiscoverDevicesAsync(cancellationToken),
MqttGatewayBase mqttGateway => mqttGateway.DiscoverDevicesAsync(cancellationToken),
_ => throw new InvalidOperationException($"Unsupported gateway implementation '{gateway.GetType().FullName}'."),
};
}The sample passes the library option objects to the gateway constructors and adds the logger factory in WithLogger. The startup loop no longer wraps construction in Task.Run, because 4.0 constructors only create protocol objects. DiscoverDevicesAsync opens the connection on first use; on MQTT gateways it also connects the broker and reads the local device tables.
// doc:skip — one file of the multi-file sample; build samples/MiHomeWorkerService instead
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MiHomeLib.Devices;
namespace MiHomeWorkerService;
public sealed class LeakNotifier : BackgroundService
{
private readonly GatewayRegistry _registry;
private readonly ILogger<LeakNotifier> _logger;
public LeakNotifier(GatewayRegistry registry, ILogger<LeakNotifier> logger)
{
_registry = registry;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_registry.OnDeviceEventAsync += HandleDeviceEventAsync;
try { await Task.Delay(Timeout.Infinite, stoppingToken).ConfigureAwait(false); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
finally { _registry.OnDeviceEventAsync -= HandleDeviceEventAsync; }
}
private Task HandleDeviceEventAsync(string gateway, DeviceEvent deviceEvent)
{
if (deviceEvent.Device is AqaraWaterLeakSensor &&
deviceEvent.EventName == nameof(AqaraWaterLeakSensor.OnMoistureChangeAsync) &&
deviceEvent.Arguments.LastOrDefault() is ValueChange<bool> { Current: true })
{
_logger.LogWarning("Water leak detected by {DeviceId} on gateway {Gateway}", deviceEvent.Device.DeviceId, gateway);
}
else if (deviceEvent.EventName == nameof(GatewaySubDeviceBase.OnAvailabilityChangedAsync) &&
deviceEvent.Arguments.LastOrDefault() is ValueChange<bool> { Current: false })
{
_logger.LogWarning("Device {DeviceId} is unavailable on gateway {Gateway}",
deviceEvent.Device.DeviceId, gateway);
}
// Replace the log call with your notification (Telegram, e-mail, MQTT).
return Task.CompletedTask;
}
}DeviceEvent arguments for value-change events carry one ValueChange<T> object. The leak notifier checks ValueChange<bool>.Current, and the availability check uses the same type instead of the 3.x raw bool argument.
// doc:skip — top-level statements; add this file to the project as Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MiHomeWorkerService;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.Configure<MiHomeOptions>(builder.Configuration.GetSection("MiHome"));
builder.Services.AddSingleton<GatewayRegistry>();
builder.Services.AddHostedService<GatewayHostedService>();
builder.Services.AddHostedService<LeakNotifier>();
builder.Build().Run();Inject GatewayRegistry into a hosted service or ASP.NET Core controller. The gateway exposes discovered devices by ID; use a capability interface when operating a device:
// doc:skip — one file of the multi-file sample; build samples/MiHomeWorkerService instead
var gateway = registry.GetMqttGateway("hub");
var plug = gateway.GetDeviceById<XiaomiMiSmartPowerPlugCN>("lumi.158d000000001234");
if (plug is ISwitchable switchable)
await switchable.TurnOnAsync(cancellationToken);All asynchronous methods accept an optional CancellationToken, including TurnOnAsync. Pass the request or stopping token through when the caller has one.
The host calls StopAsync on its hosted services during shutdown. The sample cancels in-progress discovery and calls DisposeAsync on every registered gateway. Awaiting asynchronous disposal lets gateway background loops stop and lets already-running event handlers return before the process exits.
The complete buildable sample is in samples/MiHomeWorkerService.