forked from AlexxIT/PythonScriptsPro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsensor.py
More file actions
65 lines (49 loc) · 1.59 KB
/
sensor.py
File metadata and controls
65 lines (49 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import logging
from homeassistant.const import CONF_UNIT_OF_MEASUREMENT, CONF_NAME, CONF_ICON
from homeassistant.helpers.entity import Entity
logger = logging.getLogger(__name__)
async def async_setup_platform(hass, config, add_entities, discovery_info=None):
try:
if "file" in config:
finename = hass.config.path(config["file"])
with open(finename, "rt", encoding="utf-8") as f:
source = f.read()
elif "source" in config:
source = config["source"]
else:
return
code = compile(source, "<string>", "exec")
add_entities([PythonSensor(code, config)])
except:
logger.exception("Error init python script sensor")
class PythonSensor(Entity):
_state = None
def __init__(self, code, config: dict):
self.code = code
self.config = config
self.attributes = {}
async def async_added_to_hass(self):
self.async_schedule_update_ha_state(force_refresh=True)
@property
def name(self):
return self.config.get(CONF_NAME)
@property
def state(self):
return self._state
@state.setter
def state(self, value):
self._state = value
@property
def state_attributes(self):
return self.attributes
@property
def unit_of_measurement(self):
return self.config.get(CONF_UNIT_OF_MEASUREMENT)
@property
def icon(self):
return self.config.get(CONF_ICON)
def update(self):
try:
exec(self.code)
except:
logger.exception(f"Error update {self.name}")