-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.py
365 lines (304 loc) · 14 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
## HomeWizard Wi-Fi Energy Socket Plugin
##
## Author: Eraser
## Version: 1.0.0
## Last modified: 28-05-2023
##
"""
<plugin key="HomeWizardEnergySocket" name="HomeWizard Wi-Fi Energy Socket" author="Eraser" version="1.0.0" externallink="https://www.homewizard.com/energy-socket/">
<description>
</description>
<params>
<param field="Address" label="IP Address" width="200px" required="true" default="127.0.0.1" />
<param field="Port" label="Port" width="200px" required="true" default="80" />
<param field="Mode1" label="Data interval" width="200px">
<options>
<option label="10 seconds" value="10"/>
<option label="20 seconds" value="20"/>
<option label="30 seconds" value="30"/>
<option label="1 minute" value="60" default="true"/>
<option label="2 minutes" value="120"/>
<option label="3 minutes" value="180"/>
<option label="4 minutes" value="240"/>
<option label="5 minutes" value="300"/>
</options>
</param>
<param field="Mode2" label="State interval" width="200px">
<options>
<option label="10 seconds" value="10"/>
<option label="20 seconds" value="20"/>
<option label="30 seconds" value="30"/>
<option label="1 minute" value="60" default="true"/>
<option label="2 minutes" value="120"/>
<option label="3 minutes" value="180"/>
<option label="4 minutes" value="240"/>
<option label="5 minutes" value="300"/>
</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 Domoticz
import json
import urllib
import urllib.request
class BasePlugin:
#Plugin variables
pluginInterval = 10 #in seconds
dataInterval = 60 #in seconds
stateInterval = 60 #in seconds
dataIntervalCount = 0
stateIntervalCount = 0
LastSwitchState = ""
#Homewizard Energy Socket variables
wifi_strength = -1 #: [Number] De sterkte van het Wi-Fi signaal in %
total_power_import_t1_kwh = -1 #: [Number] De stroom afname meterstand voor tarief 1 in kWh
total_power_export_t1_kwh = -1 #: [Number] De stroom teruglevering meterstand voor tarief 1 in kWh
active_power_w = -1 #: [Number] Het huidig gebruik van alle fases gecombineerd in Watt
active_power_l1_w = -1 #: [Number] Het huidig gebruik voor fase 1 in Watt (indien van toepassing)
#Calculated variables
total_power = 0 #: Het totale gecombineerde vermogen.
import_active_power_w = 0 #: Het huidig vermogen wat momenteel van het net wordt geimporteerd.
export_active_power_w = 0 #: Het huidig vermogen wat momenteel naar het net wordt geexporteerd.
#Device ID's
active_power_id = 101
switch_id = 130
wifi_signal_id = 140
def onStart(self):
if Parameters["Mode6"] == "Debug":
Domoticz.Debugging(1)
DumpConfigToLog()
# If data interval between 10 sec. and 5 min.
if 10 <= int(Parameters["Mode1"]) <= 300:
self.dataInterval = int(Parameters["Mode1"])
else:
# If not, set to 60 sec.
self.dataInterval = 60
# If data interval between 10 sec. and 5 min.
if 10 <= int(Parameters["Mode2"]) <= 300:
self.stateInterval = int(Parameters["Mode2"])
else:
# If not, set to 60 sec.
self.stateInterval = 60
try:
if ( self.switch_id not in Devices ):
Domoticz.Device(Name="Energy Socket Switch", Unit=self.switch_id, Type=244, Subtype=73, Switchtype=0).Create()
except:
Domoticz.Error("Failed to create device id " + str(self.switch_id))
# Start the heartbeat
Domoticz.Heartbeat(self.pluginInterval)
return True
def onConnect(self, Status, Description):
return True
def onMessage(self, Data, Status, Extra):
if ( Extra == "data" ):
try:
Domoticz.Debug("Reading values from data")
self.wifi_strength = Data['wifi_strength']
self.total_power_import_t1_kwh = int(Data['total_power_import_t1_kwh'] * 1000)
self.total_power_export_t1_kwh = int(Data['total_power_export_t1_kwh'] * 1000)
self.active_power_w = int(Data['active_power_w'])
if ( 'active_power_l1_w' in Data ): self.active_power_l1_w = int(Data['active_power_l1_w'])
Domoticz.Debug("Calculating values")
self.total_power = self.total_power_import_t1_kwh - self.total_power_export_t1_kwh
if ( self.active_power_w >= 0 ):
self.import_active_power_w = self.active_power_w
self.export_active_power_w = 0
else:
self.import_active_power_w = 0
self.export_active_power_w = self.active_power_w * -1
#------- Device updates -------
try:
if ( self.active_power_id not in Devices ):
Domoticz.Device(Name="Power usage", Unit=self.active_power_id, Type=243, Subtype=29).Create()
UpdateDevice(self.active_power_id, 0, numStr(self.active_power_w) + ";" + numStr(self.total_power), True)
except:
Domoticz.Error("Failed to update device id " + str(self.active_power_id))
try:
if ( self.wifi_signal_id not in Devices ):
Domoticz.Device(Name="Wifi signal", Unit=self.wifi_signal_id, TypeName="Percentage").Create()
UpdateDevice(self.wifi_signal_id, 0, numStr(self.wifi_strength), True)
except:
Domoticz.Error("Failed to update device id " + str(self.wifi_signal_id))
except:
Domoticz.Error("Failed to handle data response")
return
if ( Extra == "state" ):
try:
Domoticz.Debug("Reading values from state")
if ( 'power_on' in Data ):
PowerState = 'Off'
Domoticz.Debug("Handling power_on response")
if ( str(Data['power_on']) == 'True' ):
if ( self.LastSwitchState != "On" ):
self.LastSwitchState = "On"
UpdateDevice(self.switch_id, 1, "On", True)
else:
if ( self.LastSwitchState != "Off" ):
self.LastSwitchState = "Off"
UpdateDevice(self.switch_id, 0, "Off", True)
except:
Domoticz.Error("Failed to handle state response")
return
return True
def onCommand(self, Unit, Command, Level, Hue):
Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level) + ", Hue: " + str(Hue))
if ( Unit == self.switch_id):
if ( Command == "On"):
Domoticz.Debug("Toggle switch On")
self.toggleOn()
else:
Domoticz.Debug("Toggle switch Off")
self.toggleOff()
return True
def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
#Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)
return
def onHeartbeat(self):
self.dataIntervalCount += self.pluginInterval
self.stateIntervalCount += self.pluginInterval
if ( self.dataIntervalCount >= self.dataInterval ):
#------- Collect data -------
self.dataIntervalCount = 0
self.readData()
if ( self.stateIntervalCount >= self.stateInterval ):
#------- Read status -------
self.stateIntervalCount = 0
self.readState()
return
def onDisconnect(self):
return
def onStop(self):
#Domoticz.Log("onStop called")
return True
def readData(self):
try:
APIdata = urllib.request.urlopen("http://" + Parameters["Address"] + ":" + Parameters["Port"] + "/api/v1/data").read()
except:
Domoticz.Error("Failed to communicate with Energy Socket at ip " + Parameters["Address"] + " with port " + Parameters["Port"])
return False
try:
APIjson = json.loads(APIdata.decode("utf-8"))
except:
Domoticz.Error("Failed converting API data to JSON")
return False
try:
self.onMessage(APIjson, "200", "data")
except:
Domoticz.Error("onMessage failed with some error")
return False
def readState(self):
try:
APIdata = urllib.request.urlopen("http://" + Parameters["Address"] + ":" + Parameters["Port"] + "/api/v1/state").read()
except:
Domoticz.Error("Failed to communicate with Energy Socket at ip " + Parameters["Address"] + " with port " + Parameters["Port"])
return False
try:
APIjson = json.loads(APIdata.decode("utf-8"))
except:
Domoticz.Error("Failed converting API data to JSON")
return False
try:
self.onMessage(APIjson, "200", "state")
except:
Domoticz.Error("onMessage failed with some error")
return False
def putState(self,Data):
try:
Domoticz.Debug("Creating PUT request")
req = urllib.request.Request(url='http://' + Parameters["Address"] + ':' + Parameters['Port'] + '/api/v1/state', data=Data, method='PUT')
Domoticz.Debug("Sending PUT request")
APIdata = urllib.request.urlopen(req).read()
Domoticz.Debug("PUT request has been send")
except:
Domoticz.Error("Failed to communicate with Energy Socket at ip " + Parameters["Address"] + " with port " + Parameters["Port"])
return False
try:
Domoticz.Debug("Response data: " + APIdata.decode("utf-8"))
APIjson = json.loads(APIdata.decode("utf-8"))
except:
Domoticz.Error("Failed converting API data to JSON")
return False
try:
self.onMessage(APIjson, "200", "state")
except:
Domoticz.Error("onMessage failed with some error")
return False
def toggleOn(self):
try:
Data = b'{ "power_on": true }'
self.putState(Data)
except:
Domoticz.Error("Failed to turn Energy Socket at ip " + Parameters["Address"] + " with port " + Parameters["Port"] + " On")
return False
def toggleOff(self):
try:
Data = b'{ "power_on": false }'
self.putState(Data)
except:
Domoticz.Error("Failed to turn Energy Socket at ip " + Parameters["Address"] + " with port " + Parameters["Port"] + " Off")
return False
global _plugin
_plugin = BasePlugin()
def onStart():
global _plugin
_plugin.onStart()
def onStop():
global _plugin
_plugin.onStop()
def onConnect(Status, Description):
global _plugin
_plugin.onConnect(Status, Description)
def onMessage(Data, Status, Extra):
global _plugin
_plugin.onMessage(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():
global _plugin
_plugin.onDisconnect()
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()
# Generic helper functions
def isNumber(s):
try:
float(s)
return True
except ValueError:
return False
def numStr(s):
try:
return str(s).replace('.','')
except:
return "0"
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
def UpdateDevice(Unit, nValue, sValue, AlwaysUpdate=False, SignalLevel=12):
# Make sure that the Domoticz device still exists (they can be deleted) before updating it
if (Unit in Devices):
if ((Devices[Unit].nValue != nValue) or (Devices[Unit].sValue != sValue) or (AlwaysUpdate == True)):
Devices[Unit].Update(nValue=nValue, sValue=str(sValue), SignalLevel=SignalLevel)
Domoticz.Debug("Update "+str(nValue)+":'"+str(sValue)+"' ("+Devices[Unit].Name+")")
return