forked from merlot-dev/Domoticz-SMA-SunnyBoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.py
235 lines (192 loc) · 8.41 KB
/
plugin.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
232
233
234
# SMA Sunny Boy 1.5 Python Plugin for Domoticz
#
# Author: merlot
#
# v2 moving from Custom sensor to General/kWh
"""
<plugin key="SunnyBoy15" name="SMA Sunny Boy 1.5 Solar Inverter" author="merlot" version="2.0.0">
<description>
<h2>SMA Sunny Boy Solar Inverter Plugin</h2><br/>
<h3>Features</h3>
<ul style="list-style-type:square">
<li>For Tripower</li>
<li>Register instant power and daily generated energy</li>
</ul>
<h3>Credits</h3>
Forked from https://github.com/merlot-dev/Domoticz-SMA-SunnyBoy<br/>
<h3>Note</h3>
<ul style="list-style-type:square">
<li>The tri-power requires an HTTPS connection, but by default there is no SSL key. So the verification of the key is ignored.</li>
<li>If you do not know the Serial ID, just enter a fake one. In the error log you will see the serial coming back</li>
</ul>
</description>
<params>
<param field="Address" label="IP Address" width="200px" required="true"/>
<param field="Password" label="User group password" width="200px" required="true" password="true"/>
<param field="Mode2" label="Serial ID SMA" width="200px" required="true"/>
<param field="Mode3" label="Querying time in min" width="75px" required="true">
<options>
<option label="1 min" value="1"/>
<option label="3 min" value="3"/>
<option label="5 min" value="5" default="true"/>
<option label="10 min" value="10"/>
</options>
</param>
<param field="Mode6" label="Debug" width="75px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="true"/>
</options>
</param>
</params>
</plugin>
"""
import sys
sys.path.append('/usr/local/lib/python3.5/dist-packages/')
try:
import Domoticz
except ImportError:
import fakeDomoticz as Domoticz
import json
import requests
class BasePlugin:
enabled = False
lastPolled = 0
lastResponse = 0
# if no proper SSL key on sunny boy, ignore SSL check
verify_key = False
login_sid = None
def __init__(self):
return
def onStart(self):
Domoticz.Log("onStart called")
if Parameters["Mode6"] == "Debug":
Domoticz.Debugging(1)
else:
Domoticz.Debugging(0)
if (len(Devices) == 0):
Domoticz.Device(Name="PV Generation", Unit=1, TypeName="General", Subtype=29).Create()
Domoticz.Device("kWh total", 2, "Custom", Options={"Custom": "1;kWh"}).Create()
DumpConfigToLog()
Domoticz.Log("Plugin is started.")
# If Heartbeat>30 you'll get the error thread seems to have ended unexpectedly
# https://www.domoticz.com/wiki/Developing_a_Python_plugin#Callbacks
Domoticz.Heartbeat(20)
def onStop(self):
Domoticz.Log("onStop called")
def onConnect(self, Connection, Status, Description):
Domoticz.Log("onConnect called")
def onMessage(self, Connection, Data, Status, Extra):
Domoticz.Log("onMessage called")
def onCommand(self, Unit, Command, Level, Hue):
Domoticz.Log(
"onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level))
def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(
Priority) + "," + Sound + "," + ImageFile)
def onDisconnect(self, Connection):
Domoticz.Log("onDisconnect called")
def login(self, force_login=False):
"""
Get a SID from the SMA, cache the SID if possible
:param force_login: always re-login on the SMA
:return:
"""
sid = ""
if self.login_sid and not force_login:
sid = self.login_sid
Domoticz.Log("using cache")
else:
url_base = "https://" + Parameters["Address"] + "/dyn/"
url = url_base + "login.json"
payload = ('{"pass" : "' + Parameters["Password"] + '", "right" : "usr"}')
headers = {'Content-Type': 'application/json', 'Accept-Charset': 'UTF-8'}
Domoticz.Log("logging in....")
try:
r = requests.post(url, data=payload, headers=headers, verify=self.verify_key)
except Exception as e:
Domoticz.Log("Error accessing SMA inverter on " + Parameters["Address"] + " with error " + str(e))
else:
j = json.loads(r.text)
try:
sid = j['result']['sid']
except Exception as e:
Domoticz.Log("No response from SMA inverter on " + Parameters["Address"] + ".Result " + r.text + ". Error " + str(e))
self.login_sid = sid
return sid
def onHeartbeat(self):
Domoticz.Log("onHeartbeat called " + str(self.lastPolled))
## Read SMA Inverter ##
url_base = "https://" + Parameters["Address"] + "/dyn/"
url = url_base + "login.json"
payload = ('{"pass" : "' + Parameters["Password"] + '", "right" : "usr"}')
headers = {'Content-Type': 'application/json', 'Accept-Charset': 'UTF-8'}
self.lastPolled = self.lastPolled + 1
if (self.lastPolled > (3 * int(Parameters["Mode3"]))): self.lastPolled = 1
if (self.lastPolled == 1):
sid = self.login()
url = url_base + "getValues.json?sid=" + sid
payload = ('{"destDev":[],"keys":["6400_00260100","6400_00262200","6100_40263F00"]}')
headers = {'Content-Type': 'application/json', 'Accept-Charset': 'UTF-8'}
try:
r = requests.post(url, data=payload, headers=headers, verify=self.verify_key)
except:
Domoticz.Log("No data from SMA inverter on " + Parameters["Address"])
self.login_sid = None
else:
j = json.loads(r.text)
Domoticz.Log("response: {}".format(j))
try:
sma_data = j['result'][Parameters['Mode2']]
except:
Domoticz.Log("Possible wrong serial. Expected serial: " + Parameters[
'Mode2'] + " response: " + r.text)
else:
sma_pv_watt = sma_data['6100_40263F00']['1'][0]['val']
if sma_pv_watt is None:
sma_pv_watt = 0
sma_kwh_today = sma_data['6400_00262200']['1'][0]['val']
sma_kwh_total = sma_data['6400_00260100']['1'][0]['val'] / 1000
Devices[1].Update(nValue=0, sValue=str(sma_pv_watt) + ";" + str(sma_kwh_today))
sValue = "%.2f" % sma_kwh_total
Devices[2].Update(nValue=0, sValue=sValue.replace('.', ','))
global _plugin
_plugin = BasePlugin()
def onStart():
global _plugin
_plugin.onStart()
def onStop():
global _plugin
_plugin.onStop()
def onConnect(Connection, Status, Description):
global _plugin
_plugin.onConnect(Connection, Status, Description)
def onMessage(Connection, Data, Status, Extra):
global _plugin
_plugin.onMessage(Connection, Data, Status, Extra)
def onCommand(Unit, Command, Level, Hue):
global _plugin
_plugin.onCommand(Unit, Command, Level, Hue)
def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
global _plugin
_plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)
def onDisconnect(Connection):
global _plugin
_plugin.onDisconnect(Connection)
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()
# Generic helper functions
def DumpConfigToLog():
for x in Parameters:
if Parameters[x] != "":
Domoticz.Debug("'" + x + "':'" + str(Parameters[x]) + "'")
Domoticz.Debug("Device count: " + str(len(Devices)))
for x in Devices:
Domoticz.Debug("Device: " + str(x) + " - " + str(Devices[x]))
Domoticz.Debug("Device ID: '" + str(Devices[x].ID) + "'")
Domoticz.Debug("Device Name: '" + Devices[x].Name + "'")
Domoticz.Debug("Device nValue: " + str(Devices[x].nValue))
Domoticz.Debug("Device sValue: '" + Devices[x].sValue + "'")
Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
return