Refactor: add models.Device with req data generators

This commit is contained in:
DarkCat09 2024-05-31 17:37:42 +04:00
parent 1a514c5584
commit 404e1644db
Signed by: DarkCat09
GPG key ID: 0A26CD5B3345D6E3

View file

@ -1,34 +1,92 @@
from urllib.parse import quote
from dataclasses import dataclass
from typing import Any, Iterable
from typing import Collection
type Numeric = int | float
@dataclass
class SensorData:
mac: str
value: Any
value: Numeric
# actually `time` is either decimal int,
# hex int or <date>T<time>+/-<timezone>
time: int | None = None
name: str | None = None
def create_nm_req(
dev_mac: str,
dev_name: str | None = None,
sensors: Iterable[SensorData] = ()) -> bytes:
'''Generate a NarodMon format (#mac#value) request'''
@dataclass
class GeoPosition:
lat: Numeric
lon: Numeric
alt: Numeric
res = '#' + dev_mac
if dev_name is not None:
res += '#' + dev_name
res += '\n'
for s in sensors:
res += f'#{s.mac}#{s.value}'
if s.time is not None:
res += f'#{s.time}'
if s.name is not None:
res += '#' + s.name
@dataclass
class Device:
mac: str
name: str | None = None
owner: str | None = None
geopos: GeoPosition | None = None
sensors: Collection[SensorData] = ()
def nm_req_data(self) -> str:
'''Generate a NarodMon format (#mac#value) request body'''
res = '#' + self.mac
if self.name is not None:
res += '#' + self.name
res += '\n'
res += '##'
if self.owner is not None:
res += '#OWNER#' + self.owner + '\n'
return res.encode('utf-8')
for s in self.sensors:
res += f'#{s.mac}#{s.value}'
if s.time is not None:
res += f'#{s.time}'
if s.name is not None:
res += '#' + s.name
res += '\n'
if self.geopos is not None:
res += (
f'#LAT#{self.geopos.lat}\n'
f'#LON#{self.geopos.lon}\n'
f'#ALT#{self.geopos.alt}\n'
)
res += '##'
return res
def http_req_data(self) -> str:
'''Generate an x-www-form-urlencoded format request body'''
res = 'ID=' + self.mac
# TODO: i didn't get how to pass device name in an HTTP request
# because narodmon docs are written incredibly well /sarcasm
for s in self.sensors:
res += f'&{s.mac}={s.value}'
if s.time is not None:
res += f'&time={s.time}'
if s.name is not None:
res += f'&name={quote(s.name)}'
if self.owner is not None:
res += '&owner=' + quote(self.owner)
if self.geopos is not None:
res += (
f'&lat={self.geopos.lat}'
f'&lon={self.geopos.lon}'
f'&alt={self.geopos.alt}'
)
return res
def json_req_data(self) -> str:
raise NotImplemented