forked from sieste/darksky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
darksky
executable file
·625 lines (462 loc) · 14.7 KB
/
darksky
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
#!/usr/bin/env python2
import urllib2
import json
import time
import datetime
import ConfigParser
import argparse
import sys
import os
import math
def writeConfig(config, conffile):
'''write the config file into the specified conffile'''
with open(conffile, 'wb') as configfile:
config.write(configfile)
##################################################
# Conversion of the units
##################################################
def celsius(F):
"""Converts the temperature in Farenheit to Celsius"""
return (F - 32.0) * 5.0 / 9.0
#######################################################
# txtplot function
#######################################################
def txtplot(data, ylim, nyticks=2, yspacer=3, xticksat=[], xmticksat=[], pch="*"):
"""
Create the ascii plot on the console.
Input parameters:
-----------------
data - list of x-values to be printed
ylim - lower and upper limit of printed data
nyticks - number of ticks in y axis
nxticks - number of ticks in x axsis
xticksat - list of location for the ticks
xmticksat - list of location for the minor ticks
pch - list of symbols to be shown (for intensity)
"""
n = len(data)
m = nyticks + (nyticks - 1) * yspacer
plotmat = [[" " for i in xrange(n)] for i in xrange(m)]
ymin = min(ylim)
ymax = max(ylim)
if len(pch) != n:
pch = [pch[0] for i in xrange(n)]
# plot the data
for i in xrange(n):
j = (float(data[i]) - ymin) / (ymax - ymin) * (m - 1)
j = int(round(j))
if (j >= 0 and j < m):
plotmat[j][i] = pch[i]
# decorate the plot
# horizontal lines
plotmat.insert(0, ["-" for i in xrange(len(plotmat[0]))])
plotmat.append(["-" for i in xrange(len(plotmat[0]))])
# x ticks
for i in xticksat:
if i >=0 and i < len(plotmat[0]):
plotmat[0][i] = "|"
# x minor ticks
for i in xmticksat:
if i >=0 and i < len(plotmat[0]):
plotmat[0][i] = "+"
# vertical lines with ticks
vline = ["|" for i in xrange(m)]
yticksat = [i for i in xrange(0, m, yspacer+1)]
for i in yticksat:
vline[i] = ":"
vline.insert(0, " ")
vline.append(" ")
for i in xrange(len(vline)):
plotmat[i].insert(0, vline[i])
plotmat[i].append(vline[i])
# y tick labels
dy = float((ymax - ymin)) / (nyticks - 1)
ytickvals = [float(ymin + i * dy) for i in xrange(nyticks)]
yticklabels = []
yticklabellen = []
for i in xrange(len(ytickvals)):
s = list(str(round(ytickvals[i], 2)))
yticklabels.append(s)
yticklabellen.append(len(s))
for i in xrange(len(plotmat)):
for j in xrange(max(yticklabellen)+1):
plotmat[i].insert(0, " ")
for i in xrange(len(yticksat)):
itick = yticksat[i] + 1
plotmat[itick][0:len(yticklabels[i])] = yticklabels[i]
return plotmat
#######################################################
# get options from command line
#######################################################
# the config file has to be created. The options specified
# in the config file are overwriten by the comman line options.
# initialize the parser
parser = argparse.ArgumentParser(#usage="%(prog)s [options]",
description="Command line weather forcasts powered by Dark Sky [https://darksky.net/poweredby/].")
# forecast mode
parser.add_argument("mode",type=str,
nargs="?",
default="rain",
help="forecast mode [rain | rain2 | temp | now]")
# config file
parser.add_argument("-f",
"--file",
nargs="?",
type=str,
default = "~/.darksky.conf",
help="config file")
# forcastio Api Key
parser.add_argument("-k",
"--key",
nargs="?",
type=str,
help="darksky.net api secret key")
# location key
parser.add_argument("-l",
"--location",
nargs="?",
type=str,
default = "Settings",
help="location defined in the config file")
# force new download of the data file
parser.add_argument("-d",
"--download",
action = "store_true",
help="force new download of the data file")
# output verbosity
parser.add_argument("-v",
"--verbose",
action="store_true",
help="verbose output")
# parse arguments into args variable.
args = parser.parse_args()
# capitalize the location
args.location = args.location.capitalize()
# show what has been parsed
if args.verbose:
print "Verbose mode"
print "---------------------------------------------------------"
print "The following arguments were parsed from the command line"
print "---------------------------------------------------------"
print "Config file:\t", args.file
print "Forecast mode:\t" , args.mode
print "User key:\t", args.key
print "Location:\t", args.location
print
#######################################################
# get options from config file
#######################################################
conffile = os.path.expanduser(args.file)
config = ConfigParser.ConfigParser()
# Read config file
if os.path.isfile(conffile):
if args.verbose:
print "Parsing the config file options from " + args.file
try:
config.read(conffile)
except:
print "Error reading config file " + conffile + "... exiting"
sys.exit(1)
else:
print "No config file " + conffile + " found. Intializing from defaults ..."
print
defaultConfig = {
'jsonFile': '/tmp/darksky%s.json',
'plotsize': '2',
}
config.add_section('Settings')
for key, value in defaultConfig.iteritems():
config.set('Settings',key,'%s' % value)
writeConfig(config, conffile)
# read darksky.net secret api key
if args.key:
apiKey = args.key
elif config.has_option("Settings", "apiKey"):
apiKey = config.get("Settings", "apiKey")
else:
print "Darksky secret API key not found (from https://darksky.net/dev)."
print
apiKey = raw_input('Please enter your apiKey, or press Enter to continue without: ')
if apiKey:
config.set('Settings', 'apiKey', apiKey)
writeConfig(config, conffile)
print "provided apiKey was added to your config file " + conffile
# latitude and longitude
if (config.has_option(args.location, "lat") &
config.has_option(args.location, "lon")):
lat = config.get(args.location, "lat")
lon = config.get(args.location, "lon")
else:
try:
config.add_section(args.location)
except:
pass
print "Please enter geografic coordinates for " + args.location + "."
lat = raw_input('Latitude: ')
lon = raw_input('Longitude: ')
config.set(args.location, 'lat', lat)
config.set(args.location, 'lon', lon)
writeConfig(config, conffile)
# only download new json file if existing file is older than 2 minutes
downloadIfOlder = 120
# plot height (the number of terminal lines between two y-axis ticks)
if (config.has_option("Settings", "plotsize")):
plotsize = int(config.get("Settings", "plotsize"))
else:
plotsize = 2
# json filename
if (config.has_option("Settings", "jsonFile")):
# the jsonFile has to contain %s in the string
try:
jsonfilename = config.get("Settings", "jsonFile") % args.location
except TypeError:
print "The filename jsonFile in the [Settings] section in the config file: " + args.file +\
" Must include '%s'"
print "Using default file"
jsonfilename = "/tmp/darksky"+ args.location +".json"
else:
jsonfilename = "/tmp/darksky"+ args.location +".json"
#######################################################
# download and open json file
#######################################################
# if file doesn't exist or it's more than `downloadIfOlder` seconds old
if not (os.path.isfile(jsonfilename)) \
or (time.time() - os.path.getmtime(jsonfilename) > downloadIfOlder) \
or args.download:
if args.verbose:
print "Downloading the data."
url = ('https://api.darksky.net/forecast/' + apiKey
+ '/' + str(lat) + ',' + str(lon))
try:
response = urllib2.urlopen(url)
except:
print
print "You might have exceeded the quota of API requests."
print "Try again later or register at https://darksky.net/dev and"
print "enter obtained apiKey when prompted."
print
print "Error: Connection failed."
sys.exit(1)
fcstData = response.read()
data = json.loads(fcstData) # converts to the required format
with open(jsonfilename, 'wb') as jsonFile:
jsonFile.write(fcstData)
else:
# load the data from the file
with open(jsonfilename, 'r') as jsonFile:
data = json.load(jsonFile)
#######################################################
# 60 minutes precipitation forecast
#######################################################
if args.mode == "rain":
try:
mData = data["minutely"]["data"]
except KeyError:
print "The data for minutely precision are not available for this location ("\
+ args.location + ")."
sys.exit(1)
# get precip data from json file
precipProb = []
precipIntensity = []
fcsttime = []
pch = []
for d in mData:
precipProb.append(d["precipProbability"])
pri = d["precipIntensity"] * 25.4
if pri < 1:
pch.append(".")
elif pri < 2:
pch.append("o")
elif pri < 5:
pch.append("X")
else:
pch.append("#")
fcsttime.append(d["time"])
# plot
plotmat = txtplot(data=precipProb,
ylim=[0,1],
nyticks=5,
yspacer=plotsize,
xticksat=[0, 15, 30, 45],
pch=pch)
# add x axis labels
t0 = datetime.datetime.fromtimestamp(fcsttime[0]
+ time.timezone).strftime('%H:%M')
plotmat.insert(0, [" " for i in xrange(len(plotmat[0]))])
plotmat[0][6:12] = list(t0)
plotmat[0][21:(21+6)] = list('+15min')
plotmat[0][36:(36+6)] = list('+30min')
plotmat[0][51:(51+6)] = list('+45min')
#######################################################
# 48 hours temperature forecast
#######################################################
elif args.mode=="temp":
try:
hData = data["hourly"]["data"]
except KeyError:
print "The data for hourly precision are not available for this location ("\
+ args.location + ")."
sys.exit(1)
temp = []
fcsttime = []
fcstday = []
for d in hData:
tmp = celsius(d["temperature"])
tmp = round(tmp, 1)
temp.append(tmp)
tim = d["time"] + time.timezone
tim = datetime.datetime.fromtimestamp(tim)
fcsttime.append(tim.strftime("%H:%M"))
fcstday.append(tim.strftime("%a"))
ymin = math.floor(min(temp) / 2.5) * 2.5
ymax = math.ceil(max(temp) / 2.5) * 2.5
nytix = int((ymax - ymin) / 2.5) + 1
xtixat = []
xmtixat = []
xtix = []
for i,t in enumerate(fcsttime):
if t == "00:00":
xtixat.append(i)
xtix.append(fcstday[i])
if t == "12:00":
xtixat.append(i)
xtix.append(t)
if t == "06:00" or t == "18:00":
xmtixat.append(i)
plotmat = txtplot(data=temp,
ylim=[ymin,ymax],
nyticks=nytix,
yspacer=plotsize,
xmticksat = xmtixat,
xticksat=xtixat)
plotmat.insert(0, [" " for i in xrange(len(plotmat[0])+2)])
for i in xrange(len(xtixat)):
tic = list(xtix[i])
itic = xtixat[i] + 5
plotmat[0][itic:(itic + len(tic))] = tic
#######################################################
# 48 hours rain forecast
#######################################################
elif args.mode=="rain2":
try:
hData = data["hourly"]["data"]
except KeyError:
print "The data for hourly precision are not available for this location ("\
+ args.location + ")."
sys.exit(1)
rain = []
fcsttime = []
fcstday = []
pch = []
for d in hData:
rain.append(d["precipProbability"] )
tim = d["time"] + time.timezone
tim = datetime.datetime.fromtimestamp(tim)
fcsttime.append(tim.strftime("%H:%M"))
fcstday.append(tim.strftime("%a"))
pri = d["precipIntensity"] * 25.4
if pri < 1:
pch.append(".")
elif pri < 2:
pch.append("o")
elif pri < 5:
pch.append("X")
else:
pch.append("#")
# creates ticks at the specified positions --
xtixat = []
xmtixat = [] # minor ticks array
xtix = []
for i,t in enumerate(fcsttime):
if t == "00:00":
xtixat.append(i)
xtix.append(fcstday[i])
if t == "12:00":
xtixat.append(i)
xtix.append(t)
if t == "06:00" or t == "18:00":
xmtixat.append(i)
plotmat = txtplot(data=rain,
ylim=[0,1],
nyticks=5,
yspacer=plotsize,
xticksat=xtixat,
xmticksat = xmtixat,
pch=pch)
plotmat.insert(0, [" " for i in xrange(len(plotmat[0])+2)])
for i in xrange(len(xtixat)):
tic = list(xtix[i])
itic = xtixat[i] + 5
plotmat[0][itic:(itic + len(tic))] = tic
#######################################################
# print current conditions
#######################################################
elif args.mode == 'now':
# obtain the current condition from the data file
try:
d = data['currently']
except KeyError:
print "The data for current conditions are not available for this location ("\
+ args.location + ")."
sys.exit(1)
if not 'summary' in d:
summary = ''
else:
summary = d['summary']
if not 'temperature' in d:
temperature = ''
else:
temperature = str(round(celsius(d['temperature']))) + ' C'
if 'apparentTemperature' in d:
apptemp = round(celsius(d['apparentTemperature']), 1)
temperature = temperature + ' (feels like ' + str(apptemp) + ' C)'
if not 'precipType' in d:
d['precipType'] = 'rain'
if not 'precipIntensity' in d:
d['precipIntensity'] = 0
if d['precipIntensity'] <= 0:
precip = 'none'
else:
precip = d['precipType'] + ' ' + str(round(d['precipIntensity'] * 25.4, 2)) + ' mm/h'
# WIND
if not 'windSpeed' in d:
windSpeed = '? km/h '
bft = ''
else:
windSpeed = str(int(d['windSpeed'] * 1.6093)) + ' km/h '
bft = '('+str(int((d['windSpeed'] * 1.6093 / 3.0) ** (2.0/3.0))) + ' Bft)'
if not 'windBearing' in d:
windBearing = ''
else:
windBearing = ['N','NE','E','SE','S','SW',
'W', 'NW', 'N'][int(d["windBearing"] / 45.0)] + ' '
wind = windSpeed + windBearing + bft
if not 'humidity' in d:
humidity = ''
else:
humidity = str(int(d['humidity'] * 100.0)) + ' %'
out = [
(' Summary:', summary),
(' Temperature:', temperature),
(' Precipitation:', precip),
(' Humidity:', humidity),
(' Wind: ', wind)]
tnow = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M')
print ""
print 'Current weather conditions at ' + tnow
print ""
out2 = [[s.ljust(max(len(i) for i in column)) for s in column] for column in zip(*out)]
for p in [" ".join(row) for row in zip(*out2)]: print p
print ""
else:
print "unknown mode: "+args.mode+" "
sys.exit(1)
#######################################################
# print plot matrix
#######################################################
if not args.mode == "now":
print ""
for i in reversed(xrange(len(plotmat))):
print ''.join(plotmat[i])
idx = max(0, len(plotmat[1])-22)
print ""