| 1 |
"""async_upnp_client.cli module.""" |
| 2 |
# pylint: disable=invalid-name |
| 3 |
|
| 4 |
import argparse |
| 5 |
import asyncio |
| 6 |
import json |
| 7 |
import logging |
| 8 |
import operator |
| 9 |
import sys |
| 10 |
import time |
| 11 |
from datetime import datetime |
| 12 |
from typing import Any, Sequence, cast |
| 13 |
|
| 14 |
from async_upnp_client.advertisement import SsdpAdvertisementListener |
| 15 |
from async_upnp_client.aiohttp import AiohttpNotifyServer, AiohttpRequester |
| 16 |
from async_upnp_client.client import UpnpDevice, UpnpService, UpnpStateVariable |
| 17 |
from async_upnp_client.client_factory import UpnpFactory |
| 18 |
from async_upnp_client.const import AddressTupleVXType |
| 19 |
from async_upnp_client.exceptions import UpnpResponseError |
| 20 |
from async_upnp_client.profiles.dlna import dlna_handle_notify_last_change |
| 21 |
from async_upnp_client.search import async_search as async_ssdp_search |
| 22 |
from async_upnp_client.ssdp import SSDP_IP_V4, SSDP_IP_V6, SSDP_PORT, SSDP_ST_ALL |
| 23 |
from async_upnp_client.utils import CaseInsensitiveDict, get_local_ip |
| 24 |
|
| 25 |
logging.basicConfig() |
| 26 |
_LOGGER = logging.getLogger("upnp-client") |
| 27 |
_LOGGER.setLevel(logging.ERROR) |
| 28 |
_LOGGER_LIB = logging.getLogger("async_upnp_client") |
| 29 |
_LOGGER_LIB.setLevel(logging.ERROR) |
| 30 |
_LOGGER_TRAFFIC = logging.getLogger("async_upnp_client.traffic") |
| 31 |
_LOGGER_TRAFFIC.setLevel(logging.ERROR) |
| 32 |
|
| 33 |
|
| 34 |
parser = argparse.ArgumentParser(description="upnp_client") |
| 35 |
parser.add_argument("--debug", action="store_true", help="Show debug messages") |
| 36 |
parser.add_argument("--debug-traffic", action="store_true", help="Show network traffic") |
| 37 |
parser.add_argument("--pprint", action="store_true", help="Pretty-print (indent) JSON output") |
| 38 |
parser.add_argument("--timeout", type=int, help="Timeout for connection", default=4) |
| 39 |
parser.add_argument("--strict", action="store_true", help="Be strict about invalid data received") |
| 40 |
parser.add_argument("--iso8601", action="store_true", help="Print timestamp in ISO8601 format") |
| 41 |
|
| 42 |
subparsers = parser.add_subparsers(title="Command", dest="command") |
| 43 |
subparsers.required = True |
| 44 |
|
| 45 |
subparser = subparsers.add_parser("call-action", help="Call an action") |
| 46 |
subparser.add_argument("device", help="URL to device description XML") |
| 47 |
subparser.add_argument("call-action", nargs="+", help="service/action param1=val1 param2=val2") |
| 48 |
|
| 49 |
subparser = subparsers.add_parser("subscribe", help="Subscribe to services") |
| 50 |
subparser.add_argument("device", help="URL to device description XML") |
| 51 |
subparser.add_argument("service", nargs="+", help="service type or part or abbreviation") |
| 52 |
subparser.add_argument("--nolastchange", action="store_true", help="Do not show LastChange events") |
| 53 |
|
| 54 |
subparser = subparsers.add_parser("search", help="Search for devices") |
| 55 |
subparser.add_argument("--bind", help="ip to bind to, e.g., 192.168.0.10") |
| 56 |
subparser.add_argument( |
| 57 |
"--target", |
| 58 |
help="target ip, e.g., 192.168.0.10 or FF02::C%%6 to request from", |
| 59 |
) |
| 60 |
subparser.add_argument( |
| 61 |
"--target_port", |
| 62 |
help="port, e.g., 1900 or 1892 to request from", |
| 63 |
default=SSDP_PORT, |
| 64 |
type=int, |
| 65 |
) |
| 66 |
subparser.add_argument( |
| 67 |
"--search_target", |
| 68 |
help="search target to search for", |
| 69 |
default=SSDP_ST_ALL, |
| 70 |
) |
| 71 |
|
| 72 |
subparser = subparsers.add_parser("advertisements", help="Listen for advertisements") |
| 73 |
subparser.add_argument( |
| 74 |
"--bind", |
| 75 |
help="ip to bind to, e.g., 192.168.0.10", |
| 76 |
) |
| 77 |
subparser.add_argument( |
| 78 |
"--target", |
| 79 |
help="target ip, e.g., 239.255.255.250 or FF02::C to listen to", |
| 80 |
) |
| 81 |
subparser.add_argument( |
| 82 |
"--target_port", |
| 83 |
help="port, e.g., 1900 or 1892 to request from", |
| 84 |
default=SSDP_PORT, |
| 85 |
type=int, |
| 86 |
) |
| 87 |
|
| 88 |
args = parser.parse_args() |
| 89 |
pprint_indent = 4 if args.pprint else None |
| 90 |
|
| 91 |
event_handler = None |
| 92 |
|
| 93 |
|
| 94 |
async def create_device(description_url: str) -> UpnpDevice: |
| 95 |
"""Create UpnpDevice.""" |
| 96 |
timeout = args.timeout |
| 97 |
requester = AiohttpRequester(timeout) |
| 98 |
non_strict = not args.strict |
| 99 |
factory = UpnpFactory(requester, non_strict=non_strict) |
| 100 |
return await factory.async_create_device(description_url) |
| 101 |
|
| 102 |
|
| 103 |
def get_timestamp() -> str | float: |
| 104 |
"""Timestamp depending on configuration.""" |
| 105 |
if args.iso8601: |
| 106 |
return datetime.now().isoformat(" ") |
| 107 |
return time.time() |
| 108 |
|
| 109 |
|
| 110 |
def service_from_device(device: UpnpDevice, service_name: str) -> UpnpService | None: |
| 111 |
"""Get UpnpService from UpnpDevice by name or part or abbreviation.""" |
| 112 |
for service in device.all_services: |
| 113 |
part = service.service_id.split(":")[-1] |
| 114 |
abbr = "".join([c for c in part if c.isupper()]) |
| 115 |
if service_name in (service.service_type, part, abbr): |
| 116 |
return service |
| 117 |
|
| 118 |
return None |
| 119 |
|
| 120 |
|
| 121 |
def on_event(service: UpnpService, service_variables: Sequence[UpnpStateVariable]) -> None: |
| 122 |
"""Handle a UPnP event.""" |
| 123 |
_LOGGER.debug( |
| 124 |
"State variable change for %s, variables: %s", |
| 125 |
service, |
| 126 |
",".join([sv.name for sv in service_variables]), |
| 127 |
) |
| 128 |
obj = { |
| 129 |
"timestamp": get_timestamp(), |
| 130 |
"service_id": service.service_id, |
| 131 |
"service_type": service.service_type, |
| 132 |
"state_variables": {sv.name: sv.value for sv in service_variables}, |
| 133 |
} |
| 134 |
|
| 135 |
# special handling for DLNA LastChange state variable |
| 136 |
if len(service_variables) == 1 and service_variables[0].name == "LastChange": |
| 137 |
if not args.nolastchange: |
| 138 |
print(json.dumps(obj, indent=pprint_indent)) |
| 139 |
last_change = service_variables[0] |
| 140 |
dlna_handle_notify_last_change(last_change) |
| 141 |
else: |
| 142 |
print(json.dumps(obj, indent=pprint_indent)) |
| 143 |
|
| 144 |
|
| 145 |
async def call_action(description_url: str, call_action_args: Sequence) -> None: |
| 146 |
"""Call an action and show results.""" |
| 147 |
# pylint: disable=too-many-locals |
| 148 |
device = await create_device(description_url) |
| 149 |
|
| 150 |
if "/" in call_action_args[0]: |
| 151 |
service_name, action_name = call_action_args[0].split("/") |
| 152 |
else: |
| 153 |
service_name = call_action_args[0] |
| 154 |
action_name = "" |
| 155 |
|
| 156 |
for action_arg in call_action_args[1:]: |
| 157 |
if "=" not in action_arg: |
| 158 |
print(f"Invalid argument value: {action_arg}") |
| 159 |
print("Use: Argument=value") |
| 160 |
sys.exit(1) |
| 161 |
|
| 162 |
action_args = {a.split("=", 1)[0]: a.split("=", 1)[1] for a in call_action_args[1:]} |
| 163 |
|
| 164 |
# get service |
| 165 |
service = service_from_device(device, service_name) |
| 166 |
if not service: |
| 167 |
services_str = "\n".join( |
| 168 |
[" " + device_service.service_id.split(":")[-1] for device_service in device.all_services] |
| 169 |
) |
| 170 |
print(f"Unknown service: {service_name}") |
| 171 |
print(f"Available services:\n{services_str}") |
| 172 |
sys.exit(1) |
| 173 |
|
| 174 |
# get action |
| 175 |
if not service.has_action(action_name): |
| 176 |
actions_str = "\n".join([f" {name}" for name in sorted(service.actions)]) |
| 177 |
print(f"Unknown action: {action_name}") |
| 178 |
print(f"Available actions:\n{actions_str}") |
| 179 |
sys.exit(1) |
| 180 |
action = service.action(action_name) |
| 181 |
|
| 182 |
# get in variables |
| 183 |
coerced_args = {} |
| 184 |
for key, value in action_args.items(): |
| 185 |
in_arg = action.argument(key) |
| 186 |
if not in_arg: |
| 187 |
arguments_str = ",".join([a.name for a in action.in_arguments()]) |
| 188 |
print(f"Unknown argument: {key}") |
| 189 |
print(f"Available arguments: {arguments_str}") |
| 190 |
sys.exit(1) |
| 191 |
coerced_args[key] = in_arg.coerce_python(value) |
| 192 |
|
| 193 |
# ensure all in variables given |
| 194 |
for in_arg in action.in_arguments(): |
| 195 |
if in_arg.name not in action_args: |
| 196 |
in_args = "\n".join( |
| 197 |
[f" {in_arg.name}" for in_arg in sorted(action.in_arguments(), key=operator.attrgetter("name"))] |
| 198 |
) |
| 199 |
print("Missing in-arguments") |
| 200 |
print(f"Known in-arguments:\n{in_args}") |
| 201 |
sys.exit(1) |
| 202 |
|
| 203 |
_LOGGER.debug( |
| 204 |
"Calling %s.%s, parameters:\n%s", |
| 205 |
service.service_id, |
| 206 |
action.name, |
| 207 |
"\n".join([f"{key}:{value}" for key, value in coerced_args.items()]), |
| 208 |
) |
| 209 |
result = await action.async_call(**coerced_args) |
| 210 |
|
| 211 |
_LOGGER.debug( |
| 212 |
"Results:\n%s", |
| 213 |
"\n".join([f"{key}:{value}" for key, value in coerced_args.items()]), |
| 214 |
) |
| 215 |
|
| 216 |
obj = { |
| 217 |
"timestamp": get_timestamp(), |
| 218 |
"service_id": service.service_id, |
| 219 |
"service_type": service.service_type, |
| 220 |
"action": action.name, |
| 221 |
"in_parameters": coerced_args, |
| 222 |
"out_parameters": result, |
| 223 |
} |
| 224 |
print(json.dumps(obj, indent=pprint_indent)) |
| 225 |
|
| 226 |
|
| 227 |
async def subscribe(description_url: str, service_names: Any) -> None: |
| 228 |
"""Subscribe to service(s) and output updates.""" |
| 229 |
global event_handler # pylint: disable=global-statement |
| 230 |
|
| 231 |
device = await create_device(description_url) |
| 232 |
|
| 233 |
# start notify server/event handler |
| 234 |
source = (get_local_ip(device.device_url), 0) |
| 235 |
server = AiohttpNotifyServer(device.requester, source=source) |
| 236 |
await server.async_start_server() |
| 237 |
_LOGGER.debug("Listening on: %s", server.callback_url) |
| 238 |
|
| 239 |
# gather all wanted services |
| 240 |
if "*" in service_names: |
| 241 |
service_names = [service.service_type for service in device.all_services] |
| 242 |
|
| 243 |
services = [] |
| 244 |
for service_name in service_names: |
| 245 |
service = service_from_device(device, service_name) |
| 246 |
if not service: |
| 247 |
print(f"Unknown service: {service_name}") |
| 248 |
sys.exit(1) |
| 249 |
service.on_event = on_event |
| 250 |
services.append(service) |
| 251 |
|
| 252 |
# subscribe to services |
| 253 |
event_handler = server.event_handler |
| 254 |
for service in services: |
| 255 |
try: |
| 256 |
await event_handler.async_subscribe(service) |
| 257 |
except UpnpResponseError as ex: |
| 258 |
_LOGGER.error("Unable to subscribe to %s: %s", service, ex) |
| 259 |
|
| 260 |
# keep the webservice running |
| 261 |
while True: |
| 262 |
await asyncio.sleep(120) |
| 263 |
await event_handler.async_resubscribe_all() |
| 264 |
|
| 265 |
|
| 266 |
def source_target( |
| 267 |
source: str | None, |
| 268 |
target: str | None, |
| 269 |
target_port: int, |
| 270 |
) -> tuple[AddressTupleVXType, AddressTupleVXType]: |
| 271 |
"""Determine source/target.""" |
| 272 |
# pylint: disable=too-many-branches, too-many-return-statements |
| 273 |
if source is None and target is None: |
| 274 |
return ( |
| 275 |
"0.0.0.0", |
| 276 |
0, |
| 277 |
), (SSDP_IP_V4, SSDP_PORT) |
| 278 |
|
| 279 |
if source is not None and target is None: |
| 280 |
if ":" not in source: |
| 281 |
# IPv4 |
| 282 |
return (source, 0), (SSDP_IP_V4, SSDP_PORT) |
| 283 |
|
| 284 |
# IPv6 |
| 285 |
if "%" in source: |
| 286 |
idx = source.index("%") |
| 287 |
source_ip, scope_id = source[:idx], int(source[idx + 1 :]) |
| 288 |
else: |
| 289 |
source_ip, scope_id = source, 0 |
| 290 |
|
| 291 |
return (source_ip, 0, 0, scope_id), (SSDP_IP_V6, SSDP_PORT, 0, scope_id) |
| 292 |
|
| 293 |
if source is None and target is not None: |
| 294 |
if ":" not in target: |
| 295 |
# IPv4 |
| 296 |
return ( |
| 297 |
"0.0.0.0", |
| 298 |
0, |
| 299 |
), (target, target_port or SSDP_PORT) |
| 300 |
|
| 301 |
# IPv6 |
| 302 |
if "%" in target: |
| 303 |
idx = target.index("%") |
| 304 |
target_ip, scope_id = target[:idx], int(target[idx + 1 :]) |
| 305 |
else: |
| 306 |
target_ip, scope_id = target, 0 |
| 307 |
|
| 308 |
return ("::", 0, 0, scope_id), ( |
| 309 |
target_ip, |
| 310 |
target_port or SSDP_PORT, |
| 311 |
0, |
| 312 |
scope_id, |
| 313 |
) |
| 314 |
|
| 315 |
source_version = 6 if ":" in (source or "") else 4 |
| 316 |
target_version = 6 if ":" in (target or "") else 4 |
| 317 |
if source is not None and target is not None and source_version != target_version: |
| 318 |
print("Error: Source and target do not match protocol") |
| 319 |
sys.exit(1) |
| 320 |
|
| 321 |
if source is not None and target is not None and ":" in target: |
| 322 |
if "%" in target: |
| 323 |
idx = target.index("%") |
| 324 |
target_ip, scope_id = target[:idx], int(target[idx + 1 :]) |
| 325 |
else: |
| 326 |
target_ip, scope_id = target, 0 |
| 327 |
return (source, 0, 0, scope_id), (target_ip, target_port, 0, scope_id) |
| 328 |
|
| 329 |
return (cast(str, source), 0), (cast(str, target), target_port) |
| 330 |
|
| 331 |
|
| 332 |
async def search(search_args: Any) -> None: |
| 333 |
"""Discover devices.""" |
| 334 |
timeout = args.timeout |
| 335 |
search_target = search_args.search_target |
| 336 |
source, target = source_target(search_args.bind, search_args.target, search_args.target_port) |
| 337 |
|
| 338 |
async def on_response(headers: CaseInsensitiveDict) -> None: |
| 339 |
print( |
| 340 |
json.dumps( |
| 341 |
{key: str(value) for key, value in headers.items()}, |
| 342 |
indent=pprint_indent, |
| 343 |
) |
| 344 |
) |
| 345 |
|
| 346 |
await async_ssdp_search( |
| 347 |
search_target=search_target, |
| 348 |
source=source, |
| 349 |
target=target, |
| 350 |
timeout=timeout, |
| 351 |
async_callback=on_response, |
| 352 |
) |
| 353 |
|
| 354 |
|
| 355 |
async def advertisements(advertisement_args: Any) -> None: |
| 356 |
"""Listen for advertisements.""" |
| 357 |
source, target = source_target( |
| 358 |
advertisement_args.bind, |
| 359 |
advertisement_args.target, |
| 360 |
advertisement_args.target_port, |
| 361 |
) |
| 362 |
|
| 363 |
async def on_notify(headers: CaseInsensitiveDict) -> None: |
| 364 |
print( |
| 365 |
json.dumps( |
| 366 |
{key: str(value) for key, value in headers.items()}, |
| 367 |
indent=pprint_indent, |
| 368 |
) |
| 369 |
) |
| 370 |
|
| 371 |
listener = SsdpAdvertisementListener( |
| 372 |
async_on_alive=on_notify, |
| 373 |
async_on_byebye=on_notify, |
| 374 |
async_on_update=on_notify, |
| 375 |
source=source, |
| 376 |
target=target, |
| 377 |
) |
| 378 |
await listener.async_start() |
| 379 |
try: |
| 380 |
while True: |
| 381 |
await asyncio.sleep(60) |
| 382 |
except KeyboardInterrupt: |
| 383 |
_LOGGER.debug("KeyboardInterrupt") |
| 384 |
await listener.async_stop() |
| 385 |
raise |
| 386 |
|
| 387 |
|
| 388 |
async def async_main() -> None: |
| 389 |
"""Async main.""" |
| 390 |
if args.debug: |
| 391 |
_LOGGER.setLevel(logging.DEBUG) |
| 392 |
_LOGGER_LIB.setLevel(logging.DEBUG) |
| 393 |
_LOGGER_TRAFFIC.setLevel(logging.INFO) |
| 394 |
if args.debug_traffic: |
| 395 |
_LOGGER_TRAFFIC.setLevel(logging.DEBUG) |
| 396 |
|
| 397 |
if args.command == "call-action": |
| 398 |
await call_action(args.device, getattr(args, "call-action")) |
| 399 |
elif args.command == "subscribe": |
| 400 |
await subscribe(args.device, args.service) |
| 401 |
elif args.command == "search": |
| 402 |
await search(args) |
| 403 |
elif args.command == "advertisements": |
| 404 |
await advertisements(args) |
| 405 |
|
| 406 |
|
| 407 |
def main() -> None: |
| 408 |
"""Set up async loop and run the main program.""" |
| 409 |
loop = asyncio.get_event_loop() |
| 410 |
|
| 411 |
try: |
| 412 |
loop.run_until_complete(async_main()) |
| 413 |
except KeyboardInterrupt: |
| 414 |
if event_handler: |
| 415 |
loop.run_until_complete(event_handler.async_unsubscribe_all()) |
| 416 |
finally: |
| 417 |
loop.close() |
| 418 |
|
| 419 |
|
| 420 |
if __name__ == "__main__": |
| 421 |
main() |