Home Blog

A window AC without the app

My 12,000 BTU Midea window unit came with an iOS app. It worked, but required an account and cloud access, and did not show the overnight temperature history I wanted. Since the unit supports a documented LAN protocol on port 6444, I decided to build a web interface.

The setup uses a Python backend with one LAN connection to the unit, a browser interface updated through server-sent events, and SQLite for sensor history. After the initial pairing, control and logging work locally.

The protocol, and the part you cannot do locally

Midea units come in protocol versions. V2 is plaintext. V3 is encrypted and will only accept commands from a client holding a token and a key.

Midea’s cloud issues the token and key to an account bound to the appliance. I could not find a supported way to obtain them locally, so the initial setup still required the cloud.

Discovery itself needs no cloud. msmart-ng will identify a unit and tell you what it is:

protocol version: 3
  ip: 192.168.1.50
  port: 6444
  name: net_ac_111E
  device_type: 172

172 is 0xAC. The net_ac_… name is the same SSID the unit advertises when you put it in pairing mode.

The libraries ship with shared fallback accounts for fetching a token. Every one of them is rate-limited into uselessness and returns Code: 9999. Plan on using your own account.

The Apple sign-in dead end

I had used Sign in with Apple in the SmartHome app, so I did not have a password to supply to the cloud API.

One option is to find the relay address Apple gave the vendor under Settings → Apple ID → Sign in with Apple → the app. It is usually a …@privaterelay.appleid.com address. A password-reset email should be forwarded to the real inbox, allowing a password to be set on the account already bound to the unit.

The other option is to register an account with an email address and password, then pair the unit to it. Hold the pairing button until the net_ac_… network appears and add the unit through the app. This replaces the old binding, so the Apple-linked account will no longer see it.

One library note. msmart-ng ships a working SmartHomeCloud class — it even carries an explicit workaround for that cloud rejecting getToken with a 3004 unless you also pass the appliance ID — but its CLI only ever wires up NetHomePlusCloud. If your unit is registered to the SmartHome app, drive the token fetch yourself:

cloud = SmartHomeCloud(region, account=account, password=password)
await cloud.login()
for endian in ("little", "big"):
    udpid = Security.udpid(dev.id.to_bytes(6, endian)).hex()
    token, key = await cloud.get_token(udpid, dev.id)
    try:
        await dev.authenticate(token, key)   # prove it before saving
        return token, key
    except AuthenticationError:
        continue

The code tries both byte orders for the udpid derivation and verifies the credentials against the unit before saving them. A successful cloud response alone does not confirm that the token works.

Sharing a single device connection

The unit’s connection limit affected the rest of the design:

A Midea AC accepts one TCP connection. A second client gets ECONNRESET during authentication.

When this happens, previously working credentials begin failing during authentication. Before changing the keys, check whether another service instance or the phone app is holding the connection.

pgrep -af 'uvicorn main:app'
ss -tnp | grep 6444

Three consequences for the design. All device I/O goes behind a single asyncio lock. Rapid UI input is debounced into one command, so tapping + five times sends one write rather than five. And when the server sweeps the subnet looking for a unit that moved, it excludes the address it is already talking to — otherwise the diagnostic opens and slams a socket on the very connection it is trying to diagnose. I wrote that bug and then watched it make the problem worse.

Handling routine session drops

Even while being polled every 20 seconds, the unit closes its session roughly every two minutes. The library reconnects on the next request, so nothing is actually broken — but naively surfacing it means the UI flashes "Offline" every two minutes.

The fix is to ride out a few consecutive failures before believing it:

if self._fail_streak < _TRANSIENT_FAILURES:
    await asyncio.sleep(_TRANSIENT_RETRY)
    continue
self.connected = False    # only now is it worth telling anyone

During an eight-minute test, the connection reset about six times, while all 96 UI samples continued to report connected.

I tried recycling the socket every 120 seconds, but that only added reconnects. The unit still dropped the session on its own schedule, so I left proactive recycling disabled.

Matching the mock to the real device

I built a mock unit to develop the UI before pairing the real hardware. It helped test the interface, but its capability object differed from the library’s real object.

The real device stores its capability flags in a CapabilityManager. My mock stored a plain Flag. I expected both to support this test:

