forked from OpenVoiceOS/ovos-skill-weather
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
228 lines (207 loc) · 8.64 KB
/
api.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
# Copyright 2021, Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Call the Open Weather Map One Call API through Selene.
The One Call API provides current weather, 48 hourly forecasts, 7 daily forecasts
and weather alert data all in a single API call. The endpoint is passed a
latitude and longitude from either the user's configuration or a requested
location.
It also supports returning values in the measurement system (Metric/Imperial)
provided, precluding us from having to do the conversions.
"""
import os
from mycroft.api import Api
from .weather import WeatherReport
from .ovosapiservice import OvosService
from json_database import JsonStorageXDG
import threading
import datetime as dt
import time
OPEN_WEATHER_MAP_LANGUAGES = (
"af",
"al",
"ar",
"bg",
"ca",
"cz",
"da",
"de",
"el",
"en",
"es",
"eu",
"fa",
"fi",
"fr",
"gl",
"he",
"hi",
"hr",
"hu",
"id",
"it",
"ja",
"kr",
"la",
"lt",
"mk",
"nl",
"no",
"pl",
"pt",
"pt_br",
"ro",
"ru",
"se",
"sk",
"sl",
"sp",
"sr",
"sv",
"th",
"tr",
"ua",
"uk",
"vi",
"zh_cn",
"zh_tw",
"zu"
)
class OpenWeatherMapApi(Api):
"""Use Open Weather Map's One Call API to retrieve weather information"""
def __init__(self):
super().__init__(path="owm")
self.language = "en"
self.localbackend = OvosService()
self.cache_response_location = JsonStorageXDG(
"skill-weather-response-cache")
def get_weather_for_coordinates(
self, measurement_system: str, latitude: float, longitude: float
) -> WeatherReport:
"""Issue an API call and map the return value into a weather report
Args:
measurement_system: Metric or Imperial measurement units
latitude: the geologic latitude of the weather location
longitude: the geologic longitude of the weather location
"""
query_parameters = dict(
exclude="minutely",
lang=self.language,
lat=latitude,
lon=longitude,
units=measurement_system
)
self.clear_cache_timer()
if self.check_if_cached_weather_exist(latitude, longitude):
cache_time = self.get_cached_weather_results(
latitude, longitude)[0]
response = self.get_cached_weather_results(latitude, longitude)[1]
# add additional check for if the time is more than 15 minutes old and if so, refresh the cache
if dt.datetime.now() - dt.datetime.fromtimestamp(cache_time) > dt.timedelta(minutes=15):
try:
api_request = dict(path="/onecall", query=query_parameters)
response = self.request(api_request)
if response == {}:
response = self.localbackend.get_report_for_weather_onecall_type(
query=query_parameters)
weather_cache_response = {'time': time.mktime(dt.datetime.now(
).timetuple()), 'lat': latitude, 'lon': longitude, 'response': response}
self.cache_weather_results(weather_cache_response)
local_weather = WeatherReport(response)
else:
weather_cache_response = {'time': time.mktime(dt.datetime.now(
).timetuple()), 'lat': latitude, 'lon': longitude, 'response': response}
self.cache_weather_results(weather_cache_response)
local_weather = WeatherReport(response)
except:
response = self.localbackend.get_report_for_weather_onecall_type(
query=query_parameters)
weather_cache_response = {'time': time.mktime(dt.datetime.now(
).timetuple()), 'lat': latitude, 'lon': longitude, 'response': response}
self.cache_weather_results(weather_cache_response)
local_weather = WeatherReport(response)
else:
local_weather = WeatherReport(response)
else:
try:
api_request = dict(path="/onecall", query=query_parameters)
response = self.request(api_request)
if response == {}:
response = self.localbackend.get_report_for_weather_onecall_type(
query=query_parameters)
weather_cache_response = {'time': time.mktime(dt.datetime.now(
).timetuple()), 'lat': latitude, 'lon': longitude, 'response': response}
self.cache_weather_results(weather_cache_response)
local_weather = WeatherReport(response)
else:
weather_cache_response = {'time': time.mktime(dt.datetime.now(
).timetuple()), 'lat': latitude, 'lon': longitude, 'response': response}
self.cache_weather_results(weather_cache_response)
local_weather = WeatherReport(response)
except:
response = self.localbackend.get_report_for_weather_onecall_type(
query=query_parameters)
weather_cache_response = {'time': time.mktime(dt.datetime.now(
).timetuple()), 'lat': latitude, 'lon': longitude, 'response': response}
self.cache_weather_results(weather_cache_response)
local_weather = WeatherReport(response)
return local_weather
def cache_weather_results(self, weather_response):
cache_response = {'time': weather_response["time"], 'lat': weather_response["lat"],
'lon': weather_response["lon"], 'response': weather_response["response"]}
if "caches" in self.cache_response_location:
cache_responses = self.cache_response_location["caches"]
else:
cache_responses = []
if cache_response not in cache_responses:
cache_responses.append(cache_response)
self.cache_response_location["caches"] = cache_responses
self.cache_response_location.store()
def check_if_cached_weather_exist(self, latitude, longitude):
if "caches" in self.cache_response_location:
cache_responses = self.cache_response_location["caches"]
for cache_response in cache_responses:
if cache_response["lat"] == latitude and cache_response["lon"] == longitude:
return True
else:
return False
else:
return False
def get_cached_weather_results(self, latitude, longitude):
if "caches" in self.cache_response_location:
cache_responses = self.cache_response_location["caches"]
for cache_response in cache_responses:
if cache_response["lat"] == latitude and cache_response["lon"] == longitude:
return [cache_response['time'], cache_response["response"]]
def clear_cache_timer(self):
if "caches" in self.cache_response_location:
threading.Timer(900, self.clear_cache).start()
def clear_cache(self):
os.remove(self.cache_response_location.path)
def set_language_parameter(self, language_config: str):
"""
OWM supports 31 languages, see https://openweathermap.org/current#multi
Convert Mycroft's language code to OpenWeatherMap's, if missing use english.
Args:
language_config: The Mycroft language code.
"""
special_cases = {"cs": "cz", "ko": "kr", "lv": "la"}
language_part_one, language_part_two = language_config.split('-')
if language_config.replace('-', '_') in OPEN_WEATHER_MAP_LANGUAGES:
self.language = language_config.replace('-', '_')
elif language_part_one in OPEN_WEATHER_MAP_LANGUAGES:
self.language = language_part_one
elif language_part_two in OPEN_WEATHER_MAP_LANGUAGES:
self.language = language_part_two
elif language_part_one in special_cases:
self.language = special_cases[language_part_one]