Skip to content

Migration 4.0

Sergey Brutsky edited this page Dec 3, 2026 · 2 revisions

Migration to MiHomeLib 4.0

MiHomeLib 4.0 is an asynchronous-only, nullable-aware release. Constructors no longer touch the network, information reads are explicit, and value-change events carry a ValueChange<T>. Every change described here was already marked obsolete or announced in 3.5.0.

Migration order

  1. Update to 3.5.0 and remove its warnings. Build with TreatWarningsAsErrors enabled and replace every MIHOME0001/CS0618 call. This keeps the migration reviewable while the old members are still available.
  2. Update constructors and information reads. Pass Gateway2Options/MqttGatewayOptions/MiioDeviceOptions, call await gateway.ConnectAsync() or await gateway.DiscoverDevicesAsync(), and replace the removed information properties with await GetInfoAsync().
  3. Update event handlers. Value-change events now receive ValueChange<T> instead of a previous value, a new value, or nothing.
  4. Handle nullable references. GetDeviceById, LastTimeMessageReceived, Sid, Ip and the optional option properties are nullable in 4.0. Turn on nullable analysis in the consuming project and check the results.

B1. Obsolete and synchronous members are removed

Step B1 removed 354 public API entries that 3.5.0 marked obsolete, including all 272 synchronous methods.

3.x 4.0
PowerOn(), PowerOff(), ToggleState(), SetMode(...) and the other synchronous device methods The matching ...Async method with an optional CancellationToken
GetStatus(), GetPowerState(), GetMode() and the other synchronous getters GetStatusAsync(), GetPowerStateAsync(), GetModeAsync()
StatusLeft/StatusRight strings on AqaraDualWallSwitch LeftChannel/RightChannel of type SwitchChannelState
Status strings on door/window sensors and buttons Contact of type DoorWindowContactState, or LastClick
MotionDate (local time) MotionDateUtc; use MotionDateUtc?.ToLocalTime() for display
GetDeviceByDid<T>(did) GetDeviceById<T>(deviceId)
gateway.SetLoggerFactory(...) LoggerFactory in the options object, or MiHomeLogging.SetLoggerFactory(...)
SensivityState, SensivityMode, SetSensivityAsync, OnSmokeSensivityModeChanged SensitivityState, SensitivityMode, SetSensitivityAsync, OnSmokeSensitivityModeChangedAsync
AqaraOppleTwoButtonsWirelesSwitch, AqaraOppleFourButtonsWirelesSwitch AqaraOppleTwoButtonsWirelessSwitch, AqaraOppleFourButtonsWirelessSwitch
Sound.PoliceСar1/PoliceСar2 (Cyrillic С) Sound.PoliceCar1/PoliceCar2 (ASCII C)
DecodeMacAddress and IMiioTransport.SendMessageRepeated Internal; use the public discovery and command methods
Long gateway constructors with port, loggerFactory, gatewaySid or endMarker The short constructor or the options constructor
Static DiscoverDevices() on XiaomiRobotVacuumCleanerV1/XiaomiAirHumidifierV1 MiioDiscovery.DiscoverAsync(...)
// doc:skip — 3.x code, intentionally does not compile against 4.0
var plug = gateway.GetDeviceByDid<XiaomiMiSmartPowerPlugCN>(did);
plug.PowerOn();
Console.WriteLine(gateway.FirmwareVersion);
await using var gateway = new MultimodeGateway(new MqttGatewayOptions
{
    Ip = ip,
    Token = token,
    Did = did,
});
await gateway.DiscoverDevicesAsync();
var plug = gateway.GetDeviceById<XiaomiMiSmartPowerPlugCN>(did);
if (plug is not null)
    await plug.PowerOnAsync();
var firmware = (await gateway.GetInfoAsync()).FirmwareVersion;
Console.WriteLine(firmware);

B2. Inheritance is closed; MiotGenericDevice is the extension point

