Guidance needed: Integrating a custom Python script as a sensor

Hi everyone,

A bit of background: I’m a senior Python developer, so I’m comfortable writing code, but I’m completely new to Home Assistant and its architecture.

I’ve already written a Python script that queries water usage data from a Flo water valve and uses it to estimate my well level. Now I’d like to integrate this script into Home Assistant so that:

  1. It runs automatically (e.g., every 5 minutes)
  2. The resulting metric shows up as a sensor that I can graph in the UI

I’m aware that HA already has an official Flo integration, but I’ve run into some limitations with it. Specifically, there appears to be a bug/lag in Moen’s API where the “today’s consumption” value lags roughly 45 minutes behind real-time usage. My script works around this by making additional queries to the Moen API to correct for this discrepancy.

Given this, I’d rather not rely on the built-in integration and instead run my own script for this specific calculation.

What would be the recommended approach to:

  • Add a custom sensor backed by my Python logic
  • Have it poll/update on a schedule (e.g., every 5 minutes)
  • Make sure the data is stored properly so I can graph it in the HA UI (history/statistics)

Should I look into writing a custom component, submit bug to existing code, using a command_line or shell_command sensor, or is there a better pattern for this kind of use case? Any pointers to relevant docs or examples would be greatly appreciated.

Thanks in advance!

I recommend a custom component and I’d recommend building your script into that component. There’s already framework to handle these things. You can even overwrite the limitations in the core integration and use that as a framework.

Other option is command_line with returning data and a trigger based template entity (if you don’t want to write a custom integration).

I am very happy with pyscript custom integration.

I’ve hacked together a couple of python scripts that act as sensors. I use
MQTT to transmit the data…

Be sure there is not a reason for the 45min delay.

Like for instance, if you owned YoLink devices that have a 1/4 mile radius on LoRa, they only wake up every 10mins and send an update. If the system sent data continuously (or even like 5 secs) then the battery would die (instead of being fine for years). Your multiple calls leads me to believe that is the case and while you are working around it, you could be destroying your device.