-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcozi.py
More file actions
2017 lines (1663 loc) · 104 KB
/
cozi.py
File metadata and controls
2017 lines (1663 loc) · 104 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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# Script Cozytouch pour Domoticz
# Auteur : OBone
# review: Yannig Nov 2018
# modification : sg2 Fev 2019
# modification : OBone 2019
# Ajout classe ['DHWP_THERM_V2_MURAL_IO']="io:AtlanticDomesticHotWaterProductionV2_MURAL_IOComponent"
# info: DHWP = Domestic Hot Water Production
# modification : allstar71 10/21 : Correction authentification/connexion suite MAJ serveur
# modification : OBone 11/21 : Ajout 'io:AtlanticPassAPCHeatPumpMainComponent','io:AtlanticPassAPCHeatingAndCoolingZoneComponent','io:AtlanticPassAPCOutsideTemperatureSensor','io:AtlanticPassAPCZoneTemperatureSensor','io:TotalElectricalEnergyConsumptionSensor'.
# modification : tatrox 01/22 : ajout consigne de dérogation pour les radiateurs électriques
# modification : tatrox 01/22 : Ajout classe ['DHWP_THERM_V4_CETHI_IO']="io:AtlanticDomesticHotWaterProductionV2_CETHI_V4_IOComponent" (chauffe eau thermodynamique Atlantic Calypso)
# modification : 5.35 : tatrox 06/23 : changements adresse API et lecture des données renvoyées
# modification : 5.36 : tatrox 06/23 : ajout de vérification de version pour mettre à jour le hardware dans domoticz si c'est une version mineure
#add log error level for domoticz
#changements mineurs pour la compréhension + ajout de quelques options de debug
# TODO list:
# Prise en compte du mode dérogation sur les AtlanticElectricalHeaterWithAdjustableTemperatureSetpointIOComponent
# Affichage du mode éco ou confort sur les AtlanticPassAPCZoneControlZoneComponent (en mode prog sur lez zones)
# En TEST :
# RADIATEUR : MODIFIER LA FONCTION GESTION CONSIGNE POUR SORTIR LE CALCUL DE LA TEMP ECO
# PAC : AJOUTER LE MODE ECO OU CONFORT EN MODE PROG SUR LES ZONES
import requests, shelve, json, time, unicodedata, os, sys, errno
'''
Paramètres
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''
version=5.36 # version=majeure.mineure : Si update de version mineure alors le hardware sera mis à jour avec la nouvelle version. Sinon création d'un nouveau hardware
debug=1 # 0 : pas de traces debug / 1 : traces requêtes http / 2 : dump data json reçues du serveur cozytouch / 4 : dump data device sauvegardés / 555 : pour lier manuellement les devices déjà existants en cas de suppresion malencontreuse du cozytouch_save mais pas des devices
domoticz_ip=u'192.168.1.103'
domoticz_port=u'8080'
login=" "
password=" "
'''
Commentaires
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ce script permet de récupérer les données d'un compte Cozytouch stockées sur le cloud Atlantic, et de les synchroniser avec des capteurs virtuels domoticz
Etapes du script :
- Au démarrage, on établit la connexion TLS avec le serveur
- On interroge le serveur via une requete GET avec l'identifiant de session (cookie transmis préalablement par le serveur lors de l'identification)
- Si la réponse est OK (200): on lance les interrogations pour rafraichir les devices et on transmet le tout à Domoticz
- Si la réponse est NOK (autre que 200) : on tente une connexion avec une requete POST avec les identifiants,
une fois connecté, on sauvegarde l'identificant de session transmis par le serveur (cookie) pour les futures interrogations.
- Ensuite on scanne les devices contenus dans l'api cozytouch, on ne retient que les devices dont l'url contient un '#1' (device principal)
- Si le device est connu via son nom de classe, on créé un dictionnaire contenant ses données
- On ajoute les dictionnaires à une liste que l'on balaye et compare aux devices de l'api Cozytouch à chaque démarrage
'''
'''
Variables globlales
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''
global url_cozytouchlog, url_cozytouch, url_domoticz, url_atlantic, cookies, url_domoticz, cozytouch_save, current_path
url_cozytouchlog=u'https://ha110-1.overkiz.com/enduser-mobile-web/enduserAPI/'
url_cozytouch=u'https://ha110-1.overkiz.com/enduser-mobile-web/externalAPI/json/'
url_domoticz=u'http://'+domoticz_ip+u':'+domoticz_port+u'/json.htm?type='
url_atlantic=u'https://apis.groupe-atlantic.com'
current_path=os.path.dirname(os.path.abspath(__file__)) # repertoire actuel
cozytouch_save = current_path+'/cozytouch_save'
'''
Dictionnaire devices principaux cozytouch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
permet d'identifier les devices lors de la fonction découverte
AtlanticElectricalHeaterWithAdjustableTemperatureSetpointIOComponent = radiateur,
AtlanticDomesticHotWaterProductionIOComponent = chauffe eau
AtlanticPassAPCZoneControlMainComponent = PAC élément central zone Control
AtlanticPassAPCZoneControlZoneComponent = zone PAC
AtlanticDomesticHotWaterProductionV3IOComponent = Chauffe eau thermodynamique
PodMiniComponent = bridge Cozytouch
'''
dict_cozytouch_devtypes = {}
dict_cozytouch_devtypes['radiateur']='io:AtlanticElectricalHeaterWithAdjustableTemperatureSetpointIOComponent'
dict_cozytouch_devtypes['chauffe eau']='io:AtlanticDomesticHotWaterProductionxxxxx' #classe désactivée
dict_cozytouch_devtypes['module fil pilote']='io:AtlanticElectricalHeaterIOComponent'
dict_cozytouch_devtypes['bridge cozytouch']='internal:PodMiniComponent' or 'internal:PodV3Component'
dict_cozytouch_devtypes['PAC main control']='io:AtlanticPassAPCZoneControlMainComponent'
dict_cozytouch_devtypes['PAC zone control']='io:AtlanticPassAPCZoneControlZoneComponent'
dict_cozytouch_devtypes['DHWP_THERM_V3_IO']="io:AtlanticDomesticHotWaterProductionV3IOComponent"
dict_cozytouch_devtypes['DHWP_THERM_IO']="io:AtlanticDomesticHotWaterProductionIOComponent"
dict_cozytouch_devtypes['DHWP_THERM_V2_MURAL_IO']="io:AtlanticDomesticHotWaterProductionV2_MURAL_IOComponent"
dict_cozytouch_devtypes['DHWP_THERM_V4_CETHI_IO']="io:AtlanticDomesticHotWaterProductionV2_CETHI_V4_IOComponent"
dict_cozytouch_devtypes['PAC_HeatPump']='io:AtlanticPassAPCHeatPumpMainComponent'
dict_cozytouch_devtypes['PAC zone component']='io:AtlanticPassAPCHeatingAndCoolingZoneComponent'
dict_cozytouch_devtypes['PAC OutsideTemp']='io:AtlanticPassAPCOutsideTemperatureSensor'
dict_cozytouch_devtypes['PAC InsideTemp']='io:AtlanticPassAPCZoneTemperatureSensor'
dict_cozytouch_devtypes['PAC Electrical Energy Consumption']='io:TotalElectricalEnergyConsumptionSensor'
'''
**********************************************************
Fonctions génériques pour Domoticz
**********************************************************
'''
def domoticz_write_log(message,level='2'):
"""Fonction d'ecriture log dans Domoticz
"""
myurl=url_domoticz+u'command¶m=addlogmessage&message='+message+u'&level='+level
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
if (req.status_code != 200):
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return req.status_code
def domoticz_write_device_analog(valeur, idx):
"""Fonction écriture device domoticz
valeur : données à inscrire, idx : idx domoticz
"""
valeur=str(valeur)
idx=str(idx)
myurl=url_domoticz+'command¶m=udevice&idx='+idx+'&nvalue=0&svalue='+valeur
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
if (req.status_code != 200):
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return req.status_code
def domoticz_write_device_switch_onoff(etat, idx):
''' Fonction d'écriture device light/switch
'''
etat=str(etat)
idx=str(idx)
myurl=url_domoticz+'command¶m=switchlight&idx='+idx+'&switchcmd='+etat
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
if (req.status_code != 200):
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return req.status_code
def domoticz_write_device_switch_selector(level, idx):
''' Fonction d'écriture device selector switch
'''
level=str(level)
myurl=url_domoticz+'command¶m=switchlight&idx='+idx+'&switchcmd=Set%20Level&level='+level
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
if (req.status_code != 200):
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return req.status_code
def domoticz_read_device_analog(idx):
''' Fonction de lecture d'un device analogique domoticz
renvoie un flottant quel que soit le type de device
'''
idx=str(idx)
## Starting 2023.02
## From /json.htm?type=devices&filter=light&used=true&order=Name
## To : /json.htm?type=command¶m=getdevices&filter=light&used=true&order=Name
myurl=url_domoticz+'command¶m=getdevices&rid='+idx
if debug:
print ("####### NEW URL : # " + myurl);
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Réponse HTTP 200 OK
if req.status_code==200 :
data=json.loads(req.text)
print( data)
# Lecture de l'état du device
# Les données sont dans un dictionnaire ( [] ) d'où le [0]
select=float((data[u'result'][0][u'Data']))
return(select)
else:
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return None
def domoticz_read_device_switch_selector(idx):
''' Fonction de lecture d'un device selector switchlight domoticz
renvoie un entier
'''
idx = str(idx).decode("utf-8")
## From Stable 2023.02
myurl=url_domoticz+u'command¶m=getdevices&rid='+idx
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Réponse HTTP 200 OK
if req.status_code==200 :
data=json.loads(req.text)
# Lecture de l'état du device
# Les données sont dans un dictionnaire ( [] ) d'où le [0]
return data[u'result'][0][u'LevelInt']
else:
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return None
def domoticz_read_user_variable(idx):
''' Fonction de lecture d'une variable utilisateur
renvoie la variable lue selon l'idx
'''
idx=str(idx)
myurl=url_domoticz+'command¶m=getuservariables'
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Réponse HTTP 200 OK
if req.status_code==200 :
data=json.loads(req.text)
# Lecture de la valeur de la variable
# Les données sont dans un dictionnaire ( [] ) d'où le [0]
select=(data[u'result'][int(idx)-1][u'Value'])
return select
else:
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return None
def domoticz_create_user_variable(nom_variable, valeur_variable):
''' création d'une variable utilisateur dans domoticz
renvoie l'idx créé
'''
# Requete de création de variable
myurl=url_domoticz+'command¶m=adduservariable&vname='+nom_variable+'&vtype=0&vvalue='+valeur_variable
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Réponse HTTP 200 OK
if req.status_code==200 :
data=json.loads(req.text)
# Si status de retard 'ERR' : Envoi d'une requete différente sur une version precedente de Domoticz
if data[u'status'] == ('ERR') :
myurl=url_domoticz+'command¶m=saveuservariable&vname='+nom_variable+'&vtype=0&vvalue='+valeur_variable
req=requests.get(myurl)
data=json.loads(req.text)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Variable créée
if data[u'status'] == ('OK'):
myurl=url_domoticz+'command¶m=getuservariables'
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Réponse HTTP 200 OK
if req.status_code==200 :
data=json.loads(req.text)
# Sauvegarde idx
for a in data[u'result']:
if a[u'Name'] == nom_variable:
idx = a[u'idx']
return idx
else : print("!!!! Echec creation variable domoticz "+nom_variable)
# Variable existante
if data[u'status'] == ('Variable name already exists!') or ('OK'):
myurl=url_domoticz+'command¶m=getuservariables'
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Réponse HTTP 200 OK
if req.status_code==200 :
data=json.loads(req.text)
# Sauvegarde idx
for a in data[u'result']:
if a[u'Name'] == nom_variable:
idx = a[u'idx']
return idx
else:
print("!!!! Echec creation variable domoticz "+nom_variable)
return None
def domoticz_rename_device(idx, nom):
''' renomme un device dans domoticz
'''
nom = str(nom)
# renomme un device domoticz
myurl=url_domoticz+'command¶m=renamedevice&idx='+idx+'&name='+nom
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
if (req.status_code != 200):
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return req.status_code
def domoticz_rename_hardware(idx, nom):
''' renomme un hardware dans domoticz
'''
idx = str(idx)
nom = str(nom)
# renomme un device domoticz
myurl=url_domoticz+'command¶m=updatehardware&htype=15'+'&enabled=true'+'&idx='+idx+'&name='+nom
req=requests.get(myurl)
if debug:
print((' '.join(('GET-> ',myurl,' : ',str(req.status_code)))))
if (req.status_code != 200):
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return req.status_code
def domoticz_add_virtual_hardware():
''' Fonction de création du virtual hardware (matériel/dummy)
'''
if debug==555: #remplissage manuel
idx=str(input("idx manuel hardware : "))
else:
myurl=url_domoticz+'command¶m=addhardware&htype=15&port=1&name=Cozytouch_V'+str(version)+'&enabled=true'
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Réponse HTTP 200 OK
if req.status_code==200 :
data=json.loads(req.text)
print("data : "+str(data))
# Lecture de l'idx attribué
idx=(data[u'idx'])
else :
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
idx=0
print(' **** domoticz cozytouch hardware index : ',str(idx))
return idx
def domoticz_add_virtual_device(hwidx,typ,nom,option='none'):
''' Fonction de création de device virtuel
'''
if option == 'none' :
req_option = ''
else :
req_option=u'&sensoroptions=1;'+option
hwidx = str(hwidx).decode("utf-8")
typ = str(typ).decode("utf-8")
if debug==555: #remplissage manuel
deviceidx=str(input("idx manuel device "+str(nom)+" : "))
else:
##myurl=url_domoticz+u'createvirtualsensor&idx='+hwidx+u'&sensorname='+nom+u'+&sensortype='+typ+req_option
##domoticz_write_log('############# DEBUG ########## OLD URL ' + myurl)
## From Stable 2023.2: https://www.domoticz.com/wiki/Domoticz_API/JSON_URL%27s#Warning_Beta_Build_15326.2C_1-jun-2023_.28and_newer.29
myurl=url_domoticz+u'command¶m=createvirtualsensor&idx='+hwidx+u'&sensorname='+nom+u'+&sensortype='+typ+req_option
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Réponse HTTP 200 OK
if req.status_code==200 :
data=json.loads(req.text)
print("data : "+str(data))
# Lecture de l'idx attribué
if data['status']!='OK' :
domoticz_write_log('Cozytouch : Error creating device '+nom,'4')
deviceidx=0
else :
deviceidx=(data[u'idx'])
else :
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
deviceidx=0
print(' **** domoticz virtual sensor index : '+str(deviceidx))
return deviceidx
'''
**********************************************************
Fonctions génériques
**********************************************************
'''
def var_save(var, var_str):
"""Fonction de sauvegarde
var: valeur à sauvegarder, var_str: nom objet en mémoire
"""
d = shelve.open(cozytouch_save)
if var_str in d :
d[var_str] = var
else :
d[var_str] = 0 # init variable
d[var_str] = var
d.close()
def var_restore(var_str,format_str =False ):
'''Fonction de restauration
var_str: nom objet en mémoire
'''
d = shelve.open(cozytouch_save)
if not (var_str) in d :
if format_str:
value = 'init' # init variable
else :
value = 0 # init variable
else :
value = d[var_str]
d.close()
return value
def http_error(code_erreur, texte_erreur):
''' Evaluation des exceptions HTTP '''
print("Erreur HTTP "+str(code_erreur)+" : "+texte_erreur)
'''
**********************************************************
Fonctions Cozytouch
**********************************************************
'''
def cozytouch_login(login,password):
headers={
'Content-Type':'application/x-www-form-urlencoded',
'Authorization':'Basic Q3RfMUpWeVRtSUxYOEllZkE3YVVOQmpGblpVYToyRWNORHpfZHkzNDJVSnFvMlo3cFNKTnZVdjBh'
}
data={
'grant_type':'password',
'username':'GA-PRIVATEPERSON/' + login,
'password':password
}
url=url_atlantic+'/token'
req = requests.post(url,data=data,headers=headers)
atlantic_token=req.json()['access_token']
headers={
'Authorization':'Bearer '+atlantic_token+''
}
reqjwt=requests.get(url_atlantic+'/magellan/accounts/jwt',headers=headers)
jwt=reqjwt.content.replace('"','')
data={
'jwt':jwt
}
jsession=requests.post(url_cozytouchlog+'login',data=data)
if debug:
print(' POST-> '+url_cozytouchlog+"login | userId=****&userPassword=**** : "+str(jsession.status_code))
if jsession.status_code==200 : # Réponse HTTP 200 : OK
print("Authentification serveur cozytouch OK")
cookies =dict(JSESSIONID=(jsession.cookies['JSESSIONID'])) # Récupération cookie ID de session
var_save(cookies,'cookies') #Sauvegarde cookie
return True
print("!!!! Echec authentification serveur cozytouch")
http_error(req.status_code,req.reason)
return False
def cozytouch_GET(json):
''' Fonction d'interrogation HTTP GET avec l'url par défaut
json: nom de fonction JSON à transmettre au serveur
'''
headers = {
'cache-control': "no-cache",
'Host' : "ha110-1.overkiz.com",
'Connection':"Keep-Alive",
}
myurl=url_cozytouchlog+json
cookies=var_restore('cookies')
req = requests.get(myurl,headers=headers,cookies=cookies)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
if req.status_code==200 : # Réponse HTTP 200 : OK
data=req.json()
return data
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
time.sleep(1) # Tempo entre requetes
return None
def cozytouch_POST(url_device,name,parametre):
# Fonction d'envoi requete POST vers serveur cozytouch
# conversion entier ou flottant => unicode
if isinstance (parametre,int) or isinstance (parametre,float):
parametre = str(parametre).decode("utf-8")
# si unicode, on teste si c'est un objet JSON '{}' dans ce cas on ne met pas de double quotes, sinon on applique par défaut
elif isinstance (parametre,unicode) or isinstance (parametre,str) and parametre.find('{') == -1 :
parametre = u'"'+parametre+u'"'
# Headers HTTP
headers= {
'content-type': "application/json",
'cache-control': "no-cache"
}
myurl=url_cozytouch+u'../../enduserAPI/exec/apply'
payload =u'{\"actions\": [{ \"deviceURL\": \"'+url_device+u'\" ,\n\"commands\": [{ \"name\": \"'+name+u'\",\n\"parameters\":['+parametre+u']}]}]}'
cookies=var_restore('cookies')
req = requests.post(myurl, data=payload, headers=headers,cookies=cookies)
if debug:
print(' POST-> '+myurl+" | "+payload+" : "+str(req.status_code))
if req.status_code!=200 : # Réponse HTTP 200 : OK
http_error(req.status_code,req.reason)
return req.status_code
def test_exist_cozytouch_domoticz_hw_and_backup_store():
print("**** Test existence / creation configuration cozytouch (hardware domoticz + fichier de sauvegarde) ****")
if debug:
print("Fichier de sauvegarde de la configuration : "+str(cozytouch_save))
# Teste si le hardware cozytouch a déjà été créé dans domoticz ; sinon on le crée
# Essaie de charger le fichier de sauvegarde
try:
shelve.open(cozytouch_save,'w') # Ouvrir la sauvegarde existante
except:
# Cas où le fichier de sauvegarde contenant l'idx du hardware cozytouch est inexistant:
print("Fichier de sauvegarde de la configuration inexistant, creation hardware cozytouch dans domoticz et nouveau fichier de sauvegarde")
d=shelve.open(cozytouch_save,'c')
d.close()
idx = domoticz_add_virtual_hardware() # création d'un hardware de type virtual dans domoticz
if idx == 0:
print("!!!! Echec creation hardware cozytouch dans domoticz")
return False
var_save(idx,'save_idx') # création du fichier de sauvegarde de la configuration Cozytouch, et stockage du numéro du hardware cozytouch
domoticz_write_log("Cozytouch : Creation nouvelle configuration ...")
print("Hardware cozytouch dans domoticz et nouveau fichier de sauvegarde de la configuration crees")
# Cas où le fichier est existant et virtual hardware de domoticz inexistant/supprimé
else :
save_idx = var_restore('save_idx')
print("idx hardware cozytouch dans le fichier de sauvegarde de la configuration : "+str(save_idx))
# Test si le virtual hardware existe avec le même numéro dans domoticz
## FROM Stable 2023.02
myurl='http://'+domoticz_ip+':'+domoticz_port+'/json.htm?type=command¶m=gethardware'
req=requests.get(myurl) # renvoie la liste du hardware domoticz
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
if req.status_code==200 : #Réponse HTTP OK
data=json.loads(req.text)
# On boucle sur chaque hardware trouvé dans domoticz :
y=0
reset=False
if 'result' in data:
while True:
try :
data[u'result'][y]['idx']
a=data[u'result'][y]['idx']
if a==save_idx :
#le device sauvegardé a été trouvé, on regarde si on le met à jour ou si on en crée un nouveau dans le cadre d'une nouvelle version majeure
#récupération version sauvegardée
versionactuelle=data[u'result'][y][u'Name'].split("V")
versionactuellemajor=versionactuelle[1]
versionactuellemajor=versionactuellemajor.split(".")
versionactuellemajor=versionactuellemajor[0]
versionactuelleminor=versionactuelle[1]
versionactuelleminor=versionactuelleminor.split(".")
versionactuelleminor=versionactuelleminor[1]
#récupération version cible
versionciblemajor=str(version).split(".")
versionciblemajor=versionciblemajor[0]
versioncibleminor=str(version).split(".")
versioncibleminor=versioncibleminor[1]
if data[u'result'][y][u'Name']=='Cozytouch_V'+str(version) :
#pas de changement de script cozytouch.py
reset=False
if debug:
print(u'idx hardware cozytouch dans domoticz : '+str(a))
break
elif (int(versionactuellemajor)>=5 & int(versionactuellemajor)==int(versionciblemajor)) :
#si update de version mineure alors mise à jour du hardware dans domoticz (valable à partir de la version majeure 5.xx)
if debug:
print (u'version actuelle : '+ str(versionactuellemajor) + u'.' + str(versionactuelleminor) + u' version cible : ' + str(versionciblemajor)+ u'.' + str(versioncibleminor))
reset=False
nouveaunom='Cozytouch_V'+str(version)
if debug:
print(u'domoticz_rename_hardware : ' + str(save_idx) + u' ' + str(nouveaunom))
domoticz_rename_hardware(save_idx,nouveaunom)
break
else :
#si update de version majeure alors mise à jour du hardware dans domoticz
if debug:
print(u'Update de version majeure')
reset=True
break
elif a != save_idx:
y+=1
continue
else :
reset=True
break
except:
print(u'**** Exception a la lecture de la configuration cozytouch ****')
reset=True
break
else :
reset=True
if reset :
print("**** Reset configuration cozytouch ****")
domoticz_write_log("Cozytouch : creation nouvelle configuration ...")
# on supprime le fichier de sauvegarde
print("Suppression fichier de sauvegarde...")
if os.path.isfile(cozytouch_save):
os.remove(cozytouch_save)
if os.path.isfile(cozytouch_save+".dat"):
os.remove(cozytouch_save+".dat")
if os.path.isfile(cozytouch_save+".bak"):
os.remove(cozytouch_save+".bak")
if os.path.isfile(cozytouch_save+".dir"):
os.remove(cozytouch_save+".dir")
# et création d'un hardware de type virtual dans domoticz
print("Ajout materiel Cozytouch et fichier Cozytouch_save...")
idx = domoticz_add_virtual_hardware()
if idx == 0:
print("!!!! Echec creation hardware cozytouch dans domoticz")
return False
var_save(idx,'save_idx') # création du fichier de sauvegarde de la configuration Cozytouch, et stockage du numéro du hardware cozytouch
else:
print("!!!! Echec recuperation liste hardware dans domoticz")
return False
print("**** Fin fonction test ****")
return True
def read_label_from_cozytouch(data,x,oid='none'):
# Lecture du nom lorsqu'il est placé directement dans l'architecture du device
if oid=='none' :
label=data[u'devices'][x][u'label']
# Lecture du nom du device lorsqu'il est placé sous l'architecture 'rootplace'
# On cherche le numéro 'oid' correspondant au device pour récupérer le nom
else :
# Init variable
y=0
z=(data[u'rootPlace'][u'subPlaces'])
while True:
try :
oid_subplace=(z[y][u'oid'])
if oid_subplace == oid:
label=(z[y][u'label'])
break
else:
y+=1
continue
except:
label=u'noname'
break
return label.strip()
def decouverte_devices():
''' Fonction de découverte des devices Cozytouch
Scanne les devices présents dans l'api cozytouch et gère les ajouts à Domoticz
'''
print("**** Decouverte devices ****")
# Renvoi toutes les données du cozytouch
data = cozytouch_GET('setup')
if debug>=2:
f1=open('./dump_cozytouch.txt', 'w+')
f1.write((json.dumps(data, indent=4, separators=(',', ': '))))
f1.close()
# Lecture données Gateway Cozytouch (pour info)
select=(data[u'gateways'][0])
if select[u'alive']:
cozytouch_gateway_etat="on"
else:
cozytouch_gateway_etat="off"
if debug:
print("\nGateway Cozytouch : etat "+cozytouch_gateway_etat+" / connexion : "+select[u'connectivity'][u'status']+" / version : "+str(select[u'connectivity'][u'protocolVersion']))
# Restauration de la liste des devices
save_devices = var_restore('save_devices')
if debug>=4 :
print("save devices : "+str(save_devices))
# Restauration de l'idx hardware cozytouch dans domoticz
save_idx = var_restore('save_idx')
'''
Cas de la liste vide, au premier démarrage du script par ex.
On passe en revue les devices de l'API Cozytouch et on l'ajoute à une liste
si sa classe est connu dans le dictionnaire Cozytouch
'''
if not save_devices : # si la liste est vide on passe à la création des devices
print("**** Demarrage procedure d'ajout devices Cozytouch **** ")
liste=[] # on crée une liste vide
domoticz_write_log(u'Cozytouch : Recherche des devices connectes ... ')
# Initialisation variables
x = 0
p = 0
oid = 0
# On boucle sur chaque device trouvé :
for a in data[u'devices']:
url = a[u'deviceURL']
name = a[u'controllableName']
oid = a[u'placeOID']
if name == dict_cozytouch_devtypes.get(u'radiateur'): # on vérifie si le nom du device est connu
label = read_label_from_cozytouch(data,x,oid)
liste= ajout_radiateur(save_idx,liste,url,x,label) # ajout du device à la liste
p+=1 # incrément position dans dictionnaire des devices
elif name == dict_cozytouch_devtypes.get(u'chauffe eau'):
liste = ajout_chauffe_eau (save_idx,liste,url,x,(data[u'rootPlace'][u'label'])) # label rootplace
p+=1
elif name == dict_cozytouch_devtypes.get(u'module fil pilote'):
liste= ajout_module_fil_pilote (save_idx,liste,url,x,read_label_from_cozytouch(data,x,oid))
p+=1
elif name == dict_cozytouch_devtypes.get(u'PAC main control'):
liste= ajout_PAC_main_control (save_idx,liste,url,x,read_label_from_cozytouch(data,x))
p+=1
elif name == dict_cozytouch_devtypes.get(u'PAC zone control'):
liste= ajout_PAC_zone_control (save_idx,liste,url,x,read_label_from_cozytouch(data,x))
p+=1
elif name == dict_cozytouch_devtypes.get(u'DHWP_THERM_V3_IO') or name == dict_cozytouch_devtypes.get(u'DHWP_THERM_IO') or name == dict_cozytouch_devtypes.get(u'DHWP_THERM_V2_MURAL_IO') or name == dict_cozytouch_devtypes.get(u'DHWP_THERM_V4_CETHI_IO'):
liste= Add_DHWP_THERM (save_idx,liste,url,x,(data[u'rootPlace'][u'label']),name) # label sur rootplace
p+=1
elif name == dict_cozytouch_devtypes.get(u'bridge cozytouch'):
label = u'localisation inconnue'
liste= ajout_bridge_cozytouch (save_idx,liste,url,x,label)
p+=1
elif name == dict_cozytouch_devtypes.get(u'PAC_HeatPump'):
liste= ajout_PAC_HeatPump (save_idx,liste,url,x,read_label_from_cozytouch(data,x))
p+=1
elif name == dict_cozytouch_devtypes.get(u'PAC OutsideTemp'):
liste= ajout_PAC_Outside_Temp (save_idx,liste,url,x,read_label_from_cozytouch(data,x))
p+=1
elif name == dict_cozytouch_devtypes.get(u'PAC InsideTemp'):
liste= ajout_PAC_Inside_Temp (save_idx,liste,url,x,read_label_from_cozytouch(data,x))
p+=1
elif name == dict_cozytouch_devtypes.get(u'PAC Electrical Energy Consumption'):
liste= ajout_PAC_Electrical_Energy (save_idx,liste,url,x,read_label_from_cozytouch(data,x))
p+=1
elif name == dict_cozytouch_devtypes.get(u'PAC zone component'):
liste= ajout_PAC_zone_component (save_idx,liste,url,x,read_label_from_cozytouch(data,x))
p+=1
else :
domoticz_write_log(u'Cozytouch : Device avec classe '+name+u' inconnu')
x+=1 # incrément device dans data json cozytouch
# Fin de la boucle :
# Sauvegarde des devices ajoutés
if debug>=4:
f1=open('./cozytouch_domoticz_devices_idx.txt', 'w+')
f1.write((json.dumps(liste, indent=4, separators=(',', ': '))))
f1.close()
var_save(liste,'save_devices')
'''
Cas de liste non vide
On passe en revue les devices l'API Cozytouch
si sa classe est connue dans le dictionnaire Cozytouch on met à jour les données
'''
if save_devices != 0 : # si la liste contient des devices
print("\n**** Demarrage mise a jour devices ****")
# Initialisation variables
liste_inconnu = []
x = 0
p = 0
# On boucle sur chaque device trouvé :
for a in data['devices']:
url = a[u'deviceURL']
name = a[u'controllableName']
# On boucle sur les éléments du dictionnaire de devices
for element in save_devices :
if element.has_key(u'url') : # si la clé url est présente dans le dictionnaire
if element.get(u'url') == url : # si l'url du device est stocké dans le dictionnaire
maj_device(data,name,p,x) # mise à jour du device
p+=1 # incrément position dans le dictionnaire
for inconnu in liste_inconnu :
if inconnu == url :
liste_inconnu.remove(url) # on retire l'url inconnu à la liste
break
else : # sinon on reboucle
liste_inconnu.append(url)
else : # sinon on reboucle
continue
x+=1 # incrément position du device dans les datas json cozytouch
'''
**********************************************************
Fonctions d'ajouts des devices cozytouch dans Domoticz
suivant la classe
**********************************************************
'''
def ajout_radiateur(idx,liste,url,x,label):
''' Fonction ajout radiateur
'''
# TODO : traiter comme erreur les domoticz_add_virtual_device renvoyant 0
# création du nom suivant la position JSON du device dans l'API Cozytouch
nom = u'Rad. '+label
# création du dictionnaire de définition du device
radiateur = {}
radiateur[u'url'] = url
radiateur[u'x']= x
radiateur[u'nom']= nom
# Création switch selecteur mode de fonctionnement (level_0=off/level_10=Manuel/level_20=Auto(prog)) :
nom_switch = u'Mode '+nom
radiateur[u'idx_switch_mode']= domoticz_add_virtual_device(idx,1002,nom)
# Personnalisation du switch(Modification du nom des levels et de l'icone)
option = u'TGV2ZWxOYW1lczpPZmZ8TWFudWVsfEF1dG8gKHByb2cpO0xldmVsQWN0aW9uczp8fDtTZWxlY3RvclN0eWxlOjA7TGV2ZWxPZmZIaWRkZW46ZmFsc2U%3D&protected=false&strparam1=&strparam2=&switchtype=18&type=setused&used=true'
myurl=u'http://'+domoticz_ip+u':'+domoticz_port+u'/json.htm?addjvalue=0&addjvalue2=0&customimage=15&description=&idx='+radiateur[u'idx_switch_mode']+u'&name='+nom_switch+u'+&options='+option
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Création switch selecteur (level_10=frostprotection/level_20=eco/level_30=confort-2/level_40=confort-1/level_50=confort) :
nom_switch = u'Ordre '+nom
radiateur[u'idx_switch_level']= domoticz_add_virtual_device(idx,1002,nom)
# Personnalisation du switch(Modification du nom des levels et de l'icone)
option = u'TGV2ZWxOYW1lczpPZmZ8SG9ycyBnZWx8RWNvfENvbmZvcnQgLTJ8Q29uZm9ydCAtMXxDb25mb3J0O0xldmVsQWN0aW9uczp8fHx8fDtTZWxlY3RvclN0eWxlOjE7TGV2ZWxPZmZIaWRkZW46ZmFsc2U%3D&protected=false&strparam1=&strparam2=&switchtype=18&type=setused&used=true'
myurl=u'http://'+domoticz_ip+u":"+domoticz_port+u'/json.htm?addjvalue=0&addjvalue2=0&customimage=15&description=&idx='+radiateur[u'idx_switch_level']+u'&name='+nom_switch+u'+&options='+option
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Consigne de dérogation valable en mode auto, applique une consigne de dérogation commande :"setDerogatedTargetTemperature" + température souhaité
# Fonctionnement de la dérogation : En mode auto, si on applique uen consigne > à la consigne en cours (eco ou confort), on applique la dérogation (retour d'état pour savoir si on est dérogation? pas trouvé encore)
# Pour annuler la dérogation il faut appliquer la consigne qui doit etre en cours soit eco ou confort suivant le mode du radiateur,
# Attention le radiateur n'accepte pas une consigne de dérogation inférieure à la consigne qui doit etre appliquée (eco ou confort)
# Création Mesure température :
nom_mesure = u'T C '+nom
radiateur[u'idx_mesure_temp']= domoticz_add_virtual_device(idx,80,nom_mesure)
# Création Consigne température Confort :
nom_cons_conf = u'Cons. confort '+nom
radiateur[u'idx_cons_temp_confort']= domoticz_add_virtual_device(idx,8,nom_cons_conf )
# Création Consigne température Eco :
nom_cons_eco= u'Cons. eco '+nom
radiateur[u'idx_cons_temp_eco']= domoticz_add_virtual_device(idx,8,nom_cons_eco)
# Création Consigne température dérogation :
nom_cons_derog = u'Cons. derogation '+nom
radiateur[u'idx_cons_temp_derogation']= domoticz_add_virtual_device(idx,8,nom_cons_derog )
# Création Compteur d'énergie :
nom_compteur= u'Conso '+nom
radiateur[u'idx_compteur']= domoticz_add_virtual_device(idx,113,nom_compteur)
# Log Domoticz :
domoticz_write_log(u'Cozytouch : creation '+nom+u' ,url: '+url)
# ajout du dictionnaire dans la liste des device:
liste.append(radiateur)
print(u'Ajout: '+nom)
return liste
def ajout_module_fil_pilote(idx,liste,url,x,label):
''' Fonction ajout module fil pilote
'''
# création du nom suivant la position JSON du device dans l'API Cozytouch
nom = 'Module fil pilote '+str(label)
# création du dictionnaire de définition du device
module_fil_pilote = {}
module_fil_pilote['url'] = url
module_fil_pilote['x']= x
module_fil_pilote['nom']= nom
# Création switch selecteur (level_0=off/level_10=frostprotection/level_20=eco/level_30=confort-2/level_40=confort-1/level_50=confort) :
nom_switch = u'Mode '+nom
module_fil_pilote[u'idx_switch']= domoticz_add_virtual_device(idx,1002,nom)
# Personnalisation du switch(Modification du nom des levels et de l'icone)
option = u'TGV2ZWxOYW1lczpPZmZ8SG9ycyBnZWx8RWNvfENvbmZvcnQgLTJ8Q29uZm9ydCAtMXxDb25mb3J0O0xldmVsQWN0aW9uczp8fHx8fDtTZWxlY3RvclN0eWxlOjE7TGV2ZWxPZmZIaWRkZW46ZmFsc2U%3D&protected=false&strparam1=&strparam2=&switchtype=18&type=setused&used=true'
myurl=u'http://'+domoticz_ip+u":"+domoticz_port+u'/json.htm?addjvalue=0&addjvalue2=0&customimage=15&description=&idx='+module_fil_pilote[u'idx_switch']+u'&name='+nom_switch+u'+&options='+option
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Log Domoticz :
domoticz_write_log(u"Cozytouch : creation "+nom+u" ,url: "+url)
# ajout du dictionnaire dans la liste des device:
liste.append(module_fil_pilote)
print("Ajout: "+nom)
return liste
def ajout_chauffe_eau(idx,liste,url,x,label):
''' Fonction ajout chauffe eau
'''
# création du nom suivant la position JSON du device dans l'API Cozytouch
nom = 'Chauffe eau '+str(label)
nom.encode('utf-8')
# création du dictionnaire de définition du device
chauffe_eau= {}
chauffe_eau['url'] = url
chauffe_eau['x']= x
chauffe_eau['nom']= nom
# Switch selecteur auto/manu/manu+eco:
nom_switch = 'Mode '+nom
chauffe_eau['idx_switch_auto_manu']= domoticz_add_virtual_device(idx,1002,nom)
# Personnalisation du switch (Modification du nom des levels et de l'icone)
option = 'TGV2ZWxOYW1lcyUzQUF1dG8lN0NNYW51JTdDTWFudStFY28lM0JMZXZlbEFjdGlvbnMlM0ElN0MlN0MlN0MlM0JTZWxlY3RvclN0eWxlJTNBMCUzQkxldmVsT2ZmSGlkZGVuJTNBZmFsc2UlM0I='
myurl='http://'+domoticz_ip+":"+domoticz_port+'/json.htm?type=setused&idx='+(chauffe_eau['idx_switch_auto_manu'])+'&name='+nom_switch+'&description=&strparam1=&strparam2=&protected=false&switchtype=18&customimage=15&used=true&addjvalue=0&addjvalue2=0&options='+option
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Switch on/off
nom_switch_on_off = 'Etat '+nom
chauffe_eau['idx_on_off']= domoticz_add_virtual_device(idx,6,nom_switch_on_off)
myurl='http://'+domoticz_ip+":"+domoticz_port+'/json.htm?type=setused&idx='+(chauffe_eau['idx_on_off'])+'&name='+nom_switch_on_off+'&description=&strparam1=&strparam2=&protected=false&switchtype=0&customimage=15&used=true&addjvalue=0&addjvalue2=0&options='
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Mesure température eau:
nom_mesure = 'Temperature eau '+nom
chauffe_eau['idx_mesure_temp']= domoticz_add_virtual_device(idx,80,nom_mesure)
# Compteur d'eau :
nom_compteur= 'Eau restante '+nom
chauffe_eau['idx_conso_eau']= domoticz_add_virtual_device(idx,1004,nom_compteur,option='litres')
# Personnalisation du switch (Modification de l'icone)
myurl='http://'+domoticz_ip+":"+domoticz_port+'/json.htm?type=setused&idx='+(chauffe_eau['idx_conso_eau'])+'&name='+nom_compteur+'&description=&switchtype=2&addjvalue=0&used=true&options='
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Compteur temps de fonctionnement pompe à chaleur :
nom_compteur_pompe = 'Pompe a chaleur '+nom
chauffe_eau['idx_compteur_pompe']= domoticz_add_virtual_device(idx,113,nom_mesure)
# Personnalisation du switch (Modification du nom des levels et de l'icone)
option = 'VmFsdWVRdWFudGl0eSUzQUglM0JWYWx1ZVVuaXRzJTNBSGV1cmVzJTNC'
myurl='http://'+domoticz_ip+":"+domoticz_port+'/json.htm?type=setused&idx='+(chauffe_eau['idx_compteur_pompe'])+'&name='+nom_compteur_pompe+'&switchtype=3&addjvalue=0&used=true&options='+option
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
# Compteur d'énergie :
nom_compteur= 'Energie '+nom
chauffe_eau['idx_compteur']= domoticz_add_virtual_device(idx,18,nom_compteur)
# Log Domoticz :
domoticz_write_log(u"Cozytouch : creation "+nom+u" ,url: "+url)