Skip to content

Commit 8cf7c11

Browse files
committed
Support for entities that don't have the a round attribute
Add CHANGELOG.md
1 parent ba66171 commit 8cf7c11

File tree

3 files changed

+65
-18
lines changed

3 files changed

+65
-18
lines changed

CHANGELOG.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# CHANGELOG.md
2+
3+
## 2.1.0
4+
* Add support for a MySQL server using the package PyMySQL
5+
* Add support for entities that are no Riemann Sum Entities
6+
7+
## 2.0.0
8+
* Working script for all Riemann Sum Entities
9+
10+
## 1.0.0
11+
* Initial commit of script (Script is fixing database but sum was wrong with next Riemann Sum calculation)

HA_FixNegativeStatistics.py

+40-18
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,15 @@
1515
from datetime import datetime
1616

1717
__author__ = "Sebastian Hollas"
18-
__version__ = "2.0.0"
18+
__version__ = "2.1.0"
1919

2020
####################################################################################
2121
# USER INPUT REQUIRED !
2222
# Path to HomeAssistant config root (e.g. /HomeAssistant/config )
2323
HA_CONFIG_ROOT = "/HomeAssistant/config"
24-
HA_CONFIG_ROOT = r"C:/users/shollas"
2524
####################################################################################
2625

27-
# USER INPUT OPTIONAL ! (if DATABASE server is used instead of database file)
26+
# USER INPUT OPTIONAL ! (if MySQL server shall be used instead of a SQLite database file)
2827
DB_SERVER = {
2928
"DB_HOST": "",
3029
"DB_USER": "",
@@ -49,7 +48,7 @@
4948
sys.exit(f"File {ENTITY_REGISTRY_PATH} does not exist! (Path to HomeAssistant config valid?)")
5049

5150

52-
# Open Database Server connection if user provided DB_SERVER information
51+
# Open MySQL server connection if user provided DB_SERVER information
5352
if all(DB_SERVER.values()):
5453
import pymysql
5554
db = pymysql.connect(
@@ -59,7 +58,7 @@
5958
database=DB_SERVER["DB_NAME"]
6059
)
6160

62-
# Create connection to database file if no DB_SERVER was provided
61+
# Create connection to database file if no DB_SERVER information was provided
6362
else:
6463
# Check for database file
6564
DATABASE_PATH = os.path.join(HA_CONFIG_ROOT, "home-assistant_v2.db")
@@ -108,10 +107,11 @@ def main():
108107

109108
with open(ENTITIES_FILE, "w") as file:
110109
# Get Entities that have a round option
110+
SqlExec("SELECT statistic_id FROM statistics_meta WHERE has_sum=1", ())
111111
for entity_id in getEntitiesPrecision():
112112
file.write(f"{entity_id}\n")
113113

114-
print(f"File '{ENTITIES_FILE}' created with entities that are most likely Riemann Sum Entities"
114+
print(f"File '{ENTITIES_FILE}' created with entities that have the key 'sum'"
115115
f"\nPlease adjust to your needs and rerun the script with no arguments.")
116116

117117
else:
@@ -150,11 +150,11 @@ def fixDatabase(ENTITIES: list):
150150
################################################################################################################
151151
# Get amount of decimals for Riemann Sum integral that the user configured
152152
if entity_id not in EntityPrecision:
153-
print(f" [WARNING]: Entity seems not to be a Riemann Sum Entity! Skipping...")
154-
continue
155-
156-
# Get Precision of Entity that user configured
157-
roundDigits = EntityPrecision[entity_id]
153+
print(f" [WARNING]: Entity seems not to be a Riemann Sum Entity! UNTESTED. USE WITH CAUTION!")
154+
roundDigits = -1
155+
else:
156+
# Get Precision of Entity that user configured
157+
roundDigits = EntityPrecision[entity_id]
158158

159159
################################################################################################################
160160
# FIX DATABASE
@@ -171,8 +171,12 @@ def fixDatabase(ENTITIES: list):
171171
# Fix table "states"
172172
recalculateStates(metadata_id=metadata_id_states, roundDigits=roundDigits)
173173

174-
# Fix last valid state in HA to ensure a valid calculation with the next Riemann Sum run
175-
fixLastValidState(entity_id=entity_id, lastValidState=lastValidState)
174+
# Fix last valid state if entity seems to be a Riemann Sum Entity only
175+
# OPEN: How to find out if entity is a Riemann Sum Entity?!
176+
# Currently: If entity is in table statistics and has a "round" attribute, it is assumed to be a Riemann Sum Entity
177+
if roundDigits != -1:
178+
# Fix last valid state in HA to ensure a valid calculation with the next Riemann Sum calculation
179+
fixLastValidState(entity_id=entity_id, lastValidState=lastValidState)
176180

177181
# Store database on disk
178182
print(f"\n{db.total_changes} changes made to database!")
@@ -207,7 +211,11 @@ def recalculateStatistics(metadata_id: int, key: str, roundDigits: int) -> str:
207211
# Recalculate new value with difference of previous entries
208212
current_value += (value-pre_value)
209213

210-
roundedValue = f"{current_value:.{roundDigits}f}"
214+
if roundDigits != -1:
215+
roundedValue = f"{current_value:.{roundDigits}f}"
216+
else:
217+
# Just copy because we don't round the value
218+
roundedValue = current_value
211219
print(f" Updating {idx = }: {value = } -> {roundedValue = }")
212220
SqlExec(f"UPDATE statistics SET {key}=? WHERE id=?", (roundedValue, idx))
213221

@@ -217,7 +225,12 @@ def recalculateStatistics(metadata_id: int, key: str, roundDigits: int) -> str:
217225
current_value = value
218226

219227
# Return last value
220-
return f"{current_value:.{roundDigits}f}"
228+
if roundDigits != -1:
229+
# Return rounded value
230+
return f"{current_value:.{roundDigits}f}"
231+
else:
232+
# Return value as it is
233+
return current_value
221234

222235

223236
def fixShortTerm(metadata_id: int, lastValidSum: str, lastValidState: str):
@@ -264,7 +277,11 @@ def recalculateStates(metadata_id: int, roundDigits: int):
264277

265278
if state is None or not state.replace(".", "", 1).isdigit():
266279
# State is NULL or not numeric; update to current value
267-
roundedValue = f"{current_state:.{roundDigits}f}"
280+
if roundDigits != -1:
281+
roundedValue = f"{current_state:.{roundDigits}f}"
282+
else:
283+
# Just copy because we don't round the value
284+
roundedValue = current_state
268285
print(f" Updating {state_id = }: {state = } -> {roundedValue}")
269286
SqlExec("UPDATE states SET state=? WHERE state_id=?", (roundedValue, state_id))
270287
continue
@@ -277,7 +294,11 @@ def recalculateStates(metadata_id: int, roundDigits: int):
277294
# Recalculate new value with difference of previous entries
278295
current_state += (state - float(pre_state))
279296

280-
roundedValue = f"{current_state:.{roundDigits}f}"
297+
if roundDigits != -1:
298+
roundedValue = f"{current_state:.{roundDigits}f}"
299+
else:
300+
# Just copy because we don't round the value
301+
roundedValue = current_state
281302
print(f" Updating {state_id = }: {state = } -> {roundedValue}")
282303
SqlExec("UPDATE states SET state=? WHERE state_id=?", (roundedValue, state_id))
283304
continue
@@ -321,7 +342,7 @@ def getEntitiesPrecision() -> dict[str: int]:
321342

322343
configIds = dict()
323344

324-
# Find entry_ids which have the option/round attribute (these are most likely Riemann Sum Entities
345+
# Find entry_ids which have the option/round attribute (these are most likely Riemann Sum Entities)
325346
for configEntry in configEntries["data"]["entries"]:
326347
number = configEntry["options"].get("round", -1)
327348
if number == -1:
@@ -346,6 +367,7 @@ def getEntitiesPrecision() -> dict[str: int]:
346367

347368
def SqlExec(SqlQuery: str, arguments: tuple):
348369
if not isinstance(db, sqlite3.Connection):
370+
# Replace placeholder for module PyMySQL
349371
SqlQuery = SqlQuery.replace("?", "%s")
350372

351373
cur.execute(SqlQuery, arguments)

README.md

+14
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,16 @@ Tested with
2121
```bash
2222
HA_CONFIG_ROOT = "/HomeAssistant/config"
2323
```
24+
2. (Optional): Required for MySQL server connection
25+
Change following variables to your server details:
26+
```bash
27+
DB_SERVER = {
28+
"DB_HOST": "",
29+
"DB_USER": "",
30+
"DB_PASSWORD": "",
31+
"DB_NAME": ""
32+
}
33+
```
2434
3. Create a entities.list file which includes entities that can be fixed by this script by executing:
2535
**(This does NOT touch your database yet)**
2636
```bash
@@ -77,3 +87,7 @@ This table holds all states for every single entity in your HomeAssistant.
7787
### File *core.restore_state*
7888
This file holds all the last valid values of your entities.
7989
The Riemann Sum Integration uses this value to calculate the next state for the table *states*
90+
91+
### New with version 2.1.0
92+
This script also tries to fix entities that are not Riemann Sum Entities and skips the steps which are not required
93+
**This is an untested feature!**

0 commit comments

Comments
 (0)