Contents

Overengineering a mirror - Part 3: K8s Deployment

This is the third and last part of this series of posts:

Now that our cluster is ready and that we know how to use the Kinect, we’re ready to write a ton of yaml, deploy everything on the cluster and do some automations !

Discovering USB devices with Akri

Since we’ll be deploying our containers in a kubernetes cluster, we need a way to schedule these containers on the right node (in my case, the mini-pc that is connected to the Kinect and to the TV).

The easiest way would be to set a specific taint on the mini-pc and match it in our deployment, but this is a bit hacky.

What if we could directly tell the scheduler what devices are required on the node ? That’s what Akri provides.

More specifically, the udev handler allows us to match specific udev rules for scheduling.

Deploying Akri

I’m using Flux CD to manage all my k8s config, so I’ll show the configuration for this environnement.

First, create a HelmRepository and a HelmRelease to install Akri.

In the HelmRelease values, we’re using agent.full: true to use agent images that already includes discovery handlers (instead of deploying them separately) since currently it’s not possible to define tolerations for discovery handlers in the helm chart.

---
apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmRepository
metadata:
  name: akri-repo
  namespace: akri
spec:
  interval: 24h
  url: https://project-akri.github.io/akri/
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
  name: akri
  namespace: akri
spec:
  chart:
    spec:
      chart: akri
      sourceRef:
        kind: HelmRepository
        name: akri-repo
      version: 'v0.14.0'
  interval: 1h
  targetNamespace: akri
  values :
    agent:
      full: true
      host:
        udev: /run/udev
      tolerations:
        - key: droso/target-type
          operator: Equal
          value: lowpower
          effect: NoSchedule

  

Configuring the udev rules

Then, we create Akri Configuration objects to match specific udev rules.

I created 3 Configurations:

  • udev-framebuffer to match a framebuffer device with: SUBSYSTEM=="graphics", KERNEL=="fb[0-9]*"
  • udev-violet-mirror to match the violet mir:ror: SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1da8", ATTRS{idProduct}=="1301"
  • And udev-kinect2 with 3 rules to match the Kinect’s usb devices: SUBSYSTEM=="usb", ATTR{idVendor}=="045e", ATTR{idProduct}=="...."
apiVersion: akri.sh/v0
kind: Configuration
metadata:
  name: udev-kinectv2
  namespace: akri
spec:
  discoveryHandler:
    name: udev
    discoveryDetails: |+
        udevRules:
        -  'SUBSYSTEM=="usb", ATTR{idVendor}=="045e", ATTR{idProduct}=="02c4"'
        -  'SUBSYSTEM=="usb", ATTR{idVendor}=="045e", ATTR{idProduct}=="02d8"'
        -  'SUBSYSTEM=="usb", ATTR{idVendor}=="045e", ATTR{idProduct}=="02d9"'
        permissions: "rwm"
  capacity: 10
---
apiVersion: akri.sh/v0
kind: Configuration
metadata:
  name: udev-violet-mirror
  namespace: akri
spec:
  discoveryHandler:
    name: udev
    discoveryDetails: |+
        udevRules:
        -  'SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1da8", ATTRS{idProduct}=="1301"'
        permissions: "rwm"
  capacity: 5
---
apiVersion: akri.sh/v0
kind: Configuration
metadata:
  name: udev-framebuffer
  namespace: akri
spec:
  discoveryHandler:
    name: udev
    discoveryDetails: |+
        udevRules:
        -  'SUBSYSTEM=="graphics", KERNEL=="fb[0-9]*"'
        permissions: "rwm"
  capacity: 5

Adding it to the deployment

Now, just add the required devices as resources/limits in your deployment with the prefix akri.sh/, and the pod will automatically be scheduled on the correct node and mount the required devices (or fail if akri can’t discover any resource matching your udev rules).

For example, with the libfreenect/ffplay container:

resources:
  limits:
    akri.sh/udev-kinectv2: "3"
    akri.sh/udev-framebuffer: "1"
  requests:
    akri.sh/udev-kinectv2: "3"
    akri.sh/udev-framebuffer: "1"

Capturing the Kinect’s video

We’ve already covered how to create the kinect streaming containers in Part 2, so all we need to do is deploy it.

The deployment file is pretty standard, except for the added akri resources to require a connected kinect and a framebuffer to write the video to. The container is required to run as a privileged container to access the kinect/framebuffer. And I’m using strategy Recreate to prevent multiple concurrent instances of this pod (since this would cause issue with framebuffer/kinect allocation between more than 1 pod). The ScaledObject part will be discussed in the Keda section below but isn’t strictly required.

