-
Notifications
You must be signed in to change notification settings - Fork 1
/
weather.py
873 lines (787 loc) · 25.3 KB
/
weather.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
import ttxcolour
import ttxutils
import ttxpage
import weathermap
from wx_ids import regions, city_ids, region_ids, observation_ids, fiveday_ids
import metoffer
import newsreel
import dateutil.parser
import dateutil.tz
import dateutil.utils
import datetime
import pickle
import textwrap
import re
import types
import config
_config = config.Config().config
colours_a = [
ttxcolour.ALPHACYAN,
ttxcolour.ALPHAGREEN,
ttxcolour.ALPHAMAGENTA,
ttxcolour.ALPHAYELLOW,
ttxcolour.ALPHARED,
ttxcolour.ALPHAWHITE,
ttxcolour.ALPHABLUE,
]
colours_m = [
ttxcolour.MOSAICCYAN,
ttxcolour.MOSAICGREEN,
ttxcolour.MOSAICMAGENTA,
ttxcolour.MOSAICYELLOW,
ttxcolour.MOSAICRED,
ttxcolour.MOSAICWHITE,
ttxcolour.MOSAICBLUE,
]
weathers = {
0: "Clear",
1: "Sunny",
2: "Partly cloudy",
3: "Partly cloudy",
4: "Not used",
5: "Mist",
6: "Fog",
7: "Cloudy",
8: "Overcast",
9: "Lt.rain shower",
10: "Lt.rain shower",
11: "Drizzle",
12: "Light rain",
13: "Hvy.rain shower",
14: "Hvy.rain shower",
15: "Heavy rain",
16: "Sleet shower",
17: "Sleet shower",
18: "Sleet",
19: "Hail shower",
20: "Hail shower",
21: "Hail",
22: "Lt.snow shower",
23: "Lt.snow shower",
24: "Light snow",
25: "Hvy.snow shower",
26: "Hvy.snow shower",
27: "Heavy snow",
28: "Thunder shower",
29: "Thunder shower",
30: "Thunder",
}
short_weathers = {
0: "clear",
1: "sunny",
2: "pt cldy",
3: "pt cldy",
4: "notused",
5: "mist",
6: "fog",
7: "cloudy",
8: "ovrcast",
9: "lt rain",
10: "lt rain",
11: "drizzle",
12: "lt.rain",
13: "hy shwr",
14: "hy shwr",
15: "hy rain",
16: "sleet s",
17: "sleet s",
18: "sleet",
19: "hail sh",
20: "hail sh",
21: "hail",
22: "lt snow",
23: "lt snow",
24: "lt.snow",
25: "hy snow",
26: "hy snow",
27: "hy.snow",
28: "thnd sh",
29: "thnd sh",
30: "thunder",
}
reduction_mapping = {
2: 7,
3: 7,
9: 12,
10: 12,
13: 15,
14: 15,
16: 18,
17: 18,
19: 21,
20: 21,
22: 24,
23: 24,
25: 27,
26: 27,
28: 30,
29: 30,
}
maporder = {
"highlands": 0,
"grampian": 1,
"tayside": 2,
"central": 3,
"northeast": 4,
"nireland": 5,
"yorks": 6,
"northwest": 7,
"wales": 8,
"midlands": 9,
"east": 10,
"west": 11,
"southwest": 12,
"south": 13,
"southeast": 14,
}
class WeatherCache(object):
def __init__(self, cache_hours=6):
if "met_office_api" in _config:
self._M = metoffer.MetOffer(_config["met_office_api"])
else:
self._M = None
self.cache_hours = cache_hours
self.cache = dict()
cachedir = _config["cachedir"]
try:
with open(f"{cachedir}/weather.cache", "rb") as f:
self.cache = pickle.load(f)
except:
pass
def __del__(self):
cachedir = _config["cachedir"]
if self.cache:
with open(f"{cachedir}/weather.cache", "wb") as f:
pickle.dump(self.cache, f)
def valid(self):
return self._M is not None
@staticmethod
def _cache_value_valid(isodate, offset):
now = dateutil.utils.default_tzinfo(
datetime.datetime.now(), dateutil.tz.gettz()
)
time = dateutil.utils.default_tzinfo(
dateutil.parser.isoparse(isodate), dateutil.tz.gettz()
)
return time + datetime.timedelta(hours=offset) > now
def loc_forecast(self, request, step, isotime=None, cache_hours=None):
if cache_hours is None:
cache_hours = self.cache_hours
key = f"{request}%{step}%{isotime}"
if key in self.cache:
value = self.cache[key]
if self._cache_value_valid(value.data_date, cache_hours):
return value
w = self._M.loc_forecast(request, step, isotime=isotime)
value = metoffer.Weather(w)
self.cache[key] = value
return value
def text_forecast(self, field, request, cache_hours=None):
if cache_hours is None:
cache_hours = self.cache_hours
key = f"{field}!{request}"
if key in self.cache:
value = self.cache[key]
if self._cache_value_valid(value.issued_at, cache_hours):
return value
w = self._M.text_forecast(field, request)
value = metoffer.TextForecast(w)
self.cache[key] = value
return value
def loc_observations(self, request, cache_hours=None):
if cache_hours is None:
cache_hours = self.cache_hours
key = f"observations!{request}"
if key in self.cache:
value = self.cache[key]
if value and self._cache_value_valid(value.data_date, cache_hours):
return value
w = self._M.loc_observations(request)
try:
value = metoffer.Weather(w)
except KeyError as e:
print(f"KeyError: {key} {e}")
try:
data_date = w["SiteRep"]["DV"]["dataDate"]
except KeyError:
data_date = dateutil.utils.default_tzinfo(
datetime.datetime.now(), dateutil.tz.gettz()
).isoformat()
value = types.SimpleNamespace(data_date=data_date,
data={})
except Exception as e:
print(f"ERROR: {key}")
print(f"{e.__class__.__name__}: {str(e)}")
print(repr(w))
raise
self.cache[key] = value
return value
def firstmap(locs):
slocs = sorted(locs, key=lambda l: maporder[l])
return slocs[0]
def weathermaps(W):
cfg = _config["weather"]
if datetime.datetime.now().hour > 16:
advance = 1
else:
advance = 0
pagenum = cfg["maps"]
subpage = 1
page = ttxpage.TeletextPage("Weather Maps", pagenum, time=10)
for index in range(3):
caption = None
advanced = False
page.header(pagenum, subpage, status=0xC000)
region_wx = dict()
region_wx_reduced = dict()
for reg_name, reg_id in region_ids.items():
w = W.loc_forecast(reg_id, metoffer.DAILY)
now = w.data[index + advance]
if (not advanced and
now["timestamp"][0].date() < datetime.datetime.now().date()):
# handle overnight transition
advanced = True
advance += 1
now = w.data[index + advance]
wx_type = now["Weather Type"][0]
wx_type_full = weathers.get(wx_type, "N/A")
if wx_type_full in region_wx:
region_wx[wx_type_full].append(reg_name)
else:
region_wx[wx_type_full] = [reg_name]
if wx_type in reduction_mapping:
wx_type = reduction_mapping[wx_type]
wx_type_reduced = weathers.get(wx_type, "N/A")
if wx_type_reduced in region_wx_reduced:
region_wx_reduced[wx_type_reduced].append(reg_name)
else:
region_wx_reduced[wx_type_reduced] = [reg_name]
if len(region_wx.keys()) > len(colours_a):
# Reduce colours in weather map
region_wx = region_wx_reduced
map = weathermap.WeatherMap()
reg_mapping = dict()
i = 0
for wx, locs in region_wx.items():
if i >= len(colours_a):
print(f"Out of colours on weather map {subpage}", flush=True)
i = 0
map.plot_text(firstmap(locs), colours_a[i], wx)
for loc in locs:
reg_mapping[loc] = colours_m[i]
i += 1
for city_name, city_id in city_ids.items():
w = W.loc_forecast(city_id, metoffer.DAILY)
now = w.data[index + advance]
if not caption:
caption = now["timestamp"][0].strftime("%A")
if now["timestamp"][1] == "Night":
caption += " night"
if now["timestamp"][1] == "Day":
wx_temp = now["Day Maximum Temperature"][0]
else:
wx_temp = now["Night Minimum Temperature"][0]
map.plot_temp(city_name, wx_temp)
# This needs to go after temperatures, as it changes
# the colours following the numbers
map.plot_borders(reg_mapping)
title = f"Weather for {caption}"
title = f"{title:^39}"[2:]
page.addline(
1,
ttxcolour.blue()
+ ttxcolour.colour(ttxcolour.NEW_BACK)
+ f"{ttxcolour.yellow()}{title}",
)
l = 2
subpagenum = chr(ttxcolour.ALPHAWHITE) + f"{subpage}/3"
map.put_text(2, 35, subpagenum)
for ll in map.map_lines():
page.addline(l, ll)
l += 1
title = "From the Met Office"
title = f"{title:^39}"[2:]
page.addline(
23,
ttxcolour.blue()
+ ttxcolour.colour(ttxcolour.NEW_BACK)
+ f"{ttxcolour.yellow()}{title}",
)
page.addline(
24, ttxutils.decode("€ARegional €BSport €CWeather €FMain Menu")
)
page.addfasttext(
cfg["regional"], 0x300, cfg["index"], 0x100, 0x8FF, 0x199
)
subpage += 1
page.save(add_to_newsreel=True)
def weatherregion(W):
cfg = _config["weather"]
region = _config["bbc_news_regions"][_config["bbc_news_region"]]
wx_text = W.text_forecast(
metoffer.REGIONAL_FORECAST, regions[region["weather"]]
)
headline = wx_text.data[0][1]
head1 = wx_text.data[1][0].replace(":", "")
head2 = wx_text.data[2][0].replace(":", "")
body1 = wx_text.data[1][1]
body2 = wx_text.data[2][1]
min = None
max = None
if "Minimum Temperature" in body1:
s = re.search(r"Minimum Temperature (-?\d+)C", body1)
min = s[1]
s = re.search(r"Maximum Temperature (-?\d+)C", body2)
max = s[1]
else:
s = re.search(r"Minimum Temperature (-?\d+)C", body2)
min = s[1]
s = re.search(r"Maximum Temperature (-?\d+)C", body1)
max = s[1]
body1 = re.sub(r" M(ax|in)imum Temperature -?\d+C.*", r"", body1)
body2 = re.sub(r" M(ax|in)imum Temperature -?\d+C.*", r"", body2)
header = [
"€Wh,,lh,,lh,,l€T||,<<|,,|,,|,,|l<l,,<,,l||",
"€Wj 1nj 1nj =n€T€]€S¬jj5¬shw{4k7juz5¬sjw{%",
"€W*,,.*,,.*,,.€T€]€Sozz%¬pj5j5j5j5j5¬pj5j5",
"1234567890123€T//-,,/,,-.-.-.-.-.,,-.-.//",
]
footer = [
"€T€]€G REGIONAL€CNews€G160€CWeather€G302",
"€T€]€GNATIONAL€CMain menu€G100€CWeather€G400",
"€AOutlook €BSport €CWeather €FMain Menu",
]
short_name = f"{region['medium']:^13.13}"
header[3] = short_name + header[3][13:]
page = ttxpage.TeletextPage("Weather Page", cfg["regional"])
subpage = 1
for h, b in [(head1, body1), (head2, body2)]:
lines = textwrap.wrap(page.fixup(b), 19)
rows = ["", f"{ttxcolour.yellow()}{h.upper()}", ""]
for l in range(13):
try:
t = lines[l]
except:
t = ""
t = (
f"{ttxcolour.green()}{t:<19.19}"
f"{ttxcolour.colour(ttxcolour.MOSAICYELLOW)}5"
)
if l == 0:
t += f" {ttxcolour.yellow()}STATISTICS"
elif l == 2:
t += f" {ttxcolour.white()}Maximum"
elif l == 3:
t += f"{ttxcolour.white()}Temperature{ttxcolour.yellow()}{max}C"
elif l == 5:
t += f" {ttxcolour.white()}Minimum"
elif l == 6:
t += f"{ttxcolour.white()}Temperature{ttxcolour.yellow()}{min}C"
rows.append(t)
bot = f"{subpage}/2"
rows.append(f"{bot:>39.39}")
page.header(cfg["regional"], subpage, status=0xC000)
line = 1
for l in header:
page.addline(line, ttxutils.decode(l))
line += 1
for ll in rows:
page.addline(line, ll)
line += 1
line = 25 - len(footer)
for l in footer:
page.addline(line, ttxutils.decode(l))
line += 1
page.addfasttext(
cfg["national"], 0x300, cfg["index"], 0x100, 0x8FF, 0x199
)
subpage += 1
page.save()
return headline
def weatheroutlook(W):
cfg = _config["weather"]
wx_text = W.text_forecast(metoffer.REGIONAL_FORECAST, regions["uk"])
headline = wx_text.data[0][1]
page = ttxpage.TeletextPage("Weather Page", cfg["national"])
pages = []
for i in range(3):
head = wx_text.data[i + 1][0].replace(":", "")
head = textwrap.wrap(page.fixup(head), 39)
body = wx_text.data[i + 1][1]
body = re.sub(r" M(ax|in)imum Temperature \d+C.*", r"", body)
body = textwrap.wrap(page.fixup(body), 39)
block = []
for h in head:
block.append(f" {h:<.39}")
for b in body:
block.append(f"{ttxcolour.cyan()}{b:<.39}")
if len(pages) and len(pages[-1]) + len(block) + 1 <= 15:
pages[-1].append('')
pages[-1].extend(block)
else:
pages.append(block)
header = [
"␗j#3kj#3kj#3k␔␝␑␓h44|h<h<|(|$|h4|$|l ",
"␗j $kj $kj 'k␔␝␑␓*uu?jwj7␡ ␡ ␡k5␡1␡k4 ",
'␗"###"###"###␔////,,.-,-.,/,/,-.,.,-.///',
]
title = "From the Met Office"
title = f"{title:^39}"[2:]
footer = [
ttxcolour.blue()
+ ttxcolour.colour(ttxcolour.NEW_BACK)
+ f"{ttxcolour.yellow()}{title}",
ttxutils.decode("€AUK cities €BSport €CWeather €FMain Menu"),
]
for subpage in range(len(pages)):
rows = []
top = f"{subpage + 1}/{len(pages)}"
rows.append(f"{top:>39.39}")
rows.append(" UK WEATHER OUTLOOK")
rows.append("")
rows.extend(pages[subpage])
page.header(cfg["national"], subpage + 1, status=0xC000)
line = 1
for l in header:
page.addline(line, ttxutils.decode(l))
line += 1
for l in rows:
page.addline(line, l)
line += 1
line = 25 - len(footer)
for l in footer:
page.addline(line, l)
line += 1
page.addfasttext(
cfg["observations"], 0x300, cfg["index"], 0x100, 0x8FF, 0x199
)
page.save(add_to_newsreel=True)
return headline
def weatherobservations(W):
cfg = _config["weather"]
minimum = 9999
maximum = -9999
rows = []
timestamp = None
for city, num in observation_ids.items():
obs = W.loc_observations(num, cache_hours=1).data
time = None
temp = '-'
wind_speed = '-'
wind_dir = '-'
pressure = '-'
trend = '-'
weather_type = None
for o in obs:
if "timestamp" in o:
time = o["timestamp"][0]
if "Temperature" in o:
temp = round(float(o["Temperature"][0]))
if "Wind Speed" in o:
wind_speed = o["Wind Speed"][0]
if "Wind Direction" in o:
wind_dir = o["Wind Direction"][0]
if "Pressure" in o:
pressure = o["Pressure"][0]
if "Pressure Tendency" in o:
trend = o["Pressure Tendency"][0]
if "Weather Type" in o:
weather_type = o["Weather Type"][0]
if len(rows) % 2 == 1:
row_colour = ttxcolour.white()
else:
row_colour = ttxcolour.cyan()
if trend == "F":
trend_colour = ttxcolour.green()
elif trend == "S":
trend_colour = ttxcolour.white()
else:
trend_colour = ttxcolour.cyan()
row = f"{row_colour}{city:<12.12}{temp:>4}{wind_dir:>4}{wind_speed:>3}"
row += f"{pressure:>6}{trend_colour}{trend}{row_colour}"
if weather_type is not None:
row += short_weathers[weather_type]
else:
row += "n/a"
rows.append(row)
if time is not None and (timestamp is None or time > timestamp):
timestamp = time
if temp and temp != '-':
if temp < minimum:
minimum = temp
if temp > maximum:
maximum = temp
header = [
"␗j#3kj#3kj#3k␔␝␑␓h44|h<h<|(|$|h4|$|l ",
"␗j $kj $kj 'k␔␝␑␓*uu?jwj7␡ ␡ ␡k5␡1␡k4 ",
'␗"###"###"###␔////,,.-,-.,/,/,-.,.,-.///',
]
temps_c = []
temps_f = []
steps = (maximum - minimum) / 10
if steps < 1:
steps = 1
minimum = (minimum + maximum) // 2 - 5
for i in range(11):
temp_c = round(minimum + i * steps)
temp_f = round((temp_c * 1.8) + 32)
c = str(temp_c)
f = str(temp_f)
l = max(len(c), len(f))
temps_c.append(f"{c:>{l}}")
temps_f.append(f"{f:>{l}}")
footer = []
footer.append(ttxutils.decode(" ␃pressure␆R␃rising␇S␃steady␂F␃falling"))
footer.append("")
back = (
ttxcolour.blue()
+ ttxcolour.colour(ttxcolour.NEW_BACK)
+ ttxcolour.yellow()
)
footer.append(f"{back}C= " + " ".join(temps_c))
footer.append(f"{back}F= " + " ".join(temps_f))
footer.append(
ttxutils.decode("€AUK 5 day€B Sport €CWeather €FMain Menu")
)
page = ttxpage.TeletextPage("Weather Reports", cfg["observations"])
for subpage in (1, 2, 3):
body = []
top = f"{subpage}/3"
body.append(f"{top:>39.39}")
time = timestamp.strftime("%H%M")
body.append(f"{ttxcolour.yellow()}CURRENT UK WEATHER: Report at {time}")
body.append("")
body.append(ttxutils.decode(" ␃temp wind pres"))
body.append(ttxutils.decode(" ␇C mph mB"))
base = (subpage - 1) * 10
for l in rows[base : base + 10]:
body.append(l)
page.header(cfg["observations"], subpage, status=0xC000)
line = 1
for l in header:
page.addline(line, ttxutils.decode(l))
line += 1
for l in body:
page.addline(line, l)
line += 1
line = 25 - len(footer)
for l in footer:
page.addline(line, l)
line += 1
page.addfasttext(
cfg["fiveday"], 0x300, cfg["index"], 0x100, 0x8FF, 0x199
)
subpage += 1
page.save()
def weatherfiveday(W):
cfg = _config["weather"]
maximum = -9999
minimum = 9999
today = None
entries = []
for city, num in fiveday_ids.items():
wx = W.loc_forecast(num, metoffer.DAILY).data
if today is None:
today = wx[0]["timestamp"][0]
entry = [city]
for i in range(5):
wx_type = short_weathers.get(wx[i * 2]["Weather Type"][0], "N/A")
max_temp = int(wx[i * 2]["Day Maximum Temperature"][0])
min_temp = int(wx[i * 2 + 1]["Night Minimum Temperature"][0])
date = wx[i * 2]["timestamp"][0]
entry.append(
f"{date.strftime('%a')}" f"{max_temp:>4}{min_temp:>4} {wx_type}"
)
if max_temp > maximum:
maximum = max_temp
if min_temp < minimum:
minimum = min_temp
entries.append(entry)
header = [
"␗j#3kj#3kj#3k␔␝␑␓h44|h<h<|(|$|h4|$|l ",
"␗j $kj $kj 'k␔␝␑␓*uu?jwj7␡ ␡ ␡k5␡1␡k4 ",
'␗"###"###"###␔////,,.-,-.,/,/,-.,.,-.///',
]
temps_c = []
temps_f = []
steps = (maximum - minimum) / 10
if steps < 1:
steps = 1
minimum = (minimum + maximum) // 2 - 5
for i in range(11):
temp_c = round(minimum + i * steps)
temp_f = round((temp_c * 1.8) + 32)
c = str(temp_c)
f = str(temp_f)
l = max(len(c), len(f))
temps_c.append(f"{c:>{l}}")
temps_f.append(f"{f:>{l}}")
footer = []
back = (
ttxcolour.blue()
+ ttxcolour.colour(ttxcolour.NEW_BACK)
+ ttxcolour.yellow()
)
footer.append(f"{back}C= " + " ".join(temps_c))
footer.append(f"{back}F= " + " ".join(temps_f))
footer.append(
ttxutils.decode("€AUK map €B Sport €CWeather €FMain Menu")
)
page = ttxpage.TeletextPage("Weather Five Day", cfg["fiveday"])
numpages = (len(entries) + 3) // 4
for sub in range(numpages):
body = []
top = f"{sub+1}/{numpages}"
body.append(f"{top:>39.39}")
body.append(
ttxcolour.yellow()
+ "UK FIVE DAY FORECAST FROM "
+ today.strftime("%e %b").strip()
)
body.append(ttxcolour.green() + "max for 0600-1800 min for 1800-0600")
body.append(
ttxcolour.yellow()
+ " max min"
+ ttxcolour.white()
+ "C "
+ ttxcolour.yellow()
+ " max min"
+ ttxcolour.white()
+ "C"
)
for i in range(2):
count = 0
c1 = []
c2 = []
offset = (sub * 4) + i
if offset < len(entries):
c1 = entries[offset]
offset = (sub * 4) + i + 2
if offset < len(entries):
c2 = entries[offset]
while len(c1) and len(c2):
row = ""
if count % 2:
row += ttxcolour.cyan()
else:
row += ttxcolour.white()
if len(c1):
row += f"{c1[0]:<19.19} "
c1 = c1[1:]
if len(c2):
row += c2[0]
c2 = c2[1:]
body.append(row)
count += 1
body.append("")
page.header(cfg["fiveday"], sub + 1, status=0xC000)
line = 1
for l in header:
page.addline(line, ttxutils.decode(l))
line += 1
for l in body:
page.addline(line, l)
line += 1
line = 25 - len(footer)
for l in footer:
page.addline(line, l)
line += 1
page.addfasttext(cfg["maps"], 0x300, cfg["index"], 0x100, 0x8FF, 0x199)
page.save()
def weatherindex(regionhead, ukhead):
cfg = _config["weather"]
page = ttxpage.TeletextPage("Weather Index", cfg["index"])
regionheads = textwrap.wrap(page.fixup(regionhead), 35)
regionhead = f"{regionheads[0]:<35.35}"
regionheads = regionheads[1:]
headline = "WEATHER NEWS:¬" + page.fixup(ukhead)
headlines = textwrap.wrap(headline, 39)
for i in range(len(headlines)):
l = headlines[i]
if i == 0:
l = ttxcolour.yellow() + l.replace("¬", ttxcolour.green())
elif i == len(headlines) - 1:
l = (
ttxcolour.green()
+ f"{l:<35.35}"
+ ttxcolour.yellow()
+ f"{cfg['maps']:03x}"
)
else:
l = ttxcolour.green() + l
headlines[i] = l
header = [
"␗j#3kj#3kj#3k␔␝␑␓h44|h<h<|(|$|h4|$|l ",
"␗j $kj $kj 'k␔␝␑␓*uu?jwj7␡ ␡ ␡k5␡1␡k4 ",
'␗"###"###"###␔////,,.-,-.,/,/,-.,.,-.///',
]
middle = [
"␃UK␄````````````````````````````````````",
"␆Forecast maps ␃401␆UK Cities 5 Day␃406",
"␆Regions ␃402␆ ␃ ",
"␆National ␃403␆ ␃ ",
"␆Current Weather␃404 ",
" ",
]
attrib = "From the Met Office"
attrib = f"{attrib:^39}"[2:]
footer = headlines + [
"",
ttxcolour.blue()
+ ttxcolour.colour(ttxcolour.NEW_BACK)
+ f"{ttxcolour.yellow()}{attrib}",
ttxutils.decode("€AMaps €BRegional €COutlook €FMain Menu"),
]
page.header(cfg["index"])
line = 1
for l in header:
page.addline(line, ttxutils.decode(l))
line += 1
page.addline(
line,
ttxcolour.colour(ttxcolour.DOUBLE_HEIGHT)
+ regionhead
+ ttxcolour.yellow()
+ f"{cfg['regional']:03x}",
)
line += 2
for l in regionheads:
page.addline(line, " " + l)
line += 1
line += 1
for l in middle:
page.addline(line, ttxutils.decode(l))
line += 1
line = 25 - len(footer)
for l in footer:
page.addline(line, l)
line += 1
page.addfasttext(
cfg["maps"], cfg["regional"], cfg["national"], 0x100, 0x8FF, 0x199
)
page.save()
def makeweather():
W = WeatherCache()
if not W.valid():
print("Missing 'met_office_api' in configuration. Skipping weather.")
return []
newsreel.Newsreel().add_weather()
weathermaps(W)
regionheadline = weatherregion(W)
ukheadline = weatheroutlook(W)
weatherobservations(W)
weatherfiveday(W)
weatherindex(regionheadline, ukheadline)
return [
[
dict(section="Weather", short_title=ukheadline),
_config["weather"]["maps"],
]
]
def main():
config.Config().add("defaults.yaml")
config.Config().add("pm.yaml")
config.Config().load()
makeweather()
if __name__ == "__main__":
main()