Yearly Archives: 2026

When the AI Pod Steps Away from the MicroServer

I am not sure whether it was a flaw in the hardware design of the early LazyCat MicroServer or something else, but I ran into two hard drive failures in a short period of time. I do not know how the current MicroServer is, but the version I use is not easy to open for a drive replacement, and worse, two of the screws are stripped and will not come out at all. 😂 At first I tried to keep using the AI Pod only on my local network. Without the LazyCat MicroServer, I could not reach it from an external network at all, and leaving that much compute usable only at home felt like a real waste. So I had to find a way to access the AI Pod from outside without the LazyCat MicroServer.

This is not about walking away from LazyCat. The AI Pod is a LazyCat product too, and it works well for me. I still keep lzc-ai-agent running, and apps are still pulled from the LazyCat registry. I just do not want the AI Pod to depend on a MicroServer I can not open to replace the hard drive. And what if one day the newer LazyCat MicroServer makes replacing hard drives as easy as a Synology NAS? I might actually switch back to using it.

I wrote about Unconventional Usage of LazyCat MicroServer before, and back then that kind of tinkering felt like a lot of fun. The official AI app distribution and remote access are both managed through the MicroServer, which is a great all-in-one design in itself. But once the MicroServer goes down, the AI Pod instantly becomes a crippled device. So I had to loosely decouple them, so that when I am out, I can still reach the services on the AI Pod, such as Ollama, through the Cloudflare One client. This post records the whole process.

Anyway, back to the topic.

Why the AI Pod Depends on the MicroServer

Although the official docs clearly mention that the AI Pod and the MicroServer are two independent devices. The AI Pod comes with Ubuntu preinstalled. Plug in a keyboard, a mouse, and a monitor, and it is already a machine you can SSH into. I usually log in over Wi-Fi via SSH, and I can also attach a keyboard, a mouse, and a screen when needed.

Actually, they are not fully independent to each other because:

  1. The MicroServer is responsible for installing and distributing AI apps, and then lzc-ai-agent on the AI Pod pulls the images and starts the containers.
  2. Services are exposed through Traefik, usually with hostnames in the *-ai form.
  3. Remote access depends on the MicroServer’s built-in tunnel, rather than the AI Pod publishing an entry point itself.

So when the MicroServer has a problem, the local compute is still there, but both “remote access” and “managing apps through the MicroServer” are affected. Technically, the AI Pod can also be used as a standalone Ubuntu machine; you just have to set up the apps and the remote access yourself. 😂

What I Wanted

I set myself a fairly simple goal:

  1. Give the AI Pod a stable LAN IP, so I do not have to guess the address every time.
  2. Let the services I need listen on that IP. I will use Ollama as the example below; the same idea applies to other services.
  3. I built a Node.js portal myself, listening on Port 8088, to manage the various AI services running on the pod.
  4. For remote access, I no longer use the MicroServer’s hostnames. I reuse the cloudflared instance that already runs on the Synology NAS, and publish domains to these ports through a Cloudflare Tunnel. There is no need to install another copy of cloudflared on the AI Pod by reusing the cloudflared on the NAS.
  5. I keep lzc-ai-agent running, so the AI Pod can still pull images from the LazyCat registry.

The overall plan looks like this:

Cloudflare One client
        │
        │  include only ai.example.com and ollama.example.com
        ▼
Cloudflare Access (WARP device check first; otherwise email one-time PIN)
        │
        ▼
Cloudflare Tunnel (cloudflared runs on the NAS)
        │
        ├── ai.example.com      →  192.168.x.y:8088   portal
        └── ollama.example.com  →  192.168.x.y:11434  OllamaCode language: CSS (css)

The domains and IP addresses below are placeholders. Please replace them with your own.

Give the AI Pod a Stable LAN Address

I did not set the static address on the AI Pod itself. I reserved it in the router’s DHCP settings (some UIs call this DHCP Reservation, address binding, or MAC binding). The AI Pod still uses DHCP, but it always gets the same 192.168.x.y.

