Migreate to 0.6.0 and new device architecture

develop
Matthieu DUVAL 4 years ago
parent 56a8a35479
commit 8a44d22d41

@ -31,6 +31,8 @@ from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator, DataUpdateCoordinator,
) )
from .device import Device
from .const import ( from .const import (
CONF_EMAIL, CONF_EMAIL,
CONF_PASSWORD, CONF_PASSWORD,
@ -62,7 +64,7 @@ async def async_setup(hass, config):
hass.data[DOMAIN] = {"config": config[DOMAIN], "devices": {}, "unsub": None} hass.data[DOMAIN] = {"config": config[DOMAIN], "devices": {}, "unsub": None}
hass.async_create_task( hass.async_create_task(
hass.config_entries.flow.async_init( hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
context={ context={
"source": config_entries.SOURCE_IMPORT "source": config_entries.SOURCE_IMPORT
}, },
@ -86,7 +88,7 @@ async def async_setup_entry(hass, entry):
password, password,
token token
) )
_LOGGER.info("Context-setup and start the thread") _LOGGER.info("Context-setup and start the thread")
_LOGGER.info("Thread started") _LOGGER.info("Thread started")
@ -147,7 +149,7 @@ class GeoRideContext:
def email(self): def email(self):
""" current email """ """ current email """
return self._email return self._email
@property @property
def password(self): def password(self):
""" password """ """ password """
@ -224,9 +226,9 @@ class GeoRideContext:
"""Used to refresh the tracker list""" """Used to refresh the tracker list"""
_LOGGER.info("Tracker list refresh") _LOGGER.info("Tracker list refresh")
new_georide_trackers = await self._hass.async_add_executor_job(GeoRideApi.get_trackers, new_georide_trackers = await self._hass.async_add_executor_job(GeoRideApi.get_trackers,
await self.get_token()) await self.get_token())
for refreshed_tracker in new_georide_trackers: for refreshed_tracker in new_georide_trackers:
found = False found = False
for tracker in self._georide_trackers: for tracker in self._georide_trackers:
if tracker.tracker_id == refreshed_tracker.tracker_id: if tracker.tracker_id == refreshed_tracker.tracker_id:
tracker.update_all_data(refreshed_tracker) tracker.update_all_data(refreshed_tracker)
@ -256,7 +258,7 @@ class GeoRideContext:
update_interval=update_interval update_interval=update_interval
) )
self._georide_trackers_coordoned.append({ self._georide_trackers_coordoned.append({
"tracker": tracker, "tracker_device": Device(tracker),
"coordinator": coordinator "coordinator": coordinator
}) })
@ -270,7 +272,7 @@ class GeoRideContext:
def socket(self): def socket(self):
""" hold the GeoRide socket """ """ hold the GeoRide socket """
return self._socket return self._socket
@socket.setter @socket.setter
def socket(self, socket): def socket(self, socket):
"""set the GeoRide socket""" """set the GeoRide socket"""
@ -281,7 +283,7 @@ class GeoRideContext:
"""on lock callback""" """on lock callback"""
_LOGGER.info("On lock received") _LOGGER.info("On lock received")
for coordoned_tracker in self._georide_trackers_coordoned: for coordoned_tracker in self._georide_trackers_coordoned:
tracker = coordoned_tracker['tracker'] tracker = coordoned_tracker['tracker_device'].tracker
coordinator = coordoned_tracker['coordinator'] coordinator = coordoned_tracker['coordinator']
if tracker.tracker_id == data['trackerId']: if tracker.tracker_id == data['trackerId']:
tracker.locked_latitude = data['lockedLatitude'] tracker.locked_latitude = data['lockedLatitude']
@ -298,7 +300,7 @@ class GeoRideContext:
"""on device callback""" """on device callback"""
_LOGGER.info("On device received") _LOGGER.info("On device received")
for coordoned_tracker in self._georide_trackers_coordoned: for coordoned_tracker in self._georide_trackers_coordoned:
tracker = coordoned_tracker['tracker'] tracker = coordoned_tracker['tracker_device'].tracker
coordinator = coordoned_tracker['coordinator'] coordinator = coordoned_tracker['coordinator']
if tracker.tracker_id == data['trackerId']: if tracker.tracker_id == data['trackerId']:
tracker.status = data['status'] tracker.status = data['status']
@ -312,7 +314,7 @@ class GeoRideContext:
"""on device callback""" """on device callback"""
_LOGGER.info("On alarm received") _LOGGER.info("On alarm received")
for coordoned_tracker in self._georide_trackers_coordoned: for coordoned_tracker in self._georide_trackers_coordoned:
tracker = coordoned_tracker['tracker'] tracker = coordoned_tracker['tracker_device'].tracker
coordinator = coordoned_tracker['coordinator'] coordinator = coordoned_tracker['coordinator']
if tracker.tracker_id == data['trackerId']: if tracker.tracker_id == data['trackerId']:
if data.name == 'vibration': if data.name == 'vibration':
@ -330,7 +332,13 @@ class GeoRideContext:
elif data.name == 'powerCut': elif data.name == 'powerCut':
_LOGGER.info("powerCut detected") _LOGGER.info("powerCut detected")
else: else:
_LOGGER.warning("Unamanged alarm: ", data.name) _LOGGER.warning("Unamanged alarm: %s", data.name)
event_data = {
"device_id": tracker.tracker_id,
"type": data.name,
}
self._hass.bus.async_fire(f"{DOMAIN}_event", event_data)
asyncio.run_coroutine_threadsafe( asyncio.run_coroutine_threadsafe(
coordinator.async_request_refresh(), self._hass.loop coordinator.async_request_refresh(), self._hass.loop
).result() ).result()
@ -341,7 +349,7 @@ class GeoRideContext:
"""on position callback""" """on position callback"""
_LOGGER.info("On position received") _LOGGER.info("On position received")
for coordoned_tracker in self._georide_trackers_coordoned: for coordoned_tracker in self._georide_trackers_coordoned:
tracker = coordoned_tracker['tracker'] tracker = coordoned_tracker['tracker_device'].tracker
coordinator = coordoned_tracker['coordinator'] coordinator = coordoned_tracker['coordinator']
if tracker.tracker_id == data['trackerId']: if tracker.tracker_id == data['trackerId']:
tracker.latitude = data['latitude'] tracker.latitude = data['latitude']
@ -354,4 +362,3 @@ class GeoRideContext:
).result() ).result()
break break

