-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
plugin.py
2708 lines (2369 loc) · 119 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
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
# Linky Plugin
#
# Authors:
# Copyright (C) 2016 Baptiste Candellier
# Modified (C) 2017 Asdepique777
# Corrected (C) 2017 epierre
# Modified (C) 2017 Asdepique777
# Modified (C) 2018-2021 Barberousse
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License # along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
"""
<plugin key="linky" name="Linky" author="Barberousse" version="2.5.7" externallink="https://github.com/guillaumezin/DomoticzLinky">
<params>
<param field="Mode4" label="Heures creuses (vide pour désactiver, cf. readme pour la syntaxe)" width="500px" required="false" default="">
<!-- <param field="Mode4" label="Heures creuses" width="500px">
<options>
<option label="Désactivées" value="" default="true" />
<option label="21h30-5h30" value="21h30-5h30" />
<option label="22h00-6h00" value="22h00-6h00" />
<option label="22h30-6h30" value="22h30-6h30" />
<option label="23h00-7h00" value="23h00-7h00" />
<option label="23h30-7h00" value="23h30-7h00" />
<option label="23h30-7h30" value="23h30-7h30" />
<option label="0h00-8h00" value="0h00-8h00" />
<option label="1h00-7h00 et 12h30-14h30" value="1h00-7h00 et 12h30-14h30" />
<option label="1h00-7h30 et 12h30-14h00" value="1h00-7h30 et 12h30-14h00" />
<option label="1h00-7h30 et 12h00-14h30" value="1h00-7h30 et 13h00-14h30" />
<option label="1h30-7h30 et 12h00-14h00" value="1h30-7h30 et 12h00-14h00" />
<option label="1h30-7h30 et 12h30-14h30" value="1h30-7h30 et 12h30-14h30" />
<option label="2h00-7h00 et 12h30-15h30" value="2h00-7h00 et 12h30-15h30" />
<option label="2h00-7h00 et 13h00-16h00" value="2h00-7h00 et 13h00-16h00" />
<option label="2h00-7h00 et 14h00-17h00" value="2h00-7h00 et 14h00-17h00" />
<option label="2h00-8h00 et 13h30-15h30" value="2h00-8h00 et 13h30-15h30" />
<option label="3h00-8h00 et 13h30-16h30" value="3h00-8h00 et 13h30-16h30" />
<option label="3h00-7h00 et 12h30-14h30 et 20h30-22h30" value="3h00-7h00 et 12h30-14h30 et 20h30-22h30" />
<option label="3h30-7h00 et 13h00-16h00 et 22h30-6h30" value="3h30-7h00 et 13h00-16h00 et 22h30-6h30" />
</options>
-->
</param>
<param field="Mode5" label="Consommation à montrer sur le tableau de bord (affichage principal)" width="500px">
<options>
<option label="Pic consommation journée dernière" value="peak_day" />
<option label="Pic consommation semaine en cours" value="peak_cweek" />
<option label="Pic consommation semaine dernière" value="peak_lweek" />
<option label="Pic consommation mois en cours" value="peak_cmonth" />
<option label="Pic consommation mois dernier" value="peak_lmonth" />
<option label="Pic consommation année en cours" value="peak_year" />
</options>
</param>
<param field="Mode6" label="Consommation à montrer sur le tableau de bord (affichage secondaire)" width="500px">
<options>
<option label="Consommation / production journée dernière" value="value_day" default="true" />
<option label="Consommation / production semaine en cours" value="value_cweek" />
<option label="Consommation / production semaine dernière" value="value_lweek" />
<option label="Consommation / production mois en cours" value="value_cmonth" />
<!-- <option label="Consommation / production mois dernier" value="value_lmonth" />
<option label="Consommation / production année en cours" value="value_year" /> -->
<option label="Consommation / production horaire max journée dernière" value="max_day" />
<option label="Consommation / production horaire max semaine en cours" value="max_cweek" />
<option label="Consommation / production horaire max semaine dernière" value="max_lweek" />
<option label="Consommation / production horaire max mois en cours" value="max_cmonth" />
<!-- <option label="Consommation / production horaire max mois dernier" value="max_lmonth" />
<option label="Consommation / production horaire max année en cours" value="max_year" /> -->
<option label="Consommation / production horaire moyenne journée dernière" value="mean_day" />
<option label="Consommation / production horaire moyenne semaine en cours" value="mean_cweek" />
<option label="Consommation / production horaire moyenne semaine dernière" value="mean_lweek" />
<option label="Consommation / production horaire moyenne mois en cours" value="mean_cmonth" />
<!-- <option label="Consommation / production horaire moyenne mois dernier" value="mean_lmonth" />
<option label="Consommation / production horaire moyenne année en cours" value="mean_year" /> -->
</options>
</param>
<param field="Mode1" label="Nombre de jours à récupérer pour la vue par heures (0 min, pour désactiver la récupération par heures, 7 max)" width="50px" required="false" default="7"/>
<param field="Mode2" label="Nombre de jours à récupérer pour les autres vues (730 max)" width="50px" required="false" default="7"/>
<param field="Mode3" label="Debug" width="170px">
<options>
<option label="Non" value="0" default="true" />
<option label="Simple" value="1"/>
<option label="Avancé" value="2"/>
<option label="Reset consentement" value="3"/>
<option label="Reset cache" value="4"/>
<option label="Faux client 0" value="10"/>
<option label="Faux client 1" value="11"/>
<option label="Faux client 2" value="12"/>
<option label="Faux client 3" value="13"/>
<option label="Faux client 4" value="14"/>
<option label="Faux client 5" value="15"/>
<option label="Faux client 6" value="16"/>
<option label="Faux client 7" value="17"/>
<option label="Faux client 8" value="18"/>
<option label="Faux client 9" value="19"/>
</options>
</param>
</params>
</plugin>
"""
# https://www.domoticz.com/wiki/Developing_a_Python_plugin
import Domoticz
import sys
import json
import copy
from urllib.parse import quote
# import re
from datetime import datetime
from datetime import date
from datetime import time
from datetime import timedelta
from time import strptime
# from random import randint
# import html
import re
import tempfile
import pickle
import codecs
import hashlib
CLIENT_ID = ["d198fd52-61c0-4b77-8725-06a1ef90da9f", "9c551777-9d1b-447c-9e68-bfe6896ee002"]
LOGIN_BASE_PORT = ["443", "443"]
LOGIN_BASE_URI = ["enedis.domoticz.russandol.pro", "opensrcdev.alwaysdata.net"]
API_ENDPOINT_DEVICE_CODE = ["/device/code", "/domoticzlinkyconnect/device/code"]
API_ENDPOINT_DEVICE_TOKEN = ["/device/token", "/domoticzlinkyconnect/device/token"]
VERIFY_CODE_URI = ["https://" + LOGIN_BASE_URI[0] + "/device?code=",
"https://" + LOGIN_BASE_URI[1] + "/domoticzlinkyconnect/device?code="]
API_BASE_PORT = ["443", "443"]
API_BASE_URI = ["enedis.domoticz.russandol.pro", "opensrcdev.alwaysdata.net"]
API_ENDPOINT_DATA_URI = ["/data/proxy", "/domoticzlinkyconnect/data/proxy"]
API_ENDPOINT_DATA_CONSUMPTION_LOAD_CURVE = '/metering_data_clc/v5/consumption_load_curve'
API_ENDPOINT_DATA_CONSUMPTION_MAX_POWER = '/metering_data_dcmp/v5/daily_consumption_max_power'
API_ENDPOINT_DATA_DAILY_CONSUMPTION = '/metering_data_dc/v5/daily_consumption'
API_ENDPOINT_DATA_PRODUCTION_LOAD_CURVE = '/metering_data_plc/v5/production_load_curve'
API_ENDPOINT_DATA_DAILY_PRODUCTION = '/metering_data_dp/v5/daily_production'
HEADERS = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
}
USAGE_POINT_SEPARATOR = " / "
NB_WEEKS_LONG_HISTORY = 5
NO_STATUS_ERROR_CODE = 999
class BasePlugin:
# boolean: to check that we are started, to prevent error messages when disabling or restarting the plugin
isStarted = False
# object: http connection for login
httpLoginConn = None
# object: http connection for data
httpDataConn = None
# string: name of the Linky device
sDeviceName = "Linky"
# string: description of the Linky device
sDescription = "Compteur Linky"
# list of integer: type (pTypeP1Power or pTypeGeneral)
lType = [0xfa, 0xf3]
# list of integer: subtype (sTypeP1Power or sTypeManagedCounter)
lSubType = [0x01, 0x21]
# list of integer: switch type (Energy)
lSwitchType = [0, 0]
# list of dict: options
lOptions = [{"DisableLogAutoUpdate": "true", "AddDBLogEntry": "true"}, {}]
# string: step name of the state machine
sConnectionStep = None
# string: memory of step name of the state machine during connection
sMemConnectionStep = None
# string: step name of the next state machine during connection
sConnectionNextStep = None
# boolean: true if a step failed
bHasAFail = None
bGlobalHasAFail = None
# datetime: start date for short log
dateBeginHours = None
# datetime: end date for short log
dateEndHours = None
# datetime: start date for history
dateBeginDays = None
# datetime: end date for history
dateEndDays = None
# integer: number of days of data to grab for short log
iHistoryDaysForHoursView = None
# integer: number of days of data to grab for history
iSavedHistoryDaysForDaysView = None
iHistoryDaysForDaysView = None
# integer: number of days left fot next batch of data
iDaysLeft = None
iDaysLeftHoursView = None
# datetime: backup end date
savedDateEndDays = None
savedDateEndDaysForHoursView = None
# datetime: backup 2 end date
savedDateEndDays2 = None
# datetime: date for hours history view beginning
dateBeginDaysHistoryView = None
# boolean: is this the batch of the most recent history
bFirstMonths = None
# list: usage point id
lUsagePointIndex = None
# integer: usage point id index in list
iUsagePointIndex = None
# string: current usage point
sUsagePointId = None
# string: previous usage point
sPrevUsagePointId = None
# string: consumption to show = current week ("cweek"), the previous week ("lweek", the current month ("cmonth"), the previous month ("lmonth"), or year ("cyear"), prefix "max_" for max calculation
sConsumptionType1 = None
sConsumptionType2 = None
# Tarif
sTarif = None
# integer: number of other view (peak)
iHistoryDaysForPeakDaysView = None
# boolean: debug mode
iDebugLevel = 0
# previous day
prevDay = None
# current day
curDay = None
# first day of month
fdmonth = None
# last day of previous month
ldpmonth = None
# first day of previous month
fdpmonth = None
# first day of week
fdweek = None
# last day of previous week
ldpweek = None
# first day of previous week
fdpweek = None
# first day of year
fdyear = None
# received device code
sDeviceCode = None
# interval to retry
iInterval = 5
# no consumption data
bNoConsumption = None
# no production data
bNoProduction = None
# production mode
bProdMode = None
# send nuffer
sBuffer = None
# data sent
sMemData = None
# connect for login if true, for data if false
bLoginConnect = True
# timeout counter
iTimeoutCount = 0
# resend counter
iResendCount = 0
# data dict with date string as index and consumption1, consumption2, production1, production2, consumptionpeak, productionpeak as float, peak as boolean and date as DateTime
dData = None
# dict with time (xxhmm format) as index and a boolean to indicate tariff
dHc = None
# dict with calculation to show on dashboard
dCalculate = None
# datetime
dateNextConnection = None
# integer: which device to use
iAlternateDevice = 0
# list: false customoer
lFalseCustomer = []
# integer: which address to use (production or sandbox)
iAlternateAddress = 0
# to know that we come from refresh token step
bRefreshToken = None
# dict of timeout
dUsagePointTimeout = None
# global timeout
dtGlobalTimeout = None
# last refresh
dtNextRefresh = None
# debug file
fDebug = None
# datetime: last data sent
dtLastSend = None
# has iHistoryDaysForDaysView changed?
bHistoryDaysForDaysViewChanged = False
# should we grab all days for day view?
bHistoryDaysForDaysViewGrabAll = False
# datetime of last successfull connection in memory
def __init__(self):
self.isStarted = False
self.httpLoginConn = None
self.httpDataConn = None
self.sConnectionStep = "idle"
self.bHasAFail = False
self.bGlobalHasAFail = False
self.sBuffer = None
self.iTimeoutCount = 0
self.iResendCount = 0
self.iUsagePointIndex = 0
self.lUsagePointIndex = []
self.dUsagePointTimeout = {}
self.dtLastSend = datetime(2000, 1, 1)
def myMessage(self, message, bNoLog=False):
if (not bNoLog) and (self.iDebugLevel > 1):
Domoticz.Log(message)
if self.fDebug:
try:
self.fDebug.writelines(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + " " + message + "\n")
except:
pass
def myLog(self, message):
Domoticz.Log(message)
self.myMessage(message, True)
def myDebug(self, message, bNoLog=False):
self.myMessage("Debug : " + message)
def myStatus(self, message):
Domoticz.Status(message)
self.myMessage("Status : " + message, True)
def myError(self, message):
Domoticz.Error(message)
self.myMessage("Erreur : " + message, True)
# resend same data
def reconnectAndResend(self):
self.sBuffer = self.sMemData
self.sConnectionNextStep = self.sMemConnectionStep
self.sConnectionStep = "connecting"
self.iTimeoutCount = 0
self.iResendCount = self.iResendCount + 1
if self.bLoginConnect:
self.httpLoginConn = Domoticz.Connection(Name="HTTPS connection", Transport="TCP/IP", Protocol="HTTPS",
Address=LOGIN_BASE_URI[self.iAlternateAddress],
Port=LOGIN_BASE_PORT[self.iAlternateAddress])
self.httpLoginConn.Connect()
else:
self.httpDataConn = Domoticz.Connection(Name="HTTPS connection", Transport="TCP/IP", Protocol="HTTPS",
Address=API_BASE_URI[self.iAlternateAddress],
Port=API_BASE_PORT[self.iAlternateAddress])
self.httpDataConn.Connect()
# Prepare buffer and connect
def connectAndSend(self, conn, data, address, port):
self.sMemData = data
self.sBuffer = data
self.sConnectionNextStep = self.sConnectionStep
self.sMemConnectionStep = self.sConnectionStep
self.iTimeoutCount = 0
self.iResendCount = 0
dtNow = datetime.now()
# Prevent too quick connections, to not trigger protection mechanism
if dtNow > (self.dtLastSend + timedelta(seconds=5)):
self.dtLastSend = dtNow
self.sConnectionStep = "connecting"
conn = Domoticz.Connection(Name="HTTPS connection", Transport="TCP/IP", Protocol="HTTPS", Address=address,
Port=port)
conn.Connect()
return conn
else:
self.sConnectionStep = "retry"
self.setNextConnectionForLater(self.iInterval)
return None
# Connect for login
def connectAndSendForAuthorize(self, data):
self.bLoginConnect = True
self.httpLoginConn = self.connectAndSend(self.httpLoginConn, data, LOGIN_BASE_URI[self.iAlternateAddress],
LOGIN_BASE_PORT[self.iAlternateAddress])
# Connect for metering data
def connectAndSendForMetering(self, data):
self.bLoginConnect = False
self.httpDataConn = self.connectAndSend(self.httpDataConn, data, API_BASE_URI[self.iAlternateAddress],
API_BASE_PORT[self.iAlternateAddress])
# get default headers
def initHeaders(self, uri):
headers = dict(HEADERS)
headers["User-Agent"] = "DomoticzLinkyPlugin/" + Parameters["Version"]
headers["Host"] = uri
return headers
# get access token
def getDeviceCode(self):
if ((int(LOGIN_BASE_PORT[self.iAlternateAddress]) == 80) or (int(LOGIN_BASE_PORT[self.iAlternateAddress]) == 443)) :
headers = self.initHeaders(LOGIN_BASE_URI[self.iAlternateAddress])
else:
headers = self.initHeaders(LOGIN_BASE_URI[self.iAlternateAddress] + ":" + LOGIN_BASE_PORT[self.iAlternateAddress])
postData = {
"client_id": CLIENT_ID[self.iAlternateAddress]
}
sendData = {
"Verb": "POST",
"URL": API_ENDPOINT_DEVICE_CODE[self.iAlternateAddress],
"Headers": headers,
"Data": dictToQuotedString(postData)
}
self.dumpDictToLog(sendData)
self.connectAndSendForAuthorize(sendData)
def showStatusError(self, hours, Data, bWarningOnly=False, bDebug=False):
sErrorSentence = "Erreur"
iStatus = getStatus(Data)
if iStatus != NO_STATUS_ERROR_CODE:
sErrorSentence = sErrorSentence + " status : " + str(getStatus(Data))
sError, sErrorDescription, sErrorUri = getError(Data)
if sError:
sErrorSentence = sErrorSentence + " - code " + sError
if sErrorDescription:
sErrorSentence = sErrorSentence + " - description : " + sErrorDescription
if sErrorUri:
sErrorSentence = sErrorSentence + " - URI : " + sErrorUri
self.showStepError(hours, sErrorSentence, bWarningOnly, bDebug)
def showSimpleStatusError(self, Data, bWarningOnly=False, bDebug=False):
sErrorSentence = "Erreur"
iStatus = getStatus(Data)
if iStatus != NO_STATUS_ERROR_CODE:
sErrorSentence = sErrorSentence + " status : " + str(getStatus(Data))
sError, sErrorDescription, sErrorUri = getError(Data)
if sError:
sErrorSentence = sErrorSentence + " - code " + sError
if sErrorDescription:
sErrorSentence = sErrorSentence + " - description : " + sErrorDescription
if sErrorUri:
sErrorSentence = sErrorSentence + " - URI : " + sErrorUri
self.showSimpleStepError(sErrorSentence, bWarningOnly, bDebug)
def parseDeviceCode(self, Data):
#self.dumpDictToLog(Data)
iStatus = getStatus(Data)
if iStatus == 200:
if Data and ("Data" in Data):
try:
dJson = json.loads(Data["Data"].decode())
except ValueError as err:
self.showSimpleStepError("Les données reçues ne sont pas du JSON : " + str(err))
return False
count = 0
if dJson and ("device_code" in dJson):
self.sDeviceCode = dJson["device_code"]
count = count + 1
if dJson and ("user_code" in dJson):
sUserCode = dJson["user_code"]
count = count + 1
if count == 2:
sUrl = VERIFY_CODE_URI[self.iAlternateAddress] + quote(sUserCode)
self.myError(
"Connectez-vous à l'adresse " + sUrl + " pour lancer la demande de consentement avec le code " + sUserCode)
return "done"
else:
self.showSimpleStepError("Données incomplètes")
else:
self.showSimpleStepError("Pas de données reçue")
else:
self.showSimpleStatusError(Data)
return "retry"
# get access token
def getAccessToken(self):
if ((int(LOGIN_BASE_PORT[self.iAlternateAddress]) == 80) or (int(LOGIN_BASE_PORT[self.iAlternateAddress]) == 443)) :
headers = self.initHeaders(LOGIN_BASE_URI[self.iAlternateAddress])
else:
headers = self.initHeaders(LOGIN_BASE_URI[self.iAlternateAddress] + ":" + LOGIN_BASE_PORT[self.iAlternateAddress])
postData = {
"client_id": CLIENT_ID[self.iAlternateAddress],
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"device_code": self.sDeviceCode
}
sendData = {
"Verb": "POST",
"URL": API_ENDPOINT_DEVICE_TOKEN[self.iAlternateAddress],
"Headers": headers,
"Data": dictToQuotedString(postData)
}
self.dumpDictToLog(sendData)
self.connectAndSendForAuthorize(sendData)
# Refresh token
def refreshToken(self):
if ((int(LOGIN_BASE_PORT[self.iAlternateAddress]) == 80) or (int(LOGIN_BASE_PORT[self.iAlternateAddress]) == 443)) :
headers = self.initHeaders(LOGIN_BASE_URI[self.iAlternateAddress])
else:
headers = self.initHeaders(LOGIN_BASE_URI[self.iAlternateAddress] + ":" + LOGIN_BASE_PORT[self.iAlternateAddress])
postData = {
"grant_type": "refresh_token",
"client_id": CLIENT_ID[self.iAlternateAddress],
"usage_points_id": ','.join(self.getConfigItem("usage_points_id", [])),
"refresh_token": self.getConfigItem("refresh_token", "")
}
sendData = {
"Verb": "POST",
"URL": API_ENDPOINT_DEVICE_TOKEN[self.iAlternateAddress],
"Headers": headers,
"Data": dictToQuotedString(postData)
}
self.bRefreshToken = True
self.dumpDictToLog(sendData)
self.connectAndSendForAuthorize(sendData)
# Parse access token
def parseAccessToken(self, Data):
#self.dumpDictToLog(Data)
iStatus = getStatus(Data)
sError, sErrorDescription, sErrorUri = getError(Data)
sError = sError.casefold()
if (sError == "unauthorized") or (sError == "invalid_grant") or (sError == "invalid_request"):
self.showSimpleStatusError(Data)
return "error"
if sError == "authorization_pending":
self.myDebug("pending")
if Data and ("Data" in Data):
try:
dJson = json.loads(Data["Data"].decode())
except ValueError as err:
self.showSimpleStepError("Les données reçues ne sont pas du JSON : " + str(err))
return "retry"
if dJson and ("interval" in dJson):
try:
self.iInterval = int(dJson["interval"])
except:
self.iInterval = 5
return "pending"
elif iStatus == 200:
if Data and ("Data" in Data):
try:
dJson = json.loads(Data["Data"].decode())
except ValueError as err:
self.showSimpleStepError("Les données reçues ne sont pas du JSON : " + str(err))
return "retry"
if dJson and ("usage_points_id" in dJson):
self.setConfigItem("usage_points_id", str(dJson["usage_points_id"]).split(","))
count = 0
if dJson and ("refresh_token" in dJson):
self.setConfigItem("refresh_token", dJson["refresh_token"])
count = count + 1
if dJson and ("access_token" in dJson):
self.setConfigItem("access_token", dJson["access_token"])
count = count + 1
if dJson and ("token_type" in dJson):
self.setConfigItem("token_type", dJson["token_type"])
count = count + 1
if dJson and ("expires_in" in dJson):
self.setConfigItem("expires_at", datetime.now() + timedelta(seconds=int(dJson["expires_in"])) - timedelta(minutes=10))
count = count + 1
if count == 4:
return "done"
else:
self.showSimpleStepError("Pas assez de données reçue")
else:
self.showSimpleStepError("Pas de données reçue")
else:
self.showSimpleStatusError(Data)
return "retry"
# Get data
def getData(self, uri, dtStart, dtEnd):
if ((int(API_BASE_PORT[self.iAlternateAddress]) == 80) or (int(API_BASE_PORT[self.iAlternateAddress]) == 443)) :
headers = self.initHeaders(API_BASE_URI[self.iAlternateAddress])
else:
headers = self.initHeaders(API_BASE_URI[self.iAlternateAddress] + ":" + API_BASE_PORT[self.iAlternateAddress])
headers["Authorization"] = self.getConfigItem("token_type", "") + " " + self.getConfigItem("access_token", "")
query = {
"start": datetimeToEnedisDateString(dtStart),
"end": datetimeToEnedisDateString(dtEnd),
"usage_point_id": self.sUsagePointId
}
sendData = {
"Verb": "GET",
"URL": API_ENDPOINT_DATA_URI[self.iAlternateAddress] + uri + "?" + dictToQuotedString(query),
"Headers": headers
#"Data": dictToQuotedString(query)
}
self.dumpDictToLog(sendData)
self.connectAndSendForMetering(sendData)
# get and create if needed Domoticz device
def getOrCreateDevice(self, sUsagePointCurrentId):
for iIndexUnit, oDevice in Devices.items():
if sUsagePointCurrentId == oDevice.DeviceID:
return oDevice
for iIndexUnit in range(1, 256):
if iIndexUnit == 256:
self.showSimpleStepError(
"Ne peut ajouter de dispositif Linky à la base de données. Trop de dispositifs déjà présents, faites le ménage SVP")
return None
if iIndexUnit not in Devices:
Domoticz.Device(Name=self.sDeviceName + " " + sUsagePointCurrentId, DeviceID=sUsagePointCurrentId,
Unit=iIndexUnit, Type=self.lType[self.iAlternateDevice],
Subtype=self.lSubType[self.iAlternateDevice],
Switchtype=self.lSwitchType[self.iAlternateDevice],
Description=self.sDescription + " " + sUsagePointCurrentId,
Options=self.lOptions[self.iAlternateDevice], Used=1).Create()
if iIndexUnit not in Devices:
self.showSimpleStepError(
"Ne peut ajouter de dispositif Linky à la base de données. Vérifiez dans les paramètres de Domoticz que l'ajout de nouveaux dispositifs est autorisé")
return None
else:
return Devices[iIndexUnit]
# insert usage in Domoticz DB
def addToDevice(self, oDevice, fConsumption1, fConsumption2, fProduction1, fProduction2, sDate):
if self.iAlternateDevice:
sValue = "-1.0;" + str(fConsumption1 + fConsumption2) + ";" + sDate
else:
sValue = str(fConsumption1) + ";" + str(fConsumption2) + ";" + str(fProduction1) + ";" + str(
fProduction2) + ";0;0;" + sDate
self.myDebug("Mets dans la BDD la valeur " + sValue)
oDevice.Update(nValue=0, sValue=sValue,
Type=self.lType[self.iAlternateDevice],
Subtype=self.lSubType[self.iAlternateDevice],
Switchtype=self.lSwitchType[self.iAlternateDevice],
Options=self.lOptions[self.iAlternateDevice])
return True
# Update value shown on Domoticz dashboard
def updateDevice(self, oDevice, fConsoVal1, fConsoVal2, fProdVal1, fProdVal2, fSecVal1, fSecVal2):
if self.iAlternateDevice:
sValue = "-1.0;" + str(fSecVal1 + fSecVal2)
else:
sValue = str(fConsoVal1) + ";" + str(fConsoVal2) + ";" + str(fProdVal1) + ";" + str(fProdVal2) + ";" + str(
fSecVal1) + ";" + str(fSecVal2)
self.myDebug("Mets sur le tableau de bord la valeur " + sValue)
oDevice.Update(nValue=0, sValue=sValue,
Type=self.lType[self.iAlternateDevice],
Subtype=self.lSubType[self.iAlternateDevice],
Switchtype=self.lSwitchType[self.iAlternateDevice],
Options=self.lOptions[self.iAlternateDevice],
TimedOut=0)
return True
# Show error in state machine context
def showSimpleStepError(self, logMessage, bWarningOnly=False, bDebug=False):
sMessage = "Durant l'étape : " + self.sConnectionStep + " - " + logMessage
if bDebug:
self.myDebug(sMessage)
elif bWarningOnly:
self.myStatus(sMessage)
else:
self.myError(sMessage)
# Show error in state machine context with dates
def showStepError(self, hours, logMessage, bWarningOnly=False, bDebug=False):
if hours:
sMessage = "Durant l'étape " + self.sConnectionStep + " de " + datetimeToEnedisDateString(
self.dateBeginHours) + " à " + datetimeToEnedisDateString(self.dateEndHours) + " - " + logMessage
else:
sMessage = "Durant l'étape " + self.sConnectionStep + " de " + datetimeToEnedisDateString(
self.dateBeginDays) + " à " + datetimeToEnedisDateString(self.dateEndDays) + " - " + logMessage
if bDebug:
self.myDebug(sMessage)
elif bWarningOnly:
self.myStatus(sMessage)
else:
self.myError(sMessage)
# Parse HP/HC parameter string and store result in dHc
def parseHcParameter(self, sHcParameter):
self.dHc = {}
sLocalUsagePointId = "all"
iWeekday = 7
sProd = "all"
sHcParameter = sHcParameter.casefold().strip()
# Exemple 963222123213 12h30-14h00
# https://regex101.com/r/cMWfqj/11
for matchHc in re.finditer(r"(?:(\d+)(?:$|\s))?(?:([a-zéè]+)(?:$|\s))?(?:([a-zéè]+)(?:$|\s))?(?:(\d+)\s*[h:]\s*(\d+)?\s*(?:[-_aà]|to)+\s*(\d+)\s*[h:]\s*(\d+)?)?", sHcParameter):
#Domoticz.Log("match " + matchHc.group(1) + " " + matchHc.group(2) + " " + matchHc.group(3) + " " + matchHc.group(4) + " " + matchHc.group(5) + " " + matchHc.group(6) + " " + matchHc.group(7))
if matchHc.group(1):
sLocalUsagePointId = matchHc.group(1).upper().strip()
sProd = "all"
iWeekday = 7
#Domoticz.Log(sLocalUsagePointId)
sMG2 = matchHc.group(2)
if sMG2:
sMG2 = sMG2.casefold().strip()
sMG3 = matchHc.group(3)
if sMG3:
sMG3 = sMG3.casefold().strip()
sDay = sMG3
else:
sDay = sMG2
if sMG2.startswith("p"):
sProd = "prod"
iWeekday = 7
#Domoticz.Log(sDay)
if sDay.startswith("lu") or sDay.startswith("mo"):
iWeekday = 0
elif sDay.startswith("ma") or sDay.startswith("tu"):
iWeekday = 1
elif sDay.startswith("me") or sDay.startswith("we"):
iWeekday = 2
elif sDay.startswith("je") or sDay.startswith("th"):
iWeekday = 3
elif sDay.startswith("ve") or sDay.startswith("fr"):
iWeekday = 4
elif sDay.startswith("sa") or sDay.startswith("sa"):
iWeekday = 5
elif sDay.startswith("di") or sDay.startswith("su"):
iWeekday = 6
elif sDay.startswith("fe") or sDay.startswith("fé") or sDay.startswith("fè") or sDay.startswith("jo") or sDay.startswith("pu") or sDay.startswith("ba") or sDay.startswith("ho"):
iWeekday = 8
else:
iWeekday = 7
#Domoticz.Log(sLocalUsagePointId)
if not sLocalUsagePointId in self.dHc:
self.dHc[sLocalUsagePointId] = {}
if not sProd in self.dHc[sLocalUsagePointId]:
self.dHc[sLocalUsagePointId][sProd] = {}
if not iWeekday in self.dHc[sLocalUsagePointId][sProd]:
self.dHc[sLocalUsagePointId][sProd][iWeekday] = []
if matchHc.group(4):
iHoursBegin = int(matchHc.group(4))
iHoursEnd = int(matchHc.group(6))
if matchHc.group(5):
iMinutesBegin = int(matchHc.group(5))
else:
iMinutesBegin = 0
if matchHc.group(7):
iMinutesEnd = int(matchHc.group(7))
else:
iMinutesEnd = 0
if iHoursBegin > 23:
iHoursBegin = 23
iMinutesBegin = 59
elif iHoursBegin < 0:
iHoursBegin = 0
if iHoursEnd > 23:
iHoursEnd = 23
iMinutesEnd = 59
elif iHoursEnd < 0:
iHoursEnd = 0
if iMinutesBegin > 59:
iMinutesBegin = 59
elif iMinutesBegin < 0:
iMinutesBegin = 0
if iMinutesEnd > 59:
iMinutesEnd = 59
elif iMinutesEnd < 0:
iMinutesEnd = 0
datetimeBegin = datetime(2010, 1, 1, iHoursBegin, iMinutesBegin)
datetimeEnd = datetime(2010, 1, 1, iHoursEnd, iMinutesEnd)
timeBegin = datetimeBegin.time()
timeEnd = datetimeEnd.time()
if datetimeEnd < datetimeBegin:
self.dHc[sLocalUsagePointId][sProd][iWeekday].append([timeBegin, time(23,59,59,999999)])
self.dHc[sLocalUsagePointId][sProd][iWeekday].append([time(), timeEnd])
else:
self.dHc[sLocalUsagePointId][sProd][iWeekday].append([timeBegin, timeEnd])
#self.dumpDictToLog(self.dHc)
# Check date if in cost 1 or cost 2
def isCost2(self, dtDate, bProduction=False):
dtDate = dtDate - timedelta(minutes=30)
tDate = dtDate.time()
dDate = dtDate.date()
iWeekday = dtDate.weekday()
lUsagePointCurrentId = self.sUsagePointId.split(USAGE_POINT_SEPARATOR)
if bProduction and (len(lUsagePointCurrentId) > 1):
sLocalUsagePointId = lUsagePointCurrentId[1]
else:
sLocalUsagePointId = lUsagePointCurrentId[0]
if sLocalUsagePointId in self.dHc:
dHc = self.dHc[sLocalUsagePointId]
elif "all" in self.dHc:
dHc = self.dHc["all"]
else:
return False
if bProduction:
if "prod" in dHc:
dPHc = dHc["prod"]
elif "all" in dHc:
dPHc = dHc["all"]
else:
return False
else:
if "all" in dHc:
dPHc = dHc["all"]
else:
return False
if JoursFeries.is_bank_holiday(dDate) and (8 in dPHc):
lHc = dPHc[8]
elif iWeekday in dPHc:
lHc = dPHc[iWeekday]
elif 7 in dPHc:
lHc = dPHc[7]
else:
return False
for lDateInterval in lHc:
if (tDate >= lDateInterval[0]) and (tDate < lDateInterval[1]):
return True
return False
# Check current usage point has 2 costs
def has2Costs(self, sUsagePointCurrentId):
lUsagePointCurrentId = sUsagePointCurrentId.split(USAGE_POINT_SEPARATOR)
if len(lUsagePointCurrentId) > 1:
return ("all" in self.dHc) or (lUsagePointCurrentId[0] in self.dHc) or (lUsagePointCurrentId[1] in self.dHc)
else:
return ("all" in self.dHc) or (lUsagePointCurrentId[0] in self.dHc)
# Write data from memory to Domoticz DB
def saveDataToDb(self, sUsagePointCurrentId):
if sUsagePointCurrentId not in self.dData:
return False
oDevice = self.getOrCreateDevice(sUsagePointCurrentId)
if not oDevice:
return False
dUsagePointData = self.dData[sUsagePointCurrentId]["data"]
iConsumption1 = 0
iConsumption2 = 0
iProduction1 = 0
iProduction2 = 0
self.resetCalculate(sUsagePointCurrentId)
iDConsumption1 = 0
iDConsumption2 = 0
iDProduction1 = 0
iDProduction2 = 0
iHourCount = 0
bHasConsoProd = False
# sorting needed
for sShortDate, dOneData in sorted(dUsagePointData.items()):
bHasConsoProd = False
#self.myDebug("Save data at " + str(sShortDate))
if dOneData["haspeak"]:
#self.myDebug("Save peak at " + str(dOneData["peakdate"]))
self.dayAccumulatePeak(sUsagePointCurrentId, dOneData["peakdate"], dOneData["consumptionpeak"], dOneData["productionpeak"])
if dOneData["hasconsoprod"]:
bHasConsoProd = True
dDate = dOneData["consoproddate"]
#self.myDebug("Save consoprod at " + str(dDate))
for iHour in range (0, 24):
fValConso1 = 0
fValConso2 = 0
fValProd1 = 0
fValProd2 = 0
bHasData = False
#if iHour in dOneData["consumption1_hours"]:
# fValConso1 = dOneData["consumption1_hours"][iHour]
# iDConsumption1 = iDConsumption1 + fValConso1
# bHasData = True
#if iHour in dOneData["consumption2_hours"]:
# fValConso2 = dOneData["consumption2_hours"][iHour]
# iDConsumption2 = iDConsumption2 + fValConso2
# bHasData = True
#if iHour in dOneData["production1_hours"]:
# fValProd1 = dOneData["production1_hours"][iHour]
# iDProduction1 = iDProduction1 + fValProd1
# bHasData = True
#if iHour in dOneData["production2_hours"]:
# fValProd2 = dOneData["production2_hours"][iHour]
# iDProduction2 = iDProduction2 + fValProd2
# bHasData = True
# Here we can shift data for hours view
dDate2 = dDate + timedelta(hours = iHour)
bCost2Cons = self.isCost2(dDate2, False)
bCost2Prod = self.isCost2(dDate2, True)
if iHour in dOneData["consumption1_hours"]:
bHasData = True
if bCost2Cons:
fValConso2 = dOneData["consumption1_hours"][iHour]
iDConsumption2 = iDConsumption2 + fValConso2
else:
fValConso1 = dOneData["consumption1_hours"][iHour]
iDConsumption1 = iDConsumption1 + fValConso1
if iHour in dOneData["consumption2_hours"]:
bHasData = True
if bCost2Cons:
fValConso2 = dOneData["consumption2_hours"][iHour]
iDConsumption2 = iDConsumption2 + fValConso2
else:
fValConso1 = dOneData["consumption2_hours"][iHour]
iDConsumption1 = iDConsumption1 + fValConso1
if iHour in dOneData["production1_hours"]:
bHasData = True
if bCost2Cons:
fValProd2 = dOneData["production1_hours"][iHour]
iDProduction2 = iDProduction2 + fValProd2
else:
fValProd1 = dOneData["production1_hours"][iHour]
iDProduction1 = iDProduction1 + fValProd1
if iHour in dOneData["production2_hours"]:
bHasData = True
if bCost2Cons:
fValProd2 = dOneData["production2_hours"][iHour]
iDProduction2 = iDProduction2 + fValProd2
else:
fValProd1 = dOneData["production2_hours"][iHour]
iDProduction1 = iDProduction1 + fValProd1
if bHasData:
self.dayAccumulateConsoProd(sUsagePointCurrentId, dDate2, fValConso1, fValConso2, fValProd1, fValProd2)
if (dDate2 >= self.curDay):
break
if bHasData:
iHourCount = iHourCount + 1
#self.myDebug("date " + str(dDate) + " " + str(iHour) + " " + str(dDate2) + " " + str(self.iHistoryDaysForHoursView) + " " + str(self.dateBeginDaysHistoryView))
# We don't want the last day = today, it's incomplete and create a glitch in views
if (self.iHistoryDaysForHoursView > 0) and (dDate2 >= self.dateBeginDaysHistoryView):
sLongDate = datetimeToSQLDateTimeString(dDate2)
if self.iAlternateDevice:
if not self.addToDevice(oDevice, fValConso1, fValConso2, fValProd1, fValProd2, sLongDate):
return False
else:
iConsumption1 = iConsumption1 + fValConso1
iConsumption2 = iConsumption2 + fValConso2
iProduction1 = iProduction1 + fValProd1
iProduction2 = iProduction2 + fValProd2
if not self.addToDevice(oDevice, iConsumption1, iConsumption2, iProduction1, iProduction2, sLongDate):
return False
# Here we can shift data for other views, choosing another hour as new date reference
if iHour == 0:
# Check we have enough data, at least half a day
if iHourCount >= 12:
# Here we can shift day accordingly to iHour, to use date from beginning of data
sShortDate = datetimeToSQLDateString(dDate2 - timedelta(hours=iHourCount))
if not self.addToDevice(oDevice, iDConsumption1, iDConsumption2, iDProduction1, iDProduction2, sShortDate):
return False
iDConsumption1 = 0
iDConsumption2 = 0
iDProduction1 = 0
iDProduction2 = 0
iHourCount = 0
#self.myDebug("--- " + str(bHasConsoProd) + " " + str(iHourCount) + " " + str(dDate2) + " " + str(self.curDay))
# Store last day if we still have data
if bHasConsoProd and (iHourCount >= 1) and (dDate <= self.curDay):
# Here we can shift day accordingly to iHour, to use date from beginning of data
sShortDate = datetimeToSQLDateString(dDate2 - timedelta(hours=iHourCount))
if not self.addToDevice(oDevice, iDConsumption1, iDConsumption2, iDProduction1, iDProduction2, sShortDate):