Keep lzc-ai-agent Running

The AI Pod is still a LazyCat product, so I leave lzc-ai-agent running on purpose. Without it, pulling images from the LazyCat registry will fail.

Decoupling here means no longer depending on the MicroServer for remote access, routing, and day-to-day management. It does not mean removing LazyCat software from the pod, so do not stop or disable this service. If you want to confirm that it is still running, you can use:

systemctl status lzc-ai-agentCode language: Bash (bash)

Check Ollama from the LAN

Ollama on the AI Pod runs in a Docker container. By default from the factory, LazyCat had already configured it to listen on all interfaces and to allow cross-origin requests from devices on the LAN:

services:
  ollama:
    image: registry.lazycat.cloud/catdogai/jetson-ollama:0.20.0
    environment:
      - OLLAMA_ORIGINS=*
      - OLLAMA_HOST=0.0.0.0
    ports:
      - 11434:11434Code language: YAML (yaml)

The image comes from LazyCat’s own registry, which is also why I leave lzc-ai-agent running: without it, pulling from that registry will fail. Because it already listens on 0.0.0.0 and publishes port 11434, the Tunnel on the NAS can reach the AI Pod directly. There is no need to change the listen address.

OLLAMA_ORIGINS=* allows cross-origin requests from any origin. In my case the remote entry point already sits behind Cloudflare, so this is acceptable; if you want tighter control, you can restrict this value.

So this step is only about verifying that it is reachable from the LAN:

curl http://127.0.0.1:11434
curl http://192.168.x.y:11434Code language: Bash (bash)

If everything is fine, both should return Ollama is running. I will not walk through every service below, and will keep using Ollama as the example.

Bring the Portal Up as Well

Since I can no longer use the MicroServer apps to manage the AI Pod, I had to build my own portal in Node.js to manage the various AI services running on it. It also runs in Docker on the AI Pod, and it uses network_mode: host, so it binds directly to host ports 8088 and 18081–18099. With restart: always, the Docker daemon brings it back up on boot.

My self-built AI Pod portal: hardware overview
My self-built AI Pod portal: hardware overview

The portal also has an Ollama Studio page for viewing and managing the models in Ollama:

Ollama Studio page (model names and digests blurred)
Ollama Studio page (model names and digests blurred)

The Compose file looks roughly like this:

services:
  aipod-portal:
    container_name: aipod-portal
    image: aipod-portal:latest
    restart: always
    network_mode: host
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /sys:/host/sys:ro
      - /proc:/host/proc:ro
      - /ssd:/ssd
      - /:/host/rootfs:roCode language: YAML (yaml)

Each of these mounts has its purpose: docker.sock is used to manage container stacks and read logs; /sys and /proc are mounted read-only so the portal can read live Orin GPU load, INA3221 power rails, fan RPM, and thermals; /ssd is used to read and write Compose configs and to scan local model blobs; / is mounted read-only at /host/rootfs to monitor root eMMC disk usage.

Mounting docker.sock gives the container root-equivalent control over Docker on the host, so this portal must never be exposed to the public Internet directly. That is what the Cloudflare section later on is for.

To start it, follow the logs, and restart it:

docker compose -f /ssd/aipod-portal/docker-compose.pod.yml up -d
docker logs -f aipod-portal
docker restart aipod-portalCode language: Bash (bash)

You can first confirm that the portal is alive on the pod and on the LAN:

curl -I http://127.0.0.1:8088
curl -I http://192.168.x.y:8088Code language: Bash (bash)

Publish Hostnames with Cloudflare Tunnel

For remote access, I did not install another cloudflared on the AI Pod. I reused the Tunnel that already runs on the Synology NAS. The NAS and the AI Pod are on the same LAN, so it is enough that the NAS can reach the corresponding ports on 192.168.x.y.

