| 1 |
# Copyright 2023 Simone Chemelli and contributors |
| 2 |
# SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
"""Test script for aiocomelit library.""" |
| 5 |
|
| 6 |
import asyncio |
| 7 |
import json |
| 8 |
import logging |
| 9 |
import sys |
| 10 |
from argparse import ArgumentParser, Namespace |
| 11 |
from pathlib import Path |
| 12 |
|
| 13 |
from aiohttp import ClientSession, CookieJar, TCPConnector |
| 14 |
from colorlog import ColoredFormatter |
| 15 |
|
| 16 |
from aiocomelit import __version__ |
| 17 |
from aiocomelit.api import ( |
| 18 |
ComelitDeviceObject, |
| 19 |
ComelitHttpApi, |
| 20 |
ComelitVedoAreaObject, |
| 21 |
) |
| 22 |
from aiocomelit.const import ( |
| 23 |
ALARM_AREA, |
| 24 |
ALARM_DISABLE, |
| 25 |
ALARM_ENABLE, |
| 26 |
ALARM_ZONE, |
| 27 |
BRIDGE, |
| 28 |
COVER, |
| 29 |
IRRIGATION, |
| 30 |
LIGHT, |
| 31 |
OTHER, |
| 32 |
VEDO, |
| 33 |
AlarmAreaState, |
| 34 |
AlarmZoneState, |
| 35 |
) |
| 36 |
from aiocomelit.devices.bridge import ComeliteSerialBridgeApi |
| 37 |
from aiocomelit.devices.vedo import ComelitVedoApi |
| 38 |
from aiocomelit.exceptions import CannotAuthenticate, CannotConnect, CannotRetrieveData |
| 39 |
|
| 40 |
INDEX = 0 |
| 41 |
|
| 42 |
|
| 43 |
def get_arguments() -> tuple[ArgumentParser, Namespace]: |
| 44 |
"""Get parsed passed in arguments.""" |
| 45 |
parser = ArgumentParser(description="aiocomelit library test") |
| 46 |
parser.add_argument( |
| 47 |
"--bridge", |
| 48 |
"-b", |
| 49 |
type=str, |
| 50 |
default="192.168.1.252", |
| 51 |
help="Set Serial bridge IP address", |
| 52 |
) |
| 53 |
parser.add_argument( |
| 54 |
"--bridge_port", |
| 55 |
"-bport", |
| 56 |
type=int, |
| 57 |
default=80, |
| 58 |
help="Set Serial bridge http port", |
| 59 |
) |
| 60 |
parser.add_argument( |
| 61 |
"--bridge_pin", |
| 62 |
"-bp", |
| 63 |
type=str, |
| 64 |
default="", |
| 65 |
help="Set Serial bridge pin", |
| 66 |
) |
| 67 |
parser.add_argument( |
| 68 |
"--bridge_vedo", |
| 69 |
"-bv", |
| 70 |
action="store_true", |
| 71 |
help="Use Serial bridge to access VEDO", |
| 72 |
) |
| 73 |
parser.add_argument( |
| 74 |
"--bridge_skip", |
| 75 |
"-bs", |
| 76 |
action="store_true", |
| 77 |
help="Skip Serial bridge login", |
| 78 |
) |
| 79 |
parser.add_argument( |
| 80 |
"--vedo", |
| 81 |
"-v", |
| 82 |
type=str, |
| 83 |
default="192.168.1.230", |
| 84 |
help="Set VEDO system IP address", |
| 85 |
) |
| 86 |
parser.add_argument( |
| 87 |
"--vedo_port", |
| 88 |
"-vport", |
| 89 |
type=int, |
| 90 |
default=80, |
| 91 |
help="Set VEDO system http port", |
| 92 |
) |
| 93 |
parser.add_argument( |
| 94 |
"--vedo_pin", |
| 95 |
"-vp", |
| 96 |
type=str, |
| 97 |
default="", |
| 98 |
help="Set VEDO system pin", |
| 99 |
) |
| 100 |
parser.add_argument( |
| 101 |
"--vedo_skip", |
| 102 |
"-vs", |
| 103 |
action="store_true", |
| 104 |
help="Skip VEDO system login", |
| 105 |
) |
| 106 |
parser.add_argument( |
| 107 |
"--test", |
| 108 |
"-t", |
| 109 |
action="store_true", |
| 110 |
help="Execute test actions", |
| 111 |
) |
| 112 |
parser.add_argument( |
| 113 |
"--configfile", |
| 114 |
"-cf", |
| 115 |
type=str, |
| 116 |
help="Load options from JSON config file. \ |
| 117 |
Command line options override those in the file.", |
| 118 |
) |
| 119 |
arguments = parser.parse_args() |
| 120 |
# Re-parse the command line |
| 121 |
# taking the options in the optional JSON file as a basis |
| 122 |
if arguments.configfile and Path(arguments.configfile).exists(): |
| 123 |
with Path.open(arguments.configfile) as f: |
| 124 |
arguments = parser.parse_args(namespace=Namespace(**json.load(f))) |
| 125 |
|
| 126 |
return parser, arguments |
| 127 |
|
| 128 |
|
| 129 |
def logger(host_type: str, host: str, port: int) -> str: |
| 130 |
"""Create logging string.""" |
| 131 |
return f"{host_type} ({host}:{port})" |
| 132 |
|
| 133 |
|
| 134 |
async def execute_device_test( |
| 135 |
api: ComeliteSerialBridgeApi, |
| 136 |
device: ComelitDeviceObject, |
| 137 |
dev_type: str, |
| 138 |
api_logging: str, |
| 139 |
) -> None: |
| 140 |
"""Execute a test routine on a specific device type.""" |
| 141 |
print(f"[{api_logging}] Test {dev_type} device: {device.name}") |
| 142 |
status = await api.get_device_status(dev_type, device.index) |
| 143 |
print(f"[{api_logging}] Status before: {status}") |
| 144 |
await api.set_device_status(dev_type, device.index, (not status)) |
| 145 |
status = await api.get_device_status(dev_type, device.index) |
| 146 |
print(f"[{api_logging}] Status after: {status}") |
| 147 |
|
| 148 |
|
| 149 |
async def execute_alarm_test( |
| 150 |
api: ComelitHttpApi, area: ComelitVedoAreaObject, api_logging: str |
| 151 |
) -> None: |
| 152 |
"""Execute a test routine on a specific VEDO zone.""" |
| 153 |
print(f"[{api_logging}] Test zone: {area.name}") |
| 154 |
area_object = await api.get_area_status(area) |
| 155 |
print(f"[{api_logging}] Status before: {area_object}") |
| 156 |
action = ( |
| 157 |
ALARM_DISABLE |
| 158 |
if area_object.human_status == AlarmAreaState.ARMED |
| 159 |
else ALARM_ENABLE |
| 160 |
) |
| 161 |
await api.set_zone_status(area.index, action) |
| 162 |
print(f"[{api_logging}] Status after: {await api.get_area_status(area)}") |
| 163 |
|
| 164 |
|
| 165 |
async def bridge_test(session: ClientSession, args: Namespace) -> bool: |
| 166 |
"""Test code for Comelit Serial Bridge.""" |
| 167 |
bridge_api = ComeliteSerialBridgeApi( |
| 168 |
args.bridge, args.bridge_port, args.bridge_pin, session |
| 169 |
) |
| 170 |
api_logging = logger(BRIDGE, args.bridge, args.bridge_port) |
| 171 |
|
| 172 |
logged = False |
| 173 |
try: |
| 174 |
logged = await bridge_api.login() |
| 175 |
except (CannotConnect, CannotAuthenticate): |
| 176 |
pass |
| 177 |
finally: |
| 178 |
if not logged: |
| 179 |
print(f"[{api_logging}] Unable to login") |
| 180 |
await session.close() |
| 181 |
sys.exit(1) |
| 182 |
print(f"[{api_logging}] Logged = {logged}") |
| 183 |
print("-" * 20) |
| 184 |
devices = await bridge_api.get_all_devices() |
| 185 |
print(f"[{api_logging}] Devices: {devices}") |
| 186 |
print("-" * 20) |
| 187 |
if args.test: |
| 188 |
for device in devices[LIGHT].values(): |
| 189 |
if device.index == INDEX: |
| 190 |
await execute_device_test(bridge_api, device, LIGHT, api_logging) |
| 191 |
break |
| 192 |
for device in devices[COVER].values(): |
| 193 |
if device.index == INDEX: |
| 194 |
await execute_device_test(bridge_api, device, COVER, api_logging) |
| 195 |
break |
| 196 |
for device in devices[IRRIGATION].values(): |
| 197 |
if device.index == INDEX: |
| 198 |
await execute_device_test(bridge_api, device, IRRIGATION, api_logging) |
| 199 |
break |
| 200 |
for device in devices[OTHER].values(): |
| 201 |
if device.index == INDEX: |
| 202 |
await execute_device_test(bridge_api, device, OTHER, api_logging) |
| 203 |
break |
| 204 |
print("-" * 20) |
| 205 |
|
| 206 |
vedo_enabled: bool = args.bridge_vedo and await bridge_api.vedo_enabled( |
| 207 |
args.vedo_pin or args.bridge_pin |
| 208 |
) |
| 209 |
|
| 210 |
if vedo_enabled: |
| 211 |
print(f"[{api_logging}] VEDO Enabled !") |
| 212 |
await vedo_test(session, args, bridge_api) |
| 213 |
|
| 214 |
print(f"[{api_logging}] Logout") |
| 215 |
await bridge_api.logout() |
| 216 |
|
| 217 |
return vedo_enabled |
| 218 |
|
| 219 |
|
| 220 |
async def vedo_test( |
| 221 |
session: ClientSession, |
| 222 |
args: Namespace, |
| 223 |
bridge_api: ComeliteSerialBridgeApi | None = None, |
| 224 |
) -> None: |
| 225 |
"""Test code for Comelit VEDO system.""" |
| 226 |
api: ComelitHttpApi |
| 227 |
|
| 228 |
if not bridge_api: |
| 229 |
api = ComelitVedoApi(args.vedo, args.vedo_port, args.vedo_pin, session) |
| 230 |
api_logging = logger(VEDO, args.vedo, args.vedo_port) |
| 231 |
logged = False |
| 232 |
try: |
| 233 |
logged = await api.login() |
| 234 |
except (CannotConnect, CannotAuthenticate): |
| 235 |
pass |
| 236 |
finally: |
| 237 |
if not logged: |
| 238 |
print(f"[{api_logging}] Unable to login to {VEDO}") |
| 239 |
await session.close() |
| 240 |
sys.exit(1) |
| 241 |
print(f"[{api_logging}] Logged = {logged}") |
| 242 |
else: |
| 243 |
api = bridge_api |
| 244 |
api_logging = logger(BRIDGE, args.bridge, args.bridge_port) |
| 245 |
print(f"[{api_logging}] {VEDO} logged") |
| 246 |
print("-" * 20) |
| 247 |
try: |
| 248 |
alarm_data = await api.get_all_areas_and_zones() |
| 249 |
except (CannotAuthenticate, CannotRetrieveData): |
| 250 |
print(f"[{api_logging}] Unable to retrieve data for {VEDO}") |
| 251 |
await api.logout() |
| 252 |
await session.close() |
| 253 |
sys.exit(2) |
| 254 |
print(f"[{api_logging}] AREAS:") |
| 255 |
for area in alarm_data[ALARM_AREA]: |
| 256 |
print(alarm_data[ALARM_AREA][area]) |
| 257 |
print("-" * 20) |
| 258 |
print(f"[{api_logging}] ZONES:") |
| 259 |
for zone_index in alarm_data[ALARM_ZONE]: |
| 260 |
zone = alarm_data[ALARM_ZONE][zone_index] |
| 261 |
if zone.human_status != AlarmZoneState.UNAVAILABLE: |
| 262 |
print(zone) |
| 263 |
print("-" * 20) |
| 264 |
area_object = alarm_data[ALARM_AREA][INDEX] |
| 265 |
if args.test and isinstance(area_object, ComelitVedoAreaObject): |
| 266 |
await execute_alarm_test(api, area_object, api_logging) |
| 267 |
print("-" * 20) |
| 268 |
print(f"{api_logging} Logout") |
| 269 |
await api.logout() |
| 270 |
|
| 271 |
|
| 272 |
async def main() -> None: |
| 273 |
"""Run main.""" |
| 274 |
_, args = get_arguments() |
| 275 |
|
| 276 |
print("-" * 20) |
| 277 |
print(f"aiocomelit version: {__version__}") |
| 278 |
print("-" * 20) |
| 279 |
|
| 280 |
# Create aiohttp.ClientSsession |
| 281 |
print("Creating HTTP ClientSession") |
| 282 |
jar = CookieJar(unsafe=True) |
| 283 |
connector = TCPConnector(force_close=True) |
| 284 |
session = ClientSession(cookie_jar=jar, connector=connector) |
| 285 |
|
| 286 |
if args.bridge_skip: |
| 287 |
print(f"{BRIDGE}: Skipping login as requested") |
| 288 |
bridge_vedo_enabled = False |
| 289 |
else: |
| 290 |
bridge_vedo_enabled = await bridge_test(session, args) |
| 291 |
|
| 292 |
if args.vedo_skip: |
| 293 |
print(f"{VEDO}: Skipping login as requested") |
| 294 |
# VEDO is not accessible via Serial bridge, need direct access |
| 295 |
elif not bridge_vedo_enabled: |
| 296 |
# VEDO system mandatorily requires a pin for direct access |
| 297 |
if not args.vedo_pin: |
| 298 |
print(f"{VEDO}: Missing PIN. Skipping tests") |
| 299 |
else: |
| 300 |
await vedo_test(session, args, None) |
| 301 |
|
| 302 |
print("Closing HTTP ClientSession") |
| 303 |
await session.close() |
| 304 |
|
| 305 |
|
| 306 |
def set_logging() -> None: |
| 307 |
"""Set logging levels.""" |
| 308 |
logging.basicConfig(level=logging.DEBUG) |
| 309 |
logging.getLogger("asyncio").setLevel(logging.INFO) |
| 310 |
logging.getLogger("charset_normalizer").setLevel(logging.INFO) |
| 311 |
fmt = ( |
| 312 |
"%(asctime)s.%(msecs)03d %(levelname)s (%(threadName)s) [%(name)s] %(message)s" |
| 313 |
) |
| 314 |
colorfmt = f"%(log_color)s{fmt}%(reset)s" |
| 315 |
logging.getLogger().handlers[0].setFormatter( |
| 316 |
ColoredFormatter( |
| 317 |
colorfmt, |
| 318 |
datefmt="%Y-%m-%d %H:%M:%S", |
| 319 |
reset=True, |
| 320 |
log_colors={ |
| 321 |
"DEBUG": "cyan", |
| 322 |
"INFO": "green", |
| 323 |
"WARNING": "yellow", |
| 324 |
"ERROR": "red", |
| 325 |
"CRITICAL": "red", |
| 326 |
}, |
| 327 |
), |
| 328 |
) |
| 329 |
|
| 330 |
|
| 331 |
if __name__ == "__main__": |
| 332 |
set_logging() |
| 333 |
asyncio.run(main()) |