Skip to content

Commit

Permalink
Merge pull request #623 from alandtse/dev
Browse files Browse the repository at this point in the history
chore: release 2023-05-31
  • Loading branch information
alandtse authored Jun 1, 2023
2 parents 7f109af + 544e862 commit fc23631
Show file tree
Hide file tree
Showing 13 changed files with 173 additions and 167 deletions.
34 changes: 34 additions & 0 deletions .devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "Tesla Custom Component",
"image": "mcr.microsoft.com/vscode/devcontainers/python:0-3.10-bullseye",
"postCreateCommand": "sudo scripts/setup",
"appPort": ["9123:8123"],
"customizations": {
"vscode": {
"extensions": [
"ms-python.python",
"github.vscode-pull-request-github",
"ryanluker.vscode-coverage-gutters",
"ms-python.vscode-pylance"
],
"settings": {
"files.eol": "\n",
"editor.tabSize": 4,
"python.pythonPath": "/usr/bin/python3",
"python.analysis.autoSearchPaths": false,
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"python.formatting.provider": "black",
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"editor.formatOnType": true,
"files.trimTrailingWhitespace": true
}
}
},
"remoteUser": "vscode",
"features": {
"ghcr.io/devcontainers/features/rust:1": {}
}
}
60 changes: 0 additions & 60 deletions .devcontainer/README.md

This file was deleted.

31 changes: 0 additions & 31 deletions .devcontainer/devcontainer.json

This file was deleted.

35 changes: 0 additions & 35 deletions .devcontainer/post-create.sh

This file was deleted.

5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ deps/deps.jl
# User settings
/.vscode/settings.json

