Skip to content

Commit 07d6718

Browse files
committed
Make it simpler
1 parent 15110e7 commit 07d6718

3 files changed

Lines changed: 28 additions & 29 deletions

File tree

dingz/__init__.py

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,52 +7,44 @@
77
import aiohttp
88
import async_timeout
99

10-
from .constants import TIMEOUT, USER_AGENT
10+
from .constants import TIMEOUT, USER_AGENT, CONTENT_TYPE_JSON, CONTENT_TYPE, CONTENT_TYPE_TEXT_PLAIN
1111
from .exceptions import DingzConnectionError, DingzError
1212

1313

14-
async def _request(
14+
async def make_call(
1515
self,
1616
uri: str,
1717
method: str = "GET",
1818
data: Optional[Any] = None,
1919
json_data: Optional[dict] = None,
20-
params: Optional[Mapping[str, str]] = None,
20+
parameters: Optional[Mapping[str, str]] = None,
21+
token: str = None,
2122
) -> Any:
22-
"""Handle a request to the dingz unit."""
23+
"""Handle the requests to the dingz unit."""
24+
2325
headers = {
2426
"User-Agent": USER_AGENT,
25-
"Accept": "application/json, text/plain, */*",
27+
"Accept": f"{CONTENT_TYPE_JSON}, {CONTENT_TYPE_TEXT_PLAIN}, */*",
2628
}
2729

30+
if token:
31+
headers["Authorization"] = f"Bearer {token}"
32+
2833
if self._session is None:
2934
self._session = aiohttp.ClientSession()
3035
self._close_session = True
3136

3237
try:
3338
with async_timeout.timeout(TIMEOUT):
3439
response = await self._session.request(
35-
method, uri, data=data, json=json_data, params=params, headers=headers,
40+
method, uri, data=data, json=json_data, params=parameters, headers=headers,
3641
)
3742
except asyncio.TimeoutError as exception:
38-
raise DingzConnectionError(
39-
"Timeout occurred while connecting to dingz unit."
40-
) from exception
43+
raise DingzConnectionError("Timeout occurred while connecting to dingz unit") from exception
4144
except (aiohttp.ClientError, socket.gaierror) as exception:
42-
raise DingzConnectionError(
43-
"Error occurred while communicating with dingz."
44-
) from exception
45-
46-
content_type = response.headers.get("Content-Type", "")
47-
if (response.status // 100) in [4, 5]:
48-
contents = await response.read()
49-
response.close()
50-
51-
if content_type == "application/json":
52-
raise DingzError(response.status, json.loads(contents.decode("utf8")))
53-
raise DingzError(response.status, {"message": contents.decode("utf8")})
45+
raise DingzConnectionError("Error occurred while communicating with dingz") from exception
5446

55-
if "application/json" in content_type:
47+
if CONTENT_TYPE_JSON in response.headers.get(CONTENT_TYPE, ""):
5648
response_json = await response.json()
5749
return response_json
5850

dingz/constants.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,8 @@
3333
PIR_CONFIGURATION = "pir_config"
3434
THERMOSTAT_CONFIGURATION = "thermostat_config"
3535
INPUT_CONFIGURATION = "input_config"
36+
37+
# Communication constants
38+
CONTENT_TYPE_JSON = "application/json"
39+
CONTENT_TYPE = 'Content-Type'
40+
CONTENT_TYPE_TEXT_PLAIN = "text/plain"

dingz/dingz.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import aiohttp
55
from yarl import URL
66

7-
from . import _request as request
7+
from . import make_call
88
from .constants import API, DEVICE_INFO, TEMPERATURE, LIGHT, FRONT_LED_GET, FRONT_LED_SET
99
from .exceptions import DingzError
1010

@@ -28,38 +28,38 @@ def __init__(self, host: str, session: aiohttp.client.ClientSession = None) -> N
2828
async def get_device_info(self) -> None:
2929
"""Get the details from the dingz."""
3030
url = URL(self.uri).join(URL(DEVICE_INFO))
31-
response = await request(self, uri=url)
31+
response = await make_call(self, uri=url)
3232
self._device_details = response
3333

3434
async def get_temperature(self) -> None:
3535
"""Get the room temperature from the dingz."""
3636
url = URL(self.uri).join(URL(TEMPERATURE))
37-
response = await request(self, uri=url)
37+
response = await make_call(self, uri=url)
3838
self._temperature = response["temperature"]
3939

4040
async def get_light(self) -> None:
4141
"""Get the light details from the switch."""
4242
url = URL(self.uri).join(URL(LIGHT))
43-
response = await request(self, uri=url)
43+
response = await make_call(self, uri=url)
4444
self._intensity = response["intensity"]
4545
self._day = response["day"]
4646

4747
async def enabled(self) -> bool:
4848
"""Return true if front LED is on."""
4949
url = URL(self.uri).join(URL(FRONT_LED_GET))
50-
response = await request(self, uri=url)
50+
response = await make_call(self, uri=url)
5151
return bool(response["on"])
5252

5353
async def turn_on(self) -> None:
5454
"""Enable/turn on the front LED."""
5555
data = {"action": "on"}
5656
url = URL(self.uri).join(URL(FRONT_LED_SET))
57-
await request(self, uri=url, method="POST", data=data)
57+
await make_call(self, uri=url, method="POST", data=data)
5858

5959
async def turn_off(self) -> None:
6060
"""Disable/turn off the front LED."""
6161
url = URL(self.uri).join(URL(FRONT_LED_SET))
62-
await request(self, uri=url, method="POST", data={"action": "off"})
62+
await make_call(self, uri=url, method="POST", data={"action": "off"})
6363

6464
@property
6565
def device_details(self) -> str:
@@ -81,6 +81,8 @@ def intensity(self) -> float:
8181
"""Return the current light intensity in lux."""
8282
return round(self._intensity, 1)
8383

84+
# See "Using Asyncio in Python" by Caleb Hattingh for implementation
85+
# details.
8486
async def close(self) -> None:
8587
"""Close an open client session."""
8688
if self._session and self._close_session:

0 commit comments

Comments
 (0)