Note that I had already installed cloudflared on my NAS and the Tunnel was already running, so the steps below only add routes to an existing Tunnel. If you do not have a Tunnel yet, your steps will be a bit different from mine: first create a Tunnel and install cloudflared on a machine on your LAN (the NAS, the AI Pod, or any other always-on device) to connect it, then add the routes as described below.

In the Cloudflare dashboard, the steps are as follows (this is the path in the current documentation for the main dashboard):

  1. Open the Cloudflare dashboard, go to Networking → Tunnels, and open the Tunnel that is already running on the NAS. In my case there is no need to create a new one or to install another copy of cloudflared on the AI Pod.
  2. Open the Routes tab, select Add route, then select Published application.
  3. Fill in the first one as follows:
    • Subdomain: ai
    • Domain: choose example.com from the drop-down menu (replace this with your own domain)
    • Service URL: http://192.168.x.y:8088
  4. Select Add route.
  5. Repeat the same steps for the second one: set the subdomain to ollama, and set the Service URL to http://192.168.x.y:11434.
  6. After that, check the DNS records. For a domain fully hosted on Cloudflare, the corresponding proxied CNAME records are usually created automatically. Just confirm that ai.example.com and ollama.example.com are in the Proxied state. Leave any other published applications you already have as they are; they will stay in this list and will not affect each other.

If you usually work in the Zero Trust dashboard, you can also find the same Tunnel under Zero Trust → Networks → Connectors. That said, the current step-by-step instructions for adding a published application to an existing Tunnel are written against the Networking → Tunnels path above.

If you want to compare this with the shape of the configuration, those two entries in the dashboard are roughly equivalent to:

ingress:
  - hostname: ai.example.com
    service: http://192.168.x.y:8088
  - hostname: ollama.example.com
    service: http://192.168.x.y:11434
  - service: http_status:404Code language: YAML (yaml)

The last 404 rule is a catch-all, so unmatched requests are not forwarded to some random local service. It is usually kept automatically when you add hostnames in the dashboard, so you do not have to change it on purpose.

Access and the Cloudflare One Client

Pointing the domains over is not enough. Both entry points should sit behind Cloudflare Access. I used the same set of policies as my existing self-hosted apps. Each application gets two policies, and the order matters.

First, create an application for the portal:

  1. Go to Zero Trust → Access controls → Applications, then select Create new application.
  2. Choose Self-hosted and private, then select Add public hostname.
  3. In the Domain drop-down menu, select your domain and fill in the subdomain so that you get ai.example.com. You can name the application whatever you like, for example ai.
  4. I set a fairly long Session Duration (730 hours).
  5. Under Access policies, add the first policy, named for example WARP:
    • Set the action to Service Auth
    • In Include, choose Device posture or Warp, requiring the device to have passed the Cloudflare One Client check
  6. Add the second policy, named for example Allow Me Only:
    • Set the action to Allow
    • In Include, choose Emails and add your own email addresses
  7. Select Create. Then repeat the same steps to create another application for ollama.example.com, keeping the two policies the same and only changing the domain to the Ollama one.

The idea is simple: a device that is already connected to the Cloudflare One client can go through directly; otherwise it falls back to an email OTP.

Then set up split tunneling on the client, so that only these two hostnames go through the tunnel:

  1. Go to Zero Trust → Team & Resources → Devices → Device profiles → General profiles.
  2. Locate the profile you actually use and select Configure.
  3. Find Split Tunnels and set the mode to Include IPs and Domains.
  4. Select Manage, and add only the hostnames that should go through Cloudflare, for example:
    • ai.example.com
    • ollama.example.com
  5. Save the profile (Save profile), then reconnect the Cloudflare One client once, so the new include list takes effect.

This way the client does not send all traffic from the device into the tunnel; it only forwards these two hostnames.

For clients that talk to the Ollama / OpenAI-compatible API, change the address to https://ollama.example.com and do not add a port. If the app expects the OpenAI-compatible path, keep /v1. These apps cannot complete the email PIN login by themselves, so they only work while the Cloudflare One client is on. If you later have an app that must reach Ollama with the client off, you can create a separate Access service token for it.

