Fixing a bricked Mi Flora sensor

I am using MiFlora sensors from Xiaomi to monitor some of the plants in our apartment. Around 2 years ago one of the sensors got bricked and started to advertise itself as "Dial Test" while turning its LED on permanently. This caused the battery to drain very rapidly making the sensor no longer viable. Some quick research showed that Chris Scheffler was encountering a very similar behavior after he wrote data using the wrong byte order to the device.

Since I did not want to spend a lot of time investigating and tinkering with the sensor I just ordered a new one as they were only around 10$ including shipping back then. This week I had another sensor showing the exact same behavior after the battery died. I spent a bit of time on it and realized that the simplest way to set up an environment to run code to fix this was to log into the container running Home Assistant since it already had all the libraries installed. Turned out it was fairly simple to fix the sensor after all.

To create an interactive python shell using the Home Assistant container on my Home Assistant Blue I am using the following command.

docker exec -it container python3

And this is the code snippet I have used to connect to my sensor and write the magic bytes to reset it which turns the LED off again. Just replace the mac address with your mac address and give it a try.

import btlewrap
from btlewrap.base import BluetoothBackendException, BluetoothInterface

_bt_interface = BluetoothInterface(backend, adapter="hci0")
_RESET_DEVICE = bytes([0xD0, 0xAA])
mac = "C4:7C:8D:00:00:00"

backend = btlewrap.BluepyBackend
with _bt_interface.connect(mac) as connection: