forked from MichaluxPL/Sofar_LSW3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInverterData.py
executable file
·196 lines (177 loc) · 7.18 KB
/
InverterData.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
#!/usr/bin/python3
# Script gathering solar data from Sofar Solar Inverter (K-TLX) via WiFi module LSW-3
# by Michalux (original DEYE script by jlopez77)
import sys
import socket
import binascii
import re
import libscrc
import json
import paho.mqtt.client as paho
import os
import configparser
import time
def twosComplement_hex(hexval):
bits = 16
val = int(hexval, bits)
if val & (1 << (bits-1)):
val -= 1 << bits
return val
# Write metrics for Prometheus
def PMetrics(mfile, mname, mtype, mlabel, mlvalue, data):
line="# TYPE "+mname+" "+mtype+"\n"+mname+"{"+mlabel+"=\""+mlvalue+"\"} "+str(data)+"\n"
mfile.write(line)
os.chdir(os.path.dirname(sys.argv[0]))
#os.chdir("/home/pi/solarman/SofarInverter")
# CONFIG
configParser = configparser.RawConfigParser()
configFilePath = r'./config.cfg'
configParser.read(configFilePath)
inverter_ip=configParser.get('SofarInverter', 'inverter_ip')
inverter_port=int(configParser.get('SofarInverter', 'inverter_port'))
inverter_sn=int(configParser.get('SofarInverter', 'inverter_sn'))
mqtt=int(configParser.get('SofarInverter', 'mqtt'))
mqtt_server=configParser.get('SofarInverter', 'mqtt_server')
mqtt_port=int(configParser.get('SofarInverter', 'mqtt_port'))
mqtt_topic=configParser.get('SofarInverter', 'mqtt_topic')
mqtt_username=configParser.get('SofarInverter', 'mqtt_username')
mqtt_passwd=configParser.get('SofarInverter', 'mqtt_passwd')
lang=configParser.get('SofarInverter', 'lang')
verbose=configParser.get('SofarInverter', 'verbose')
prometheus=configParser.get('SofarInverter', 'prometheus')
prometheus_file=configParser.get('SofarInverter', 'prometheus_file')
# END CONFIG
timestamp=str(time.time()).split(".")[0]
if prometheus=="1": prometheus_file = open(prometheus_file, "w");
# PREPARE & SEND DATA TO THE INVERTER
output="{" # initialise json output
pini=0
pfin=39
chunks=0
while chunks<2:
if verbose=="1": print("Chunk no: ", chunks);
# Data frame begin
start = binascii.unhexlify('A5') #start
length=binascii.unhexlify('1700') # datalength
controlcode= binascii.unhexlify('1045') #controlCode
serial=binascii.unhexlify('0000') # serial
datafield = binascii.unhexlify('020000000000000000000000000000') #com.igen.localmode.dy.instruction.send.SendDataField
pos_ini=str(hex(pini)[2:4].zfill(4))
pos_fin=str(hex(pfin-pini+1)[2:4].zfill(4))
businessfield= binascii.unhexlify('0103' + pos_ini + pos_fin) # sin CRC16MODBUS
crc=binascii.unhexlify(str(hex(libscrc.modbus(businessfield))[4:6])+str(hex(libscrc.modbus(businessfield))[2:4])) # CRC16modbus
checksum=binascii.unhexlify('00') #checksum F2
endCode = binascii.unhexlify('15')
inverter_sn2 = bytearray.fromhex(hex(inverter_sn)[8:10] + hex(inverter_sn)[6:8] + hex(inverter_sn)[4:6] + hex(inverter_sn)[2:4])
frame = bytearray(start + length + controlcode + serial + inverter_sn2 + datafield + businessfield + crc + checksum + endCode)
if verbose=="1": print("Sent data: ", frame);
# Data frame end
checksum = 0
frame_bytes = bytearray(frame)
for i in range(1, len(frame_bytes) - 2, 1):
checksum += frame_bytes[i] & 255
frame_bytes[len(frame_bytes) - 2] = int((checksum & 255))
# OPEN SOCKET
for res in socket.getaddrinfo(inverter_ip, inverter_port, socket.AF_INET, socket.SOCK_STREAM):
family, socktype, proto, canonname, sockadress = res
try:
clientSocket= socket.socket(family,socktype,proto);
clientSocket.settimeout(10);
clientSocket.connect(sockadress);
except socket.error as msg:
print("Could not open socket - inverter/logger turned off");
if prometheus=="1": prometheus_file.close();
sys.exit(1)
# SEND DATA
clientSocket.sendall(frame_bytes);
ok=False;
while (not ok):
try:
data = clientSocket.recv(1024);
ok=True
try:
data
except:
print("No data - Exit")
sys.exit(1) #Exit, no data
except socket.timeout as msg:
print("Connection timeout - inverter and/or gateway is off");
sys.exit(1) #Exit
# PARSE RESPONSE (start position 56, end position 60)
if verbose=="1": print("Received data: ", data);
totalpower=0
totaltime=0
i=pfin-pini
a=0
while a<=i:
p1=56+(a*4)
p2=60+(a*4)
response=twosComplement_hex(str(''.join(hex(ord(chr(x)))[2:].zfill(2) for x in bytearray(data))+' '+re.sub('[^\x20-\x7f]', '', ''))[p1:p2])
hexpos=str("0x") + str(hex(a+pini)[2:].zfill(4)).upper()
with open("./SOFARMap.xml") as txtfile:
parameters=json.loads(txtfile.read())
for parameter in parameters:
for item in parameter["items"]:
if lang=="PL":
title=item["titlePL"]
else:
title=item["titleEN"]
ratio=item["ratio"]
unit=item["unit"]
export2prometheus=item["export2prometheus"]
metric_name=item["metric_name"]
label_name=item["label_name"]
label_value=item["label_value"]
metric_type=item["metric_type"]
for register in item["registers"]:
if register==hexpos and chunks!=-1:
response=round(response*ratio,2)
for option in item["optionRanges"]:
if option["key"] == response:
if lang == "PL":
response='"'+option["valuePL"]+'"'
else:
response='"'+option["valueEN"]+'"'
if hexpos!='0x0015' and hexpos!='0x0016' and hexpos!='0x0017' and hexpos!='0x0018':
if verbose=="1": print(hexpos+" - "+title+": "+str(response)+unit);
if prometheus=="1" and export2prometheus==1:
PMetrics(prometheus_file, metric_name, metric_type, label_name, label_value, response)
if unit!="":
output=output+"\""+ title + " (" + unit + ")" + "\":" + str(response)+","
else:
output=output+"\""+ title + "\":" + str(response)+","
if hexpos=='0x0015': totalpower+=response*ratio*65536;
if hexpos=='0x0016':
totalpower+=response*ratio
if verbose=="1": print(hexpos+" - "+title+": "+str(response*ratio)+unit);
output=output+"\""+ title + " (" + unit + ")" + "\":" + str(totalpower)+","
if prometheus=="1" and export2prometheus==1:
PMetrics(prometheus_file, metric_name, metric_type, label_name, label_value, (totalpower*1000))
if hexpos=='0x0017': totaltime+=response*ratio*65536;
if hexpos=='0x0018':
totaltime+=response*ratio
if verbose=="1": print(hexpos+" - "+title+": "+str(response*ratio)+unit);
output=output+"\""+ title + " (" + unit + ")" + "\":" + str(totaltime)+","
if prometheus=="1" and export2prometheus==1:
PMetrics(prometheus_file, metric_name, metric_type, label_name, label_value, totaltime)
a+=1
if chunks==0:
pini=261
pfin=276
chunks+=1
output=output[:-1]+"}"
if prometheus=="1": prometheus_file.close();
# MQTT integration
if mqtt==1:
# Initialise MQTT if configured
client=paho.Client("inverter")
if mqtt_username!="":
client.tls_set() # <--- even without arguments
client.username_pw_set(username=mqtt_username, password=mqtt_passwd)
client.connect(mqtt_server, mqtt_port)
client.publish(mqtt_topic,totalpower)
client.publish(mqtt_topic+"/attributes",output)
print("Data has been sent to MQTT")
else:
jsonoutput=json.loads(output)
print(json.dumps(jsonoutput, indent=4, sort_keys=False, ensure_ascii=False))