#!/bin/bash # MQTT configuration attributes # https://www.home-assistant.io/integrations/sensor.mqtt/ # https://www.home-assistant.io/integrations/switch.mqtt/ # Explanation # https://www.youtube.com/watch?v=VHiCtZqllU8 # https://resinchemtech.blogspot.com/2023/12/mqtt-auto-discovery.html # Prerequesite #apt install mosquitto-clients source ~/.mqtt-hass.conf #MQTT_BROKER="" #MQTT_PORT=1883 #MQTT_USERNAME="" #MQTT_PASSWORD="" #TYPE="power" #NAME="Host $(hostname -s)" #ID="host_$(hostname -s)" #TOPIC="host/$(hostname -s)" LC_NAME=${DEVICE_NAME,,} ID=${LC_NAME// /_} TOPIC=${LC_NAME// //} case ${TYPE} in "power") DEVICE_CLASS="power" UNIT="W" ICON="mdi:lightning-bolt" ;; "voltage") DEVICE_CLASS="voltage" UNIT="V" ICON="mdi:sine-wave" ;; "temperature") DEVICE_CLASS="temperature" UNIT="°C" ICON="mdi:thermometer" ;; "humidity") DEVICE_CLASS="humidity" UNIT="%" ICON="mdi:water-percent" ;; *) echo "Unknown sensor type: ${TYPE}" >2 exit 1 ;; esac MANUFACTURER="custom" MODEL="custom" EXPIRE_AFTER_S="600" MQTT_CONFIG_TOPIC="homeassistant/sensor/${ID}/config" MQTT_STATE_TOPIC="${TOPIC}/${DEVICE_CLASS}" function send { TOPIC=$1 PAYLOAD=$2 echo "Sending payload to ${MQTT_BROKER}:${MQTT_PORT}/${TOPIC} ..." echo "TOPIC=$TOPIC" echo "PAYLOAD=$PAYLOAD" mosquitto_pub -h "${MQTT_BROKER}" -p "${MQTT_PORT}" -u "${MQTT_USERNAME}" -P "${MQTT_PASSWORD}" \ -t "$TOPIC" \ -m "$PAYLOAD" } function config { send "${MQTT_CONFIG_TOPIC}" "$1" } function state { send "${MQTT_STATE_TOPIC}" "$1" } function setupEntity { config "{\ \"name\": \"${NAME}\",\ \"unique_id\": \"${ID}_${DEVICE_CLASS}\",\ \"device_class\": \"${DEVICE_CLASS}\",\ \"unit_of_measurement\": \"${UNIT}\",\ \"state_topic\": \"${MQTT_STATE_TOPIC}\",\ \"expire_after\": \"${EXPIRE_AFTER_S}\",\ \"icon\": \"${ICON}\",\ \"device\": {\ \"name\": \"${DEVICE_NAME}\",\ \"identifiers\": \"${ID}\",\ \"manufacturer\": \"${MANUFACTURER}\",\ \"model\": \"${MODEL}\"\ }}" #\"firendly_name\": \"${NAME} power\",\ # "hw_version":"1.02", # "sw_version":"2.45", # "configuration_url":"http://192.168.1.226" } function deleteEntity { config "" } if [ "$1" == "r" ]; then deleteEntity exit 0 fi if [ -n "$1" ]; then setupEntity state "$1" exit 0 fi if [ -z "$1" ]; then setupEntity exit 0 fi exit 1