Skip to content

Commit

Permalink
feat: add service call to return prices around device_track location (#…
Browse files Browse the repository at this point in the history
…114)

* feat: add service call to return prices around device_track location

* formatting

* remove unused import

* update linter config

* update test
  • Loading branch information
firstof9 authored Nov 20, 2024
1 parent a0fce37 commit d63eb5d
Show file tree
Hide file tree
Showing 12 changed files with 1,242 additions and 2 deletions.
4 changes: 4 additions & 0 deletions custom_components/gasbuddy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
PLATFORMS,
VERSION,
)
from .services import GasBuddyServices

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -68,6 +69,9 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b

hass.data[DOMAIN][config_entry.entry_id] = {COORDINATOR: coordinator}

services = GasBuddyServices(hass, config_entry)
services.async_register()

await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
return True

Expand Down
3 changes: 3 additions & 0 deletions custom_components/gasbuddy/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
ISSUE_URL = "https://github.com/firstof9/ha-gasbuddy/issues"
PLATFORMS = ["sensor"]

# services
SERVICE_LOOKUP_GPS = "lookup_gps"

# sensor constants
UNIT_OF_MEASURE = {
"dollars_per_gallon": "gallon",
Expand Down
2 changes: 1 addition & 1 deletion custom_components/gasbuddy/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"import_executor": true,
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/firstof9/ha-gasbuddy/issues",
"requirements": ["py-gasbuddy==0.2.8"],
"requirements": ["py-gasbuddy==0.2.9"],
"version": "0.0.0-dev"
}

66 changes: 66 additions & 0 deletions custom_components/gasbuddy/services.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""GasBuddy services."""

import logging

import voluptuous as vol
from gasbuddy import GasBuddy # pylint: disable=import-self
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_ID, ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.core import (
HomeAssistant,
ServiceCall,
ServiceResponse,
SupportsResponse,
callback,
)
from homeassistant.helpers import config_validation as cv

from .const import DOMAIN, SERVICE_LOOKUP_GPS

_LOGGER = logging.getLogger(__name__)


class GasBuddyServices:
"""Class that holds our services."""

def __init__(
self,
hass: HomeAssistant,
config: ConfigEntry,
) -> None:
"""Initialize with hass object."""
self.hass = hass
self._config = config

@callback
def async_register(self) -> None:
"""Register all our services."""
self.hass.services.async_register(
DOMAIN,
SERVICE_LOOKUP_GPS,
self._price_lookup_gps,
schema=vol.Schema(
{
vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
}
),
supports_response=SupportsResponse.ONLY,
)

# Setup services
async def _price_lookup_gps(self, service: ServiceCall) -> ServiceResponse:
"""Set the override."""
entity_ids = service.data[ATTR_ENTITY_ID]

results = {}
for entity_id in entity_ids:
try:
entity = self.hass.states.get(entity_id)
lat = entity.attributes[ATTR_LATITUDE]
lon = entity.attributes[ATTR_LONGITUDE]
results[entity_id] = await GasBuddy().price_lookup_gps(lat=lat, lon=lon)
except Exception as err:
_LOGGER.error("Error checking prices: %s", err)

_LOGGER.debug("GPS price lookup: %s", results)
return results
6 changes: 6 additions & 0 deletions custom_components/gasbuddy/services.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
lookup_gps:
name: Lookup GPS
description: List gas prices based on GPS coordinates of device tracker.
target:
entity:
domain: device_tracker
1 change: 1 addition & 0 deletions pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ disable=
too-many-locals,
unexpected-keyword-arg,
abstract-method,
cyclic-import,

[REFACTORING]

Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
py-gasbuddy==0.2.8
py-gasbuddy==0.2.9
1 change: 1 addition & 0 deletions requirements_test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ isort
pylint==3.3.1
tox==4.23.2
pytest
aioresponses
10 changes: 10 additions & 0 deletions tests/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""Provide common pytest fixtures."""

import os


def load_fixture(filename):
"""Load a fixture."""
path = os.path.join(os.path.dirname(__file__), "fixtures", filename)
with open(path, encoding="utf-8") as fptr:
return fptr.read()
8 changes: 8 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from unittest.mock import patch

import pytest
from aioresponses import aioresponses

from tests.const import COORDINATOR_DATA, COORDINATOR_DATA_CAD

Expand Down Expand Up @@ -45,3 +46,10 @@ def mock_gasbuddy_cad():
) as mock_value:
mock_value.return_value = COORDINATOR_DATA_CAD
yield


@pytest.fixture
def mock_aioclient():
"""Fixture to mock aioclient calls."""
with aioresponses() as m:
yield m
Loading

0 comments on commit d63eb5d

Please sign in to comment.