Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save iiidefix/2d170a9cbe92974b25fdd1f88adb2c96 to your computer and use it in GitHub Desktop.

Select an option

Save iiidefix/2d170a9cbe92974b25fdd1f88adb2c96 to your computer and use it in GitHub Desktop.
Home Assistant MQTT Discovery Script for Meross EM06P Smart Energy Monitor
#!/usr/bin/env bash
set -euo pipefail
# configuration
BROKER_HOST="${BROKER_HOST:-localhost}"
BROKER_PORT="${BROKER_PORT:-1883}"
BROKER_USER="${BROKER_USER:-}" # optional "user:pass"
PREFIX="${PREFIX:-homeassistant}"
DEVICE_NAME="${DEVICE_NAME:-Meross EM06P}" # change device name
DEVICE_ID="${DEVICE_ID:-meross-em06p-c4e7ae000000}" # change device id
STATE_TOPIC="${STATE_TOPIC:-${DEVICE_ID}/notify}"
# sensors list (field|unit|device_class|name)
SENSORS='
current|A|current|Current
voltage|V|voltage|Voltage
power|W|power|Power
pf||power_factor|Power Factor
day_energy|Wh|energy|Energy Day
month_energy|Wh|energy|Energy Month
week_energy|Wh|energy|Energy Week
year_energy|Wh|energy|Energy Year
day_ret_energy|Wh|energy|Energy returned Day
month_ret_energy|Wh|energy|Energy returned Month
week_ret_energy|Wh|energy|Energy returned Week
year_ret_energy|Wh|energy|Energy returned Year
'
# helper to publish with curl (uses curl mqtt://host/topic -d payload)
publish() {
local topic=$1 payload=$2 url
url="mqtt://${BROKER_HOST}:${BROKER_PORT}/${topic}"
if [ -n "$BROKER_USER" ]; then
curl -sS -u "$BROKER_USER" -d "$payload" "$url" >/dev/null
else
curl -sS -d "$payload" "$url" >/dev/null
fi
}
for ch in 1 2 3 4 5 6; do
printf '%s\n' "$SENSORS" | while IFS= read -r line; do
[ -z "$line" ] && continue
IFS='|' read -r field unit device_class name <<<"$line"
disc_topic="${PREFIX}/sensor/${DEVICE_ID}/em${ch}_${field}/config"
unique_id="${DEVICE_ID}_em${ch}_${field}"
name="${DEVICE_NAME} Channel ${ch} ${name}"
value_template="{{ value_json.params['em:${ch}'].${field} }}"
payload="{\"name\":\"${name}\",\"unique_id\":\"${unique_id}\",\"state_topic\":\"${STATE_TOPIC}\",\"value_template\":\"${value_template}\",\"expire_after\":1800,\"device\":{\"identifiers\":[\"${DEVICE_ID}\"],\"name\":\"${DEVICE_NAME}\",\"manufacturer\":\"Meross\",\"model\":\"EM06P\"},\"device_class\":\"${device_class}\""
[ -n "$unit" ] && payload+=",\"unit_of_measurement\":\"${unit}\""
# disable day/week/month/year energy sensors by default
case "$field" in
day_*|week_*|month_*|year_*)
payload+=",\"enabled_by_default\":false"
;;
esac
payload+="}"
publish "$disc_topic" "$payload"
printf 'Published %s -> %s\n' "$disc_topic" "$unique_id"
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment