| 1 |
import asyncio |
| 2 |
from dataclasses import dataclass, field |
| 3 |
import datetime |
| 4 |
from enum import IntEnum |
| 5 |
import re |
| 6 |
import struct |
| 7 |
import math |
| 8 |
from typing import List, NamedTuple |
| 9 |
|
| 10 |
from bleak import BleakClient |
| 11 |
from bleak import BleakScanner |
| 12 |
from bleak.backends.device import BLEDevice |
| 13 |
from bleak.uuids import normalize_uuid_16 |
| 14 |
|
| 15 |
|
| 16 |
class Aranet4Error(Exception): |
| 17 |
pass |
| 18 |
|
| 19 |
|
| 20 |
class Param(IntEnum): |
| 21 |
"""Enums for the different log_size available""" |
| 22 |
|
| 23 |
TEMPERATURE = 1 |
| 24 |
HUMIDITY = 2 |
| 25 |
PRESSURE = 3 |
| 26 |
CO2 = 4 |
| 27 |
HUMIDITY2 = 5 |
| 28 |
PULSES = 6 |
| 29 |
RADIATION_DOSE = 7 |
| 30 |
RADIATION_DOSE_RATE = 8 |
| 31 |
RADIATION_DOSE_INTEGRAL = 9 |
| 32 |
RADON_CONCENTRATION = 10 |
| 33 |
|
| 34 |
class Color(IntEnum): |
| 35 |
"""Enum for the different status colors""" |
| 36 |
|
| 37 |
ERROR = 0 |
| 38 |
GREEN = 1 |
| 39 |
YELLOW = 2 |
| 40 |
RED = 3 |
| 41 |
|
| 42 |
class Status(IntEnum): |
| 43 |
"""Enum for the different status alerts""" |
| 44 |
|
| 45 |
OFF = 0 |
| 46 |
UNDER = 1 |
| 47 |
OVER = 2 |
| 48 |
DASH = 3 |
| 49 |
|
| 50 |
class AranetType(IntEnum): |
| 51 |
"""Enum for the different Aranet devices""" |
| 52 |
|
| 53 |
ARANET4 = 0 |
| 54 |
ARANET2 = 1 |
| 55 |
ARANET_RADIATION = 2 |
| 56 |
ARANET_RADON = 3 |
| 57 |
UNKNOWN = 255 |
| 58 |
|
| 59 |
@property |
| 60 |
def model(self): |
| 61 |
description = { |
| 62 |
AranetType.ARANET4: "Aranet4", |
| 63 |
AranetType.ARANET2: "Aranet2", |
| 64 |
AranetType.ARANET_RADIATION: "Aranet Radiation", |
| 65 |
AranetType.ARANET_RADON: "Aranet Radon Plus", |
| 66 |
AranetType.UNKNOWN: "Unknown Aranet Device" |
| 67 |
} |
| 68 |
return description.get(self, "Unknown Aranet Device") |
| 69 |
|
| 70 |
@dataclass |
| 71 |
class Aranet4HistoryDelegate: |
| 72 |
""" |
| 73 |
When collecting the historical records they are sent using BLE |
| 74 |
notifications. This class takes those notifications and presents them |
| 75 |
as a Python dataclass |
| 76 |
""" |
| 77 |
|
| 78 |
handle: str |
| 79 |
param: Param |
| 80 |
size: int |
| 81 |
client: object |
| 82 |
result: list = field(default_factory=list) |
| 83 |
|
| 84 |
def __post_init__(self): |
| 85 |
self.result = _empty_reading(self.size) |
| 86 |
|
| 87 |
def handle_notification(self, sender: int, packet: bytes): |
| 88 |
""" |
| 89 |
Method to use with Bleak's `start_notify` function. |
| 90 |
Takes data returned and process it before storing |
| 91 |
""" |
| 92 |
data_type, start, count = struct.unpack("<BHB", packet[:4]) |
| 93 |
if start > self.size or count == 0: |
| 94 |
self.client.reading = False |
| 95 |
return |
| 96 |
|
| 97 |
if self.param != data_type: |
| 98 |
( |
| 99 |
print(f"ERROR: invalid parameter. Got {data_type:02X}, expected {self.param:02X}") |
| 100 |
) |
| 101 |
return |
| 102 |
pattern = "<B" if data_type == Param.HUMIDITY else "<H" |
| 103 |
|
| 104 |
data_values = struct.iter_unpack(pattern, packet[4:]) |
| 105 |
for idx, value in enumerate(data_values, start - 1): |
| 106 |
if idx == start - 1 + count: |
| 107 |
break |
| 108 |
self.result[idx] = CurrentReading._set(self.param, value[0]) |
| 109 |
|
| 110 |
|
| 111 |
@dataclass |
| 112 |
class CurrentReading: |
| 113 |
"""dataclass to store the information when querying the devices current settings""" |
| 114 |
|
| 115 |
name: str = "" |
| 116 |
version: str = "" |
| 117 |
type: AranetType = AranetType.UNKNOWN |
| 118 |
|
| 119 |
# Aranet2, Aranet4 |
| 120 |
temperature: float = -1 |
| 121 |
humidity: float = -1 |
| 122 |
|
| 123 |
# Aranet 4 |
| 124 |
pressure: float = -1 |
| 125 |
co2: int = -1 |
| 126 |
|
| 127 |
# Aranet Radiation |
| 128 |
radiation_rate: float = -1 |
| 129 |
radiation_total: float = -1 |
| 130 |
radiation_duration: int = -1 |
| 131 |
|
| 132 |
# Aranet Radon |
| 133 |
radon_concentration: int = -1 |
| 134 |
radon_concentration_avg_24h: int = -1 |
| 135 |
radon_concentration_avg_7d: int = -1 |
| 136 |
radon_concentration_avg_30d: int = -1 |
| 137 |
|
| 138 |
battery: int = -1 |
| 139 |
status: int = -1 |
| 140 |
status_temperature: int = -1 |
| 141 |
status_humidity: int = -1 |
| 142 |
interval: int = -1 |
| 143 |
ago: int = -1 |
| 144 |
stored: int = -1 |
| 145 |
counter: int = -1 |
| 146 |
|
| 147 |
def toString(self, advertisement=None): |
| 148 |
ret = "=======================================\n" |
| 149 |
ret += f" Name: {self.name}\n" |
| 150 |
|
| 151 |
if advertisement: |
| 152 |
ret += f" Address: {advertisement.device.address}\n" |
| 153 |
ret += f" RSSI: {advertisement.rssi} dBm\n" |
| 154 |
|
| 155 |
if self.stored > 0: |
| 156 |
ret += f" Logs: {self.stored}\n" |
| 157 |
|
| 158 |
ret += "---------------------------------------\n" |
| 159 |
|
| 160 |
if self.type == AranetType.ARANET4: |
| 161 |
ret += f" CO2: {self.co2} ppm\n" |
| 162 |
ret += f" Temperature: {self.temperature:.01f} \u00b0C\n" |
| 163 |
ret += f" Humidity: {self.humidity} %\n" |
| 164 |
ret += f" Pressure: {self.pressure:.01f} hPa\n" |
| 165 |
ret += f" Battery: {self.battery} %\n" |
| 166 |
ret += f" Status Display: {self.status.name}\n" |
| 167 |
ret += f" Age: {self.ago}/{self.interval} s\n" |
| 168 |
elif self.type == AranetType.ARANET2: |
| 169 |
ret += f" Temperature: {self.temperature:.01f} \u00b0C\n" |
| 170 |
ret += f" Humidity: {self.humidity} %\n" |
| 171 |
ret += f" Battery: {self.battery} %\n" |
| 172 |
ret += f" Status Temp.: {self.status_temperature.name}\n" |
| 173 |
ret += f" Status Humid.: {self.status_humidity.name}\n" |
| 174 |
ret += f" Age: {self.ago}/{self.interval} s\n" |
| 175 |
elif self.type == AranetType.ARANET_RADIATION: |
| 176 |
m = math.floor(self.radiation_duration / 60 % 60) |
| 177 |
h = math.floor(self.radiation_duration / 3600 % 24) |
| 178 |
d = math.floor(self.radiation_duration / 86400) |
| 179 |
|
| 180 |
dose_duration = str(m) + "m" |
| 181 |
if h > 0: |
| 182 |
dose_duration = str(h) + "h " + dose_duration |
| 183 |
if d > 0: |
| 184 |
dose_duration = str(d) + "d " + dose_duration |
| 185 |
|
| 186 |
ret += f" Dose rate: {self.radiation_rate/1000:.02f} uSv/h\n" |
| 187 |
ret += f" Dose total: {self.radiation_total/1000000:.04f} mSv/{dose_duration}\n" |
| 188 |
ret += f" Battery: {self.battery} %\n" |
| 189 |
ret += f" Age: {self.ago}/{self.interval} s\n" |
| 190 |
elif self.type == AranetType.ARANET_RADON: |
| 191 |
ret += f" Radon Conc.: {self.radon_concentration} Bq/m3\n" |
| 192 |
ret += f" Temperature: {self.temperature:.01f} \u00b0C\n" |
| 193 |
ret += f" Humidity: {self.humidity} %\n" |
| 194 |
ret += f" Pressure: {self.pressure:.01f} hPa\n" |
| 195 |
ret += f" Battery: {self.battery} %\n" |
| 196 |
ret += f" Status Display: {self.status.name}\n" |
| 197 |
ret += f" Age: {self.ago}/{self.interval} s\n" |
| 198 |
|
| 199 |
else: |
| 200 |
ret += " Unknown device type\n" |
| 201 |
|
| 202 |
return ret |
| 203 |
|
| 204 |
def toDict(self): |
| 205 |
data = { |
| 206 |
"battery": self.battery, |
| 207 |
"type": self.type.name |
| 208 |
} |
| 209 |
|
| 210 |
if self.type == AranetType.ARANET2: |
| 211 |
data["temperature"] = self.temperature |
| 212 |
data["humidity"] = self.humidity |
| 213 |
elif self.type == AranetType.ARANET4: |
| 214 |
data["co2"] = self.co2 |
| 215 |
data["temperature"] = self.temperature |
| 216 |
data["pressure"] = self.pressure |
| 217 |
data["humidity"] = self.humidity |
| 218 |
elif self.type == AranetType.ARANET_RADIATION: |
| 219 |
data["radiation_rate"] = self.radiation_rate |
| 220 |
data["radiation_total"] = self.radiation_total |
| 221 |
data["radiation_duration"] = self.radiation_duration |
| 222 |
|
| 223 |
return data |
| 224 |
|
| 225 |
def decode(self, value: tuple, type: AranetType, gatt=False): |
| 226 |
"""Process advertisement or gatt data""" |
| 227 |
|
| 228 |
self.type = type |
| 229 |
if type == AranetType.ARANET4: |
| 230 |
self._decode_aranet4(value, gatt) |
| 231 |
elif type == AranetType.ARANET2: |
| 232 |
self._decode_aranet2(value, gatt) |
| 233 |
elif type == AranetType.ARANET_RADIATION: |
| 234 |
self._decode_aranetR(value, gatt) |
| 235 |
elif type == AranetType.ARANET_RADON: |
| 236 |
self._decode_aranetRn(value, gatt) |
| 237 |
|
| 238 |
def _decode_aranet4(self, value: tuple, gatt=False): |
| 239 |
"""Process Aranet4 data - CO2, Temperature, Humidity, Pressure""" |
| 240 |
|
| 241 |
self.co2 = self._set(Param.CO2, value[0]) |
| 242 |
self.temperature = self._set(Param.TEMPERATURE, value[1]) |
| 243 |
self.pressure = self._set(Param.PRESSURE, value[2]) |
| 244 |
self.humidity = self._set(Param.HUMIDITY, value[3]) |
| 245 |
self.battery = value[4] |
| 246 |
self.status = Color(value[5]) |
| 247 |
# If extended data list |
| 248 |
if len(value) > 6: |
| 249 |
self.interval = value[6] |
| 250 |
self.ago = value[7] |
| 251 |
|
| 252 |
def _decode_aranet2(self, value: tuple, gatt=False): |
| 253 |
"""Process Aranet2 data - Temperature, Humidity""" |
| 254 |
|
| 255 |
# order from gatt and advertisements are different |
| 256 |
if gatt: |
| 257 |
self.temperature = self._set(Param.TEMPERATURE, value[4]) |
| 258 |
self.humidity = self._set(Param.HUMIDITY2, value[5]) |
| 259 |
self.battery = value[3] |
| 260 |
self.status_humidity = Status(value[6] & 0b0011) |
| 261 |
self.status_temperature = Status((value[6] & 0b1100) >> 2) |
| 262 |
self.interval = value[1] |
| 263 |
self.ago = value[2] |
| 264 |
else: |
| 265 |
self.temperature = self._set(Param.TEMPERATURE, value[1]) |
| 266 |
self.humidity = self._set(Param.HUMIDITY2, value[3]) |
| 267 |
self.status_humidity = Status(value[6] & 0b0011) |
| 268 |
self.status_temperature = Status((value[6] & 0b1100) >> 2) |
| 269 |
self.battery = value[5] |
| 270 |
self.interval = value[7] |
| 271 |
self.ago = value[8] |
| 272 |
self.counter = value[9] |
| 273 |
|
| 274 |
def _decode_aranetR(self, value: tuple, gatt=False): |
| 275 |
"""Process Aranet Radiation data - radiation dose""" |
| 276 |
# order from gatt and advertisements are different |
| 277 |
if gatt: |
| 278 |
self.radiation_duration = value[6] |
| 279 |
self.radiation_rate = value[4] |
| 280 |
self.radiation_total = value[5] |
| 281 |
self.battery = value[3] |
| 282 |
self.interval = value[1] |
| 283 |
self.ago = value[2] |
| 284 |
else: |
| 285 |
self.radiation_total = value[0] |
| 286 |
self.radiation_duration = value[1] |
| 287 |
self.radiation_rate = value[2] |
| 288 |
self.battery = value[4] |
| 289 |
self.interval = value[6] |
| 290 |
self.ago = value[7] |
| 291 |
self.counter = value[8] |
| 292 |
|
| 293 |
def _decode_aranetRn(self, value: tuple, gatt=False): |
| 294 |
"""Process Aranet Radon data""" |
| 295 |
# order from gatt and advertisements are different |
| 296 |
if gatt: |
| 297 |
self.battery = value[3] |
| 298 |
self.temperature = self._set(Param.TEMPERATURE, value[4]) |
| 299 |
self.pressure = self._set(Param.PRESSURE, value[5]) |
| 300 |
self.humidity = self._set(Param.HUMIDITY2, value[6]) |
| 301 |
self.radon_concentration = self._set(Param.RADON_CONCENTRATION, value[7]) |
| 302 |
self.status = Color(value[8]) |
| 303 |
self.radon_concentration_avg_24h = self._parse_avg_radon(value[9], value[10])["value"] |
| 304 |
self.radon_concentration_avg_7d = self._parse_avg_radon(value[11], value[12])["value"] |
| 305 |
self.radon_concentration_avg_30d = self._parse_avg_radon(value[13], value[14])["value"] |
| 306 |
else: |
| 307 |
self.radon_concentration = self._set(Param.RADON_CONCENTRATION, value[0]) |
| 308 |
self.temperature = self._set(Param.TEMPERATURE, value[1]) |
| 309 |
self.pressure = self._set(Param.PRESSURE, value[2]) |
| 310 |
self.humidity = self._set(Param.HUMIDITY2, value[3]) |
| 311 |
self.battery = value[5] |
| 312 |
self.status = Color(value[6]) |
| 313 |
self.interval = value[7] |
| 314 |
self.ago = value[8] |
| 315 |
self.counter = value[9] |
| 316 |
|
| 317 |
@staticmethod |
| 318 |
def _parse_avg_radon(time, average) -> dict: |
| 319 |
inProgress = average >= 0xff000000 |
| 320 |
progress = -1 |
| 321 |
value = average |
| 322 |
|
| 323 |
if inProgress: |
| 324 |
progress = average & 0x00FFFFFF |
| 325 |
value = -1 |
| 326 |
|
| 327 |
return { |
| 328 |
"time": time, |
| 329 |
"value": value, |
| 330 |
"progress": progress |
| 331 |
} |
| 332 |
|
| 333 |
@staticmethod |
| 334 |
def _set(param: Param, value: int): |
| 335 |
""" |
| 336 |
While in CO2 calibration mode Aranet4 did not take new measurements and |
| 337 |
stores Magic numbers in measurement history. |
| 338 |
Here data is converted with checking for Magic numbers. |
| 339 |
""" |
| 340 |
invalid_reading_flag = True |
| 341 |
multiplier = 1 |
| 342 |
if param == Param.CO2: |
| 343 |
invalid_reading_flag = value >> 15 == 1 |
| 344 |
multiplier = 1 |
| 345 |
elif param == Param.PRESSURE: |
| 346 |
invalid_reading_flag = value >> 15 == 1 |
| 347 |
multiplier = 0.1 |
| 348 |
elif param == Param.TEMPERATURE: |
| 349 |
invalid_reading_flag = value >> 14 & 1 == 1 |
| 350 |
multiplier = 0.05 |
| 351 |
elif param == Param.HUMIDITY: |
| 352 |
invalid_reading_flag = value >> 8 |
| 353 |
multiplier = 1 |
| 354 |
elif param == Param.HUMIDITY2: |
| 355 |
invalid_reading_flag = value >> 15 == 1 |
| 356 |
multiplier = 0.1 |
| 357 |
elif param == Param.RADIATION_DOSE: |
| 358 |
invalid_reading_flag = value >> 15 == 1 |
| 359 |
multiplier = 1 # nSv |
| 360 |
elif param == Param.RADIATION_DOSE_RATE: |
| 361 |
invalid_reading_flag = value >> 15 == 1 |
| 362 |
multiplier = 10 # nSv/h |
| 363 |
elif param == Param.RADIATION_DOSE_INTEGRAL: |
| 364 |
invalid_reading_flag = value >> 63 == 1 |
| 365 |
multiplier = 1 # nSv |
| 366 |
elif param == Param.RADON_CONCENTRATION: |
| 367 |
# 0x1f00 general error |
| 368 |
# 0x1f01 no data |
| 369 |
# 0x1f02 Hi humidity in sensor chamber |
| 370 |
invalid_reading_flag = value >= 0x1f00 |
| 371 |
multiplier = 1 # Bq/m3 |
| 372 |
|
| 373 |
if invalid_reading_flag: |
| 374 |
return -1 |
| 375 |
if isinstance(multiplier, float): |
| 376 |
return round(value * multiplier, 1) |
| 377 |
return value * multiplier |
| 378 |
|
| 379 |
|
| 380 |
@dataclass(order=True) |
| 381 |
class Version: |
| 382 |
major: int = -1 |
| 383 |
minor: int = -1 |
| 384 |
patch: int = -1 |
| 385 |
|
| 386 |
def __init__(self, major, minor, patch): |
| 387 |
self.major = major |
| 388 |
self.minor = minor |
| 389 |
self.patch = patch |
| 390 |
|
| 391 |
def __str__(self): |
| 392 |
return f"v{self.major}.{self.minor}.{self.patch}" |
| 393 |
|
| 394 |
|
| 395 |
class CalibrationState(IntEnum): |
| 396 |
"""Enum for calibration state""" |
| 397 |
NOT_ACTIVE = 0 |
| 398 |
END_REQUEST = 1 |
| 399 |
IN_PROGRESS = 2 |
| 400 |
ERROR = 3 |
| 401 |
|
| 402 |
|
| 403 |
@dataclass |
| 404 |
class ManufacturerData: |
| 405 |
"""dataclass to store manufacturer data""" |
| 406 |
|
| 407 |
disconnected: bool = False |
| 408 |
calibration_state: CalibrationState = -1 |
| 409 |
dfu_active: bool = False |
| 410 |
integrations: bool = False |
| 411 |
version: Version = None |
| 412 |
|
| 413 |
def decode(self, value: tuple): |
| 414 |
self.disconnected = self._get_b(value[0], 0) |
| 415 |
self.calibration_state = CalibrationState(self._get_uint2(value[0], 2)) |
| 416 |
self.dfu_active = self._get_b(value[0], 4) |
| 417 |
self.integrations = self._get_b(value[0], 5) |
| 418 |
self.version = Version(value[3], value[2], value[1]) |
| 419 |
|
| 420 |
def _get_b(self, value, pos): |
| 421 |
return (value & (1 << pos)) != 0 |
| 422 |
|
| 423 |
def _get_uint2(self, value, pos): |
| 424 |
return (value >> pos) & 0x03 |
| 425 |
|
| 426 |
|
| 427 |
@dataclass |
| 428 |
class Aranet4Advertisement: |
| 429 |
"""dataclass to store the information aboud scanned aranet4 device""" |
| 430 |
|
| 431 |
device: BLEDevice = None |
| 432 |
readings: CurrentReading = None |
| 433 |
manufacturer_data: ManufacturerData = None |
| 434 |
rssi: int = None |
| 435 |
|
| 436 |
def __init__(self, device = None, ad_data = None): |
| 437 |
self.device = device |
| 438 |
|
| 439 |
if device and ad_data: |
| 440 |
has_manufacturer_data = Aranet4.MANUFACTURER_ID in ad_data.manufacturer_data |
| 441 |
self.rssi = getattr(ad_data, "rssi", None) |
| 442 |
|
| 443 |
if has_manufacturer_data: |
| 444 |
mf_data = ManufacturerData() |
| 445 |
raw_bytes = bytearray(ad_data.manufacturer_data[Aranet4.MANUFACTURER_ID]) |
| 446 |
if len(raw_bytes) < 5: |
| 447 |
# invalid manufacturer data |
| 448 |
return |
| 449 |
|
| 450 |
# Passive scan may return result with no name. |
| 451 |
valid_name = device.name and device.name.startswith(("Aranet4", "Aranet2", "Aranet\u2622", "AranetRn")) |
| 452 |
cond_name = valid_name and device.name.startswith("Aranet4") |
| 453 |
cond_len = not valid_name and len(raw_bytes) in [7,22] |
| 454 |
|
| 455 |
if cond_name or cond_len: # Should be Aranet4 |
| 456 |
raw_bytes.insert(0,0) |
| 457 |
|
| 458 |
# Basic info |
| 459 |
value_fmt = "<BBBB" |
| 460 |
value = struct.unpack(value_fmt, raw_bytes[1:5]) |
| 461 |
mf_data.decode(value) |
| 462 |
self.manufacturer_data = mf_data |
| 463 |
|
| 464 |
if not mf_data.integrations: |
| 465 |
return |
| 466 |
|
| 467 |
# Extended info / measurements |
| 468 |
aranetv = raw_bytes[0] |
| 469 |
|
| 470 |
if aranetv == 0: # Aranet4 |
| 471 |
value_fmt = "<xxxxxxxxxHHHBBBHH" |
| 472 |
aranetv = AranetType.ARANET4 |
| 473 |
elif aranetv == 1: # Aranet2 |
| 474 |
value_fmt = "<xxxxxxxxHHHHBBBHHB" |
| 475 |
aranetv = AranetType.ARANET2 |
| 476 |
elif aranetv == 2: # Aranet Radiation |
| 477 |
value_fmt = "<xxxxxxIIHBBBHHB" |
| 478 |
aranetv = AranetType.ARANET_RADIATION |
| 479 |
elif aranetv == 3: # Aranet Radon |
| 480 |
value_fmt = "<xxxxxxxxHHHHBBBHHB" |
| 481 |
aranetv = AranetType.ARANET_RADON |
| 482 |
else: |
| 483 |
value_fmt = "" |
| 484 |
aranetv = None |
| 485 |
|
| 486 |
end = struct.calcsize(value_fmt) |
| 487 |
if end > 0 and len(raw_bytes[:end]) == end: |
| 488 |
value = struct.unpack(value_fmt, raw_bytes[:end]) |
| 489 |
self.readings = CurrentReading() |
| 490 |
self.readings.decode(value, aranetv) |
| 491 |
self.readings.name = device.name |
| 492 |
else: |
| 493 |
mf_data.integrations = False |
| 494 |
|
| 495 |
|
| 496 |
@dataclass |
| 497 |
class RecordItem: |
| 498 |
"""dataclass to store historical records""" |
| 499 |
|
| 500 |
date: datetime |
| 501 |
temperature: float |
| 502 |
humidity: int |
| 503 |
pressure: float |
| 504 |
co2: int |
| 505 |
rad_dose: float |
| 506 |
rad_dose_rate: float |
| 507 |
rad_dose_total: float |
| 508 |
radon_concentration: int |
| 509 |
|
| 510 |
|
| 511 |
@dataclass |
| 512 |
class Filter: |
| 513 |
"""dataclass to store log filter information""" |
| 514 |
|
| 515 |
begin: int |
| 516 |
end: int |
| 517 |
incl_temperature: bool |
| 518 |
incl_humidity: int |
| 519 |
incl_pressure: bool |
| 520 |
incl_co2: bool |
| 521 |
incl_rad_dose: bool |
| 522 |
incl_rad_dose_rate: bool |
| 523 |
incl_rad_dose_total: bool |
| 524 |
incl_radon_concentration: bool |
| 525 |
|
| 526 |
|
| 527 |
@dataclass |
| 528 |
class Record: |
| 529 |
name: str |
| 530 |
version: str |
| 531 |
records_on_device: int |
| 532 |
filter: Filter |
| 533 |
value: List[RecordItem] = field(default_factory=list) |
| 534 |
|
| 535 |
@dataclass |
| 536 |
class SensorState: |
| 537 |
"""dataclass to store sensor state values""" |
| 538 |
|
| 539 |
type: AranetType = AranetType.UNKNOWN |
| 540 |
buzzerSetting: str = "unknown" |
| 541 |
calibrationState: str = "unknown" |
| 542 |
calibrationProgress: int = 0 |
| 543 |
warningPreset: str = "unknown" |
| 544 |
isLoRaEnabled: bool = False |
| 545 |
temperatureUnit: str = "unknown" |
| 546 |
isPulseBeepOn: bool = False |
| 547 |
isUsingCustomThreshold: bool = False |
| 548 |
isAutomaticCalibrationEnabled: bool = False |
| 549 |
radiationDisplayUnits: str = "unknown" |
| 550 |
radonDisplayUnits: str = "unknown" |
| 551 |
isBuzzerAvailable: bool = False |
| 552 |
bluetoothRange: str = "unknown" |
| 553 |
isOpenForIntegration: bool = False |
| 554 |
|
| 555 |
def decode(self, t): |
| 556 |
isAranet2 = t[0] == 0xF2 # Aranet2 |
| 557 |
isAranet4 = t[0] == 0xF1 # Aranet4 |
| 558 |
isNucleo = t[0] == 0xF4 # Aranet Radiation |
| 559 |
isRadon = t[0] == 0xF3 # Aranet Radon |
| 560 |
c = format(ord(chr(t[1])), "08b")[::-1] |
| 561 |
o = format(ord(chr(t[2])), "08b")[::-1] |
| 562 |
|
| 563 |
if isAranet4: |
| 564 |
self.type = AranetType.ARANET4 |
| 565 |
elif isAranet2: |
| 566 |
self.type = AranetType.ARANET2 |
| 567 |
elif isNucleo: |
| 568 |
self.type = AranetType.ARANET_RADIATION |
| 569 |
elif isRadon: |
| 570 |
self.type = AranetType.ARANET_RADON |
| 571 |
else: |
| 572 |
self.type = AranetType.UNKNOWN |
| 573 |
|
| 574 |
self.buzzerSetting = ( |
| 575 |
"none" if isAranet2 else |
| 576 |
"off" if not _eval(c[0]) else |
| 577 |
"on" if isRadon else |
| 578 |
"once" if not _eval(c[1]) else |
| 579 |
"each" |
| 580 |
) |
| 581 |
|
| 582 |
self.calibrationState = self.cond(isAranet4, self.parseCalibrationState(t[1]), "none") |
| 583 |
self.calibrationProgress = self.cond(isAranet4, t[3], 0) |
| 584 |
self.warningPreset = self.cond(isAranet2, self.cond(t[3] == 1, "ISO", "custom"), "none") |
| 585 |
self.isLoRaEnabled = self.cond(c[4], True, False) |
| 586 |
self.temperatureUnit = self.cond(isNucleo, "none", self.cond(c[5], "C", "F")) |
| 587 |
self.isPulseBeepOn = self.cond(isNucleo, _eval(c[5]), False) |
| 588 |
self.isUsingCustomThreshold = c[6] == (isNucleo or isRadon) |
| 589 |
self.isAutomaticCalibrationEnabled = isAranet4 and c[7] |
| 590 |
self.radiationDisplayUnits = self.cond(isNucleo, self.cond(c[7], "Sv", "rem"), "none") |
| 591 |
self.radonDisplayUnits = ( |
| 592 |
"none" if not isRadon else |
| 593 |
"Bq/m³" if _eval(c[7]) else |
| 594 |
"pCi/L" |
| 595 |
) |
| 596 |
self.isBuzzerAvailable = self.cond(isNucleo or isRadon, True, isAranet4 and _eval(o[0])) |
| 597 |
self.bluetoothRange = self.cond(o[1], "extended", "normal") |
| 598 |
self.isOpenForIntegration = _eval(o[7]) |
| 599 |
|
| 600 |
@staticmethod |
| 601 |
def parseCalibrationState(e): |
| 602 |
t = format(ord(chr(e)), "08b")[::-1] |
| 603 |
return SensorState.cond( |
| 604 |
t[3], |
| 605 |
SensorState.cond(t[2], "inErrorState", "endRequest"), |
| 606 |
SensorState.cond(t[2], "inProgress", "notActive") |
| 607 |
) |
| 608 |
|
| 609 |
@staticmethod |
| 610 |
def cond(check, true_condition, false_condition): |
| 611 |
if _eval(check): |
| 612 |
return true_condition |
| 613 |
return false_condition |
| 614 |
|
| 615 |
|
| 616 |
class HistoryHeader(NamedTuple): |
| 617 |
param: int |
| 618 |
interval: int |
| 619 |
total_readings: int |
| 620 |
ago: int |
| 621 |
start: int |
| 622 |
count: int |
| 623 |
|
| 624 |
|
| 625 |
def _empty_reading(size): |
| 626 |
return [-1] * size |
| 627 |
|
| 628 |
|
| 629 |
class Aranet4: |
| 630 |
|
| 631 |
# Param return value if no data |
| 632 |
AR4_NO_DATA_FOR_PARAM = -1 |
| 633 |
|
| 634 |
# Company Identifier (Akciju sabiedriba "SAF TEHNIKA") |
| 635 |
MANUFACTURER_ID = 0x0702 |
| 636 |
|
| 637 |
# GAP Service |
| 638 |
SERVICE_GAP = normalize_uuid_16(0x1800) |
| 639 |
|
| 640 |
# GAP Service Characteristics |
| 641 |
CHARACTERISTIC_DEVICE_NAME = normalize_uuid_16(0x2a00) |
| 642 |
CHARACTERISTIC_APPEARANCE = normalize_uuid_16(0x2a01) |
| 643 |
|
| 644 |
# Device Information Service |
| 645 |
SERVICE_DIS = normalize_uuid_16(0x180a) |
| 646 |
|
| 647 |
# Device Information Service Characteristics |
| 648 |
CHARACTERISTIC_SYSTEM_ID = normalize_uuid_16(0x2a23) |
| 649 |
CHARACTERISTIC_MODEL_NUMBER = normalize_uuid_16(0x2a24) |
| 650 |
CHARACTERISTIC_SERIAL_NO = normalize_uuid_16(0x2a25) |
| 651 |
CHARACTERISTIC_SW_REV = normalize_uuid_16(0x2a26) |
| 652 |
CHARACTERISTIC_HW_REV = normalize_uuid_16(0x2a27) |
| 653 |
CHARACTERISTIC_SW_REV_FACTORY = normalize_uuid_16(0x2a28) |
| 654 |
CHARACTERISTIC_MANUFACTURER_NAME = normalize_uuid_16(0x2a29) |
| 655 |
|
| 656 |
# Battery Service |
| 657 |
SERVICE_BATTERY = normalize_uuid_16(0x180f) |
| 658 |
|
| 659 |
# Battery Service Characteristics |
| 660 |
CHARACTERISTIC_BATTERY_LEVEL = normalize_uuid_16(0x2a19) |
| 661 |
|
| 662 |
# SAF Tehnika Service |
| 663 |
SERVICE_SAF_TEHNIKA = normalize_uuid_16(0xfce0) # v1.2.0 and later |
| 664 |
SERVICE_SAF_TEHNIKA_OLD = "f0cd1400-95da-4f4b-9ac8-aa55d312af0c" # until v1.2.0 |
| 665 |
|
| 666 |
# SAF Tehnika Service Characteristics (Aranet2 has different readings characteristic uuids) |
| 667 |
CHARACTERISTIC_SENSOR_STATE = "f0cd1401-95da-4f4b-9ac8-aa55d312af0c" |
| 668 |
CHARACTERISTIC_CMD = "f0cd1402-95da-4f4b-9ac8-aa55d312af0c" |
| 669 |
CHARACTERISTIC_CALIBRATION_DATA = "f0cd1502-95da-4f4b-9ac8-aa55d312af0c" |
| 670 |
CHARACTERISTIC_CURRENT_READINGS = "f0cd1503-95da-4f4b-9ac8-aa55d312af0c" |
| 671 |
CHARACTERISTIC_CURRENT_READINGS_AR2 = "f0cd1504-95da-4f4b-9ac8-aa55d312af0c" # Aranet2 Only |
| 672 |
CHARACTERISTIC_TOTAL_READINGS = "f0cd2001-95da-4f4b-9ac8-aa55d312af0c" |
| 673 |
CHARACTERISTIC_INTERVAL = "f0cd2002-95da-4f4b-9ac8-aa55d312af0c" |
| 674 |
CHARACTERISTIC_HISTORY_READINGS_V1 = "f0cd2003-95da-4f4b-9ac8-aa55d312af0c" |
| 675 |
CHARACTERISTIC_SECONDS_SINCE_UPDATE = "f0cd2004-95da-4f4b-9ac8-aa55d312af0c" |
| 676 |
CHARACTERISTIC_HISTORY_READINGS_V2 = "f0cd2005-95da-4f4b-9ac8-aa55d312af0c" |
| 677 |
CHARACTERISTIC_CURRENT_READINGS_DET = "f0cd3001-95da-4f4b-9ac8-aa55d312af0c" |
| 678 |
CHARACTERISTIC_CURRENT_READINGS_A = "f0cd3002-95da-4f4b-9ac8-aa55d312af0c" |
| 679 |
CHARACTERISTIC_CURRENT_READINGS_A_AR2 = "f0cd3003-95da-4f4b-9ac8-aa55d312af0c" # Aranet2 Only |
| 680 |
|
| 681 |
# Nordic Semiconductor ASA Service |
| 682 |
SERVICE_NORDIC_SEMICONDUCTOR = normalize_uuid_16(0xfe59) |
| 683 |
|
| 684 |
# Nordic Semiconductor ASA Service Characteristics |
| 685 |
CHARACTERISTIC_SECURE_DFU = "8ec90003-f315-4f60-9fb8-838830daea50" |
| 686 |
|
| 687 |
# Regexp |
| 688 |
REGEX_MAC = "([0-9a-f]{2}[:-]){5}([0-9a-f]{2})" |
| 689 |
REGEX_UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" |
| 690 |
REGEX_ADDR = f"({REGEX_MAC})|({REGEX_UUID})" |
| 691 |
|
| 692 |
def __init__(self, address: str): |
| 693 |
if not re.match(self.REGEX_ADDR, address.lower()): |
| 694 |
raise Aranet4Error("Invalid device address") |
| 695 |
|
| 696 |
self.address = address |
| 697 |
self.device = BleakClient(address) |
| 698 |
self.reading = True |
| 699 |
|
| 700 |
def __del__(self): |
| 701 |
"""Close remote""" |
| 702 |
if self.device.is_connected: |
| 703 |
asyncio.shield(self.device.disconnect()) |
| 704 |
|
| 705 |
async def connect(self): |
| 706 |
"""Connect to remote device""" |
| 707 |
await self.device.connect() |
| 708 |
|
| 709 |
async def current_readings(self, details: bool = False): |
| 710 |
"""Extract current readings from remote device""" |
| 711 |
readings = CurrentReading() |
| 712 |
|
| 713 |
new_aranet_char = self.device.services.get_characteristic( |
| 714 |
self.CHARACTERISTIC_CURRENT_READINGS_AR2 |
| 715 |
) |
| 716 |
|
| 717 |
if new_aranet_char: |
| 718 |
uuid = self.CHARACTERISTIC_CURRENT_READINGS_AR2 |
| 719 |
raw_bytes = await self.device.read_gatt_char(uuid) |
| 720 |
|
| 721 |
isRadon = raw_bytes[0] == 3 |
| 722 |
isNucleo = raw_bytes[0] == 4 |
| 723 |
isAranet2 = raw_bytes[0] == 2 |
| 724 |
|
| 725 |
if isRadon and len(raw_bytes) >= 47: |
| 726 |
# radon |
| 727 |
value_fmt = "<HHHBHHHIBIIIIIIIB" |
| 728 |
value = struct.unpack(value_fmt, raw_bytes[0:47]) |
| 729 |
readings.decode(value, AranetType.ARANET_RADON, True) |
| 730 |
elif isNucleo and len(raw_bytes) >= 28: |
| 731 |
# radiation |
| 732 |
value_fmt = "<HHHBIQQB" |
| 733 |
value = struct.unpack(value_fmt, raw_bytes[0:28]) |
| 734 |
readings.decode(value, AranetType.ARANET_RADIATION, True) |
| 735 |
elif isAranet2: |
| 736 |
value_fmt = "<HHHBHHB" |
| 737 |
value = struct.unpack(value_fmt, raw_bytes) |
| 738 |
readings.decode(value, AranetType.ARANET2, True) |
| 739 |
else: |
| 740 |
if details: |
| 741 |
uuid = self.CHARACTERISTIC_CURRENT_READINGS_DET |
| 742 |
# co2, temp, pressure, humidity, battery, status |
| 743 |
value_fmt = "<HHHBBBHH" |
| 744 |
else: |
| 745 |
uuid = self.CHARACTERISTIC_CURRENT_READINGS |
| 746 |
# co2, temp, pressure, humidity, battery, status, interval, ^ |
| 747 |
value_fmt = "<HHHBBB" |
| 748 |
|
| 749 |
raw_bytes = await self.device.read_gatt_char(uuid) |
| 750 |
value = struct.unpack(value_fmt, raw_bytes) |
| 751 |
readings.decode(value, AranetType.ARANET4) |
| 752 |
return readings |
| 753 |
|
| 754 |
async def get_interval(self) -> int: |
| 755 |
"""Get the value for how often datapoints are logged on device""" |
| 756 |
raw_bytes = await self.device.read_gatt_char(self.CHARACTERISTIC_INTERVAL) |
| 757 |
return int.from_bytes(raw_bytes, byteorder="little") |
| 758 |
|
| 759 |
async def get_name(self): |
| 760 |
"""Get name of remote device""" |
| 761 |
try: |
| 762 |
raw_bytes = await self.device.read_gatt_char(self.CHARACTERISTIC_DEVICE_NAME) |
| 763 |
return raw_bytes.decode("utf-8") |
| 764 |
except: |
| 765 |
# fallback to serial number |
| 766 |
raw_bytes = await self.device.read_gatt_char(self.CHARACTERISTIC_SERIAL_NO) |
| 767 |
return "Aranet4 {}".format(raw_bytes.decode("utf-8")) |
| 768 |
|
| 769 |
async def get_version(self): |
| 770 |
"""Get firmware version of remote device""" |
| 771 |
raw_bytes = await self.device.read_gatt_char(self.CHARACTERISTIC_SW_REV) |
| 772 |
return raw_bytes.decode("utf-8") |
| 773 |
|
| 774 |
async def get_seconds_since_update(self): |
| 775 |
""" |
| 776 |
Get the value for how long (in seconds) has passed since last |
| 777 |
datapoint was logged |
| 778 |
""" |
| 779 |
raw_bytes = await self.device.read_gatt_char(self.CHARACTERISTIC_SECONDS_SINCE_UPDATE) |
| 780 |
return int.from_bytes(raw_bytes, byteorder="little") |
| 781 |
|
| 782 |
async def get_total_readings(self): |
| 783 |
"""Return the count of how many datapoints are logged on device""" |
| 784 |
raw_bytes = await self.device.read_gatt_char(self.CHARACTERISTIC_TOTAL_READINGS) |
| 785 |
return int.from_bytes(raw_bytes, byteorder="little") |
| 786 |
|
| 787 |
async def get_last_measurement_date(self, use_epoch: bool = False): |
| 788 |
"""Calculate the time the last datapoint was logged""" |
| 789 |
ago = await self.get_seconds_since_update() |
| 790 |
now = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0) |
| 791 |
delta_ago = datetime.timedelta(seconds=ago) |
| 792 |
last_reading = now - delta_ago |
| 793 |
if use_epoch: |
| 794 |
return last_reading.timestamp() |
| 795 |
return last_reading |
| 796 |
|
| 797 |
async def get_records( |
| 798 |
self, param: Param, log_size: int, start: int = 0x0001, end: int = 0xFFFF |
| 799 |
): |
| 800 |
""" |
| 801 |
Return ordered list of datapoints for requested parameter. |
| 802 |
List will be length of "total datapoints". If index is outside `start` |
| 803 |
and `end` request then default of `-1` is returned for those datapoints. |
| 804 |
""" |
| 805 |
|
| 806 |
history_v2 = self.device.services.get_characteristic( |
| 807 |
self.CHARACTERISTIC_HISTORY_READINGS_V2 |
| 808 |
) |
| 809 |
|
| 810 |
if history_v2 is not None: |
| 811 |
return await self._get_records_v2(param, log_size, start, end) |
| 812 |
|
| 813 |
return await self._get_records_v1(param, log_size, start, end) |
| 814 |
|
| 815 |
async def _get_records_v2( |
| 816 |
self, param: Param, log_size: int, start: int = 0x0001, end: int = 0xFFFF |
| 817 |
): |
| 818 |
""" |
| 819 |
Return ordered list of datapoints for requested parameter. |
| 820 |
List will be length of "total datapoints". If index is outside `start` |
| 821 |
and `end` request then default of `-1` is returned for those datapoints. |
| 822 |
""" |
| 823 |
start = max(start, 0x0001) |
| 824 |
|
| 825 |
header = 0x61 |
| 826 |
val = struct.pack("<BBH", header, param.value, start) |
| 827 |
# Request command: b"\x61\x01\x01\x00" |
| 828 |
# for temperature from start at 1 |
| 829 |
# Request command: b"\x61\x04\xde\x01" |
| 830 |
# for co2 from start at 478 |
| 831 |
|
| 832 |
result = _empty_reading(log_size) |
| 833 |
|
| 834 |
await self.device.write_gatt_char(self.CHARACTERISTIC_CMD, val, True) |
| 835 |
|
| 836 |
reading = True |
| 837 |
while reading: |
| 838 |
packet = await self.device.read_gatt_char( |
| 839 |
self.CHARACTERISTIC_HISTORY_READINGS_V2 |
| 840 |
) |
| 841 |
|
| 842 |
header = HistoryHeader(*struct.unpack("<BHHHHB", packet[:10])) |
| 843 |
packet = packet[10:] |
| 844 |
|
| 845 |
if header.param != param.value or header.count == 0: |
| 846 |
await asyncio.sleep(0.1) |
| 847 |
continue |
| 848 |
|
| 849 |
if param.value == Param.HUMIDITY: |
| 850 |
pattern = "<B" |
| 851 |
elif param.value == Param.RADIATION_DOSE: |
| 852 |
pattern = "<Hx" |
| 853 |
elif param.value == Param.RADIATION_DOSE_RATE: |
| 854 |
pattern = "<Hx" |
| 855 |
elif param.value == Param.RADIATION_DOSE_INTEGRAL: |
| 856 |
pattern = "<Q" |
| 857 |
elif param.value == Param.RADON_CONCENTRATION: |
| 858 |
pattern = "<I" |
| 859 |
else: |
| 860 |
pattern = "<H" |
| 861 |
|
| 862 |
# trim to multiples of pattern size |
| 863 |
plen = len(packet) |
| 864 |
packet = packet[:plen - plen % struct.calcsize(pattern)] |
| 865 |
|
| 866 |
# extract values |
| 867 |
data_values = struct.iter_unpack(pattern, packet) |
| 868 |
for idx, value in enumerate(data_values, header.start - 1): |
| 869 |
if idx > end or idx == header.start - 1 + header.count: |
| 870 |
break |
| 871 |
result[idx] = CurrentReading._set(param, value[0]) |
| 872 |
|
| 873 |
if idx >= end or (header.start - 1 + header.count) == log_size: |
| 874 |
reading = False |
| 875 |
|
| 876 |
return result |
| 877 |
|
| 878 |
async def _get_records_v1( |
| 879 |
self, param: Param, log_size: int, start: int = 0x0001, end: int = 0xFFFF |
| 880 |
): |
| 881 |
""" |
| 882 |
Return ordered list of datapoints for requested parameter. |
| 883 |
List will be length of "total datapoints". If index is outside `start` |
| 884 |
and `end` request then default of `-1` is returned for those datapoints. |
| 885 |
""" |
| 886 |
start = max(start, 0x0001) |
| 887 |
|
| 888 |
header = 0x82 |
| 889 |
unknown = 0x00 |
| 890 |
val = struct.pack("<BBHHH", header, param.value, unknown, start, end) |
| 891 |
# Request command: b"\x82\x01\x00\x00\x01\x00\xe0\x07" |
| 892 |
# for temperature from start at 1 and ending 2016 |
| 893 |
# Request command: b"\x82\x04\x00\x00\xde\x01\x3d\x05" |
| 894 |
# for co2 from start at 478 and end 1341 |
| 895 |
|
| 896 |
# register delegate |
| 897 |
delegate = Aranet4HistoryDelegate( |
| 898 |
self.CHARACTERISTIC_HISTORY_READINGS_V1, param, log_size, self |
| 899 |
) |
| 900 |
|
| 901 |
await self.device.write_gatt_char(self.CHARACTERISTIC_CMD, val, True) |
| 902 |
self.reading = True |
| 903 |
await self.device.start_notify( |
| 904 |
self.CHARACTERISTIC_HISTORY_READINGS_V1, delegate.handle_notification |
| 905 |
) |
| 906 |
while self.reading: |
| 907 |
await asyncio.sleep(0.1) |
| 908 |
await self.device.stop_notify(self.CHARACTERISTIC_HISTORY_READINGS_V1) |
| 909 |
return delegate.result |
| 910 |
|
| 911 |
async def set_readings_interval(self, interval: int, verify: bool=True): |
| 912 |
"""Set reading interval""" |
| 913 |
header = 0x90 |
| 914 |
val = struct.pack("<BB", header, interval) |
| 915 |
await self.device.write_gatt_char(self.CHARACTERISTIC_CMD, val, True) |
| 916 |
if verify: |
| 917 |
iv = await self.get_interval() |
| 918 |
return interval == (iv / 60) |
| 919 |
return True |
| 920 |
|
| 921 |
async def set_home_integration_enabled(self, enabled: bool, verify: bool=True): |
| 922 |
""" |
| 923 |
Toggle smart home integrations. |
| 924 |
This is required to receive measurements in advertisements. |
| 925 |
""" |
| 926 |
header = 0x91 |
| 927 |
val = struct.pack("<BB", header, 1 if enabled else 0) |
| 928 |
await self.device.write_gatt_char(self.CHARACTERISTIC_CMD, val, True) |
| 929 |
if verify: |
| 930 |
state = await self.get_sensor_state() |
| 931 |
return enabled == state.isOpenForIntegration |
| 932 |
return True |
| 933 |
|
| 934 |
async def set_bluetooth_range(self, extended: bool, verify: bool=True): |
| 935 |
"""Set bluetooth range""" |
| 936 |
header = 0x92 |
| 937 |
val = struct.pack("<BB", header, 1 if extended else 0) |
| 938 |
await self.device.write_gatt_char(self.CHARACTERISTIC_CMD, val, True) |
| 939 |
if verify: |
| 940 |
state = await self.get_sensor_state() |
| 941 |
if extended: |
| 942 |
return state.bluetoothRange == "extended" |
| 943 |
return state.bluetoothRange == "normal" |
| 944 |
|
| 945 |
async def get_sensor_state(self): |
| 946 |
"""Return the count of how many datapoints are logged on device""" |
| 947 |
raw_bytes = await self.device.read_gatt_char(self.CHARACTERISTIC_SENSOR_STATE) |
| 948 |
state = SensorState() |
| 949 |
state.decode(raw_bytes) |
| 950 |
return state |
| 951 |
|
| 952 |
|
| 953 |
def _log_times(now, total, interval, ago): |
| 954 |
"""Calculate the actual times datapoints were logged on device""" |
| 955 |
times = [] |
| 956 |
start = now - datetime.timedelta(seconds=((total - 1) * interval) + ago) |
| 957 |
for idx in range(total): |
| 958 |
times.append(start + datetime.timedelta(seconds=interval * idx)) |
| 959 |
return times |
| 960 |
|
| 961 |
|
| 962 |
def _attach_tzinfo(dt: datetime) -> datetime: |
| 963 |
if dt and not dt.tzinfo: |
| 964 |
now = datetime.datetime.now().astimezone() |
| 965 |
dt = dt.replace(tzinfo=now.tzinfo) |
| 966 |
return dt |
| 967 |
|
| 968 |
|
| 969 |
def _calc_start_end(datapoint_times: int, entry_filter): |
| 970 |
""" |
| 971 |
Apply filters to get required start and end datapoint. |
| 972 |
`entry_filter` is a dictionary that can have the following values: |
| 973 |
`last`: int : Get last n entries |
| 974 |
`start`: datetime : Get entries after specified time |
| 975 |
`end`: datetime : Get entries before specified time |
| 976 |
""" |
| 977 |
last_n_entries = entry_filter.get("last") |
| 978 |
filter_start = _attach_tzinfo(entry_filter.get("start")) |
| 979 |
filter_end = _attach_tzinfo(entry_filter.get("end")) |
| 980 |
start = 0x0001 |
| 981 |
end = len(datapoint_times) |
| 982 |
if last_n_entries: |
| 983 |
# Result is inclusive so reduce count back by 1 |
| 984 |
start = max(end - last_n_entries + 1, start) |
| 985 |
if filter_start: |
| 986 |
time_start = -1 |
| 987 |
for idx, timestamp in enumerate(datapoint_times, start=1): |
| 988 |
if filter_start <= timestamp: |
| 989 |
time_start = idx |
| 990 |
break |
| 991 |
if 0 < time_start <= end: |
| 992 |
start = time_start |
| 993 |
else: |
| 994 |
start = -1 # out of range |
| 995 |
if filter_end: |
| 996 |
time_end = -1 |
| 997 |
for idx, timestamp in enumerate(datapoint_times, start=1): |
| 998 |
if timestamp <= filter_end: |
| 999 |
time_end = idx |
| 1000 |
else: |
| 1001 |
break |
| 1002 |
if start <= time_end <= end: |
| 1003 |
end = time_end |
| 1004 |
else: |
| 1005 |
end = -1 # out of range |
| 1006 |
return start, end |
| 1007 |
|
| 1008 |
|
| 1009 |
async def _current_reading(address): |
| 1010 |
"""Populate and return `client.CurrentReading` dataclass""" |
| 1011 |
monitor = Aranet4(address=address) |
| 1012 |
await monitor.connect() |
| 1013 |
readings = await monitor.current_readings(details=True) |
| 1014 |
readings.name = await monitor.get_name() |
| 1015 |
readings.version = await monitor.get_version() |
| 1016 |
readings.stored = await monitor.get_total_readings() |
| 1017 |
return readings |
| 1018 |
|
| 1019 |
def _eval(val) -> bool: |
| 1020 |
falsy = ["0", "false", "disable", "disabled", "no", "off", "none"] |
| 1021 |
if isinstance(val, str): |
| 1022 |
return val.lower() not in falsy |
| 1023 |
return bool(val) |
| 1024 |
|
| 1025 |
async def _set_settings(address, settings, verify: bool=True) -> dict: |
| 1026 |
"""Change device settings. Returns changed count""" |
| 1027 |
monitor = Aranet4(address=address) |
| 1028 |
await monitor.connect() |
| 1029 |
status = {} |
| 1030 |
|
| 1031 |
if "interval" in settings: |
| 1032 |
intval = int(settings["interval"]) |
| 1033 |
status["interval"] = await monitor.set_readings_interval(intval, verify) |
| 1034 |
|
| 1035 |
if "range" in settings: |
| 1036 |
extend = ["extend", "extended", "1"] |
| 1037 |
extend = settings["range"].lower() in extend |
| 1038 |
status["range"] = await monitor.set_bluetooth_range(extend, verify) |
| 1039 |
|
| 1040 |
if "integrations" in settings: |
| 1041 |
on = ["on", "enable", "enabled", "1"] |
| 1042 |
on = settings["integrations"].lower() in on |
| 1043 |
status["integrations"] = await monitor.set_home_integration_enabled(on, verify) |
| 1044 |
|
| 1045 |
return status |
| 1046 |
|
| 1047 |
def get_current_readings(mac_address: str) -> CurrentReading: |
| 1048 |
"""Get from the device the current measurements""" |
| 1049 |
return asyncio.run(_current_reading(mac_address)) |
| 1050 |
|
| 1051 |
def set_settings(mac_address: str, settings: dict, verify: bool=True) -> int: |
| 1052 |
"""Get from the device the current measurements""" |
| 1053 |
return asyncio.run(_set_settings(mac_address, settings, verify)) |
| 1054 |
|
| 1055 |
|
| 1056 |
class Aranet4Scanner: |
| 1057 |
"""Aranet4 Scanner class - scan advertisements and process data, if available""" |
| 1058 |
|
| 1059 |
def _process_advertisement(self, device, ad_data): |
| 1060 |
"""Processes Aranet4 advertisement data""" |
| 1061 |
adv = Aranet4Advertisement(device, ad_data) |
| 1062 |
self.on_scan(adv) |
| 1063 |
|
| 1064 |
def __init__(self, on_scan): |
| 1065 |
uuids = [Aranet4.SERVICE_SAF_TEHNIKA, Aranet4.SERVICE_SAF_TEHNIKA_OLD] |
| 1066 |
self.on_scan = on_scan |
| 1067 |
self.scanner = BleakScanner( |
| 1068 |
detection_callback=self._process_advertisement, |
| 1069 |
service_uuids=uuids |
| 1070 |
) |
| 1071 |
|
| 1072 |
async def start(self): |
| 1073 |
await self.scanner.start() |
| 1074 |
|
| 1075 |
async def stop(self): |
| 1076 |
await self.scanner.stop() |
| 1077 |
|
| 1078 |
async def _find_nearby(detect_callback: callable, duration: int) -> List[BLEDevice]: |
| 1079 |
scanner = Aranet4Scanner(detect_callback) |
| 1080 |
await scanner.start() |
| 1081 |
await asyncio.sleep(duration) |
| 1082 |
await scanner.stop() |
| 1083 |
return [device |
| 1084 |
for device in scanner.scanner.discovered_devices |
| 1085 |
if "Aranet" in device.name] |
| 1086 |
|
| 1087 |
|
| 1088 |
def find_nearby(detect_callback: callable, duration: int = 5) -> List[BLEDevice]: |
| 1089 |
""" |
| 1090 |
Scans for nearby Aranet4 devices. |
| 1091 |
Will call callback on every valid Aranet4 advertisement, including duplicates |
| 1092 |
""" |
| 1093 |
|
| 1094 |
return asyncio.run(_find_nearby(detect_callback, duration)) |
| 1095 |
|
| 1096 |
async def _all_records(address, entry_filter, remove_empty): |
| 1097 |
""" |
| 1098 |
Get stored data points from device. Apply any filters requested |
| 1099 |
`entry_filter` is a dictionary that can have the following values: |
| 1100 |
`last`: int : Get last n entries |
| 1101 |
`start`: datetime : Get entries after specified time |
| 1102 |
`end`: datetime : Get entries before specified time |
| 1103 |
`temp`: bool : Get temperature data points (default = True) |
| 1104 |
`humi`: bool : Get humidity data points (default = True) |
| 1105 |
`pres`: bool : Get pressure data points (default = True) |
| 1106 |
`co2`: bool : Get co2 data points (default = True) |
| 1107 |
""" |
| 1108 |
# Connect |
| 1109 |
monitor = Aranet4(address=address) |
| 1110 |
await monitor.connect() |
| 1111 |
# Get Basic information |
| 1112 |
dev_name = await monitor.get_name() |
| 1113 |
dev_version = await monitor.get_version() |
| 1114 |
last_log = await monitor.get_seconds_since_update() |
| 1115 |
now = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0) |
| 1116 |
interval = await monitor.get_interval() |
| 1117 |
next_log = interval - last_log |
| 1118 |
# Decide if there is enough time to read all the data |
| 1119 |
# before the next datapoint is logged. |
| 1120 |
print(f"Next data point will be logged in {next_log} seconds") |
| 1121 |
if next_log < 10: |
| 1122 |
print(f"Waiting {next_log} for next datapoint to be taken...") |
| 1123 |
await asyncio.sleep(next_log) |
| 1124 |
# there was another log so update the numbers |
| 1125 |
last_log = await monitor.get_seconds_since_update() |
| 1126 |
now = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0) |
| 1127 |
|
| 1128 |
if dev_name.startswith("Aranet2"): |
| 1129 |
entry_filter["pres"] = False |
| 1130 |
entry_filter["co2"] = False |
| 1131 |
if entry_filter.get("humi", False): |
| 1132 |
entry_filter["humi"] = 2 #v2 humidity |
| 1133 |
elif dev_name.startswith("Aranet\u2622"): |
| 1134 |
entry_filter["pres"] = False |
| 1135 |
entry_filter["co2"] = False |
| 1136 |
entry_filter["humi"] = False |
| 1137 |
entry_filter["temp"] = False |
| 1138 |
entry_filter["rad_dose"] = entry_filter.get("rad_dose", True) |
| 1139 |
entry_filter["rad_dose_rate"] = entry_filter.get("rad_dose_rate", True) |
| 1140 |
entry_filter["rad_dose_total"] = entry_filter.get("rad_dose_total", True) |
| 1141 |
elif dev_name.startswith("AranetRn"): |
| 1142 |
entry_filter["co2"] = False |
| 1143 |
entry_filter["radon_concentration"] = entry_filter.get("radon_concentration", True) |
| 1144 |
entry_filter["pres"] = entry_filter.get("pres", True) |
| 1145 |
entry_filter["temp"] = entry_filter.get("temp", True) |
| 1146 |
if entry_filter.get("humi", False): |
| 1147 |
entry_filter["humi"] = 2 #v2 humidity |
| 1148 |
|
| 1149 |
log_size = await monitor.get_total_readings() |
| 1150 |
log_points = _log_times(now, log_size, interval, last_log) |
| 1151 |
begin, end = _calc_start_end(log_points, entry_filter) |
| 1152 |
rec_filter = Filter( |
| 1153 |
begin, |
| 1154 |
end, |
| 1155 |
entry_filter.get("temp", True), |
| 1156 |
entry_filter.get("humi", True), |
| 1157 |
entry_filter.get("pres", True), |
| 1158 |
entry_filter.get("co2", True), |
| 1159 |
entry_filter.get("rad_dose", False), |
| 1160 |
entry_filter.get("rad_dose_rate", False), |
| 1161 |
entry_filter.get("rad_dose_total", False), |
| 1162 |
entry_filter.get("radon_concentration", False), |
| 1163 |
) |
| 1164 |
|
| 1165 |
if begin < 0 or end < 0: |
| 1166 |
# invalid range. Most likely no points available |
| 1167 |
return Record(dev_name, dev_version, log_size, rec_filter) |
| 1168 |
|
| 1169 |
# Read datapoint history from device |
| 1170 |
if rec_filter.incl_temperature: |
| 1171 |
temperature_val = await monitor.get_records( |
| 1172 |
Param.TEMPERATURE, log_size=log_size, start=begin, end=end |
| 1173 |
) |
| 1174 |
else: |
| 1175 |
temperature_val = _empty_reading(log_size) |
| 1176 |
if rec_filter.incl_humidity == 2: |
| 1177 |
humidity_val = await monitor.get_records( |
| 1178 |
Param.HUMIDITY2, log_size=log_size, start=begin, end=end |
| 1179 |
) |
| 1180 |
elif rec_filter.incl_humidity: |
| 1181 |
humidity_val = await monitor.get_records( |
| 1182 |
Param.HUMIDITY, log_size=log_size, start=begin, end=end |
| 1183 |
) |
| 1184 |
else: |
| 1185 |
humidity_val = _empty_reading(log_size) |
| 1186 |
if rec_filter.incl_pressure: |
| 1187 |
pressure_val = await monitor.get_records( |
| 1188 |
Param.PRESSURE, log_size=log_size, start=begin, end=end |
| 1189 |
) |
| 1190 |
else: |
| 1191 |
pressure_val = _empty_reading(log_size) |
| 1192 |
if rec_filter.incl_co2: |
| 1193 |
co2_val = await monitor.get_records( |
| 1194 |
Param.CO2, log_size=log_size, start=begin, end=end |
| 1195 |
) |
| 1196 |
else: |
| 1197 |
co2_val = _empty_reading(log_size) |
| 1198 |
if rec_filter.incl_rad_dose: |
| 1199 |
rad_dose_val = await monitor.get_records( |
| 1200 |
Param.RADIATION_DOSE, log_size=log_size, start=begin, end=end |
| 1201 |
) |
| 1202 |
else: |
| 1203 |
rad_dose_val = _empty_reading(log_size) |
| 1204 |
if rec_filter.incl_rad_dose_rate: |
| 1205 |
rad_dose_rate_val = await monitor.get_records( |
| 1206 |
Param.RADIATION_DOSE_RATE, log_size=log_size, start=begin, end=end |
| 1207 |
) |
| 1208 |
else: |
| 1209 |
rad_dose_rate_val = _empty_reading(log_size) |
| 1210 |
if rec_filter.incl_rad_dose_total: |
| 1211 |
rad_dose_total_val = await monitor.get_records( |
| 1212 |
Param.RADIATION_DOSE_INTEGRAL, log_size=log_size, start=begin, end=end |
| 1213 |
) |
| 1214 |
else: |
| 1215 |
rad_dose_total_val = _empty_reading(log_size) |
| 1216 |
if rec_filter.incl_radon_concentration: |
| 1217 |
radon_concentration_val = await monitor.get_records( |
| 1218 |
Param.RADON_CONCENTRATION, log_size=log_size, start=begin, end=end |
| 1219 |
) |
| 1220 |
else: |
| 1221 |
radon_concentration_val = _empty_reading(log_size) |
| 1222 |
#### |
| 1223 |
# Store returned data in dataclass |
| 1224 |
data = zip( |
| 1225 |
log_points, |
| 1226 |
co2_val, |
| 1227 |
temperature_val, |
| 1228 |
pressure_val, |
| 1229 |
humidity_val, |
| 1230 |
rad_dose_val, |
| 1231 |
rad_dose_rate_val, |
| 1232 |
rad_dose_total_val, |
| 1233 |
radon_concentration_val |
| 1234 |
) |
| 1235 |
|
| 1236 |
record = Record(dev_name, dev_version, log_size, rec_filter) |
| 1237 |
|
| 1238 |
for date, co2, temp, pres, hum, rad, rad_rate, rad_integral, radon in data: |
| 1239 |
record.value.append(RecordItem(date, temp, hum, pres, co2, rad, rad_rate, rad_integral, radon)) |
| 1240 |
if remove_empty: |
| 1241 |
record.value = record.value[begin-1:end+1] |
| 1242 |
return record |
| 1243 |
|
| 1244 |
|
| 1245 |
def get_all_records(mac_address: str, entry_filter: dict, remove_empty: bool = False) -> Record: |
| 1246 |
""" |
| 1247 |
Get stored datapoints from device. Apply any filters requested |
| 1248 |
`entry_filter` is a dictionary that can have the following values: |
| 1249 |
`last`: int : Get last n entries |
| 1250 |
`start`: datetime : Get entries after specified time |
| 1251 |
`end`: datetime : Get entries before specified time |
| 1252 |
`temp`: bool : Get temperature data points (default = True) |
| 1253 |
`humi`: bool : Get humidity data points (default = True) |
| 1254 |
`pres`: bool : Get pressure data points (default = True) |
| 1255 |
`co2`: bool : Get co2 data points (default = True) |
| 1256 |
""" |
| 1257 |
return asyncio.run(_all_records(mac_address, entry_filter, remove_empty)) |