| 1 |
"""Standalone CLI example for exercising the iotawattpy library.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import argparse |
| 6 |
import asyncio |
| 7 |
import logging |
| 8 |
|
| 9 |
import httpx |
| 10 |
|
| 11 |
from iotawattpy.iotawatt import Iotawatt |
| 12 |
|
| 13 |
logging.basicConfig(level="DEBUG") |
| 14 |
LOGGER = logging.getLogger(__name__) |
| 15 |
|
| 16 |
|
| 17 |
class Tester: |
| 18 |
def __init__( |
| 19 |
self, ip_addr: str, username: str | None, password: str | None |
| 20 |
) -> None: |
| 21 |
self._ip_addr = ip_addr |
| 22 |
self._username = username |
| 23 |
self._password = password |
| 24 |
|
| 25 |
async def run(self) -> None: |
| 26 |
async with httpx.AsyncClient() as session: |
| 27 |
iotawatt = Iotawatt( |
| 28 |
"iotawatt", |
| 29 |
self._ip_addr, |
| 30 |
session, |
| 31 |
self._username, |
| 32 |
self._password, |
| 33 |
) |
| 34 |
try: |
| 35 |
connected = await iotawatt.connect() |
| 36 |
except httpx.HTTPStatusError: |
| 37 |
LOGGER.exception("Connect failed") |
| 38 |
return |
| 39 |
if not connected: |
| 40 |
LOGGER.error("Failed to connect to IoTaWatt (check credentials?)") |
| 41 |
return |
| 42 |
|
| 43 |
while True: |
| 44 |
LOGGER.info("=" * 45) |
| 45 |
await iotawatt.update() |
| 46 |
LOGGER.info("=" * 45) |
| 47 |
await asyncio.sleep(5) |
| 48 |
|
| 49 |
|
| 50 |
def main() -> None: |
| 51 |
parser = argparse.ArgumentParser(description="Run the IoTaWatt tester") |
| 52 |
parser.add_argument("ip_address", help="IP address of the IoTaWatt") |
| 53 |
parser.add_argument("-u", "--username", default=None) |
| 54 |
parser.add_argument("-p", "--password", default=None) |
| 55 |
args = parser.parse_args() |
| 56 |
|
| 57 |
LOGGER.info("Started") |
| 58 |
asyncio.run(Tester(args.ip_address, args.username, args.password).run()) |
| 59 |
|
| 60 |
|
| 61 |
if __name__ == "__main__": |
| 62 |
main() |