Skip to content

Instantly share code, notes, and snippets.

@atiti
Last active January 5, 2023 12:25
Show Gist options
  • Select an option

  • Save atiti/75ce218051d6a3358d6d6696affc1ec3 to your computer and use it in GitHub Desktop.

Select an option

Save atiti/75ce218051d6a3358d6d6696affc1ec3 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# LYWSD03MMC read out temperature & humidity
# report it to Home Assistant as a new sensor over MQTT
#
# 1. Setup the MAC address (hcitool lescan if you don't know) and MQTTT parameters
# 2. Initialize the MQTT structure: ./push-to-ha.sh init
# 3. Send in the reading: ./push-to-ha.sh
#
# Setup a periodic cron job -> profit!
# Sensor MAC address
MAC="A4:C1:38:12:34:56"
# MQTT parameters
MQTT_SERVER="192.168.10.2"
MQTT_PORT=1883
MQTT_USERNAME=""
MQTT_PASSWORD=""
MQTT_CLIENTID="officesensor_bd8041d0cdf131a6ba4e5b3360b8bc5a"
MQTT_TOPIC="homeassistant"
MQTT_DEVICENAME="officesensor"
registerTopic () {
mosquitto_pub \
-h $MQTT_SERVER \
-p $MQTT_PORT \
-u "$MQTT_USERNAME" \
-P "$MQTT_PASSWORD" \
-i $MQTT_CLIENTID \
-t "$MQTT_TOPIC/sensor/"$MQTT_DEVICENAME"_$1/config" \
-m "{
\"name\": \""$MQTT_DEVICENAME"_$1\",
\"unit_of_measurement\": \"$2\",
\"state_topic\": \"$MQTT_TOPIC/sensor/"$MQTT_DEVICENAME"_$1\",
\"icon\": \"mdi:$3\"
}"
}
pushMQTTData () {
mosquitto_pub \
-h $MQTT_SERVER \
-p $MQTT_PORT \
-u "$MQTT_USERNAME" \
-P "$MQTT_PASSWORD" \
-i $MQTT_CLIENTID \
-t "$MQTT_TOPIC/sensor/"$MQTT_DEVICENAME"_$1" \
-m "$2"
}
# Initialize HA MQTT sensor
if [ "$1" = "init" ]; then
registerTopic "temperature" "°C" "temperatur"
registerTopic "humidity" "%" "humidity"
echo "Done."
exit 0;
fi;
# Query the temp & humidity sensor over BLE
bt=$(timeout 15 gatttool -b $MAC --char-write-req --handle='0x0038' --value="0100" --listen 2>&1 |tail -n1)
if [ "$?" -ne 0 -o -z "$bt" ]; then
echo "Reading failed";
exit 1;
fi;
reading_hex=$(echo $bt |cut -d ':' -f 2)
temp_hex=$(echo $reading_hex |awk -F ' ' '{print $2$1}' | tr [:lower:] [:upper:])
humi_hex=$(echo $reading_hex |awk -F ' ' '{print $3}' | tr [:lower:] [:upper:])
temp100=$(echo "ibase=16; $temp_hex" |bc)
temp=$(echo "scale=2;$temp100/100" |bc)
humi=$(echo "ibase=16; $humi_hex" |bc)
echo "Temp: $temp C"
echo "Humidity: $humi %"
pushMQTTData "temperature" "$temp"
pushMQTTData "humidity" "$humi"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment