-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.py
234 lines (210 loc) · 9.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
# This little program is for the Waveshare 7.5
# inch Version 2 black and white only epaper display
# It uses OpenWeatherMap API to display weather info
import sys
import os
picdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'pic')
icondir = os.path.join(picdir, 'icon')
fontdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'font')
# Search lib folder for display driver modules
sys.path.append('lib')
from waveshare_epd import epd7in5_V2
epd = epd7in5_V2.EPD()
from datetime import datetime
import time
from PIL import Image,ImageDraw,ImageFont
import traceback
import requests, json
from io import BytesIO
import csv
# define funciton for writing image and sleeping for 5 min.
def write_to_screen(image, sleep_seconds):
print('Writing to screen.')
# Write to screen
h_image = Image.new('1', (epd.width, epd.height), 255)
# Open the template
screen_output_file = Image.open(os.path.join(picdir, image))
# Initialize the drawing context with template as background
h_image.paste(screen_output_file, (0, 0))
epd.init()
epd.display(epd.getbuffer(h_image))
# Sleep
time.sleep(2)
epd.sleep()
print('Sleeping for ' + str(sleep_seconds) +'.')
time.sleep(sleep_seconds)
# define function for displaying error
def display_error(error_source):
# Display an error
print('Error in the', error_source, 'request.')
# Initialize drawing
error_image = Image.new('1', (epd.width, epd.height), 255)
# Initialize the drawing
draw = ImageDraw.Draw(error_image)
draw.text((100, 150), error_source +' ERROR', font=font50, fill=black)
draw.text((100, 300), 'Retrying in 30 seconds', font=font22, fill=black)
current_time = datetime.now().strftime('%H:%M')
draw.text((300, 365), 'Last Refresh: ' + str(current_time), font = font50, fill=black)
# Save the error image
error_image_file = 'error.png'
error_image.save(os.path.join(picdir, error_image_file))
# Close error image
error_image.close()
# Write error to screen
write_to_screen(error_image_file, 30)
# Set the fonts
font22 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 22)
font30 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 30)
font35 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 35)
font50 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 50)
font60 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 60)
font100 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 100)
font160 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 160)
# Set the colors
black = 'rgb(0,0,0)'
white = 'rgb(255,255,255)'
grey = 'rgb(235,235,235)'
# Initialize and clear screen
print('Initializing and clearing screen.')
epd.init()
epd.Clear()
API_KEY = '******API KEY*******'
LOCATION = '*******'
LATITUDE = '*******'
LONGITUDE = '*******'
UNITS = 'imperial'
CSV_OPTION = True # if csv_option == True, a weather data will be appended to 'record.csv'
BASE_URL = 'http://api.openweathermap.org/data/2.5/onecall?'
URL = BASE_URL + 'lat=' + LATITUDE + '&lon=' + LONGITUDE + '&units=' + UNITS +'&appid=' + API_KEY
while True:
# Ensure there are no errors with connection
error_connect = True
while error_connect == True:
try:
# HTTP request
print('Attempting to connect to OWM.')
response = requests.get(URL)
print('Connection to OWM successful.')
error_connect = None
except:
# Call function to display connection error
print('Connection error.')
display_error('CONNECTION')
error = None
while error == None:
# Check status of code request
if response.status_code == 200:
print('Connection to Open Weather successful.')
# get data in jason format
data = response.json()
# get current dict block
current = data['current']
# get current
temp_current = current['temp']
# get feels like
feels_like = current['feels_like']
# get humidity
humidity = current['humidity']
# get pressure
wind = current['wind_speed']
# get description
weather = current['weather']
report = weather[0]['description']
# get icon url
icon_code = weather[0]['icon']
#icon_URL = 'http://openweathermap.org/img/wn/'+ icon_code +'@4x.png'
# get daily dict block
daily = data['daily']
# get daily precip
daily_precip_float = daily[0]['pop']
#format daily precip
daily_precip_percent = daily_precip_float * 100
# get min and max temp
daily_temp = daily[0]['temp']
temp_max = daily_temp['max']
temp_min = daily_temp['min']
# Append weather data to CSV if csv_option == True
if CSV_OPTION == True:
# Get current year, month, date, and time
current_year = datetime.now().strftime('%Y')
current_month = datetime.now().strftime('%m')
current_date = datetime.now().strftime('%d')
current_time = datetime.now().strftime('%H:%M')
#open the CSV and append weather data
with open('records.csv', 'a', newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow([current_year, current_month, current_date, current_time,
LOCATION,temp_current, feels_like, temp_max, temp_min,
humidity, daily_precip_float, wind])
print('Weather data appended to CSV.')
# Set strings to be printed to screen
string_location = LOCATION
string_temp_current = format(temp_current, '.0f') + u'\N{DEGREE SIGN}F'
string_feels_like = 'Feels like: ' + format(feels_like, '.0f') + u'\N{DEGREE SIGN}F'
string_humidity = 'Humidity: ' + str(humidity) + '%'
string_wind = 'Wind: ' + format(wind, '.1f') + ' MPH'
string_report = 'Now: ' + report.title()
string_temp_max = 'High: ' + format(temp_max, '>.0f') + u'\N{DEGREE SIGN}F'
string_temp_min = 'Low: ' + format(temp_min, '>.0f') + u'\N{DEGREE SIGN}F'
string_precip_percent = 'Precip: ' + str(format(daily_precip_percent, '.0f')) + '%'
# Set error code to false
error = False
'''
print('Location:', LOCATION)
print('Temperature:', format(temp_current, '.0f'), u'\N{DEGREE SIGN}F')
print('Feels Like:', format(feels_like, '.0f'), 'F')
print('Humidity:', humidity)
print('Wind Speed:', format(wind_speed, '.1f'), 'MPH')
print('Report:', report.title())
print('High:', format(temp_max, '.0f'), 'F')
print('Low:', format(temp_min, '.0f'), 'F')
print('Probabilty of Precipitation: ' + str(format(daily_precip_percent, '.0f')) + '%')
'''
else:
# Call function to display HTTP error
display_error('HTTP')
# Open template file
template = Image.open(os.path.join(picdir, 'template.png'))
# Initialize the drawing context with template as background
draw = ImageDraw.Draw(template)
# Draw top left box
## Open icon file
icon_file = icon_code + '.png'
icon_image = Image.open(os.path.join(icondir, icon_file))
### Paste the image
template.paste(icon_image, (40, 15))
## Place a black rectangle outline
draw.rectangle((25, 20, 225, 180), outline=black)
## Draw text
draw.text((30, 200), string_report, font=font22, fill=black)
draw.text((30, 240), string_precip_percent, font=font30, fill=black)
# Draw top right box
draw.text((375, 35), string_temp_current, font=font160, fill=black)
draw.text((350, 210), string_feels_like, font=font50, fill=black)
# Draw bottom left box
draw.text((35, 325), string_temp_max, font=font50, fill=black)
draw.rectangle((170, 385, 265, 387), fill=black)
draw.text((35, 390), string_temp_min, font=font50, fill=black)
# Draw bottom middle box
draw.text((345, 340), string_humidity, font=font30, fill=black)
draw.text((345, 400), string_wind, font=font30, fill=black)
# Draw bottom right box
draw.text((627, 330), 'UPDATED', font=font35, fill=white)
current_time = datetime.now().strftime('%H:%M')
draw.text((627, 375), current_time, font = font60, fill=white)
## Add a reminder to take out trash on Mon and Thurs
weekday = datetime.today().weekday()
if weekday == 0 or weekday == 3:
draw.rectangle((345, 13, 705, 55), fill =black)
draw.text((355, 15), 'TAKE OUT TRASH TODAY!', font=font30, fill=white)
# Save the image for display as PNG
screen_output_file = os.path.join(picdir, 'screen_output.png')
template.save(screen_output_file)
# Close the template file
template.close()
# Refresh clear screen to avoid burn-in at 3:00 AM
if datetime.now().strftime('%H') == '03':
print('Clearning screen to avoid burn-in.')
epd.Clear()
# Write to screen
write_to_screen(screen_output_file, 600)