Repository navigation
Migration 3.0
Upgrade the package, update the affected namespaces and network operations, then review event handling and initial-state assumptions. The project targets .NET Framework 4.8.1, .NET Standard 2.0 and .NET 10. Release notes and breaking changes · Wiki home
- Replace
MiHomeLib.XiaomiGateway2.DevicesandMiHomeLib.MqttGateway.Devicesimports withMiHomeLib.Devices. - Use
GatewaySubDeviceBasefor a collection or callback containing different gateway devices. UseGetDeviceById<T>to look up a known concrete type. - Replace
XiaomiMultifunctionalGateway2withMiHomeLib.XiaomiGateway2.XiaomiGateway2. - Shared motion handling can use
MotionSensorBase, and window/door handling can useWindowDoorSensorBase. - Review concrete-type checks.
AqaraTemperatureHumiditySensorandXiaomiTemperatureHumiditySensorare separate types. Use two branches when handling both. UseWindowDoorSensorBaseto handle both Aqara and Xiaomi window/door sensors. - Many concrete device types are sealed. Adapt custom subclasses and code using the removed MQTT device base classes separately.
Public transport interfaces live alongside their domains. Use MiHomeLib.MiioDevices.IMiioTransport, MiHomeLib.MqttGateway.IMqttTransport and MiHomeLib.MqttGateway.Discovery.IDevicesDiscoverer. Code referring to removed MiHomeLib.Contracts types must use the corresponding surviving contract. Protocol registration, device adapters, action processors and packet parsing are internal implementation details. Replace client dependencies on removed response DTOs with application-owned models. The legacy Helpers class is removed.
Network reads and writes use methods. Gateway-device properties hold received state, while properties on status snapshots hold the values returned by that read.
Replace a network-property read such as purifier.Temperature with purifier.GetTemperature() or await purifier.GetTemperatureAsync(). Replace a write such as purifier.Mode = mode with purifier.SetMode(mode) or await purifier.SetModeAsync(mode).
For MijiaSmartSocket2China, XiaomiSmartPlug2Euro and XiaomiSmartAirPurifier4Lite, replace each removed network property Name with GetName() and, for writable values, SetName(value). Use GetPowerState() for the former IsTurnedOn property. Its former IsTurnedOnAsync() method becomes GetPowerStateAsync(). Each operation has an Async counterpart.
For XiaomiAirHumidifierV1, make these replacements in both sync and async code.
-
IsTurnedOnbecomesGetPowerState. -
PowerOnandPowerOffbecomeTurnOnandTurnOff. -
GetDeviceModebecomesGetMode. -
IsBuzzerOnbecomesGetBuzzerEnabled.BuzzerOnandBuzzerOffbecomeSetBuzzerEnabled(true)andSetBuzzerEnabled(false). -
IsChildLockOnbecomesGetChildLockEnabled.ChildLockOnandChildLockOffbecomeSetChildLockEnabled(true)andSetChildLockEnabled(false).
For XiaomiRobotVacuumCleanerV1, replace Home, Start, Stop and Spot with GoHome, StartCleaning, StopCleaning and StartSpotCleaning. The Async names change accordingly.
For XiaomiRobotVacuumMop3C, the old enum-returning GetStatus becomes GetState. GetStatus now returns a DeviceStatus snapshot. Replace GoCharging with GoHome, GetNoDisturbingSettings with GetDndSettings, and GetSweepConsumablesInfo with GetConsumables. Apply the same renames to Async methods.
XiaomiRobotVacuumX20Plus uses explicit methods for status, settings and actions. Review the method XML comments for value ranges and device-specific units.
Each property listed below becomes GetName() and SetName(value) with Async counterparts. Tuple types, enum types and wire formats are preserved.
- All MQTT gateways inherit
GetAccidentalDeletionEnabledandSetAccidentalDeletionEnabled. - AqaraHubE1China settings include
NightModeEnabled,NightModeEffectiveHours,HotspotModeEnabled,HotspotNameandHotspotPassword. Read clients withGetHotspotClientsorGetHotspotClientsAsync. - MultimodeGateway settings include
LedEnabled,ArmingModeandAlarmState. Existing Get/Set methods for arming delay, alarm duration and alarm volume gain Async versions. - MultimodeGateway2China and MultimodeGateway2Global inherit Get/Set methods for
AccessMode,DoNotDisturbModeEnabled,DoNotDisturbEffectiveTimeandLedIndicatorBrightness.
For example, replace gateway.NightModeEnabled = true with the following call.
using System.Threading.Tasks;
using MiHomeLib.MqttGateway;
public static class GatewaySettingsExample
{
public static async Task ConfigureAsync(AqaraHubE1China gateway)
{
await gateway.SetNightModeEnabledAsync(true);
await gateway.SetNightModeEffectiveHoursAsync(((byte)23, (byte)0, (byte)7, (byte)0));
}
}Replace LinqQuality with LinkQuality and OnBatteryPercentChange with OnBatteryPercentChangeAsync. Device state setters become private. Consume values through reports and events.
Value-change events generally pass the previous value. Read the current property at the beginning of the callback, especially before awaiting another operation. A later report can arrive while an async callback is still running. Some events fire for repeated reports, while state-transition events on particular devices fire only on changes. Follow the concrete event's XML contract. AqaraWaterLeakSensor.OnMoistureChangeAsync passes the new moisture state. Button and motion events carry their documented action or period.
using System;
using System.Threading.Tasks;
using MiHomeLib.Devices;
public static class TemperatureEventsExample
{
public static void Subscribe(XiaomiTemperatureHumiditySensor sensor)
{
sensor.OnTemperatureChangeAsync += previous =>
{
var current = sensor.Temperature;
Console.WriteLine($"Temperature changed from {previous} to {current} °C");
return Task.CompletedTask;
};
}
}Subscribe during OnDeviceDiscoveredAsync. Reports buffered during Zigbee initialization are delivered after the discovery callback finishes. Keep synchronous work short. Async event callbacks can overlap, and their exceptions are logged. Executing client callbacks must finish themselves after disposal.
For MQTT motion sensors, no-motion countdowns start when motion is processed, before invoking OnMotionAsync. A slow callback therefore no longer extends the configured periods. Repeated motion restarts the countdowns. The periods remain 60, 120, 180, 300, 600 and 1800 seconds.
GatewaySubDeviceBase.LastTimeMessageReceived changes from DateTime to DateTime?. It contains the library's UTC reception time. It is null until a device message arrives. LastMessageSourceTimeUtc separately records a source timestamp, when the message contains one. Source clocks can be inaccurate or move backwards.
using System;
using MiHomeLib.Devices;
public static class DeviceTimeExample
{
public static void Display(GatewaySubDeviceBase device)
{
var received = device.LastTimeMessageReceived;
Console.WriteLine(received.HasValue
? received.Value.ToLocalTime().ToString("O")
: "Awaiting the first device message");
}
}BLE devices can await broadcasts for initial measurements. Selected device descriptions display Unknown per field until a report supplies it. Their numeric properties can still contain default zero values. The device-level reception timestamp indicates that some message arrived, so consume field-specific events when establishing initial readings. Missing initial values on other devices can also retain defaults.
Keep gateway instances alive for the entire period of listening. Await DiscoverDevicesAsync, subscribe during discovery, then keep the application running until shutdown. Dispose the gateway at shutdown. Gateway2 discovery has a bounded wait for the hub and read retries for subdevices. Repeated discovery preserves known device objects. Discovery applies successfully read initial properties even if another property is unavailable.
Ordinary MQTT/Gateway2 command completion means transport submission. The device's properties are subsequently updated from reports. miio/MIoT methods validate their responses. A lost response to a nonrepeatable command leaves its outcome unknown. Read the state before choosing to resend an action.
For ZNCZ02LM and LLKZMK11LM, explicit confirmed power methods use a matching device write_ack through the built-in Lumi MQTT transport. The match includes the request ID, device, resource and value. A successful write_rsp alone leaves those methods waiting. Rejected writes fail, and timeout or connection loss means an unknown outcome. Writes are sent once. Unsupported custom transports throw NotSupportedException.
using System.Threading.Tasks;
using MiHomeLib.Devices;
public static class ConfirmedRelayExample
{
public static Task TurnOffAsync(AqaraDualWirelessRelayCN relay) =>
relay.SetChannel1StateConfirmedAsync(AqaraDualWirelessRelayCN.ChannelState.Off);
}The Aqara T1 hardware check returned write_rsp followed by an independently numbered state report. Its control methods currently provide transport submission semantics. A same-network Gateway2 check on firmware 1.4.1_176 found that write_ack could contain the preceding state and omitted an additional request id. The original state was verified through fresh reads after switching. Gateway2 subdevice methods provide transport-submission completion. Gateway2 hardware observations
Gateway2 write_ack errors are logged at Error level with the device SID. Successful ACKs are logged at Debug level, and their snapshots do not update device properties. A logged ACK failure can arrive after a control method has completed transport submission. ZNCZ02LM retains its last recognized power state on an unknown read status.
MQTT reconnects automatically. Subscribe to OnConnectionLostAsync and OnConnectionRestoredAsync for application diagnostics. Incoming queues are bounded. Overload can lose state reports and button actions. An affected discovery throws IOException and can be retried after addressing the overload. Initial reads can fail without preventing an otherwise valid device from being discovered.
The application owner runs the multi-day stabilization check in their own application.
- Build the application against 3.0, replace removed members and review concrete-type checks that still compile after the inheritance changes.
- Run normal automations for several days. Record the library version, hub model/firmware, uptime and discovery count. Observe memory after the initial warm-up and compare similar workloads.
- Temporarily interrupt network access to an MQTT hub in a controlled test. Confirm one loss/restoration sequence, recovery of reports and usable commands after reconnection.
- Repeat discovery and restart the application. Check for duplicate handlers, duplicated button actions and unexpected device replacement.
- Inspect warnings for queue overflow, unsupported resources and callback errors. Confirm initial BLE readings, UTC display and motion countdown behavior against the application requirements.
- Test Gateway2 discovery and representative device operations when the machine is on the hub's network. Record write acknowledgements separately before enabling confirmed Gateway2 commands.
- Run the release package consumer checks for Windows net481, Linux net8.0 and Linux net10.0. Record results before publishing.
Treat unexplained memory growth under steady load, repeated healthy-network reconnections, duplicate events or incorrect command completion as release blockers. Record experimental device functions explicitly. Once these checks pass and migration examples compile, freeze the public API and limit further changes to reproducible defects.