-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.py
438 lines (385 loc) · 16.7 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# Dashticz plugin for Innovation in Motion Slide
#
# Author: lokonli
#
"""
<plugin key="iim-slide" name="Slide by Innovation in Motion" author="lokonli" version="1.0.2" wikilink="https://github.com/lokonli/slide-domoticz" externallink="https://slide.store/">
<description>
<h2>Slide by Innovation in Motion</h2><br/>
Plugin for Slide by Innovation in Motion.<br/>
<br/>
It uses the Innovation in Motion open API.<br/>
<br/>
This is release 1.0.2. <br/>
<br/>
<h3>Configuration</h3>
First you have to register via the Slide app.
Fill in your email-address and password you used during registration below.<br/>
<br/>
Slides will be discovered and added to Domoticz automatically.<br/>
<br/>
</description>
<params>
<param field="Mode1" label="Email address" width="200px" required="true" default="name@gmail.com"/>
<param field="Mode2" label="Password" width="200px" required="true" default="" password="true"/>
<param field="Mode6" label="Debug" width="150px">
<options>
<option label="None" value="0" default="true" />
<option label="Python Only" value="2"/>
<option label="Basic Debugging" value="62"/>
<option label="Basic+Messages" value="126"/>
<option label="Connections Only" value="16"/>
<option label="Connections+Python" value="18"/>
<option label="Connections+Queue" value="144"/>
<option label="All" value="-1"/>
</options>
</param>
</params>
</plugin>
"""
# pylint:disable=undefined-variable
import Domoticz
import json
from datetime import datetime, timezone
import time
import _strptime
import re
class iimSlide:
enabled = False
def __init__(self):
#self.var = 123
self.access_token = ''
self.messageQueue = {}
self._expiretoken = None
# 0: Date including timezone info; 1: No timezone info. Workaround for strptime bug
self._dateType = 0
self._checkMovement = 0
return
def onStart(self):
Domoticz.Debug("onStart called")
strVersion = Parameters['DomoticzVersion']
Domoticz.Log('Version ' + strVersion)
reDomoVersion = re.findall("[\d.]+", strVersion)
print(reDomoVersion)
## Domoticz.Log('domoVersion ' + json.dumps(reDomoVersion))
domoVersion = 0
domoBuild = 0
if(len(reDomoVersion)>=1):
domoVersion = float(reDomoVersion[0])
if(len(reDomoVersion)>=2):
domoBuild = int(reDomoVersion[1])
self.nVersion = 0
if domoVersion >= 2022.2 or (domoVersion == 2022.1 and domoBuild > 14560):
self.nVersion = 1
Domoticz.Log('New version')
Domoticz.Log('Version ' + str(self.nVersion))
if Parameters["Mode6"] != "0":
Domoticz.Debugging(int(Parameters["Mode6"]))
DumpConfigToLog()
Domoticz.Debug("Length {}".format(len(self.messageQueue)))
self._tick = 0
self._dateType = 0
self._checkMovement = 0
self.access_token = ''
self.myConn = Domoticz.Connection(
Name="IIM Connection", Transport="TCP/IP", Protocol="HTTPS", Address="api.goslide.io", Port="443")
self.myConn.Connect()
def onStop(self):
Domoticz.Debug("onStop called")
def onConnect(self, Connection, Status, Description):
Domoticz.Debug("onConnect called")
if (Status == 0):
Domoticz.Debug("IIM connected successfully.")
if (self.access_token == ''):
self.authorize()
elif len(self.messageQueue) > 0:
self.slideRequest(self.messageQueue)
self.messageQueue = {}
# self.getOverview(1)
else:
Domoticz.Error("Failed to connect ("+str(Status)+") to: " +
Parameters["Address"]+" with error: "+Description)
def onMessage(self, Connection, Data):
Domoticz.Debug("onMessage called")
DumpHTTPResponseToLog(Data)
strData = Data["Data"].decode("utf-8", "ignore")
Status = int(Data["Status"])
try:
Response = json.loads(strData)
except:
Domoticz.Debug("Invalid response data")
return
if ("access_token" in Response):
self.access_token = Response["access_token"]
if "expires_at" in Response:
from datetime import datetime
expires_at = Response["expires_at"]
try: # Python bug? strptime doesn't work the second time ...
self._expiretoken = datetime.strptime(
expires_at + ' +0000', "%Y-%m-%d %H:%M:%S %z"
)
self._dateType = 0
except TypeError:
self._expiretoken = datetime(*(time.strptime(
expires_at + ' +0000', "%Y-%m-%d %H:%M:%S %z"
)[0:7]))
self._dateType = 1
self.getOverview()
else:
self._expiretoken = None
Domoticz.Error(
"Auth login JSON is missing the 'expires_at' field "
)
elif ("slides" in Response):
updated = False
for slide in Response["slides"]:
Domoticz.Debug('Slide id: {}'.format(slide["id"]))
for device in Devices:
if (Devices[device].DeviceID == str(slide["id"])):
Domoticz.Debug('Device exists')
# in case device is offline then no pos info
if "device_info" in slide:
if "pos" in slide["device_info"]:
if self.setStatus(Devices[device], slide["device_info"]["pos"]):
updated = True
else:
Domoticz.Log('Device offline: ' +
str(slide["id"]))
break
else:
Domoticz.Log('Device offline: ' + str(slide["id"]))
break
else:
Domoticz.Log('New slide found')
Domoticz.Log(json.dumps(slide))
# During installation of Slide the name is null
if slide["device_name"] != None:
# Try to find the first free id
units = list(range(1, len(Devices)+2))
for device in Devices:
units.remove(device)
unit = min(units)
#switchType 21=percentage+stop which has been added September 2021, previous version uses 13 (=percentage)
switchType = 21 if self.nVersion>=1 else 13
myDev = Domoticz.Device(Name=slide["device_name"], Unit=unit, DeviceID=str(
slide["id"]), Type=244, Subtype=73, Switchtype=switchType, Used=1)
myDev.Create()
# in case device is offline then no pos info
if "pos" in slide["device_info"]:
self.setStatus(myDev, slide["device_info"]["pos"])
else:
Domoticz.Debug(
'Unnamed slide. Waiting for slide name.')
self._checkMovement = max(self._checkMovement-1, 0)
if updated | (self._checkMovement > 0):
self.getOverview(2)
else:
Domoticz.Debug("Unhandled response")
Domoticz.Debug(json.dumps(Response))
if (Status == 200):
Domoticz.Debug("Good Response received from IIM")
elif (Status == 302):
Domoticz.Debug("IIM returned a Page Moved Error.")
sendData = {'Verb': 'POST',
'URL': Data["Headers"]["Location"],
'Headers': {'Content-Type': 'Content-Type: application/json',
# 'Connection': 'keep-alive',
'Accept': 'Content-Type: application/json',
'Host': Parameters["Address"],
'User-Agent': 'Domoticz/1.0'},
'Data': ''
}
Connection.Send(sendData)
elif (Status == 400):
Domoticz.Error("IIM returned a Bad Request Error.")
elif (Status == 500):
Domoticz.Error("IIM returned a Server Error.")
elif (Status == 424):
Domoticz.Debug('Status 424: At least one slide is offline')
else:
Domoticz.Debug("IIM returned a status: "+str(Status))
if len(self.messageQueue) > 0:
self.slideRequest(self.messageQueue)
self.messageQueue = {}
def setStatus(self, device, pos):
Domoticz.Debug("setStatus called")
nValue = 2
nPos = 1- pos if self.nVersion >= 1 else pos
sValue = str(int(nPos*100))
if nPos < 0.13:
nValue = 0
sValue = '0'
if nPos > 0.87:
nValue = 1
sValue = '100'
if(device.sValue != sValue):
device.Update(nValue=nValue, sValue=sValue)
return True
else:
return False
# New Domoticz versions
#- 0 = Blind Close in GUI/dzvents
#- 100 = Blind Open in GUI/dzvents
#- 90 = Show 90 in the GUI/dzvents, Send 90 to the device (Blind almost fully Open)
#- 10 = Show 10 in the GUI/dzvents, Send 10 to the device (Blind almost fully Closed)
def onCommand(self, Unit, Command, Level, Hue):
Domoticz.Log('Level ' + str(Level) + ' Command ' + Command)
Domoticz.Debug("onCommand called for Unit " + str(Unit) +
": Parameter '" + str(Command) + "', Level: " + str(Level))
if (Command == 'Off' or Command == 'Close'):
self.setPosition(Devices[Unit].DeviceID, 0)
if (Command == 'On' or Command == 'Open'):
self.setPosition(Devices[Unit].DeviceID, 1)
if (Command == 'Set Level'):
self.setPosition(Devices[Unit].DeviceID, Level/100)
if (Command == 'Stop'):
self.slideStop(Devices[Unit].DeviceID, Level/100)
def slideRequest(self, sendData, delay=0):
Domoticz.Debug("slideRequest called")
if self.myConn.Connected() and (self.access_token != ''):
sendData['Headers'] = {'Content-Type': 'application/json',
'Host': 'api.goslide.io',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'Authorization': 'Bearer ' + self.access_token
}
self.myConn.Send(sendData, delay)
# only start checking if we are not checking yet
if (sendData['Verb'] == 'POST'):
self._checkMovement = min(self._checkMovement+1, 2)
if self._checkMovement == 1:
self.getOverview(2)
else:
self.messageQueue = sendData
if (not self.myConn.Connecting() and not self.myConn.Connected()):
self.myConn.Connect()
def setPosition(self, id, level):
Domoticz.Debug("setPosition called")
Domoticz.Log("Nversion "+ str(self.nVersion))
nLevel = 1-level if self.nVersion >= 1 else level
Domoticz.Log("nLevel " + str(nLevel))
sendData = {'Verb': 'POST',
'URL': '/api/slide/{}/position'.format(id),
'Data': json.dumps({"pos": str(nLevel)})
}
self.slideRequest(sendData)
def slideStop(self, id, level):
Domoticz.Debug("slideStop called")
sendData = {'Verb': 'POST',
'URL': '/api/slide/{}/stop'.format(id)
}
self.slideRequest(sendData)
def authorize(self):
Domoticz.Debug("authorize called")
postdata = {
'email': Parameters["Mode1"],
'password': Parameters['Mode2']
}
sendData = {'Verb': 'POST',
'URL': '/api/auth/login',
'Headers': {'Content-Type': 'application/json',
'Accept': 'application/json',
'Host': 'api.goslide.io',
'User-Agent': 'Domoticz/1.0'},
'Data': json.dumps(postdata)
}
self.myConn.Send(sendData)
def getOverview(self, delay=0):
Domoticz.Debug("getOverview called")
sendData = {'Verb': 'GET',
'URL': '/api/slides/overview'
}
self.slideRequest(sendData, delay)
def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
Domoticz.Debug("Notification: " + Name + "," + Subject + "," + Text +
"," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)
def onDisconnect(self, Connection):
Domoticz.Debug("onDisconnect called")
if (not self.myConn.Connecting() and not self.myConn.Connected()):
self.myConn.Connect()
self._checkMovement = 0
def onHeartbeat(self):
self._tick = self._tick + 1
if self._tick > 1:
self._tick = 0
self.getOverview()
if self._expiretoken is not None:
from datetime import datetime, timezone
diffdays = 30 # In case of errors no token refresh
try:
if self._dateType == 0:
diff = self._expiretoken - datetime.now(timezone.utc)
else:
diff = self._expiretoken - datetime.now()
diffdays = diff.days
except:
Domoticz.Error('Error in computing date difference')
# Reauthenticate if token is less then 7 days valid
if diffdays <= 7:
Domoticz.Debug(
"Authentication token will expire in {} days, renewing it".format(
int(diffdays))
)
self.authorize()
global _plugin
_plugin = iimSlide()
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):
global _plugin
_plugin.onMessage(Connection, Data)
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 LogMessage(Message):
Domoticz.Debug(Message)
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 DumpHTTPResponseToLog(httpResp, level=0):
if (level == 0):
Domoticz.Debug("HTTP Details ("+str(len(httpResp))+"):")
indentStr = ""
for x in range(level):
indentStr += "----"
if isinstance(httpResp, dict):
for x in httpResp:
if not isinstance(httpResp[x], dict) and not isinstance(httpResp[x], list):
Domoticz.Debug(indentStr + ">'" + x +
"':'" + str(httpResp[x]) + "'")
else:
Domoticz.Debug(indentStr + ">'" + x + "':")
DumpHTTPResponseToLog(httpResp[x], level+1)
elif isinstance(httpResp, list):
for x in httpResp:
Domoticz.Debug(indentStr + "['" + x + "']")
else:
Domoticz.Debug(indentStr + ">'" + x + "':'" + str(httpResp[x]) + "'")