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
65 changes: 65 additions & 0 deletions src/api/hive_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ def request(self, type, url, jsc=None, camera=False):
return requests.post(
url=url, headers=self.headers, data=jsc, timeout=self.timeout
)
if type == "DELETE":
return requests.delete(
url=url, headers=self.headers, data=jsc, timeout=self.timeout
)
except Exception as e:
_LOGGER.error("Request failed: %s", e)
raise
Expand Down Expand Up @@ -359,6 +363,67 @@ def setAction(self, n_id, data):

return self.json_return

def get_holiday_mode(self):
"""Get the current holiday mode configuration."""
url = self.urls["base"] + self.urls["holiday_mode"]
try:
response = self.request("GET", url)
self.json_return.update({"original": response.status_code})
self.json_return.update({"parsed": response.json()})
except (
OSError,
RuntimeError,
ZeroDivisionError,
ConnectionError,
json.JSONDecodeError,
):
self.error()

return self.json_return

def set_holiday_mode(self, start, end, temperature):
"""Schedule holiday mode.

Args:
start: Start time as epoch milliseconds.
end: End time as epoch milliseconds.
temperature: Frost-protection temperature to hold during holiday mode.
"""
jsc = json.dumps({"start": start, "end": end, "temperature": temperature})
url = self.urls["base"] + self.urls["holiday_mode"]
try:
response = self.request("POST", url, jsc)
self.json_return.update({"original": response.status_code})
self.json_return.update({"parsed": response.json()})
except (
OSError,
RuntimeError,
ZeroDivisionError,
ConnectionError,
json.JSONDecodeError,
):
self.error()

return self.json_return

def cancel_holiday_mode(self):
"""Cancel any scheduled or active holiday mode."""
url = self.urls["base"] + self.urls["holiday_mode"]
try:
response = self.request("DELETE", url, json.dumps({}))
self.json_return.update({"original": response.status_code})
self.json_return.update({"parsed": response.json()})
except (
OSError,
RuntimeError,
ZeroDivisionError,
ConnectionError,
json.JSONDecodeError,
):
self.error()

return self.json_return

def error(self):
"""An error has occurred interacting with the Hive API."""
_LOGGER.error("API error occurred - returning error response")
Expand Down
58 changes: 58 additions & 0 deletions src/api/hive_async_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,64 @@ async def setAction(self, n_id, data):

return self.json_return

async def get_holiday_mode(self):
"""Get the current holiday mode configuration."""
json_return = {}
try:
resp = await self.request("get", self.urls["holiday_mode"])
json_return.update({"original": resp.status})
json_return.update({"parsed": await resp.json(content_type=None)})
except (OSError, RuntimeError, ZeroDivisionError):
await self.error()

return json_return

async def set_holiday_mode(self, start: int, end: int, temperature: float):
"""Schedule holiday mode.

Args:
start: Start time as epoch milliseconds.
end: End time as epoch milliseconds.
temperature: Frost-protection temperature to hold during holiday mode.
"""
_LOGGER.debug(
"set_holiday_mode - Scheduling holiday mode from %s to %s at %s°.",
start,
end,
temperature,
)
json_return = {}
jsc = json.dumps({"start": start, "end": end, "temperature": temperature})
try:
await self.isFileBeingUsed()
resp = await self.request("post", self.urls["holiday_mode"], data=jsc)
json_return.update({"original": resp.status})
json_return.update({"parsed": await resp.json(content_type=None)})
except (FileInUse, OSError, RuntimeError, ConnectionError) as e:
if e.__class__.__name__ == "FileInUse":
return {"original": "file"}
await self.error()

return json_return

async def cancel_holiday_mode(self):
"""Cancel any scheduled or active holiday mode."""
_LOGGER.debug("cancel_holiday_mode - Cancelling holiday mode.")
json_return = {}
try:
await self.isFileBeingUsed()
resp = await self.request(
"delete", self.urls["holiday_mode"], data=json.dumps({})
)
json_return.update({"original": resp.status})
json_return.update({"parsed": await resp.json(content_type=None)})
except (FileInUse, OSError, RuntimeError, ConnectionError) as e:
if e.__class__.__name__ == "FileInUse":
return {"original": "file"}
await self.error()

return json_return

async def error(self):
"""An error has occurred interacting with the Hive API."""
_LOGGER.error("HTTP error occurred during Hive API interaction.")
Expand Down
60 changes: 59 additions & 1 deletion src/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

# pylint: skip-file
import logging
from datetime import datetime

from .helper.const import HIVETOHA
from .helper.const import HIVETOHA, HTTP_OK

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -88,3 +89,60 @@ async def getGlassBreakStatus(self, device: dict):
_LOGGER.error(e)

return final

async def get_holiday_mode(self):
"""Get the current holiday mode configuration.

Returns:
dict: Keys are active (bool), enabled (bool), start (epoch ms),
end (epoch ms) and temperature. None on failure.
"""
await self.session.hiveRefreshTokens()
resp = await self.session.api.get_holiday_mode()
if resp.get("original") == HTTP_OK:
return resp["parsed"]
_LOGGER.error(
"get_holiday_mode - Failed to fetch holiday mode: HTTP %s",
resp.get("original"),
)
return None

async def set_holiday_mode(self, start: datetime, end: datetime, temperature):
"""Schedule holiday mode.

Args:
start (datetime): Start date/time. Naive datetimes are local time.
end (datetime): End date/time. Naive datetimes are local time.
temperature (float): Frost-protection temperature to hold.

Returns:
boolean: True/False if successful.
"""
start_ms = int(start.timestamp() * 1000)
end_ms = int(end.timestamp() * 1000)
_LOGGER.debug(
"set_holiday_mode - Scheduling holiday mode from %s to %s at %s°.",
start,
end,
temperature,
)
await self.session.hiveRefreshTokens()
resp = await self.session.api.set_holiday_mode(start_ms, end_ms, temperature)
if resp.get("original") == HTTP_OK:
return True
_LOGGER.error("set_holiday_mode - Failed: HTTP %s", resp.get("original"))
return False

async def cancel_holiday_mode(self):
"""Cancel any scheduled or active holiday mode.

Returns:
boolean: True/False if successful.
"""
_LOGGER.debug("cancel_holiday_mode - Cancelling holiday mode.")
await self.session.hiveRefreshTokens()
resp = await self.session.api.cancel_holiday_mode()
if resp.get("original") == HTTP_OK:
return True
_LOGGER.error("cancel_holiday_mode - Failed: HTTP %s", resp.get("original"))
return False
Loading