kind: Deployment
apiVersion: apps/v1
metadata:
  name: kinect
  labels:
    app: kinect
spec:
  selector:
    matchLabels:
      app: kinect
  template:
    metadata:
      labels:
        app: kinect
    spec:
      strategy:
        type: Recreate
      containers:
        - name: kinect
          image: registry.tld/kinectv2_streamer:v0.0.2
          resources:
            limits:
              akri.sh/udev-kinectv2: "3"
              akri.sh/udev-framebuffer: "1"
            requests:
              akri.sh/udev-kinectv2: "3"
              akri.sh/udev-framebuffer: "1"
          env:
            - name: RTSP_URL
              valueFrom:
                secretKeyRef:
                  name: kinect-secrets
                  key: RTSP_URL
          securityContext:
            privileged: true
---
# scaler based on home assistant switch state
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: kinect-scaler
spec:
  scaleTargetRef:
    name: kinect
  triggers:
  - type: mysql
    metadata:
      queryValue: "1"
      activationQueryValue: "0"
      query: "select IF(state='on', 1, 0) AS scale from states where metadata_id = (select metadata_id from states_meta where entity_id = 'input_boolean.kinect_streamer') order by last_updated_ts desc limit 1;"
    authenticationRef:
      name: keda-sql-scaler-auth

You can notice the RTSP_URL that is used to also restream the video to a RTSP server (see the part 2 container start script for more info), this variable is stored in a k8s secret (encrypted with SOPS) and looks like rtsp://user:password@mediamtx.home.svc.cluster.local:8554/kinect. This url is used to publish the video stream to a 3rd party server.

To deploy such a server, I’m using mediamtx with the following deployment:

kind: Deployment
apiVersion: apps/v1
metadata:
  name: mediamtx
  labels:
    app: mediamtx
spec:
  selector:
    matchLabels:
      app: mediamtx
  template:
    metadata:
      labels:
        app: mediamtx
    spec:
      strategy:
        type: Recreate
      containers:
        - name: mediamtx
          image: bluenviron/mediamtx:1
          volumeMounts:
            - name: mediamtx-config
              mountPath: /mediamtx.yml
              subPath: config.yaml
          ports:
            - name: rtsp
              containerPort: 8554
      volumes:
        - name: mediamtx-config
          secret:
            secretName: mediamtx-config
---
apiVersion: v1
kind: Service
metadata:
  name: mediamtx
spec:
  ports:
    - protocol: TCP
      name: rtsp
      port: 8554
  selector:
    app: mediamtx
---
apiVersion: v1
kind: Service
metadata:
  name: mediamtx-lb
  labels:
    cilium-lb: lan-main
  annotations:
    lbipam.cilium.io/ips: "10.10.200.4"
spec:
  ports:
    - protocol: TCP
      name: rtsp
      port: 8554
  selector:
    app: mediamtx
  type: LoadBalancer
  loadBalancerClass: io.cilium/bgp-control-plane
  externalTrafficPolicy: Local
  ipFamilies:
    - IPv4

The server gets a dedicated IPv4 address (10.10.200.4 in this example) directly reachable from my lan (to receive the video stream from my PC) with the LoadBalancer Service, and is also reachable inside the cluster with its normal Service and DNS name mediamtx.home.svc.cluster.local (for the kinect container to send the stream).

Automating everything with Home-Assistant

Now, there are a few “problems” that remains:

  • I don’t really want the Kinect to be streaming 24/7
  • Actually I don’t even want to have it powered on when I’m not using it
  • It would be annoying to manually power on the tv, the kinect and deploy the streaming pod
  • Ideally, triggering an automation should be fast/user friendly (so no opening and waiting for an app to load)

To solve all of these problems at once, I will use Home-Assistant as a platform to connect and automate all the moving parts of this system.

The goal is here to have a single script in home-assistant that will:

  • Power On and change the TV input to the mini-PC with an ESP32
  • Power On the Kinect with a remote-controlled plug
  • Scale-up the kinect-streamer pod with Keda
    • This is done using Keda (see below)
    • On home-assistant’s side, we’re only using a helper boolean which state will be used to scale up or down the pod

And this script can directly be called when a tag is scanned on the violet mir:ror.

The script looks something like this:

