Skip to content

Commit

Permalink
Initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
pnbruckner committed Jan 17, 2024
0 parents commit 9db3290
Show file tree
Hide file tree
Showing 46 changed files with 1,093 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Validate

on:
pull_request:
push:

jobs:
validate-hassfest:
runs-on: ubuntu-latest
name: With hassfest
steps:
- name: 📥 Checkout the repository
uses: actions/checkout@v3

- name: 🏃 Hassfest validation
uses: "home-assistant/actions/hassfest@master"

validate-hacs:
runs-on: ubuntu-latest
name: With HACS Action
steps:
- name: 🏃 HACS validation
uses: hacs/action@main
with:
category: integration
ignore: brands
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

.vscode/
24 changes: 24 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# <img src="https://brands.home-assistant.io/gpslogger/icon.png" alt="GPSLogger" width="50" height="50"/> GPSLogger

This is a custom version of the Home Assistant built-in [GPSLogger](https://www.home-assistant.io/integrations/gpslogger/) integration.

It extends the built-in integration in ways that make sense, but are no longer accepted practice.
Specifically, it allows additional attributes, especially `last_seen`,
which is crucial when combining entities from this Device Tracker integration with ones from other integrations,
e.g., via my [Composite Device Tracker](https://github.com/pnbruckner/ha-composite-tracker) integration.
Also, `last_seen` is important when dealing with packets received out of order from the corresponding Android app,
e.g., due to network delays.

## Installation
### With HACS
[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg)](https://hacs.xyz/)

You can use HACS to manage the installation and provide update notifications.

1. Add this repo as a [custom repository](https://hacs.xyz/docs/faq/custom_repositories/):

```text
https://github.com/pnbruckner/ha-gpslogger
```

2. Install the integration using the appropriate button on the HACS Integrations page. Search for "gpslogger".

### Manual

Place a copy of the files from [`custom_components/gpslogger`](custom_components/gpslogger)
in `<config>/custom_components/gpslogger`,
where `<config>` is your Home Assistant configuration directory.

>__NOTE__: When downloading, make sure to use the `Raw` button from each file's page.
## Setup

Please see the standard [GPSLogger](https://www.home-assistant.io/integrations/gpslogger/) documentation for basic set up.

The following should be added to the **HTTP Body** setting in the Android app (in addition to what the standard docs suggest):

```text
&last_seen=%TIME&battery_charging=%ISCHARGING
```

Note that `%TIME` provides the phone's time in UTC.
If you'd rather have the time specified in the phone's local time zone, use `%TIMEOFFSET` instead.
127 changes: 127 additions & 0 deletions custom_components/gpslogger/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""Support for GPSLogger."""
from http import HTTPStatus
import logging

from aiohttp import web
import voluptuous as vol

from homeassistant.components import webhook
from homeassistant.components.device_tracker import ATTR_BATTERY
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_BATTERY_CHARGING,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_WEBHOOK_ID,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_flow
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send

from .const import (
ATTR_ACCURACY,
ATTR_ACTIVITY,
ATTR_ALTITUDE,
ATTR_DEVICE,
ATTR_DIRECTION,
ATTR_LAST_SEEN,
ATTR_PROVIDER,
ATTR_SPEED,
DOMAIN,
)

_LOGGER = logging.getLogger(__name__)

PLATFORMS = [Platform.DEVICE_TRACKER]
TRACKER_UPDATE = f"{DOMAIN}_tracker_update"

DEFAULT_ACCURACY = 200
DEFAULT_BATTERY = -1


def _id(value: str) -> str:
"""Coerce id by removing '-'."""
return value.replace("-", "")


WEBHOOK_SCHEMA = vol.Schema(
{
vol.Required(ATTR_DEVICE): _id,
vol.Required(ATTR_LATITUDE): cv.latitude,
vol.Required(ATTR_LONGITUDE): cv.longitude,
vol.Optional(ATTR_ACCURACY, default=DEFAULT_ACCURACY): vol.Coerce(float),
vol.Optional(ATTR_ACTIVITY): cv.string,
vol.Optional(ATTR_ALTITUDE): vol.Coerce(float),
vol.Optional(ATTR_BATTERY, default=DEFAULT_BATTERY): vol.Coerce(float),
vol.Optional(ATTR_BATTERY_CHARGING): cv.boolean,
vol.Optional(ATTR_DIRECTION): vol.Coerce(float),
vol.Optional(ATTR_LAST_SEEN): cv.datetime,
vol.Optional(ATTR_PROVIDER): cv.string,
vol.Optional(ATTR_SPEED): vol.Coerce(float),
}
)


async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook with GPSLogger request."""
try:
data = WEBHOOK_SCHEMA(dict(await request.post()))
except vol.MultipleInvalid as error:
return web.Response(
text=error.error_message, status=HTTPStatus.UNPROCESSABLE_ENTITY
)

if ATTR_LAST_SEEN not in data and not hass.data[DOMAIN]["warned_no_last_seen"]:
_LOGGER.warning(
"HTTP Body does not contain %s. Consider adding it for better results. See "
"https://github.com/pnbruckner/ha-gpslogger/blob/master/README.md",
ATTR_LAST_SEEN,
)
hass.data[DOMAIN]["warned_no_last_seen"] = True

attrs = {
ATTR_ACTIVITY: data.get(ATTR_ACTIVITY),
ATTR_ALTITUDE: data.get(ATTR_ALTITUDE),
ATTR_BATTERY_CHARGING: data.get(ATTR_BATTERY_CHARGING),
ATTR_DIRECTION: data.get(ATTR_DIRECTION),
ATTR_LAST_SEEN: data.get(ATTR_LAST_SEEN),
ATTR_PROVIDER: data.get(ATTR_PROVIDER),
ATTR_SPEED: data.get(ATTR_SPEED),
}

device = data[ATTR_DEVICE]

async_dispatcher_send(
hass,
TRACKER_UPDATE,
device,
(data[ATTR_LATITUDE], data[ATTR_LONGITUDE]),
data[ATTR_BATTERY],
data[ATTR_ACCURACY],
attrs,
)

return web.Response(text=f"Setting location for {device}")


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Configure based on config entry."""
hass.data.setdefault(DOMAIN, {"devices": set(), "warned_no_last_seen": False})
webhook.async_register(
hass, DOMAIN, "GPSLogger", entry.data[CONF_WEBHOOK_ID], handle_webhook
)

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
webhook.async_unregister(hass, entry.data[CONF_WEBHOOK_ID])
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)


async_remove_entry = config_entry_flow.webhook_async_remove_entry
10 changes: 10 additions & 0 deletions custom_components/gpslogger/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""Config flow for GPSLogger."""
from homeassistant.helpers import config_entry_flow

from .const import DOMAIN

config_entry_flow.register_webhook_flow(
DOMAIN,
"GPSLogger Webhook",
{"docs_url": "https://github.com/pnbruckner/ha-gpslogger/blob/master/README.md"},
)
12 changes: 12 additions & 0 deletions custom_components/gpslogger/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""Const for GPSLogger."""

DOMAIN = "gpslogger"

ATTR_ALTITUDE = "altitude"
ATTR_ACCURACY = "accuracy"
ATTR_ACTIVITY = "activity"
ATTR_DEVICE = "device"
ATTR_DIRECTION = "direction"
ATTR_LAST_SEEN = "last_seen"
ATTR_PROVIDER = "provider"
ATTR_SPEED = "speed"
Loading

0 comments on commit 9db3290

Please sign in to comment.