Skip to content

Commit

Permalink
Merge pull request #81 from cryptk/fix_sensor_conversions
Browse files Browse the repository at this point in the history
Fix sensor unit handling
  • Loading branch information
mrk-its authored Apr 20, 2024
2 parents 3833c6c + 6edfb33 commit ada59e7
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 39 deletions.
19 changes: 8 additions & 11 deletions custom_components/blitzortung/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,15 @@

import voluptuous as vol

from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, UnitOfLength
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.event import async_track_time_interval

from homeassistant.util.unit_system import IMPERIAL_SYSTEM
from homeassistant.util.unit_conversion import DistanceConverter
from homeassistant.const import (
LENGTH_KILOMETERS,
LENGTH_MILES,
)
from . import const
from .const import (
CONF_IDLE_RESET_TIMEOUT,
Expand Down Expand Up @@ -75,7 +72,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):

if hass.config.units == IMPERIAL_SYSTEM:
radius_mi = radius
radius = DistanceConverter.convert(radius, LENGTH_MILES, LENGTH_KILOMETERS)
radius = DistanceConverter.convert(radius, UnitOfLength.MILES, UnitOfLength.KILOMETERS)
_LOGGER.info("imperial system, %s mi -> %s km", radius_mi, radius)

coordinator = BlitzortungCoordinator(
Expand Down Expand Up @@ -235,7 +232,7 @@ def compute_polar_coords(self, lightning):
distance = round(math.sqrt(dx * dx + dy * dy) * 6371, 1)
azimuth = round(math.atan2(dx, dy) * 180 / math.pi) % 360

lightning[const.ATTR_LIGHTNING_DISTANCE] = distance
lightning[SensorDeviceClass.DISTANCE] = distance
lightning[const.ATTR_LIGHTNING_AZIMUTH] = azimuth

async def connect(self):
Expand Down Expand Up @@ -289,17 +286,17 @@ def parse_version(version_str):
notification_id="blitzortung_new_version_available",
)

def on_mqtt_message(self, message, *args):
async def on_mqtt_message(self, message, *args):
for callback in self.callbacks:
callback(message)
if message.topic.startswith("blitzortung/1.1"):
lightning = json.loads(message.payload)
self.compute_polar_coords(lightning)
if lightning[const.ATTR_LIGHTNING_DISTANCE] < self.radius:
_LOGGER.debug("ligntning data: %s", lightning)
if lightning[SensorDeviceClass.DISTANCE] < self.radius:
_LOGGER.debug("lightning data: %s", lightning)
self.last_time = time.time()
for callback in self.lightning_callbacks:
callback(lightning)
await callback(lightning)
for sensor in self.sensors:
sensor.update_lightning(lightning)

Expand Down
1 change: 0 additions & 1 deletion custom_components/blitzortung/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

DOMAIN = "blitzortung"
DATA_UNSUBSCRIBE = "unsubscribe"
ATTR_LIGHTNING_DISTANCE = "distance"
ATTR_LIGHTNING_AZIMUTH = "azimuth"
ATTR_LIGHTNING_COUNTER = "counter"

Expand Down
9 changes: 4 additions & 5 deletions custom_components/blitzortung/geo_location.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
from homeassistant.components.geo_location import GeolocationEvent
from homeassistant.const import (
ATTR_ATTRIBUTION,
LENGTH_KILOMETERS,
LENGTH_MILES,
UnitOfLength
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (
Expand Down Expand Up @@ -98,11 +97,11 @@ def __init__(
self._window_seconds = window_seconds

if hass.config.units == IMPERIAL_SYSTEM:
self._unit = LENGTH_MILES
self._unit = UnitOfLength.MILES
else:
self._unit = LENGTH_KILOMETERS
self._unit = UnitOfLength.KILOMETERS

def lightning_cb(self, lightning):
async def lightning_cb(self, lightning):
_LOGGER.debug("geo_location lightning: %s", lightning)
event = BlitzortungEvent(
lightning["distance"],
Expand Down
35 changes: 13 additions & 22 deletions custom_components/blitzortung/sensor.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import logging

from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, LENGTH_KILOMETERS
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, DEGREE, UnitOfLength
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
from homeassistant.helpers.device_registry import DeviceEntryType

from .const import (
ATTR_LAT,
ATTR_LIGHTNING_AZIMUTH,
ATTR_LIGHTNING_COUNTER,
ATTR_LIGHTNING_DISTANCE,
ATTR_LON,
ATTRIBUTION,
DOMAIN,
Expand All @@ -21,8 +20,6 @@
ATTR_UNIT = "unit"
ATTR_LIGHTNING_PROPERTY = "lightning_prop"

DEGREE = "°"

_LOGGER = logging.getLogger(__name__)


Expand Down Expand Up @@ -74,7 +71,6 @@ def __init__(self, coordinator, integration_name, unique_prefix):
self.entity_id = f"sensor.{integration_name}-{self.name}"
self._unique_id = f"{unique_prefix}-{self.kind}"
self._device_class = None
self._state = None
self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION}

should_poll = False
Expand All @@ -94,11 +90,6 @@ def name(self):
"""Return the name."""
return f"Lightning {self.label}"

@property
def state(self):
"""Return the state."""
return self._state

@property
def extra_state_attributes(self):
"""Return the state attributes."""
Expand Down Expand Up @@ -142,21 +133,21 @@ class LightningSensor(BlitzortungSensor):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._state = self.INITIAL_STATE
self._attr_native_value = self.INITIAL_STATE

def tick(self):
if self._state != self.INITIAL_STATE and self.coordinator.is_inactive:
self._state = self.INITIAL_STATE
if self._attr_native_value != self.INITIAL_STATE and self.coordinator.is_inactive:
self._attr_native_value = self.INITIAL_STATE
self.async_write_ha_state()


class DistanceSensor(LightningSensor):
kind = ATTR_LIGHTNING_DISTANCE
device_class = ATTR_LIGHTNING_DISTANCE
_attr_native_unit_of_measurement = LENGTH_KILOMETERS
kind = SensorDeviceClass.DISTANCE
device_class = SensorDeviceClass.DISTANCE
_attr_native_unit_of_measurement = UnitOfLength.KILOMETERS

def update_lightning(self, lightning):
self._state = lightning["distance"]
self._attr_native_value = lightning["distance"]
self._attrs[ATTR_LAT] = lightning[ATTR_LAT]
self._attrs[ATTR_LON] = lightning[ATTR_LON]
self.async_write_ha_state()
Expand All @@ -167,7 +158,7 @@ class AzimuthSensor(LightningSensor):
_attr_native_unit_of_measurement = DEGREE

def update_lightning(self, lightning):
self._state = lightning["azimuth"]
self._attr_native_value = lightning["azimuth"]
self._attrs[ATTR_LAT] = lightning[ATTR_LAT]
self._attrs[ATTR_LON] = lightning[ATTR_LON]
self.async_write_ha_state()
Expand All @@ -179,7 +170,7 @@ class CounterSensor(LightningSensor):
INITIAL_STATE = 0

def update_lightning(self, lightning):
self._state = self._state + 1
self._attr_native_value = self._attr_native_value + 1
self.async_write_ha_state()


Expand Down Expand Up @@ -218,9 +209,9 @@ def on_message(self, topic, message):
if topic == self._topic:
payload = message.payload.decode("utf-8")
try:
self._state = self.data_type(payload)
self._attr_native_value = self.data_type(payload)
except ValueError:
self._state = str(payload)
self._attr_native_value = str(payload)
if self.hass:
self.async_write_ha_state()

Expand Down

0 comments on commit ada59e7

Please sign in to comment.