-
-
Notifications
You must be signed in to change notification settings - Fork 31.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Automatic odb device tracker #3035
Merged
kellerza
merged 13 commits into
home-assistant:dev
from
Teagan42:AutomaticODBDeviceTracker
Sep 3, 2016
Merged
Changes from 11 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
9e9de8b
Update tests (+17 squashed commits)
Teagan42 3940d08
Log error
Teagan42 b1dff4a
Reduce instance attributes
Teagan42 04c77b3
Updates
Teagan42 e5bba2b
Raise for status
Teagan42 29b8c9e
Linting
Teagan42 7771f49
More listing
Teagan42 9d307d4
Add raise for error method to mock response
Teagan42 4069279
Change to attributes
Teagan42 202a052
Change to attributes
Teagan42 2535023
Change to attributes
Teagan42 d5b7d0c
Consistency
Teagan42 1444674
Lint fix
Teagan42 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
""" | ||
Support for the Automatic platform. | ||
|
||
For more details about this platform, please refer to the documentation at | ||
https://home-assistant.io/components/device_tracker.automatic/ | ||
""" | ||
from datetime import timedelta | ||
import logging | ||
import re | ||
import requests | ||
|
||
import voluptuous as vol | ||
|
||
from homeassistant.components.device_tracker import (PLATFORM_SCHEMA, | ||
ATTR_ATTRIBUTES) | ||
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD | ||
import homeassistant.helpers.config_validation as cv | ||
from homeassistant.util import Throttle, datetime as dt_util | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=30) | ||
|
||
CONF_CLIENT_ID = 'client_id' | ||
CONF_SECRET = 'secret' | ||
CONF_DEVICES = 'devices' | ||
|
||
SCOPE = 'scope:location scope:vehicle:profile scope:user:profile scope:trip' | ||
|
||
ATTR_ACCESS_TOKEN = 'access_token' | ||
ATTR_EXPIRES_IN = 'expires_in' | ||
ATTR_RESULTS = 'results' | ||
ATTR_VEHICLE = 'vehicle' | ||
ATTR_ENDED_AT = 'ended_at' | ||
ATTR_END_LOCATION = 'end_location' | ||
|
||
URL_AUTHORIZE = 'https://accounts.automatic.com/oauth/access_token/' | ||
URL_VEHICLES = 'https://api.automatic.com/vehicle/' | ||
URL_TRIPS = 'https://api.automatic.com/trip/' | ||
|
||
_VEHICLE_ID_REGEX = re.compile( | ||
(URL_VEHICLES + '(.*)?[/]$').replace('/', r'\/')) | ||
|
||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ | ||
vol.Required(CONF_CLIENT_ID): cv.string, | ||
vol.Required(CONF_SECRET): cv.string, | ||
vol.Required(CONF_USERNAME): cv.string, | ||
vol.Required(CONF_PASSWORD): cv.string, | ||
vol.Optional(CONF_DEVICES): vol.All(cv.ensure_list, [cv.string]) | ||
}) | ||
|
||
|
||
def setup_scanner(hass, config: dict, see): | ||
"""Validate the configuration and return an Automatic scanner.""" | ||
try: | ||
AutomaticDeviceScanner(config, see) | ||
except requests.HTTPError as err: | ||
_LOGGER.error(str(err)) | ||
return False | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe add |
||
|
||
return True | ||
|
||
|
||
class AutomaticDeviceScanner(object): | ||
"""A class representing an Automatic device.""" | ||
|
||
def __init__(self, config: dict, see) -> None: | ||
"""Initialize the automatic device scanner.""" | ||
self._devices = config.get(CONF_DEVICES, None) | ||
self._access_token_payload = { | ||
'username': config.get(CONF_USERNAME), | ||
'password': config.get(CONF_PASSWORD), | ||
'client_id': config.get(CONF_CLIENT_ID), | ||
'client_secret': config.get(CONF_SECRET), | ||
'grant_type': 'password', | ||
'scope': SCOPE | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
self._headers = None | ||
self._token_expires = dt_util.now() | ||
self.last_results = {} | ||
self.last_trips = {} | ||
self.see = see | ||
|
||
self.scan_devices() | ||
|
||
def scan_devices(self): | ||
"""Scan for new devices and return a list with found device IDs.""" | ||
self._update_info() | ||
|
||
return [item['id'] for item in self.last_results] | ||
|
||
def get_device_name(self, device): | ||
"""Get the device name from id.""" | ||
vehicle = [item['display_name'] for item in self.last_results | ||
if item['id'] == device] | ||
|
||
return vehicle[0] | ||
|
||
def _update_headers(self): | ||
"""Get the access token from automatic.""" | ||
if self._headers is None or self._token_expires <= dt_util.now(): | ||
resp = requests.post( | ||
URL_AUTHORIZE, | ||
data=self._access_token_payload) | ||
|
||
resp.raise_for_status() | ||
|
||
json = resp.json() | ||
|
||
access_token = json[ATTR_ACCESS_TOKEN] | ||
self._token_expires = dt_util.now() + timedelta( | ||
seconds=json[ATTR_EXPIRES_IN]) | ||
self._headers = { | ||
'Authorization': 'Bearer {}'.format(access_token) | ||
} | ||
|
||
@Throttle(MIN_TIME_BETWEEN_SCANS) | ||
def _update_info(self) -> None: | ||
"""Update the device info.""" | ||
_LOGGER.info('Updating devices') | ||
self._update_headers() | ||
|
||
response = requests.get(URL_VEHICLES, headers=self._headers) | ||
|
||
response.raise_for_status() | ||
|
||
self.last_results = [item for item in response.json()[ATTR_RESULTS] | ||
if self._devices is None or item[ | ||
'display_name'] in self._devices] | ||
|
||
response = requests.get(URL_TRIPS, headers=self._headers) | ||
|
||
if response.status_code == 200: | ||
for trip in response.json()[ATTR_RESULTS]: | ||
vehicle_id = _VEHICLE_ID_REGEX.match( | ||
trip[ATTR_VEHICLE]).group(1) | ||
if vehicle_id not in self.last_trips: | ||
self.last_trips[vehicle_id] = trip | ||
elif self.last_trips[vehicle_id][ATTR_ENDED_AT] < trip[ | ||
ATTR_ENDED_AT]: | ||
self.last_trips[vehicle_id] = trip | ||
|
||
for vehicle in self.last_results: | ||
dev_id = vehicle.get('id') | ||
|
||
attrs = { | ||
'fuel_level': vehicle.get('fuel_level_percent') | ||
} | ||
|
||
kwargs = { | ||
'dev_id': dev_id, | ||
'mac': dev_id, | ||
ATTR_ATTRIBUTES: attrs | ||
} | ||
|
||
if dev_id in self.last_trips: | ||
end_location = self.last_trips[dev_id][ATTR_END_LOCATION] | ||
kwargs['gps'] = (end_location['lat'], end_location['lon']) | ||
kwargs['gps_accuracy'] = end_location['accuracy_m'] | ||
|
||
self.see(**kwargs) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keep the name consistent
attributes
. Allows for passing as attributes={} in all see functionsThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks - addressed.