Repository navigation
Expand file tree
/
Copy pathmodels.py
More file actions
290 lines (227 loc) · 7.66 KB
/
Copy pathmodels.py
File metadata and controls
290 lines (227 loc) · 7.66 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import datetime
import json
import logging
import operator
import statistics
from collections import deque
from collections.abc import Callable
from typing import Literal
import paho.mqtt.client as mqtt_client
import requests
from jsonpath_ng import parse
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator
import mqtt
from notification import send_action_notification
logger = logging.getLogger(__name__)
class Sensors(BaseModel):
mqtt: str = ""
def add_mqtt(self):
pass
def add(self, sensor):
self[sensor.nam] = sensor
def start(self):
pass
SENSORS = {}
class Sensor(BaseModel):
name: str = Field(title="Sensor name")
route: str = Field(title="mqtt path")
json_path: str | None = None
return_type: Literal["float", "int", "str", "bool"] = "float"
connected: bool = False
ready: bool = False
value_list_length: int = 5
values: deque[float | int | bool | str] | None = None
def model_post_init(self, __context) -> None:
if self.values is None:
self.values = deque(maxlen=self.value_list_length)
def __str__(self):
return str(self.name)
@property
def mean(self) -> float | int | bool | str | None:
if not self.values:
return None
if self.return_type == "bool":
return self.values[-1]
return float(statistics.mean(self.values))
@property
def last(self):
if not self.values:
return None
return self.values[-1]
def _json_path_value(self, data):
if isinstance(data, bytes) or isinstance(data, str):
data = json.loads(data)
jsonpath_expr = parse(self.json_path)
matches = jsonpath_expr.find(data)
if matches:
return matches[0].value
else:
logging.error(
f"JSON path '{self.json_path}' not found in response for {self.name}"
)
return None
def _get_parsed_value(self, value):
parsed_value = None
if self.return_type == "bool":
if isinstance(value, bool):
parsed_value = value
elif isinstance(value, str):
parsed_value = value.lower() in ("true", "1", "on", "yes")
else:
parsed_value = bool(value)
elif self.return_type == "int":
parsed_value = int(float(value))
elif self.return_type == "float":
parsed_value = float(value)
else:
parsed_value = str(value)
return parsed_value
def add(self, value):
if self.json_path:
parsed_value = self._json_path_value(value)
else:
parsed_value = self._get_parsed_value(value)
if parsed_value is None:
return None
logging.debug(f"{self.name}.add({parsed_value}) mean:{self.mean}")
self.connected = True
if self.values is not None:
self.values.append(parsed_value)
return parsed_value
class MqttSensor(Sensor):
type: Literal["mqtt"] = "mqtt"
class HttpSensor(Sensor):
type: Literal["http"] = "http"
def get_add_value(self):
try:
response = requests.get(self.route, timeout=10)
response.raise_for_status()
data = response.json()
self.add(data)
logging.debug(f"HTTP sensor {self.name}: {data}")
except Exception as e:
logging.error(f"Error fetching HTTP sensor {self.name}: {e}")
self.connected = False
class TimeSensor(Sensor):
type: Literal["time"] = "time"
route: str = ""
connected: bool = True
@property
def mean(self):
return datetime.datetime.now().strftime("%H:%M")
def add_sensor(sensor):
if sensor.route in SENSORS:
raise ValueError("Sensor route alreasy exists")
SENSORS[sensor.route] = sensor
class SensorD(BaseModel):
ss: dict[str, MqttSensor | HttpSensor | TimeSensor] = {
"time": TimeSensor(name="time", return_type="str")
}
def add(self, sensor_data: dict | MqttSensor | HttpSensor | TimeSensor):
if isinstance(sensor_data, dict):
sensor_type = sensor_data.get("type", "mqtt")
if sensor_type == "mqtt":
sensor = MqttSensor(**sensor_data)
elif sensor_type == "http":
sensor = HttpSensor(**sensor_data)
elif sensor_type == "time":
sensor = TimeSensor(**sensor_data)
else:
raise ValueError(f"Unknown sensor type: {sensor_type}")
else:
sensor = sensor_data
self.ss[sensor.route] = sensor
self.ss[sensor.name] = sensor
return sensor
def __getitem__(self, key):
return self.ss[key]
def add_value(self, route, value):
self.ss[route].add(value)
def keys(self):
return self.ss.keys()
def values(self):
return self.ss.values()
VALID_OPERATOR = {
"<": operator.lt,
"<=": operator.le,
">": operator.gt,
">=": operator.ge,
"==": operator.eq,
"!=": operator.ne,
}
class Test(BaseModel):
sensor: MqttSensor | HttpSensor | TimeSensor
op: str
_operator: Callable = PrivateAttr()
@property
def operator(self):
return self._operator
value: float | str | int
@field_validator("op", mode="after")
@classmethod
def validate_op(cls, v):
valid_operators = VALID_OPERATOR.keys()
if v not in valid_operators:
raise ValueError(f"Invalid operator '{v}'. Must be one of: {valid_operators}")
return v
def __init__(self, **data):
super().__init__(**data)
self._operator = VALID_OPERATOR[self.op]
class Action(BaseModel):
name: str
route: str
_web_api = None
_recipients = None
def set_web_api(self, web_api):
self._web_api = web_api
def set_recipients(self, recipients):
self._recipients = recipients
def _send_email_notification(self, rule_context=None):
send_action_notification(self._recipients, self.name, rule_context)
def do(self, rule_context=None):
logger.info(f"Do {self.name}")
try:
response = requests.get(self.route)
if self._web_api:
self._web_api.log_action(self.name, self.route)
self._send_email_notification(rule_context)
logger.debug(f"Action {self.name} executed: {response.status_code}")
except Exception as e:
logger.error(f"Action {self.name} failed: {e}")
class Rule(BaseModel):
name: str
tests: list[Test]
action: Action
active: bool = True
class ConfigRule(BaseModel):
name: str
tests: list[tuple[str, str, float | str | int]]
action: str
active: bool = True
class Mqtt(BaseModel):
host: str
port: int
username: str
password: str
model_config = ConfigDict(arbitrary_types_allowed=True)
client: mqtt_client.Client | None = None
def set_client(self, sensord):
mqttc = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2)
mqttc.on_connect = mqtt.on_connect
mqttc.on_message = mqtt.on_message
mqttc.user_data_set(sensord)
if self.username:
mqttc.username_pw_set(self.username, self.password)
try:
mqttc.connect(self.host)
except OSError:
raise ConnectionError(f"Could not connect to {self.host}")
mqttc.loop_start() # threaded client interface
class Global(BaseModel):
recipients: list[str] = []
class Config(BaseModel):
global_: Global | None = Field(None, alias="global")
mqtt: Mqtt
sensors: list[dict]
actions: list[Action]
rules: list[ConfigRule]