add timestamp sensor for space weather pred., fix not correctly doing pred. for tommorow, get pred. card working
This commit is contained in:
parent
0215004691
commit
6b62346d99
|
@ -1,10 +1,7 @@
|
||||||
import logging
|
import logging
|
||||||
from datetime import timedelta
|
from datetime import timedelta, datetime
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
import homeassistant.helpers.config_validation as cv
|
|
||||||
import voluptuous as vol
|
|
||||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
|
||||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||||
from homeassistant.helpers.entity import Entity
|
from homeassistant.helpers.entity import Entity
|
||||||
from homeassistant.util import Throttle
|
from homeassistant.util import Throttle
|
||||||
|
@ -14,23 +11,19 @@ _LOGGER = logging.getLogger(__name__)
|
||||||
CONF_URL = "https://services.swpc.noaa.gov/products/noaa-scales.json"
|
CONF_URL = "https://services.swpc.noaa.gov/products/noaa-scales.json"
|
||||||
SCAN_INTERVAL = timedelta(minutes=30)
|
SCAN_INTERVAL = timedelta(minutes=30)
|
||||||
|
|
||||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
|
||||||
vol.Optional("url", default=CONF_URL): cv.string,
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
|
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
|
||||||
url = config.get("url")
|
|
||||||
session = async_get_clientsession(hass)
|
session = async_get_clientsession(hass)
|
||||||
async_add_entities([
|
async_add_entities([
|
||||||
SpaceWeatherScaleSensor(session, url, "R"),
|
SpaceWeatherScaleSensor(session, CONF_URL, "R"),
|
||||||
SpaceWeatherScaleSensor(session, url, "S"),
|
SpaceWeatherScaleSensor(session, CONF_URL, "S"),
|
||||||
SpaceWeatherScaleSensor(session, url, "G"),
|
SpaceWeatherScaleSensor(session, CONF_URL, "G"),
|
||||||
SpaceWeatherPredictionSensor(session, url, "R", "MinorProb", "pred_r_minor"),
|
SpaceWeatherPredictionSensor(session, CONF_URL, "R", "MinorProb", "pred_r_minor"),
|
||||||
SpaceWeatherPredictionSensor(session, url, "R", "MajorProb", "pred_r_major"),
|
SpaceWeatherPredictionSensor(session, CONF_URL, "R", "MajorProb", "pred_r_major"),
|
||||||
SpaceWeatherPredictionSensor(session, url, "S", "Scale", "pred_s_scale"),
|
SpaceWeatherPredictionSensor(session, CONF_URL, "S", "Scale", "pred_s_scale"),
|
||||||
SpaceWeatherPredictionSensor(session, url, "S", "Prob", "pred_s_prob"),
|
SpaceWeatherPredictionSensor(session, CONF_URL, "S", "Prob", "pred_s_prob"),
|
||||||
SpaceWeatherPredictionSensor(session, url, "G", "Scale", "pred_g_scale"),
|
SpaceWeatherPredictionSensor(session, CONF_URL, "G", "Scale", "pred_g_scale"),
|
||||||
|
SpaceWeatherDateStampSensor(session, CONF_URL),
|
||||||
], True)
|
], True)
|
||||||
|
|
||||||
|
|
||||||
|
@ -129,9 +122,64 @@ class SpaceWeatherPredictionSensor(Entity):
|
||||||
async with self._session.get(self._url) as response:
|
async with self._session.get(self._url) as response:
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
data = await response.json()
|
data = await response.json()
|
||||||
self._data = data["1"]
|
now = datetime.now() + timedelta(days=1)
|
||||||
|
tomorrow_date = now.strftime('%Y-%m-%d')
|
||||||
|
tomorrow_data = {}
|
||||||
|
for k, v in data.items():
|
||||||
|
datestamp = v['DateStamp']
|
||||||
|
if datestamp == tomorrow_date:
|
||||||
|
tomorrow_data = v
|
||||||
|
assert len(tomorrow_data.keys()) is not None
|
||||||
|
self._data = tomorrow_data
|
||||||
self._state = self._data[self._scale_key][self._pred_key]
|
self._state = self._data[self._scale_key][self._pred_key]
|
||||||
else:
|
else:
|
||||||
_LOGGER.error(f"Error fetching data from {self._url}")
|
_LOGGER.error(f"Error fetching data from {self._url}")
|
||||||
except aiohttp.ClientError as err:
|
except aiohttp.ClientError as err:
|
||||||
_LOGGER.error(f"Error fetching data from {self._url}: {err}")
|
_LOGGER.error(f"Error fetching data from {self._url}: {err}")
|
||||||
|
|
||||||
|
|
||||||
|
class SpaceWeatherDateStampSensor(Entity):
|
||||||
|
"""
|
||||||
|
Attributes don't seem to be working so we use a single sensor to track the timestamp of the space weather
|
||||||
|
prediction updated.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, session, url):
|
||||||
|
self._session = session
|
||||||
|
self._url = url
|
||||||
|
self._name = "Space Weather Prediction Date Stamp"
|
||||||
|
self._state = None
|
||||||
|
self._data = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name(self):
|
||||||
|
return self._name
|
||||||
|
|
||||||
|
@property
|
||||||
|
def unique_id(self):
|
||||||
|
return "space_weather_prediction_date_stamp"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def state(self):
|
||||||
|
return self._state
|
||||||
|
|
||||||
|
@Throttle(SCAN_INTERVAL)
|
||||||
|
async def async_update(self):
|
||||||
|
try:
|
||||||
|
async with self._session.get(self._url) as response:
|
||||||
|
if response.status == 200:
|
||||||
|
data = await response.json()
|
||||||
|
now = datetime.now() + timedelta(days=1)
|
||||||
|
tomorrow_date = now.strftime('%Y-%m-%d')
|
||||||
|
tomorrow_data = {}
|
||||||
|
for k, v in data.items():
|
||||||
|
datestamp = v['DateStamp']
|
||||||
|
if datestamp == tomorrow_date:
|
||||||
|
tomorrow_data = v
|
||||||
|
assert len(tomorrow_data.keys()) is not None
|
||||||
|
self._data = tomorrow_data
|
||||||
|
self._state = datetime.strptime(f'{self._data["DateStamp"]} {self._data["TimeStamp"]}', "%Y-%m-%d %H:%M:%S").strftime('%m-%d-%Y %H:%M')
|
||||||
|
else:
|
||||||
|
_LOGGER.error(f"Error fetching data from {self._url}")
|
||||||
|
except aiohttp.ClientError as err:
|
||||||
|
_LOGGER.error(f"Error fetching data from {self._url}: {err}")
|
||||||
|
|
|
@ -29,6 +29,7 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
.prediction-item {
|
.prediction-item {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
margin-bottom: 16px;
|
margin-bottom: 16px;
|
||||||
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prediction-label {
|
.prediction-label {
|
||||||
|
@ -66,9 +67,16 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
.card-header {
|
.card-header {
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
padding: 16px;
|
padding: 0 16px 2px 16px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-subheader {
|
||||||
|
padding: 0 16px 16px 16px;
|
||||||
margin-bottom: 16px;
|
margin-bottom: 16px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
|
font-style: italic;
|
||||||
|
font-size: 15px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scale-value {
|
.scale-value {
|
||||||
|
@ -87,9 +95,12 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
|
|
||||||
<ha-card>
|
<ha-card>
|
||||||
<div class="card-header">Space Weather Predictions</div>
|
<div class="card-header">Space Weather Predictions</div>
|
||||||
|
<div class="card-subheader">
|
||||||
|
${this._getStateValue('sensor.space_weather_prediction_date_stamp')}
|
||||||
|
</div>
|
||||||
<div class="card-content">
|
<div class="card-content">
|
||||||
<div class="prediction-container">
|
<div class="prediction-container">
|
||||||
<div class="prediction-item">
|
<div class="prediction-item" data-entity-id="sensor.space_weather_prediction_r_minorprob">
|
||||||
<div class="prediction-label">R1-R2</div>
|
<div class="prediction-label">R1-R2</div>
|
||||||
<!-- TODO: what happens when "Scale" in JSON is not null? -->
|
<!-- TODO: what happens when "Scale" in JSON is not null? -->
|
||||||
<!-- TODO: what happens when "Text" in JSON is not null? -->
|
<!-- TODO: what happens when "Text" in JSON is not null? -->
|
||||||
|
@ -97,7 +108,7 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
${Math.round(parseFloat(this._getStateValue('sensor.space_weather_prediction_r_minorprob')))}%
|
${Math.round(parseFloat(this._getStateValue('sensor.space_weather_prediction_r_minorprob')))}%
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="prediction-item">
|
<div class="prediction-item" data-entity-id="sensor.space_weather_prediction_r_majorprob">
|
||||||
<div class="prediction-label">R3-R5</div>
|
<div class="prediction-label">R3-R5</div>
|
||||||
<!-- TODO: what happens when "Scale" in JSON is not null? -->
|
<!-- TODO: what happens when "Scale" in JSON is not null? -->
|
||||||
<!-- TODO: what happens when "Text" in JSON is not null? -->
|
<!-- TODO: what happens when "Text" in JSON is not null? -->
|
||||||
|
@ -105,7 +116,7 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
${Math.round(parseFloat(this._getStateValue('sensor.space_weather_prediction_r_majorprob')))}%
|
${Math.round(parseFloat(this._getStateValue('sensor.space_weather_prediction_r_majorprob')))}%
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="prediction-item">
|
<div class="prediction-item" data-entity-id="sensor.space_weather_prediction_s_prob">
|
||||||
<div class="prediction-label">S1 or Greater</div>
|
<div class="prediction-label">S1 or Greater</div>
|
||||||
<!-- TODO: what happens when "Scale" in JSON is not null? -->
|
<!-- TODO: what happens when "Scale" in JSON is not null? -->
|
||||||
<!-- TODO: what happens when "Text" in JSON is not null? -->
|
<!-- TODO: what happens when "Text" in JSON is not null? -->
|
||||||
|
@ -119,7 +130,7 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
${this._getStateValue('sensor.space_weather_prediction_s_scale')}
|
${this._getStateValue('sensor.space_weather_prediction_s_scale')}
|
||||||
</div>
|
</div>
|
||||||
</div> -->
|
</div> -->
|
||||||
<div class="prediction-item">
|
<div class="prediction-item" data-entity-id="sensor.space_weather_prediction_g_scale">
|
||||||
<div class="prediction-label">G Scale</div>
|
<div class="prediction-label">G Scale</div>
|
||||||
<div class="prediction-value scale-value noaa_scale_bg_${this._getStateValue('sensor.space_weather_prediction_g_scale')}">
|
<div class="prediction-value scale-value noaa_scale_bg_${this._getStateValue('sensor.space_weather_prediction_g_scale')}">
|
||||||
G${this._getStateValue('sensor.space_weather_prediction_g_scale')}
|
G${this._getStateValue('sensor.space_weather_prediction_g_scale')}
|
||||||
|
@ -129,6 +140,7 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
</div>
|
</div>
|
||||||
</ha-card>
|
</ha-card>
|
||||||
`;
|
`;
|
||||||
|
this._attachClickListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
_getStateValue(entityId) {
|
_getStateValue(entityId) {
|
||||||
|
@ -136,6 +148,11 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
return state ? state.state : '';
|
return state ? state.state : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_getAttribute(entityId, attribute) {
|
||||||
|
const state = this._hass.states[entityId];
|
||||||
|
return state ? state.attributes[attribute] : '';
|
||||||
|
}
|
||||||
|
|
||||||
_getNumericState(entityId) {
|
_getNumericState(entityId) {
|
||||||
const stateValue = this._getStateValue(entityId);
|
const stateValue = this._getStateValue(entityId);
|
||||||
return stateValue.substring(1);
|
return stateValue.substring(1);
|
||||||
|
@ -144,6 +161,22 @@ class SpaceWeatherPredictionCard extends HTMLElement {
|
||||||
getCardSize() {
|
getCardSize() {
|
||||||
return 5;
|
return 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_attachClickListeners() {
|
||||||
|
const scaleItems = this.shadowRoot.querySelectorAll('.prediction-item');
|
||||||
|
scaleItems.forEach(item => {
|
||||||
|
item.addEventListener('click', () => {
|
||||||
|
const entityId = item.dataset.entityId;
|
||||||
|
this._handleClick(entityId);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
_handleClick(entityId) {
|
||||||
|
const event = new Event('hass-more-info', {composed: true});
|
||||||
|
event.detail = {entityId};
|
||||||
|
this.dispatchEvent(event);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
customElements.define('space-weather-prediction-card', SpaceWeatherPredictionCard);
|
customElements.define('space-weather-prediction-card', SpaceWeatherPredictionCard);
|
||||||
|
|
Loading…
Reference in New Issue