Skip to content

Commit

Permalink
Check configuration items exist. Fixes, j1nx#2.
Browse files Browse the repository at this point in the history
  • Loading branch information
scottwallacesh committed Apr 20, 2023
1 parent 7efd91c commit 2e7844c
Show file tree
Hide file tree
Showing 6 changed files with 134 additions and 97 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.pyenv/
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ device_tracker:
- platform: phonetrack
url: https://<NEXTCLOUD_URL>/index.php/apps/phonetrack/api/getlastpositions/
token: <SHARED_VIEW_TOKEN>

devices:
- <DEVICE_NAME>
```
Expand All @@ -47,6 +47,6 @@ Please use [secrets](https://www.home-assistant.io/docs/configuration/secrets/)
Finish the optional GPS accuracy threshold value similar as Google LOcation Sharing.
## Troubleshooting
I don't know how to code in Python (yet). This is just copy & paste work and using Google (a lot) debugging all error's I do not understand, while doing stuff I don't know. I have some more Python projects on the shelf, so whenever I start leaning that code a bit more, I will look into making it better.
I don't know how to code in Python (yet). This is just copy & paste work and using Google (a lot) debugging all errors I do not understand, while doing stuff I don't know. I have some more Python projects on the shelf, so whenever I start leaning that code a bit more, I will look into making it better.
Till then, feel free to fork and create PR's.
Till then, feel free to fork and create PRs.
2 changes: 1 addition & 1 deletion custom_components/phonetrack/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"""The phonetrack component."""
"""The phonetrack component."""
198 changes: 116 additions & 82 deletions custom_components/phonetrack/device_tracker.py
Original file line number Diff line number Diff line change
@@ -1,82 +1,116 @@
"""Support for PhoneTrack device tracking."""
import logging
import urllib.parse
from datetime import timedelta

import requests
import voluptuous as vol

from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA, SOURCE_TYPE_GPS)
from homeassistant.const import (
CONF_DEVICES, CONF_TOKEN, CONF_URL)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_time_interval
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import slugify, Throttle

_LOGGER = logging.getLogger(__name__)

CONF_MAX_GPS_ACCURACY = 'max_gps_accuracy'
UPDATE_INTERVAL = timedelta(minutes=5)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_DEVICES): vol.All(cv.ensure_list, [cv.string]),
vol.Required(CONF_TOKEN): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Optional(CONF_MAX_GPS_ACCURACY, default=100000): vol.Coerce(float),
})


def setup_scanner(hass, config: ConfigType, see, discovery_info=None):
"""Set up the PhoneTrack scanner."""
PhoneTrackDeviceTracker(hass, config, see)
return True


class PhoneTrackDeviceTracker(object):
"""
A device tracker fetching last position from the PhoneTrack Nextcloud
app.
"""
def __init__(self, hass, config: ConfigType, see) -> None:
"""Initialize the PhoneTrack tracking."""
self.hass = hass
self.url = config[CONF_URL]
self.token = config[CONF_TOKEN]
self.devices = config[CONF_DEVICES]
self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY]
self.see = see
self._update_info()

track_time_interval(
hass, self._update_info, UPDATE_INTERVAL
)

@Throttle(UPDATE_INTERVAL)
def _update_info(self, now=None):
"""Update the device info."""
_LOGGER.debug("Updating devices %s", now)
data = requests.get(urllib.parse.urljoin(self.url, self.token)).json()
data = data[self.token]
for device in self.devices:
if device not in data.keys():
_LOGGER.info('Device %s is not available.', device)
continue
lat, lon = data[device]['lat'], data[device]['lon']
accuracy = data[device]['accuracy']
battery = data[device]['batterylevel']
if self.max_gps_accuracy is not None and \
data[device]['accuracy'] > self.max_gps_accuracy:
_LOGGER.info("Ignoring %s update because expected GPS "
"accuracy is not met", device)
continue

self.see(
dev_id=slugify(device),
gps=(lat, lon),
source_type=SOURCE_TYPE_GPS,
gps_accuracy=accuracy,
battery=battery
)
return True
"""Support for PhoneTrack device tracking."""
import logging
import urllib.parse
from datetime import timedelta
from typing import Any

import homeassistant.helpers.config_validation as cv # type: ignore[import]
import requests # type: ignore[import]
import voluptuous as vol # type: ignore[import]
from homeassistant.components.device_tracker import ( # type: ignore[import]
PLATFORM_SCHEMA,
SOURCE_TYPE_GPS,
SeeCallback,
)
from homeassistant.const import CONF_DEVICES # type: ignore[import]
from homeassistant.const import CONF_TOKEN, CONF_URL
from homeassistant.core import HomeAssistant # type: ignore[import]
from homeassistant.helpers.event import track_time_interval # type: ignore[import]
from homeassistant.helpers.typing import ConfigType # type: ignore[import]
from homeassistant.helpers.typing import DiscoveryInfoType
from homeassistant.util import Throttle, slugify # type: ignore[import]

_LOGGER = logging.getLogger(__name__)

CONF_MAX_GPS_ACCURACY = "max_gps_accuracy"
UPDATE_INTERVAL = timedelta(minutes=5)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_DEVICES, default=[]): vol.All(cv.ensure_list, [cv.string]),
vol.Required(CONF_TOKEN, default=""): cv.string,
vol.Required(CONF_URL, default=""): cv.string,
vol.Optional(CONF_MAX_GPS_ACCURACY, default=100000): vol.Coerce(float),
}
)


def setup_scanner(
hass: HomeAssistant,
config: ConfigType,
see: SeeCallback,
_: DiscoveryInfoType | None = None,
) -> bool:
"""Set up the PhoneTrack scanner."""
config_check = {
CONF_URL: "URL",
CONF_TOKEN: "Token",
CONF_DEVICES: "Device list",
}

for key, item in config_check.items():
if not config[key]:
_LOGGER.error("%s missing from configuration", item)
return False

PhoneTrackDeviceTracker(hass, config, see)
return True


class PhoneTrackDeviceTracker: # pylint: disable=too-few-public-methods
"""
A device tracker fetching last position from the PhoneTrack Nextcloud
app.
"""

def __init__(
self,
hass: HomeAssistant,
config: ConfigType,
see: SeeCallback,
) -> None:
"""Initialize the PhoneTrack tracking."""
self.hass = hass
self.url = config[CONF_URL]
self.token = config[CONF_TOKEN]
self.devices = config[CONF_DEVICES]
self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY]
self.see = see
self._update_info()

track_time_interval(hass, self._update_info, UPDATE_INTERVAL)

@Throttle(UPDATE_INTERVAL) # type: ignore[misc]
def _update_info(self, *_: Any, **__: Any) -> bool:
"""Update the device info."""
_LOGGER.debug("Updating devices")
data = requests.get(
urllib.parse.urljoin(self.url, self.token),
timeout=30,
).json()
data = data[self.token]
for device in self.devices:
if device not in data.keys():
_LOGGER.info("Device %s is not available.", device)
continue
lat, lon = data[device]["lat"], data[device]["lon"]
accuracy = data[device]["accuracy"]
battery = data[device]["batterylevel"]
if (
self.max_gps_accuracy is not None
and data[device]["accuracy"] > self.max_gps_accuracy
):
_LOGGER.info(
"Ignoring %s update because expected GPS accuracy is not met",
device,
)
continue

self.see(
dev_id=slugify(device),
gps=(lat, lon),
source_type=SOURCE_TYPE_GPS,
gps_accuracy=accuracy,
battery=battery,
)
return True
23 changes: 12 additions & 11 deletions custom_components/phonetrack/manifest.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
{
"domain": "phonetrack",
"name": "PhoneTrack",
"documentation": "https://github.com/j1nx/homeassistant-phonetrack",
"requirements": [],
"dependencies": [],
"codeowners": [
"@Phyks",
"@j1nx"
]
}
{
"domain": "phonetrack",
"name": "PhoneTrack",
"documentation": "https://github.com/j1nx/homeassistant-phonetrack",
"version": "2023.04.20",
"requirements": [],
"dependencies": [],
"codeowners": [
"@Phyks",
"@j1nx"
]
}
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
homeassistant

0 comments on commit 2e7844c

Please sign in to comment.