How to Confirm It Works

I checked in this order, from near to far:

  1. On the AI Pod itself: curl http://127.0.0.1:11434 and curl -I http://127.0.0.1:8088 both looked fine.
  2. From another machine on the LAN, I repeated the same checks against both ports on 192.168.x.y, to confirm that other devices on the same network (including the NAS that runs the Tunnel) can reach them directly.
  3. It is also worth curling the same addresses from the NAS, to confirm that the NAS running the Tunnel can reach the AI Pod. This step is often skipped, and it becomes hard to debug later if the public hostnames do not work.
  4. With the Cloudflare One client off, visiting https://ai.example.com from an external network redirects to the Access login page.
  5. With the client on, the portal opens directly, and https://ollama.example.com works as well.

I have tested step 5 from an external network: with the Cloudflare One client on, both the portal and Ollama already work end to end.

A Few Issues Worth Noting

The default device profile sends all traffic into the tunnel. As mentioned above, use Include mode for these hostnames, and make sure your device matches that profile. Do not fall through to a profile whose exclude list is empty.

Alright, that’s all for now. The MicroServer’s out-of-the-box experience is indeed convenient, but the AI Pod itself is already a complete Ubuntu machine. Once the address is stable, the services listen on the LAN, and the existing Tunnel publishes the hostnames, I can keep using my own compute without depending on the MicroServer. I still leave lzc-ai-agent running, so the AI Pod can pull images from the LazyCat registry. This setup is already working for me from outside. Hopefully this post can help a little for anyone who is also figuring out how to run the AI Pod without the MicroServer.

Keeping Xiaomi Doorbell Videos Forever with Home Assistant and Xiaomi Miot Auto

Recently I got a Xiaomi Smart Doorbell 3S. This doorbell is quite interesting! It doesn’t support local storage, and all the videos are kept only in Xiaomi Cloud. The problem is that, without a cloud subscription, Xiaomi Cloud only keeps the videos from the last 72 hours and then deletes them.

To save battery, the doorbell stays asleep most of the time. It only wakes up and records in three cases:

  1. Someone is detected at the door
  2. Someone presses the doorbell
  3. Someone tries to forcibly remove the doorbell

So keeping the videos only in the cloud is a fairly good compromise between saving battery and letting users check the videos at any time. If the videos were stored locally, users couldn’t watch them while the doorbell is asleep. And because the doorbell sleeps, it obviously doesn’t provide RTSP or ONVIF for 24/7 continuous recording either. As it happens, Synology Surveillance Station only came with two free camera licenses on my NAS, and both are already used by my two cameras.

Before ordering it, I thought Home Assistant, with its huge community, would already have an integration that keeps the doorbell videos. After it arrived, I found that Xiaomi Miot Auto, the integration I use to manage my Xiaomi Home devices, doesn’t support this at all 😅.

If you want something done, do it yourself. My basic idea was to use Home Assistant and Xiaomi Miot Auto to automatically download and decrypt the cloud videos, then store them on my Synology NAS.

After a bit of research, I found that each time the doorbell wakes up, it records a clip of up to 30 seconds. Each clip is tagged with an event type, such as Pass for someone passing by, Pass:Stay for someone staying at the door, and Pass:Bell for someone pressing the doorbell.

Here is a quick note on the whole process and the issues I ran into along the way.

No Need to Reinvent the Wheel

Why build on Home Assistant and Xiaomi Miot Auto? Because they already handle the Xiaomi account login and token refresh, and the doorbell’s camera entity also shows the time of the latest event (motion_video_time), the event type (motion_video_type), and an m3u8 playback URL (stream_address).

Since the wheel already exists, I didn’t want to reinvent it. Building directly on top of this integration is clearly the most efficient and simplest option. It looks like all I need to do is get stream_address and convert it with ffmpeg, right?

