Created
November 29, 2024 22:47
-
-
Save giulianob/4414dca1f4d9043e7d94c9428eb27b81 to your computer and use it in GitHub Desktop.
Bermuda BLE SQL Debounce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Add a SQL Integration and specify "state" for the column then | |
-- paste query below. Update the line "entity_id = 'sensor....'" to refer | |
-- to the sensor you want to debounce | |
WITH | |
StateHistory as ( | |
SELECT | |
state_id, | |
state, | |
last_updated_ts as start_ts, | |
LEAD (last_updated_ts, 1, unixepoch ()) OVER ( | |
ORDER BY | |
last_updated_ts | |
) as end_ts, | |
datetime (last_updated_ts, 'unixepoch', 'localtime') as last_updated_dt | |
FROM | |
states | |
WHERE | |
metadata_id = ( | |
SELECT | |
metadata_id | |
FROM | |
states_meta | |
WHERE | |
entity_id = 'sensor.xxxxxxxxxxxxxx' | |
) | |
AND last_changed_ts IS NULL --Ignore rows when state didnt change | |
ORDER BY | |
state_id DESC | |
LIMIT | |
50 | |
), | |
Durations as ( | |
SELECT | |
state_id, | |
state, | |
(end_ts - MAX(start_ts, unixepoch () - 60)) as duration, | |
datetime (start_ts, 'unixepoch', 'localtime') as start_dt, | |
datetime (end_ts, 'unixepoch', 'localtime') as end_dt | |
FROM | |
StateHistory | |
WHERE | |
end_ts > unixepoch () - 60 | |
), | |
Totals as ( | |
SELECT | |
state, | |
SUM(duration) as total_duration | |
FROM | |
Durations | |
GROUP BY | |
state | |
), | |
BestState as ( | |
SELECT | |
state | |
FROM | |
Totals | |
ORDER BY | |
total_duration desc | |
LIMIT | |
1 | |
) | |
SELECT | |
* | |
FROM | |
BestState |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment