This repository has been archived by the owner on Oct 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
pyyrascii.py
executable file
·390 lines (321 loc) · 13.2 KB
/
pyyrascii.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PyYrAscii
-------
PyYrAscii is a simple python grapher for using Yr.no’s weather data API.
You are welcome to participate in this project!
"""
__version__ = '20180929'
__url__ = 'https://github.com/ways/pyyrascii'
__license__ = 'GPL License'
import socketserver, sys, math, random
import pyyrlib # https://github.com/ways/pyyrlib
import pyofc # https://github.com/ways/pyofflinefilecache
verbose = False
def wind_symbols ():
return {
"N":" N", "NNE":"NE", "NE":"NE", "ENE":"NE", \
"E":" E", "ESE":"SE", "SE":"SE", "SSE":"SE", \
"S":" S", "SSW":"SW", "SW":"SW", "WSW":"SW", \
"W":" W", "WNW":"NW", "NW":"NW", "NNW":"NW"}
def c_to_f (c=0):
return int(c*9/5+32)
def get_pyyrascii (location, offset = 0, hourstep = 1, screenwidth = 80,
imperial = False):
weatherdata, source = pyyrlib.returnWeatherData(location, True)
if not weatherdata:
return False, False
offset = int(offset)
hourstep = int(hourstep)
screenwidth = int(screenwidth)
# Init graph
ret = "" #all output goes here
graph=dict()
tempheight = 10+1
timeline = 13
windline = 15
windstrline = 16
graph[timeline] = " " #time
graph[timeline+1] = " " #date line
graph[windline] = " " #wind
graph[windstrline] = " " #wind strenght
temphigh = -99
templow = 99
tempstep = -1
hourcount = int((screenwidth-14)/3 + offset)
# Rain in graph:
rainheight = 10
rainstep = -1
rainhigh = 0 #highest rain on graph
wind = wind_symbols()
sunrise = None
sunset = None
if verbose:
print("offset %s, hourstep %s, hourcount %s" % (offset, hourstep, hourcount))
# Convert to imperial if needed:
if imperial:
for tid in range(len(weatherdata['tabular'][offset:hourcount])):
weatherdata['tabular'][tid]['temperature'] = c_to_f(int(weatherdata['tabular'][tid]['temperature']))
#collect temps, rain from xml
for item in weatherdata['tabular'][offset:hourcount]:
if int(item['temperature']) > temphigh:
temphigh = int(item['temperature'])
if int(item['temperature']) < templow:
templow = int(item['temperature'])
if math.ceil(float(item['precipitation'])) > rainhigh:
rainhigh = math.ceil(float(item['precipitation']))
rainhighmax = 0
try:
rainhighmax = math.ceil(float(item['precipitationmax']))
except KeyError:
pass
if rainhighmax > rainhigh:
rainhigh = rainhighmax
if verbose:
print("high",temphigh,"low",templow,"rainhigh",rainhigh)
#scale y-axis. default = -1
if tempheight <= (temphigh - templow):
tempstep = -2
if verbose:
print("Upped tempstep")
#sunrise
if weatherdata['sunrise']:
sunrise = str(weatherdata['sunrise'])[11:13] #2014-11-21T08:28:42
if weatherdata['sunset']:
sunset = str(weatherdata['sunset'])[11:13] #2014-11-21T08:28:42
if verbose:
print('sunrise' + sunrise + 'sunset' + sunset)
if temphigh == templow:
templow = temphigh-1
#create temp range
temps=[]
for t in range(int(temphigh), int(templow)-1, tempstep):
temps.append(t)
if verbose:
print("temps",temps)
#extend temp range
for t in range(0, tempheight):
if len(temps)+1 < tempheight:
if t%2 == 0: #extend down
temps.append( temps[len(temps)-1] - abs(tempstep) )
else: #extend up
temps = [ temps[0] + abs(tempstep) ] + temps
if verbose:
print("temps",temps)
#write temps to graph
for i in range(1, tempheight):
try:
graph[i] = str(temps[i-1]).rjust(3, ' ')
except IndexError: #list empty
pass
#create rainaxis
#TODO: make this scale
rainaxis = []
for r in range(rainheight, 0, rainstep):
if r <= rainhigh: # + 1
rainaxis.append('%2.0f mm ' % r)
else:
rainaxis.append(' ')
if verbose:
print("rain axis",str(rainaxis))
#draw graph elements:
time=[]
for item in weatherdata['tabular'][offset:hourcount:hourstep]:
# Rain
rain = math.ceil(float(item['precipitation']))
rainmax = 0 #max rain for this hour
try:
rainmax = math.ceil(float(item['precipitationmax']))
if verbose:
print("precmax", rainmax)
except KeyError:
pass
# Wind on x axis
graph[windline] += " " + \
(wind[ item['windDirection']['code'] ] \
if 0.0 != float(item['windSpeed']['mps']) else " O")
# Wind strength on x axis
graph[windstrline] += " " + '%2.0f' % float(item['windSpeed']['mps'])
# Time on x axis
spacer=' '
date=str(item['from'])[0:10]
hour=str(item['from'])[11:13] #2012-01-17T21:00
if sunrise and sunset and \
int(sunrise) < int(hour) and \
int(sunset) > int(hour):
spacer='_'
graph[timeline] += spacer + hour
# Create time range
time.append(str(item['from'])[11:13])
# Date
if '00' == hour:
graph[timeline+1] += date
else:
graph[timeline+1] += ' '
#for each y (temp) look for matching temp, draw graph
for i in range(1, tempheight):
#draw temp
try:
#parse out numbers to be compared
temptomatch = [ int(item['temperature']) ]
tempingraph = int(graph[i][:3].strip())
if tempstep < -1: #TODO: this should scale higher than one step
temptomatch.append(temptomatch[0] - 1)
if tempingraph in temptomatch:
if int(item['symbolnumber']) in [3,4]: #partly
graph[i] += "^^^"
elif int(item['symbolnumber']) in [5,7,8,9,10,12,13]: #clouded
graph[i] += "==="
elif int(item['symbolnumber']) in [6,11,14,20,21,22,23]: #lightning
graph[i] += "=V="
elif int(item['symbolnumber']) == 15: #fog
graph[i] += "###"
elif int(item['symbolnumber']) == 2: #light clouds
graph[i] += "=--"
elif int(item['symbolnumber']) in [1]: #clear
graph[i] += "---"
else: #Shouldn't hit this
graph[i] += "???"
else:
graph[i] += " "
except KeyError:
continue
#compare rain, and print
#TODO: scaling
if (rain != 0) and (rain > 10-i):
if int(item['symbolnumber']) in [7,12]: #sleet
rainsymbol = "!"
elif int(item['symbolnumber']) in [8,13]: #snow
rainsymbol = "*"
else: #if int(item['symbolnumber']) in [5,6,9,10,11,14]: #rain
rainsymbol = "|"
if 0 > int(item['temperature']): #rain but cold
rainsymbol = "*"
if verbose:
print("rainmax: ", rainmax,"i",i,"rain",rain)
#if overflow, print number at top
if rain > 10 and i == 1:
rainsymbol = '%2.0f' % rain
graph[i] = graph[i][:-2] + rainsymbol
else:
#print rainmax if larger than rain.
if rainmax > rain:
try:
graph[i-1] = graph[i-1][:-1] + "'"
except UnboundLocalError:
print("Err2: " + str(item['symbolnumber']))
except KeyError:
pass
#print rain
try:
graph[i] = graph[i][:-1] + rainsymbol
except UnboundLocalError:
print("Err: " + str(item['symbolnumber']))
#Legends
graph[0] = " 'C" + str.rjust('Rain (mm) ', screenwidth-3)
if imperial:
graph[0] = " 'F" + str.rjust('Rain', screenwidth-9)
graph[windline] += " Wind dir."
graph[windstrline] += " Wind(mps)"
graph[timeline] += " Hour"
#header
headline = "-= Meteogram for " + source_to_concise_string(source)
if location.isdigit():
headline += " for the next " + str(hourcount) + " hours"
headline += " =-"
ret += str.center(headline, screenwidth) + "\n"
#add rain to graph
for i in range(1, tempheight):
try:
graph[i] += rainaxis[i-1]
except IndexError:
pass
for k in sorted(graph.keys()):
ret += graph[k] + "\n"
#legend
ret += "\nLegend left axis: - Sunny ^ Scattered = Clouded =V= Thunder # Fog" +\
"\nLegend right axis: | Rain ! Sleet * Snow\n"
appendix = list()
appendix.append('[Weather forecast from yr.no, delivered by the Norwegian Meteorological ' +\
'Institute and the NRK.]')
appendix.append('[Try finger @graph.no for more info.]')
appendix.append('[Mail a "thank you" to [email protected] if you like the service.]')
#appendix.append('[Version ' + __version__ + ']')
appendix.append('[Project home: ' + __url__ + ']')
#appendix.append('[Hi mom!]')
#appendix.append('[Your ad here? (Forget it!)]')
appendix.append('[Blog at http://0p.no]')
#appendix.append('[Finger not available? Use echo oslo|nc graph.no finger]')
#appendix.append('[Thumbs up for open data.]')
#appendix.append('[Served to you by GNU/Linux.]')
#appendix.append('[Want to help? This service sucks for non-norwegian forecast.]')
appendix.append("[You can not use US zip codes here. Try finger @graph.no.]")
appendix.append('[The _ in front of hours means the sun is up.]')
#appendix.append('[This service now has a client, check out the github repo.]')
#appendix.append('[Ask me again, I dare you!]')
appendix.append('[Data is cached for 20 minutes, please dont hammer.]')
#appendix.append('[Sorry for the instability. Daily requests recently went up tenfold.]')
#appendix.append('[Data is cached for 20 minutes. No use in asking every second...]')
#appendix.append('[My bitcoin, flatter, patreon IDs are... Nah, keep your money.]')
#appendix.append('[Peace, love, linux.]')
#appendix.append('[Rate limited to survive twitter storm. Max 3 connections pr. 30 seconds.]')
#appendix.append('[Pipe finger to head -n19 to remove this message.]')
#appendix.append('[Source data has changed. Sunrise info missing for now.]')
#appendix.append('[Vote: Add "feels like" temperature as default or option?]')
#appendix.append('[NEW: Now supports imperial units. See finger @graph.no.]')
# Add a random appendix
ret += appendix [ random.randint( 0, len(appendix)-1 ) ]
return ret, source
def get_pyyrshort (location, offset = 0, hourstep = 1, screenwidth = 80):
weatherdata, source = pyyrlib.returnWeatherData(location, True)
if not weatherdata:
return False, False
offset = int(offset)
ret = "" #all output goes here
if verbose:
print("weather")
print(weatherdata['tabular'][offset])
print(weatherdata['tabular'][offset]['temperature'])
print(weatherdata['tabular'][offset]['precipitation'])
print(weatherdata['tabular'][offset]['windSpeed']['mps'])
print(weatherdata['tabular'][offset]['windDirection']['code'])
shortened_source = source_to_concise_string(source)
ret += shortened_source + \
' at %(from)s: %(temp)s C, %(symbolname)s' % \
{"location": location,
"from": weatherdata['tabular'][offset]['from'][11:16],
"temp": str(weatherdata['tabular'][offset]['temperature']),
"symbolname": str(weatherdata['tabular'][offset]['symbolname']).lower(),
}
if 0 < float(weatherdata['tabular'][offset]['precipitation']):
precipitation = "rain"
if 0 > float (weatherdata['tabular'][offset]['temperature']):
precipitation = "snow"
ret += ' ( %(precipitation)s mm %(name)s )' % \
{"precipitation": str(math.ceil(float(weatherdata['tabular'][offset]['precipitation']))),
"name": precipitation}
if 0 < float(weatherdata['tabular'][offset]['windSpeed']['mps']):
ret += ', %(speed)s mps wind from %(direction)s' % \
{"speed": str(weatherdata['tabular'][offset]['windSpeed']['mps']),
"direction": weatherdata['tabular'][offset]['windDirection']['code']}
ret += '.'
return ret, source
def source_to_concise_string(source):
ret = ''
ret += str(source)\
.replace('http://www.yr.no/sted/', '')\
.replace('http://www.yr.no/place/', '')\
.replace('/forecast.xml','')\
.replace('/forecast_hour_by_hour.xml','')
return ret
if __name__ == "__main__":
# Test if location is provided
if 2 > len(sys.argv):
location = "0458"
else:
location = ''.join(sys.argv[1:])
ret, source = get_pyyrascii(location)
print(ret)
#ret, source = get_pyyrshort(location)
#print(ret)