Repository navigation
Listeners and Polling
For long-running use, like a dashboard, an MQTT bridge or home automation, let the client keep itself up to date.
MideaAirConditioner ac = new MideaAirConditioner(cfg);
ac.addListener(state -> {
if (!state.isAvailable()) {
log.warn("air conditioner not reachable");
return;
}
mqtt.publish("climate/livingroom/temperature", state.getIndoorTemperature());
});
ac.startPolling(Duration.ofSeconds(30));
// ...
ac.close(); // stops polling and disconnects- A full
refresh()at the interval you choose. - A heartbeat every 10 seconds in between, so the connection stays open.
- Changes the unit reports on its own (for example when someone uses the remote) are picked up between refreshes.
- After a failure, the client keeps trying to reconnect on every tick.
The polling thread is a daemon thread and doesn't keep the JVM alive. Calling startPolling() again replaces the running poller. stopPolling() stops it without closing the connection.
A listener gets a fresh snapshot
- after every
refresh(), - after every command,
- when the unit pushes a change,
- once with
isAvailable() == falsewhen the unit stops answering.
removeListener() unregisters one.
Listeners run on the thread that handled the update: your own thread for direct calls, the polling thread otherwise. Sending a command from inside a listener is fine. Hand anything slow to your own executor, otherwise it delays the next poll.
Cool to 25 degrees when the room gets warmer than 26, switch off below 23:
ac.addListener(s -> {
Double room = s.getIndoorTemperature();
if (!s.isAvailable() || room == null) return;
try {
if (room > 26 && !s.isPower()) {
ac.control().mode(OperatingMode.COOL).targetTemperature(25).send();
} else if (room < 23 && s.isPower()) {
ac.turnOff();
}
} catch (IOException e) {
System.err.println("command failed: " + e.getMessage());
}
});
ac.startPolling(Duration.ofSeconds(60));Next: Error handling
midea-ac · MIT License · Protocol based on midea-local · Not affiliated with Midea