add custom component and cards to track space weather conditions

This commit is contained in:
Cyberes 2024-08-17 22:48:00 -06:00
parent 4687210542
commit 0215004691
6 changed files with 458 additions and 0 deletions

View File

@ -0,0 +1 @@
DOMAIN = "space_weather"

View File

@ -0,0 +1,11 @@
{
"codeowners": ["@cyberes"],
"config_flow": false,
"dependencies": [],
"documentation": "https://git.evulid.cc/cyberes/ha-noaa-space-weather-sensor",
"domain": "space_weather",
"iot_class": "cloud_polling",
"name": "Space Weather",
"requirements": [],
"version": "1.0.0"
}

View File

@ -0,0 +1,137 @@
import logging
from datetime import timedelta
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.entity import Entity
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
CONF_URL = "https://services.swpc.noaa.gov/products/noaa-scales.json"
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):
url = config.get("url")
session = async_get_clientsession(hass)
async_add_entities([
SpaceWeatherScaleSensor(session, url, "R"),
SpaceWeatherScaleSensor(session, url, "S"),
SpaceWeatherScaleSensor(session, url, "G"),
SpaceWeatherPredictionSensor(session, url, "R", "MinorProb", "pred_r_minor"),
SpaceWeatherPredictionSensor(session, url, "R", "MajorProb", "pred_r_major"),
SpaceWeatherPredictionSensor(session, url, "S", "Scale", "pred_s_scale"),
SpaceWeatherPredictionSensor(session, url, "S", "Prob", "pred_s_prob"),
SpaceWeatherPredictionSensor(session, url, "G", "Scale", "pred_g_scale"),
], True)
class SpaceWeatherScaleSensor(Entity):
def __init__(self, session, url, scale_key):
self._session = session
self._url = url
self._scale_key = scale_key
self._name = f'Space Weather Scale {scale_key}'
self._state = None
self._data = None
@property
def name(self):
return self._name
@property
def unique_id(self):
return f"space_weather_scale_{self._scale_key.lower()}"
@property
def state(self):
return self._state
@property
def device_state_attributes(self):
if self._data:
return {
"scale": self._data[self._scale_key]["Scale"],
"text": self._data[self._scale_key]["Text"],
}
return None
@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()
self._data = data["-1"]
self._state = f'{self._scale_key}{self._data[self._scale_key]["Scale"]}'
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}")
class SpaceWeatherPredictionSensor(Entity):
def __init__(self, session, url, scale_key, pred_key, unique_id):
self._session = session
self._url = url
self._scale_key = scale_key
self._pred_key = pred_key
self._unique_id = unique_id
self._name = f'Space Weather Prediction {scale_key} {pred_key}'
self._state = None
self._data = None
@property
def name(self):
return self._name
@property
def unique_id(self):
return self._unique_id
@property
def state(self):
if self._pred_key == "Scale":
return self._state
elif self._state is not None:
try:
return float(self._state)
except ValueError:
return None
return None
@property
def unit_of_measurement(self):
if self._pred_key in ["MinorProb", "MajorProb", "Prob"]:
return "%"
return None
@property
def device_state_attributes(self):
if self._data:
return {
"date_stamp": self._data["DateStamp"],
"time_stamp": self._data["TimeStamp"],
}
return None
@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()
self._data = data["1"]
self._state = self._data[self._scale_key][self._pred_key]
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}")

View File

@ -0,0 +1,160 @@
class SpaceWeatherCard extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
}
setConfig(config) {
this._config = config;
}
set hass(hass) {
this._hass = hass;
this.render();
}
render() {
if (!this.shadowRoot) return;
this.shadowRoot.innerHTML = `
<style>
.scale-container {
display: flex;
justify-content: space-around;
}
.scale-item {
text-align: center;
}
.scale-label {
font-weight: bold;
margin-bottom: 8px;
}
.scale-value {
font-size: 24px;
font-weight: bold;
margin-bottom: 4px;
padding: 8px;
border-radius: 4px;
}
.scale-text {
font-size: 14px;
}
.noaa_scale_bg_5 {
background-color: #C80000;
}
.noaa_scale_bg_4 {
background-color: #FF0000;
}
.noaa_scale_bg_3 {
background-color: #FF9600;
}
.noaa_scale_bg_2 {
background-color: #FFC800;
}
.noaa_scale_bg_1 {
background-color: #F6EB14;
}
.noaa_scale_bg_0 {
background-color: #92D050;
}
a {
text-decoration: none;
color: inherit;
}
.card-header {
font-size: 20px;
font-weight: bold;
padding: 16px;
margin-bottom: 16px;
text-align: center;
}
.scale-item {
cursor: pointer;
}
</style>
<ha-card>
<div class="card-header">
<a href="https://www.spaceweather.gov/noaa-scales-explanation" target="_blank">Space Weather Conditions</a>
</div>
<div class="card-content">
<div class="scale-container">
<div class="scale-item" data-entity-id="sensor.space_weather_scale_r">
<!-- <div class="scale-label">R Scale</div>-->
<div class="scale-value noaa_scale_bg_${this._getNumericState('sensor.space_weather_scale_r')}">
${this._getStateValue('sensor.space_weather_scale_r')}
</div>
<div class="scale-text">
${this._getStateAttribute('sensor.space_weather_scale_r', 'text')}
</div>
</div>
<div class="scale-item" data-entity-id="sensor.space_weather_scale_s">
<!-- <div class="scale-label">S Scale</div>-->
<div class="scale-value noaa_scale_bg_${this._getNumericState('sensor.space_weather_scale_s')}">
${this._getStateValue('sensor.space_weather_scale_s')}
</div>
<div class="scale-text">
${this._getStateAttribute('sensor.space_weather_scale_s', 'text')}
</div>
</div>
<div class="scale-item" data-entity-id="sensor.space_weather_scale_g">
<!-- <div class="scale-label">G Scale</div>-->
<div class="scale-value noaa_scale_bg_${this._getNumericState('sensor.space_weather_scale_g')}">
${this._getStateValue('sensor.space_weather_scale_g')}
</div>
<div class="scale-text">
${this._getStateAttribute('sensor.space_weather_scale_g', 'text')}
</div>
</div>
</div>
</div>
</ha-card>
`;
this._attachClickListeners();
}
_getStateValue(entityId) {
const state = this._hass.states[entityId];
return state ? state.state : '';
}
_getStateAttribute(entityId, attribute) {
const state = this._hass.states[entityId];
return state ? state.attributes[attribute] || '' : '';
}
_getNumericState(entityId) {
const stateValue = this._getStateValue(entityId);
return stateValue.substring(1);
}
_attachClickListeners() {
const scaleItems = this.shadowRoot.querySelectorAll('.scale-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);
}
getCardSize() {
return 3;
}
}
customElements.define('space-weather-card', SpaceWeatherCard);

