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,27 +1,49 @@
from urllib.parse import quote
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Iterable from typing import Collection
type Numeric = int | float
@dataclass @dataclass
class SensorData: class SensorData:
mac: str mac: str
value: Any value: Numeric
# actually `time` is either decimal int,
# hex int or <date>T<time>+/-<timezone>
time: int | None = None time: int | None = None
name: str | None = None name: str | None = None
def create_nm_req( @dataclass
dev_mac: str, class GeoPosition:
dev_name: str | None = None, lat: Numeric
sensors: Iterable[SensorData] = ()) -> bytes: lon: Numeric
'''Generate a NarodMon format (#mac#value) request''' alt: Numeric
res = '#' + dev_mac
if dev_name is not None: @dataclass
res += '#' + dev_name 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 += '\n'
for s in sensors: if self.owner is not None:
res += '#OWNER#' + self.owner + '\n'
for s in self.sensors:
res += f'#{s.mac}#{s.value}' res += f'#{s.mac}#{s.value}'
if s.time is not None: if s.time is not None:
res += f'#{s.time}' res += f'#{s.time}'
@ -29,6 +51,42 @@ def create_nm_req(
res += '#' + s.name res += '#' + s.name
res += '\n' 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 += '##' res += '##'
return res.encode('utf-8') 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