sequence:
  - action: switch.turn_on
    target:
      entity_id:
        - switch.0x0de3396_mqtt_switch # kinect remote plug
        - switch.tv_v2 # TV IR command
    data: {}
  - action: input_boolean.turn_on
    target:
      entity_id: input_boolean.kinect_streamer # boolean helper
  - delay:
      hours: 0
      minutes: 0
      seconds: 15 # wait for tv to power on
      milliseconds: 0
  - delay:
      hours: 0
      minutes: 0
      seconds: 2
      milliseconds: 0
  - action: button.press
    target:
      entity_id: button.lg_tv_hdmi_1 # switch source
    data: {}
alias: Dance Mode
description: ''

Using the mir:ror as a trigger

For the mir:ror and the RFXLAN, both pieces of software are using MQTT, so we first need to deploy an MQTT server (also called broker).

On my infra, I’m using NATS which is currently only compatible with MQTT3.1.1. Going forward, Home-Assistant will require MQTT5, so I’ll probably using this additional project: mqtt-nats-broker to add MQTT5 compatibility to NATS.

Once the broker is deployed and configured in Home-Assistant, we can deploy the mirror-mqtt service. This service requires the akri.sh/udev-violet-mirror resource to ensure that it’s deployed on the node where the mir:ror is actually connected, it then forwards tag scan events to Home-Assistant with MQTT.

All the scanned nanoz:tag appears in Home-Assistant as tags.

kind: Deployment
apiVersion: apps/v1
metadata:
  name: violet-mirror
  labels:
    app: violet-mirror
spec:
  selector:
    matchLabels:
      app: violet-mirror
  template:
    metadata:
      labels:
        app: violet-mirror
    spec:
      strategy:
        type: Recreate
      containers:
        - name: violet-mirror
          image: ghcr.io/droso-hass/mirror-mqtt:v0.0.5
          resources:
            limits:
              akri.sh/udev-violet-mirror: "1"
            requests:
              akri.sh/udev-violet-mirror: "1"
          env:
            - name: MIRROR_MQTT_HOST
              value: nats.home.svc.cluster.local
            - name: MIRROR_MQTT_PORT
              value: "1883"
            - name: MIRROR_DEV
              value: /dev/hidraw0
            - name: MIRROR_ID
              value: mirror1
            - name: MIRROR_MQTT_USERNAME
              valueFrom:
                secretKeyRef:
                  name: violet-mirror-secrets
                  key: MIRROR_MQTT_USERNAME
            - name: MIRROR_MQTT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: violet-mirror-secrets
                  key: MIRROR_MQTT_PASSWORD

Switching the TV On

This was already an existing part of my current setup (see this older post: create your own ambilight solution), but since then, a few things changed in ESPHome.

The hardware setup is still the same, with: an ESP32 and an infrared led taped to the TV’s receiver.

The ESP is running ESPHome and is configured to use the IR Proxy component.

remote_transmitter:
  - id: ir_tx
    pin: GPIO5
    carrier_duty_percent: 10%

infrared:
  - platform: ir_rf_proxy
    name: IR Transmitter
    remote_transmitter_id: ir_tx

Once the esp is connected to home-assistant, the TV can then be controlled using the LG Infrared integration.

Switching the Kinect On

The Kinect is connected by USB to the mini-PC but also requires an external power supply to work.

I connected this power supply to a cheap remote-controlled 433mhz plug that I had laying around.

To control it, I’m using my old RFXLAN (see the previous post of this series) with my xpl2mqtt software.

The software is completely stateless and can be deployed on any node, as long as is has network access to the MQTT broker and can receive the UDP packets from the RFXLAN.

Once the plug is used at least once with the remote, the signal is captured by the RFXLAN and the plug appears directly in Home-Assistant as a switch and can be controlled from there.

Scaling workloads with Keda

Another existing part of my k8s infra that I can take advantage of is Keda which is an event-driven autoscaler.

I mostly use it with the keda-http addon for scaling-to-zero for my least used services.

But in this case, I’ll be using the MySQL scaler. Why ?

Because my Home-Assistant is configured to store its database in MariaDB instead of the default sqlite. So, we can use this scaler to read the database and automatically scale up or down our workload based on the state of some entities in the DB.

We first need to define a Secret and a TriggerAuthentication object to store access credentials for the db.

And then we can define the ScaledObject with a mysql trigger.