View File

@ -0,0 +1,149 @@
class SpaceWeatherPredictionCard extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
}
setConfig(config) {
this._config = config;
}
set hass(hass) {
this._hass = hass;
this.render();
}
render() {
if (!this.shadowRoot) return;
this.shadowRoot.innerHTML = `
<style>
/* TODO: unify this with the other card */
.prediction-container {
display: flex;
flex-direction: column;
align-items: center;
}
.prediction-item {
text-align: center;
margin-bottom: 16px;
}
.prediction-label {
font-weight: bold;
margin-bottom: 8px;
}
.prediction-value {
font-size: 24px;
font-weight: bold;
margin-bottom: 4px;
padding: 8px;
border-radius: 4px;
}
.noaa_scale_bg_5 {
background-color: #C80000;
}
.noaa_scale_bg_4 {
background-color: #FF0000;
}
.noaa_scale_bg_3 {
background-color: #FF9600;
}
.noaa_scale_bg_2 {
background-color: #FFC800;
}
.noaa_scale_bg_1 {
background-color: #F6EB14;
}
.noaa_scale_bg_0 {
background-color: #92D050;
}
.card-header {
font-size: 20px;
font-weight: bold;
padding: 16px;
margin-bottom: 16px;
text-align: center;
}
.scale-value {
font-size: 24px;
font-weight: bold;
margin-bottom: 4px;
padding: 8px;
border-radius: 4px;
}
a {
text-decoration: none;
color: inherit;
}
</style>
<ha-card>
<div class="card-header">Space Weather Predictions</div>
<div class="card-content">
<div class="prediction-container">
<div class="prediction-item">
<div class="prediction-label">R1-R2</div>
<!-- TODO: what happens when "Scale" in JSON is not null? -->
<!-- TODO: what happens when "Text" in JSON is not null? -->
<div class="prediction-value">
${Math.round(parseFloat(this._getStateValue('sensor.space_weather_prediction_r_minorprob')))}%
</div>
</div>
<div class="prediction-item">
<div class="prediction-label">R3-R5</div>
<!-- TODO: what happens when "Scale" in JSON is not null? -->
<!-- TODO: what happens when "Text" in JSON is not null? -->
<div class="prediction-value">
${Math.round(parseFloat(this._getStateValue('sensor.space_weather_prediction_r_majorprob')))}%
</div>
</div>
<div class="prediction-item">
<div class="prediction-label">S1 or Greater</div>
<!-- TODO: what happens when "Scale" in JSON is not null? -->
<!-- TODO: what happens when "Text" in JSON is not null? -->
<div class="prediction-value">
${Math.round(parseFloat(this._getStateValue('sensor.space_weather_prediction_s_prob')))}%
</div>
</div>
<!-- <div class="prediction-item">
<div class="prediction-label">S Probability</div>
<div class="prediction-value">
${this._getStateValue('sensor.space_weather_prediction_s_scale')}
</div>
</div> -->
<div class="prediction-item">
<div class="prediction-label">G Scale</div>
<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')}
</div>
</div>
</div>
</div>
</ha-card>
`;
}
_getStateValue(entityId) {
const state = this._hass.states[entityId];
return state ? state.state : '';
}
_getNumericState(entityId) {
const stateValue = this._getStateValue(entityId);
return stateValue.substring(1);
}
getCardSize() {
return 5;
}
}
customElements.define('space-weather-prediction-card', SpaceWeatherPredictionCard);