Add JSON format

This commit is contained in:
DarkCat09 2024-05-31 18:45:44 +04:00
parent 45a5b7c0f6
commit 869908daef
Signed by: DarkCat09
GPG key ID: 0A26CD5B3345D6E3
2 changed files with 40 additions and 4 deletions

View file

@ -22,7 +22,8 @@ class TestTCP(TestCase):
self._wait_for_ok() self._wait_for_ok()
def test_json(self) -> None: def test_json(self) -> None:
raise NotImplemented self.sock.sendall(device.json_req_data().encode())
self._wait_for_ok()
def _wait_for_ok(self) -> None: def _wait_for_ok(self) -> None:
data = self.sock.recv(1024) data = self.sock.recv(1024)
@ -43,7 +44,10 @@ class TestHTTP(TestCase):
)) ))
def test_json(self) -> None: def test_json(self) -> None:
raise NotImplemented self._send_and_check(Request(
HTTP_URL + '/json',
data=device.json_req_data().encode(),
))
def _send_and_check(self, req: Request) -> None: def _send_and_check(self, req: Request) -> None:
with urlopen(req) as resp: with urlopen(req) as resp:

View file

@ -1,7 +1,8 @@
import json
from urllib.parse import quote from urllib.parse import quote
from dataclasses import dataclass from dataclasses import dataclass
from typing import Collection from typing import Collection, Any
type Numeric = int | float type Numeric = int | float
@ -89,4 +90,35 @@ class Device:
return res return res
def json_req_data(self) -> str: def json_req_data(self) -> str:
raise NotImplemented '''Generate a JSON format request body'''
obj = {
'devices': [{
'mac': self.mac,
'sensors': [],
}]
}
dev = obj['devices'][0]
if self.name is not None:
dev['name'] = self.name
if self.owner is not None:
dev['owner'] = self.owner
if self.geopos is not None:
dev['lat'] = self.geopos.lat
dev['lon'] = self.geopos.lon
dev['alt'] = self.geopos.alt
sl: list[dict[str, Any]] = dev['sensors']
for s in self.sensors:
sobj = {
'id': s.mac,
'value': s.value,
}
if s.time is not None:
sobj['time'] = s.time
if s.name is not None:
sobj['name'] = s.name
sl.append(sobj)
return json.dumps(obj)