The actual SQL request is: SELECT IF(state='on', 1, 0) AS scale from states where metadata_id = (SELECT metadata_id from states_meta where entity_id = 'input_boolean.kinect_streamer') order by last_updated_ts desc limit 1;. It’s used to read the latest state of the boolean helper declared in home-assistant (here, input_boolean.kinect_streamer) and to return “1” if it’s “on” and “0” otherwise. The scaler then uses these values to scale up or down the referenced scaledTargetRef (here, the kinect deployment)

apiVersion: v1
kind: Secret
metadata:
    name: keda-secrets
type: Opaque
stringData:
    mysql_hass_conn_str: user:password@tcp(mysql.storage.svc.cluster.local:3306)/home_assistant
---
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
  name: keda-sql-scaler-auth
spec:
  secretTargetRef:
  - parameter: connectionString
    name: keda-secrets
    key: mysql_hass_conn_str
---
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: kinect-scaler
spec:
  scaleTargetRef:
    name: kinect
  triggers:
  - type: mysql
    metadata:
      queryValue: "1"
      activationQueryValue: "0"
      query: "select IF(state='on', 1, 0) AS scale from states where metadata_id = (select metadata_id from states_meta where entity_id = 'input_boolean.kinect_streamer') order by last_updated_ts desc limit 1;"
    authenticationRef:
      name: keda-sql-scaler-auth

Final Setup

Everything is now completed, so here’s the final picture of the full setup !

/2026/11/26/overengineering-a-mirror-or-how-i-pxe-booted-a-k3s-cluster-part-3/assets/schema/infra_mirror.drawio.png
full mirror setup

Since I also have a Kinect V1 as my main PC’s webcam (but with way less more room in front of it), I created this little helper script to show the video from the PC’s V1 (connected on usb) or the mini-PC’s V2 (streamed over RSTP).

It can be used like kctl rec usb or kctl rec rstp to record video. There is also an option to play the live video from the V1 kctl play usb and even to add delay (to have some kind of “live replay”) kctl play usb 2 (to add 2 sec of delay).

#!/bin/bash

TARGET=$1 # usb / rstp
MODE=$2 # play / rec
DELAY=${3:-0} # delay in seconds for play mode, default 0s

if [ "$TARGET" == "usb" ] && [ "$MODE" == "play" ]; then
    if [ "$DELAY" -gt 0 ]; then
        rm -f /tmp/video_buffer.raw
        ffmpeg -i /dev/video0 -vf "hflip" -preset ultrafast -pix_fmt uyvy422 -f rawvideo -r 30 /tmp/video_buffer.raw &
        FFMPEG_PID=$!
        sleep $DELAY
        ffplay -i /tmp/video_buffer.raw -f rawvideo -pixel_format uyvy422 -video_size 640x480 -framerate 30
        kill $FFMPEG_PID 2>/dev/null
        rm -f /tmp/video_buffer.raw
    else
        ffmpeg -i /dev/video0 -vf "hflip" -c:a copy -preset ultrafast -pix_fmt uyvy422 -f rawvideo - | ffplay -autoexit -max_delay 0 -max_probe_packets 1 -analyzeduration 0 -flags +low_delay -fflags +nobuffer -f rawvideo -pixel_format uyvy422 -video_size 640x480 -
    fi

elif [ "$TARGET" == "usb" ] && [ "$MODE" == "rec" ]; then
    ffmpeg -i /dev/video0 -vf "hflip" -c:a copy -preset ultrafast -pix_fmt uyvy422 -f rawvideo - -f matroska -vf "hflip" "/home/user/rec/vid-$(date +"%FT%H%M%S").mkv" | ffplay -autoexit -max_delay 0 -max_probe_packets 1 -analyzeduration 0 -flags +low_delay -fflags +nobuffer -f rawvideo -pixel_format uyvy422 -video_size 640x480 -

elif [ "$TARGET" == "rtsp" ] && [ "$MODE" == "rec" ]; then
    ffmpeg -vsync 2 -rtsp_transport tcp -i rtsp://user:password@10.10.200.4:8554/kinect "/home/user/rec/vid-$(date +"%FT%H%M%S").mkv"

fi

Conclusion

This is finally the end of this long series and, as you can see, this wasn’t the easiest project to take on and the “overengineering” in the title really takes on its full meaning here.

But in the end it doesn’t even matter, the setup is pretty reliable (even with all these moving parts) and the most important part: it’s easy and fast to use (here, I just have to tap the tag on my mir:ror and lift the bed to get started), so the only thing that remains to do is practice !