Skip to content

Commit

Permalink
reduce floats to 4 decimal places in global state and message bus
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshuaDodds committed Jul 1, 2023
1 parent 5ee7afd commit 622ff00
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib/global_state.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import sqlite3

from lib.helpers import publish_message
from lib.helpers import publish_message, reduce_decimal
from lib.constants import logging


Expand Down Expand Up @@ -51,13 +51,14 @@ def get(self, key):
return bool(False)
else:
return int(result_value)
except Exception as e:
except Exception as e: # noqa
return str(result_value)
else:
return 0

def set(self, key, value):
self.cursor.execute("INSERT OR REPLACE INTO data VALUES (?, ?)", (key, value))
publish_message(f"Cerbomoticzgx/GlobalState/{key}", message=value, retain=True)
_value = reduce_decimal(value)
self.cursor.execute("INSERT OR REPLACE INTO data VALUES (?, ?)", (key, _value))
publish_message(f"Cerbomoticzgx/GlobalState/{key}", message=_value, retain=True)

self.connection.commit()
12 changes: 12 additions & 0 deletions lib/helpers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,5 +78,17 @@ def get_seasonally_adjusted_max_charge_slots(batt_soc: float) -> int:
return 0


def reduce_decimal(value):
if '.' in value:
try:
float_value = float(value)
rounded_value = round(float_value, 4)
return str(rounded_value)
except ValueError:
return value
else:
return value


# Function Aliases
retrieve_message = get_current_value_from_mqtt

0 comments on commit 622ff00

Please sign in to comment.