-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathplugin.py
More file actions
815 lines (720 loc) · 33.4 KB
/
plugin.py
File metadata and controls
815 lines (720 loc) · 33.4 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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
# Freebox Python Plugin
#
# Author: supermat & ilionel : https://github.com/ilionel/PluginDomoticzFreebox/
# Credit: https://matdomotique.wordpress.com/2018/03/25/plugin-freebox-pour-domoticz/
#
"""
<plugin key="Freebox" name="Freebox (via API)" author="supermat & ilionel" version="2.1.4" wikilink="https://www.domoticz.com/wiki/Plugins" externallink="https://matdomotique.wordpress.com/2018/03/25/plugin-freebox-pour-domoticz">
<description>
<br/>
<h2>Initialisation</h2><br/>
<h3>Au premier démarrage :</h3><br/>
<pre> 1. Laisser le champ "token" vide</pre>
<pre> 2. Accepter la demande directement depuis l'écran de la Freebox (vous aurez 30 secondes)</pre>
<pre> 3a. Copier la clé "Token" affichée dans les logs de Domoticz ("Menu Configuration" > "Log" )</pre>
<pre> 3b. Coller la clé dans le champ "Token" de la configuration ci-dessous</pre>
<pre> 4. Enregistrer les modifications puis redémarrer le serveur Domoticz</pre>
<pre> 5. Ajouter les nouveaux dispositifs depuis le menu adéquat de Domoticz</pre><br/>
<br/><b>Remarque : Les codes de télécommandes sont visibles depuis le Player TV : "Menu Système" > "Informations" > "Player"</b><br/><br/>
</description>
<params>
<param field="Address" label="Freebox URL (avec http[s]://)" width="600px" required="true" default="https://mafreebox.freebox.fr"/>
<param field="Port" label="Port" width="50px" required="true" default="443"/>
<param field="Mode1" label="Token" width="600px"/>
<param field="Mode2" label="Liste d'adresses mac (séparateur ;)" width="600px"/>
<param field="Mode3" label="Remote TV1" width="200px"/>
<param field="Mode4" label="Remote TV2" width="200px"/>
<param field="Mode5" label="Fréquence de rafraîchissement" width="200px">
<options>
<option label="10s" value="10"/>
<option label="30s" value="30"/>
<option label="60s (default)" value="60" default="true"/>
<option label="90s" value="90"/>
<option label="120s (2 minutes)" value="120"/>
<option label="300s (5 minutes)" value="300"/>
<option label="600s (10 minutes)" value="600"/>
</options>
</param>
<param field="Mode6" label="Debug" width="200px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="true"/>
</options>
</param>
</params>
</plugin>
"""
import freebox
import json
import os
import datetime
import time
import traceback
# Only enable when debug mode add "from data import"
from enum import Enum
import Domoticz
SCHEME = 'https://'
HOST = 'mafreebox.freebox.fr'
PORT = '443'
JSON_FILE = 'devicemapping.json'
POWER_STATE = ("OFF", "ON")
LINK_STATE = ("DOWN", "UP")
PRESENCE_STATE = ("hors ligne", "en ligne")
RATE_TYPE = {"rate_down": "download", "rate_up": "upload"}
SWITCH_CMD = {"Off": 0, "On": 1}
class FreeboxPlugin:
"""
Domoticz plugin for Freebox. Freebox is an appliance provided by Free ISP (Iliad group)
"""
class Device(Enum):
"""
List of constants type for devices
"""
DISK = 'Disk'
CONNECTION_RATE = 'ConnectionRate'
SYSTEM_SENSOR = 'SystemTemp'
PRESENCE = 'Presence'
COMMAND = 'Commande'
ALARM = 'Alarme'
PLAYER = 'TVPlayer'
PRECORD = 'ProgrammedRecord'
enabled = False
token = ""
freebox_url = SCHEME + HOST + ":" + PORT
remote_code_tv1 = ""
remote_code_tv2 = ""
_refresh_interval = 60
_tick = 0
def __init__(self):
return
def get_all_devices_dict(self):
"""
List all Domoticz devices created by the Freebox plugin
Returns:
(dict of str: str): {Type:{List},...}
"""
dictionary = {}
if os.path.isfile(Parameters["HomeFolder"] + JSON_FILE):
with open(Parameters["HomeFolder"] + JSON_FILE, encoding='utf-8') as data_file:
dictionary = json.load(data_file)
return dictionary
def save_all_devices_dict(self, dictionary):
"""
Save the list of Domoticz devices (create by Freebox plugin) to file
Args:
dictionary (dict of str: str): List of all devices as dictionary
"""
with open(Parameters["HomeFolder"] + JSON_FILE, 'w', encoding='utf-8') as data_file:
json.dump(dictionary, data_file)
def get_first_unused_unit_id(self, dictionary):
"""
Position of first available ID of dictionary
Args:
dictionary (dict of str: str): List of all devices as dictionary
Returns:
int: Unused position
"""
position = 0
for device in dictionary:
position = position + len(dictionary[device])
return position + 1
def return_unit_id(self, device, name):
"""
Find device ID number from is type and name
Args:
device (str): device type as Device(Enum)
name (str): device name
Returns:
str: unit id (integer as string)
"""
dict_devices = self.get_all_devices_dict()
dict_types = {}
if device.value in dict_devices:
dict_types = dict_devices[device.value]
else:
dict_devices.update({device.value: dict_types})
if name in dict_types:
return dict_types[name]
else:
uid = self.get_first_unused_unit_id(dict_devices)
dict_types.update({name: uid})
self.save_all_devices_dict(dict_devices)
return uid
def return_properties_from_id(self, uid):
"""
Find from device ID number the type and name of device
Args:
uid (int): device id
Returns:
tuple: (type,name)
"""
dict_devices = self.get_all_devices_dict()
for device in dict_devices:
for name, value in dict_devices[device].items():
if value == uid:
return (device, name)
def return_device_from_properties(self, properties):
"""
Return device type from properties
Args:
tuple (type,name): properties
Returns:
str: Device.value
"""
if len(properties) == 2 :
return properties[0]
def return_name_from_properties(self, properties):
"""
Return name from properties
Args:
tuple (type,name): properties
Returns:
str: name
"""
if len(properties) == 2 :
return properties[1]
def unit_exist(self, device, name):
"""
Find device ID number from is type and name
Args:
device (str): device type as Device(Enum)
name (str): device name
Returns:
bool: True if device exist else False
"""
dict_devices = self.get_all_devices_dict()
if device.value in dict_devices:
dict_types = dict_devices[device.value]
if name in dict_types:
return True
return False
def _update_device(self, unit_id, category, name, action='update', n_value=None, s_value=None, battery_level=None):
log = "Le dipositif de type " + category.value + " associé à " + name
if action == 'update':
log = log + " a été mis à jour " + str(n_value) + "/" + str(s_value)
if battery_level is not None:
log = log + \
" - battery level: " + \
str(Devices[unit_id].BatteryLevel) + "/" + str(battery_level)
Devices[unit_id].Update(nValue=n_value, sValue=s_value, BatteryLevel=battery_level)
else:
Devices[unit_id].Update(nValue=n_value, sValue=s_value)
elif action == 'up-to-date':
log = log + " est déjà à jour."
elif action == 'delete':
log = log + " a été supprimé dans Domoticz."
elif action == 'unknown':
log = log + " n'a pas été créé dans Domoticz. Veuillez désactiver et réactiver le plugin, en autorisant l'ajout de nouveaux dispositifs."
Domoticz.Debug(log)
def update_device(self, device, name, n_value, s_value, battery_level=None):
"""
Update Domoticz value of a Freebox device
Args:
device (str): device type as Device(Enum)
name (str): device name
n_value (int): Domoticz numeric value
s_value (str): Domoticz string value
battery_level (int, optional:
l): Domoticz battery level. Defaults to None.
"""
unit_id = None
if not self.unit_exist(device, name):
self._update_device(unit_id, device, name, 'unknown')
# Device not exist
return
unit_id = self.return_unit_id(device, name)
if not unit_id in Devices:
self._update_device(unit_id, device, name, 'delete')
# Device as been deleted
return
if ((device.value == self.Device.ALARM.value) and (
(Devices[unit_id].sValue != s_value) or (
Devices[unit_id].BatteryLevel != battery_level)
)
):
self._update_device(unit_id, device, name, 'update', n_value, s_value, battery_level)
# Test if PRESENCE are already up-to-date
elif device.value != self.Device.PRESENCE.value \
or (
device.value == self.Device.PRESENCE.value
and
Devices[unit_id].sValue != s_value
):
self._update_device(unit_id, device, name, 'update', n_value, s_value)
else:
self._update_device(unit_id, device, name, 'up-to-date')
def init(self):
"""
Initialize the connection with Freebox server.
Returns:
bool: True is success else False
"""
url = Parameters["Address"]
port = Parameters["Port"]
token = Parameters["Mode1"] # Parameters["Mode1"] == Token field
debug = Parameters["Mode6"] # Parameters["Mode6"] == Debug field [Debug|Normal]
self.remote_code_tv1 = Parameters["Mode3"] # Parameters["Mode3"] == TV Player 1 remote code field
self.remote_code_tv2 = Parameters["Mode4"] # Parameters["Mode4"] == TV Player 2 remote code field
self._refresh_interval = int(float(Parameters["Mode5"])) # Parameters["Mode5"] == Refresh interval field
if url != "":
if port != "":
url = url + ":" + port
self.freebox_url = url
else:
self.freebox_url = SCHEME + HOST + ":" + PORT
# If Debug checked
if debug == "Debug":
Domoticz.Debugging(1)
DumpConfigToLog()
# If Token field is empty
if token == "":
Domoticz.Log(
"C'est votre première connexion, le token n'est pas renseigné.")
Domoticz.Log(
"Vous devez autoriser le plugin sur l'écran de la Freebox.")
Domoticz.Log(
"Une fois autorisé sur la Freebox, le token s'affichera ici.")
token = freebox.FbxCnx(self.freebox_url).register(
"idPluginDomoticz", "Plugin Freebox", "1", "Domoticz")
# We got a Token thanks to freebox.FbxCnx
if token != "":
Domoticz.Log(
"------------------------------------------------------------------------------")
Domoticz.Log(
"Veuillez copier ce token dans la configuration du plugin Reglages > Matériel")
Domoticz.Log(token)
Domoticz.Log(
"------------------------------------------------------------------------------")
else:
Domoticz.Log(
"Vous avez été trop long (ou avez refusé), veuillez désactiver et réactiver le matériel Reglages > Matériel.")
else:
self.token = token
Domoticz.Log("Token déjà présent. OK.")
return True if self.token else False
def new_device(self, device, category, name):
"""
Add a new device in Domoticz list
Args:
device (device): Domoticz device
category (str): name of device's category
value (str): name of device
"""
device.Create()
Domoticz.Log(f"Nouveau dispositif: '{category}' -> '{name}'")
def _create_devices_reboot(self):
# Create Reboot server switch
unit_id = self.return_unit_id(
self.Device.COMMAND, "REBOOT")
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name="Reboot Server",
TypeName="Switch"
)
self.new_device(device, self.Device.COMMAND.value, 'REBOOT')
def _create_devices_storages(self, f):
# Creation of disk devices
disks = f.ls_storage()
for disk, value in disks.items():
unit_id = self.return_unit_id(self.Device.DISK, disk)
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name="Occupation " + disk,
TypeName="Percentage")
self.new_device(device, self.Device.DISK.value, disk)
# Unfortunately the image in the Percentage device can not be changed. Use Custom device!
# Domoticz.Device(Unit=_UNIT_USAGE, Name=Parameters["Address"], TypeName="Custom", Options={"Custom": "1;%"}, Image=3, Used=1).Create()
Domoticz.Log(f"L'espace disque de '{disk}' est occupé à {value}%")
self.update_device(self.Device.DISK, disk, int(float(value)), str(value))
def _create_devices_rates(self, f):
# Connection rates of WAN Freebox interface
connection_rates = f.connection_rate()
for rate, value in connection_rates.items():
unit_id = self.return_unit_id(self.Device.CONNECTION_RATE, rate)
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name="Débit " + RATE_TYPE[rate],
TypeName="Custom",
Options={"Custom": "1;ko/s"},
Used=1
)
self.new_device(device, self.Device.CONNECTION_RATE.value, RATE_TYPE[rate])
Domoticz.Log(f"Le débit WAN en '{RATE_TYPE[rate]}' est de {value} ko/s")
self.update_device(self.Device.CONNECTION_RATE, rate, int(float(value)), str(value))
def _create_devices_sensors(self, f):
# Create °C temp devices
sensors = f.system.sensors()
for sensor in sensors:
uid = str(sensor['id'])
name = sensor['name']
value = int(sensor['value'])
unit_id = self.return_unit_id(self.Device.SYSTEM_SENSOR, uid)
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name=name,
TypeName="Temperature"
)
self.new_device(device, self.Device.SYSTEM_SENSOR.value, name)
Domoticz.Log(f"La sonde '{name}' affiche {value}°C")
self.update_device(self.Device.SYSTEM_SENSOR, uid, value, str(value))
def _create_devices_alarm(self, f):
# Create alarms devices
alarminfo = f.alarminfo()
for alarm_device in alarminfo:
Domoticz.Debug("Label " + alarminfo[alarm_device]['label'])
keyunit = self.return_unit_id(
self.Device.ALARM, alarminfo[alarm_device]['label'])
if (keyunit not in Devices):
if (alarminfo[alarm_device]['type']) == 'alarm_control' or (alarminfo[alarm_device]['type']) == 'dws':
device = Domoticz.Device(
Unit=keyunit, Name=alarminfo[alarm_device]['label'], TypeName="Switch", Switchtype=0)
self.new_device(device, self.Device.ALARM.value, alarminfo[alarm_device]['label'])
elif (alarminfo[alarm_device]["type"]) == 'pir':
device = Domoticz.Device(
Unit=keyunit, Name=alarminfo[alarm_device]["label"], TypeName="Switch", Switchtype=8)
self.new_device(device, self.Device.ALARM.value, alarminfo[alarm_device]['label'])
def _create_devices_presence(self, f):
# Create presence sensor
str_ls_macaddr = Parameters["Mode2"]
if str_ls_macaddr != "":
ls_macaddr = str_ls_macaddr.split(";")
for macaddress in ls_macaddr:
name = f.get_name_from_macaddress(macaddress)
if name is None:
Domoticz.Log(
f"L'adresse mac: '{macaddress}' est inconnue de la Freebox et sera ignorée"
)
else:
unit_id = self.return_unit_id(self.Device.PRESENCE, macaddress)
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name="Presence " + name,
TypeName="Switch")
self.new_device(device, self.Device.PRESENCE.value, name)
presence = 1 if f.reachable_macaddress(macaddress) else 0
Domoticz.Log(
f"L'équipement '{name}' est actuellement {PRESENCE_STATE[presence]}"
)
self.update_device(self.Device.PRESENCE, macaddress, presence, str(presence))
def _create_devices_wifi(self, f):
# Create ON/OFF WIFI switch
wifi_state = 1 if f.wifi_state() else 0
unit_id = self.return_unit_id(
self.Device.COMMAND, "WIFI")
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name="WIFI On/Off",
TypeName="Switch"
)
self.new_device(device, self.Device.COMMAND.value, 'WIFI')
Domoticz.Log("Le WIFI est " + LINK_STATE[wifi_state])
self.update_device(self.Device.COMMAND, "WIFI", wifi_state, str(wifi_state))
def _create_devices_wan(self, f):
# Create WAN status item
wan_state = 1 if f.wan_state() else 0
unit_id = self.return_unit_id(
self.Device.COMMAND, "WANStatus")
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name="WAN Status",
TypeName="Switch"
)
self.new_device(device, self.Device.COMMAND.value, 'WANStatus')
Domoticz.Log("La connexion Internet est " + LINK_STATE[wan_state])
self.update_device(self.Device.COMMAND, "WANStatus", wan_state, str(wan_state))
def _create_devices_players(self, f):
# Create FreeboxPlayer
players = f.players.info
for player in players:
uid = str(player['id'])
player_state = 1 if f.players.state(uid) else 0
name = player['device_name'] + ' ' + uid
unit_name = player['device_model'] + '_' + uid
unit_id = self.return_unit_id(
self.Device.PLAYER, unit_name)
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name=name,
TypeName="Switch"
)
self.new_device(device, self.Device.PLAYER.value, name)
Domoticz.Log(f"Le player TV{uid} est " + POWER_STATE[player_state])
self.update_device(self.Device.PLAYER, unit_name, player_state, str(player_state))
def _create_devices_precord(self,f):
# Create Next Programmed Record counter item
timestamp = f.next_pvr_precord_timestamp()
unit_id = self.return_unit_id(
self.Device.PRECORD, "NextPrecord")
if unit_id not in Devices:
device = Domoticz.Device(
Unit=unit_id,
Name="Next Record In",
TypeName="Custom",
Options={"Custom": "1;s"},
Used=1
)
self.new_device(device, self.Device.PRECORD.value, 'NextPrecord')
Domoticz.Log(self._str_precode_state(timestamp))
self.update_device(self.Device.PRECORD, "NextPrecord", timestamp, str(timestamp))
def _refresh_devices_storages(self, f):
# Update Disk metics
disks = f.ls_storage()
for disk, value in disks.items():
Domoticz.Debug(f"L'espace disque de '{disk}' est occupé à {value}%")
self.update_device(self.Device.DISK, disk, int(float(value)), str(value))
def _refresh_devices_rates(self, f):
# Update WAN UP/DL Rates
connection_rates = f.connection_rate()
for rate, value in connection_rates.items():
Domoticz.Debug(f"Le débit WAN en '{RATE_TYPE[rate]}' est de {value} ko/s")
self.update_device(self.Device.CONNECTION_RATE, rate, int(float(value)), str(value))
def _refresh_devices_sensors(self, f):
# Update °C temp devices
sensors = f.system.sensors()
for sensor in sensors:
uid = str(sensor['id'])
value = int(sensor['value'])
Domoticz.Debug(f"La sonde '{sensor['name']}' affiche {value}°C")
self.update_device(self.Device.SYSTEM_SENSOR, uid, value, str(value))
def _refresh_devices_alarm(self, f):
# Update Alarm informations (Only in option with the Frebox Delta)
alarminfo = f.alarminfo()
for alarm_device in alarminfo:
self.update_device(
self.Device.ALARM,
alarminfo[alarm_device]["label"],
int(alarminfo[alarm_device]["value"]),
str(alarminfo[alarm_device]["value"]),
int(alarminfo[alarm_device]["battery"])
)
def _refresh_devices_presence(self, f):
# Update "Presence" Domoticz values
str_ls_macaddr = Parameters["Mode2"]
ls_macaddr = str_ls_macaddr.split(";")
for macaddress in ls_macaddr:
name = f.get_name_from_macaddress(macaddress)
if name is not None:
presence = 1 if f.reachable_macaddress(macaddress) else 0
Domoticz.Debug(
f"L'équipement '{name}' est actuellement {PRESENCE_STATE[presence]}"
)
self.update_device(self.Device.PRESENCE, macaddress, presence, str(presence))
def _refresh_devices_wifi(self, f):
# Update "Wifi" Domoticz switch state
wifi_state = 1 if f.wifi_state() else 0
Domoticz.Debug("Le WIFI est " + LINK_STATE[wifi_state])
self.update_device(self.Device.COMMAND, "WIFI", wifi_state, str(wifi_state))
def _refresh_devices_wan(self, f):
# Update "WAN interface" Domoticz switch state
wan_state = 1 if f.wan_state() else 0
Domoticz.Debug("La connexion Internet est " + LINK_STATE[wan_state])
self.update_device(self.Device.COMMAND, "WANStatus", wan_state, str(wan_state))
def _refresh_devices_players(self, f):
# Update "Players" Domoticz values
players = f.players.info
for player in players:
uid = str(player['id'])
player_state = 1 if f.players.state(uid) else 0
unit_name = player['device_model'] + '_' + uid
Domoticz.Debug(f"Le player TV{uid} est " + POWER_STATE[player_state])
self.update_device(self.Device.PLAYER, unit_name, player_state, str(player_state))
def _refresh_devices_precord(self,f):
# Update "Next Programmed record In" value
timestamp = f.next_pvr_precord_timestamp()
Domoticz.Debug(self._str_precode_state(timestamp))
self.update_device(self.Device.PRECORD, "NextPrecord", timestamp, str(timestamp))
def _switch_reboot(self, f):
f.reboot()
def _switch_wifi(self, f, command):
f.wifi_enable(SWITCH_CMD[command])
time.sleep(1)
# Update Wifi state
self._refresh_devices_wifi(f)
def _switch_player(self, f, command, player_id="1"):
Domoticz.Log(f"Switch 'TV Player{player_id}'")
if player_id=="1":
remote_code = self.remote_code_tv1
elif player_id=="2":
remote_code = self.remote_code_tv2
if remote_code is not None and command=="Off" :
f.players.shutdown(player_id, remote_code)
time.sleep(1)
# Update Player state
self._refresh_devices_players(f)
def _str_precode_state(self, timestamp):
if timestamp == -1:
return "Aucun enregistrement n'est programmé"
elif timestamp == 0:
return "Un enregistrement est en cours"
else:
return "Prochain enregistrement TV dans " + str(timestamp) + " secondes"
def onStart(self):
"""
Called when the hardware is started, either after Domoticz start, hardware creation or update.
"""
Domoticz.Log("onStart called")
try:
if self.init() :
f = freebox.FbxApp("idPluginDomoticz", self.token, self.freebox_url)
self._create_devices_reboot()
self._create_devices_storages(f)
self._create_devices_rates(f)
self._create_devices_sensors(f)
self._create_devices_alarm(f)
self._create_devices_presence(f)
self._create_devices_wifi(f)
self._create_devices_wan(f)
self._create_devices_players(f)
self._create_devices_precord(f)
DumpConfigToLog()
except Exception as e:
Domoticz.Error(f"OnStart error: {e}")
Domoticz.Error(traceback.format_exc())
def onStop(self):
"""
Called when the hardware is stopped or deleted from Domoticz.
"""
Domoticz.Log("onStop called")
def onConnect(self, connection, status, description):
"""
Called when connection to remote device either succeeds or fails,
or when a connection is made to a listening Address:Port.
Connection is the Domoticz Connection object associated with the event.
Zero Status indicates success. If Status is not zero then the Description will describe
the failure.
This callback is not called for connectionless Transports such as UDP/IP.
"""
Domoticz.Log(f"onConnect called: \
Connection={connection}, Status={status}, Description={description}")
def onMessage(self, connection, data, status, extra):
"""
Called when a single, complete message is received from the external hardware
(as defined by the Protocol setting). This callback should be used to interpret
messages from the device and set the related Domoticz devices as required.
Connection is the Domoticz Connection object associated with the event.
Data is normally a ByteArray except where the Protocol for the Connection has
structure (such as HTTP or ICMP), in that case Data will be a Dictionary containing
Protocol specific details such as Status and Headers.
"""
Domoticz.Log(f"onMessage called for Connection={connection}, \
Data={data}, Status={status}, Extra={extra}")
def onCommand(self, unit, command, level, hue):
"""
Called by Domoticz in response to a script or Domoticz Web API call sending a command
to a Unit in the Device's Units dictionary
"""
Domoticz.Log(f"onCommand called for Unit={unit}, Command={command}, Level={level}, Hue={hue}")
properties = self.return_properties_from_id(unit)
device = self.return_device_from_properties(properties)
name = self.return_name_from_properties(properties)
try:
f = freebox.FbxApp("idPluginDomoticz", self.token, host=self.freebox_url)
if device == self.Device.COMMAND.value:
if name == "REBOOT": self._switch_reboot(f)
elif name == "WIFI": self._switch_wifi(f, command)
elif device == self.Device.PLAYER.value:
self._switch_player(f, command, str(name)[-1:])
except Exception as e:
Domoticz.Error(f"onHeartbeat error: {e}")
Domoticz.Error(traceback.format_exc())
def onNotification(self, name, subject, text, status, priority, sound, image):
"""
Called when any Domoticz device generates a notification.
Name parameter is the device that generated the notification, the other parameters
contain the notification details. Hardware that can handle notifications should
be notified as required.
"""
Domoticz.Log(f"Notification: {name}, Subject={subject}, Text={text}, Status={status}, \
Priority={priority}, Sound={sound}, ImageFile={image}")
def onDisconnect(self, connection):
"""
Called after the remote device is disconnected.
Connection is the Domoticz Connection object associated with the event.
This callback is not called for connectionless Transports such as UDP/IP.
"""
Domoticz.Log(f"onDisconnect called for {connection}")
def onHeartbeat(self):
"""
Called every 'heartbeat' seconds (default 10) regardless of connection status.
Heartbeat interval can be modified by the Heartbeat command.
Allows the Plugin to do periodic tasks including request reconnection if the connection
has failed.
"""
Domoticz.Debug("onHeartbeat called")
self._tick = self._tick + 10 # Add 10s (i.e. the default heartbeat)
self._tick = self._tick % self._refresh_interval
if self._tick != 0:
return # To skip beacause refresh interval doesn't reach
if self.token == "":
Domoticz.Log("Pas de token défini.")
return
try:
f = freebox.FbxApp("idPluginDomoticz", self.token, host=self.freebox_url)
self._refresh_devices_storages(f)
self._refresh_devices_rates(f)
self._refresh_devices_sensors(f)
self._refresh_devices_alarm(f)
self._refresh_devices_presence(f)
self._refresh_devices_wifi(f)
self._refresh_devices_wan(f)
self._refresh_devices_players(f)
self._refresh_devices_precord(f)
except Exception as e:
Domoticz.Error(f"onHeartbeat error: {e}")
Domoticz.Error(traceback.format_exc())
global _plugin
_plugin = FreeboxPlugin()
def onStart():
global _plugin
# on fait une pause de 10 secondes au démarrage pour attendre la Freebox si besoin
# correction apporté par Gells qui avait des erreur au démarrage
# https://easydomoticz.com/forum/viewtopic.php?f=10&t=6222&p=55468#p55442
time.sleep(5)
_plugin.onStart()
def onStop():
"""
Called when the hardware is stopped or deleted from Domoticz.
"""
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()
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))
Domoticz.Debug("Options: '" + str(Devices[x].Options) + "'")
return