Skip to content

Commit 8f11cfb

Browse files
committed
updated to darksky.net weather api
1 parent 027f158 commit 8f11cfb

File tree

2 files changed

+75
-72
lines changed

2 files changed

+75
-72
lines changed

forecast.py

Lines changed: 29 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/python
22

33
# Weather forecast for Raspberry Pi w/Adafruit Mini Thermal Printer.
4-
# Retrieves data from Yahoo! weather, prints current conditions and
4+
# Retrieves data from DarkSky.net's API, prints current conditions and
55
# forecasts for next two days. See timetemp.py for a different
66
# weather example using nice bitmaps.
77
# Written by Adafruit Industries. MIT license.
@@ -14,51 +14,52 @@
1414
# http://www.adafruit.com/products/600 Printer starter pack
1515

1616
from __future__ import print_function
17-
import urllib, time
1817
from Adafruit_Thermal import *
19-
from xml.dom.minidom import parseString
18+
from datetime import date
19+
from datetime import datetime
20+
import calendar
21+
import urllib, json
2022

21-
# WOEID indicates the geographic location for the forecast. It is
22-
# not a ZIP code or other common indicator. Instead, it can be found
23-
# by 'manually' visiting http://weather.yahoo.com, entering a location
24-
# and requesting a forecast, then copy the number from the end of the
25-
# current URL string and paste it here.
26-
WOEID = '2459115'
23+
# API_KEY = "YOUR_API_KEY"
24+
25+
LAT = "40.726019"
26+
LONG = "-74.00536"
2727

2828
# Dumps one forecast line to the printer
2929
def forecast(idx):
30-
tag = 'yweather:forecast'
31-
day = dom.getElementsByTagName(tag)[idx].getAttribute('day')
32-
lo = dom.getElementsByTagName(tag)[idx].getAttribute('low')
33-
hi = dom.getElementsByTagName(tag)[idx].getAttribute('high')
34-
cond = dom.getElementsByTagName(tag)[idx].getAttribute('text')
35-
printer.print(day + ': low ' + lo )
36-
printer.print(deg)
37-
printer.print(' high ' + hi)
38-
printer.print(deg)
39-
printer.println(' ' + cond)
30+
31+
date = datetime.fromtimestamp(int(data['daily']['data'][idx]['time']))
32+
33+
day = calendar.day_name[date.weekday()]
34+
lo = data['daily']['data'][idx]['temperatureMin']
35+
hi = data['daily']['data'][idx]['temperatureMax']
36+
cond = data['daily']['data'][idx]['summary']
37+
printer.print(day + ': low ' + str(lo) )
38+
printer.print(deg)
39+
printer.print(' high ' + str(hi))
40+
printer.print(deg)
41+
printer.println(' ' + cond.replace(u'\u2013', '-').encode('utf-8')) # take care of pesky unicode dash "–" or \u2013
4042

4143
printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
4244
deg = chr(0xf8) # Degree symbol on thermal printer
4345

44-
# Fetch forecast data from Yahoo!, parse resulting XML
45-
dom = parseString(urllib.urlopen(
46-
'http://weather.yahooapis.com/forecastrss?w=' + WOEID).read())
46+
url = "https://api.darksky.net/forecast/"+API_KEY+"/"+LAT+","+LONG+"?exclude=[alerts,minutely,hourly,flags]&units=us"
47+
response = urllib.urlopen(url)
48+
data = json.loads(response.read())
4749

4850
# Print heading
4951
printer.inverseOn()
50-
printer.print('{:^32}'.format(
51-
dom.getElementsByTagName('description')[0].firstChild.data))
52+
printer.print('{:^32}'.format("DarkSky.Net Forecast"))
5253
printer.inverseOff()
5354

5455
# Print current conditions
5556
printer.boldOn()
5657
printer.print('{:^32}'.format('Current conditions:'))
5758
printer.boldOff()
58-
printer.print('{:^32}'.format(
59-
dom.getElementsByTagName('pubDate')[0].firstChild.data))
60-
temp = dom.getElementsByTagName('yweather:condition')[0].getAttribute('temp')
61-
cond = dom.getElementsByTagName('yweather:condition')[0].getAttribute('text')
59+
60+
61+
temp = data['currently']['temperature']
62+
cond = data['currently']['summary']
6263
printer.print(temp)
6364
printer.print(deg)
6465
printer.println(' ' + cond)

timetemp.py

Lines changed: 46 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/python
22

33
# Current time and temperature display for Raspberry Pi w/Adafruit Mini
4-
# Thermal Printer. Retrieves data from Yahoo! weather, prints current
4+
# Thermal Printer. Retrieves data from DarkSky.net's API, prints current
55
# conditions and time using large, friendly graphics.
66
# See forecast.py for a different weather example that's all text-based.
77
# Written by Adafruit Industries. MIT license.
@@ -15,31 +15,31 @@
1515

1616
from __future__ import print_function
1717
from Adafruit_Thermal import *
18-
from xml.dom.minidom import parseString
19-
import Image, ImageDraw, time, urllib
18+
import Image, ImageDraw, time, urllib, json
2019

21-
# WOEID indicates the geographic location for the forecast. It is
22-
# not a ZIP code or other common indicator. Instead, it can be found
23-
# by 'manually' visiting http://weather.yahoo.com, entering a location
24-
# and requesting a forecast, then copy the number from the end of the
25-
# current URL string and paste it here.
26-
WOEID = '2459115'
20+
# API_KEY = "YOUR_API_KEY"
2721

