-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
231 lines (198 loc) · 7.79 KB
/
__init__.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
""" Sungrow inverter interface"""
from __future__ import annotations
import asyncio
try:
from typing import TypedDict
except ImportError:
from typing_extensions import TypedDict
import websockets.client
import json
import aiohttp
import argparse
from terminaltables import AsciiTable # type: ignore
from collections import namedtuple
from .version import version
InverterItem = namedtuple("InverterItem", ["name", "desc", "value", "unit"])
# Typing of the json we get from the inverter
class Result(TypedDict):
result_code: int
result_msg: str
result_data: ResultData
class ResultDataItems(TypedDict):
dev_id: str
data_name: str
data_value: str
data_unit: str
class ResultData(TypedDict):
token: str
list: list[ResultDataItems]
class SungrowWebsocket:
""" Websocket API to the Sungrow Inverter"""
def __init__(self, host: str, *, port: int = 8082, locale: str = "en_US"):
self.host: str = host
self.port: int = port
self.locale: str = locale
self.strings: dict[str, str] = {}
async def _update_strings(self):
self.strings = {}
url: str = f"http://{self.host}/i18n/{self.locale}.properties"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
text: str = await response.text()
else:
url: str = f"http://{self.host}/i18n/en_US.properties"
async with session.get(url) as response:
if response.status == 200:
text: str = await response.text()
else:
raise Exception("Unable to get locale")
for line in text.splitlines():
v = line.split("=", 1)
if len(v) == 2:
self.strings[v[0]] = v[1]
async def get_data_async(self) -> dict[str, InverterItem]:
if len(self.strings) == 0:
await self._update_strings()
data: dict[str, InverterItem] = {}
async with websockets.client.connect(
f"ws://{self.host}:{self.port}/ws/home/overview"
) as websocket:
await websocket.send(
json.dumps(
{"lang": self.locale, "token": "", "service": "connect"}
)
)
d: Result = json.loads(await websocket.recv())
if d["result_code"] != 1 or d["result_msg"] != "success":
return data
token: str = d["result_data"]["token"]
await websocket.send(
json.dumps(
{
"lang": self.locale,
"token": token,
"service": "devicelist",
"type": "0",
"is_check_token": "0",
}
)
)
d = json.loads(await websocket.recv())
if d["result_code"] != 1 or d["result_msg"] != "success":
return data
dev_id: str = str(d["result_data"]["list"][0]["dev_id"])
await websocket.send(
json.dumps(
{
"lang": self.locale,
"token": token,
"service": "real",
"dev_id": dev_id,
}
)
)
d = json.loads(await websocket.recv())
if d["result_code"] != 1 or d["result_msg"] != "success":
return data
for item in d["result_data"]["list"]:
name = item["data_name"]
if name.startswith("I18N_COMMON_"):
#id: str = name.removeprefix("I18N_COMMON_").lower()
id: str = name.replace("I18N_COMMON_", "").lower()
else:
#id = name.removeprefix("I18N_").lower()
id = name.replace("I18N_", "").lower()
data[id] = InverterItem(
name=name,
desc=self.strings.get(name, name),
value=self.strings.get(item["data_value"], item["data_value"]),
unit=item["data_unit"],
)
await websocket.send(
json.dumps(
{
"lang": self.locale,
"token": token,
"service": "real_battery",
"dev_id": dev_id,
}
)
)
d = json.loads(await websocket.recv())
if d["result_code"] != 1 or d["result_msg"] != "success":
return data
for item in d["result_data"]["list"]:
name = item["data_name"]
if name.startswith("I18N_COMMON_"):
#id: str = name.removeprefix("I18N_COMMON_").lower()
id: str = name.replace("I18N_COMMON_", "").lower()
else:
#id = name.removeprefix("I18N_").lower()
id = name.replace("I18N_", "").lower()
data[id] = InverterItem(
name=name,
desc=self.strings.get(name, name),
value=item["data_value"],
unit=item["data_unit"],
)
await websocket.send(
json.dumps(
{
"lang": self.locale,
"token": token,
"service": "direct",
"dev_id": dev_id,
}
)
)
d = json.loads(await websocket.recv())
if d["result_code"] != 1 or d["result_msg"] != "success":
return data
from pprint import pprint
for item in d["result_data"]["list"]:
if item["name"].startswith("I18N_COMMON_"):
item_name = self.strings.get(item["name"][:-3]).format(item["name"][-1])
else:
item_name = item["name"]
name = item_name + " Voltage"
id = name.lower().replace(" ", "_")
data[id] = InverterItem(
name=item["name"],
desc=name,
value=item["voltage"],
unit=item["voltage_unit"],
)
name = item_name + " Current"
id = name.lower().replace(" ", "_")
data[id] = InverterItem(
name=item["name"],
desc=name,
value=item["current"],
unit=item["current_unit"],
)
return data
def get_data(self) -> dict[str, InverterItem]:
return asyncio.run(self.get_data_async())
def main():
"""Command line interface to the inververter"""
parser = argparse.ArgumentParser(
description="Retrieve data from Sungrow inverter using websocket"
)
parser.add_argument("host", help="Host (IP or address) of the inverter")
parser.add_argument(
"--details", action="store_true", help="show more details"
)
parser.add_argument('--version', action='version', version=version)
args: dict[str, InverterItem] = parser.parse_args()
data: list[InverterItem] = SungrowWebsocket(args.host).get_data()
if args.details:
table: list[list[str]] = [["Item", "Value", "ID"]] + [
[item.desc, f"{item.value} {item.unit}", id]
for id, item in data.items()
]
else:
table = [["Item", "Value"]] + [
[item.desc, f"{item.value} {item.unit}"] for item in data.values()
]
print(AsciiTable(table).table)