-
-
Notifications
You must be signed in to change notification settings - Fork 112
/
belchertown.py
3967 lines (3650 loc) · 180 KB
/
belchertown.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
"""
Extension for the Belchertown skin.
This extension builds search list extensions as well
as a crude "cron" to download necessary files.
Pat O'Brien, August 19, 2018
"""
from __future__ import print_function # Python 2/3 compatibility
from __future__ import with_statement
import calendar
import datetime
import json
import locale
import os
import os.path
import sys
import syslog
import time
from collections import OrderedDict
from math import asin, atan2, cos, degrees, pi, radians, sin, sqrt
from re import match
import configobj
import weeutil.weeutil
import weewx
import weewx.reportengine
import weewx.station
import weewx.tags
import weewx.units
from weeutil.weeutil import (
TimeSpan,
archiveDaySpan,
archiveMonthSpan,
archiveSpanSpan,
archiveWeekSpan,
archiveYearSpan,
isStartOfDay,
startOfDay,
to_bool,
to_float,
to_int,
)
from weewx.cheetahgenerator import SearchList
from weewx.tags import TimespanBinder
if sys.version_info[0] >= 3:
from weeutil.config import search_up
# Check weewx version. Many things like search_up, weeutil.weeutil.KeyDict
# (label_dict) are from 3.9
if weewx.__version__ < "3.9":
raise weewx.UnsupportedFeature(
"weewx 3.9 and newer is required, found %s" % weewx.__version__
)
if weewx.__version__ < "4":
def logmsg(level, msg):
syslog.syslog(level, "Belchertown Extension: %s" % msg)
def logdbg(msg):
logmsg(syslog.LOG_DEBUG, msg)
def loginf(msg):
logmsg(syslog.LOG_INFO, msg)
def logerr(msg):
logmsg(syslog.LOG_ERR, msg)
from weeutil.weeutil import accumulateLeaves
import syslog
else:
# weewx 4.0+
from weeutil.config import accumulateLeaves
import weeutil.logger
import logging
log = logging.getLogger(__name__)
def logdbg(msg):
log.debug(msg)
def loginf(msg):
log.info(msg)
def logerr(msg):
log.error(msg)
# Print version in syslog for easier troubleshooting
VERSION = "1.3.1"
loginf("version %s" % VERSION)
# Define these as global so they can be used in both the search list extension
# and custom graphs section
aqi = ""
aqi_category = ""
aqi_time = 0
aqi_location = ""
class getData(SearchList):
"""
Collect all custom data and calculations, then return search list extension
"""
def __init__(self, generator):
SearchList.__init__(self, generator)
def get_gps_distance(self, pointA, pointB, distance_unit):
"""
https://www.geeksforgeeks.org/program-distance-two-points-earth/ and
https://stackoverflow.com/a/43960736 The math module contains a
function named radians which converts from degrees to radians.
"""
if not isinstance((pointA, pointB), tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = pointA[0]
lon1 = pointA[1]
lat2 = pointB[0]
lon2 = pointB[1]
# convert decimal degrees to radians
lat1r, lon1r, lat2r, lon2r = map(radians, [lat1, lon1, lat2, lon2])
# Haversine formula
dlat = lat2r - lat1r
dlon = lon2r - lon1r
a = sin(dlat / 2) ** 2 + cos(lat1r) * cos(lat2r) * sin(dlon / 2) ** 2
c = 2 * asin(sqrt(a))
# Radius of earth in kilometers is 6371. Use 3956 for miles
if distance_unit == "km":
r = 6371
else:
# Assume mile
r = 3956
bearing = self.get_gps_bearing(pointA, pointB)
# Returns distance as object 0 and bearing as object 1
return [(c * r), self.get_cardinal_direction(bearing), bearing]
def get_gps_bearing(self, pointA, pointB):
"""
https://gist.github.com/jeromer/2005586
Calculates the bearing between two points.
:Parameters:
- pointA: The tuple representing the latitude/longitude for the
first point. Latitude and longitude must be in decimal degrees
- pointB: The tuple representing the latitude/longitude for the
second point. Latitude and longitude must be in decimal degrees
:Returns:
The bearing in degrees
:Returns Type:
float
"""
if not isinstance((pointA, pointB), tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = radians(pointA[0])
lat2 = radians(pointB[0])
diffLong = radians(pointB[1] - pointA[1])
x = sin(diffLong) * cos(lat2)
y = cos(lat1) * sin(lat2) - (sin(lat1) * cos(lat2) * cos(diffLong))
initial_bearing = atan2(x, y)
# Now we have the initial bearing but math.atan2 return values
# from -180 to + 180 degrees which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360
return compass_bearing
def get_cardinal_direction(self, degree, return_only_labels=False):
default_ordinate_names = [
"N",
"NNE",
"NE",
"ENE",
"E",
"ESE",
"SE",
"SSE",
"S",
"SSW",
"SW",
"WSW",
"W",
"WNW",
"NW",
"NNW",
"N/A",
]
try:
ordinate_names = weeutil.weeutil.option_as_list(
self.generator.skin_dict["Units"]["Ordinates"]["directions"]
)
except KeyError:
ordinate_names = default_ordinate_names
if return_only_labels:
return ordinate_names
if 0 <= degree <= 11.25:
return ordinate_names[0]
if 11.26 <= degree <= 33.75:
return ordinate_names[1]
if 33.76 <= degree <= 56.25:
return ordinate_names[2]
if 56.26 <= degree <= 78.75:
return ordinate_names[3]
if 78.76 <= degree <= 101.25:
return ordinate_names[4]
if 101.26 <= degree <= 123.75:
return ordinate_names[5]
if 123.76 <= degree <= 146.25:
return ordinate_names[6]
if 146.26 <= degree <= 168.75:
return ordinate_names[7]
if 168.76 <= degree <= 191.25:
return ordinate_names[8]
if 191.26 <= degree <= 213.75:
return ordinate_names[9]
if 213.76 <= degree <= 236.25:
return ordinate_names[10]
if 236.26 <= degree <= 258.75:
return ordinate_names[11]
if 258.76 <= degree <= 281.25:
return ordinate_names[12]
if 281.26 <= degree <= 303.75:
return ordinate_names[13]
if 303.76 <= degree <= 326.25:
return ordinate_names[14]
if 326.26 <= degree <= 348.75:
return ordinate_names[15]
if 348.76 <= degree <= 360:
return ordinate_names[0]
def get_extension_list(self, timespan, db_lookup):
"""
Build the data needed for the Belchertown skin
"""
global aqi
global aqi_category
global aqi_time
global aqi_location
# Look for the debug flag which can be used to show more logging
weewx.debug = int(self.generator.config_dict.get("debug", 0))
# Setup label dict for text and titles
try:
d = self.generator.skin_dict["Labels"]["Generic"]
except KeyError:
d = {}
label_dict = weeutil.weeutil.KeyDict(d)
# Setup database manager
binding = self.generator.config_dict["StdReport"].get(
"data_binding", "wx_binding"
)
manager = self.generator.db_binder.get_manager(binding)
belchertown_debug = self.generator.skin_dict["Extras"].get(
"belchertown_debug", 0
)
# Find the right HTML ROOT
if "HTML_ROOT" in self.generator.skin_dict:
html_root = os.path.join(
self.generator.config_dict["WEEWX_ROOT"],
self.generator.skin_dict["HTML_ROOT"],
)
else:
html_root = os.path.join(
self.generator.config_dict["WEEWX_ROOT"],
self.generator.config_dict["StdReport"]["HTML_ROOT"],
)
# Setup UTC offset hours for moment.js in index.html
moment_js_stop_struct = time.localtime(time.time())
moment_js_utc_offset = (
calendar.timegm(moment_js_stop_struct)
- calendar.timegm(time.gmtime(time.mktime(moment_js_stop_struct)))
) / 60
try:
moment_js_tz = self.generator.skin_dict["Units"]["TimeZone"].get("time_zone")
except KeyError:
moment_js_tz = ""
# Highcharts UTC offset is the opposite of normal. Positive values are
# west, negative values are east of UTC.
# https://api.highcharts.com/highcharts/time.timezoneOffset Multiplying
# by -1 will reverse the number sign and keep 0 (not -0).
# https://stackoverflow.com/a/14053631/1177153
highcharts_timezoneoffset = moment_js_utc_offset * -1
# If theme locale is auto, get the system locale for use with
# moment.js, and the system decimal for use with highcharts
if self.generator.skin_dict["Extras"]["belchertown_locale"] == "auto":
system_locale, locale_encoding = locale.getdefaultlocale()
else:
try:
# Try setting the locale. Locale needs to be in locale.encoding
# format. Example: "en_US.UTF-8", or "de_DE.UTF-8"
locale.setlocale(
locale.LC_ALL,
self.generator.skin_dict["Extras"]["belchertown_locale"],
)
system_locale, locale_encoding = locale.getlocale()
except Exception as error:
# The system can't find the locale requested, so just set the
# variables anyways for JavaScript's use.
system_locale, locale_encoding = self.generator.skin_dict["Extras"][
"belchertown_locale"
].split(".")
if belchertown_debug:
logerr(
"Locale: Error using locale %s. "
"This locale may not be installed on your system and you may see unexpected results. "
"Belchertown skin JavaScript will try to use this locale. Full error: %s"
% (
self.generator.skin_dict["Extras"]["belchertown_locale"],
error,
)
)
if system_locale is None:
# Unable to determine locale. Fallback to en_US
system_locale = "en_US"
if locale_encoding is None:
# Unable to determine locale_encoding. Fallback to UTF-8
locale_encoding = "UTF-8"
try:
system_locale_js = system_locale.replace(
"_", "-"
) # Python's locale is underscore. JS uses dashes.
except:
system_locale_js = "en-US" # Error finding locale, set to en-US
highcharts_decimal = self.generator.skin_dict["Extras"].get(
"highcharts_decimal", None
)
# Change the Highcharts decimal to the locale if the option is missing
# or on auto mode, otherwise use whats defined in Extras
if highcharts_decimal is None or highcharts_decimal == "auto":
try:
highcharts_decimal = locale.localeconv()["decimal_point"]
except:
# Locale not found, default back to a period
highcharts_decimal = "."
highcharts_thousands = self.generator.skin_dict["Extras"].get(
"highcharts_thousands", None
)
# Change the Highcharts thousands separator to the locale if the option
# is missing or on auto mode, otherwise use whats defined in Extras
if highcharts_thousands is None or highcharts_thousands == "auto":
try:
highcharts_thousands = locale.localeconv()["thousands_sep"]
except:
# Locale not found, default back to a comma
highcharts_thousands = ","
# Get the archive interval for the highcharts gapsize
try:
archive_interval_ms = (
int(self.generator.config_dict["StdArchive"]["archive_interval"]) * 1000
)
except KeyError:
archive_interval_ms = (
300000 # 300*1000 for archive_interval emulated to millis
)
# Get the ordinal labels
ordinate_names = self.get_cardinal_direction("", True)
# Build the chart array for the HTML. Outputs a dict of nested lists
# which allow you to have different charts for different timespans on
# the site in different order with different names.
# OrderedDict([('day', ['chart1', 'chart2', 'chart3', 'chart4']),
# ('week', ['chart1', 'chart5', 'chart6', 'chart2', 'chart3', 'chart4']),
# ('month', ['this_is_chart1', 'chart2_is_here', 'chart3', 'windSpeed_and_windDir', 'chart5', 'chart6', 'chart7']),
# ('year', ['chart1', 'chart2', 'chart3', 'chart4', 'chart5'])])
chart_config_path = os.path.join(
self.generator.config_dict["WEEWX_ROOT"],
self.generator.skin_dict["SKIN_ROOT"],
self.generator.skin_dict.get("skin", ""),
"graphs.conf",
)
default_chart_config_path = os.path.join(
self.generator.config_dict["WEEWX_ROOT"],
self.generator.skin_dict["SKIN_ROOT"],
self.generator.skin_dict.get("skin", ""),
"graphs.conf.example",
)
if os.path.exists(chart_config_path):
chart_dict = configobj.ConfigObj(chart_config_path, file_error=True)
else:
chart_dict = configobj.ConfigObj(default_chart_config_path, file_error=True)
charts = OrderedDict()
for chart_timespan in chart_dict.sections:
timespan_chart_list = []
for plotname in chart_dict[chart_timespan].sections:
if plotname not in timespan_chart_list:
timespan_chart_list.append(plotname)
charts[chart_timespan] = timespan_chart_list
# Create a dict of chart group titles for use on the graphs page
# header. If no title defined, use the chart group name
graphpage_titles = OrderedDict()
for chartgroup in chart_dict.sections:
if "title" in chart_dict[chartgroup]:
graphpage_titles[chartgroup] = chart_dict[chartgroup]["title"]
else:
graphpage_titles[chartgroup] = chartgroup
# Create a dict of chart group page content for use on the graphs page
# below the header.
graphpage_content = OrderedDict()
for chartgroup in chart_dict.sections:
if "page_content" in chart_dict[chartgroup]:
graphpage_content[chartgroup] = chart_dict[chartgroup]["page_content"]
# Setup the Graphs page button row based on the skin extras option and
# the button_text from graphs.conf
graph_page_buttons = ""
graph_page_graphgroup_buttons = []
for chartgroup in chart_dict.sections:
if (
"show_button" in chart_dict[chartgroup]
and chart_dict[chartgroup]["show_button"].lower() == "true"
):
graph_page_graphgroup_buttons.append(chartgroup)
for gg in graph_page_graphgroup_buttons:
if "button_text" in chart_dict[gg]:
button_text = chart_dict[gg]["button_text"]
else:
button_text = gg
graph_page_buttons += (
'<a href="./?graph='
+ gg
+ '"><button type="button" class="btn btn-primary">'
+ button_text
+ "</button></a>"
)
graph_page_buttons += " " # Spacer between the button
# Set a default radar URL using station's lat/lon. Moved from skin.conf
# so we can get station lat/lon from weewx.conf. A lot of stations out
# there with Belchertown 0.1 through 0.7 are showing the visitor's
# location and not the proper station location because nobody edited
# the radar_html which did not have lat/lon set previously.
lat = self.generator.config_dict["Station"]["latitude"]
lon = self.generator.config_dict["Station"]["longitude"]
radar_width = self.generator.skin_dict["Extras"]["radar_width"]
radar_height = self.generator.skin_dict["Extras"]["radar_height"]
if "radar_zoom" in self.generator.skin_dict["Extras"]:
zoom = self.generator.skin_dict["Extras"]["radar_zoom"]
else:
zoom = "8"
if (
"radar_marker" in self.generator.skin_dict["Extras"]
and self.generator.skin_dict["Extras"]["radar_marker"] == "1"
):
marker = "true"
else:
marker = ""
# Set default radar html code, and override with user-specified value
if self.generator.skin_dict["Extras"].get("radar_html") == "":
if self.generator.skin_dict["Extras"].get("aeris_map") == "1":
radar_html = '<img style="object-fit:cover;width:{}px;height:{}px" src="https://maps.aerisapi.com/{}_{}/flat,water-depth,counties:60,rivers,interstates:60,admin-cities,alerts-severe:50:blend(darken),radar:blend(darken)/{}x{}/{},{},{}/current.png" referrerpolicy="no-referrer"></img>'.format(
radar_width,
radar_height,
self.generator.skin_dict["Extras"]["forecast_api_id"],
self.generator.skin_dict["Extras"]["forecast_api_secret"],
radar_width,
radar_height,
lat,
lon,
zoom,
)
else:
radar_html = '<iframe width="{}px" height="{}px" src="https://embed.windy.com/embed2.html?lat={}&lon={}&zoom={}&level=surface&overlay=radar&menu=&message=true&marker={}&calendar=&pressure=&type=map&location=coordinates&detail=&detailLat={}&detailLon={}&metricWind=&metricTemp=&radarRange=-1" frameborder="0"></iframe>'.format(
radar_width, radar_height, lat, lon, zoom, marker, lat, lon
)
else:
radar_html = self.generator.skin_dict["Extras"]["radar_html"]
if self.generator.skin_dict["Extras"].get("radar_html_dark") == "":
if self.generator.skin_dict["Extras"].get("aeris_map") == "1":
radar_html_dark = '<img style="object-fit:cover;width:{}px;height:{}px" src="https://maps.aerisapi.com/{}_{}/flat-dk,water-depth-dk,counties:60,rivers,interstates:60,admin-cities-dk,alerts-severe:50:blend(lighten),radar:blend(lighten)/{}x{}/{},{},{}/current.png" referrerpolicy="no-referrer"></img>'.format(
radar_width,
radar_height,
self.generator.skin_dict["Extras"]["forecast_api_id"],
self.generator.skin_dict["Extras"]["forecast_api_secret"],
radar_width,
radar_height,
lat,
lon,
zoom,
)
else:
radar_html_dark = "None"
else:
radar_html_dark = self.generator.skin_dict["Extras"]["radar_html_dark"]
# If the kiosk radar is different then the homepage one.
if self.generator.skin_dict["Extras"].get("radar_html_kiosk") == "":
radar_html_kiosk = radar_html
else:
radar_width_kiosk = self.generator.skin_dict["Extras"]["radar_width_kiosk"]
radar_height_kiosk = self.generator.skin_dict["Extras"]["radar_height_kiosk"]
radar_html_kiosk = '<iframe width="{}px" height="{}px" src="{}" frameborder="0"></iframe>'.format(
radar_width_kiosk,
radar_height_kiosk,
self.generator.skin_dict["Extras"]["radar_html_kiosk"]
)
# ==============================================================================
# Build the all time stats.
# ==============================================================================
wx_manager = db_lookup()
# Find the beginning of the current year
now = datetime.datetime.now()
date_time = "01/01/%s 00:00:00" % now.year
pattern = "%m/%d/%Y %H:%M:%S"
year_start_epoch = int(time.mktime(time.strptime(date_time, pattern)))
date_time = "%s/%s/%s 00:00:00" % (now.month, now.day, now.year)
today_start_epoch = int(time.mktime(time.strptime(date_time, pattern)))
# Setup the converter
# Get the target unit nickname (something like 'US' or 'METRIC'):
target_unit_nickname = self.generator.config_dict["StdConvert"]["target_unit"]
# Get the target unit: weewx.US, weewx.METRIC, weewx.METRICWX
target_unit = weewx.units.unit_constants[target_unit_nickname.upper()]
# Bind to the appropriate standard converter units
converter = weewx.units.StdUnitConverters[target_unit]
# Temperature Range Lookups
# 1. The database query finds the result based off the total column.
# 2. We need to convert the min, max to the site's requested unit.
# 3. We need to recalculate the min/max range because the unit may have changed.
year_outTemp_max_range_query = wx_manager.getSql(
"SELECT dateTime, ROUND( (max - min), 1 ) as total, ROUND( min, 1 ) as min, ROUND( max, 1 ) as max FROM archive_day_outTemp WHERE dateTime >= %s AND dateTime < %s AND min IS NOT NULL AND max IS NOT NULL ORDER BY total DESC LIMIT 1;"
% (year_start_epoch, today_start_epoch)
)
year_outTemp_min_range_query = wx_manager.getSql(
"SELECT dateTime, ROUND( (max - min), 1 ) as total, ROUND( min, 1 ) as min, ROUND( max, 1 ) as max FROM archive_day_outTemp WHERE dateTime >= %s AND dateTime < %s AND min IS NOT NULL AND max IS NOT NULL ORDER BY total ASC LIMIT 1;"
% (year_start_epoch, today_start_epoch)
)
at_outTemp_max_range_query = wx_manager.getSql(
"SELECT dateTime, ROUND( (max - min), 1 ) as total, ROUND( min, 1 ) as min, ROUND( max, 1 ) as max FROM archive_day_outTemp WHERE dateTime < %s AND min IS NOT NULL AND max IS NOT NULL ORDER BY total DESC LIMIT 1;"
% today_start_epoch
)
at_outTemp_min_range_query = wx_manager.getSql(
"SELECT dateTime, ROUND( (max - min), 1 ) as total, ROUND( min, 1 ) as min, ROUND( max, 1 ) as max FROM archive_day_outTemp WHERE dateTime < %s AND min IS NOT NULL AND max IS NOT NULL ORDER BY total ASC LIMIT 1;"
% today_start_epoch
)
# Find the group_name for outTemp in database
outTemp_unit = converter.group_unit_dict["group_temperature"]
# Find the group_name for outTemp from the skin.conf
skin_outTemp_unit = self.generator.converter.group_unit_dict[
"group_temperature"
]
# Find the number of decimals to round to based on the skin.conf
outTemp_round = self.generator.skin_dict["Units"]["StringFormats"].get(
skin_outTemp_unit, "%.1f"
)
# Largest Daily Temperature Range Conversions
# Max temperature for this day
if year_outTemp_max_range_query is not None:
year_outTemp_max_range_max_tuple = (
year_outTemp_max_range_query[3],
outTemp_unit,
"group_temperature",
)
year_outTemp_max_range_max = (
outTemp_round
% self.generator.converter.convert(year_outTemp_max_range_max_tuple)[0]
)
# Min temperature for this day
year_outTemp_max_range_min_tuple = (
year_outTemp_max_range_query[2],
outTemp_unit,
"group_temperature",
)
year_outTemp_max_range_min = (
outTemp_round
% self.generator.converter.convert(year_outTemp_max_range_min_tuple)[0]
)
# Largest Daily Temperature Range total
year_outTemp_max_range_total = outTemp_round % (
float(year_outTemp_max_range_max) - float(year_outTemp_max_range_min)
)
# Replace the SQL Query output with the converted values
year_outTemp_range_max = [
year_outTemp_max_range_query[0],
locale.format_string("%g", float(year_outTemp_max_range_total)),
locale.format_string("%g", float(year_outTemp_max_range_min)),
locale.format_string("%g", float(year_outTemp_max_range_max)),
]
else:
year_outTemp_range_max = [
calendar.timegm(time.gmtime()),
locale.format_string("%.1f", 0),
locale.format_string("%.1f", 0),
locale.format_string("%.1f", 0),
]
# Smallest Daily Temperature Range Conversions
# Max temperature for this day
if year_outTemp_min_range_query is not None:
year_outTemp_min_range_max_tuple = (
year_outTemp_min_range_query[3],
outTemp_unit,
"group_temperature",
)
year_outTemp_min_range_max = (
outTemp_round
% self.generator.converter.convert(year_outTemp_min_range_max_tuple)[0]
)
# Min temperature for this day
year_outTemp_min_range_min_tuple = (
year_outTemp_min_range_query[2],
outTemp_unit,
"group_temperature",
)
year_outTemp_min_range_min = (
outTemp_round
% self.generator.converter.convert(year_outTemp_min_range_min_tuple)[0]
)
# Smallest Daily Temperature Range total
year_outTemp_min_range_total = outTemp_round % (
float(year_outTemp_min_range_max) - float(year_outTemp_min_range_min)
)
# Replace the SQL Query output with the converted values
year_outTemp_range_min = [
year_outTemp_min_range_query[0],
locale.format_string("%g", float(year_outTemp_min_range_total)),
locale.format_string("%g", float(year_outTemp_min_range_min)),
locale.format_string("%g", float(year_outTemp_min_range_max)),
]
else:
year_outTemp_range_min = [
calendar.timegm(time.gmtime()),
locale.format_string("%.1f", 0),
locale.format_string("%.1f", 0),
locale.format_string("%.1f", 0),
]
# All Time - Largest Daily Temperature Range Conversions
# Max temperature
if at_outTemp_max_range_query is not None:
at_outTemp_max_range_max_tuple = (
at_outTemp_max_range_query[3],
outTemp_unit,
"group_temperature",
)
at_outTemp_max_range_max = (
outTemp_round
% self.generator.converter.convert(at_outTemp_max_range_max_tuple)[0]
)
# Min temperature for this day
at_outTemp_max_range_min_tuple = (
at_outTemp_max_range_query[2],
outTemp_unit,
"group_temperature",
)
at_outTemp_max_range_min = (
outTemp_round
% self.generator.converter.convert(at_outTemp_max_range_min_tuple)[0]
)
# Largest Daily Temperature Range total
at_outTemp_max_range_total = outTemp_round % (
float(at_outTemp_max_range_max) - float(at_outTemp_max_range_min)
)
# Replace the SQL Query output with the converted values
at_outTemp_range_max = [
at_outTemp_max_range_query[0],
locale.format_string("%g", float(at_outTemp_max_range_total)),
locale.format_string("%g", float(at_outTemp_max_range_min)),
locale.format_string("%g", float(at_outTemp_max_range_max)),
]
else:
at_outTemp_range_max = [
calendar.timegm(time.gmtime()),
locale.format_string("%.1f", 0),
locale.format_string("%.1f", 0),
locale.format_string("%.1f", 0),
]
# All Time - Smallest Daily Temperature Range Conversions
# Max temperature for this day
if at_outTemp_min_range_query is not None:
at_outTemp_min_range_max_tuple = (
at_outTemp_min_range_query[3],
outTemp_unit,
"group_temperature",
)
at_outTemp_min_range_max = (
outTemp_round
% self.generator.converter.convert(at_outTemp_min_range_max_tuple)[0]
)
# Min temperature for this day
at_outTemp_min_range_min_tuple = (
at_outTemp_min_range_query[2],
outTemp_unit,
"group_temperature",
)
at_outTemp_min_range_min = (
outTemp_round
% self.generator.converter.convert(at_outTemp_min_range_min_tuple)[0]
)
# Smallest Daily Temperature Range total
at_outTemp_min_range_total = outTemp_round % (
float(at_outTemp_min_range_max) - float(at_outTemp_min_range_min)
)
# Replace the SQL Query output with the converted values
at_outTemp_range_min = [
at_outTemp_min_range_query[0],
locale.format_string("%g", float(at_outTemp_min_range_total)),
locale.format_string("%g", float(at_outTemp_min_range_min)),
locale.format_string("%g", float(at_outTemp_min_range_max)),
]
else:
at_outTemp_range_min = [
calendar.timegm(time.gmtime()),
locale.format_string("%.1f", 0),
locale.format_string("%.1f", 0),
locale.format_string("%.1f", 0),
]
# Rain lookups
# Find the group_name for rain in database
rain_unit = converter.group_unit_dict["group_rain"]
# Find the group_name for rain in the skin.conf
skin_rain_unit = self.generator.converter.group_unit_dict["group_rain"]
# Find the number of decimals to round the result based on the skin.conf
rain_round = self.generator.skin_dict["Units"]["StringFormats"].get(
skin_rain_unit, "%.2f"
)
# Rainiest Day
rainiest_day_query = wx_manager.getSql(
"SELECT dateTime, sum FROM archive_day_rain WHERE dateTime >= %s ORDER BY sum DESC LIMIT 1;"
% year_start_epoch
)
if rainiest_day_query is not None:
rainiest_day_tuple = (rainiest_day_query[1], rain_unit, "group_rain")
rainiest_day_converted = (
rain_round % self.generator.converter.convert(rainiest_day_tuple)[0]
)
rainiest_day = [
rainiest_day_query[0],
locale.format_string("%g", float(rainiest_day_converted)),
]
else:
rainiest_day = [calendar.timegm(time.gmtime()), locale.format_string("%.2f", 0)]
# All Time Rainiest Day
at_rainiest_day_query = wx_manager.getSql(
"SELECT dateTime, sum FROM archive_day_rain ORDER BY sum DESC LIMIT 1"
)
at_rainiest_day_tuple = (at_rainiest_day_query[1], rain_unit, "group_rain")
at_rainiest_day_converted = (
rain_round % self.generator.converter.convert(at_rainiest_day_tuple)[0]
)
at_rainiest_day = [
at_rainiest_day_query[0],
locale.format_string("%g", float(at_rainiest_day_converted)),
]
# Find what kind of database we're working with and specify the
# correctly tailored SQL Query for each type of database
data_binding = self.generator.config_dict["StdArchive"]["data_binding"]
database = self.generator.config_dict["DataBindings"][data_binding]["database"]
database_type = self.generator.config_dict["Databases"][database][
"database_type"
]
driver = self.generator.config_dict["DatabaseTypes"][database_type]["driver"]
if driver == "weedb.sqlite":
year_rainiest_month_sql = (
'SELECT strftime("%%m", datetime(dateTime, "unixepoch", "localtime")) as month, SUM( sum ) as total FROM archive_day_rain WHERE strftime("%%Y", datetime(dateTime, "unixepoch", "localtime")) = "%s" GROUP BY month ORDER BY total DESC LIMIT 1;'
% time.strftime("%Y", time.localtime(time.time()))
)
at_rainiest_month_sql = 'SELECT strftime("%m", datetime(dateTime, "unixepoch", "localtime")) as month, strftime("%Y", datetime(dateTime, "unixepoch", "localtime")) as year, SUM( sum ) as total FROM archive_day_rain GROUP BY month, year ORDER BY total DESC LIMIT 1;'
year_rain_data_sql = (
'SELECT dateTime, sum FROM archive_day_rain WHERE strftime("%%Y", datetime(dateTime, "unixepoch", "localtime")) = "%s" AND count > 0;'
% time.strftime("%Y", time.localtime(time.time()))
)
# The all stats from http://www.weewx.com/docs/customizing.htm
# doesn't seem to calculate "Total Rainfall for" all time stat
# correctly.
at_rain_highest_year_sql = 'SELECT strftime("%Y", datetime(dateTime, "unixepoch", "localtime")) as year, SUM( sum ) as total FROM archive_day_rain GROUP BY year ORDER BY total DESC LIMIT 1;'
elif driver == "weedb.mysql":
year_rainiest_month_sql = 'SELECT FROM_UNIXTIME( dateTime, "%%m" ) AS month, ROUND( SUM( sum ), 2 ) AS total FROM archive_day_rain WHERE year( FROM_UNIXTIME( dateTime ) ) = "{0}" GROUP BY month ORDER BY total DESC LIMIT 1;'.format(
time.strftime("%Y", time.localtime(time.time()))
) # Why does this one require .format() but the other's don't?
at_rainiest_month_sql = 'SELECT FROM_UNIXTIME( dateTime, "%%m" ) AS month, FROM_UNIXTIME( dateTime, "%%Y" ) AS year, ROUND( SUM( sum ), 2 ) AS total FROM archive_day_rain GROUP BY month, year ORDER BY total DESC LIMIT 1;'
year_rain_data_sql = (
'SELECT dateTime, ROUND( sum, 2 ) FROM archive_day_rain WHERE year( FROM_UNIXTIME( dateTime ) ) = "%s" AND count > 0;'
% time.strftime("%Y", time.localtime(time.time()))
)
# The all stats from http://www.weewx.com/docs/customizing.htm
# doesn't seem to calculate "Total Rainfall for" all time stat
# correctly.
at_rain_highest_year_sql = 'SELECT FROM_UNIXTIME( dateTime, "%%Y" ) AS year, ROUND( SUM( sum ), 2 ) AS total FROM archive_day_rain GROUP BY year ORDER BY total DESC LIMIT 1;'
# Rainiest month
year_rainiest_month_query = wx_manager.getSql(year_rainiest_month_sql)
if year_rainiest_month_query is not None:
year_rainiest_month_tuple = (
year_rainiest_month_query[1],
rain_unit,
"group_rain",
)
year_rainiest_month_converted = (
rain_round
% self.generator.converter.convert(year_rainiest_month_tuple)[0]
)
year_rainiest_month_name = calendar.month_name[
int(year_rainiest_month_query[0])
]
year_rainiest_month = [
year_rainiest_month_name,
locale.format_string("%g", float(year_rainiest_month_converted)),
]
else:
year_rainiest_month = ["N/A", 0.0]
# All time rainiest month
at_rainiest_month_query = wx_manager.getSql(at_rainiest_month_sql)
at_rainiest_month_tuple = (at_rainiest_month_query[2], rain_unit, "group_rain")
at_rainiest_month_converted = (
rain_round % self.generator.converter.convert(at_rainiest_month_tuple)[0]
)
at_rainiest_month_name = calendar.month_name[int(at_rainiest_month_query[0])]
at_rainiest_month = [
"%s, %s" % (at_rainiest_month_name, at_rainiest_month_query[1]),
locale.format_string("%g", float(at_rainiest_month_converted)),
]
# All time rainiest year
at_rain_highest_year_query = wx_manager.getSql(at_rain_highest_year_sql)
at_rain_highest_year_tuple = (
at_rain_highest_year_query[1],
rain_unit,
"group_rain",
)
at_rain_highest_year_converted = (
rain_round % self.generator.converter.convert(at_rain_highest_year_tuple)[0]
)
at_rain_highest_year = [
at_rain_highest_year_query[0],
locale.format_string("%g", float(at_rain_highest_year_converted)),
]
# Consecutive days with/without rainfall
# dateTime needs to be epoch. Conversion done in the template using #echo
year_days_with_rain_total = 0
year_days_without_rain_total = 0
year_days_with_rain_output = {}
year_days_without_rain_output = {}
year_rain_query = wx_manager.genSql(year_rain_data_sql)
for row in year_rain_query:
# Original MySQL way: CASE WHEN sum!=0 THEN @total+1 ELSE 0 END
if row[1] != 0:
year_days_with_rain_total += 1
else:
year_days_with_rain_total = 0
# Original MySQL way: CASE WHEN sum=0 THEN @total+1 ELSE 0 END
if row[1] == 0:
year_days_without_rain_total += 1
else:
year_days_without_rain_total = 0
year_days_with_rain_output[row[0]] = year_days_with_rain_total
year_days_without_rain_output[row[0]] = year_days_without_rain_total
if year_days_with_rain_output:
year_days_with_rain = max(
zip(
year_days_with_rain_output.values(),
year_days_with_rain_output.keys(),
)
)
else:
year_days_with_rain = [
locale.format_string("%.1f", 0),
calendar.timegm(time.gmtime()),
]
if year_days_without_rain_output:
year_days_without_rain = max(
zip(
year_days_without_rain_output.values(),
year_days_without_rain_output.keys(),
)
)
else:
year_days_without_rain = [
locale.format_string("%.1f", 0),
calendar.timegm(time.gmtime()),
]
at_days_with_rain_total = 0
at_days_without_rain_total = 0
at_days_with_rain_output = {}
at_days_without_rain_output = {}
at_rain_query = wx_manager.genSql(
"SELECT dateTime, ROUND( sum, 2 ) FROM archive_day_rain WHERE count > 0;"
)
for row in at_rain_query:
# Original MySQL way: CASE WHEN sum!=0 THEN @total+1 ELSE 0 END
if row[1] != 0:
at_days_with_rain_total += 1
else:
at_days_with_rain_total = 0
# Original MySQL way: CASE WHEN sum=0 THEN @total+1 ELSE 0 END
if row[1] == 0:
at_days_without_rain_total += 1
else:
at_days_without_rain_total = 0
at_days_with_rain_output[row[0]] = at_days_with_rain_total
at_days_without_rain_output[row[0]] = at_days_without_rain_total
if len(at_days_with_rain_output) > 0:
at_days_with_rain = max(
zip(at_days_with_rain_output.values(), at_days_with_rain_output.keys())
)
else:
at_days_with_rain = (0, 0)
if len(at_days_without_rain_output) > 0:
at_days_without_rain = max(
zip(
at_days_without_rain_output.values(),
at_days_without_rain_output.keys(),
)
)
else:
at_days_without_rain = (0, 0)
# This portion is right from the weewx sample
# http://www.weewx.com/docs/customizing.htm
all_stats = TimespanBinder(
timespan,
db_lookup,
formatter=self.generator.formatter,
converter=self.generator.converter,
skin_dict=self.generator.skin_dict,
)
# Get the unit label from the skin dict for speed.
windSpeed_unit = self.generator.skin_dict["Units"]["Groups"]["group_speed"]
windSpeed_unit_label = self.generator.skin_dict["Units"]["Labels"][
windSpeed_unit
]
# ==============================================================================
# Get NOAA Data
# ==============================================================================
years = []
noaa_header_html = ""
default_noaa_file = ""
noaa_dir = html_root + "/NOAA/"
try:
noaa_file_list = os.listdir(noaa_dir)
# Generate a list of years based on file name
for f in noaa_file_list:
filename = f.split(".")[0] # Drop the .txt
year = filename.split("-")[1]
years.append(year)
# Remove duplicates with set, and sort numerically, then reverse
# sort with [::-1] oldest year last
# first_year = years[0]
# final_year = years[-1]
years = sorted(set(years))[::-1]