Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 57abb51b13 | |||
| 54b7e9b5d6 | |||
| 24180c9345 | |||
| af0a4a37aa | |||
| a83bae6d3e | |||
| c229ca4b6e | |||
| b84a4cfd7f | |||
| 5c77acbdb7 | |||
| 5e83ed1c68 | |||
| 8a44d22d41 | |||
| 56a8a35479 | |||
| 7d25405c2f | |||
| dbbe1f33b9 | |||
| 660aaa0180 | |||
| 0113102a7f | |||
| 093bebc391 | |||
| ec63a36c81 | |||
| 283a1074e1 | |||
| 5cab811c85 | |||
| e09f8eb7e7 | |||
| be4e68e152 | |||
| bcaa4bf957 | |||
| af1df1cd84 | |||
| b4871b9374 | |||
| f72481236d | |||
| 1e21de655f | |||
| 3c6f39f7ba | |||
| 02e1656aab | |||
| 4593c694d5 | |||
| 9b651f933e | |||
| a8274f7fd1 | |||
| ef783db79b | |||
| 18de851e4d | |||
|
|
cbed2cebb3 | ||
| e5bd90ae6f | |||
| a2e65694fc | |||
| 66bd335a8e | |||
| 14300c5278 | |||
| bc3da8f0e5 | |||
| ecf2a23c70 | |||
| 991370fcec | |||
| 649c97b8bb | |||
| 9ffc8de8a7 | |||
| 9399c8e11a | |||
| b40c41e6b8 | |||
| 3c9f42aa2b | |||
| cc45b02a3a | |||
| 750073b8f3 |
111
README.md
111
README.md
@@ -1,8 +1,111 @@
|
||||
# Georide Home assistant
|
||||

|
||||
# GeoRide Home assistant
|
||||