@ -2,7 +2,6 @@
import logging import logging
from datetime import timedelta
from typing import Any, Mapping from typing import Any, Mapping
from homeassistant.core import callback from homeassistant.core import callback
@ -13,27 +12,26 @@ from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator DataUpdateCoordinator
) )
import georideapilib.api as GeoRideApi
import georideapilib.objects as GeoRideTracker
from .const import DOMAIN as GEORIDE_DOMAIN from .const import DOMAIN as GEORIDE_DOMAIN
from .device import Device
_LOGGER = logging.getLogger(__name__)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: disable=W0613 async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: disable=W0613
"""Set up GeoRide tracker based off an entry.""" """Set up GeoRide tracker based off an entry."""
georide_context = hass.data[GEORIDE_DOMAIN]["context"] georide_context = hass.data[GEORIDE_DOMAIN]["context"]
entities = [] entities = []
coordoned_trackers = georide_context.get_coordoned_trackers() coordoned_trackers = georide_context.get_coordoned_trackers()
for coordoned_tracker in coordoned_trackers: for coordoned_tracker in coordoned_trackers:
tracker = coordoned_tracker['tracker'] tracker_device = coordoned_tracker['tracker_device']
coordinator = coordoned_tracker['coordinator'] coordinator = coordoned_tracker['coordinator']
stolen_entity = GeoRideStolenBinarySensorEntity(coordinator, tracker) entities.append(GeoRideStolenBinarySensorEntity(coordinator, tracker_device))
crashed_entity = GeoRideCrashedBinarySensorEntity(coordinator, tracker) entities.append(GeoRideCrashedBinarySensorEntity(coordinator, tracker_device))
entities.append(stolen_entity) entities.append(GeoRideOwnerBinarySensorEntity(coordinator, tracker_device))
entities.append(crashed_entity) entities.append(GeoRideActiveSubscriptionBinarySensorEntity(coordinator, tracker_device))
hass.data[GEORIDE_DOMAIN]["devices"][tracker.tracker_id] = coordinator
hass.data[GEORIDE_DOMAIN]["devices"][tracker_device.tracker.tracker_id] = coordinator
async_add_entities(entities, True) async_add_entities(entities, True)
@ -43,71 +41,117 @@ async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: d
class GeoRideBinarySensorEntity(CoordinatorEntity, BinarySensorEntity): class GeoRideBinarySensorEntity(CoordinatorEntity, BinarySensorEntity):
"""Represent a tracked device.""" """Represent a tracked device."""
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]], def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
tracker: GeoRideTracker): tracker_device: Device):
"""Set up Georide entity.""" """Set up Georide entity."""
super().__init__(coordinator) super().__init__(coordinator)
self._tracker = tracker self._tracker_device = tracker_device
self._name = tracker.tracker_name self._name = tracker_device.tracker.tracker_name
self.entity_id = ENTITY_ID_FORMAT.format("is_stolen") + "." + str(tracker.tracker_id) self.entity_id = f"{ENTITY_ID_FORMAT.format('binary_sensor')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
self._is_on = False self._is_on = False
@property
def device_info(self):
"""Return the device info."""
return self._tracker_device.device_info
class GeoRideStolenBinarySensorEntity(GeoRideBinarySensorEntity):
"""Represent a tracked device."""
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
tracker_device: Device):
"""Set up Georide entity."""
super().__init__(coordinator, tracker_device)
self.entity_id = f"{ENTITY_ID_FORMAT.format('is_stolen')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
@property @property
def unique_id(self): def unique_id(self):
"""Return the unique ID.""" """Return the unique ID."""
return self._tracker.tracker_id return f"is_stolen_{self._tracker_device.tracker.tracker_id}"
@property
def is_on(self):
"""state value property"""
return self._tracker_device.is_stolen
@property @property
def name(self): def name(self):
""" GeoRide odometer name """ """ GeoRide odometer name """
return self._name return f"{self._name} is stolen"
@property
def device_info(self):
"""Return the device info."""
return {
"name": self.name,
"identifiers": {(GEORIDE_DOMAIN, self._tracker.tracker_id)},
"manufacturer": "GeoRide"
}
class GeoRideStolenBinarySensorEntity(GeoRideBinarySensorEntity): class GeoRideCrashedBinarySensorEntity(GeoRideBinarySensorEntity):
"""Represent a tracked device.""" """Represent a tracked device."""
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]], def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
tracker: GeoRideTracker): tracker_device: Device):
"""Set up Georide entity.""" """Set up Georide entity."""
super().__init__(coordinator, tracker) super().__init__(coordinator, tracker_device)
self.entity_id = ENTITY_ID_FORMAT.format("is_stolen") + "." + str(tracker.tracker_id) self.entity_id = f"{ENTITY_ID_FORMAT.format('is_crashed')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
@property @property
def unique_id(self): def unique_id(self):
"""Return the unique ID.""" """Return the unique ID."""
return f"is_stolen_{self._tracker.tracker_id}" return f"is_crashed_{self._tracker_device.tracker.tracker_id}"
@property @property
def is_on(self): def is_on(self):
"""state value property""" """state value property"""
return self._tracker.is_stolen return self._tracker_device.tracker.is_crashed
@property
def name(self):
""" GeoRide odometer name """
return f"{self._name} is crashed"
class GeoRideActiveSubscriptionBinarySensorEntity(GeoRideBinarySensorEntity):
"""Represent a tracked device."""
class GeoRideCrashedBinarySensorEntity(GeoRideBinarySensorEntity): def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
tracker_device: Device):
"""Set up Georide entity."""
super().__init__(coordinator, tracker_device)
self.entity_id = f"{ENTITY_ID_FORMAT.format('is_active_subscription_')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
@property
def unique_id(self):
"""Return the unique ID."""
return f"is_active_subscription_{self._tracker_device.tracker.tracker_id}"
@property
def is_on(self):
"""state value property"""
if self._tracker.subscription_id is not None:
return True
return False
@property
def name(self):
""" GeoRide odometer name """
return f"{self._name} has an active subscription"
class GeoRideOwnerBinarySensorEntity(GeoRideBinarySensorEntity):
"""Represent a tracked device.""" """Represent a tracked device."""
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]], def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
tracker: GeoRideTracker): tracker_device: Device):
"""Set up Georide entity.""" """Set up Georide entity."""
super().__init__(coordinator, tracker) super().__init__(coordinator, tracker_device)
self.entity_id = ENTITY_ID_FORMAT.format("is_crashed") + "." + str(tracker.tracker_id) self.entity_id = f"{ENTITY_ID_FORMAT.format('is_owner')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
@property @property
def unique_id(self): def unique_id(self):
"""Return the unique ID.""" """Return the unique ID."""
return f"is_crashed_{self._tracker.tracker_id}" return f"is_owner_{self._tracker_device.tracker.tracker_id}"
@property @property
def is_on(self): def is_on(self):
"""state value property""" """state value property"""
return self._tracker.is_crashed if self._tracker_device.tracker.role == "owner":
return True
return False
@property
def name(self):
""" GeoRide odometer name """
return f"{self._name} is own tracker"

