-
Notifications
You must be signed in to change notification settings - Fork 3
/
veolia-idf-domoticz.py
executable file
·1465 lines (1294 loc) · 50.7 KB
/
veolia-idf-domoticz.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
#!/usr/bin/env python3
"""
@author: s0nik42
"""
# veolia-idf
# Copyright (C) 2019 Julien NOEL
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
################################################################################
# SCRIPT DEPENDENCIES
################################################################################
import sys
import os
import signal
import time
import csv
import json
import logging
import argparse
import base64
import re
import subprocess
from datetime import datetime
from logging.handlers import RotatingFileHandler
from urllib.parse import urlencode
from shutil import which
VERSION = "v1.3"
try:
# Only add packages that are not built-in here
import requests
import urllib3
from colorama import Fore, Style
from pyvirtualdisplay import Display, xauth
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
except ImportError as exc:
print(
"Error: failed to import python required module : " + str(exc),
file=sys.stderr,
)
sys.exit(2)
################################################################################
# Output Class in charge of managing all script output to file or console
################################################################################
class Output:
def __init__(self, logs_folder=None, debug=False):
self.__debug = debug
self.__logger = logging.getLogger()
self.__print_buffer = ""
logs_folder = (
os.path.dirname(os.path.realpath(__file__))
if logs_folder is None
else logs_folder
)
logfile = logs_folder + "/veolia.log"
# By default log to console
self.print = self.__print_to_console
# In standard mode log to a file
if self.__debug is False:
# Check if we can create logfile
try:
open(logfile, "a+", encoding="utf_8").close()
except Exception as e:
raise RuntimeError('"%s" %s' % (logfile, e,))
# Set the logfile format
file_handler = RotatingFileHandler(logfile, "a", 1000000, 1)
formatter = logging.Formatter("%(asctime)s : %(message)s")
file_handler.setFormatter(formatter)
self.__logger.setLevel(logging.INFO)
self.__logger.addHandler(file_handler)
self.print = self.__print_to_logfile
def __print_to_console(self, string="", st=None, end=None):
if st:
st = st.upper()
st = st.replace("OK", Fore.GREEN + "OK")
st = st.replace("WW", Fore.YELLOW + "WW")
st = st.replace("EE", Fore.RED + "EE")
st = "[" + st + Style.RESET_ALL + "] "
if end is not None:
st = st + " " if st else ""
print(st + "%-75s" % (string,), end="", flush=True)
self.__print_buffer = self.__print_buffer + string
elif self.__print_buffer:
st = st if st else "[--] "
print(st + string.rstrip())
self.__print_buffer = ""
else:
st = st if st else "[--]"
print(("{:75s}" + st).format(string.rstrip()))
self.__print_buffer = ""
def __print_to_logfile(self, string="", st=None, end=None):
if end is not None:
self.__print_buffer = self.__print_buffer + string
else:
st = st if st else "--"
self.__logger.info(
"%s : %s %s",
st.upper().lstrip(),
self.__print_buffer.lstrip().rstrip(),
string.lstrip().rstrip()
)
self.__print_buffer = ""
def document_initialised(driver):
return driver.execute_script("return true;")
################################################################################
# Configuration Class toparse and load config.json
################################################################################
class Configuration:
def __init__(self, super_print=None, debug=False):
self.__debug = debug
# Supersede local print function if provided as an argument
self.print = super_print if super_print else self.print # type:ignore[assignment]
def load_configuration_file(self, configuration_file):
self.print(
"Loading configuration file : " + configuration_file, end=""
) #############################################################
try:
with open(configuration_file, encoding="utf_8") as conf_file:
content = json.load(conf_file)
except json.JSONDecodeError as e:
raise RuntimeError("json format error : " + str(e))
except Exception:
raise
else:
self.print(st="OK")
return content
def print(self, string="", st=None, end=None):
st = "[" + st + "] " if st else ""
if end is None:
print(st + string)
else:
print(st + string + " ", end="", flush="True") # type:ignore[call-overload]
################################################################################
# Object that retrieve the historical data from Veolia website
################################################################################
class VeoliaCrawler:
site_url = "https://espace-client.vedif.eau.veolia.fr/s/login/"
download_filename = "historique_jours_litres.csv"
def __init__(self, config_dict, super_print=None, debug=False):
self.__debug = debug
# Supersede local print function if provided as an argument
self.print = super_print if super_print else self.print # type:ignore[has-type]
self.__display = None
self.__browser = None # type: webdriver.Firefox
self.__wait = None # type: WebDriverWait
install_dir = os.path.dirname(os.path.realpath(__file__))
self.configuration = {
# Mandatory config values
"veolia_login": None,
"veolia_password": None,
"veolia_contract": None,
# Optional config values
"geckodriver": which("geckodriver")
if which("geckodriver")
else install_dir + "/geckodriver",
"firefox": which("firefox")
if which("firefox")
else install_dir + "/firefox",
"chromium": which("chromium")
if which("chromium")
else which("chromium-browser") if which("chromium-browser")
else install_dir + "/chromium",
"chromedriver": which("chromedriver")
if which("chromedriver")
else install_dir + "/chromedriver",
"timeout": "30",
"download_folder": install_dir + os.path.sep,
"logs_folder": install_dir + os.path.sep,
}
self.print("Start loading veolia configuration")
try:
self._load_configururation_items(config_dict)
self.print("End loading veolia configuration", end="")
except Exception:
raise
else:
self.print(st="ok")
self.__full_path_download_file = (
str(self.configuration["download_folder"]) + self.download_filename
)
# Load configuration items
def _load_configururation_items(self, config_dict):
for param in list((self.configuration).keys()):
if param not in config_dict:
if self.configuration[param] is not None:
self.print(
' "'
+ param
+ '" = "'
+ str(self.configuration[param])
+ '"',
end="",
)
self.print(
"param is not found in config file, using default value",
"WW",
)
else:
self.print(' "' + param + '"', end="")
raise RuntimeError(
"param is missing in configuration file"
)
else:
if (
param in ("download_folder", "logs_folder",)
) and config_dict[param][-1] != os.path.sep:
self.configuration[param] = (
str(config_dict[param]) + os.path.sep
)
else:
self.configuration[param] = config_dict[param]
if param == "veolia_password":
self.print(
' "'
+ param
+ '" = "'
+ "*" * len(str(self.configuration[param]))
+ '"',
end="",
)
else:
self.print(
' "'
+ param
+ '" = "'
+ str(self.configuration[param])
+ '"',
end="",
)
self.print(st="OK")
# INIT DISPLAY & BROWSER
def init_browser_firefox(self):
self.print(
"Start virtual display", end=""
) #############################################################
# veolia website needs at least 1600x1200 to render all components
if self.__debug:
self.__display = Display(visible=1, size=(1600, 1200))
else:
self.__display = Display(visible=0, size=(1600, 1200))
try:
self.__display.start()
except Exception as e:
raise RuntimeError(
str(e)
+ "if you launch the script through a ssh connection with '--debug' ensure X11 forwarding is activated"
)
else:
self.print(st="OK")
self.print(
"Setup Firefox profile", end=""
) #############################################################
try:
# Enable Download
opts = webdriver.FirefoxOptions()
fp = webdriver.FirefoxProfile()
opts.profile = fp
fp.set_preference(
"browser.download.dir", self.configuration["download_folder"]
)
fp.set_preference("browser.download.folderList", 2)
fp.set_preference(
"browser.helperApps.neverAsk.saveToDisk", "text/csv"
)
fp.set_preference(
"browser.download.manager.showWhenStarting", False
)
fp.set_preference(
"browser.helperApps.neverAsk.openFile", "text/csv"
)
fp.set_preference("browser.helperApps.alwaysAsk.force", False)
# Set firefox binary to use
opts.binary_location = FirefoxBinary(str(self.configuration["firefox"]))
service = FirefoxService(self.configuration["geckodriver"])
if not hasattr(service, 'process'):
# Webdriver may complain about missing process.
service.process = None
# Enable the browser
try:
self.__browser = webdriver.Firefox(
options=opts,
service_log_path=str(self.configuration["logs_folder"])
+ "/geckodriver.log",
service=service,
)
except Exception as e:
raise RuntimeError(
str(e)
+ "if you launch the script through a ssh connection with '--debug' ensure X11 forwarding is activated, and you have a working X environment. debug mode start Firefox and show all clicks over the website"
)
except Exception:
raise
else:
self.print(st="ok")
self.print(
"Start Firefox", end=""
) #############################################################
try:
# self.__browser.maximize_window()
# replacing maximize_window by set_window_size to get the window full screen
self.__browser.set_window_size(1600, 1200)
timeout = int(self.configuration["timeout"]) # type: ignore[arg-type]
self.__wait = WebDriverWait(
self.__browser, timeout=timeout
)
except Exception:
raise
else:
self.print(st="OK")
def init_browser_chrome(self):
# Set Chrome options
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-modal-animations")
options.add_argument("--disable-login-animations")
options.add_argument("--disable-renderer-backgrounding")
options.add_argument("--disable-background-timer-throttling")
options.add_argument("--disable-backgrounding-occluded-wndows")
options.add_argument("--disable-translate")
options.add_argument("--disable-popup-blocking")
options.add_experimental_option(
"prefs",
{
"download.default_directory": self.configuration[
"download_folder"
],
"profile.default_content_settings.popups": 0,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"extensions_to_open": "text/csv",
"safebrowsing.enabled": True,
},
)
self.print(
"Start virtual display (chromium)", end=""
) #############################################################
if self.__debug:
self.__display = Display(visible=1, size=(1280, 1024))
else:
options.add_argument("--headless")
options.add_argument("--disable-gpu")
try:
self.__display = Display(visible=0, size=(1280, 1024))
except Exception:
raise
try:
self.__display.start()
except Exception:
raise
else:
self.print(st="OK")
self.print(
"Start the browser", end=""
) #############################################################
try:
self.__browser = webdriver.Chrome(
executable_path=self.configuration["chromedriver"],
options=options,
)
self.__browser.maximize_window()
timeout = int(self.configuration["timeout"]) # type: ignore[arg-type]
self.__wait = WebDriverWait(
self.__browser, timeout
)
except Exception:
raise
else:
self.print(st="OK")
def sanity_check(self, debug=False): # pylint: disable=unused-argument
self.print(
"Check download location integrity", end=""
) #############################################################
if os.path.exists(self.__full_path_download_file):
self.print(
self.__full_path_download_file
+ " already exists, will be removed",
"WW",
)
else:
try:
open(self.__full_path_download_file, "a+", encoding="utf_8").close()
except Exception as e:
raise RuntimeError(
'"%s" %s' % (self.__full_path_download_file, e,)
)
else:
self.print(st="ok")
#############################################################
try:
self.print( "Remove temporary download file", end="")
os.remove(self.__full_path_download_file)
except Exception:
raise
else:
self.print(st="ok")
self.print(
'Check availability of "geckodriver"+"firefox" or "chromedriver"+"chromium"', end=""
) #############################################################
if ( os.access(str(self.configuration["geckodriver"]), os.X_OK) and
os.access(str(self.configuration["firefox"]), os.X_OK)):
self.print(st="ok")
self.print(
"Check firefox browser version", end=""
) #############################################################
try:
major, minor = self.__get_firefox_version()
except Exception:
raise
else:
if (major, minor) < (60, 9):
self.print(
"Firefox version ("
+ str(major)
+ "."
+ str(minor)
+ " is too old (< 60.9) script may fail",
st="WW",
)
else:
self.print(st="ok")
elif (os.access(str(self.configuration["chromedriver"]), os.X_OK) and
os.access(str(self.configuration["chromium"]), os.X_OK)):
self.print(st="ok")
else:
raise OSError(
'"%s"/"%s" or "%s"/"%s": no valid pair of executables found' % (
self.configuration["geckodriver"],
self.configuration["firefox"],
self.configuration["chromedriver"],
self.configuration["chromium"],
)
)
def __get_firefox_version(self):
try:
output = subprocess.check_output(
[str(self.configuration["firefox"]), "--version"]
)
except Exception:
raise
try:
major, minor = map(
int, re.search(r"(\d+).(\d+)", str(output)).groups() # type:ignore[union-attr]
)
except Exception:
raise
return major, minor
def clean_up(self, debug=False, keep_csv=False):
self.print(
"Close Browser", end=""
) #############################################################
if self.__browser:
try:
self.__browser.quit()
except Exception as _e:
os.kill(self.__browser.service.process.pid, signal.SIGTERM)
self.print(
"selenium didn't properly close the process, so we kill firefox manually (pid="
+ str(self.__browser.service.process.pid)
+ ")",
"WW",
)
else:
self.print(st="OK")
else:
self.print(st="OK")
self.print(
"Close Display", end=""
) #############################################################
if self.__display:
try:
self.__display.stop()
except:
raise
else:
self.print(st="ok")
# Remove downloaded file
try:
if not debug and not keep_csv and os.path.exists(self.__full_path_download_file):
#############################################################
# Remove file
self.print( "Remove downloaded file " + self.download_filename, end="")
os.remove(self.__full_path_download_file)
else:
self.print(st="ok")
except Exception as e:
self.print(str(e), st="EE")
def wait_until_disappeared(self, method, key, wait_message=None):
"""Wait until element is gone"""
if wait_message is None:
wait_message = "Wait for missing %s" % (key,)
self.print(wait_message, end="")
ep = EC.visibility_of_element_located(
(
method,
key,
)
)
timeout_message = "Failed, page timeout (timeout=%s)" % (
str(self.configuration["timeout"]),
)
self.__wait.until_not(ep, message=timeout_message)
self.print(st="ok")
def click_in_view( # pylint: disable=R0913
self, method, key, click_message=None, wait_message=None, delay=0
):
"""
1. Wait until element is visible
2. Wait for delay.
3. Bring into view (location may have changed)
4. Click
"""
# Wait until element is visible
ep = EC.visibility_of_element_located(
(
method,
key,
)
)
if wait_message is None:
wait_message = "Wait for Button %s" % (key,)
self.print(wait_message, end="")
timeout_message = "Failed, page timeout (timeout=%s)" % (
str(self.configuration["timeout"]),
)
el = self.__wait.until(ep, message=timeout_message)
self.print(st="ok")
if delay != 0.0:
self.print("Wait before clicking (%.1fs)" % (delay,), end="")
self.print(st="~~")
time.sleep(delay)
# Bring the element into view
el.location_once_scrolled_into_view
# Click
if click_message is None:
click_message = "Click on %s" % (key,)
self.print(click_message, end="")
try:
el.click()
except Exception:
raise
else:
self.print(st="ok")
def get_file(self):
###### Wait for Connexion #####
self.print("Connexion au site Veolia Eau Ile de France", end="")
self.__browser.get(self.__class__.site_url)
self.print(st="ok")
###### Wait for Password #####
self.print("Waiting for Password", end="")
ep = EC.presence_of_element_located(
(By.CSS_SELECTOR, 'input[type="password"]')
)
el_password = self.__wait.until(
ep,
message="failed, page timeout (timeout="
+ str(self.configuration["timeout"])
+ ")",
)
self.print(st="ok")
###### Wait for Email #####
self.print("Waiting for Email", end="")
self.__wait.until(document_initialised)
ep = EC.presence_of_element_located(
(By.XPATH, r"//input[@inputmode='email']")
)
el_email = self.__wait.until(
ep,
message="failed, page timeout (timeout="
+ str(self.configuration["timeout"])
+ ")",
)
self.print(st="ok")
###### Type Email #####
self.print("Type Email", end="")
el_email.clear()
el_email.send_keys(self.configuration["veolia_login"])
self.print(st="ok")
###### Type Password #####
self.print("Type Password", end="")
el_password.send_keys(self.configuration["veolia_password"])
self.print(st="ok")
###### Click Submit #####
self.click_in_view(
By.CLASS_NAME,
"submit-button",
wait_message="Waiting for submit button",
click_message="Click on submit button",
delay=1,
)
time.sleep(10)
###### Wait until spinner is gone #####
self.wait_until_disappeared(By.CSS_SELECTOR, "lightning-spinner")
time.sleep(1)
### COMPORTEMENT DIFFERENT S'IL S AGIT D'UN MULTU CONTRATS
### OU D'UN CONTRAT UNIQUE (CLICK DIRECTEMENT SUR HISTORIQUE)
self.print("Wait for MENU contrats or historique", end="")
ep = EC.visibility_of_element_located(
(
By.XPATH,
"//span[contains(text(), 'CONTRATS') or contains(text(), 'HISTORIQUE')]",
)
)
el = self.__wait.until(
ep,
message="failed, page timeout (timeout="
+ str(self.configuration["timeout"])
+ ")",
)
self.print(st="ok")
time.sleep(2)
menu_type = str(el.get_attribute("innerHTML"))
###### Click on Menu #####
self.print("Click on menu : " + menu_type, end="")
el.click()
self.print(st="ok")
# GESTION DU PARCOURS MULTICONTRATS
if menu_type == "CONTRATS":
time.sleep(2)
self.click_in_view(
By.LINK_TEXT,
str(self.configuration["veolia_contract"]),
wait_message="Select contract : %s"
% (str(self.configuration["veolia_contract"]),),
click_message="Click on contract",
delay=0,
)
time.sleep(2)
###### Click Historique #####
self.click_in_view(
By.LINK_TEXT,
"Historique",
wait_message="Wait for historique menu",
click_message="Click on historique menu",
delay=4,
)
time.sleep(10)
###### Click Litres #####
self.click_in_view(
By.XPATH,
"//span[contains(text(), 'Litres')]/parent::node()",
wait_message="Wait for button Litres",
click_message="Click on button Litres",
delay=2,
)
time.sleep(2)
###### Click Jours #####
self.click_in_view(
By.XPATH,
"//span[contains(text(), 'Jours')]/parent::node()",
wait_message="Wait for button Jours",
click_message="Click on button Jours",
delay=2,
)
###### Click Telechargement #####
self.click_in_view(
By.XPATH,
'//button[contains(text(),"charger la p")]',
wait_message="Wait for button Telechargement",
click_message="Click on button Telechargement",
delay=10,
)
self.print(
"Wait for end of download to " + self.__full_path_download_file,
end="",
) #############################################################
t = int(str(self.configuration["timeout"]))
while t > 0 and not os.path.exists(self.__full_path_download_file):
time.sleep(1)
t -= 1
if os.path.exists(self.__full_path_download_file):
self.print(st="ok")
else:
try:
error_img = "%serror.png" % (
self.configuration["logs_folder"],
)
self.print("Get & Save '%s'" % (error_img,), end="")
# img = self.__display.waitgrab()
self.__browser.get_screenshot_as_file(error_img)
except Exception as e:
self.print("Exception while getting image: %s" % (e,), end="")
raise RuntimeError("File download timeout")
return self.__full_path_download_file
################################################################################
# Object injects historical data into domoticz
################################################################################
class DomoticzInjector:
def __init__(self, config_dict, super_print, debug=False):
self.__debug = debug
# Supersede local print function if provided as an argument
self.print = super_print if super_print else self.print # type:ignore[has-type]
self.configuration = {
# Mandatory config values
"domoticz_idx": None,
"domoticz_server": None,
# Optional config values
"domoticz_login": "",
"domoticz_password": "",
"timeout": "30",
"download_folder": os.path.dirname(os.path.realpath(__file__))
+ os.path.sep,
}
self.print("Start Loading Domoticz configuration")
try:
self._load_configururation_items(config_dict)
self.print("End loading domoticz configuration", end="")
except Exception:
raise
else:
self.print(st="ok")
self.__http = urllib3.PoolManager(
retries=1, timeout=int(str(self.configuration["timeout"]))
)
self.headers = urllib3.make_headers()
def open_url(self, uri, data=None): # pylint: disable=unused-argument
# Generate URL
url_test = str(self.configuration["domoticz_server"]) + uri
if self.configuration["domoticz_login"] != "" and self.configuration["domoticz_password"] != "":
http_auth = ':'.join((self.configuration["domoticz_login"] , self.configuration["domoticz_password"] ))
self.headers.update(urllib3.make_headers(basic_auth=http_auth))
try:
response = self.__http.request("GET", url_test, headers=self.headers)
except urllib3.exceptions.MaxRetryError as e:
# HANDLE CONNECTIVITY ERROR
raise RuntimeError("url=" + url_test + " : " + str(e))
# HANDLE SERVER ERROR CODE
if not response.status == 200:
raise RuntimeError(
"url="
+ url_test
+ " - (code = "
+ str(response.status)
+ ")\ncontent="
+ str(response.data)
)
try:
j = json.loads(response.data.decode("utf-8"))
except Exception as e:
# Handle JSON ERROR
raise RuntimeError("unable to parse the JSON : " + str(e))
if j["status"].lower() != "ok":
raise RuntimeError(
"url="
+ url_test
+ "\nrepsonse="
+ str(response.status)
+ "\ncontent="
+ str(j)
)
return j
# Load configuration items
def _load_configururation_items(self, config_dict):
for param in list((self.configuration).keys()):
if param not in config_dict:
if self.configuration[param] is not None:
self.print(
' "%s" = "%s"' % (
param,
self.configuration[param],
),
end="",
)
self.print(
"param is not found in config file, using default value",
"WW",
)
else:
self.print(' "' + param + '"', end="")
raise RuntimeError(
"param is missing in configuration file"
)
else:
if (
param == "download_folder"
and str(config_dict[param])[-1] != os.path.sep
):
self.configuration[param] = (
str(config_dict[param]) + os.path.sep
)
else:
self.configuration[param] = config_dict[param]
if re.match(r".*(token|password).*", param, re.IGNORECASE):
self.print(
' "'
+ param
+ '" = "'
+ "*" * len(str(self.configuration[param]))
+ '"',
end="",
)
else:
self.print(
' "'
+ param
+ '" = "'
+ str(self.configuration[param])
+ '"',
end="",
)
self.print(st="OK")
def sanity_check(self, debug=False): # pylint: disable=unused-argument
self.print(
"Check domoticz connectivity", st="--", end=""
) #############################################################
response = self.open_url("/json.htm?type=command¶m=getversion")
if response["status"].lower() == "ok":
self.print(st="ok")
self.print(
"Check domoticz Device", end=""
) #############################################################
# generate 2 urls, one for historique, one for update
response = self.open_url(
"/json.htm?type=devices&rid=" + str(self.configuration["domoticz_idx"])
)
if not "result" in response:
raise RuntimeError(
"device "
+ str(self.configuration["domoticz_idx"])
+ " could not be found on domoticz server "
+ str(self.configuration["domoticz_server"])
)
else:
properly_configured = True
dev_AddjValue = response["result"][0]["AddjValue"]
dev_AddjValue2 = response["result"][0]["AddjValue2"]
dev_SubType = response["result"][0]["SubType"]
dev_Type = response["result"][0]["Type"]
dev_SwitchTypeVal = response["result"][0]["SwitchTypeVal"]
dev_Name = response["result"][0]["Name"]
self.print(st="ok")
# Retrieve Device Name
self.print(
' Device Name : "'
+ dev_Name
+ '" (idx='
+ self.configuration["domoticz_idx"]
+ ")",
end="",
) #############################################################
self.print(st="ok")
# Checking Device Type
self.print(
' Device Type : "' + dev_Type + '"', end=""
) #############################################################
if dev_Type == "General":
self.print(st="ok")
else:
self.print(
'wrong sensor type. Go to Domoticz/Hardware - Create a pseudo-sensor type "Managed Counter"',
st="EE",
)
properly_configured = False
# Checking device subtype
self.print(
' Device SubType : "' + dev_SubType + '"', end=""
) #############################################################
if dev_SubType == "Managed Counter":
self.print(st="ok")
else:
self.print(
'wrong sensor type. Go to Domoticz/Hardware - Create a pseudo-sensor type "Managed Counter"',
st="ee",
)
properly_configured = False
# Checking for SwitchType
self.print(
' Device SwitchType : "' + str(dev_SwitchTypeVal),