-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathopenweathermap.js
More file actions
260 lines (222 loc) · 6.73 KB
/
openweathermap.js
File metadata and controls
260 lines (222 loc) · 6.73 KB
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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: purple; icon-glyph: sun;
/* -----------------------------------------------
Script : openweathermap.js
Author : dev@supermamon.com
Version : 1.2.0
Description :
A Scriptable module that encapsulate the
One Call API from OpenWeatherMap and additional
information shared by developers over the
Automators.fm community.
Features
* Auto location detection or custom coordinates
* Night time detection
* SFSymbol names for weather conditions
* Units information
* OpenWeatherMap icon urls
References:
https://openweathermap.org/api/one-call-api
https://talk.automators.fm/t/widget-examples/7994/412
https://talk.automators.fm/t/widget-examples/7994/414
Changelog :
v1.0.0
- Initial release
-------------------------------------------------
v1.1.0
- (new) Add sfsymbol and icon to daily forecast
- (fix) Does not allow changing units
-------------------------------------------------
v1.2.0 | 20 Sep 2022
- (fix) lang option does not do anything
- (fix) night detection is incorrect sometimes
- (fix) minutely forecast not being excluded
- (fix) error when hourly or daily is excluded
- (new) api_version parameter
----------------------------------------------- */
async function getOpenWeatherData({
appid = '',
api_version = '2.5',
units = 'metric',
lang = 'en',
exclude = 'minutely,alerts',
revgeocode = false,
lat,
lon,
location_name,
} = {}) {
// auto-exclude minutely and alerts
if (!exclude.includes('minutely')) {
exclude = `${exclude},minutely`
}
if (!exclude.includes('alerts')) {
exclude = `${exclude},alerts`
}
const opts = { appid, api_version, units, lang, exclude, revgeocode, lat, lon, location_name }
// validate units
if (!(/metric|imperial|standard/.test(opts.units))) {
opts.units = 'metric'
}
// if coordinates are not provided, attempt to
// automatically find them
if (!opts.lat || !opts.lon) {
log('coordinates not provided. detecting...')
try {
var loc = await Location.current()
log('successfully detected')
} catch (e) {
log('unable to detect')
throw new Error('Unable to find your location.')
}
opts.lat = loc.latitude
opts.lon = loc.longitude
log(`located lat: ${opts.lat}, lon: ${opts.lon}`)
}
// ready to fetch the weather data
let url = `https://api.openweathermap.org/data/${opts.api_version}/onecall?lat=${opts.lat}&lon=${opts.lon}&exclude=${opts.exclude}&units=${opts.units}&lang=${opts.lang}&appid=${opts.appid}`
let req = new Request(url)
let wttr = await req.loadJSON()
if (wttr.cod) {
throw new Error(wttr.message)
}
// add some information not provided by OWM
// UNITS
const currUnits = {
standard: {
temp: "K",
pressure: "hPa",
visibility: "m",
wind_speed: "m/s",
wind_gust: "m/s",
rain: "mm",
snow: "mm"
},
metric: {
temp: "C",
pressure: "hPa",
visibility: "m",
wind_speed: "m/s",
wind_gust: "m/s",
rain: "mm",
snow: "mm"
},
imperial: {
temp: "F",
pressure: "hPa",
visibility: "m",
wind_speed: "mi/h",
wind_gust: "mi/h",
rain: "mm",
snow: "mm"
}
}
wttr.units = currUnits[opts.units]
// Reverse Geocoding
if (opts.revgeocode) {
log('reverse geocoding...')
const geo = await Location.reverseGeocode(opts.lat, opts.lon)
if (geo.length) {
wttr.geo = geo[0]
}
}
// Night Detections, Weather Symbols and Icons
//----------------------------------------------
// SFSymbol function
// Credits to @eqsOne | https://talk.automators.fm/t/widget-examples/7994/414
// Reference: https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2
const symbolForCondition = function (cond, night = false) {
let symbols = {
// Thunderstorm
"2": function () {
return "cloud.bolt.rain.fill"
},
// Drizzle
"3": function () {
return "cloud.drizzle.fill"
},
// Rain
"5": function () {
return (cond == 511) ? "cloud.sleet.fill" : "cloud.rain.fill"
},
// Snow
"6": function () {
return (cond >= 611 && cond <= 613) ? "cloud.snow.fill" : "snow"
},
// Atmosphere
"7": function () {
if (cond == 781) { return "tornado" }
if (cond == 701 || cond == 741) { return "cloud.fog.fill" }
return night ? "cloud.fog.fill" : "sun.haze.fill"
},
// Clear and clouds
"8": function () {
if (cond == 800) { return night ? "moon.stars.fill" : "sun.max.fill" }
if (cond == 802 || cond == 803) { return night ? "cloud.moon.fill" : "cloud.sun.fill" }
return "cloud.fill"
}
}
// Get first condition digit.
let conditionDigit = Math.floor(cond / 100)
return symbols[conditionDigit]()
}
// find the day that matched the epoch `dt`
const findDay = function (dt) {
const hDate = new Date(1000 * (dt))
const tzOffset = (new Date()).getTimezoneOffset() * 60
const match = wttr.daily.filter(daily => {
// somehow the daily timestamps are at UTC but inputs are local
// just trying this out if it works long term
const dDate = new Date(1000 * (daily.dt + tzOffset))
return (
hDate.getYear() == dDate.getYear() &&
hDate.getMonth() == dDate.getMonth() &&
hDate.getDate() == dDate.getDate())
})[0]
return match
}
wttr.current.is_night = (
wttr.current.dt > (wttr.current.sunset) ||
wttr.current.dt < (wttr.current.sunrise))
wttr.current.weather[0].sfsymbol =
symbolForCondition(
wttr.current.weather[0].id,
wttr.current.is_night)
let wicon = wttr.current.weather[0].icon
wttr.current.weather[0].icon_url =
`http://openweathermap.org/img/wn/@2x.png${wicon}`
// hourly data
if (wttr.hourly) {
wttr.hourly.map(hourly => {
var day = findDay(hourly.dt)
hourly.is_night = (
hourly.dt > day.sunset ||
hourly.dt < day.sunrise)
hourly.weather[0].sfsymbol =
symbolForCondition(
hourly.weather[0].id,
hourly.is_night)
let wicon = hourly.weather[0].icon
hourly.weather[0].icon_url =
`http://openweathermap.org/img/wn/@2x.png${wicon}`
return hourly
})
}
if (wttr.daily) {
wttr.daily.map(daily => {
daily.weather[0].sfsymbol =
symbolForCondition(
daily.weather[0].id,
false)
let wicon = daily.weather[0].icon
daily.weather[0].icon_url =
`http://openweathermap.org/img/wn/@2x.png${wicon}`
return daily
})
}
// also return the arguments provided
wttr.args = opts
//log(wttr)
return wttr
}
module.exports = getOpenWeatherData