28-
# Fetch weather data from Yahoo!, parse resulting XML
29-
dom = parseString(urllib.urlopen(
30-
'http://weather.yahooapis.com/forecastrss?w=' + WOEID).read())
22+
LAT = "40.726019"
23+
LONG = "-74.00536"
24+
25+
# Fetch weather data from DarkSky, parse resulting JSON
26+
url = "https://api.darksky.net/forecast/"+API_KEY+"/"+LAT+","+LONG+"?exclude=[alerts,minutely,hourly,flags]&units=us"
27+
response = urllib.urlopen(url)
28+
data = json.loads(response.read())
3129

3230
# Extract values relating to current temperature, humidity, wind
33-
temperature = int(dom.getElementsByTagName(
34-
'yweather:condition')[0].getAttribute('temp'))
35-
humidity = int(dom.getElementsByTagName(
36-
'yweather:atmosphere')[0].getAttribute('humidity'))
37-
windSpeed = int(dom.getElementsByTagName(
38-
'yweather:wind')[0].getAttribute('speed'))
39-
windDir = int(dom.getElementsByTagName(
40-
'yweather:wind')[0].getAttribute('direction'))
41-
windUnits = dom.getElementsByTagName(
42-
'yweather:units')[0].getAttribute('speed')
31+
32+
temperature = int(data['currently']['temperature'])
33+
humidity = int(data['currently']['humidity'] * 100);
34+
windSpeed = int(data['currently']['windSpeed'])
35+
windDir = str(data['currently']['windBearing'])
36+
windUnits = "mph"
37+
38+
# print(temperature)
39+
# print(humidity)
40+
# print(windSpeed)
41+
# print(windDir)
42+
# print(windUnits)
4343

4444
# Although the Python Imaging Library does have nice font support,
4545
# I opted here to use a raster bitmap for all of the glyphs instead.
@@ -62,11 +62,11 @@
6262

6363
# Generate a list of sub-image glyphs cropped from the symbols image
6464
def croplist(widths, x, y, height):
65-
list = []
66-
for i in range(len(widths)):
67-
list.append(symbols.crop(
68-
[x, y+i*height, x+widths[i], y+(i+1)*height]))
69-
return list
65+
list = []
66+
for i in range(len(widths)):
67+
list.append(symbols.crop(
68+
[x, y+i*height, x+widths[i], y+(i+1)*height]))
69+
return list
7070

7171
# Crop glyph lists (digits, days of week, etc.)
7272
TimeDigit = croplist(TimeDigitWidth, 0, 0, 44)
@@ -91,20 +91,20 @@ def croplist(widths, x, y, height):
9191

9292
# Paste a series of glyphs (mostly numbers) from string to img
9393
def drawNums(str, x, y, list):
94-
for i in range(len(str)):
95-
d = ord(str[i]) - ord('0')
96-
img.paste(list[d], (x, y))
97-
x += list[d].size[0] + 1
98-
return x
94+
for i in range(len(str)):
95+
d = ord(str[i]) - ord('0')
96+
img.paste(list[d], (x, y))
97+
x += list[d].size[0] + 1
98+
return x
9999

100100
# Determine total width of a series of glyphs in string
101101
def numWidth(str, list):
102-
w = 0 # Cumulative width
103-
for i in range(len(str)):
104-
d = ord(str[i]) - ord('0')
105-
if i > 0: w += 1 # Space between digits
106-
w += list[d].size[0] # Digit width
107-
return w
102+
w = 0 # Cumulative width
103+
for i in range(len(str)):
104+
d = ord(str[i]) - ord('0')
105+
if i > 0: w += 1 # Space between digits
106+
w += list[d].size[0] # Digit width
107+
return w
108108

109109
# Render current time (always 24 hour XX:XX format)
110110
t = time.localtime()
@@ -134,12 +134,13 @@ def numWidth(str, list):
134134
s2 = str(windSpeed)
135135
winDirNum = 0 # Wind direction glyph number
136136
if windSpeed > 0:
137-
for winDirNum in range(len(DirAngle) - 1):
138-
if windDir < DirAngle[winDirNum]: break
137+
for winDirNum in range(len(DirAngle) - 1):
138+
if windDir < DirAngle[winDirNum]: break
139+
winDirNum+=1
139140
w = Humidity.size[0] + 5 + numWidth(s, HumiDigit)
140141
w2 = Wind.size[0] + 5 + numWidth(s2, HumiDigit)
141142
if windSpeed > 0:
142-
w2 += 3 + Dir[winDirNum].size[0]
143+
w2 += 3 + Dir[winDirNum].size[0]
143144
if windUnits == 'kph': w2 += 3 + Kph.size[0]
144145
else: w2 += 3 + Mph.size[0]
145146
if w2 > w: w = w2
@@ -154,14 +155,15 @@ def numWidth(str, list):
154155
y += 23 # And advance to next line
155156
img.paste(Wind, (x, y))
156157
x += Wind.size[0] + 5
158+
157159
if windSpeed > 0:
158-
img.paste(Dir[winDirNum], (x, y))
159-
x += Dir[winDirNum].size[0] + 3
160+
img.paste(Dir[winDirNum], (x, y))
161+
x += Dir[winDirNum].size[0] + 3
160162
x = drawNums(s2, x, y, HumiDigit) + 3
161163
if windUnits == 'kph': img.paste(Kph, (x, y))
162164
else: img.paste(Mph, (x, y))
163165

164166
# Open connection to printer and print image
165167
printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
166168
printer.printImage(img, True)
167-
printer.feed(3)
169+
printer.feed(3)

0 commit comments

Comments
 (0)