I hoped so.

Four Issues

Issue 1: The m3u8 Is Encrypted

Requesting stream_address returns an HLS playlist — an m3u8 file, which is basically a list that points to several video segments — and every piece is encrypted with AES-128:

#EXTM3U
#EXT-X-VERSION:7
#EXT-X-KEY:METHOD=AES-128,URI="https://sg.app.processor.smartcamera.api.io.mi.com/common/app/play/v1/key?did=<DEVICE_ID>&keyInfo=...",IV=0x<IV>
#EXTINF:3.931311
https://sg.app.processor.smartcamera.api.io.mi.com/common/app/play/v1/video?did=<DEVICE_ID>&stoId=...
#EXT-X-DISCONTINUITY
...
#EXT-X-ENDLISTCode language: PHP (php)

The idea isn’t complicated: fetch the 16-byte key from the URI in #EXT-X-KEY, then use that key and the IV to decrypt each segment with AES-128-CBC. But testing every detail one by one is essentially a very boring process of trial and error.

To be honest, I handed this part over to AI. I used Google Antigravity, let it do the boring trial and error, and just took the results 😂.

Issue 2: A 4-Second Video

After decryption worked, I naturally treated the segments as standard MPEG-TS (.ts) chunks — the usual fragments of one long video — appended all the decrypted bytes into a single file /tmp/test_doorbell.ts, and then remuxed it into an MP4 with ffmpeg:

ffmpeg -y -i /tmp/test_doorbell.ts -c copy /tmp/test_doorbell.mp4Code language: Bash (bash)

The same clip is more than 14 seconds long in the Xiaomi Home app, but what I got was only 4 seconds, plus a screen full of Non-monotonous DTS errors 🤦‍♂️:

[mp4 @ 0x5643e5ef0a00] Non-monotonous DTS in output stream 0:1; previous: 193133, current: 54751; changing to 193134. This may result in incorrect timestamps in the output file.
[mp4 @ 0x5643e5ef0a00] Non-monotonous DTS in output stream 0:1; previous: 193134, current: 55782; changing to 193135. This may result in incorrect timestamps in the output file.
...
frame=  213 fps=0.0 q=-1.0 Lsize=    2649kB time=00:00:04.02 bitrate=5393.4kbits/s speed= 104x

When I printed the first 8 bytes of each decrypted segment, every one of them was 0000002066747970:

Seg 0: enc=826720 dec=826717 magic=0000002066747970
Seg 1: enc=569072 dec=569064 magic=0000002066747970
Seg 2: enc=557232 dec=557222 magic=0000002066747970
Seg 3: enc=497008 dec=497007 magic=0000002066747970
Seg 4: enc=271360 dec=271354 magic=0000002066747970

In short, these segments are MP4 files, not TS. Why? An MP4 file is made of boxes. Each box starts with a 4-byte big-endian size, followed by a 4-byte type written in ASCII:

  • 00 00 00 20: the box size, 0x20 = 32 bytes.
  • 66 74 79 70: the box type in ASCII, 0x66 = f, 0x74 = t, 0x79 = y, 0x70 = p, so it reads ftyp.

ftyp (File Type Box) is normally the very first box of an MP4 file. A TS chunk would start with the sync byte 0x47 instead.

In other words, each roughly three-second segment from Xiaomi is a complete, standalone MP4 file, not the usual TS or fMP4 chunk. Each segment’s timestamps start from zero, so joining them byte by byte is bound to be a mess.

The fix is to save each segment as its own temporary file and losslessly stitch them together with ffmpeg’s concat demuxer. -c copy means ffmpeg copies the video as-is, without converting it again:

ffmpeg -f concat -safe 0 -i concat_list.txt -c copy -movflags +faststart output.mp4Code language: Bash (bash)

The result is the full 2K HEVC (H.265) video with no re-encoding, and it’s really fast.

Issue 3: 60-Second Polling Misses Clips