All concrete devices and gateways are sealed. GatewaySubDeviceBase, ProtocolMappedDeviceBase, LumiBatteryDeviceBase, MotionSensorBase, WindowDoorSensorBase, AqaraOppleWirelessSwitch, MqttGatewayBase, MultimodeGateway2Base and MiioDevice no longer expose protected members. IMiioTransport, IMqttTransport, IDevicesDiscoverer and the discovery info types became internal.

MiotGenericDevice is now abstract and the only supported base class for custom MIoT devices. Its protected contract is exactly:

// doc:skip — protected contract shown as a signature list
public abstract class MiotGenericDevice : MiioDevice
{
    protected MiotGenericDevice(MiioDeviceOptions options);
    protected ILogger Logger { get; }
    protected Task<string> GetPropertyAsync(int siid, int piid, CancellationToken cancellationToken = default);
    protected Task<T> GetPropertyAsync<T>(int siid, int piid, Func<string, T> parse, CancellationToken cancellationToken = default);
    protected Task SetPropertyAsync<T>(int siid, int piid, T value, CancellationToken cancellationToken = default);
    protected Task CallActionAsync(int siid, int aiid, IReadOnlyList<object> arguments, CancellationToken cancellationToken = default);
}
3.x 4.0
Public MiotGenericDevice(string did, IMiioTransport transport, int initialId) protected MiotGenericDevice(MiioDeviceOptions options)
GetMiotProperty, SetMiotProperty, CallMiotAction synchronous helpers GetPropertyAsync, SetPropertyAsync, CallActionAsync
Arbitrary objects serialized through reflection Primitives, strings, enums, JsonNode, arrays and dictionaries of those; other objects throw NotSupportedException
Custom device could use the logger, DID, transport and internal request builders Logger and the four request methods above
// doc:skip — 3.x code, intentionally does not compile against 4.0
public sealed class MyPlug : MiotGenericDevice
{
    public MyPlug(IMiioTransport transport) : base("", transport, 0) { }

    public bool GetPower() => bool.Parse(GetMiotProperty(2, 1));
}
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MiHomeLib;
using MiHomeLib.MiioDevices;

public sealed class MyPlug(MiioDeviceOptions options) : MiotGenericDevice(options)
{
    public Task<bool> GetPowerAsync(CancellationToken cancellationToken = default) =>
        GetPropertyAsync(2, 1, bool.Parse, cancellationToken);

    public Task SetPowerAsync(bool on, CancellationToken cancellationToken = default) =>
        SetPropertyAsync(2, 1, on, cancellationToken);
}

B3. Constructors make no network requests

MiotGenericDevice no longer sends miIO.info while initializing. MqttTransport no longer opens its socket in the constructor; MqttGatewayBase.ConnectAsync connects explicitly, and DiscoverDevicesAsync and the first publish connect on demand. XiaomiGateway2 keeps its existing deferred behaviour.

3.x 4.0
Long gateway constructors with connection parameters new MultimodeGateway(new MqttGatewayOptions { ... }), new XiaomiGateway2(new Gateway2Options { ... })
Constructor performs miIO.info, so FirmwareVersion, Hardware, Mac, Wifi and Network are filled immediately Constructor does nothing network-related; call await GetInfoAsync()
Constructor connects the MQTT socket; failures surface at construction Connection is made by the first operation; failures surface there
Task.Run(() => new Gateway(...)) to avoid blocking the UI thread Construct directly; the constructor returns immediately
No way to check the MQTT connection before discovery await gateway.ConnectAsync(cancellationToken)
XiaomiAirHumidifierV1.ToString() and XiaomiRobotVacuumCleanerV1.ToString() request the device state ToString() returns the model and address only; call await device.GetStatusAsync()
// doc:skip — 3.x code, intentionally does not compile against 4.0
using var gateway = new MultimodeGateway(ip, token, did, 1883, loggerFactory);
Console.WriteLine(gateway.FirmwareVersion);
await using var gateway = new MultimodeGateway(new MqttGatewayOptions
{
    Ip = ip,
    Token = token,
    Did = did,
});
await gateway.ConnectAsync();
var info = await gateway.GetInfoAsync();
Console.WriteLine(info.FirmwareVersion);
await gateway.DiscoverDevicesAsync();