@ -0,0 +1,52 @@
"""Home Assistant representation of an GeoRide Tracker device."""
import georideapilib.objects as GeoRideTracker
from .const import DOMAIN as GEORIDE_DOMAIN
class Device:
"""Home Assistant representation of a GeoRide Tracker device."""
def __init__(self, tracker):
"""Initialize GeoRideTracker device."""
self._tracker: GeoRideTracker = tracker
@property
def name(self) -> str:
"""Get the name."""
return self._tracker.name
@property
def manufacturer(self) -> str:
"""Get the manufacturer."""
return "GeoRide"
@property
def model_name(self) -> str:
"""Get the model name."""
name = "GeoRide 1"
if self._tracker.is_old_tracker:
name = "Prototype / GeoRide 1"
elif self._tracker.is_second_gen:
name = "GeoRide 2 / GeoRide 3"
return name
@property
def device_info(self):
"""Return the device info."""
return {
"name": self.name,
"identifiers": {(GEORIDE_DOMAIN, self._tracker.tracker_id)},
"manufacturer": "GeoRide",
"model": self.model_name,
"suggested_area": "Garage"
}
@property
def unique_id(self) -> str:
"""Get the unique id."""
return {(GEORIDE_DOMAIN, self._tracker.tracker_id)}
def __str__(self) -> str:
"""Get string representation."""
return f"GeoRide Device: {self.name}::{self.model_name}::self.unique_id"

