Seems pretty straightforwards
. Create a reusable template file:
/config/custom_templates/smartlife.jinja
with this content:
{% macro get_data(s) -%}
{% set ns = namespace(s="") -%}
{% for c in s|map('ord')|reject('==',61) -%}
{% set ns.s = ns.s+"{:0=6b}".format(c+{1:-71,c<91:-65,c<58:4,c<48:16,c<44:19}[true]) -%}
{% endfor -%}
{{ {"voltage": ns.s[0:16] |int(base=2) / 10,
"current": ns.s[16:40]|int(base=2) / 1000,
"power": ns.s[40:64]|int(base=2)}|to_json -}}
{% endmacro -%}
Then either restart HA or call the homeassistant.reload_custom_templates service from Developer Tools / Services.
Now set up template sensors in the UI with the following state templates, and the appropriate device classes (voltage, current, power). In each case, replace sensor.smartlife_value with whatever entity holds the code e.g. CWgABtwAABE=
{% from 'smartlife.jinja' import get_data %}
{{ (get_data(states('sensor.smartlife_value'))|from_json)['voltage'] }}
{% from 'smartlife.jinja' import get_data %}
{{ (get_data(states('sensor.smartlife_value'))|from_json)['current'] }}
{% from 'smartlife.jinja' import get_data %}
{{ (get_data(states('sensor.smartlife_value'))|from_json)['power'] }}
Test:
I joke about the “straightforwards” of course. A couple of key references needed for this:
- needed to write my own base 64 decoder: RFC 4648 - The Base16, Base32, and Base64 Data Encodings
- used prior work on decoding the info: Decoding smart WiFi meter data · codetheweb/tuyapi · Discussion #440 · GitHub
Disclaimer: give this a really good test before using it for anything critical. It’s all been thrown together quite quickly. Might be some b64 padding issues lurking.
