Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add set_curfew #150

Merged
merged 6 commits into from
Apr 4, 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
40 changes: 37 additions & 3 deletions surepy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import asyncio
import logging

from datetime import datetime
from datetime import datetime, time
from http import HTTPStatus
from http.client import HTTPException
from logging import Logger
Expand Down Expand Up @@ -205,6 +205,7 @@ async def call(
method: str,
resource: str,
data: dict[str, Any] | None = None,
json: dict[str, Any] | None = None,
second_try: bool = False,
**_: Any,
) -> dict[str, Any] | None:
Expand Down Expand Up @@ -236,7 +237,7 @@ async def call(

await session.options(resource, headers=headers)
response: aiohttp.ClientResponse = await session.request(
method, resource, headers=headers, data=data
method, resource, headers=headers, data=data, json=json
)

if response.status == HTTPStatus.OK or response.status == HTTPStatus.CREATED:
Expand Down Expand Up @@ -377,6 +378,39 @@ async def _set_lock_state(self, device_id: int, mode: LockState) -> dict[str, An
# return None
raise SurePetcareError("ERROR (UN)LOCKING DEVICE - PLEASE CHECK IMMEDIATELY!")

async def set_curfew(
self, device_id: int, lock_time: time, unlock_time: time
) -> dict[str, Any] | None:
"""Set the flap curfew times, using the household's timezone"""

resource = CONTROL_RESOURCE.format(BASE_RESOURCE=BASE_RESOURCE, device_id=device_id)

data = {
"curfew": [
{
"lock_time": lock_time.strftime("%H:%M"),
"unlock_time": unlock_time.strftime("%H:%M"),
"enabled": True,
}
]
}

if (
response := await self.call(
method="PUT", resource=resource, device_id=device_id, json=data
)
) and (response_data := response.get("data")):

desired_state = data.get("curfew")
state = response_data.get("curfew")

# check if the state is correctly updated
if state == desired_state:
return response

# return None
raise SurePetcareError("ERROR SETTING CURFEW - PLEASE CHECK IMMEDIATELY!")

async def _add_tag_to_device(self, device_id: int, tag_id: int) -> dict[str, Any] | None:
"""Add the specified tag ID to the specified device ID"""
resource = DEVICE_TAG_RESOURCE.format(BASE_RESOURCE=BASE_RESOURCE, device_id=device_id, tag_id=tag_id)
Expand All @@ -397,4 +431,4 @@ async def _remove_tag_from_device(self, device_id: int, tag_id: int) -> dict[str
method="DELETE", resource=resource
)
):
return response
return response
53 changes: 52 additions & 1 deletion surepy/surecli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import asyncio
import json

from datetime import datetime
from datetime import datetime, time
from functools import wraps
from pathlib import Path
from shutil import copyfile
Expand Down Expand Up @@ -426,6 +426,57 @@ async def locking(ctx: click.Context, device_id: int, mode: str, token: str | No
# await sp.sac.close_session()


@cli.command()
@click.pass_context
@click.option(
"-d", "--device", "device_id", required=True, type=int, help="id of the sure petcare device"
)
@click.option(
"--lock-time",
required=True,
type=time.fromisoformat,
help="Curfew lock time (in household's timezone)",
)
@click.option(
"--unlock-time",
required=True,
type=time.fromisoformat,
help="Curfew unlock time (in household's timezone)",
)
@click.option(
"-t", "--token", required=False, type=str, help="sure petcare api token", hide_input=True
)
@coro
async def curfew(
ctx: click.Context, device_id: int, lock_time: time, unlock_time: time, token: str | None = None
) -> None:
"""curfew control"""

token = token if token else ctx.obj.get("token", None)

sp = Surepy(auth_token=token)

if (flap := await sp.get_device(device_id=device_id)) and (type(flap) == Flap):

flap = cast(Flap, flap)

console.print(
f"setting {flap.name} curfew lock_time={str(lock_time)} unlock_time={str(unlock_time)}"
)

if await sp.sac.set_curfew(
device_id=device_id, lock_time=lock_time, unlock_time=unlock_time
) and (device := await sp.get_device(device_id=device_id)):
console.print(
f"✅ {device.name} curfew lock_time={str(lock_time)} unlock_time={str(unlock_time)} 🐾"
)
else:
console.print(
f"❌ setting curfew lock_time={str(lock_time)} unlock_time={str(unlock_time)} may have worked but "
f"something is fishy..!"
)


@cli.command()
@click.pass_context
@click.option("--pet", "pet_id", required=True, type=int, help="id of the pet")
Expand Down