-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
242 lines (194 loc) · 7.83 KB
/
plugin.py
File metadata and controls
242 lines (194 loc) · 7.83 KB
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
# Python Plugin SyncDeviceToTimer
#
# Created: 01-nov-2020
# Author: Skarab22
# Collaborator: Syrhus
#
"""
<plugin key="SyncDeviceToTimer" name="SyncDeviceToTimer" author="Skarab22" version="1.0.0" externallink="https://github.com/skarab22/Update_timer">
<params>
<param field="Address" label="IP Domoticz" width="250px" required="true"/>
<param field="Port" label="Port Domoticz" width="100px" required="true"/>
<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 requests
import datetime
now = datetime.datetime.now()
#constants
MON = 1;
TUE = 2;
WED = 4;
THU = 8;
FRI = 16;
SAT = 32;
SUN = 64;
EVERYDAYS = 128;
WEEKDAYS = 256;
WEEKENDS = 512;
SUM_EVERYDAYS = 127;
SUM_WEEKDAYS = 31;
SUM_WEEKENDS = 96;
ONTIME = 2;
class BasePlugin:
enabled = False
def url(self, json_cmd):
return 'http://' + self.HOST + ':'+ self.PORT + json_cmd
def request(self, json_cmd):
cmd = self.url(json_cmd)
Domoticz.Debug(f"url:{cmd}")
response = requests.get(cmd)
if response.ok:
return response.json()
def get_timer_list(self,ip, port):
Domoticz.Debug(f"get_timer_list=> {ip}:{port}")
self.HOST= ip
self.PORT= port
cmd = '/json.htm?type=schedules&filter=device'
timers = self.request(cmd)['result']
Domoticz.Debug(f"timers:{timers}")
#on filtre les timers actifs
activeTimers = [timer for timer in timers if timer['Active'] == "true"]
#print(f"activeTimers:{activeTimers}")
deviceID = 0
timer_kvp = {}
timer_list_id = []
for timer in activeTimers:
ID = timer['DeviceRowID']
timer_list_id.append(ID)
if deviceID != ID:
timer_kvp[ID] = []
deviceID = ID
timer_kvp[ID].append(timer)
#print(f"timer_kvp:{timer_kvp}")
self.active_day(timer_kvp)
def active_day(self, list_id):
day = now.weekday()
for id,timers in list_id.items():
Domoticz.Debug(f"entre dans la fonction active_timer avec l'ID = {id}")
triggers = sorted(timers, key=byTime)
Domoticz.Debug(f"Il y a {len(triggers)} timer pour l'idx {id} ")
triggers_active_day = []
for j, k in enumerate(triggers):
Domoticz.Debug(f"Days = {k['Days']}")
if k['Days'] == EVERYDAYS:
Domoticz.Debug('Timer actif tous les jours')
bin_active_day = SUM_EVERYDAYS
elif k['Days'] == WEEKDAYS:
Domoticz.Debug('Timer actif jours de semaine')
bin_active_day = SUM_WEEKDAYS
elif k['Days'] == WEEKENDS:
Domoticz.Debug('Timer actif le weekend')
bin_active_day = SUM_WEEKENDS
else:
bin_active_day = int(k['Days'])
Domoticz.Debug(f"Nous somme le {day}e jour de la semaine. Valeur Days en binaire = {2**day}")
if bin_active_day & (2**day) :
triggers_active_day.append(k)
if triggers:
Domoticz.Debug(f"ID des timer actifs pour ce jours de la semaine : {triggers_active_day}")
self.active_hour(id, triggers_active_day)
def active_hour(self, device_id, triggers):
Domoticz.Debug(f"Nb déclencheurs = {len(triggers)}")
m = 0
nw = now.time()
if len(triggers) > 1:
while not (strToTime(triggers[m]) <= nw <= strToTime(triggers[m+1])):
#print(f" i = {m}, a = {triggers[m]}, now time = {nw}, str_time = {strToTime(triggers[m])}")
if m + 2 < len(triggers):
m = m + 1
else:
m = m + 1
break
Domoticz.Debug(f" i = {m}, a = {triggers[m]}, now time = {nw}, str_time = {strToTime(triggers[m])}")
self.update_device(str(device_id), triggers[m])
def update_device(self, device_id, trigger):
Domoticz.Debug("update_device:" + device_id)
cmd = '/json.htm?type=devices&rid=' + device_id
result = self.request(cmd)
if result:
deviceJson = result['result'][0]
Domoticz.Debug(f'status {device_id}: {deviceJson} ')
status = 'On'
prop = 'Status'
selectorType = (deviceJson['SwitchType'] == "Selector")
if selectorType:
prop = 'Level'
status = trigger['Level']
else:
status = 'On' if trigger['TimerCmd']==0 else 'Off'
if (status != deviceJson[prop]):
cmd = '/json.htm?type=command¶m=switchlight&idx=' + device_id + '&switchcmd=' + ('Set%20Level&level=' if selectorType else '') + str(status)
if self.request(cmd):
Domoticz.Log(f'device {device_id} changes to {status} status')
# return True
else:
Domoticz.Log(f'device {device_id} already on good state')
def onStart(self):
if Parameters["Mode6"] == "Debug":
Domoticz.Debugging(1)
Domoticz.Heartbeat(30)
DumpConfigToLog()
if (len(Devices) == 0):
Domoticz.Device(Name="SynchronizeDevices", Unit=1, TypeName="Push On").Create()
Domoticz.Log("Device " + Devices[1].Name + " created")
self.get_timer_list(Parameters["Address"],Parameters["Port"])
def onStop(self):
Domoticz.Log("Plugin is stopping.")
# def onHeartbeat(self):
# Domoticz.Debug("onHeartbeat")
def onCommand(self, Unit, Command, Level, Hue):
Domoticz.Debug(f"Unit:{Unit}, Command:{Command}")
self.get_timer_list(Parameters["Address"],Parameters["Port"])
def onDisconnect(self, Connection):
Domoticz.Log("Device has disconnected")
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):
# global _plugin
# _plugin.onMessage(Connection, Data)
def onCommand(Unit, Command, Level, Hue):
global _plugin
_plugin.onCommand(Unit, Command, Level, Hue)
#def onHeartbeat():
# global _plugin
# #_plugin.onHeartbeat()
def onDisconnect(Connection):
global _plugin
_plugin.onDisconnect(Connection)
# 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
def byTime(obj):
return obj['Time']
def strToTime(trigger):
#return datetime.strptime(trigger['Time'], '%H:%M').time()
val = trigger['Time']
return datetime.time(hour=int(val.split(':')[0]),minute=int(val.split(':')[1]),second=0)