Mixing sensor and custom control logic on board code

Hi, I’d like to control my home hot water recirculation pump using a Sonoff TH16, i.e. run the pump and heater when the recirc line is cold, turn it off when warm enough, and run it periodically even if still warm.

Can I add custom code to the device and have ESPHome connect the device to HA at the same time?
To be specific, I want the pump to function even if HA is not running, but to report status to HA when running, thus the control logic needs to be programmed onto the TH16.

Is this a supported use of ESPHome?

Yes, it is all in the docs. https://esphome.io/guides/automations.html

Thx, I’ll dig in.