forked from PiDiBi/meshbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather_bot.py
402 lines (351 loc) · 14.2 KB
/
weather_bot.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
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
import json
import requests
import xml.dom.minidom
import ephem
import bs4 as bs
from datetime import datetime
from datetime import timedelta
from log import log_timestamp
from message_processor import MessageProcessor
from meshtastic.stream_interface import StreamInterface
class WeatherBot(MessageProcessor):
DAYS_OF_WEATHER = (
2 # weather forecast days, the first two rows are today and tonight
)
def __init__(self, interface: StreamInterface):
super(WeatherBot, self).__init__(interface)
self.trap_list = ["sun", "solar", "hfcond", "tide", "moon", "wxc", "wx", "alerts"]
pass
def auto_response(
self, message, snr, rssi, hop, message_from_id, location: list[float]
):
print(f"WeatherBot: Got message: {message}")
message = message.lower().strip()
if "sun" in message:
bot_response = self.get_sun(str(location[0]), str(location[1]))
elif "hfcond" in message:
bot_response = self.hf_band_conditions()
elif "solar" in message:
bot_response = self.drap_xray_conditions() + "\n" + self.solar_conditions()
elif "tide" in message:
bot_response = self.get_tide(str(location[0]), str(location[1]))
elif "moon" in message:
bot_response = self.get_moon(str(location[0]), str(location[1]))
elif "wxc" in message:
bot_response = self.get_weather(str(location[0]), str(location[1]), 1)
elif "wx" in message:
bot_response = self.get_weather(str(location[0]), str(location[1]))
elif "alerts" in message:
bot_response = self.get_wx_alerts(str(location[0]), str(location[1]))
return bot_response
def hf_band_conditions(self):
# ham radio HF band conditions
hf_cond = ""
band_cond = requests.get(
"https://www.hamqsl.com/solarxml.php", timeout=self.URL_TIMEOUT
)
print(f"{log_timestamp()} System: {band_cond}")
if band_cond.ok:
solarxml = xml.dom.minidom.parseString(band_cond.text)
for i in solarxml.getElementsByTagName("band"):
hf_cond += (
i.getAttribute("time")[0]
+ i.getAttribute("name")
+ "="
+ str(i.childNodes[0].data)
+ "\n"
)
else:
hf_cond = self.ERROR_FETCHING_DATA
hf_cond = hf_cond[:-1] # remove the last newline
return hf_cond
def solar_conditions(self):
# radio related solar conditions from hamsql.com
solar_cond = ""
solar_cond = requests.get(
"https://www.hamqsl.com/solarxml.php", timeout=self.URL_TIMEOUT
)
print(f"{log_timestamp()} System: {solar_cond}")
if solar_cond.ok:
solar_xml = xml.dom.minidom.parseString(solar_cond.text)
for i in solar_xml.getElementsByTagName("solardata"):
solar_a_index = i.getElementsByTagName("aindex")[0].childNodes[0].data
solar_k_index = i.getElementsByTagName("kindex")[0].childNodes[0].data
solar_xray = i.getElementsByTagName("xray")[0].childNodes[0].data
solar_flux = i.getElementsByTagName("solarflux")[0].childNodes[0].data
sunspots = i.getElementsByTagName("sunspots")[0].childNodes[0].data
signalnoise = (
i.getElementsByTagName("signalnoise")[0].childNodes[0].data
)
solar_cond = (
"A-Index: "
+ solar_a_index
+ "\nK-Index: "
+ solar_k_index
+ "\nSunspots: "
+ sunspots
+ "\nX-Ray Flux: "
+ solar_xray
+ "\nSolar Flux: "
+ solar_flux
+ "\nSignal Noise: "
+ signalnoise
)
else:
solar_cond += "error fetching"
return solar_cond
def drap_xray_conditions(self):
# DRAP X-ray flux conditions, from NOAA direct
drap_cond = ""
drap_cond = requests.get(
"https://services.swpc.noaa.gov/text/drap_global_frequencies.txt",
timeout=self.URL_TIMEOUT,
)
print(f"{log_timestamp()} System: {drap_cond}")
if drap_cond.ok:
drap_list = drap_cond.text.split("\n")
x_filter = "# X-RAY Message :"
for line in drap_list:
if x_filter in line:
xray_flux = line.split(": ")[1]
else:
xray_flux += "error fetching"
return xray_flux
def get_sun(self, lat=0, lon=0):
# get sunrise and sunset times using callers location or default
obs = ephem.Observer()
obs.date = datetime.now()
sun = ephem.Sun()
if lat != 0 and lon != 0:
obs.lat = str(lat)
obs.lon = str(lon)
else:
obs.lat = str(self.LATITUDE)
obs.lon = str(self.LONGITUDE)
sun.compute(obs)
sun_table = {}
sun_table["azimuth"] = sun.az
sun_table["altitude"] = sun.alt
# get the next rise and set times
local_sunrise = ephem.localtime(obs.next_rising(sun))
local_sunset = ephem.localtime(obs.next_setting(sun))
sun_table["rise_time"] = local_sunrise.strftime("%a %d %I:%M")
sun_table["set_time"] = local_sunset.strftime("%a %d %I:%M")
# if sunset is before sunrise, then it's tomorrow
if local_sunset < local_sunrise:
local_sunset = ephem.localtime(obs.next_setting(sun)) + timedelta(1)
sun_table["set_time"] = local_sunset.strftime("%a %d %I:%M")
sun_data = (
"Sun Rise: " + sun_table["rise_time"] + "\nSet: " + sun_table["set_time"]
)
return sun_data
def get_moon(self, lat=0, lon=0):
# get moon phase and rise/set times using callers location or default
# the phase calculation mght not be accurate (followup later)
obs = ephem.Observer()
moon = ephem.Moon()
if lat != 0 and lon != 0:
obs.lat = str(lat)
obs.lon = str(lon)
else:
obs.lat = str(self.LATITUDE)
obs.lon = str(self.LONGITUDE)
obs.date = datetime.now()
moon.compute(obs)
moon_table = {}
moon_phase = [
"New Moon",
"Waxing Crescent",
"First Quarter",
"Waxing Gibbous",
"Full Moon",
"Waning Gibbous",
"Last Quarter",
"Waning Crescent",
][round(moon.phase / (2 * ephem.pi) * 8) % 8]
moon_table["phase"] = moon_phase
moon_table["illumination"] = moon.phase
moon_table["azimuth"] = moon.az
moon_table["altitude"] = moon.alt
local_moonrise = ephem.localtime(obs.next_rising(moon))
local_moonset = ephem.localtime(obs.next_setting(moon))
moon_table["rise_time"] = local_moonrise.strftime("%a %d %I:%M%p")
moon_table["set_time"] = local_moonset.strftime("%a %d %I:%M%p")
local_next_full_moon = ephem.localtime(ephem.next_full_moon((obs.date)))
local_next_new_moon = ephem.localtime(ephem.next_new_moon((obs.date)))
moon_table["next_full_moon"] = local_next_full_moon.strftime("%a %b %d %I:%M%p")
moon_table["next_new_moon"] = local_next_new_moon.strftime("%a %b %d %I:%M%p")
moon_data = (
"Moon Rise:"
+ moon_table["rise_time"]
+ "\nSet:"
+ moon_table["set_time"]
+ "\nPhase:"
+ moon_table["phase"]
+ " @:"
+ str("{0:.2f}".format(moon_table["illumination"]))
+ "%"
+ "\nFull Moon:"
+ moon_table["next_full_moon"]
+ "\nNew Moon:"
+ moon_table["next_new_moon"]
)
return moon_data
def get_tide(self, lat=0, lon=0):
station_id = ""
if float(lat) == 0 and float(lon) == 0:
return self.NO_DATA_NOGPS
station_lookup_url = (
"https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/tidepredstations.json?lat="
+ str(lat)
+ "&lon="
+ str(lon)
+ "&radius=50"
)
print(f"{log_timestamp()} System: {station_lookup_url}")
try:
station_data = requests.get(station_lookup_url, timeout=self.URL_TIMEOUT)
if station_data.ok:
station_json = station_data.json()
else:
return self.ERROR_FETCHING_DATA
except (requests.exceptions.RequestException, json.JSONDecodeError):
return self.ERROR_FETCHING_DATA
if station_id is None:
return "no tide station found"
station_id = station_json["stationList"][0]["stationId"]
station_url = (
"https://tidesandcurrents.noaa.gov/noaatidepredictions.html?id="
+ station_id
)
print(f"{log_timestamp()} System: {station_url}")
try:
station_data = requests.get(station_url, timeout=self.URL_TIMEOUT)
if not station_data.ok:
return self.ERROR_FETCHING_DATA
except requests.exceptions.RequestException:
return self.ERROR_FETCHING_DATA
# extract table class="table table-condensed"
soup = bs.BeautifulSoup(station_data.text, "html.parser")
table = soup.find("table", class_="table table-condensed")
# extract rows
rows = table.find_all("tr")
# extract data from rows
tide_data = []
for row in rows:
row_text = ""
cols = row.find_all("td")
for col in cols:
row_text += col.text + " "
tide_data.append(row_text)
# format tide data into a string
tide_string = ""
for data in tide_data:
tide_string += data + "\n"
# trim off last newline
tide_string = tide_string[:-1]
return tide_string
def get_weather(self, lat=0, lon=0, unit=0):
weather = ""
if float(lat) == 0 and float(lon) == 0:
return self.NO_DATA_NOGPS
weather_url = (
"https://forecast.weather.gov/MapClick.php?FcstType=text&lat="
+ str(lat)
+ "&lon="
+ str(lon)
)
if unit == 1:
weather_url += "&unit=1"
print(f"{log_timestamp()} System: {weather_url}")
try:
weather_data = requests.get(weather_url, timeout=self.URL_TIMEOUT)
if not weather_data.ok:
return self.ERROR_FETCHING_DATA
except requests.exceptions.RequestException:
return self.ERROR_FETCHING_DATA
soup = bs.BeautifulSoup(weather_data.text, "html.parser")
table = soup.find("div", id="detailed-forecast-body")
if table is None:
return "no weather data found on NOAA for your location"
else:
# get rows
rows = table.find_all("div", class_="row")
# extract data from rows
for index, row in enumerate(rows):
# shrink the text
line = self.replace_weather(row.text)
weather += line + "\n"
# only grab a few days of weather
if index >= self.DAYS_OF_WEATHER - 1:
break
# trim off last newline
weather = weather[:-1]
return weather
def get_wx_alerts(self, lat=0, lon=0):
# get weather alerts from NOAA :: NOT IMPLEMENTED YET
alerts = ""
if float(lat) == 0 and float(lon) == 0:
return self.NO_DATA_NOGPS
# get weather alerts from NOAA
alert_url = "https://api.weather.gov/alerts/active.atom?point=" + str(lat) + "," + str(lon)
print(f"{log_timestamp()} System: {alert_url}")
try:
alert_data = requests.get(alert_url, timeout=self.URL_TIMEOUT)
if not alert_data.ok:
return self.ERROR_FETCHING_DATA
except (requests.exceptions.RequestException):
return self.ERROR_FETCHING_DATA
alerts = ""
alertxml = xml.dom.minidom.parseString(alert_data.text)
for i in alertxml.getElementsByTagName("entry"):
alerts += (
i.getElementsByTagName("updated")[0].childNodes[0].nodeValue
+ ": "
+ i.getElementsByTagName("title")[0].childNodes[0].nodeValue
+ "\n"
)
if alerts == "":
alerts = "No weather alerts found"
# trim off last newline
if alerts[-1] == "\n":
alerts = alerts[:-1]
return alerts
def replace_weather(self, row):
replacements = {
"Monday": "Mon ",
"Tuesday": "Tue ",
"Wednesday": "Wed ",
"Thursday": "Thu ",
"Friday": "Fri ",
"Saturday": "Sat ",
"Sunday": "Sun ",
"Today": "Today ",
"Tonight": "Tonight ",
"Tomorrow": "Tomorrow ",
"This Afternoon": "Afternoon ",
"Overnight": "Overnight ",
"northwest": "NW",
"northeast": "NE",
"southwest": "SW",
"southeast": "SE",
"north": "N",
"south": "S",
"east": "E",
"west": "W",
"Northwest": "NW",
"Northeast": "NE",
"Southwest": "SW",
"Southeast": "SE",
"North": "N",
"South": "S",
"East": "E",
"West": "W",
"precipitation": "precip",
"showers": "shwrs",
"thunderstorms": "t-storms",
}
line = row
for key, value in replacements.items():
line = line.replace(key, value)
return line