116 lines
2.4 KiB
Bash
Executable File
116 lines
2.4 KiB
Bash
Executable File
#!/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
|
|
|
|
LC_NAME="${DEVICE_NAME,,}"
|
|
|
|
# Device attriutes
|
|
DEVICE_ID="${LC_NAME// /_}"
|
|
DEVICE_MANUFACTURER="custom"
|
|
DEVICE_MODEL="${DEVICE_NAME}" #"custom"
|
|
|
|
# Sensor attributes
|
|
SENSOR_ID="${DEVICE_ID}_${SENSOR_TYPE}"
|
|
SENSOR_EXPIRE_AFTER_S="600"
|
|
|
|
case ${SENSOR_TYPE} in
|
|
"power")
|
|
SENSOR_UNIT="W"
|
|
SENSOR_ICON="mdi:lightning-bolt"
|
|
;;
|
|
"voltage")
|
|
SENSOR_UNIT="V"
|
|
SENSOR_ICON="mdi:sine-wave"
|
|
;;
|
|
"temperature")
|
|
SENSOR_UNIT="°C"
|
|
SENSOR_ICON="mdi:thermometer"
|
|
;;
|
|
"humidity")
|
|
SENSOR_UNIT="%"
|
|
SENSOR_ICON="mdi:water-percent"
|
|
;;
|
|
*)
|
|
echo "Unknown sensor type: ${SENSOR_TYPE}" >&2
|
|
exit 1
|
|
;;
|
|
esac
|
|
|
|
# MQTT attributes
|
|
MQTT_CONFIG_TOPIC="homeassistant/sensor/${SENSOR_ID}/config"
|
|
MQTT_STATE_TOPIC="${LC_NAME// //}/${SENSOR_TYPE}/state"
|
|
|
|
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\": \"${SENSOR_NAME}\",\
|
|
\"unique_id\": \"${SENSOR_ID}\",\
|
|
\"device_class\": \"${SENSOR_TYPE}\",\
|
|
\"unit_of_measurement\": \"${SENSOR_UNIT}\",\
|
|
\"state_topic\": \"${MQTT_STATE_TOPIC}\",\
|
|
\"expire_after\": \"${SENSOR_EXPIRE_AFTER_S}\",\
|
|
\"icon\": \"${SENSOR_ICON}\",\
|
|
\"device\": {\
|
|
\"name\": \"${DEVICE_NAME}\",\
|
|
\"identifiers\": [\"${DEVICE_ID}\"],\
|
|
\"manufacturer\": \"${DEVICE_MANUFACTURER}\",\
|
|
\"model\": \"${DEVICE_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
|