Skip to content
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

fix: issue with template rendering in AppDaemon addon #812

Merged
merged 1 commit into from
Apr 15, 2023
Merged
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
4 changes: 2 additions & 2 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ _This minor change does not contain any breaking changes._
- [XYZ](https://BASE_URL/controllerx/controllers/XYZ) - add device with Z2M support. [ #123 ]
-->

<!--
## :hammer: Fixes
-->

- Fix template rendering for AppDaemon addon. [ #810 ]

<!--
## :scroll: Docs
Expand Down
6 changes: 4 additions & 2 deletions apps/controllerx/cx_core/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,8 +364,10 @@ async def call_service(
# Start condition to be deleted
# Read doc string from apps/controllerx/cx_core/fix_template.py
if service == "template/render":
ha_config = self.config["plugins"]["HASS"]
return await fix_template.render_template(ha_config, attributes, self)
hass_plugin = await self.AD.plugins.get_plugin_object("default")
return await fix_template.render_template(
hass_plugin.session, hass_plugin.ha_url, attributes, self
)
# End of condition to be deleted.
return await ADAPI.call_service(self, service, **attributes)

Expand Down
51 changes: 18 additions & 33 deletions apps/controllerx/cx_core/fix_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import asyncio
import json
import traceback
from typing import TYPE_CHECKING, Any, Dict, Optional
from typing import TYPE_CHECKING, Any, Optional

import aiohttp

Expand All @@ -30,43 +30,30 @@ def convert_json(data: Any, **kwargs: Any) -> str:


async def render_template(
config: Dict[str, Any], data: Any, controller: "Controller"
session: aiohttp.ClientSession, ha_url: str, data: Any, controller: "Controller"
) -> Optional[str]:
if isinstance(data, str):
data = {"entity_id": data}

if "token" in config:
headers = {"Authorization": "Bearer {}".format(config["token"])}
elif "ha_key" in config:
headers = {"x-ha-access": config["ha_key"]}
else:
headers = {}

api_url = "{}/api/template".format(config["ha_url"])
api_url = f"{ha_url}/api/template"

try:
async with aiohttp.ClientSession(
connector=aiohttp.TCPConnector(), json_serialize=convert_json
) as session:
async with session.post(
api_url, headers=headers, json=data, verify_ssl=config["cert_verify"]
) as resp:
if resp.status == 200 or resp.status == 201:
result = await resp.text()
else:
controller.log.warning(
"Error calling Home Assistant service %s/%s",
domain,
service,
)
txt = await resp.text()
controller.log.warning("Code: %s, error: %s", resp.status, txt)
result = None

return result
async with session.post(api_url, json=data) as resp:
if resp.status == 200 or resp.status == 201:
result = await resp.text()
else:
controller.log(
f"Error calling Home Assistant service {domain}/{service}",
level="WARNING",
)
txt = await resp.text()
controller.log(f"Code: {resp.status}, error: {txt}", level="WARNING")
result = None

return result
except (asyncio.TimeoutError, asyncio.CancelledError):
controller.log(
"Timeout in call_service(%s/%s, %s)", domain, service, data, level="WARNING"
f"Timeout in call_service({domain}/{service}, {data})", level="WARNING"
)
except aiohttp.client_exceptions.ServerDisconnectedError:
controller.log(
Expand All @@ -75,9 +62,7 @@ async def render_template(
except Exception:
controller.log("-" * 60, level="ERROR")
controller.log("Unexpected error during call_plugin_service()", level="ERROR")
controller.log(
"Service: %s.%s Arguments: %s", domain, service, data, level="ERROR"
)
controller.log(f"Service: {domain}.{service} Arguments: {data}", level="ERROR")
controller.log("-" * 60, level="ERROR")
controller.log(traceback.format_exc(), level="ERROR")
controller.log("-" * 60, level="ERROR")
Expand Down