@ -5,13 +5,13 @@ from typing import Any, Mapping
from homeassistant.components.device_tracker.const import DOMAIN, SOURCE_TYPE_GPS from homeassistant.components.device_tracker.const import DOMAIN, SOURCE_TYPE_GPS
from homeassistant.components.device_tracker.config_entry import TrackerEntity from homeassistant.components.device_tracker.config_entry import TrackerEntity
from homeassistant.helpers.update_coordinator import ( from homeassistant.helpers.update_coordinator import (
CoordinatorEntity, CoordinatorEntity,
DataUpdateCoordinator, DataUpdateCoordinator,
) )
import georideapilib.api as GeoRideApi from .device import Device
from .const import DOMAIN as GEORIDE_DOMAIN from .const import DOMAIN as GEORIDE_DOMAIN
@ -24,10 +24,10 @@ async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: d
entities = [] entities = []
for coordoned_tracker in coordoned_trackers: for coordoned_tracker in coordoned_trackers:
tracker = coordoned_tracker['tracker'] tracker_device = coordoned_tracker['tracker_device']
coordinator = coordoned_tracker['coordinator'] coordinator = coordoned_tracker['coordinator']
entity = GeoRideTrackerEntity(coordinator, tracker, hass) entity = GeoRideTrackerEntity(coordinator, tracker_device, hass)
hass.data[GEORIDE_DOMAIN]["devices"][tracker.tracker_id] = coordinator hass.data[GEORIDE_DOMAIN]["devices"][tracker_device.tracker.tracker_id] = coordinator
entities.append(entity) entities.append(entity)
async_add_entities(entities) async_add_entities(entities)
@ -38,12 +38,13 @@ async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: d
class GeoRideTrackerEntity(CoordinatorEntity, TrackerEntity): class GeoRideTrackerEntity(CoordinatorEntity, TrackerEntity):
"""Represent a tracked device.""" """Represent a tracked device."""
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]], tracker, hass): def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
tracker_device: Device, hass):
"""Set up GeoRide entity.""" """Set up GeoRide entity."""
super().__init__(coordinator) super().__init__(coordinator)
self._name = tracker.tracker_name self._name = tracker_device.tracker.tracker_name
self._tracker = tracker self._tracker_device = tracker_device
self.entity_id = DOMAIN + ".{}".format(tracker.tracker_id) self.entity_id = DOMAIN + ".{}".format(tracker_device.tracker.tracker_id)
self._hass = hass self._hass = hass
@property @property
@ -53,29 +54,28 @@ class GeoRideTrackerEntity(CoordinatorEntity, TrackerEntity):
@property @property
def name(self): def name(self):
"""ame property""" """ GeoRide odometer name """
return self._name return f"{self._name} position"
@property @property
def latitude(self): def latitude(self):
"""Return latitude value of the device.""" """Return latitude value of the device."""
if self._tracker.latitude: if self._tracker_device.tracker.latitude:
return self._tracker.latitude return self._tracker_device.tracker.latitude
return None return None
@property @property
def longitude(self): def longitude(self):
"""Return longitude value of the device.""" """Return longitude value of the device."""
if self._tracker.longitude: if self._tracker_device.tracker.longitude:
return self._tracker.longitude return self._tracker_device.tracker.longitude
return None return None
@property @property
def source_type(self): def source_type(self):
"""Return the source type, eg gps or router, of the device.""" """Return the source type, eg gps or router, of the device."""
return SOURCE_TYPE_GPS return SOURCE_TYPE_GPS
@property @property
def location_accuracy(self): def location_accuracy(self):
""" return the gps accuracy of georide (could not be aquired, then 10) """ """ return the gps accuracy of georide (could not be aquired, then 10) """
@ -89,26 +89,4 @@ class GeoRideTrackerEntity(CoordinatorEntity, TrackerEntity):
@property @property
def device_info(self): def device_info(self):
"""Return the device info.""" """Return the device info."""
return { return self._tracker_device.device_info
"name": self.name,
"identifiers": {(GEORIDE_DOMAIN, self._tracker.tracker_id)},
"manufacturer": "GeoRide",
"odometer": "{} km".format(self._tracker.odometer)
}
@property
def get_tracker_callback(self):
""" get tracker callaback"""
return self._get_tracker_callback
@property
def get_token_callback(self):
""" get token callaback"""
return self._get_token_callback
@property
def should_poll(self):
"""No polling needed."""
return True

