f72740d89a
Toggling works for turning the switch off, but doesn't seem to work for turning it back on.
96 lines
2.2 KiB
Python
96 lines
2.2 KiB
Python
import dataclasses
|
|
import enum
|
|
import logging
|
|
import typing
|
|
|
|
import requests
|
|
import requests.auth
|
|
import typer
|
|
import yarl
|
|
|
|
|
|
class SwitchStatus(str, enum.Enum):
|
|
on = "on"
|
|
off = "off"
|
|
|
|
|
|
@dataclasses.dataclass
|
|
class Switch:
|
|
address: str
|
|
user: str
|
|
password: str
|
|
|
|
def switch(
|
|
self,
|
|
switch_id: int,
|
|
outlet: int,
|
|
from_state: SwitchStatus | None = None,
|
|
) -> None:
|
|
url = yarl.URL(f"http://{self.address}").joinpath(
|
|
"cgi-bin",
|
|
f"iswitch{switch_id:02d}",
|
|
"irswitch.exe",
|
|
)
|
|
|
|
params = {
|
|
"CURRENT": f"{switch_id:02d}",
|
|
f"SW{outlet}.x": 1,
|
|
f"SW{outlet}.y": 1,
|
|
}
|
|
if from_state:
|
|
params[f"STATUS{outlet}"] = f"{from_state.value.upper():3s}"
|
|
|
|
logging.info("Switching outlet: %s", params)
|
|
response = requests.post(
|
|
str(url),
|
|
auth=requests.auth.HTTPBasicAuth(self.user, self.password),
|
|
data=params,
|
|
allow_redirects=False,
|
|
)
|
|
print(response)
|
|
|
|
def switch_on(self, switch_id: int, outlet: int) -> None:
|
|
return self.switch(switch_id, outlet, from_state=SwitchStatus.off)
|
|
|
|
def switch_off(self, switch_id: int, outlet: int) -> None:
|
|
return self.switch(switch_id, outlet, from_state=SwitchStatus.on)
|
|
|
|
|
|
app = typer.Typer()
|
|
|
|
SwitchIdArgument = typing.Annotated[int, typer.Argument(min=1, max=16)]
|
|
OutletArgument = typing.Annotated[int, typer.Argument(min=1, max=8)]
|
|
|
|
|
|
@app.command()
|
|
def switch(
|
|
context: typer.Context,
|
|
switch_id: SwitchIdArgument,
|
|
outlet: OutletArgument,
|
|
action: typing.Annotated[SwitchStatus, typer.Argument(case_sensitive=False)],
|
|
) -> None:
|
|
switch: Switch = context.obj
|
|
match action:
|
|
case SwitchStatus.on:
|
|
switch.switch_on(switch_id, outlet)
|
|
case SwitchStatus.off:
|
|
switch.switch_off(switch_id, outlet)
|
|
|
|
|
|
@app.callback()
|
|
def main(
|
|
context: typer.Context,
|
|
address: str,
|
|
user: str = "admin",
|
|
password: str = "admin",
|
|
) -> None:
|
|
logging.basicConfig(level=logging.INFO)
|
|
context.obj = Switch(
|
|
address=address,
|
|
user=user,
|
|
password=password,
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app()
|