power: use the http_client component
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
This commit is contained in:
parent
0abb831ea0
commit
5bf112bcbc
|
@ -11,7 +11,6 @@ import struct
|
||||||
import socket
|
import socket
|
||||||
import asyncio
|
import asyncio
|
||||||
import time
|
import time
|
||||||
from tornado.httpclient import AsyncHTTPClient
|
|
||||||
from tornado.escape import json_decode
|
from tornado.escape import json_decode
|
||||||
|
|
||||||
# Annotation imports
|
# Annotation imports
|
||||||
|
@ -24,6 +23,7 @@ from typing import (
|
||||||
Dict,
|
Dict,
|
||||||
Coroutine,
|
Coroutine,
|
||||||
Union,
|
Union,
|
||||||
|
cast
|
||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
@ -33,6 +33,7 @@ if TYPE_CHECKING:
|
||||||
from . import klippy_apis
|
from . import klippy_apis
|
||||||
from .mqtt import MQTTClient
|
from .mqtt import MQTTClient
|
||||||
from .template import JinjaTemplate
|
from .template import JinjaTemplate
|
||||||
|
from .http_client import HttpClient
|
||||||
APIComp = klippy_apis.KlippyAPI
|
APIComp = klippy_apis.KlippyAPI
|
||||||
|
|
||||||
class PrinterPower:
|
class PrinterPower:
|
||||||
|
@ -411,7 +412,7 @@ class HTTPDevice(PowerDevice):
|
||||||
default_protocol: str = "http"
|
default_protocol: str = "http"
|
||||||
) -> None:
|
) -> None:
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
self.client = AsyncHTTPClient()
|
self.client: HttpClient = self.server.lookup_component("http_client")
|
||||||
self.addr: str = config.get("address")
|
self.addr: str = config.get("address")
|
||||||
self.port = config.getint("port", default_port)
|
self.port = config.getint("port", default_port)
|
||||||
self.user = config.load_template("user", default_user).render()
|
self.user = config.load_template("user", default_user).render()
|
||||||
|
@ -428,18 +429,13 @@ class HTTPDevice(PowerDevice):
|
||||||
command: str,
|
command: str,
|
||||||
retries: int = 3
|
retries: int = 3
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
for i in range(retries):
|
url = self.client.escape_url(url)
|
||||||
try:
|
response = await self.client.get(
|
||||||
response = await self.client.fetch(
|
url, request_timeout=20., attempts=retries,
|
||||||
url, connect_timeout=5., request_timeout=20.)
|
retry_pause_time=1., enable_cache=False)
|
||||||
data = json_decode(response.body)
|
response.raise_for_status(
|
||||||
except Exception as e:
|
f"Error sending '{self.type}' command: {command}")
|
||||||
if i == retries - 1:
|
data = cast(dict, response.json())
|
||||||
msg = f"Error sending '{self.type}' command: {command}"
|
|
||||||
raise self.server.error(msg) from e
|
|
||||||
await asyncio.sleep(1.0)
|
|
||||||
else:
|
|
||||||
break
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
async def _send_power_request(self, state: str) -> str:
|
async def _send_power_request(self, state: str) -> str:
|
||||||
|
@ -955,14 +951,18 @@ class SmartThings(HTTPDevice):
|
||||||
async def _send_smartthings_command(self,
|
async def _send_smartthings_command(self,
|
||||||
command: str
|
command: str
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
|
body: Optional[List[Dict[str, Any]]] = None
|
||||||
if (command == "on" or command == "off"):
|
if (command == "on" or command == "off"):
|
||||||
method = "POST"
|
method = "POST"
|
||||||
url = (f"{self.protocol}://{self.addr}"
|
url = (f"{self.protocol}://{self.addr}"
|
||||||
f"/v1/devices/{self.device}/commands")
|
f"/v1/devices/{self.device}/commands")
|
||||||
body = (f'[{{"component":"main", '
|
body = [
|
||||||
'"capability":"switch", '
|
{
|
||||||
f'"command": "{command}"}}]')
|
"component": "main",
|
||||||
|
"capability": "switch",
|
||||||
|
"command": command
|
||||||
|
}
|
||||||
|
]
|
||||||
elif command == "info":
|
elif command == "info":
|
||||||
method = "GET"
|
method = "GET"
|
||||||
url = (f"{self.protocol}://{self.addr}/v1/devices/{self.device}/"
|
url = (f"{self.protocol}://{self.addr}/v1/devices/{self.device}/"
|
||||||
|
@ -972,22 +972,16 @@ class SmartThings(HTTPDevice):
|
||||||
f"Invalid SmartThings command: {command}")
|
f"Invalid SmartThings command: {command}")
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
'Authorization': f'Bearer {self.token}',
|
'Authorization': f'Bearer {self.token}'
|
||||||
'Content-Type': 'application/json'
|
|
||||||
}
|
}
|
||||||
|
url = self.client.escape_url(url)
|
||||||
try:
|
response = await self.client.request(
|
||||||
if method == "POST":
|
method, url, body=body, headers=headers,
|
||||||
response = await self.client.fetch(
|
enable_cache=False
|
||||||
url, method=method, headers=headers, body=body)
|
)
|
||||||
elif method == "GET":
|
msg = f"Error sending SmartThings command: {command}"
|
||||||
response = await self.client.fetch(
|
response.raise_for_status(msg)
|
||||||
url, method=method, headers=headers)
|
data = cast(dict, response.json())
|
||||||
data: Dict[str, Any] = json_decode(response.body)
|
|
||||||
except Exception:
|
|
||||||
msg = f"Error sending SmartThings command: {command}"
|
|
||||||
logging.exception(msg)
|
|
||||||
raise self.server.error(msg)
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
async def _send_status_request(self) -> str:
|
async def _send_status_request(self) -> str:
|
||||||
|
@ -1038,13 +1032,10 @@ class HomeAssistant(HTTPDevice):
|
||||||
|
|
||||||
async def _send_homeassistant_command(self,
|
async def _send_homeassistant_command(self,
|
||||||
command: str
|
command: str
|
||||||
) -> Dict[Union[str, int], Any]:
|
) -> Dict[str, Any]:
|
||||||
if command == "on":
|
body: Optional[Dict[str, Any]] = None
|
||||||
out_cmd = f"api/services/{self.domain}/turn_on"
|
if command in ["on", "off"]:
|
||||||
body = {"entity_id": self.device}
|
out_cmd = f"api/services/{self.domain}/turn_{command}"
|
||||||
method = "POST"
|
|
||||||
elif command == "off":
|
|
||||||
out_cmd = f"api/services/{self.domain}/turn_off"
|
|
||||||
body = {"entity_id": self.device}
|
body = {"entity_id": self.device}
|
||||||
method = "POST"
|
method = "POST"
|
||||||
elif command == "info":
|
elif command == "info":
|
||||||
|
@ -1055,21 +1046,18 @@ class HomeAssistant(HTTPDevice):
|
||||||
f"Invalid homeassistant command: {command}")
|
f"Invalid homeassistant command: {command}")
|
||||||
url = f"{self.protocol}://{self.addr}:{self.port}/{out_cmd}"
|
url = f"{self.protocol}://{self.addr}:{self.port}/{out_cmd}"
|
||||||
headers = {
|
headers = {
|
||||||
'Authorization': f'Bearer {self.token}',
|
'Authorization': f'Bearer {self.token}'
|
||||||
'Content-Type': 'application/json'
|
|
||||||
}
|
}
|
||||||
try:
|
data: Dict[str, Any] = {}
|
||||||
if (method == "POST"):
|
url = self.client.escape_url(url)
|
||||||
response = await self.client.fetch(
|
response = await self.client.request(
|
||||||
url, method="POST", body=json.dumps(body), headers=headers)
|
method, url, body=body, headers=headers,
|
||||||
else:
|
enable_cache=False
|
||||||
response = await self.client.fetch(
|
)
|
||||||
url, method="GET", headers=headers)
|
msg = f"Error sending homeassistant command: {command}"
|
||||||
data: Dict[Union[str, int], Any] = json_decode(response.body)
|
response.raise_for_status(msg)
|
||||||
except Exception:
|
if method == "GET":
|
||||||
msg = f"Error sending homeassistant command: {command}"
|
data = cast(dict, response.json())
|
||||||
logging.exception(msg)
|
|
||||||
raise self.server.error(msg)
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
async def _send_status_request(self) -> str:
|
async def _send_status_request(self) -> str:
|
||||||
|
|
Loading…
Reference in New Issue