@ -4,7 +4,7 @@
"config_flow": true, "config_flow": true,
"documentation": "https://github.com/ptimatth/GeorideHA", "documentation": "https://github.com/ptimatth/GeorideHA",
"requirements": [ "requirements": [
"georideapilib>=0.5.0", "georideapilib>=0.6.0",
"pyjwt>=1.7.1" "pyjwt>=1.7.1"
], ],
"dependencies": [], "dependencies": [],

@ -11,9 +11,8 @@ from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator, DataUpdateCoordinator,
) )
import georideapilib.api as GeoRideApi
from .const import DOMAIN as GEORIDE_DOMAIN from .const import DOMAIN as GEORIDE_DOMAIN
from .device import Device
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -26,10 +25,10 @@ async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: d
entities = [] entities = []
for coordoned_tracker in coordoned_trackers: for coordoned_tracker in coordoned_trackers:
tracker = coordoned_tracker['tracker'] tracker_device = coordoned_tracker['tracker_device']
coordinator = coordoned_tracker['coordinator'] coordinator = coordoned_tracker['coordinator']
entity = GeoRideOdometerSensorEntity(coordinator, tracker, hass) entity = GeoRideOdometerSensorEntity(coordinator, tracker_device, hass)
hass.data[GEORIDE_DOMAIN]["devices"][tracker.tracker_id] = coordinator hass.data[GEORIDE_DOMAIN]["devices"][tracker_device.tracker.tracker_id] = coordinator
entities.append(entity) entities.append(entity)
async_add_entities(entities) async_add_entities(entities)
@ -39,48 +38,44 @@ async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: d
class GeoRideOdometerSensorEntity(CoordinatorEntity, SensorEntity): class GeoRideOdometerSensorEntity(CoordinatorEntity, SensorEntity):
"""Represent a tracked device.""" """Represent a tracked device."""
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]], tracker, hass): def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
tracker_device:Device, hass):
"""Set up GeoRide entity.""" """Set up GeoRide entity."""
super().__init__(coordinator) super().__init__(coordinator)
self._tracker = tracker self._tracker_device = tracker_device
self._name = tracker.tracker_name self._name = tracker_device.tracker.tracker_name
self._unit_of_measurement = "m" self._unit_of_measurement = "m"
self.entity_id = ENTITY_ID_FORMAT.format("odometer") + "." + str(tracker.tracker_id) self.entity_id = f"{ENTITY_ID_FORMAT.format('odometer')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
self._state = 0 self._state = 0
self._hass = hass self._hass = hass
@property @property
def unique_id(self): def unique_id(self):
"""Return the unique ID.""" """Return the unique ID."""
return self._tracker.tracker_id return self._tracker_device.tracker.tracker_id
@property
def name(self):
""" GeoRide odometer name """
return self._tracker.tracker_name
@property @property
def state(self): def state(self):
"""state property""" """state property"""
return self._tracker.odometer return self._tracker_device.tracker.odometer
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""unit of mesurment property""" """unit of mesurment property"""
return self._unit_of_measurement return self._unit_of_measurement
@property
def name(self):
""" GeoRide odometer name """
return f"{self._name} odometer"
@property @property
def icon(self): def icon(self):
"""icon getter""" """icon getter"""
return "mdi:counter" return "mdi:counter"
@property @property
def device_info(self): def device_info(self):
"""Return the device info.""" """Return the device info."""
return { return self._tracker_device.device_info()
"name": self.name,
"identifiers": {(GEORIDE_DOMAIN, self._tracker.tracker_id)},
"manufacturer": "GeoRide"
}

@ -3,10 +3,8 @@
import logging import logging
from datetime import timedelta
from typing import Any, Mapping from typing import Any, Mapping
from homeassistant.core import callback
from homeassistant.components.switch import SwitchEntity from homeassistant.components.switch import SwitchEntity
from homeassistant.components.switch import ENTITY_ID_FORMAT from homeassistant.components.switch import ENTITY_ID_FORMAT
@ -18,7 +16,7 @@ from homeassistant.helpers.update_coordinator import (
import georideapilib.api as GeoRideApi import georideapilib.api as GeoRideApi
from .const import DOMAIN as GEORIDE_DOMAIN from .const import DOMAIN as GEORIDE_DOMAIN
from .device import Device
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -30,29 +28,27 @@ async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: d
lock_switch_entities = [] lock_switch_entities = []
for coordoned_tracker in coordoned_trackers: for coordoned_tracker in coordoned_trackers:
tracker = coordoned_tracker['tracker'] tracker_device = coordoned_tracker['tracker_device']
coordinator = coordoned_tracker['coordinator'] coordinator = coordoned_tracker['coordinator']
entity = GeoRideLockSwitchEntity(coordinator, tracker, hass) entity = GeoRideLockSwitchEntity(coordinator, tracker_device, hass)
hass.data[GEORIDE_DOMAIN]["devices"][tracker.tracker_id] = coordinator hass.data[GEORIDE_DOMAIN]["devices"][tracker_device.tracker.tracker_id] = coordinator
lock_switch_entities.append(entity) lock_switch_entities.append(entity)
async_add_entities(lock_switch_entities) async_add_entities(lock_switch_entities)
return True return True
class GeoRideLockSwitchEntity(CoordinatorEntity, SwitchEntity): class GeoRideLockSwitchEntity(CoordinatorEntity, SwitchEntity):
"""Represent a tracked device.""" """Represent a tracked device."""
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]], tracker, hass): def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
tracker_device:Device, hass):
"""Set up GeoRide entity.""" """Set up GeoRide entity."""
super().__init__(coordinator) super().__init__(coordinator)
self._tracker = tracker self._tracker_device = tracker_device
self._name = tracker.tracker_name self._name = tracker_device.tracker.tracker_name
self.entity_id = ENTITY_ID_FORMAT.format("lock") +"." + str(tracker.tracker_id) self.entity_id = f"{ENTITY_ID_FORMAT.format('lock')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
self._hass = hass self._hass = hass
async def async_turn_on(self, **kwargs): async def async_turn_on(self, **kwargs):
""" lock the GeoRide tracker """ """ lock the GeoRide tracker """
@ -60,17 +56,17 @@ class GeoRideLockSwitchEntity(CoordinatorEntity, SwitchEntity):
georide_context = self._hass.data[GEORIDE_DOMAIN]["context"] georide_context = self._hass.data[GEORIDE_DOMAIN]["context"]
token = await georide_context.get_token() token = await georide_context.get_token()
success = await self._hass.async_add_executor_job(GeoRideApi.lock_tracker, success = await self._hass.async_add_executor_job(GeoRideApi.lock_tracker,
token, self._tracker.tracker_id) token, self._tracker_device.tracker.tracker_id)
if success: if success:
self._tracker.is_locked = True self._tracker.is_locked = True
async def async_turn_off(self, **kwargs): async def async_turn_off(self, **kwargs):
""" unlock the GeoRide tracker """ """ unlock the GeoRide tracker """
_LOGGER.info('async_turn_off %s', kwargs) _LOGGER.info('async_turn_off %s', kwargs)
georide_context = self._hass.data[GEORIDE_DOMAIN]["context"] georide_context = self._hass.data[GEORIDE_DOMAIN]["context"]
token = await georide_context.get_token() token = await georide_context.get_token()
success = await self._hass.async_add_executor_job(GeoRideApi.unlock_tracker, success = await self._hass.async_add_executor_job(GeoRideApi.unlock_tracker,
token, self._tracker.tracker_id) token, self._tracker_device.tracker.tracker_id)
if success: if success:
self._tracker.is_locked = False self._tracker.is_locked = False
@ -80,7 +76,7 @@ class GeoRideLockSwitchEntity(CoordinatorEntity, SwitchEntity):
georide_context = self._hass.data[GEORIDE_DOMAIN]["context"] georide_context = self._hass.data[GEORIDE_DOMAIN]["context"]
token = await georide_context.get_token() token = await georide_context.get_token()
result = await self._hass.async_add_executor_job(GeoRideApi.toogle_lock_tracker, result = await self._hass.async_add_executor_job(GeoRideApi.toogle_lock_tracker,
token, self._tracker.tracker_id) token, self._tracker_device.tracker.tracker_id)
self._tracker.is_locked = result self._tracker.is_locked = result
@property @property
@ -90,29 +86,22 @@ class GeoRideLockSwitchEntity(CoordinatorEntity, SwitchEntity):
@property @property
def name(self): def name(self):
""" GeoRide switch name """ """ GeoRide odometer name """
return self._name return f"{self._name} lock"
@property @property
def is_on(self): def is_on(self):
""" GeoRide switch status """ """ GeoRide switch status """
return self._tracker.is_locked return self._tracker_device.tracker.is_locked
@property @property
def icon(self): def icon(self):
"""return the entity icon""" """return the entity icon"""
if self._tracker.tracker_id: if self._tracker_device.tracker.is_locked:
return "mdi:lock" return "mdi:lock"
return "mdi:lock-open" return "mdi:lock-open"
@property @property
def device_info(self): def device_info(self):
"""Return the device info.""" """Return the device info."""
return { return self._tracker_device.device_info()
"name": self.name,
"identifiers": {(GEORIDE_DOMAIN, self._tracker.tracker_id)},
"manufacturer": "GeoRide"
}

@ -4,5 +4,5 @@
"render_readme": true, "render_readme": true,
"domains": ["devices_tracker", "sensor"], "domains": ["devices_tracker", "sensor"],
"country": ["FR"], "country": ["FR"],
"homeassistant": "0.110.0" "homeassistant": "2021.4.0"
} }
Loading…
Cancel
Save