MiioDeviceInfo contains Model, FirmwareVersion, Hardware, MiioVersion, Mac, UptimeSeconds, Wifi (Ssid, Bssid, Rssi, Frequency) and Network (Ip, Mask, Gateway). Each call asks the device again; nothing is cached except the text description of a MIoT device.

B4. Value-change events carry ValueChange<T>

The 33 value-change events listed in Appendix A of the refactoring plan changed from Func<T, Task> or Func<Task> to Func<ValueChange<T>, Task>. Event names and the conditions that raise them did not change. Action events such as OnClickAsync, OnVibrationAsync, OnAlarmAsync, OnDeviceDiscoveredAsync and OnConnectionLostAsync keep their old arguments.

using System;

public readonly record struct ValueChange<T>(T Previous, T Current, DateTime TimestampUtc);
3.x 4.0
OnTemperatureChangeAsync is Func<float, Task> and passes the previous value Func<ValueChange<float>, Task>; change.Previous, change.Current, change.TimestampUtc
OnStateChangeAsync on the plug is Func<Task>; the new state is read from State Func<ValueChange<PlugState>, Task>
OnContactChangedAsync is Func<Task>; the state is read from Contact Func<ValueChange<DoorWindowContactState>, Task>
OnSwitchChannelLeftAsync passes a string Func<ValueChange<SwitchChannelState>, Task>
OnChannel1StateChangeAsync is Func<Task> Func<ValueChange<ChannelState>, Task>
DeviceEvent.Arguments carries a raw value or nothing for those events Carries exactly one ValueChange<T>; use Arguments.LastOrDefault() is ValueChange<T> change
OnAvailabilityChangedAsync is Func<bool, Task> Func<ValueChange<bool>, Task>; the transition out of null still raises no event
// doc:skip — 3.x code, intentionally does not compile against 4.0
sensor.OnTemperatureChangeAsync += previous =>
{
    Console.WriteLine($"{previous} -> {sensor.Temperature}");
    return Task.CompletedTask;
};
await using var gateway = new XiaomiGateway2(ip, token);
await gateway.DiscoverDevicesAsync();
var sensor = gateway.GetDeviceById<XiaomiTemperatureHumiditySensor>(did);
if (sensor is null)
    return;

sensor.OnTemperatureChangeAsync += change =>
{
    Console.WriteLine($"{change.Previous} -> {change.Current} at {change.TimestampUtc:O}");
    return Task.CompletedTask;
};

B5. CancellationToken in every asynchronous method

Every public method returning Task, Task<T> or ValueTask now ends with CancellationToken cancellationToken = default, except DisposeAsync. The 3.x overload pairs were merged.

3.x 4.0
DiscoverDevicesAsync() and DiscoverDevicesAsync(CancellationToken) One DiscoverDevicesAsync(CancellationToken cancellationToken = default)
GetInfoAsync() and GetInfoAsync(CancellationToken) One GetInfoAsync(CancellationToken cancellationToken = default)
GetDeviceIdByIpAsync(string) and the token overload GetDeviceIdByIpAsync(string ip, CancellationToken cancellationToken = default)
MiioDiscovery.DiscoverAsync(TimeSpan?) and the token overload DiscoverAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Fire-and-forget Zigbee/Gateway 2 commands ignore cancellation The token is checked before sending; the command may still be on the wire when cancellation is observed
// doc:skip — 3.x code, intentionally does not compile against 4.0
await plug.PowerOnAsync();
await gateway.DiscoverDevicesAsync();
var plug = new XiaomiSmartPlug2Euro(ip, token);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await plug.TurnOnAsync(cts.Token);

B6. Collections, radio channels and typed channel states

