-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnws_alerts.py
188 lines (154 loc) · 6.02 KB
/
nws_alerts.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
'''
---------------------------------------------------------
NWS Alerts
---------------------------------------------------------
VERSION: 0.0.2
Forum: https://community.home-assistant.io/t/severe-weather-alerts-from-the-us-national-weather-service/71853
API Documentation
---------------------------------------------------------
https://www.weather.gov/documentation/services-web-api
https://forecast-v3.weather.gov/documentation
---------------------------------------------------------
'''
import requests
import logging
import voluptuous as vol
from datetime import timedelta
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, ATTR_ATTRIBUTION
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
API_ENDPOINT = 'https://api.weather.gov'
USER_AGENT = 'Home Assistant'
DEFAULT_ICON = 'mdi:alert'
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'NWS Alerts'
CONF_ZONE_ID = 'zone_id'
ZONE_ID = ''
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ZONE_ID): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the sensor platform."""
name = config.get(CONF_NAME, DEFAULT_NAME)
zone_id = config.get(CONF_ZONE_ID)
add_devices([NWSAlertSensor(name, zone_id)])
class NWSAlertSensor(Entity):
"""Representation of a Sensor."""
def __init__(self, name, zone_id):
"""Initialize the sensor."""
self._name = name
self._icon = DEFAULT_ICON
self._state = 0
self._event = None
self._display_desc = None
self._spoken_desc = None
self._zone_id = zone_id.replace(' ', '')
self.update()
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return self._icon
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def device_state_attributes(self):
"""Return the state message."""
attributes = {"title": self._event,
"display_desc": self._display_desc,
"spoken_desc": self._spoken_desc
}
return attributes
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Fetch new state data for the sensor.
This is the only method that should fetch new data for Home Assistant.
"""
values = self.get_state()
self._state = values['state']
self._event = values['event']
self._display_desc = values['display_desc']
self._spoken_desc = values['spoken_desc']
def get_state(self):
values = {'state': 0,
'event': None,
'display_desc': None,
'spoken_desc': None
}
headers = {'User-Agent': USER_AGENT,
'Accept': 'application/ld+json'
}
url = '%s/alerts/active/count' % API_ENDPOINT
r = requests.get(url, headers=headers)
_LOGGER.debug("getting state, %s", url)
if r.status_code == 200:
if 'zones' in r.json():
for zone in self._zone_id.split(','):
if zone in r.json()['zones']:
values = self.get_alerts()
break
return values
def get_alerts(self):
values = {'state': 0,
'event': None,
'display_desc': None,
'spoken_desc': None
}
headers = {'User-Agent': USER_AGENT,
'Accept': 'application/geo+json'
}
url = '%s/alerts/active?zone=%s' % (API_ENDPOINT, self._zone_id)
r = requests.get(url, headers=headers)
_LOGGER.debug("getting alert, %s", url)
if r.status_code == 200:
events = []
headlines = []
display_desc = ''
spoken_desc = ''
features = r.json()['features']
for alert in features:
event = alert['properties']['event']
if 'NWSheadline' in alert['properties']['parameters']:
headline = alert['properties']['parameters']['NWSheadline'][0]
else:
headline = event
description = alert['properties']['description']
instruction = alert['properties']['instruction']
if event in events:
continue
events.append(event)
headlines.append(headline)
if display_desc != '':
display_desc += '\n\n'
display_desc += '<b>%s</b>\n%s\n%s\n%s' % (event, headline, description, instruction)
if headlines:
num_headlines = len(headlines)
i = 0
for headline in headlines:
i += 1
if spoken_desc != '':
if i == num_headlines:
spoken_desc += ' and a '
else:
spoken_desc += ', a '
spoken_desc += headline
if len(events) > 0:
event_str = ''
for item in events:
if event_str != '':
event_str += ' - '
event_str += item
values['state'] = len(events)
values['event'] = event_str
values['display_desc'] = display_desc
values['spoken_desc'] = spoken_desc
return values