Skip to content

Listeners and Polling

Niklas Linz edited this page Oct 3, 2026 · 1 revision

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

What polling does

  • 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.

When listeners are called

A listener gets a fresh snapshot

  • after every refresh(),
  • after every command,
  • when the unit pushes a change,
  • once with isAvailable() == false when the unit stops answering.

removeListener() unregisters one.

Threads

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.

Example: simple thermostat

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

Clone this wiki locally