From c53562be6a86bb71b4ec92d58809bb0d65cdc66a Mon Sep 17 00:00:00 2001 From: UpstreamData Date: Wed, 22 Sep 2021 14:34:10 -0600 Subject: [PATCH] added API base class with send_command --- main.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/main.py b/main.py index 8b137891..10a56591 100644 --- a/main.py +++ b/main.py @@ -1 +1,35 @@ +import asyncio +import json + +class API: + def __init__(self, port, ip): + self.port = port + self.ip = ip + + async def send_command(self, command): + # get reader and writer streams + reader, writer = await asyncio.open_connection(self.ip, self.port) + + # send the command + writer.write(json.dumps({"command": command}).encode('utf-8')) + await writer.drain() + + # instantiate data + data = b"" + + # loop to receive all the data + while True: + d = await reader.read(4096) + if not d: + break + data += d + + data = json.loads(data.decode('utf-8')[:-1]) + + # close the connection + writer.close() + await writer.wait_closed() + + # return the data + return data