Xiaomi Miot Auto polls every 60 seconds and only picks up the latest event. If someone stays at the door and triggers two clips in a short time, the next Home Assistant poll only sees the second one, and the first one is missed for good.

So besides accepting the URL passed from Home Assistant, the script uses the credentials that Xiaomi Miot Auto stores in .storage/xiaomi_miot/auth-*.json to call Xiaomi Cloud’s event list API (common/app/get/eventlist) directly. It checks the recent events, compares them with the videos already on the NAS, and downloads any that are missing.

Another benefit is that token refresh is handled entirely by Home Assistant and Xiaomi Miot Auto, so the code needs no account information at all.

Issue 4: The Clip Is Still Being Uploaded

The doorbell records up to 30 seconds per event and uploads to the cloud while recording. If you download a clip as soon as the event shows up, you will probably only get the first one or two segments.

The fix is simple and blunt:

  1. In the automation, wait 35 seconds after motion_video_time changes before calling the script.
  2. In the script, check whether the m3u8 contains #EXT-X-ENDLIST. If not, the clip is still being uploaded, so wait 10 seconds and fetch it again.

Architecture

The whole flow looks roughly like this:

//www.plantuml.com/plantuml/png/RP9FRzGm4CNl_XH3J-qXAhJygJYWXknA22cX9KBbK6db9hCRgxOdiYUxohTdRCYYXLxzU_FyvjctaNNWoLdrYWTq2FeG2mhQxr2fKP3fpAWzmzcAA3oXjMUW8wnEsK-ZoHceB4rzvjMBl3R4K4vCMLEVQhwK6JdDXdmMbFy6E7XBkiS0RHVCo5dKdegQiit7ZL8hA3v11H_XnvZ607qNvf6nXuWxXvxZepz_nf5XIm4-NC50KuWNoXADiDvZcE7zQz5svFke0Eh5xuwi1QiP8mFknKXW1ONGMgYZjC1cRtga3Hkfz18Y1zHke_i-O8mAVQ-oM_cYlXjI_Rqg5yc3DWpNxuvPCcW5n44UPDEHSreisoNW_PJ2vsXWJMJrErsQ-8vTEiqi_bbLTmDqrepWvNd8Wtm4a1vXnhJPqNNf7zprT0Do8JpZV5mzcQ__QtYPJtI5cS9vkMwBDrStHVMvkdZqoIYoOGbnC3p0Tkj6t2s3ZGosUezGtxs5fnbwgJttrnxB2OPH73HF4Rwstvg_lJLIxNPEAs485DIj3AQl_Wi
Sequence diagram of the doorbell video archiving flow
  1. The doorbell uploads encrypted segments to Xiaomi Cloud (kept for 72 hours).
  2. Xiaomi Miot Auto polls every 60 seconds and updates the doorbell entity’s attributes.
  3. When motion_video_time changes, a Home Assistant automation waits 35 seconds and calls the downloader script through shell_command. The script also runs when Home Assistant starts and every 30 minutes as a safety net.
  4. The script reads the latest auth file, queries the event list, downloads the m3u8 and the key, decrypts the segments, and joins them with ffmpeg.
  5. Videos are saved by date under /volume1/surveillance/Xiaomi Doorbell 3S/YYYY-MM-DD/ with names like 2026-10-30_21-20-29_Pass-Stay.mp4. I chose this folder on purpose, because it’s also where Surveillance Station stores the camera footage, so I can check all the videos in one place.
  6. The script writes its status to a JSON file, and a Home Assistant sensor reads it and sends a notification when something goes wrong.

The Downloader Script

The downloader is a Python script that runs on the Python 3.13 bundled with the Synology Home Assistant package. requests, cryptography, and the micloud library used by Xiaomi Miot Auto are all built in, so there’s nothing extra to pip install.

The heart of the script is these few decryption lines: decrypt each segment with AES-128-CBC, then strip the PKCS7 padding:

