From 869908daef2e7d28a9f196c25d397809d8de9497 Mon Sep 17 00:00:00 2001 From: DarkCat09 Date: Fri, 31 May 2024 18:45:44 +0400 Subject: [PATCH] Add JSON format --- main.py | 8 ++++++-- models.py | 36 ++++++++++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index 47f388f..3ee96dd 100644 --- a/main.py +++ b/main.py @@ -22,7 +22,8 @@ class TestTCP(TestCase): self._wait_for_ok() 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: data = self.sock.recv(1024) @@ -43,7 +44,10 @@ class TestHTTP(TestCase): )) 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: with urlopen(req) as resp: diff --git a/models.py b/models.py index c0a0935..d546476 100644 --- a/models.py +++ b/models.py @@ -1,7 +1,8 @@ +import json from urllib.parse import quote from dataclasses import dataclass -from typing import Collection +from typing import Collection, Any type Numeric = int | float @@ -89,4 +90,35 @@ class Device: return res 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)