|
||||
|
||||
⚠️ this is not an official implementation
|
||||
⚠️ This is not an official implementation
|
||||
[](https://github.com/custom-components/hacs)
|
||||
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||
|
||||
Official georide website: https://georide.fr/
|
||||
Official GeoRide website: https://georide.fr/
|
||||
|
||||
## Description
|
||||
This component add some sensor for GeoRide Tracker
|
||||
|
||||
### What's entity is available :
|
||||
|
||||
Get GeoRide position
|
||||
Get GeoRide lock status
|
||||
Change GeoRide lock status
|
||||
Add GeoRide from configuration.yml
|
||||
Add GeoRide from interface
|
||||
Get stollen status
|
||||
Get crashed status
|
||||
Get is owner status
|
||||
Get subsription status
|
||||
|
||||
### What's events are available:
|
||||
you can filter by data.device_id == XX (XX is your tracker id)
|
||||
you can display your tracker name by by data.device_name
|
||||
|
||||
event;
|
||||
|
||||
georide_position_event
|
||||
georide_lock_event
|
||||
georide_device_event
|
||||
georide_alarm_event
|
||||
|
||||
you can filter with data.type == 'alarm_vibration' to filter by vibration
|
||||
here is the alarm type available: (listen the georide_alarm_event)
|
||||
|
||||
alarm_vibration
|
||||
alarm_exitZone
|
||||
alarm_crash
|
||||
alarm_crashParking
|
||||
alarm_deviceOffline
|
||||
alarm_deviceOnline
|
||||
alarm_powerCut
|
||||
alarm_powerUncut
|
||||
alarm_batteryWarning
|
||||
alarm_temperatureWarning
|
||||
alarm_magnetOn
|
||||
alarm_magnetOff
|
||||
alarm_sonorAlarmOn
|
||||
|
||||
|
||||
## Question:
|
||||
|
||||
### How to have the odometer in Km ?
|
||||
|
||||
Simply add a sensor like this in configuration.yaml
|
||||
(Replace XX by your tracker id)
|
||||
|
||||
```yaml
|
||||
sensor:
|
||||
- platform: template # Conversion georide de m en km
|
||||
sensors:
|
||||
odometer_XX_km:
|
||||
friendly_name: "Odometter - Km"
|
||||
value_template: "{{ states.sensor.odometer_XX.state | multiply(0.001) | round(3, 'flour') }}"
|
||||
unit_of_measurement: 'Km'
|
||||
|
||||
|
||||
```
|
||||
|
||||
### How to use the event:
|
||||
|
||||
Simply made a automation like this:
|
||||
|
||||
```yaml
|
||||
alias: '[TEST] Send notification'
|
||||
description: ''
|
||||
trigger:
|
||||
- platform: event
|
||||
event_type: georide_lock_event
|
||||
condition: []
|
||||
action:
|
||||
- service: notify.mobile_app_oneplus_a3003
|
||||
data:
|
||||
message: 'The device {{ data.device_name }} have recieved a lock event'
|
||||
mode: single
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Options
|
||||
|
||||
| Name | Type | Requirement | `default` Description
|
||||
| ---- | ---- | ------- | -----------
|
||||
| email | string | **Required** | GeoRide email
|
||||
| password | string | **Required** | GeoRide password
|
||||
|
||||
|
||||
## Installation
|
||||
### Option 1
|
||||
- Just folow the integration config steps.
|
||||
|
||||
### Option 2
|
||||
- Add the folowing line in your configuration.yml
|
||||
```yaml
|
||||
georide:
|
||||
email: <your-email>@exmple.com
|
||||
password: <your-password>
|
||||
```
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "GeoRide",
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Set up GeoRide",
|
||||
"description": "Are you sure you want to set up GeoRide ?",
|
||||
"data": {
|
||||
"email": "email",
|
||||
"password": "password"
|
||||
}
|
||||
}
|
||||
},
|
||||
"abort": {
|
||||
"one_instance_allowed": "Only a single instance is allowed.",
|
||||
"no_credential": "You need to add your credentails."
|
||||
|
||||
},
|
||||
"create_entry": {
|
||||
"default": "\n\nLogin succes"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,22 @@
|
||||
""" georide custom conpennt """
|
||||
from collections import defaultdict
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Any, Mapping
|
||||
from datetime import timedelta
|
||||
import math
|
||||
import time
|
||||
import json
|
||||
from threading import Thread
|
||||
import voluptuous as vol
|
||||
|
||||
import jwt
|
||||
|
||||
from aiohttp.web import json_response
|
||||
from georideapilib.objects import GeorideAccount
|
||||
import georideapilib.api as GeorideApi
|
||||
from georideapilib.objects import GeoRideAccount
|
||||
import georideapilib.api as GeoRideApi
|
||||
|
||||
from georideapilib.socket import GeoRideSocket
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.const import CONF_WEBHOOK_ID
|
||||
@@ -18,14 +25,25 @@ import homeassistant.helpers.config_validation as cv
|
||||
import homeassistant.helpers.event as ha_event
|
||||
|
||||
from homeassistant.setup import async_when_setup
|
||||
from homeassistant.helpers.typing import HomeAssistantType
|
||||
from homeassistant.helpers.update_coordinator import (
|
||||
CoordinatorEntity,
|
||||
DataUpdateCoordinator,
|
||||
)
|
||||
|
||||
|
||||
from .device import Device
|
||||
from .const import (
|
||||
CONF_EMAIL,
|
||||
CONF_PASSWORD,
|
||||
TRACKER_ID
|
||||
CONF_TOKEN,
|
||||
TRACKER_ID,
|
||||
TOKEN_SAFE_DAY,
|
||||
MIN_UNTIL_REFRESH,
|
||||
DOMAIN
|
||||
)
|
||||
|
||||
DOMAIN = "georide"
|
||||
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -42,90 +60,84 @@ CONFIG_SCHEMA = vol.Schema(
|
||||
|
||||
|
||||
async def async_setup(hass, config):
|
||||
"""Setup Georide component."""
|
||||
"""Setup GeoRide component."""
|
||||
hass.data[DOMAIN] = {"config": config[DOMAIN], "devices": {}, "unsub": None}
|
||||
hass.async_create_task(
|
||||
hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data={}
|
||||
DOMAIN,
|
||||
context={
|
||||
"source": config_entries.SOURCE_IMPORT
|
||||
},
|
||||
data={}
|
||||
)
|
||||
)
|
||||
|
||||
_LOGGER.info("Georide-setup ")
|
||||
|
||||
# Return boolean to indicate that initialization was successful.
|
||||
return True
|
||||
|
||||
|
||||
|
||||
async def async_setup_entry(hass, entry):
|
||||
"""Set up Georide entry."""
|
||||
|
||||
def georide_update(event):
|
||||
"""Update tracker info"""
|
||||
nonlocal hass
|
||||
_LOGGER.info('Georide update event %s', event)
|
||||
georide_context = hass.data[DOMAIN]["context"]
|
||||
token = georide_context.async_get_token()
|
||||
trackers = GeorideApi.get_trackers(token)
|
||||
georide_context.georide_trackers = trackers
|
||||
|
||||
ha_event.async_track_time_interval(hass, georide_update, timedelta(seconds=30))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"""Set up GeoRide entry."""
|
||||
config = hass.data[DOMAIN]["config"]
|
||||
email = config.get(CONF_EMAIL) or entry.data[CONF_EMAIL]
|
||||
password = config.get(CONF_PASSWORD) or entry.data[CONF_PASSWORD]
|
||||
|
||||
if email is None or password is None:
|
||||
return False
|
||||
|
||||
account = GeorideApi.get_authorisation_token(email, password)
|
||||
context = GeorideContext(
|
||||
token = config.get(CONF_TOKEN) or entry.data[CONF_TOKEN]
|
||||
context = GeoRideContext(
|
||||
hass,
|
||||
email,
|
||||
password,
|
||||
account.auth_token
|
||||
token
|
||||
)
|
||||
|
||||
_LOGGER.info("Context-setup and start the thread")
|
||||
_LOGGER.info("Thread started")
|
||||
|
||||
hass.data[DOMAIN]["context"] = context
|
||||
|
||||
# We add trackers to the context
|
||||
trackers = GeorideApi.get_trackers(account.auth_token)
|
||||
context.georide_trackers = trackers
|
||||
|
||||
hass.async_create_task(hass.config_entries.async_forward_entry_setup(entry, "device_tracker"))
|
||||
hass.async_create_task(hass.config_entries.async_forward_entry_setup(entry, "switch"))
|
||||
|
||||
|
||||
await context.init_context(hass)
|
||||
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(entry, "device_tracker"))
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(entry, "switch"))
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(entry, "sensor"))
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(entry, "binary_sensor"))
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass, entry):
|
||||
"""Unload an Georide config entry."""
|
||||
"""Unload an GeoRide config entry."""
|
||||
|
||||
await hass.config_entries.async_forward_entry_unload(entry, "device_tracker")
|
||||
await hass.config_entries.async_forward_entry_unload(entry, "switch")
|
||||
await hass.config_entries.async_forward_entry_unload(entry, "sensor")
|
||||
await hass.config_entries.async_forward_entry_unload(entry, "binary_sensor")
|
||||
|
||||
hass.data[DOMAIN]["unsub"]()
|
||||
|
||||
context = hass.data[DOMAIN]["context"]
|
||||
context.socket.disconnect()
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class GeorideContext:
|
||||
"""Hold the current Georide context."""
|
||||
|
||||
class GeoRideContext:
|
||||
"""Hold the current GeoRide context."""
|
||||
|
||||
def __init__(self, hass, email, password, token):
|
||||
"""Initialize an Georide context."""
|
||||
"""Initialize an GeoRide context."""
|
||||
self._hass = hass
|
||||
self._email = email
|
||||
self._password = password
|
||||
self._georide_trackers = defaultdict(set)
|
||||
self._georide_trackers_coordoned = []
|
||||
self._georide_trackers = []
|
||||
self._token = token
|
||||
self._pending_msg = []
|
||||
|
||||
self._socket = None
|
||||
self._thread_started = False
|
||||
self._previous_refresh = math.floor(time.time()/60)
|
||||
@property
|
||||
def hass(self):
|
||||
""" hass """
|
||||
@@ -135,7 +147,7 @@ class GeorideContext:
|
||||
def email(self):
|
||||
""" current email """
|
||||
return self._email
|
||||
|
||||
|
||||
@property
|
||||
def password(self):
|
||||
""" password """
|
||||
@@ -148,29 +160,236 @@ class GeorideContext:
|
||||
|
||||
@property
|
||||
def georide_trackers(self):
|
||||
""" georide tracker list """
|
||||
""" GeoRide tracker list """
|
||||
return self._georide_trackers
|
||||
|
||||
@georide_trackers.setter
|
||||
def georide_trackers(self, trackers):
|
||||
""" georide tracker list """
|
||||
""" GeoRide tracker list """
|
||||
self._georide_trackers = trackers
|
||||
|
||||
@callback
|
||||
def async_get_token(self):
|
||||
""" here we return the current valid tocken, TODO: add here token expiration control"""
|
||||
async def connect_socket(self):
|
||||
"""subscribe to GeoRide socket"""
|
||||
_LOGGER.info("GeoRide socket connexion")
|
||||
socket = GeoRideSocket()
|
||||
socket.subscribe_locked(self.on_lock_callback)
|
||||
socket.subscribe_device(self.on_device_callback)
|
||||
socket.subscribe_position(self.on_position_callback)
|
||||
socket.subscribe_alarm(self.on_alarm_callback)
|
||||
|
||||
self._socket = socket
|
||||
|
||||
socket.init()
|
||||
self._hass.async_add_executor_job(socket.connect, await self.get_token())
|
||||
|
||||
async def get_token(self):
|
||||
""" here we return the current valid tocken """
|
||||
jwt_data = jwt.decode(self._token, verify=False)
|
||||
exp_timestamp = jwt_data['exp']
|
||||
|
||||
epoch = math.ceil(time.time())
|
||||
if (exp_timestamp - TOKEN_SAFE_DAY) < epoch:
|
||||
_LOGGER.info("Time reached, renew token")
|
||||
account = await self._hass.async_add_executor_job(GeoRideApi.get_authorisation_token,
|
||||
self._email, self._password)
|
||||
config = self._hass.data[DOMAIN]["config"]
|
||||
config[CONF_TOKEN] = account.auth_token
|
||||
self._token = account.auth_token
|
||||
|
||||
|
||||
_LOGGER.info("Token exp data: %s", exp_timestamp)
|
||||
return self._token
|
||||
|
||||
@callback
|
||||
def async_get_tracker(self, tracker_id):
|
||||
""" here we return the current valid tocken, TODO: add here token expiration control"""
|
||||
async def get_tracker(self, tracker_id):
|
||||
""" here we return last tracker by id"""
|
||||
await self.refresh_trackers()
|
||||
for tracker in self._georide_trackers:
|
||||
if tracker.tracker_id == tracker_id:
|
||||
return tracker
|
||||
return None
|
||||
return {}
|
||||
|
||||
async def refresh_trackers(self):
|
||||
""" here we return last tracker by id"""
|
||||
_LOGGER.debug("Call refresh tracker")
|
||||
epoch_min = math.floor(time.time()/60)
|
||||
#if (epoch_min % MIN_UNTIL_REFRESH) == 0:
|
||||
if epoch_min != self._previous_refresh:
|
||||
self._previous_refresh = epoch_min
|
||||
await self.force_refresh_trackers()
|
||||
#else:
|
||||
# _LOGGER.debug("We wil dont refresh the tracker list")
|
||||
|
||||
|
||||
async def force_refresh_trackers(self):
|
||||
"""Used to refresh the tracker list"""
|
||||
_LOGGER.info("Tracker list refresh")
|
||||
new_georide_trackers = await self._hass.async_add_executor_job(GeoRideApi.get_trackers,
|
||||
await self.get_token())
|
||||
for refreshed_tracker in new_georide_trackers:
|
||||
found = False
|
||||
for tracker in self._georide_trackers:
|
||||
if tracker.tracker_id == refreshed_tracker.tracker_id:
|
||||
tracker.update_all_data(refreshed_tracker)
|
||||
found = True
|
||||
if not found:
|
||||
self._georide_trackers.append(refreshed_tracker)
|
||||
if not self._thread_started:
|
||||
_LOGGER.info("Start the thread")
|
||||
# We refresh the tracker list each hours
|
||||
self._thread_started = True
|
||||
await self.connect_socket()
|
||||
|
||||
|
||||
|
||||
async def init_context(self, hass):
|
||||
"""Used to refresh the tracker list"""
|
||||
_LOGGER.info("Init_context")
|
||||
await self.force_refresh_trackers()
|
||||
update_interval = timedelta(minutes=MIN_UNTIL_REFRESH)
|
||||
|
||||
for tracker in self._georide_trackers:
|
||||
coordinator = DataUpdateCoordinator[Mapping[str, Any]](
|
||||
hass,
|
||||
_LOGGER,
|
||||
name=tracker.tracker_name,
|
||||
update_method=self.refresh_trackers,
|
||||
update_interval=update_interval
|
||||
)
|
||||
self._georide_trackers_coordoned.append({
|
||||
"tracker_device": Device(tracker),
|
||||
"coordinator": coordinator
|
||||
})
|
||||
|
||||
|
||||
def get_coordoned_trackers(self):
|
||||
"""Return coordoned trackers"""
|
||||
|
||||
return self._georide_trackers_coordoned
|
||||
|
||||
@property
|
||||
def socket(self):
|
||||
""" hold the GeoRide socket """
|
||||
return self._socket
|
||||
|
||||
@socket.setter
|
||||
def socket(self, socket):
|
||||
"""set the GeoRide socket"""
|
||||
self._socket = socket
|
||||
|
||||
@callback
|
||||
def async_see(self, **data):
|
||||
"""Send a see message to the device tracker."""
|
||||
_LOGGER.info("sync_see")
|
||||
self._pending_msg.append(data)
|
||||
def on_lock_callback(self, data):
|
||||
"""on lock callback"""
|
||||
_LOGGER.info("On lock received")
|
||||
for coordoned_tracker in self._georide_trackers_coordoned:
|
||||
tracker = coordoned_tracker['tracker_device'].tracker
|
||||
coordinator = coordoned_tracker['coordinator']
|
||||
if tracker.tracker_id == data['trackerId']:
|
||||
tracker.locked_latitude = data['lockedLatitude']
|
||||
tracker.locked_longitude = data['lockedLongitude']
|
||||
tracker.is_locked = data['isLocked']
|
||||
|
||||
event_data = {
|
||||
"device_id": tracker.tracker_id,
|
||||
"device_name": tracker.tracker_name
|
||||
}
|
||||
self._hass.bus.async_fire(f"{DOMAIN}_lock_event", event_data)
|
||||
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
coordinator.async_request_refresh(), self._hass.loop
|
||||
).result()
|
||||
break
|
||||
|
||||
|
||||
@callback
|
||||
def on_device_callback(self, data):
|
||||
"""on device callback"""
|
||||
_LOGGER.info("On device received")
|
||||
for coordoned_tracker in self._georide_trackers_coordoned:
|
||||
tracker = coordoned_tracker['tracker_device'].tracker
|
||||
coordinator = coordoned_tracker['coordinator']
|
||||
if tracker.tracker_id == data['trackerId']:
|
||||
tracker.status = data['status']
|
||||
|
||||
event_data = {
|
||||
"device_id": tracker.tracker_id,
|
||||
"device_name": tracker.tracker_name,
|
||||
}
|
||||
self._hass.bus.async_fire(f"{DOMAIN}_device_event", event_data)
|
||||
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
coordinator.async_request_refresh(), self._hass.loop
|
||||
).result()
|
||||
break
|
||||
|
||||
@callback
|
||||
def on_alarm_callback(self, data):
|
||||
"""on device callback"""
|
||||
_LOGGER.info("On alarm received")
|
||||
for coordoned_tracker in self._georide_trackers_coordoned:
|
||||
tracker = coordoned_tracker['tracker_device'].tracker
|
||||
coordinator = coordoned_tracker['coordinator']
|
||||
if tracker.tracker_id == data['trackerId']:
|
||||
if data.name == 'vibration':
|
||||
_LOGGER.info("Vibration detected")
|
||||
elif data.name == 'exitZone':
|
||||
_LOGGER.info("Exit zone detected")
|
||||
elif data.name == 'crash':
|
||||
_LOGGER.info("Crash detected")
|
||||
elif data.name == 'crashParking':
|
||||
_LOGGER.info("Crash parking detected")
|
||||
elif data.name == 'deviceOffline':
|
||||
_LOGGER.info("Device offline detected")
|
||||
elif data.name == 'deviceOnline':
|
||||
_LOGGER.info("Device online detected")
|
||||
elif data.name == 'powerCut':
|
||||
_LOGGER.info("powerCut detected")
|
||||
elif data.name == 'powerUncut':
|
||||
_LOGGER.info("powerUncut detected")
|
||||
elif data.name == 'batteryWarning':
|
||||
_LOGGER.info("batteryWarning detected")
|
||||
elif data.name == 'temperatureWarning':
|
||||
_LOGGER.info("temperatureWarning detected")
|
||||
elif data.name == 'magnetOn':
|
||||
_LOGGER.info("magnetOn detected")
|
||||
elif data.name == 'magnetOff':
|
||||
_LOGGER.info("magnetOff detected")
|
||||
elif data.name == 'sonorAlarmOn':
|
||||
_LOGGER.info("sonorAlarmOn detected")
|
||||
else:
|
||||
_LOGGER.warning("Unmanaged alarm: %s", data.name)
|
||||
|
||||
event_data = {
|
||||
"device_id": tracker.tracker_id,
|
||||
"device_name": tracker.tracker_name,
|
||||
"type": f"alarm_{data.name}"
|
||||
}
|
||||
self._hass.bus.fire(f"{DOMAIN}_alarm_event", event_data)
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
coordinator.async_request_refresh(), self._hass.loop
|
||||
).result()
|
||||
break
|
||||
|
||||
@callback
|
||||
def on_position_callback(self, data):
|
||||
"""on position callback"""
|
||||
_LOGGER.info("On position received")
|
||||
for coordoned_tracker in self._georide_trackers_coordoned:
|
||||
tracker = coordoned_tracker['tracker_device'].tracker
|
||||
coordinator = coordoned_tracker['coordinator']
|
||||
if tracker.tracker_id == data['trackerId']:
|
||||
tracker.latitude = data['latitude']
|
||||
tracker.longitude = data['longitude']
|
||||
tracker.moving = data['moving']
|
||||
tracker.speed = data['speed']
|
||||
tracker.fixtime = data['fixtime']
|
||||
|
||||
event_data = {
|
||||
"device_id": tracker.tracker_id,
|
||||
"device_name": tracker.tracker_name
|
||||
}
|
||||
self._hass.bus.async_fire(f"{DOMAIN}_position_event", event_data)
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
coordinator.async_request_refresh(), self._hass.loop
|
||||
).result()
|
||||
break
|
||||
|
||||
|
||||
157
custom_components/georide/binary_sensor.py
Normal file
157
custom_components/georide/binary_sensor.py
Normal file
@@ -0,0 +1,157 @@
|
||||
""" binary_sensor for GeoRide object """
|
||||
|
||||
import logging
|
||||
|
||||
from typing import Any, Mapping
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.components.binary_sensor import BinarySensorEntity
|
||||
from homeassistant.components.binary_sensor import ENTITY_ID_FORMAT
|
||||
from homeassistant.helpers.update_coordinator import (
|
||||
CoordinatorEntity,
|
||||
DataUpdateCoordinator
|
||||
)
|
||||
|
||||
|
||||
from .const import DOMAIN as GEORIDE_DOMAIN
|
||||
from .device import Device
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: disable=W0613
|
||||
"""Set up GeoRide tracker based off an entry."""
|
||||
georide_context = hass.data[GEORIDE_DOMAIN]["context"]
|
||||
entities = []
|
||||
coordoned_trackers = georide_context.get_coordoned_trackers()
|
||||
for coordoned_tracker in coordoned_trackers:
|
||||
tracker_device = coordoned_tracker['tracker_device']
|
||||
coordinator = coordoned_tracker['coordinator']
|
||||
|
||||
entities.append(GeoRideStolenBinarySensorEntity(coordinator, tracker_device))
|
||||
entities.append(GeoRideCrashedBinarySensorEntity(coordinator, tracker_device))
|
||||
entities.append(GeoRideOwnerBinarySensorEntity(coordinator, tracker_device))
|
||||
entities.append(GeoRideActiveSubscriptionBinarySensorEntity(coordinator, tracker_device))
|
||||
|
||||
hass.data[GEORIDE_DOMAIN]["devices"][tracker_device.tracker.tracker_id] = coordinator
|
||||
|
||||
async_add_entities(entities, True)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class GeoRideBinarySensorEntity(CoordinatorEntity, BinarySensorEntity):
|
||||
"""Represent a tracked device."""
|
||||
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
|
||||
tracker_device: Device):
|
||||
"""Set up Georide entity."""
|
||||
super().__init__(coordinator)
|
||||
self._tracker_device = tracker_device
|
||||
self._name = tracker_device.tracker.tracker_name
|
||||
|
||||
self.entity_id = f"{ENTITY_ID_FORMAT.format('binary_sensor')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
|
||||
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
|
||||
def unique_id(self):
|
||||
"""Return the unique ID."""
|
||||
return f"is_stolen_{self._tracker_device.tracker.tracker_id}"
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""state value property"""
|
||||
return self._tracker_device.tracker.is_stolen
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
""" GeoRide odometer name """
|
||||
return f"{self._name} is stolen"
|
||||
|
||||
|
||||
class GeoRideCrashedBinarySensorEntity(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_crashed')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return the unique ID."""
|
||||
return f"is_crashed_{self._tracker_device.tracker.tracker_id}"
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""state value property"""
|
||||
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."""
|
||||
|
||||
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_device.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."""
|
||||
|
||||
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_owner')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return the unique ID."""
|
||||
return f"is_owner_{self._tracker_device.tracker.tracker_id}"
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""state value property"""
|
||||
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"
|
||||
|
||||
@@ -3,58 +3,70 @@
|
||||
import logging
|
||||
from homeassistant import config_entries
|
||||
import voluptuous as vol
|
||||
import georideapilib.api as GeoRideApi
|
||||
import georideapilib.exception as GeoRideException
|
||||
|
||||
|
||||
from .const import CONF_EMAIL, CONF_PASSWORD
|
||||
from .const import CONF_EMAIL, CONF_PASSWORD, CONF_TOKEN, DOMAIN
|
||||
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@config_entries.HANDLERS.register("georide")
|
||||
class GeorideConfigFlow(config_entries.ConfigFlow):
|
||||
"""Georide config flow """
|
||||
class GeoRideConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""GeoRide config flow """
|
||||
|
||||
async def async_step_user(self, user_input=None):
|
||||
""" handle info to help to configure georide """
|
||||
async def async_step_user(self, user_input=None): #pylint: disable=W0613
|
||||
""" handle info to help to configure GeoRide """
|
||||
|
||||
if self._async_current_entries():
|
||||
return self.async_abort(reason="one_instance_allowed")
|
||||
|
||||
if user_input is None:
|
||||
return self.async_show_form(step_id='user', data_schema=vol.Schema({
|
||||
vol.Required(CONF_EMAIL): vol.All(str, vol.Length(min=3)),
|
||||
vol.Required(CONF_PASSWORD): vol.All(str)
|
||||
}))
|
||||
return self.async_show_form(step_id='georide_login', data_schema=vol.Schema({
|
||||
vol.Required(CONF_EMAIL): vol.All(str, vol.Length(min=3)),
|
||||
vol.Required(CONF_PASSWORD): vol.All(str)
|
||||
}))
|
||||
|
||||
return self.async_create_entry(
|
||||
title=user_input[CONF_EMAIL],
|
||||
data={
|
||||
CONF_EMAIL: user_input[CONF_EMAIL],
|
||||
CONF_PASSWORD: user_input[CONF_PASSWORD]
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
|
||||
async def async_step_import(self, user_input):
|
||||
async def async_step_import(self, user_input=None): #pylint: disable=W0613
|
||||
"""Import a config flow from configuration."""
|
||||
|
||||
_LOGGER.info("user email: %", str(user_input))
|
||||
|
||||
if self._async_current_entries():
|
||||
return self.async_abort(reason="one_instance_allowed")
|
||||
|
||||
if user_input is None:
|
||||
return self.async_show_form(step_id='user', data_schema=vol.Schema({
|
||||
vol.Required(CONF_EMAIL): vol.All(str, vol.Length(min=3)),
|
||||
vol.Required(CONF_PASSWORD): vol.All(str)
|
||||
}))
|
||||
return self.async_show_form(step_id='georide_login', data_schema=vol.Schema({
|
||||
vol.Required(CONF_EMAIL): vol.All(str, vol.Length(min=3)),
|
||||
vol.Required(CONF_PASSWORD): vol.All(str)
|
||||
}))
|
||||
|
||||
return self.async_create_entry(
|
||||
title=user_input,
|
||||
data={
|
||||
CONF_EMAIL: user_input[CONF_EMAIL],
|
||||
CONF_PASSWORD: user_input[CONF_PASSWORD]
|
||||
|
||||
|
||||
async def async_step_georide_login(self, user_input):
|
||||
""" try to seupt GeoRide Account """
|
||||
|
||||
schema = vol.Schema({
|
||||
vol.Required(CONF_EMAIL): vol.All(str, vol.Length(min=3)),
|
||||
vol.Required(CONF_PASSWORD): vol.All(str)
|
||||
})
|
||||
|
||||
if user_input is None:
|
||||
return self.async_show_form(step_id='georide_login', data_schema=schema)
|
||||
|
||||
email = user_input[CONF_EMAIL]
|
||||
password = user_input[CONF_PASSWORD]
|
||||
|
||||
try:
|
||||
account = await self.hass.async_add_executor_job(GeoRideApi.get_authorisation_token, email, password)
|
||||
data = {
|
||||
CONF_EMAIL: email,
|
||||
CONF_PASSWORD: password,
|
||||
CONF_TOKEN: account.auth_token
|
||||
}
|
||||
)
|
||||
return self.async_create_entry(title=email, data=data)
|
||||
except (GeoRideException.SeverException, GeoRideException.LoginException):
|
||||
_LOGGER.error("Invalid credentials provided, config not created")
|
||||
errors = {"base": "faulty_credentials"}
|
||||
return self.async_show_form(step_id="georide_login", data_schema=schema, errors=errors)
|
||||
except:
|
||||
_LOGGER.error("Unknown error")
|
||||
errors = {"base": "unkonwn"}
|
||||
return self.async_show_form(step_id="georide_login", data_schema=schema, errors=errors)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
""" Georide const file """
|
||||
""" GeoRide const file """
|
||||
DOMAIN = "georide"
|
||||
|
||||
CONF_EMAIL = "email"
|
||||
CONF_PASSWORD = "password"
|
||||
@@ -6,3 +7,7 @@ CONF_PASSWORD = "password"
|
||||
CONF_TOKEN = "token"
|
||||
|
||||
TRACKER_ID = "trackerId"
|
||||
|
||||
MIN_UNTIL_REFRESH = 10
|
||||
|
||||
TOKEN_SAFE_DAY = 432000 # five days
|
||||
|
||||
57
custom_components/georide/device.py
Normal file
57
custom_components/georide/device.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""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 tracker(self):
|
||||
"""return the tracker"""
|
||||
return self._tracker
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Get the name."""
|
||||
return self._tracker.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"
|
||||
@@ -1,87 +1,81 @@
|
||||
""" device tracker for Georide object """
|
||||
""" device tracker for GeoRide object """
|
||||
|
||||
import logging
|
||||
from typing import Any, Mapping
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.components.device_tracker.const import ENTITY_ID_FORMAT, SOURCE_TYPE_GPS
|
||||
from homeassistant.components.device_tracker.const import DOMAIN, SOURCE_TYPE_GPS
|
||||
from homeassistant.components.device_tracker.config_entry import TrackerEntity
|
||||
|
||||
import georideapilib.api as GeorideApi
|
||||
from homeassistant.helpers.update_coordinator import (
|
||||
CoordinatorEntity,
|
||||
DataUpdateCoordinator,
|
||||
)
|
||||
|
||||
from . import DOMAIN as GEORIDE_DOMAIN
|
||||
from .device import Device
|
||||
from .const import DOMAIN as GEORIDE_DOMAIN
|
||||
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: disable=W0613
|
||||
"""Set up Georide tracker based off an entry."""
|
||||
|
||||
georide_context = hass.data[GEORIDE_DOMAIN]["context"]
|
||||
|
||||
if georide_context.token is None:
|
||||
return False
|
||||
coordoned_trackers = georide_context.get_coordoned_trackers()
|
||||
|
||||
_LOGGER.info('Current georide token: %s', georide_context.async_get_token())
|
||||
entities = []
|
||||
for coordoned_tracker in coordoned_trackers:
|
||||
tracker_device = coordoned_tracker['tracker_device']
|
||||
coordinator = coordoned_tracker['coordinator']
|
||||
entity = GeoRideTrackerEntity(coordinator, tracker_device, hass)
|
||||
hass.data[GEORIDE_DOMAIN]["devices"][tracker_device.tracker.tracker_id] = coordinator
|
||||
entities.append(entity)
|
||||
|
||||
|
||||
trackers = GeorideApi.get_trackers(georide_context.async_get_token())
|
||||
|
||||
|
||||
tracker_entities = []
|
||||
for tracker in trackers:
|
||||
entity = GeorideTrackerEntity(tracker.tracker_id, georide_context.async_get_token,
|
||||
georide_context.async_get_tracker, tracker)
|
||||
|
||||
|
||||
hass.data[GEORIDE_DOMAIN]["devices"][tracker.tracker_id] = entity
|
||||
tracker_entities.append(entity)
|
||||
|
||||
async_add_entities(tracker_entities)
|
||||
async_add_entities(entities)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class GeorideTrackerEntity(TrackerEntity):
|
||||
class GeoRideTrackerEntity(CoordinatorEntity, TrackerEntity):
|
||||
"""Represent a tracked device."""
|
||||
|
||||
def __init__(self, tracker_id, get_token_callback, get_tracker_callback, tracker):
|
||||
"""Set up Georide entity."""
|
||||
self._tracker_id = tracker_id
|
||||
self._get_token_callback = get_token_callback
|
||||
self._get_tracker_callback = get_tracker_callback
|
||||
self._name = tracker.tracker_name
|
||||
self._data = tracker or {}
|
||||
self.entity_id = ENTITY_ID_FORMAT.format(tracker_id)
|
||||
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
|
||||
tracker_device: Device, hass):
|
||||
"""Set up GeoRide entity."""
|
||||
super().__init__(coordinator)
|
||||
self._name = tracker_device.tracker.tracker_name
|
||||
self._tracker_device = tracker_device
|
||||
self.entity_id = DOMAIN + ".{}".format(tracker_device.tracker.tracker_id)
|
||||
self._hass = hass
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return the unique ID."""
|
||||
return self._tracker_id
|
||||
return f"georide_tracker_{self._tracker_device.tracker.tracker_id}"
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name
|
||||
|
||||
""" GeoRide odometer name """
|
||||
return f"{self._name} position"
|
||||
|
||||
@property
|
||||
def latitude(self):
|
||||
"""Return latitude value of the device."""
|
||||
if self._data.latitude:
|
||||
return self._data.latitude
|
||||
if self._tracker_device.tracker.latitude:
|
||||
return self._tracker_device.tracker.latitude
|
||||
return None
|
||||
|
||||
@property
|
||||
def longitude(self):
|
||||
"""Return longitude value of the device."""
|
||||
if self._data.longitude:
|
||||
return self._data.longitude
|
||||
|
||||
if self._tracker_device.tracker.longitude:
|
||||
return self._tracker_device.tracker.longitude
|
||||
return None
|
||||
|
||||
@property
|
||||
def source_type(self):
|
||||
"""Return the source type, eg gps or router, of the device."""
|
||||
return SOURCE_TYPE_GPS
|
||||
|
||||
|
||||
@property
|
||||
def location_accuracy(self):
|
||||
""" return the gps accuracy of georide (could not be aquired, then 10) """
|
||||
@@ -89,39 +83,10 @@ class GeorideTrackerEntity(TrackerEntity):
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""return the entity icon"""
|
||||
return "mdi:map-marker"
|
||||
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device info."""
|
||||
return {
|
||||
"name": self.name,
|
||||
"identifiers": {(GEORIDE_DOMAIN, self._tracker_id)},
|
||||
"manufacturer": "GeoRide",
|
||||
"odometer": "{} km".format(self._data.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
|
||||
|
||||
async def async_update(self):
|
||||
""" update the current tracker"""
|
||||
_LOGGER.info('async_update ')
|
||||
self._data = self._get_tracker_callback(self._tracker_id)
|
||||
self._name = self._data.tracker_name
|
||||
return
|
||||
|
||||
return self._tracker_device.device_info
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
{
|
||||
"domain": "georide",
|
||||
"name": "Georide",
|
||||
"name": "GeoRide",
|
||||
"config_flow": true,
|
||||
"documentation": "https://git.tontontux.fr/mduval/GeorideHA",
|
||||
"documentation": "https://github.com/ptimatth/GeorideHA",
|
||||
"requirements": [
|
||||
"georideapilib>=0.2.0"
|
||||
"georideapilib>=0.6.1",
|
||||
"pyjwt>=1.7.1"
|
||||
],
|
||||
"dependencies": [],
|
||||
"codeowners": ["@ptimatth"]
|
||||
"codeowners": ["ptimatth"],
|
||||
"version": "0.7.0"
|
||||
}
|
||||
81
custom_components/georide/sensor.py
Normal file
81
custom_components/georide/sensor.py
Normal file
@@ -0,0 +1,81 @@
|
||||
""" odometter sensor for GeoRide object """
|
||||
|
||||
import logging
|
||||
from typing import Any, Mapping
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.components.sensor import SensorEntity
|
||||
from homeassistant.components.sensor import ENTITY_ID_FORMAT
|
||||
from homeassistant.helpers.update_coordinator import (
|
||||
CoordinatorEntity,
|
||||
DataUpdateCoordinator,
|
||||
)
|
||||
|
||||
from .const import DOMAIN as GEORIDE_DOMAIN
|
||||
from .device import Device
|
||||
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: disable=W0613
|
||||
"""Set up GeoRide tracker based off an entry."""
|
||||
georide_context = hass.data[GEORIDE_DOMAIN]["context"]
|
||||
coordoned_trackers = georide_context.get_coordoned_trackers()
|
||||
|
||||
entities = []
|
||||
for coordoned_tracker in coordoned_trackers:
|
||||
tracker_device = coordoned_tracker['tracker_device']
|
||||
coordinator = coordoned_tracker['coordinator']
|
||||
entity = GeoRideOdometerSensorEntity(coordinator, tracker_device, hass)
|
||||
hass.data[GEORIDE_DOMAIN]["devices"][tracker_device.tracker.tracker_id] = coordinator
|
||||
entities.append(entity)
|
||||
|
||||
async_add_entities(entities)
|
||||
|
||||
return True
|
||||
|
||||
class GeoRideOdometerSensorEntity(CoordinatorEntity, SensorEntity):
|
||||
"""Represent a tracked device."""
|
||||
|
||||
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
|
||||
tracker_device:Device, hass):
|
||||
"""Set up GeoRide entity."""
|
||||
super().__init__(coordinator)
|
||||
self._tracker_device = tracker_device
|
||||
self._name = tracker_device.tracker.tracker_name
|
||||
self._unit_of_measurement = "m"
|
||||
self.entity_id = f"{ENTITY_ID_FORMAT.format('odometer')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
|
||||
|
||||
self._state = 0
|
||||
self._hass = hass
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return the unique ID."""
|
||||
return f"odometer_{self._tracker_device.tracker.tracker_id}"
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""state property"""
|
||||
return self._tracker_device.tracker.odometer
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""unit of mesurment property"""
|
||||
return self._unit_of_measurement
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
""" GeoRide odometer name """
|
||||
return f"{self._name} odometer"
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""icon getter"""
|
||||
return "mdi:counter"
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device info."""
|
||||
return self._tracker_device.device_info
|
||||
@@ -2,19 +2,21 @@
|
||||
"config": {
|
||||
"title": "GeoRide",
|
||||
"step": {
|
||||
"user": {
|
||||
"georide_login": {
|
||||
"title": "Set up GeoRide",
|
||||
"description": "Are you sure you want to set up GeoRide ?",
|
||||
"description": "Sign-in to GeoRide",
|
||||
"data": {
|
||||
"email": "email",
|
||||
"password": "password"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"faulty_credentials": "Authorization failed",
|
||||
"unknown": "Unknown error"
|
||||
},
|
||||
"abort": {
|
||||
"one_instance_allowed": "Only a single instance is allowed.",
|
||||
"no_credential": "You need to add your credentails."
|
||||
|
||||
"one_instance_allowed": "Only a single instance is allowed."
|
||||
},
|
||||
"create_entry": {
|
||||
"default": "\n\nLogin succes"
|
||||
|
||||
@@ -1,131 +1,107 @@
|
||||
""" device tracker for Georide object """
|
||||
""" device tracker for GeoRide object """
|
||||
|
||||
import logging
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.components.switch import SwitchDevice
|
||||
|
||||
from typing import Any, Mapping
|
||||
|
||||
from homeassistant.components.switch import SwitchEntity
|
||||
from homeassistant.components.switch import ENTITY_ID_FORMAT
|
||||
|
||||
import georideapilib.api as GeorideApi
|
||||
from homeassistant.helpers.update_coordinator import (
|
||||
CoordinatorEntity,
|
||||
DataUpdateCoordinator,
|
||||
)
|
||||
|
||||
from . import DOMAIN as GEORIDE_DOMAIN
|
||||
import georideapilib.api as GeoRideApi
|
||||
|
||||
from .const import DOMAIN as GEORIDE_DOMAIN
|
||||
from .device import Device
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities): # pylint: disable=W0613
|
||||
"""Set up Georide tracker based off an entry."""
|
||||
georide_context = hass.data[GEORIDE_DOMAIN]["context"]
|
||||
|
||||
if georide_context.async_get_token() is None:
|
||||
return False
|
||||
|
||||
|
||||
_LOGGER.info('Current georide token: %s', georide_context.async_get_token())
|
||||
trackers = GeorideApi.get_trackers(georide_context.async_get_token())
|
||||
"""Set up GeoRide tracker based off an entry."""
|
||||
georide_context = hass.data[GEORIDE_DOMAIN]["context"]
|
||||
coordoned_trackers = georide_context.get_coordoned_trackers()
|
||||
|
||||
lock_switch_entities = []
|
||||
for tracker in trackers:
|
||||
entity = GeorideLockSwitchEntity(tracker.tracker_id, georide_context.async_get_token,
|
||||
georide_context.async_get_tracker, data=tracker)
|
||||
hass.data[GEORIDE_DOMAIN]["devices"][tracker.tracker_id] = entity
|
||||
for coordoned_tracker in coordoned_trackers:
|
||||
tracker_device = coordoned_tracker['tracker_device']
|
||||
coordinator = coordoned_tracker['coordinator']
|
||||
entity = GeoRideLockSwitchEntity(coordinator, tracker_device, hass)
|
||||
hass.data[GEORIDE_DOMAIN]["devices"][tracker_device.tracker.tracker_id] = coordinator
|
||||
lock_switch_entities.append(entity)
|
||||
|
||||
async_add_entities(lock_switch_entities)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
|
||||
class GeorideLockSwitchEntity(SwitchDevice):
|
||||
class GeoRideLockSwitchEntity(CoordinatorEntity, SwitchEntity):
|
||||
"""Represent a tracked device."""
|
||||
|
||||
def __init__(self, tracker_id, get_token_callback, get_tracker_callback, data):
|
||||
"""Set up Georide entity."""
|
||||
self._tracker_id = tracker_id
|
||||
self._data = data or {}
|
||||
self._get_token_callback = get_token_callback
|
||||
self._get_tracker_callback = get_tracker_callback
|
||||
self._name = data.tracker_name
|
||||
self._is_on = data.is_locked
|
||||
self.entity_id = ENTITY_ID_FORMAT.format("lock."+str(tracker_id))
|
||||
self._state = {}
|
||||
|
||||
def __init__(self, coordinator: DataUpdateCoordinator[Mapping[str, Any]],
|
||||
tracker_device:Device, hass):
|
||||
"""Set up GeoRide entity."""
|
||||
super().__init__(coordinator)
|
||||
self._tracker_device = tracker_device
|
||||
self._name = tracker_device.tracker.tracker_name
|
||||
self.entity_id = f"{ENTITY_ID_FORMAT.format('lock')}.{tracker_device.tracker.tracker_id}"# pylint: disable=C0301
|
||||
self._hass = hass
|
||||
|
||||
async def async_turn_on(self, **kwargs):
|
||||
""" lock the georide tracker """
|
||||
""" lock the GeoRide tracker """
|
||||
_LOGGER.info('async_turn_on %s', kwargs)
|
||||
success = GeorideApi.lock_tracker(self._get_token_callback(), self._tracker_id)
|
||||
georide_context = self._hass.data[GEORIDE_DOMAIN]["context"]
|
||||
token = await georide_context.get_token()
|
||||
success = await self._hass.async_add_executor_job(GeoRideApi.lock_tracker,
|
||||
token, self._tracker_device.tracker.tracker_id)
|
||||
if success:
|
||||
self._is_on = True
|
||||
|
||||
self._tracker_device.tracker.is_locked = True
|
||||
|
||||
async def async_turn_off(self, **kwargs):
|
||||
""" unlock the georide tracker """
|
||||
""" unlock the GeoRide tracker """
|
||||
_LOGGER.info('async_turn_off %s', kwargs)
|
||||
success = GeorideApi.unlock_tracker(self._get_token_callback(), self._tracker_id)
|
||||
georide_context = self._hass.data[GEORIDE_DOMAIN]["context"]
|
||||
token = await georide_context.get_token()
|
||||
success = await self._hass.async_add_executor_job(GeoRideApi.unlock_tracker,
|
||||
token, self._tracker_device.tracker.tracker_id)
|
||||
if success:
|
||||
self._is_on = False
|
||||
self._tracker_device.tracker.is_locked = False
|
||||
|
||||
async def async_toggle(self, **kwargs):
|
||||
""" toggle lock the georide tracker """
|
||||
_LOGGER.info('async_toggle %s', kwargs)
|
||||
self._is_on = GeorideApi.toogle_lock_tracker(self._get_token_callback(),
|
||||
self._tracker_id)
|
||||
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""No polling needed."""
|
||||
return True
|
||||
|
||||
async def async_update(self):
|
||||
""" update the current tracker"""
|
||||
_LOGGER.info('async_update ')
|
||||
self._data = self._get_tracker_callback(self._tracker_id)
|
||||
self._name = self._data.tracker_name
|
||||
self._is_on = self._data.is_locked
|
||||
return
|
||||
georide_context = self._hass.data[GEORIDE_DOMAIN]["context"]
|
||||
token = await georide_context.get_token()
|
||||
result = await self._hass.async_add_executor_job(GeoRideApi.toogle_lock_tracker,
|
||||
token, self._tracker_device.tracker.tracker_id)
|
||||
self._tracker_device.tracker.is_locked = result
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return the unique ID."""
|
||||
return self._tracker_id
|
||||
return f"lock_{self._tracker_device.tracker.tracker_id}"
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
""" Georide switch name """
|
||||
return self._name
|
||||
|
||||
""" GeoRide odometer name """
|
||||
return f"{self._name} lock"
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
""" Georide switch status """
|
||||
return self._is_on
|
||||
|
||||
@property
|
||||
def get_token_callback(self):
|
||||
""" Georide switch token callback method """
|
||||
return self._get_token_callback
|
||||
|
||||
@property
|
||||
def get_tracker_callback(self):
|
||||
""" Georide switch token callback method """
|
||||
return self._get_tracker_callback
|
||||
""" GeoRide switch status """
|
||||
return self._tracker_device.tracker.is_locked
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
if self._is_on:
|
||||
"""return the entity icon"""
|
||||
if self._tracker_device.tracker.is_locked:
|
||||
return "mdi:lock"
|
||||
return "mdi:lock-open"
|
||||
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device info."""
|
||||
return {
|
||||
"name": self.name,
|
||||
"identifiers": {(GEORIDE_DOMAIN, self._tracker_id)},
|
||||
"manufacturer": "GeoRide"
|
||||
}
|
||||
|
||||
|
||||
return self._tracker_device.device_info
|
||||
|
||||
25
custom_components/georide/translations/en.json
Normal file
25
custom_components/georide/translations/en.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "GeoRide",
|
||||
"step": {
|
||||
"georide_login": {
|
||||
"title": "Set up GeoRide",
|
||||
"description": "Sign-in to GeoRide",
|
||||
"data": {
|
||||
"email": "email",
|
||||
"password": "password"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"faulty_credentials": "Authorization failed",
|
||||
"unknown": "Unknown error"
|
||||
},
|
||||
"abort": {
|
||||
"one_instance_allowed": "Only one instance is allowed."
|
||||
},
|
||||
"create_entry": {
|
||||
"default": "\n\nLogin success"
|
||||
}
|
||||
}
|
||||
}
|
||||
25
custom_components/georide/translations/fr.json
Normal file
25
custom_components/georide/translations/fr.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "GeoRide",
|
||||
"step": {
|
||||
"georide_login": {
|
||||
"title": "Configuration de GeoRide",
|
||||
"description": "T'es un motard ! V",
|
||||
"data": {
|
||||
"email": "email",
|
||||
"password": "password"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"faulty_credentials": "Connexion \u00e9chou\u00e9e",
|
||||
"unkonwn": "Erreur inconnue"
|
||||
},
|
||||
"abort": {
|
||||
"one_instance_allowed": "Seulement une instance est autoris\u00e9e"
|
||||
},
|
||||
"create_entry": {
|
||||
"default": "\n\nConnexion r\u00e9ussie !"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user