I created a triggered template entity that won’t become available:
shell_command:
battery_percentage: /config/scripts/BatteryPercentage.sh {{device_id}}
template:
- trigger:
- platform: time_pattern
minutes: /1
action:
- action: shell_command.battery_percentage
data:
device_id: bf3...n7d
response_variable: battery_percentage_value
sensor:
- name: "Heizung Kuche Batterie"
unique_id: heizung_kuche_batterie
icon: mdi:battery
unit_of_measurement: "%"
state: >
{% if battery_percentage_value['returncode'] == 0 %}
{{ battery_percentage_value['stdout'] | int(default=0) }}
{% else %}
{{ this.state }}
{% endif %}
device_class: battery
state_class: measurement
It uses a shell script:
#!/bin/bash
# Declare Variables
DeviceID="$1"
ClientID="jgf...3qp"
ClientSecret="230...320"
BaseUrl="https://openapi.tuyaeu.com"
EmptyBodyEncoded="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
tuyatime=$(date +%s000)
# Get Access Token
URL="/v1.0/token?grant_type=1"
StringToSign="${ClientID}${tuyatime}GET\\n${EmptyBodyEncoded}\n\n${URL}"
AccessTokenSign=$(printf "$StringToSign" | openssl sha256 -hmac "$ClientSecret" | awk '{print toupper($0)}' | sed 's/^.*= //')
AccessToken=$(curl -sSLkX GET "$BaseUrl$URL" \
-H "sign_method: HMAC-SHA256" \
-H "client_id: $ClientID" \
-H "t: $tuyatime" \
-H "mode: cors" \
-H "Content-Type: application/json" \
-H "sign: $AccessTokenSign" | jq -r ".result.access_token")
# Get battery percentage of device
URL="/v2.0/cloud/thing/$DeviceID/shadow/properties?codes=battery_percentage"
StringToSign="${ClientID}${AccessToken}${tuyatime}GET\n${EmptyBodyEncoded}\n\n${URL}"
BatteryPercentageSign=$(printf $StringToSign | openssl sha256 -hmac "$ClientSecret" | awk '{print toupper($0)}' | sed 's/^.*= //')
BatteryPercentageResponse=$(curl -sSLkX GET "$BaseUrl$URL" \
-H "sign_method: HMAC-SHA256" \
-H "client_id: $ClientID" \
-H "t: $tuyatime" \
-H "mode: cors" \
-H "Content-Type: application/json" \
-H "sign: $BatteryPercentageSign" \
-H "access_token: $AccessToken")
# Output percentage if successful
success=$(echo "$BatteryPercentageResponse" | jq -r ".success")
if [ "$success" = "true" ]; then
echo "$BatteryPercentageResponse" | jq -r ".result.properties[].value"
else
exit 1
fi
Although I tried various configuration settings the entity remains unavailable although sensor gets data.
There are neither errors nor warnings in home-assistant.log.
Need some help what’s wrong with this entity.