From 47ab3d064d1fff7645fa55e39a1642e9643107e1 Mon Sep 17 00:00:00 2001 From: Evgeny Zinoviev Date: Fri, 7 May 2021 00:34:21 +0300 Subject: initial --- inverterd/__init__.py | 1 + inverterd/inverterd.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 inverterd/__init__.py create mode 100644 inverterd/inverterd.py (limited to 'inverterd') diff --git a/inverterd/__init__.py b/inverterd/__init__.py new file mode 100644 index 0000000..531a1fc --- /dev/null +++ b/inverterd/__init__.py @@ -0,0 +1 @@ +from .inverterd import Client, Format, InverterError \ No newline at end of file diff --git a/inverterd/inverterd.py b/inverterd/inverterd.py new file mode 100644 index 0000000..9f07c2e --- /dev/null +++ b/inverterd/inverterd.py @@ -0,0 +1,53 @@ +import socket + +from enum import Enum + + +class Format(Enum): + JSON = 'json' + TABLE = 'table' + SIMPLE_TABLE = 'simple-table' + + +class Client: + def __init__(self, port=8305, host='127.0.0.1'): + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.connect((host, port)) + + def _write(self, line): + self.sock.sendall((line+'\r\n').encode()) + + def _read(self): + buf = bytearray() + while True: + buf.extend(self.sock.recv(256)) + if b'\r\n\r\n' in buf: + break + + response = buf.decode().strip().split("\r\n") + status = response.pop(0) + if status not in ('ok', 'err'): + raise InverterError(f"Unexpected status '{status}'") + + if status == 'err': + raise InverterError(response[0] if len(response) >= 0 else "Unknown error") + + return '\r\n'.join(response) + + def protocol(self, v): + self._write(f'v {v}') + return self._read() + + def format(self, format): + self._write(f'format {format}') + return self._read() + + def exec(self, command, arguments=()): + buf = f'exec {command}' + for arg in arguments: + buf += f' {arg}' + self._write(buf) + return self._read() + + +class InverterError(RuntimeError): pass \ No newline at end of file -- cgit v1.2.3