# Home Assistant configuration
config/*
!config/configuration.yaml

# Keep these config files
!/.gitignore
Expand All @@ -75,5 +78,5 @@ deps/deps.jl
!.npmignore
!/.scrutinizer.yml
!/.prospector.yml
!/.devcontainer
!/.devcontainer.json
!/.vscode
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ repos:
- id: commitizen
stages: ["commit-msg"]
repo: https://github.com/commitizen-tools/commitizen
rev: 3.2.0
rev: 3.2.2
# --- Linters ---
- hooks:
- id: dockerfile_lint
Expand All @@ -61,12 +61,12 @@ repos:
)$
rev: v3.0.0-alpha.9-for-vscode
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.2
rev: v3.4.0
hooks:
- id: pyupgrade
args: [--py38-plus]
- repo: https://github.com/PyCQA/prospector
rev: v1.9.0
rev: 1.10.1
hooks:
- id: prospector
exclude: ^(tests)/.+\.py$
Expand Down
26 changes: 1 addition & 25 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,7 @@
{
"label": "Run Home Assistant on port 9123",
"type": "shell",
"command": "container start",
"problemMatcher": []
},
{
"label": "Run Home Assistant configuration against /config",
"type": "shell",
"command": "container check",
"problemMatcher": []
},
{
"label": "Upgrade Home Assistant to latest dev",
"type": "shell",
"command": "container install",
"problemMatcher": []
},
{
"label": "Install a specific version of Home Assistant",
"type": "shell",
"command": "container set-version",
"problemMatcher": []
},
{
"label": "Serve Documentation on port 8000",
"type": "shell",
"command": "mkdocs -v serve",
"command": "scripts/develop",
"problemMatcher": []
}
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ logger:
authcaptureproxy: debug
teslajsonpy: debug
# If you need to debug uncommment the line below (doc: https://www.home-assistant.io/integrations/debugpy/)
# debugpy:
debugpy:
start: True
# wait: True
90 changes: 83 additions & 7 deletions custom_components/tesla_custom/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
)
from homeassistant.core import callback
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.httpx_client import SERVER_SOFTWARE, USER_AGENT
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
import httpx
Expand Down Expand Up @@ -280,14 +281,30 @@ def _async_create_close_task():
vins=set(),
update_vehicles=False,
)
coordinators = {
"update_vehicles": _partial_coordinator(update_vehicles=True),
**{
energy_site_id: _partial_coordinator(energy_site_ids={energy_site_id})
for energy_site_id in energysites
},
**{vin: _partial_coordinator(vins={vin}) for vin in cars},
energy_coordinators = {
energy_site_id: _partial_coordinator(energy_site_ids={energy_site_id})
for energy_site_id in energysites
}
car_coordinators = {vin: _partial_coordinator(vins={vin}) for vin in cars}
coordinators = {**energy_coordinators, **car_coordinators}

if car_coordinators:
update_vehicles_coordinator = _partial_coordinator(update_vehicles=True)
coordinators["update_vehicles"] = update_vehicles_coordinator

# If we have cars, we want to update the vehicles coordinator
# to keep the vehicles up to date.
@callback
def _async_update_vehicles():
"""Update vehicles coordinator.
This listener is called when the update_vehicles_coordinator
is updated. Since each car coordinator is also polling we don't
need to do anything here, but we need to have this listener
to ensure the update_vehicles_coordinator is updated regularly.
"""

update_vehicles_coordinator.async_add_listener(_async_update_vehicles)

teslamate = TeslaMate(hass=hass, cars=cars, coordinators=coordinators)

Expand Down Expand Up @@ -386,6 +403,8 @@ def __init__(
self.vins = vins
self.energy_site_ids = energy_site_ids
self.update_vehicles = update_vehicles
self._debounce_task = None
self._last_update_time = None

update_interval = timedelta(seconds=MIN_SCAN_INTERVAL)

Expand Down Expand Up @@ -431,3 +450,60 @@ async def _async_update_data(self):
await self.hass.config_entries.async_reload(self.config_entry.entry_id)
except TeslaException as err:
raise UpdateFailed(f"Error communicating with API: {err}") from err

def async_update_listeners_debounced(self, delay_since_last=0.1, max_delay=1.0):
"""
Debounced version of async_update_listeners.
This function cancels the previous task (if any) and creates a new one.
Parameters
----------
delay_since_last : float
Minimum delay in seconds since the last received message before calling async_update_listeners.
max_delay : float
Maximum delay in seconds before calling async_update_listeners,
regardless of when the last message was received.
"""
# If there's an existing debounce task, cancel it
if self._debounce_task:
self._debounce_task()
_LOGGER.debug("Previous debounce task cancelled")

# Schedule the call to _debounced, pass max_delay using partial
self._debounce_task = async_call_later(
self.hass, delay_since_last, partial(self._debounced, max_delay)
)
_LOGGER.debug("New debounce task scheduled")

async def _debounced(self, max_delay, *args):
"""
Debounce method that waits a certain delay since the last update.
This method ensures that async_update_listeners is called at least every max_delay seconds.
Parameters
----------
max_delay : float
Maximum delay in seconds before calling async_update_listeners.
"""
# Get the current time
now = self.hass.loop.time()

# If it's been at least max_delay since the last update (or there was no previous update),
# call async_update_listeners and update the last update time
if not self._last_update_time or now - self._last_update_time >= max_delay:
self._last_update_time = now
self.async_update_listeners()
_LOGGER.debug("Listeners updated")
else:
# If it hasn't been max_delay since the last update,
# schedule the call to _debounced again after the remaining time
self._debounce_task = async_call_later(
self.hass,
max_delay - (now - self._last_update_time),
partial(self._debounced, max_delay),
)
_LOGGER.debug("Max delay not reached, scheduling another debounce task")
8 changes: 4 additions & 4 deletions custom_components/tesla_custom/teslamate.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,22 +297,22 @@ async def async_handle_new_data(self, msg: ReceiveMessage):
if mqtt_attr in MAP_DRIVE_STATE:
attr, cast = MAP_DRIVE_STATE[mqtt_attr]
self.update_drive_state(car, attr, cast(msg.payload))
coordinator.async_update_listeners()
coordinator.async_update_listeners_debounced()

elif mqtt_attr in MAP_VEHICLE_STATE:
attr, cast = MAP_VEHICLE_STATE[mqtt_attr]
self.update_vehicle_state(car, attr, cast(msg.payload))
coordinator.async_update_listeners()
coordinator.async_update_listeners_debounced()

elif mqtt_attr in MAP_CLIMATE_STATE:
attr, cast = MAP_CLIMATE_STATE[mqtt_attr]
self.update_climate_state(car, attr, cast(msg.payload))
coordinator.async_update_listeners()
coordinator.async_update_listeners_debounced()

elif mqtt_attr in MAP_CHARGE_STATE:
attr, cast = MAP_CHARGE_STATE[mqtt_attr]
self.update_charge_state(car, attr, cast(msg.payload))
coordinator.async_update_listeners()
coordinator.async_update_listeners_debounced()

@staticmethod
def update_drive_state(car: TeslaCar, attr, value):
Expand Down
Loading

0 comments on commit fc23631

Please sign in to comment.