I need the ability to regularly post ‘unknown’ states for an entity with device_class energy and state_class total (these will be placeholders for later inserted historical states – note I do NOT want to just import statistics)
I came up with 2 partial workarounds:
- Option A: Use REST_API but this method only allows me to insert one instance as it sees repeated instances as duplicates
(Workaround is to cycle between 2 dummy attribute_ids and then later use sqlite3 UPDATE to restore correct attributes id)
My corresponding crontab entry looks like this:
14,29,44,59 * * * * sleep 45 && RES="$(curl -sS -X POST "http://supervisor/core/api/states/sensor.electic_meter" -H "Authorization: Bearer $SUPERVISOR_TOKEN" -H "Content-Type: application/json" -d '{"state":"unknown","attributes":{"sensor.electric_meter_dummy":'"$(( $(date "+%M") % 2 ))"'}}')" && DATE="$(echo "$RES" | jq -r .last_updated | sed -e 's/T/ /' -e 's/+.*//')" && LAST_UPDATED_TS="$(date "+%s" -d "${DATE%%.*}+0000").$(echo "$DATE" | cut -d. -f2-)" && sleep 5 && sudo sqlite3 -batch /config/home-assistant_v2.db "BEGIN IMMEDIATE; UPDATE states SET attributes_id = 347345 WHERE metadata_id = 924 AND ROUND(last_updated_ts,6)=ROUND(CAST('$LAST_UPDATED_TS' AS FLOAT),6); COMMIT"
- Option B: Use MQTT, but then I can only insert numerical state values (it seems) and they also can’t be repeated
(Workaround is to post a random numerical state - e.g., epoch timestamp - then later use sqlite3 to UPDATE state value to ‘unknown’ – and do this before statistics get updated – i.e. avoid 5-minute marks. This approach also has the negative impact that history dashboards show the last posted numerical state)
My corresponding crontab entry looks like:
14,29,44,59 * * * * sleep 45 && /usr/bin/mosquitto_pub -h localhost -u "MQTT" -P 'XXXXXXX' -t "home/mysensors/meters/Electric-XXXXXXXX" -m "{\"Consumption\": \"$(date +\%s)\"}" && sleep 5 && sudo sqlite3 /config/home-assistant_v2.db "BEGIN IMMEDIATE; UPDATE states SET state = 'unknown' WHERE CAST(state AS REAL) > 99999999 AND metadata_id = 924; COMMIT"
Neither is ideal - so is there any way to post repeated identical states to the states database with value ‘unknown’?
Note I use this as part of an add-on I am building that scrapes my Electricity utilities website once a day to download quarter-hour kWh energy consumption. I then import the quarter-hour totals by updating the historical placeholder states and then run a routine to update statistics and statistics_short_term tables.
I know it is possible just to insert statistics but I want to also maintain a states history