3.x 4.0
List<GatewaySubDeviceBase> GetDevices() IReadOnlyList<GatewaySubDeviceBase> GetDevices(); copy with ToList() before modifying
XiaomiGateway2.RadioChannel mutable class with manual Equals public sealed record RadioChannel(int Id, string Url, int Type); equality includes Type
AqaraDualWallSwitch.OnSwitchChannelLeft/RightAsync pass a string Func<ValueChange<SwitchChannelState>, Task>
Callers can add or remove entries in the list returned by GetDevices() The list is read-only; copy it with ToList() before modifying
// doc:skip — 3.x code, intentionally does not compile against 4.0
List<GatewaySubDeviceBase> devices = gateway.GetDevices();
using System.Collections.Generic;

await using var gateway = new XiaomiGateway2(ip, token);
await gateway.DiscoverDevicesAsync();
IReadOnlyList<GatewaySubDeviceBase> devices = gateway.GetDevices();
var editable = devices.ToList();
var channels = await gateway.GetRadioChannelsAsync();

B7. Public API audit

Step B7 compared every entry of PublicAPI.Unshipped.txt with steps B1–B6. The 4.0 delta is 761 removed and 375 added entries; the remaining 101 additions are the 3.5.0 options and typed-state API that shipped earlier. No removal is unexplained.

3.x 4.0
The public API still contains every obsolete member and its replacement Obsolete members are removed; every removal is owned by B1–B6
PublicAPI.Unshipped.txt mixes the 3.5.0 baseline with the 4.0 changes The baseline is in PublicAPI.Shipped.txt; unshipped holds exactly the audited 4.0 delta
No machine-readable list of breaking changes The B1–B6 table below and the compatibility suppression file list them
Step Removed Added What changed
B1 354 20 Obsolete and synchronous API removed; Opple classes merged and renamed
B2 64 6 Inheritance closed, transports internal, MiotGenericDevice contract
B3 0 3 ConnectAsync, virtual/override GetInfoAsync
B4 67 76 ValueChange<T> events
B5 268 264 CancellationToken in every asynchronous method
B6 8 6 GetDevices() return type and the RadioChannel record
B1–B6 761 375
3.5.0 baseline (A1/A2/A2a) 0 101 Already shipped in 3.5.0
File total 761 476

Recompile against 4.0 and read the compiler errors as the authoritative list for the consuming project:

dotnet build -c Release

B8. Nullable reference types

The library builds with <Nullable>enable</Nullable> and nullable diagnostics as errors. Annotating the consuming project is optional, but recommended.

3.x 4.0
GetDeviceById<T> is oblivious; a missing device is null at run time Returns T?; check for null
LastTimeMessageReceived is DateTime? since 3.0 Unchanged, but now annotated
XiaomiGateway2.Sid, ProtoVersion and Ip are oblivious Sid?, ProtoVersion?, Ip? until the first heartbeat
Gateway2Options.GatewaySid, LoggerFactory, ReconnectDelays Nullable; Ip and Token are non-null and still validated in the constructor
GetInfoAsync() is assumed to succeed It returns MiioDeviceInfo or throws; the result is non-null
// doc:skip — 3.x code, intentionally does not compile against 4.0
var plug = gateway.GetDeviceById<XiaomiMiSmartPowerPlugCN>(deviceId);
plug.PowerOn();
await using var gateway = new XiaomiGateway2(ip, token);
await gateway.DiscoverDevicesAsync();
var plug = gateway.GetDeviceById<XiaomiMiSmartPowerPlugCN>(did);
if (plug is not null)
    await plug.PowerOnAsync();

Verification checklist

  • The solution builds with zero warnings against 4.0.
  • No call to a synchronous device method remains: search for MIHOME0001 after updating to 3.5.0, then rebuild against 4.0.
  • Every event handler reads change.Previous/change.Current instead of a separate argument.
  • Every GetDeviceById result is checked for null before use.
  • Every asynchronous call that can outlive the request receives the caller's CancellationToken.

See the 4.0 release notes and the worker service guide.

Clone this wiki locally