AC.Capability.ENERGY_STATS in dev._capabilities

except that on the real object it raises TypeError: argument of type 'CapabilityManager' is not a container or iterable. Every mock run passed. The first run against hardware crashed.

I switched to the public accessor, dev.capabilities_dict()["additional_capabilities"], which returns a list on both. I also changed the mock to match the real object’s interface. The original mock had accepted an operation that the actual library did not support.

The real unit also reports automatic fan speed as the raw value 102, rather than an enum member. Comparing it with "auto" left the UI with no selected speed. This model has neither a humidity sensor nor energy metering, so I hide those readings and charts based on the capabilities reported at connection time.

Chart interaction and axis bugs

An <svg> root only hit-tests where a child actually paints. I put pointermove on the chart's <svg> and the crosshair tooltip never fired, because the pointer was over empty plot area between the lines. Nothing is painted there, so nothing receives the event. The fix is a transparent capture layer:

<rect x="0" y="0" width="100%" height="100%" fill="none" pointer-events="all"/>

I verified the capture layer with elementFromPoint at ten positions across the plot. Those coordinates must be inside the viewport; I had to scroll the chart into view before testing.

Do not snap a chart's domain out to round tick values. The obvious "nice ticks" implementation extends the domain to the outermost tick, which for data spanning 68–90 gives you an axis of 60–100 and throws away a third of the plot height. Pad the data range instead and place ticks inside it.

Related: pick the tick count from the label format's width. Adding seconds to the time format for short ranges made every label wide enough to collide with its neighbour.

Uvicorn will not shut down while a stream is open

Restarting the service took 90 seconds and ended in a SIGKILL, leaving the unit stuck in stop-sigterm.

The cause is an ordering detail: uvicorn drains in-flight requests before running lifespan shutdown. An SSE endpoint looping on while True is an in-flight request forever, so it holds the process open until systemd's stop timeout fires.

My first fix was to set an asyncio.Event during lifespan shutdown and have the stream watch for it. That does not work, for exactly the reason above — by the time lifespan shutdown runs, uvicorn has already been waiting on the stream for a minute and a half. What works is capping the drain:

uvicorn ... --timeout-graceful-shutdown 5

With TimeoutStopSec=20 in the systemd unit as a backstop, shutdown fell from 90 seconds to about 6.

Kernel modules and a pending reboot

Installing Tailscale on the host, tailscaled refused to start and crash-looped 156 times:

modprobe tun failed: Module tun not found in /lib/modules/6.19.11-zen1-1-zen
tun.ko found on disk, but not for current kernel:
  /lib/modules/7.2.6-zen2-1-zen/kernel/drivers/net/tun.ko.zst

The kernel had been upgraded by pacman -Syu six minutes after boot. The upgrade removed the running kernel’s module tree, so it could no longer load tun. The same situation can affect other modules that were not loaded before the upgrade, including VirtualBox, ZFS, and some Wi-Fi drivers.

Rebooting into the installed kernel restored module loading.

HTTPS on a phone, without a CA profile

Over plain HTTP, iOS labels the page "not secure" every time. A self-signed certificate is worse — you install a profile on the phone and manually trust it in Certificate Trust Settings.

Tailscale solves this in two commands, and gives you off-LAN access at the same time:

# admin console -> DNS -> Enable HTTPS
sudo tailscale serve --bg 8464

That publishes the local port at https://<host>.<tailnet>.ts.net with a real Let's Encrypt certificate, scoped to the tailnet rather than the public internet, renewed automatically. iOS trusts it out of the box. Add to Home Screen and it behaves like the app it replaced.

Do disable key expiry on the machine in the admin console. The default node key lasts 180 days, after which a headless box quietly drops off the tailnet.

Worth it?

The finished UI shows the controls and sensors this model supports and logs temperature to SQLite. I can check what the room did overnight and control the unit from my phone, both at home and over Tailscale.

After pairing, the AC control traffic stays between the local server and the unit.

Most of the debugging was in the surrounding software: the mock’s interface, SVG pointer events, SSE shutdown, and a kernel upgrade waiting for a reboot. The AC protocol itself was a relatively small part of the work.