aboutsummaryrefslogtreecommitdiff
path: root/src/home/inverter/inverter_wrapper.py
blob: df2c2fc27d963313bfa2b5f3d50307bebc3f41ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import json

from threading import Lock
from inverterd import (
    Format,
    Client as InverterClient,
    InverterError
)

_lock = Lock()


class InverterClientWrapper:
    def __init__(self):
        self._inverter = None
        self._host = None
        self._port = None

    def init(self, host: str, port: int):
        self._host = host
        self._port = port
        self.create()

    def create(self):
        self._inverter = InverterClient(host=self._host, port=self._port)
        self._inverter.connect()

    def exec(self, command: str, arguments: tuple = (), format=Format.JSON):
        with _lock:
            try:
                self._inverter.format(format)
                response = self._inverter.exec(command, arguments)
                if format == Format.JSON:
                    response = json.loads(response)
                return response
            except InverterError as e:
                raise e
            except Exception as e:
                # silently try to reconnect
                try:
                    self.create()
                except Exception:
                    pass
                raise e


wrapper_instance = InverterClientWrapper()