Sending messages from pi zero rain detector to Hass

I have a home made pi zero w rain detector that i want to send messages to hass on a pi 4. It will be a simple flag for whether it is raining or not.

I used the MagPi scripts for a rain detector and think i am pretty comfortable with changing python scripts.

The issue is I am not experienced with MQTT whic I believe is the preferred method.

I have installed Mosquitto on the hass pi 4 (with an account) and I have also installed Mosquitto with paho on the rain detector pi.

I just don’t fully understand how to use this to send a MQTT message in Python.

Also, as the raining/not raining message will only be sent intermittently (ie when rain starts and then stops), i guess Hass will need to hold the last rain status for use in local automation scripts. So Hass will need a method to do this which I am also unsure of (set up a sensor somehow to hold the last status?).

the easiest would be to send a shell command to your MQTT broker

publish.single(
                'topic',
                'message', # this would be where you post on of off
                retain=True, # if you want this to be available after you restart HA
                hostname=192.168.0.x,
                port=1883,
                auth={'username':'MQTT_USERNAME', 'password':'MQTT_PASSWORD'}
            )

I forgot you need this on top of your script:

import paho.mqtt.publish as publish