-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththermostat.py
2090 lines (1669 loc) · 84.5 KB
/
thermostat.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
# coding: latin-1
### BEGIN LICENSE
# Copyright (c) 2016 Jpnos <[email protected]>
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
### END LICENSE
##############################################################################
# #
# Core Imports #
# #
##############################################################################
import threading
import math
import os, os.path, sys
import time
import datetime
import urllib2
import json
import random
import socket
import re
import locale
locale.setlocale(locale.LC_ALL, '')
##############################################################################
# #
# Kivy UI Imports #
# #
##############################################################################
import kivy
kivy.require( '1.10.0' ) # replace with your current kivy version !
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.uix.slider import Slider
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle
from kivy.storage.jsonstore import JsonStore
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.garden.knob import Knob
##############################################################################
# #
# Other Imports #
# #
##############################################################################
import cherrypy
import schedule
import struct
##############################################################################
# #
# GPIO & Simulation Imports #
# #
##############################################################################
try:
import RPi.GPIO as GPIO
except ImportError:
import FakeRPi.GPIO as GPIO
##############################################################################
# #
# Sensor Imports #
# #
##############################################################################
from w1thermsensor import W1ThermSensor
import Adafruit_DHT
##############################################################################
# #
# Utility classes #
# #
##############################################################################
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
##############################################################################
# #
# MySensor.org Controller compatible translated constants #
# #
##############################################################################
MSG_TYPE_SET = "set"
MSG_TYPE_PRESENTATION = "presentation"
CHILD_DEVICE_NODE = "node"
CHILD_DEVICE_UICONTROL_HEAT = "heatControl"
CHILD_DEVICE_UICONTROL_FAN = "fanControl"
CHILD_DEVICE_UICONTROL_HOLD = "holdControl"
CHILD_DEVICE_UICONTROL_TPLUS = "tempPlus"
CHILD_DEVICE_UICONTROL_SLIDER = "tempSlider"
CHILD_DEVICE_WEATHER_FCAST_TODAY = "weatherForecastToday"
CHILD_DEVICE_WEATHER_FCAST_TOMO = "weatherForecastTomorrow"
CHILD_DEVICE_WEATHER_CURR = "weatherCurrent"
CHILD_DEVICE_HEAT = "heat"
CHILD_DEVICE_FAN = "fan"
CHILD_DEVICE_PIR = "motionSensor"
CHILD_DEVICE_TEMP = "temperatureSensor"
CHILD_DEVICE_SCREEN = "screen"
CHILD_DEVICE_SCHEDULER = "scheduler"
CHILD_DEVICE_WEBSERVER = "webserver"
CHILD_DEVICES = [
CHILD_DEVICE_NODE,
CHILD_DEVICE_UICONTROL_HEAT,
CHILD_DEVICE_UICONTROL_FAN,
CHILD_DEVICE_UICONTROL_HOLD,
CHILD_DEVICE_UICONTROL_SLIDER,
CHILD_DEVICE_WEATHER_CURR,
CHILD_DEVICE_WEATHER_FCAST_TODAY,
CHILD_DEVICE_WEATHER_FCAST_TOMO,
CHILD_DEVICE_HEAT,
CHILD_DEVICE_FAN,
CHILD_DEVICE_PIR,
CHILD_DEVICE_TEMP,
CHILD_DEVICE_SCREEN,
CHILD_DEVICE_SCHEDULER,
CHILD_DEVICE_WEBSERVER
]
CHILD_DEVICE_SUFFIX_UICONTROL = "Control"
MSG_SUBTYPE_NAME = "sketchName"
MSG_SUBTYPE_VERSION = "sketchVersion"
MSG_SUBTYPE_BINARY_STATUS = "binaryStatus"
MSG_SUBTYPE_TRIPPED = "armed"
MSG_SUBTYPE_ARMED = "tripped"
MSG_SUBTYPE_TEMPERATURE = "temperature"
MSG_SUBTYPE_FORECAST = "forecast"
MSG_SUBTYPE_CUSTOM = "custom"
MSG_SUBTYPE_TEXT = "text"
##############################################################################
# #
# Settings #
# #
##############################################################################
THERMOSTAT_VERSION = "3.0.1"
# Debug settings
debug = False
useTestSchedule = False
# Threading Locks
thermostatLock = threading.RLock()
weatherLock = threading.Lock()
scheduleLock = threading.RLock()
# Thermostat persistent settings
settings = JsonStore( "./setting/thermostat_settings.json" )
state = JsonStore( "./setting/thermostat_state.json" )
actual = JsonStore( "./setting/thermostat_actual.json")
#graphics
# Logging settings/setup
LOG_FILE_NAME = "./log/thermostat.log"
LOG_ALWAYS_TIMESTAMP = True
LOG_LEVEL_DEBUG = 1
LOG_LEVEL_INFO = 2
LOG_LEVEL_ERROR = 3
LOG_LEVEL_STATE = 4
LOG_LEVEL_NONE = 5
LOG_LEVELS = {
"debug": LOG_LEVEL_DEBUG,
"info": LOG_LEVEL_INFO,
"state": LOG_LEVEL_STATE,
"error": LOG_LEVEL_ERROR
}
LOG_LEVELS_STR = { v: k for k, v in LOG_LEVELS.items() }
logFile = None
def log_dummy( level, child_device, msg_subtype, msg, msg_type=MSG_TYPE_SET, timestamp=True, single=False ):
pass
def log_file( level, child_device, msg_subtype, msg, msg_type=MSG_TYPE_SET, timestamp=True, single=False ):
if level >= logLevel:
ts = datetime.datetime.now().strftime( "%Y-%m-%dT%H:%M:%S%z " )
logFile.write( ts + LOG_LEVELS_STR[ level ] + "/" + child_device + "/" + msg_type + "/" + msg_subtype + ": " + msg + "\n" )
def log_print( level, child_device, msg_subtype, msg, msg_type=MSG_TYPE_SET, timestamp=True, single=False ):
if level >= logLevel:
ts = datetime.datetime.now().strftime( "%Y-%m-%dT%H:%M:%S%z " ) if LOG_ALWAYS_TIMESTAMP or timestamp else ""
print( ts + LOG_LEVELS_STR[ level ] + "/" + child_device + "/" + msg_type + "/" + msg_subtype + ": " + msg )
loggingChannel = "none" if not( settings.exists( "logging" ) ) else settings.get( "logging" )[ "channel" ]
loggingLevel = "state" if not( settings.exists( "logging" ) ) else settings.get( "logging" )[ "level" ]
for case in switch( loggingChannel ):
if case( 'none' ):
log = log_dummy
break
if case( 'file' ):
log = log_file
logFile = open( LOG_FILE_NAME, "a", 0 )
break
if case( 'print' ):
log = log_print
break
if case(): # default
log = log_dummy
logLevel = LOG_LEVELS.get( loggingLevel, LOG_LEVEL_NONE )
# Send presentations for Node
log( LOG_LEVEL_STATE, CHILD_DEVICE_NODE, MSG_SUBTYPE_NAME, "Thermostat Starting Up...", msg_type=MSG_TYPE_PRESENTATION )
log( LOG_LEVEL_STATE, CHILD_DEVICE_NODE, MSG_SUBTYPE_VERSION, THERMOSTAT_VERSION, msg_type=MSG_TYPE_PRESENTATION )
#send presentations for all other child "sensors"
for i in range( len( CHILD_DEVICES ) ):
child = CHILD_DEVICES[ i ]
if child != CHILD_DEVICE_NODE:
log( LOG_LEVEL_STATE, child, child, "", msg_type=MSG_TYPE_PRESENTATION )
# Various temperature settings:
tempScale = settings.get( "scale" )[ "tempScale" ]
scaleUnits = u"\xb0" if tempScale == "metric" else "f"
precipUnits = " mm" if tempScale == "metric" else '"'
precipFactor = 1.0 if tempScale == "metric" else 0.0393701
precipRound = 1 if tempScale == "metric" else 1
sensorUnits = W1ThermSensor.DEGREES_C if tempScale == "metric" else W1ThermSensor.DEGREES_F
windFactor = 3.6 if tempScale == "metric" else 1.0
windUnits = " km/h" if tempScale == "metric" else " mph"
TEMP_TOLERANCE = 0.1 if tempScale == "metric" else 0.18
currentTemp = 20.0 if tempScale == "metric" else 72.0
outside_temp = 20.0 if tempScale == "metric" else 72.0
water_temp = 20.0 if tempScale == "metric" else 72.0
priorCorrected = -100.0
# openDoor e openDoorcheck for stop sistem for a time set in thermostat_setting and temperature change quickly of 1 C degrees
openDoor = 21 if not( state.exists( "thermostat" ) ) else int((state.get( "thermostat" )[ "openDoor" ]/state.get( "thermostat" )[ "tempCheckInterval" ])+1)
openDoorCheck = 20 if not( state.exists( "thermostat" ) ) else int(state.get( "thermostat" )[ "openDoor" ]/state.get( "thermostat" )[ "tempCheckInterval" ])
measure_count = 0
setTemp = 22.0 if not( state.exists( "state" ) ) else state.get( "state" )[ "setTemp" ]
setice = 15.0 if not(settings.exists ( "thermostat")) else settings.get("thermostat")["tempice"]
tempHysteresis = 0.5 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "tempHysteresis" ]
tempCheckInterval = 3 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "tempCheckInterval" ]
out_temp = 0.0
temp_vis = 0
minUIEnabled = 0 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "minUIEnabled" ]
minUITimeout = 20 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "minUITimeout" ]
lightOff = 60 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "lightOff" ]
minUITimer = None
csvSaver = None
lightOffTimer = None
csvTimeout = 300 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "saveCsv" ]
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/tempScale", str( tempScale ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/scaleUnits", scaleUnits, timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/precipUnits", str( precipUnits ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/precipFactor", str( precipFactor ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/sensorUnits", str( sensorUnits ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/windFactor", str( windFactor ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/windUnits", str( windUnits ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/currentTemp", str( currentTemp ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/setTemp", str( setTemp ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/tempHysteresis", str( tempHysteresis ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/tempCheckInterval", str( tempCheckInterval ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/minUIEnabled", str( minUIEnabled ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/minUITimeout", str( minUITimeout ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/temperature/lightOff", str( lightOff ), timestamp=False )
# Temperature calibration settings:
elevation = 0 if not( settings.exists( "thermostat" ) ) else settings.get( "calibration" )[ "elevation" ]
boilingPoint = ( 100.0 - 0.003353 * elevation ) if tempScale == "metric" else ( 212.0 - 0.00184 * elevation )
freezingPoint = 0.01 if tempScale == "metric" else 32.018
referenceRange = boilingPoint - freezingPoint
correctSensor = 0 if not( settings.exists( "thermostat" ) ) else settings.get( "calibration" )[ "correctSensor" ]
boilingMeasured = settings.get( "calibration" )[ "boilingMeasured" ]
freezingMeasured = settings.get( "calibration" )[ "freezingMeasured" ]
measuredRange = boilingMeasured - freezingMeasured
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/calibration/elevation", str( elevation ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/calibration/boilingPoint", str( boilingPoint ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/calibration/freezingPoint", str( freezingPoint ), timestamp=False )
log( LOG_LEVEL_DEBUG, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/calibration/referenceRange", str( referenceRange ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/calibration/boilingMeasured", str( boilingMeasured ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/calibration/freezingMeasured", str( freezingMeasured ), timestamp=False )
log( LOG_LEVEL_DEBUG, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/calibration/measuredRange", str( measuredRange ), timestamp=False )
# UI Slider settings:
minTemp = 15.0 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "minTemp" ]
maxTemp = 30.0 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "maxTemp" ]
tempStep = 0.5 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "tempStep" ]
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/UISlider/minTemp", str( minTemp ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/UISlider/maxTemp", str( maxTemp ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/UISlider/tempStep", str( tempStep ), timestamp=False )
try:
tempSensor = W1ThermSensor()
print("tempsensor ON")
except:
tempSensor = None
print("tempsensor OFF")
# PIR (Motion Sensor) setup:
pirEnabled = 0 if not( settings.exists( "pir" ) ) else settings.get( "pir" )[ "pirEnabled" ]
pirPin = 5 if not( settings.exists( "pir" ) ) else settings.get( "pir" )[ "pirPin" ]
pirCheckInterval = 0.5 if not( settings.exists( "pir" ) ) else settings.get( "pir" )[ "pirCheckInterval" ]
pirIgnoreFromStr = "00:00" if not( settings.exists( "pir" ) ) else settings.get( "pir" )[ "pirIgnoreFrom" ]
pirIgnoreToStr = "00:00" if not( settings.exists( "pir" ) ) else settings.get( "pir" )[ "pirIgnoreTo" ]
pirIgnoreFrom = datetime.time( int( pirIgnoreFromStr.split( ":" )[ 0 ] ), int( pirIgnoreFromStr.split( ":" )[ 1 ] ) )
pirIgnoreTo = datetime.time( int( pirIgnoreToStr.split( ":" )[ 0 ] ), int( pirIgnoreToStr.split( ":" )[ 1 ] ) )
log( LOG_LEVEL_INFO, CHILD_DEVICE_PIR, MSG_SUBTYPE_ARMED, str( pirEnabled ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/pir/checkInterval", str( pirCheckInterval ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/pir/ignoreFrom", str( pirIgnoreFromStr ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/pir/ignoreTo", str( pirIgnoreToStr ), timestamp=False )
# GPIO Pin setup and utility routines:
heatPin = 27 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "heatPin" ]
fanPin = 25 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "fanPin" ]
lightPin = 24 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "lightPin" ]
extprobePin = 22 if not( settings.exists( "thermostat" ) ) else settings.get( "thermostat" )[ "extprobePin" ] #Rele Byp Sonda esterna IN2
GPIO.setmode( GPIO.BCM )
GPIO.setup( heatPin, GPIO.OUT )
GPIO.output( heatPin, GPIO.HIGH )
GPIO.setup( extprobePin, GPIO.OUT )
GPIO.output( extprobePin, GPIO.HIGH )
GPIO.setup( fanPin, GPIO.OUT )
GPIO.output( fanPin, GPIO.HIGH )
GPIO.setup( lightPin, GPIO.OUT )
GPIO.output( lightPin, GPIO.HIGH )
if pirEnabled:
GPIO.setup( pirPin, GPIO.IN )
CHILD_DEVICE_HEAT = "heat"
CHILD_DEVICE_FAN = "fan"
log( LOG_LEVEL_INFO, CHILD_DEVICE_HEAT, MSG_SUBTYPE_BINARY_STATUS, str( heatPin ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_FAN, MSG_SUBTYPE_BINARY_STATUS, str( fanPin ), timestamp=False )
log( LOG_LEVEL_INFO, CHILD_DEVICE_PIR, MSG_SUBTYPE_TRIPPED, str( pirPin ), timestamp=False )
##############################################################################
# #
# dht22 esp8266 external temp connect #
# #
##############################################################################
#dht ext temp setup:
dhtEnabled = 0 if not( settings.exists( "dhtext") ) else settings.get("dhtext" )[ "dhtEnabled" ]
dhtInterval = 2000 if not( settings.exists( "dhtext") ) else settings.get("dhtext" )[ "dhtTimeout" ]
dhtTemp = 0
dhtUm = 0
dht_label = Label( text= " ",size_hint = (None,None), font_size = '25sp', markup=True, text_size= (300,75),color=( 0.5, 0.5, 0.5, 0.2 ))
dhtTest = 0
dhtSchedule = 0
dhtCorrect = 0 if not( settings.exists( "dhtext") ) else settings.get("dhtext" )[ "dhtCorrect" ]
dhtweb = "http://" + settings.get( "dhtext" )[ "dhtClientIP" ] + "/"
def get_dht( url ):
return json.loads( urllib2.urlopen( url, None, 5 ).read() )
def dht_load (dt):
global dhtTemp,dhtEnabled,dhtTest,dhtSchedule
try :
dhtUrl = "http://"+settings.get("dhtext" )[ "dhtClientIP" ]+"/dati"
dhtread = get_dht(dhtUrl )
dhtTemp=dhtread["S_temperature"]
dhtUm=dhtread["S_humidity"]
dht_label.text = "Dht : T: "+str(dhtTemp)+" c , Ur: "+str(dhtUm)+" %"
#dhtEnabled = 1
dhtTest = 0
#if dhtSchedule == 0 :
# dhtSchedule = 1
# reloadSchedule()
except:
dht_label.text = ""
dhtTest += 1
dhtEnabled = 0
dhtSchedule = 0
if dhtTest <= 5:
Clock.schedule_once( dht_load, dhtInterval )
#print "normal ",dhtTest
elif dhtTest >=7 :
Clock.schedule_once(dht_load,120)
#print "blocked ", dhtTest
else:
reloadSchedule()
Clock.schedule_once(dht_load,60)
#print "errato ", dhtTest
def dht_load_wired(dt):
global dhtTemp,dhtEnabled,dhtTest,dhtSchedule
try :
getDhtSensorData()
#dhtTemp=dhtread["S_temperature"]
#dhtUm=dhtread["S_humidity"]
#dht_label.text = "Dht : T: "+str(dhtTemp)+" c , Ur: "+str(dhtUm)+" %"
#dhtEnabled = 1
#dhtTest = 0
#if dhtSchedule == 0 :
# dhtSchedule = 1
# reloadSchedule()
except:
dht_label.text = ""
dhtTest += 1
dhtEnabled = 0
dhtSchedule = 0
print "Exception in dht_load_wired"
if dhtTest <= 5:
Clock.schedule_once( dht_load_wired, dhtInterval )
#print "normal ",dhtTest
elif dhtTest >=7 :
Clock.schedule_once(dht_load_wired,120)
#print "blocked ", dhtTest
else:
reloadSchedule()
Clock.schedule_once(dht_load_wired, 3)
#print "errato ", dhtTest
##############################################################################
# #
# dht22 esp8266 out temp #
# #
##############################################################################
dhtoutEnabled = 0 if not( settings.exists( "dhtout") ) else settings.get("dhtout" )[ "dhtoutEnabled" ]
dhtoutWired = 0 if not( settings.exists( "dhtout") ) else settings.get("dhtout" )[ "dhtoutWired" ]
dhtoutWiredPin = 0 if not( settings.exists( "dhtout") ) else settings.get("dhtout" )[ "dhtoutWiredPin" ]
dhtoutweb = "http://" + settings.get( "dhtout" )[ "dhtoutIP" ] + "/dati"
def dhtoutRead():
global out_temp,out_humidity,dhtoutweb
try:
dhtoutread = get_dht(dhtoutweb)
out_temp=dhtoutread["S_temperature"]
out_humidity=dhtoutread["S_humidity"]
print out_temp,out_humidity
except:
out_temp= 0
out_humidity=0
def getDhtSensorData():
global dhtTemp,dhtEnabled,dhtTest,dhtSchedule,out_temp,in_humidity,dhtUm
in_humidity, out_temp = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, dhtoutWiredPin)
dhtTemp=out_temp
dhtUm=in_humidity
dht_label.text = "Dht : T: "+str(dhtTemp)+" c , Ur: "+str(dhtUm)+" %"
#dhtEnabled = 1
dhtTest = 0
#if dhtSchedule == 0 :
# dhtSchedule = 1
# reloadSchedule()
#out_humidity = str(out_humidity)
#out_temp = str(out_temp)
print out_temp,in_humidity
##############################################################################
# #
# UI Controls/Widgets #
# #
##############################################################################
controlColours = {
"normal": ( 1.0, 1.0, 1.0, 1.0 ),
"Cool": ( 0.0, 0.0, 1.0, 0.4 ),
"Heat": ( 4.0, 0.0, 0.0, 1.0 ),
"Fan": ( 0.0, 1.0, 0.0, 0.4 ),
"Manuale": ( 0.5, 1.0, 0.0, 0.4 ),
}
def setControlState( control, state ):
with thermostatLock:
control.state = state
if state == "normal":
control.background_color = controlColours[ "normal" ]
else:
control.background_color = controlColours[ control.text.replace( "[b]", "" ).replace( "[/b]", "" ) ]
controlLabel = control.text.replace( "[b]", "" ).replace( "[/b]", "" ).lower()
log( LOG_LEVEL_STATE, controlLabel + CHILD_DEVICE_SUFFIX_UICONTROL, MSG_SUBTYPE_BINARY_STATUS, "0" if state == "normal" else "1" )
heatControl = ToggleButton( text="[b]Heat[/b]",
markup=True,
size_hint = ( None, None )
)
setControlState( heatControl, "normal" if not( state.exists( "state" ) ) else state.get( "state" )[ "heatControl" ] )
fanControl = ToggleButton( text="[b]Fan[/b]",
markup=True,
size_hint = ( None, None )
)
setControlState( fanControl, "normal" if not( state.exists( "state" ) ) else state.get( "state" )[ "fanControl" ] )
holdControl = ToggleButton( text="[b]Manuale[/b]",
markup=True,
size_hint = ( None, None )
)
#tempPlus = Button( text="[b]+[/b]", font_size = 24, markup=True, size_hint = ( None, None ) )
tempPlus = Button( text="",
markup=True,
size_hint = ( None, None ),
font_size="30sp",
border = (0,0,0,0),
background_normal= "web/images/plus.png",
background_down = "web/images/plus_1.png",
color = (1,1,1,1)
)
tempMinus = Button( text="",
markup=True,
size_hint = ( None, None ),
font_size="30sp",
border = (0,0,0,0),
background_normal= "web/images/minus.png",
background_down = "web/images/minus_1.png",
color = (1,1,1,1)
)
closeBtn = Button( text=" [b]Chiudi App[/b]",
markup=True,
size_hint = ( None, None ),
font_size="24sp",
border = (0,0,0,0),
background_normal= "web/images/button_1.png",
background_down = "web/images/button_11.png",
color = (1,1,1,1)
)
rebootBtn = Button( text=" [b]Riavvia Sist[/b]",
markup=True,
size_hint = ( None, None ),
font_size="24sp",
border = (0,0,0,0),
background_normal= "web/images/button_1.png",
background_down = "web/images/button_11.png",
color = (1,1,1,1)
)
meteoBtn = Button( text=" [b]Previsioni\n meteo[/b]",
markup=True,
size_hint = ( None, None ),
font_size="18sp",
border = (0,0,0,0),
background_normal= "web/images/button_1.png",
background_down = "web/images/button_11.png",
color = (1,1,1,1)
)
backBtn = Button( text=" [b]Indietro[/b]",
markup=True,
size_hint = ( None, None ),
font_size="30sp",
border = (0,0,0,0),
background_normal= "web/images/button_1.png",
background_down = "web/images/button_11.png",
color = (1,1,1,1)
)
menuBtn = Button( text="[b]Menu[/b]",
markup=True,
size_hint = ( None, None ),
font_size="15sp",
border = (0,0,0,0),
background_normal= "web/images/button_round_off.png",
background_down = "web/images/button_round_on.png",
color = (1,1,1,1)
)
setControlState( holdControl, "normal" if not( state.exists( "state" ) ) else state.get( "state" )[ "holdControl" ] )
def get_status_string():
with thermostatLock:
temperature = 0
if holdControl.state == "down":
sched = "Manuale"
temperature = setTemp
elif useTestSchedule:
sched = "Test"
temperature = setTemp
elif heatControl.state == "down":
if dhtSchedule == 0:
sched = "Heat"
else:
sched = "Dht"
temperature = setTemp
else:
sched = "No Ice"
temperature = settings.get("thermostat")["tempice"]
testHeat = False
if GPIO.input( heatPin ) == True:
testHeat = False
else:
testHeat = True
setLabel.color = (1,1,1,1)
return " [b]Ur: " +str(round(dhtUm,1))+"%[/b]\n " + \
" T Imp: " +str(temperature)+ scaleUnits +" \n "+\
" Caldaia: " + ( "[i][b][color=ff3333]On[/b][/i][/color]" if testHeat else "Off" ) + "\n "+\
" Sched: " + sched
versionLabel = Label( text="Thermostat v" + str( THERMOSTAT_VERSION ), size_hint = ( None, None ), font_size='10sp', markup=True, text_size=( 150, 20 ) )
currentLabel = Label( text="[b]" + str( currentTemp ) + scaleUnits + "[/b]", size_hint = ( None, None ), font_size='100sp', markup=True, text_size=( 300, 200 ) )
altCurLabel = Label( text=currentLabel.text, size_hint = ( None, None ), font_size='100sp', markup=True, text_size=( 300, 200 ), color=( 0.5, 0.5, 0.5, 0.2 ) )
waterTempLabel = Label (text="[b][i] NA [/b][/i]", font_size='20sp', markup=True, size_hint = ( None, None ), pos = ( 600, 400 ))
setLabel = Label( text=" Set\n[b]" + str( setTemp ) + scaleUnits + "[/b]", size_hint = ( None, None ), font_size='25sp', markup=True, text_size=( 100, 100 ) )
statusLabel = Label( text=get_status_string(), size_hint = ( None, None ), font_size='30sp', markup=True, text_size=( 300, 230 ) )
altStatusLabel = Label( text=get_status_string(), size_hint = ( None, None),font_size='30sp', markup=True, text_size=( 300, 230 ),color=(0.5,0.5,0.5,0.2))
dateLabel = Label( text="[b]" + time.strftime("%d %b %a, %Y") + "[/b]", size_hint = ( None, None ), font_size='25sp', markup=True, text_size=( 270, 40 ) )
timeStr = time.strftime("%H:%M").lower()
timeInit = time.time()
timeLabel = Label( text="[b]" + ( timeStr if timeStr[0:1] != "0" else timeStr[1:] ) + "[/b]", size_hint = ( None, None ), font_size='45sp', markup=True, text_size=( 180, 75 ) )
altTimeLabel = Label( text=timeLabel.text, size_hint = ( None, None ), font_size='40sp', markup=True, text_size=( 180, 75 ), color=( 0.5, 0.5, 0.5, 0.2 ) )
#tempSlider = Slider( orientation='vertical', min=minTemp, max=maxTemp, step=tempStep, value=setTemp, size_hint = ( None, None ) )
tempSlider = Knob( knobimg_source = "web/images/round.png",marker_img = "web/images/bline.png", markeroff_color = (0, 0, 0, 0), marker_inner_color = (0, 0, 0, 1) )
screenMgr = None
#############################################################################
# #
# Weather functions/constants/widgets #
# #
##############################################################################
weatherLocation = settings.get("weather")["location"]
weatherAppKey = settings.get("weather")["appkey"]
weatherURLBase = "https://api.darksky.net/forecast/"
weatherURLTimeout = settings.get("weather")["URLtimeout"]
weatherURLCurrent = weatherURLBase + weatherAppKey + "/" + weatherLocation + "?units=si&exclude=[minutely,hourly,flags,alerts]&lang=it"
#weatherLocation = settings.get( "weather" )[ "location" ]
#weatherAppKey = settings.get( "weather" )[ "appkey" ]
#weatherURLBase = "http://api.openweathermap.org/data/2.5/"
#weatherURLForecast = weatherURLBase + "forecast/daily?units=" + tempScale + "&id=" + weatherLocation + "&APPID=" + weatherAppKey + "&lang=it"
#weatherURLTimeout = settings.get( "weather" )[ "URLtimeout" ]
#weatherURLCurrent = weatherURLBase + "weather?units=" + tempScale + "&id=" + weatherLocation + "&APPID=" + weatherAppKey + "&lang=it"
forecastRefreshInterval = settings.get( "weather" )[ "forecastRefreshInterval" ] * 60
weatherExceptionInterval = settings.get( "weather" )[ "weatherExceptionInterval" ] * 60
weatherRefreshInterval = settings.get( "weather" )[ "weatherRefreshInterval" ] * 60
weatherSummaryLabel = Label( text="", size_hint = ( None, None ), font_size='18sp', markup=True, text_size=( 250, 50 ), max_lines = 2 )
weatherDetailsLabel = Label( text="", size_hint = ( None, None ), font_size='20sp', markup=True, text_size=( 300, 150 ), valign="top" )
weatherImg = Image( source="web/images/na.png", size_hint = ( None, None ) )
weatherminSummaryLabel = Label( text="", size_hint = ( None, None ), font_size='20sp', markup=True, text_size=( 200, 20 ), color=(0.5,0.5,0.5,0.2) )
weatherminImg = Image( source="web/images/na.png", size_hint = ( None, None ), color=(1,1,1,0.4) )
forecastTodaySummaryLabel = Label( text="", size_hint = ( None, None ), font_size='10sp', markup=True, text_size=( 120, 40 ), max_lines = 3 )
forecastTodayDetailsLabel = Label( text="", size_hint = ( None, None ), font_size='15sp', markup=True, text_size=( 200, 150 ), valign="top" )
forecastTodayImg = Image( source="web/images/na.png", size_hint = ( None, None ) )
forecastTomoSummaryLabel = Label( text="", size_hint = ( None, None ), font_size='10sp', markup=True, text_size=( 120, 40 ), max_lines = 3)
forecastTomoDetailsLabel = Label( text="", size_hint = ( None, None ), font_size='15sp', markup=True, text_size=( 200, 150 ), valign="top" )
forecastTomoImg = Image( source="web/images/na.png", size_hint = ( None, None ) )
forecastDataNew = []
forecastSummaryLabelNew = []
forecastDetailsLabelNew = []
forecastImgNew = []
for c in range(0, 3):
forecastDataNew.append(Label(text="", size_hint=(None, None), font_size='16sp', markup=True, text_size=(300, 20)))
forecastSummaryLabelNew.append(
Label(text="", size_hint=(None, None), font_size='16sp', markup=True, text_size=(250, 50)))
forecastDetailsLabelNew.append(
Label(text="", size_hint=(None, None), font_size='16sp', markup=True, text_size=(300, 150), valign="top"))
forecastImgNew.append(Image(source="web/images/na.png", size_hint=(None, None)))
forecastSummaryNew = Label(text="", size_hint=(None, None), font_size='18sp', markup=True, text_size=(800, 50))
def get_weather( url ):
return json.loads(urllib2.urlopen(url, None, weatherURLTimeout).read())#json.loads( urllib2.urlopen( url, None, weatherURLTimeout ).read() )
def load_weather_info(dt):
with weatherLock:
interval = weatherRefreshInterval
try:
weather = json.loads(urllib2.urlopen(weatherURLCurrent, None, weatherURLTimeout).read())
forecastSummaryNew.text = "[b]" + weather["daily"]["summary"] + "[/b]"
# compile data for forecast
for c in range(0, 3):
today = weather["daily"]["data"][c]
forecastDataNew[c].text = "[b]" + time.strftime('%A %d/%m ', time.localtime(today["time"])) + "[/b]"
forecastImgNew[c].source = "web/images/" + today["icon"] + ".png"
forecastSummaryLabelNew[c].text = "[b]" + today["summary"][:-1] + "[/b] "
#print "range ", c ," forecastDataNew[c].text " ,forecastDataNew[c].text, " forecastImgNew[c].source ",forecastImgNew[c].source," forecastSummaryLabelNew[c].text ",forecastSummaryLabelNew[c].text
cloudString = " 0"
windGustString = " 0"
humidityString = " 0"
if "cloudCover" in today:
cloudString = str(today["cloudCover"] * 100)
if "windGust" in today:
windGustString = str(int(round(today["windGust"] * windFactor)))
if "cloudCover" in today:
humidityString = str( today[ "humidity" ] * 100)
forecastTextNew = "\n".join((
"Max: " + str(int(round(today["temperatureMax"], 0))) + " Min: " + str(
int(round(today["temperatureMin"], 0))),
"Umidita: " + humidityString + "%",
"Nuvole: " + cloudString + "%",
"Pressione: " + str(int(today["pressure"])) + "mBar",
"Vento: " + str(
int(round(today["windSpeed"] * windFactor))) + " - " + windGustString + windUnits + get_cardinal_direction(
today["windBearing"]),
))
#print "forecastTextNew ", forecastTextNew
if "precipType" in today or "snow" in today:
forecastTextNew += "\n"
if "rain" in today["precipType"]:
rainTime = time.strftime("%H:%M", time.localtime(int(today["precipIntensityMaxTime"])))
forecastTextNew += "Pioggia: " + get_precip_amount( today[ "precipIntensityMax" ] ) + precipUnits + " " + rainTime + "\nProbabilita': " + str(today[ "precipProbability" ] * 100) + "%"
if "snow" in today["precipType"]:
forecastTextNew += ", Neve: " + get_precip_amount( today[ "precipAccumulation" ] ) + precipUnits + "\nProbabilita': " + str(today[ "precipProbability" ] * 100) + "%"
else:
forecastTextNew += "Neve: " + get_precip_amount( today[ "precipAccumulation" ] ) + precipUnits + "\nProbabilita': " + str(today[ "precipProbability" ] * 100) + "%"
forecastDetailsLabelNew[c].text = forecastTextNew
except:
print "Something went wrong in load_weather_info"
interval = weatherExceptionInterval
Clock.schedule_once( load_weather_info, interval )
def get_cardinal_direction( heading ):
directions = [ "N", "NE", "E", "SE", "S", "SW", "W", "NW", "N" ]
return directions[ int( round( ( ( heading % 360 ) / 45 ) ) ) ]
def display_current_weather( dt ):
with weatherLock:
global out_temp,temp_vis, outside_temp, out_humidity
interval = weatherRefreshInterval
try:
weather = get_weather( weatherURLCurrent )
weatherImg.source = "web/images/" + weather["currently"]["icon"] + ".png"
print weatherImg.source
weatherSummaryLabel.text = "[b]" + weather["currently"]["summary"] + "[/b]"
#weatherImg.source = "web/images/" + weather[ "weather" ][ 0 ][ "icon" ] + ".png"
#weatherSummaryLabel.text = "[b]" + weather[ "weather" ][ 0 ][ "description" ].title() + "[/b]"
#weatherminImg.source = "web/images/" + weather[ "weather" ][ 0 ][ "icon" ] + ".png"
#weatherminSummaryLabel.text = "[b]" + weather[ "weather" ][ 0 ][ "description" ].title() + "[/b]"
if dhtoutEnabled == 1 and dhtoutWired == 0:
dhtoutRead()
print "letta temperatura",out_temp
if out_temp == 0 or out_temp == None:
temp_vis = str( int( round( weather["currently"]["temperature"], 1 ) ) )
else:
temp_vis = str(round(out_temp,1))
out_humidity = str(int(round(out_humidity,0)))
print temp_vis
elif dhtoutEnabled == 1 and dhtoutWired == 1:
getDhtSensorData()
print "letta temperatura DHT Filato",out_temp
if out_temp == 0 or out_temp == None:
temp_vis = str( int( round( weather["currently"]["temperature"], 1 ) ) )
else:
temp_vis = str(round(out_temp,1))
out_humidity = str(int(round(out_humidity,0)))
print temp_vis
else:
temp_vis = str(round(outside_temp,1)) #outside_temp is coming from external sensor #was# str( int( round( weather[ "main" ][ "temp" ], 0 ) ) )
out_humidity = str( weather["currently"]["humidity"]*100 )
weatherDetailsLabel.text = "\n".join( (
"T Out: " + temp_vis + " " +scaleUnits,
" Ur : " + out_humidity + "%",
#"Vento: " + str( int( round( weather[ "wind" ][ "speed" ] * windFactor ) ) ) + windUnits + " " + get_cardinal_direction( weather[ "wind" ][ "deg" ] ),
#"Nuvole: " + str( weather[ "clouds" ][ "all" ] ) + "%",
) )
log( LOG_LEVEL_INFO, CHILD_DEVICE_WEATHER_CURR, MSG_SUBTYPE_TEXT, weather[ "currently" ][ "summary" ].title() + "; " + re.sub( '\n', "; ", re.sub( ' +', ' ', weatherDetailsLabel.text ).strip() ) )
except:
interval = weatherExceptionInterval
print "debug sono qui"
weatherImg.source = "web/images/na.png"
weatherSummaryLabel.text = ""
weatherDetailsLabel.text = ""
log( LOG_LEVEL_ERROR, CHILD_DEVICE_WEATHER_CURR, MSG_SUBTYPE_TEXT, "Update FAILED!" )
Clock.schedule_once( display_current_weather, interval )
def display_forecast_weather( dt ):
with weatherLock:
interval = forecastRefreshInterval
try:
forecast = get_weather( weatherURLCurrent )
today = forecast["daily"]["data"][0]
tomo = forecast["daily"]["data"][1]
forecastTodayImg.source = "web/images/" + today[ "icon" ] + ".png"
forecastTodaySummaryLabel.text = "[b]" + today[ "summary" ].title() + "[/b]"
cloudString = " 0"
windGustString = " 0"
humidityString = " 0"
if "cloudCover" in today:
cloudString = str(today["cloudCover"] * 100)
if "windGust" in today:
windGustString = str(int(round(today["windGust"] * windFactor)))
if "cloudCover" in today:
humidityString = str( today[ "humidity" ] * 100)
todayText = "\n".join( (
"Temp Max: " + str( int( round( today[ "temperatureMax" ], 0 ) ) ) + scaleUnits + ", Min: " + str( int( round( today[ "temperatureMin" ], 0 ) ) ) + scaleUnits,
"Umidita: "+ humidityString + "%",
"Vento: " + str( int( round( today[ "windSpeed" ] * windFactor ) ) ) + " - " + windGustString + windUnits +" " + get_cardinal_direction( today[ "windBearing" ] ),
"Nuvole: " + cloudString + "%",
) )
# print "today - forecastTodaySummaryLabel.text " ,forecastTodaySummaryLabel.text, " forecastTodayImg ",forecastTodayImg.source," todayText ",todayText
if "precipType" in today or "snow" in today:
todayText += "\n"
if "rain" in today["precipType"]:
rainTime = time.strftime("%H:%M", time.localtime(int(today["precipIntensityMaxTime"])))
todayText += "Pioggia: " + get_precip_amount( today[ "precipIntensityMax" ] ) + precipUnits + " " + rainTime + "\nProbabilita': " + str(today[ "precipProbability" ] * 100) + "%"
if "snow" in today["precipType"]:
todayText += ", Neve: " + get_precip_amount( today[ "precipAccumulation" ] ) + precipUnits + "\nProbabilita': " + str(today[ "precipProbability" ] * 100) + "%"
else:
todayText += "Neve: " + get_precip_amount( today[ "precipAccumulation" ] ) + precipUnits + "\nProbabilita': " + str(today[ "precipProbability" ] * 100) + "%"
forecastTodayDetailsLabel.text = todayText;
forecastTomoImg.source = "web/images/" + tomo["icon" ] + ".png"
forecastTomoSummaryLabel.text = "[b]" + tomo[ "summary" ].title() + "[/b]"
cloudString = " 0"
windGustString = " 0"
humidityString = " 0"
if "cloudCover" in tomo:
cloudString = str(tomo["cloudCover"] * 100)
if "windGust" in tomo:
windGustString = str(int(round(tomo["windGust"] * windFactor)))
if "cloudCover" in tomo:
humidityString = str( tomo[ "humidity" ] * 100)
tomoText = "\n".join( (
"Temp Max: " + str( int( round( tomo[ "temperatureMax" ], 0 ) ) ) + scaleUnits + ", Min: " + str( int( round( tomo[ "temperatureMin" ], 0 ) ) ) + scaleUnits,
"Umidita: " + humidityString + "%",
"Vento: " + str( int( round( tomo[ "windSpeed" ] * windFactor ) ) ) + " - " + windGustString + windUnits + " " + get_cardinal_direction( tomo[ "windBearing" ] ),
"Nuvole: " + cloudString + "%",
) )
if "precipType" in tomo or "snow" in tomo:
tomoText += "\n"
if "rain" in tomo["precipType"]:
rainTime = time.strftime("%H:%M", time.localtime(int(tomo["precipIntensityMaxTime"])))
tomoText += "Pioggia: " + get_precip_amount( tomo[ "precipIntensityMax" ] ) + precipUnits + " " + rainTime + "\nProbabilita': " + str(tomo[ "precipProbability" ] * 100) + "%"
if "snow" in ["precipType"]:
tomoText += ", Neve: " + get_precip_amount( tomo[ "precipAccumulation" ] ) + precipUnits + "\nProbabilita': " + str(tomo[ "precipProbability" ] * 100) + "%"
else:
tomoText += "Neve: " + get_precip_amount( tomo[ "precipAccumulation" ] ) + precipUnits + "\nProbabilita': " + str(tomo[ "precipProbability" ] * 100) + "%"
forecastTomoDetailsLabel.text = tomoText
log( LOG_LEVEL_INFO, CHILD_DEVICE_WEATHER_FCAST_TODAY, MSG_SUBTYPE_TEXT, today[ "summary" ].title() + "; " + re.sub( '\n', "; ", re.sub( ' +', ' ', forecastTodayDetailsLabel.text ).strip() ) )
log( LOG_LEVEL_INFO, CHILD_DEVICE_WEATHER_FCAST_TOMO, MSG_SUBTYPE_TEXT, tomo[ "summary" ].title() + "; " + re.sub( '\n', "; ", re.sub( ' +', ' ', forecastTomoDetailsLabel.text ).strip() ) )
except:
print "Something went wrong in display_forecast_weather"
interval = weatherExceptionInterval
forecastTodayImg.source = "web/images/na.png"
forecastTodaySummaryLabel.text = ""
forecastTodayDetailsLabel.text = ""
forecastTomoImg.source = "web/images/na.png"
forecastTomoSummaryLabel.text = ""
forecastTomoDetailsLabel.text = ""
log( LOG_LEVEL_ERROR, CHILD_DEVICE_WEATHER_FCAST_TODAY, MSG_SUBTYPE_TEXT, "Update FAILED!" )
Clock.schedule_once( display_forecast_weather, interval )
def get_precip_amount( raw ):
precip = round( raw * precipFactor, precipRound )
if tempScale == "metric":
return str( precip )
else:
return str( precip )
##############################################################################
# #
# Utility Functions #
# #
##############################################################################
def get_ip_address():
s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
s.settimeout( 10 ) # 10 seconds
try:
s.connect( ( "8.8.8.8", 80 ) ) # Google DNS server
ip = s.getsockname()[0]
log( LOG_LEVEL_INFO, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM +"/settings/ip", ip, timestamp=False )
except socket.error:
ip = "127.0.0.1"
log( LOG_LEVEL_ERROR, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/settings/ip", "FAILED to get ip address, returning " + ip, timestamp=False )
return ip