Last active
January 19, 2023 21:45
-
-
Save rklomp/231c5cb0c7780019d544f77edc6878e5 to your computer and use it in GitHub Desktop.
ha_stats_fix.py
This file contains 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
#!/usr/bin/env python3 | |
import argparse | |
import sqlite3 | |
import sys | |
def main(arguments): | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
"entity_id", help="The entity ID of the sensor to fix statistics for" | |
) | |
parser.add_argument( | |
"-f", | |
metavar="filename", | |
help="Database file to open", | |
default="home-assistant_v2.db", | |
) | |
args = parser.parse_args(arguments) | |
print(f"Opening database file: '{args.f}'") | |
con = sqlite3.connect(args.f) | |
con.row_factory = sqlite3.Row | |
cur = con.cursor() | |
cur.execute(f"SELECT * FROM statistics_meta WHERE statistic_id='{args.entity_id}'") | |
result = cur.fetchone() | |
meta_id = result["id"] | |
print(f"Found metadata ID: '{meta_id}'") | |
cur.execute( | |
f"SELECT * FROM statistics WHERE metadata_id='{meta_id}' ORDER BY start ASC" | |
) | |
first_row = cur.fetchone() | |
first_state = first_row["state"] | |
prev_state = first_state | |
update_query = "UPDATE statistics SET state = ?, sum = ? WHERE id = ?" | |
update_cur = con.cursor() | |
print("Fixing statistics...") | |
for row in cur: | |
new_state = prev_state if row["state"] == 0 else row["state"] | |
new_sum = new_state - first_state | |
update_cur.execute(update_query, (new_state, new_sum, row["id"])) | |
prev_state = new_state | |
update_cur.execute("UPDATE `statistics_short_term` SET `sum` = `state`-? WHERE `metadata_id`=?", (first_state, meta_id)) | |
print("Commit to database...") | |
con.commit() | |
con.close() | |
print("Done!") | |
if __name__ == "__main__": | |
sys.exit(main(sys.argv[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment