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

Add commands for setting date and time #83

Merged
merged 1 commit into from
Jan 11, 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
52 changes: 39 additions & 13 deletions examples/rainbird_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,33 @@
```
"""

import argparse
import asyncio
import aiohttp
import sys
import datetime
import inspect
import argparse
import logging

from pyrainbird import async_client
import logging
import os
from typing import Any

import aiohttp

from pyrainbird import async_client

_LOGGER = logging.getLogger(__name__)


def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--log-level', default='warning', choices=['debug', 'info', 'warning', 'error', 'critical'], help='The log level')

subcommand_parsers = parser.add_subparsers(title='Commands', dest='command', required=True)
parser.add_argument(
"--log-level",
default="warning",
choices=["debug", "info", "warning", "error", "critical"],
help="The log level",
)

subcommand_parsers = parser.add_subparsers(
title="Commands", dest="command", required=True
)
for method_name in dir(async_client.AsyncRainbirdController):
if method_name.startswith("_"):
continue
Expand All @@ -47,7 +54,9 @@ def parse_args():
continue

# Create a parser for the method
method_parser = subcommand_parsers.add_parser(method_name, help=f'Call the {method_name} method')
method_parser = subcommand_parsers.add_parser(
method_name, help=f"Call the {method_name} method"
)
method_parser.set_defaults(func=method)

# Get the arguments of the method
Expand All @@ -60,20 +69,37 @@ def parse_args():
return parser.parse_args()


def parse_value(value: Any) -> Any:
"""Parse the command line arg into a value."""
try:
return datetime.date.fromisoformat(value)
except ValueError:
pass
try:
return datetime.time.fromisoformat(value)
except ValueError:
pass
return int(value, 16)


async def main():
args = parse_args()
print(getattr(logging, args.log_level.upper()))
logging.basicConfig(level=getattr(logging, args.log_level.upper()))

host = os.environ["RAINBIRD_SERVER"]
password = os.environ["RAINBIRD_PASSWORD"]

async with aiohttp.ClientSession() as session:
client = async_client.CreateController(session, host, password)
method_args = {k: v for k, v in vars(args).items() if k != 'func' and k != 'command' and k != 'log_level'}
method_args = {
k: parse_value(v)
for k, v in vars(args).items()
if k != "func" and k != "command" and k != "log_level"
}
result = await args.func(client, **method_args)
print(result)


# Run the main function if this script is run
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())
20 changes: 20 additions & 0 deletions pyrainbird/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,13 +153,33 @@ async def get_current_time(self) -> datetime.time:
"CurrentTimeRequest",
)

async def set_current_time(self, value: datetime.time) -> None:
"""Set the device current time."""
await self._process_command(
lambda resp: True,
"SetCurrentTimeRequest",
value.hour,
value.minute,
value.second,
)

async def get_current_date(self) -> datetime.date:
"""Get the device current date."""
return await self._process_command(
lambda resp: datetime.date(resp["year"], resp["month"], resp["day"]),
"CurrentDateRequest",
)

async def set_current_date(self, value: datetime.date) -> None:
"""Set the device current date."""
await self._process_command(
lambda resp: True,
"SetCurrentDateRequest",
value.day,
value.month,
value.year,
)

async def get_wifi_params(self) -> WifiParams:
"""Return wifi parameters and other settings."""
result = await self._local_client.request("getWifiParams")
Expand Down
28 changes: 26 additions & 2 deletions pyrainbird/resources/sipcommands.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,36 @@ ControllerCommands:
command: '10'
response: '90'
length: 1
# SetTimeRequest: 11
SetCurrentTimeRequest:
command: '11'
response: '01'
length: 4
hour:
position: 2
length: 2
minute:
position: 4
length: 2
second:
position: 6
length: 2
CurrentDateRequest:
command: '12'
response: '92'
length: 1
# SetDateRequest: 13
SetCurrentDateRequest:
command: '13'
response: '01'
length: 4
day:
position: 2
length: 2
month:
position: 4
length: 1
year:
position: 5
length: 3
# currentTimeZone: FC
# SetTimeZoneRequest: 2B
RetrieveScheduleRequest:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,26 @@ async def test_get_current_date(
assert await controller.get_current_date() == date


async def test_set_current_time(
rainbird_controller: Callable[[], Awaitable[AsyncRainbirdController]],
api_response: Callable[[...], Awaitable[None]],
) -> None:
"""Test for setting the current time."""
controller = await rainbird_controller()
api_response("01", commandEcho="11")
await controller.set_current_time(datetime.datetime.now().time())


async def test_set_current_date(
rainbird_controller: Callable[[], Awaitable[AsyncRainbirdController]],
api_response: Callable[[...], Awaitable[None]],
) -> None:
"""Test for setting the current date."""
controller = await rainbird_controller()
api_response("01", commandEcho="13")
await controller.set_current_date(datetime.date.today())


async def test_get_water_budget(
rainbird_controller: Callable[[], Awaitable[AsyncRainbirdController]],
api_response: Callable[[...], Awaitable[None]],
Expand Down
18 changes: 17 additions & 1 deletion tests/testdata/date_time.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
data:
- "10"
- "900C3623"
- "12"
- "9212B7E2"
- "11162F13"
- "130917E7"
- "0111"
decoded_data:
- type: CurrentTimeRequest
- type: CurrentTimeResponse
hour: 12
minute: 54
second: 35
- type: CurrentDateRequest
- type: CurrentDateResponse
year: 2018
month: 11
day: 18

- type: SetCurrentTimeRequest
hour: 22
minute: 47
second: 19
- type: SetCurrentDateRequest
day: 9
month: 1
year: 2023
- type: AcknowledgeResponse
commandEcho: 17