Skip to content

Instantly share code, notes, and snippets.

@ctrld-pl
Last active December 27, 2022 21:13
Show Gist options
  • Select an option

  • Save ctrld-pl/78b36c5d6ee795ed7380e20882fa2ce1 to your computer and use it in GitHub Desktop.

Select an option

Save ctrld-pl/78b36c5d6ee795ed7380e20882fa2ce1 to your computer and use it in GitHub Desktop.
working with home assistant internal sql database

Jak wyciągać statystyki bezpośrednio z bazy HA

szybkie rozwiązanie

HA zapisuje zmianę stanu każdej encji w tablicy states w dosyc prosty sposób: nowy stan + data. Chcać zliczać czas w każdego ze stanów potrzebujemy doporowadzić do sytuacji kiedy mamy taką wirtualną kolumne (view): stan, kiedy_zaistniał, jak_długo_trwał.

-- 3rd: obliczamy jak długo trwał dany stan na podstawie poprzedniego wpisu
select
    miejsce,
    start,
    -- sprawdzamy jaki był poprzedni stan
    round(extract(epoch from lag(u.start, 1, now()) over() - u.start),0) as jak_dlugo
from (
    select * from 
        -- 2nd: zostawiamy TYLKO rekordy gdzie poprzednie_miejsce != aktualne miejsce
        --      dzięki czemu odrzucamy rekordy, które pojawiają się w bzie po prostu jako
        --      updejty
    (
        -- 1st sql: miejsce, poprzednie_miejsce, last_updated
        select
            state AS miejsce,
            --tutaj musimy posortować tablicę odwrotnie ponieważ bierzemy dane bezpośrednio z
            --tablicy states w HA
            lead(state,1) over(order by last_updated desc) as poprzednie_miejsce,
            last_updated AS start
        from 
            states 
        where 
            entity_id='person.ludw'
        order by 
            last_updated desc
    ) t
    where
        miejsce != poprzednie_miejsce
) u;

przydatne linki:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment