Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions appdaemon/plugins/hass/hassplugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,8 +459,10 @@ async def http_method(
**kwargs (optional): Zero or more keyword arguments. These get used as the data for the method, as
appropriate.
"""
kwargs = utils.clean_http_kwargs(kwargs)
url = utils.make_endpoint(f"{self.config.ha_url!s}", endpoint)
if method.lower() in ("get", "delete"):
kwargs = utils.clean_http_kwargs(kwargs)

url = utils.make_endpoint(self.config.ha_url, endpoint)

try:
self.update_perf(
Expand All @@ -475,7 +477,7 @@ async def http_method(
case "post":
http_method = functools.partial(self.session.post, json=kwargs)
case "delete":
http_method = functools.partial(self.session.delete, json=kwargs)
http_method = functools.partial(self.session.delete, params=kwargs)
case _:
raise ValueError(f"Invalid method: {method}")

Expand Down Expand Up @@ -889,8 +891,7 @@ async def set_plugin_state(

@utils.warning_decorator(error_text=f"Error setting state for {entity_id}")
async def safe_set_state(self: "HassPlugin"):
api_url = self.config.get_entity_api(entity_id)
return await self.http_method("post", api_url, state=state, attributes=attributes)
return await self.http_method("post", f'/api/states/{entity_id}', state=state, attributes=attributes)

return await safe_set_state(self)

Expand Down
20 changes: 12 additions & 8 deletions appdaemon/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@
from pathlib import Path
from time import perf_counter
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Literal, ParamSpec, Protocol, TypeVar
from urllib import parse

import dateutil.parser
import tomli
import tomli_w
import yaml
from astral.location import Location
from pydantic import BaseModel, ValidationError
from pydantic import AnyHttpUrl, BaseModel, ValidationError
from pytz import BaseTzInfo

from appdaemon.parse import parse_datetime
Expand Down Expand Up @@ -862,7 +863,12 @@ def dt_to_str(dt: datetime, tz: tzinfo | None = None, *, round: bool = False) ->


def convert_json(data, **kwargs):
return json.dumps(data, default=str, **kwargs)
def fallback_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
return str(obj)

return json.dumps(data, default=fallback_serializer, **kwargs)


def get_object_size(obj, seen=None):
Expand Down Expand Up @@ -1167,13 +1173,11 @@ def clean_http_kwargs(val: Any) -> Any:
return pruned


def make_endpoint(base: str, endpoint: str) -> str:
def make_endpoint(base: str | AnyHttpUrl, endpoint: str) -> str:
"""Formats a URL appropriately with slashes"""
if not endpoint.startswith(base):
result = f"{base}/{endpoint.strip('/')}"
else:
result = endpoint
return result.strip("/")
parsed = parse.urlparse(str(base))
result = parsed._replace(path=endpoint)
return parse.urlunparse(result)


def unwrapped(func: Callable) -> Callable:
Expand Down
9 changes: 1 addition & 8 deletions docs/HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Added some basic test for persistent namespaces
- Add request context logging for failed HASS calls - contributed by [ekutner](https://github.com/ekutner)
- Reload modified apps on SIGUSR2 - contributed by [chatziko](https://github.com/chatziko)
- Using urlib to create endpoints from URLs

**Fixes**

Expand All @@ -16,14 +17,6 @@
- Fix for connecting to Home Assistant with https
- Fix for persistent namespaces in Python 3.12
- Better error handling for receiving huge websocket messages in the Hass plugin
- Fix production mode and scheduler race - contributed by [cebtenzzre](https://github.com/cebtenzzre)
- Fix scheduler crash - contributed by [cebtenzzre](https://github.com/cebtenzzre)
- Fix startup when no plugins are configured - contributed by [cebtenzzre](https://github.com/cebtenzzre)
- Fix entity persistencre - contributed by [cebtenzzre](https://github.com/cebtenzzre)

**Features**

None

**Breaking Changes**

Expand Down
Loading