def decrypt_aes_cbc(data: bytes, key: bytes, iv: bytes) -> bytes:
    """Decrypt AES-128-CBC segment and remove PKCS7 padding."""
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
    decryptor = cipher.decryptor()
    raw = decryptor.update(data) + decryptor.finalize()
    try:
        unpadder = padding.PKCS7(128).unpadder()
        return unpadder.update(raw) + unpadder.finalize()
    except ValueError:
        return rawCode language: Python (python)

configuration.yaml

In configuration.yaml, add the allowed directory, two shell_command entries (one for event-triggered downloads and one for scheduled syncs), and a command_line sensor that reads the status JSON:

homeassistant:
  allowlist_external_dirs:
    - "/volume1/surveillance/Xiaomi Doorbell 3S"

shell_command:
  download_doorbell_video: >-
    /var/packages/HomeAssistant/target/bin/python3.13
    /var/packages/HomeAssistant/home/.homeassistant/download_doorbell_video.py
    --url "{{ stream_address }}"
    --time "{{ video_time }}"
    --type "{{ video_type }}"
    --limit 8
  sync_doorbell_cloud: >-
    /var/packages/HomeAssistant/target/bin/python3.13
    /var/packages/HomeAssistant/home/.homeassistant/download_doorbell_video.py
    --limit 15Code language: YAML (yaml)

To keep the post short, I won’t paste the full code here, but here’s a quick note on the parameters used:

  • --url, --time, --type: the playback URL, time, and event type of the latest event.
  • --limit: how many of the most recent events to fetch from Xiaomi Cloud’s event list and check. Clips already on the NAS are skipped, and only the ones not yet downloaded are downloaded. The event-triggered run uses 8 and the scheduled sync uses 15. Both are kept small so the script finishes within the 60-second shell_command timeout.
  • --backfill: catch-up mode. The script pages backward through the event list, --limit events per page, and checks every clip still kept in Xiaomi Cloud. It takes a while, so I recommend running it by hand rather than from an automation.

automations.yaml

The automation has three triggers: an event update, Home Assistant startup, and every 30 minutes. The event branch waits 35 seconds first:

triggers:
  - id: motion_event
    trigger: state
    entity_id: camera.madv_mi3sg_xxxx_video_doorbell
    attribute: motion_video_time
  - id: ha_startup
    trigger: homeassistant
    event: start
  - id: periodic_catchup
    trigger: time_pattern
    minutes: "/30"Code language: YAML (yaml)

There’s also a second automation that has Home Assistant send a notification when the status sensor turns to ERROR. I won’t go into detail here.

Backfilling Existing Cloud Clips

Once everything is configured, run the script once by hand with --backfill to pull all the clips from the last 72 hours in Xiaomi Cloud. The logs look roughly like this:

[INFO] Downloading cloud event: time=2026-10-30 21:20:29 type=Pass:Stay fileId=...
[INFO] Saved /volume1/surveillance/Xiaomi Doorbell 3S/2026-10-30/2026-10-30_21-20-29_Pass-Stay.mp4 (2655.5 KB, 5 segments)

Lessons Learned

  • Don’t assume the segments in an m3u8 are TS. Check the first 8 bytes of a decrypted segment. Once you see ftyp, the problem is obvious.
  • Home Assistant’s shell_command has a 60-second timeout. For automatic runs, keep --limit (the number of events checked per run) small; for big catch-ups, run --backfill by hand.
  • Xiaomi Cloud stalls now and then. Adding retries to every HTTP request saves you from a lot of random failures.
  • File permissions on Synology. Manual tests over SSH run as your own admin account, while Home Assistant runs as the HomeAssistant user, so when you hand the code over to Home Assistant and something goes wrong, check the permissions on the log, the status file, and the folders first.

Now every time the doorbell is triggered, the video lands on my NAS automatically, and I no longer worry about it disappearing after 72 hours. Not many people come and go at my door, and 30-second clips are small, so I didn’t set any maximum retention period in the script.

That’s all for now.