Files
cantabile-ha-addons/src/edge/cantabile_edge/consent.py
T

65 lines
2.4 KiB
Python

# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The owner's consent to share energy data with Cantabile: one switch for
the whole site, on top of the mapping's per-entity consent (mapping.py).
Off until the owner turns it on. Kept in <state dir>/consent.json
({"share": bool, "at": unix time, "by": "panel"|"ha-addon-config",
"source", "text_version"}), written by the Hub's setup wizard and panel
(/usr/lib/cantabile/web) or, on an HA add-on site, by addon-run from the
add-on's configuration at installation;
never by support; re-read when it changes.
Off means: nothing is collected, and what is queued is not sent (deleted).
Control (v1) has its own switch in the same file, "control": true, off
unless set: the owner allows Cantabile to act on the devices whose controls
have their own consent (controls.py). Data sharing alone never allows
control. The Hub's panel writes it with the consent text that covers control
(pre-launch notes: a working text until the legal team's)."""
import json
import os
import time
class Consent:
def __init__(self, state_dir: str):
self.path = os.path.join(state_dir, "consent.json")
self._key = None
self._share = False
self._control = False
def _stat(self):
try:
st = os.stat(self.path)
return (st.st_ino, st.st_mtime_ns, st.st_size)
except OSError:
return None
def _load(self):
key = self._stat()
if key != self._key:
self._key = key
try:
with open(self.path) as f:
d = json.load(f)
self._share, self._control = d.get("share") is True, d.get("control") is True
except (OSError, ValueError, AttributeError):
self._share = self._control = False
@property
def share(self) -> bool:
self._load()
return self._share
@property
def control(self) -> bool:
self._load()
return self._control
def set(self, share: bool, by: str):
tmp = self.path + ".tmp"
with open(tmp, "w") as f:
# keeps the control switch as it was (the panel sets both)
json.dump({"share": bool(share), "control": self.control and bool(share), "at": int(time.time()),
"by": by}, f)
os.replace(tmp, self.path)
self._key = None