python-kasa 0.7.0.5__py3-none-any.whl → 0.7.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. kasa/aestransport.py +4 -3
  2. kasa/cli/__init__.py +1 -0
  3. kasa/cli/__main__.py +6 -0
  4. kasa/cli/common.py +231 -0
  5. kasa/cli/device.py +184 -0
  6. kasa/cli/discover.py +142 -0
  7. kasa/cli/feature.py +134 -0
  8. kasa/cli/lazygroup.py +70 -0
  9. kasa/cli/light.py +200 -0
  10. kasa/cli/main.py +412 -0
  11. kasa/cli/schedule.py +46 -0
  12. kasa/cli/time.py +55 -0
  13. kasa/cli/usage.py +134 -0
  14. kasa/cli/wifi.py +50 -0
  15. kasa/device.py +10 -3
  16. kasa/device_factory.py +5 -2
  17. kasa/discover.py +3 -2
  18. kasa/emeterstatus.py +1 -1
  19. kasa/feature.py +49 -30
  20. kasa/httpclient.py +3 -3
  21. kasa/interfaces/energy.py +6 -6
  22. kasa/iot/iotbulb.py +19 -5
  23. kasa/iot/iotdevice.py +16 -15
  24. kasa/iot/iotdimmer.py +8 -8
  25. kasa/iot/iotmodule.py +9 -8
  26. kasa/iot/iotstrip.py +9 -1
  27. kasa/iot/modules/ambientlight.py +1 -1
  28. kasa/iot/modules/light.py +3 -2
  29. kasa/iot/modules/lighteffect.py +16 -9
  30. kasa/klaptransport.py +29 -20
  31. kasa/module.py +2 -0
  32. kasa/protocol.py +1 -1
  33. kasa/smart/modules/__init__.py +2 -0
  34. kasa/smart/modules/alarm.py +1 -1
  35. kasa/smart/modules/autooff.py +1 -1
  36. kasa/smart/modules/batterysensor.py +1 -1
  37. kasa/smart/modules/brightness.py +1 -2
  38. kasa/smart/modules/cloud.py +0 -7
  39. kasa/smart/modules/color.py +11 -5
  40. kasa/smart/modules/colortemperature.py +8 -11
  41. kasa/smart/modules/energy.py +9 -1
  42. kasa/smart/modules/fan.py +1 -2
  43. kasa/smart/modules/firmware.py +51 -24
  44. kasa/smart/modules/humiditysensor.py +1 -1
  45. kasa/smart/modules/led.py +1 -1
  46. kasa/smart/modules/light.py +3 -1
  47. kasa/smart/modules/lighteffect.py +1 -1
  48. kasa/smart/modules/lightpreset.py +14 -0
  49. kasa/smart/modules/lightstripeffect.py +11 -2
  50. kasa/smart/modules/lighttransition.py +3 -3
  51. kasa/smart/modules/motionsensor.py +36 -0
  52. kasa/smart/modules/reportmode.py +1 -1
  53. kasa/smart/modules/temperaturecontrol.py +1 -2
  54. kasa/smart/modules/temperaturesensor.py +1 -1
  55. kasa/smart/smartchilddevice.py +19 -2
  56. kasa/smart/smartdevice.py +49 -39
  57. kasa/smart/smartmodule.py +54 -1
  58. kasa/smartprotocol.py +11 -87
  59. kasa/tests/conftest.py +1 -1
  60. kasa/tests/device_fixtures.py +2 -2
  61. kasa/tests/discovery_fixtures.py +2 -2
  62. kasa/tests/fakeprotocol_iot.py +25 -9
  63. kasa/tests/fakeprotocol_smart.py +12 -8
  64. kasa/tests/fixtures/KP400(US)_3.0_1.0.3.json +45 -0
  65. kasa/tests/fixtures/KP400(US)_3.0_1.0.4.json +46 -0
  66. kasa/tests/fixtures/KP405(US)_1.0_1.0.6.json +65 -0
  67. kasa/tests/fixtures/KS200M(US)_1.0_1.0.11.json +96 -0
  68. kasa/tests/fixtures/smart/HS220(US)_3.26_1.0.1.json +371 -0
  69. kasa/tests/fixtures/smart/KS205(US)_1.0_1.1.0.json +298 -0
  70. kasa/tests/fixtures/smart/KS225(US)_1.0_1.1.0.json +332 -0
  71. kasa/tests/fixtures/smart/L920-5(EU)_1.0_1.1.3.json +1085 -0
  72. kasa/tests/fixtures/smart/child/T100(EU)_1.0_1.12.0.json +537 -0
  73. kasa/tests/smart/features/test_brightness.py +8 -6
  74. kasa/tests/smart/features/test_colortemp.py +2 -2
  75. kasa/tests/smart/modules/test_autooff.py +1 -1
  76. kasa/tests/smart/modules/test_contact.py +1 -1
  77. kasa/tests/smart/modules/test_fan.py +2 -2
  78. kasa/tests/smart/modules/test_firmware.py +35 -5
  79. kasa/tests/smart/modules/test_humidity.py +1 -1
  80. kasa/tests/smart/modules/test_light_effect.py +1 -1
  81. kasa/tests/smart/modules/test_light_strip_effect.py +13 -16
  82. kasa/tests/smart/modules/test_motionsensor.py +28 -0
  83. kasa/tests/smart/modules/test_temperature.py +1 -1
  84. kasa/tests/smart/modules/test_temperaturecontrol.py +16 -7
  85. kasa/tests/smart/modules/test_waterleak.py +1 -1
  86. kasa/tests/test_aestransport.py +3 -3
  87. kasa/tests/test_bulb.py +97 -22
  88. kasa/tests/test_cli.py +139 -20
  89. kasa/tests/test_common_modules.py +86 -12
  90. kasa/tests/test_device.py +4 -2
  91. kasa/tests/test_dimmer.py +30 -10
  92. kasa/tests/test_discovery.py +4 -4
  93. kasa/tests/test_emeter.py +2 -2
  94. kasa/tests/test_feature.py +6 -6
  95. kasa/tests/test_httpclient.py +2 -2
  96. kasa/tests/test_iotdevice.py +20 -1
  97. kasa/tests/test_klapprotocol.py +72 -6
  98. kasa/tests/test_lightstrip.py +3 -1
  99. kasa/tests/test_protocol.py +84 -29
  100. kasa/tests/test_readme_examples.py +3 -49
  101. kasa/tests/test_smartdevice.py +89 -87
  102. kasa/tests/test_smartprotocol.py +1 -1
  103. kasa/tests/test_usage.py +2 -1
  104. kasa/xortransport.py +2 -2
  105. {python_kasa-0.7.0.5.dist-info → python_kasa-0.7.2.dist-info}/METADATA +4 -3
  106. {python_kasa-0.7.0.5.dist-info → python_kasa-0.7.2.dist-info}/RECORD +109 -86
  107. python_kasa-0.7.2.dist-info/entry_points.txt +3 -0
  108. kasa/cli.py +0 -1316
  109. python_kasa-0.7.0.5.dist-info/entry_points.txt +0 -3
  110. {python_kasa-0.7.0.5.dist-info → python_kasa-0.7.2.dist-info}/LICENSE +0 -0
  111. {python_kasa-0.7.0.5.dist-info → python_kasa-0.7.2.dist-info}/WHEEL +0 -0
kasa/aestransport.py CHANGED
@@ -117,8 +117,10 @@ class AesTransport(BaseTransport):
117
117
  return self.DEFAULT_PORT
118
118
 
119
119
  @property
120
- def credentials_hash(self) -> str:
120
+ def credentials_hash(self) -> str | None:
121
121
  """The hashed credentials used by the transport."""
122
+ if self._credentials == Credentials():
123
+ return None
122
124
  return base64.b64encode(json_dumps(self._login_params).encode()).decode()
123
125
 
124
126
  def _get_login_params(self, credentials: Credentials) -> dict[str, str]:
@@ -276,9 +278,8 @@ class AesTransport(BaseTransport):
276
278
  + "\n-----END PUBLIC KEY-----\n"
277
279
  )
278
280
  handshake_params = {"key": pub_key}
279
- _LOGGER.debug(f"Handshake params: {handshake_params}")
280
281
  request_body = {"method": "handshake", "params": handshake_params}
281
- _LOGGER.debug(f"Request {request_body}")
282
+ _LOGGER.debug("Handshake request: %s", request_body)
282
283
  yield json_dumps(request_body).encode()
283
284
 
284
285
  async def perform_handshake(self) -> None:
kasa/cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Package for the cli."""
kasa/cli/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Main module."""
2
+
3
+ from kasa.cli.main import cli
4
+
5
+ if __name__ == "__main__":
6
+ cli()
kasa/cli/common.py ADDED
@@ -0,0 +1,231 @@
1
+ """Common cli module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import sys
8
+ from contextlib import contextmanager
9
+ from functools import singledispatch, update_wrapper, wraps
10
+ from typing import Final
11
+
12
+ import asyncclick as click
13
+
14
+ from kasa import (
15
+ Device,
16
+ )
17
+
18
+ # Value for optional options if passed without a value
19
+ OPTIONAL_VALUE_FLAG: Final = "_FLAG_"
20
+
21
+ # Block list of commands which require no update
22
+ SKIP_UPDATE_COMMANDS = ["raw-command", "command"]
23
+
24
+ pass_dev = click.make_pass_decorator(Device) # type: ignore[type-abstract]
25
+
26
+
27
+ try:
28
+ from rich import print as _echo
29
+ except ImportError:
30
+ # Strip out rich formatting if rich is not installed
31
+ # but only lower case tags to avoid stripping out
32
+ # raw data from the device that is printed from
33
+ # the device state.
34
+ rich_formatting = re.compile(r"\[/?[a-z]+]")
35
+
36
+ def _strip_rich_formatting(echo_func):
37
+ """Strip rich formatting from messages."""
38
+
39
+ @wraps(echo_func)
40
+ def wrapper(message=None, *args, **kwargs):
41
+ if message is not None:
42
+ message = rich_formatting.sub("", message)
43
+ echo_func(message, *args, **kwargs)
44
+
45
+ return wrapper
46
+
47
+ _echo = _strip_rich_formatting(click.echo)
48
+
49
+
50
+ def echo(*args, **kwargs):
51
+ """Print a message."""
52
+ ctx = click.get_current_context().find_root()
53
+ if "json" not in ctx.params or ctx.params["json"] is False:
54
+ _echo(*args, **kwargs)
55
+
56
+
57
+ def error(msg: str):
58
+ """Print an error and exit."""
59
+ echo(f"[bold red]{msg}[/bold red]")
60
+ sys.exit(1)
61
+
62
+
63
+ def json_formatter_cb(result, **kwargs):
64
+ """Format and output the result as JSON, if requested."""
65
+ if not kwargs.get("json"):
66
+ return
67
+
68
+ @singledispatch
69
+ def to_serializable(val):
70
+ """Regular obj-to-string for json serialization.
71
+
72
+ The singledispatch trick is from hynek: https://hynek.me/articles/serialization/
73
+ """
74
+ return str(val)
75
+
76
+ @to_serializable.register(Device)
77
+ def _device_to_serializable(val: Device):
78
+ """Serialize smart device data, just using the last update raw payload."""
79
+ return val.internal_state
80
+
81
+ json_content = json.dumps(result, indent=4, default=to_serializable)
82
+ print(json_content)
83
+
84
+
85
+ def pass_dev_or_child(wrapped_function):
86
+ """Pass the device or child to the click command based on the child options."""
87
+ child_help = (
88
+ "Child ID or alias for controlling sub-devices. "
89
+ "If no value provided will show an interactive prompt allowing you to "
90
+ "select a child."
91
+ )
92
+ child_index_help = "Child index controlling sub-devices"
93
+
94
+ @contextmanager
95
+ def patched_device_update(parent: Device, child: Device):
96
+ try:
97
+ orig_update = child.update
98
+ # patch child update method. Can be removed once update can be called
99
+ # directly on child devices
100
+ child.update = parent.update # type: ignore[method-assign]
101
+ yield child
102
+ finally:
103
+ child.update = orig_update # type: ignore[method-assign]
104
+
105
+ @click.pass_obj
106
+ @click.pass_context
107
+ @click.option(
108
+ "--child",
109
+ "--name",
110
+ is_flag=False,
111
+ flag_value=OPTIONAL_VALUE_FLAG,
112
+ default=None,
113
+ required=False,
114
+ type=click.STRING,
115
+ help=child_help,
116
+ )
117
+ @click.option(
118
+ "--child-index",
119
+ "--index",
120
+ required=False,
121
+ default=None,
122
+ type=click.INT,
123
+ help=child_index_help,
124
+ )
125
+ async def wrapper(ctx: click.Context, dev, *args, child, child_index, **kwargs):
126
+ if child := await _get_child_device(dev, child, child_index, ctx.info_name):
127
+ ctx.obj = ctx.with_resource(patched_device_update(dev, child))
128
+ dev = child
129
+ return await ctx.invoke(wrapped_function, dev, *args, **kwargs)
130
+
131
+ # Update wrapper function to look like wrapped function
132
+ return update_wrapper(wrapper, wrapped_function)
133
+
134
+
135
+ async def _get_child_device(
136
+ device: Device, child_option, child_index_option, info_command
137
+ ) -> Device | None:
138
+ def _list_children():
139
+ return "\n".join(
140
+ [
141
+ f"{idx}: {child.device_id} ({child.alias})"
142
+ for idx, child in enumerate(device.children)
143
+ ]
144
+ )
145
+
146
+ if child_option is None and child_index_option is None:
147
+ return None
148
+
149
+ if info_command in SKIP_UPDATE_COMMANDS:
150
+ # The device hasn't had update called (e.g. for cmd_command)
151
+ # The way child devices are accessed requires a ChildDevice to
152
+ # wrap the communications. Doing this properly would require creating
153
+ # a common interfaces for both IOT and SMART child devices.
154
+ # As a stop-gap solution, we perform an update instead.
155
+ await device.update()
156
+
157
+ if not device.children:
158
+ error(f"Device: {device.host} does not have children")
159
+
160
+ if child_option is not None and child_index_option is not None:
161
+ raise click.BadOptionUsage(
162
+ "child", "Use either --child or --child-index, not both."
163
+ )
164
+
165
+ if child_option is not None:
166
+ if child_option is OPTIONAL_VALUE_FLAG:
167
+ msg = _list_children()
168
+ child_index_option = click.prompt(
169
+ f"\n{msg}\nEnter the index number of the child device",
170
+ type=click.IntRange(0, len(device.children) - 1),
171
+ )
172
+ elif child := device.get_child_device(child_option):
173
+ echo(f"Targeting child device {child.alias}")
174
+ return child
175
+ else:
176
+ error(
177
+ "No child device found with device_id or name: "
178
+ f"{child_option} children are:\n{_list_children()}"
179
+ )
180
+
181
+ if child_index_option + 1 > len(device.children) or child_index_option < 0:
182
+ error(
183
+ f"Invalid index {child_index_option}, "
184
+ f"device has {len(device.children)} children"
185
+ )
186
+ child_by_index = device.children[child_index_option]
187
+ echo(f"Targeting child device {child_by_index.alias}")
188
+ return child_by_index
189
+
190
+
191
+ def CatchAllExceptions(cls):
192
+ """Capture all exceptions and prints them nicely.
193
+
194
+ Idea from https://stackoverflow.com/a/44347763 and
195
+ https://stackoverflow.com/questions/52213375
196
+ """
197
+
198
+ def _handle_exception(debug, exc):
199
+ if isinstance(exc, click.ClickException):
200
+ raise
201
+ # Handle exit request from click.
202
+ if isinstance(exc, click.exceptions.Exit):
203
+ sys.exit(exc.exit_code)
204
+
205
+ echo(f"Raised error: {exc}")
206
+ if debug:
207
+ raise
208
+ echo("Run with --debug enabled to see stacktrace")
209
+ sys.exit(1)
210
+
211
+ class _CommandCls(cls):
212
+ _debug = False
213
+
214
+ async def make_context(self, info_name, args, parent=None, **extra):
215
+ self._debug = any(
216
+ [arg for arg in args if arg in ["--debug", "-d", "--verbose", "-v"]]
217
+ )
218
+ try:
219
+ return await super().make_context(
220
+ info_name, args, parent=parent, **extra
221
+ )
222
+ except Exception as exc:
223
+ _handle_exception(self._debug, exc)
224
+
225
+ async def invoke(self, ctx):
226
+ try:
227
+ return await super().invoke(ctx)
228
+ except Exception as exc:
229
+ _handle_exception(self._debug, exc)
230
+
231
+ return _CommandCls
kasa/cli/device.py ADDED
@@ -0,0 +1,184 @@
1
+ """Module for cli device commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pprint import pformat as pf
6
+
7
+ import asyncclick as click
8
+
9
+ from kasa import (
10
+ Device,
11
+ Module,
12
+ )
13
+ from kasa.smart import SmartDevice
14
+
15
+ from .common import (
16
+ echo,
17
+ error,
18
+ pass_dev,
19
+ pass_dev_or_child,
20
+ )
21
+
22
+
23
+ @click.group()
24
+ @pass_dev_or_child
25
+ def device(dev):
26
+ """Commands to control basic device settings."""
27
+
28
+
29
+ @device.command()
30
+ @pass_dev_or_child
31
+ @click.pass_context
32
+ async def state(ctx, dev: Device):
33
+ """Print out device state and versions."""
34
+ from .feature import _echo_all_features
35
+
36
+ verbose = ctx.parent.params.get("verbose", False) if ctx.parent else False
37
+
38
+ echo(f"[bold]== {dev.alias} - {dev.model} ==[/bold]")
39
+ echo(f"Host: {dev.host}")
40
+ echo(f"Port: {dev.port}")
41
+ echo(f"Device state: {dev.is_on}")
42
+
43
+ echo(f"Time: {dev.time} (tz: {dev.timezone}")
44
+ echo(f"Hardware: {dev.hw_info['hw_ver']}")
45
+ echo(f"Software: {dev.hw_info['sw_ver']}")
46
+ echo(f"MAC (rssi): {dev.mac} ({dev.rssi})")
47
+ if verbose:
48
+ echo(f"Location: {dev.location}")
49
+
50
+ echo()
51
+ _echo_all_features(dev.features, verbose=verbose)
52
+
53
+ if verbose:
54
+ echo("\n[bold]== Modules ==[/bold]")
55
+ for module in dev.modules.values():
56
+ echo(f"[green]+ {module}[/green]")
57
+
58
+ if dev.children:
59
+ echo("\n[bold]== Children ==[/bold]")
60
+ for child in dev.children:
61
+ _echo_all_features(
62
+ child.features,
63
+ title_prefix=f"{child.alias} ({child.model})",
64
+ verbose=verbose,
65
+ indent="\t",
66
+ )
67
+ if verbose:
68
+ echo(f"\n\t[bold]== Child {child.alias} Modules ==[/bold]")
69
+ for module in child.modules.values():
70
+ echo(f"\t[green]+ {module}[/green]")
71
+ echo()
72
+
73
+ if verbose:
74
+ echo("\n\t[bold]== Protocol information ==[/bold]")
75
+ echo(f"\tCredentials hash: {dev.credentials_hash}")
76
+ echo()
77
+ from .discover import _echo_discovery_info
78
+
79
+ _echo_discovery_info(dev._discovery_info)
80
+
81
+ return dev.internal_state
82
+
83
+
84
+ @device.command()
85
+ @pass_dev_or_child
86
+ async def sysinfo(dev):
87
+ """Print out full system information."""
88
+ echo("== System info ==")
89
+ echo(pf(dev.sys_info))
90
+ return dev.sys_info
91
+
92
+
93
+ @device.command()
94
+ @click.option("--transition", type=int, required=False)
95
+ @pass_dev_or_child
96
+ async def on(dev: Device, transition: int):
97
+ """Turn the device on."""
98
+ echo(f"Turning on {dev.alias}")
99
+ return await dev.turn_on(transition=transition)
100
+
101
+
102
+ @click.command
103
+ @click.option("--transition", type=int, required=False)
104
+ @pass_dev_or_child
105
+ async def off(dev: Device, transition: int):
106
+ """Turn the device off."""
107
+ echo(f"Turning off {dev.alias}")
108
+ return await dev.turn_off(transition=transition)
109
+
110
+
111
+ @device.command()
112
+ @click.option("--transition", type=int, required=False)
113
+ @pass_dev_or_child
114
+ async def toggle(dev: Device, transition: int):
115
+ """Toggle the device on/off."""
116
+ if dev.is_on:
117
+ echo(f"Turning off {dev.alias}")
118
+ return await dev.turn_off(transition=transition)
119
+
120
+ echo(f"Turning on {dev.alias}")
121
+ return await dev.turn_on(transition=transition)
122
+
123
+
124
+ @device.command()
125
+ @click.argument("state", type=bool, required=False)
126
+ @pass_dev_or_child
127
+ async def led(dev: Device, state):
128
+ """Get or set (Plug's) led state."""
129
+ if not (led := dev.modules.get(Module.Led)):
130
+ error("Device does not support led.")
131
+ return
132
+ if state is not None:
133
+ echo(f"Turning led to {state}")
134
+ return await led.set_led(state)
135
+ else:
136
+ echo(f"LED state: {led.led}")
137
+ return led.led
138
+
139
+
140
+ @device.command()
141
+ @click.argument("new_alias", required=False, default=None)
142
+ @pass_dev_or_child
143
+ async def alias(dev, new_alias):
144
+ """Get or set the device (or plug) alias."""
145
+ if new_alias is not None:
146
+ echo(f"Setting alias to {new_alias}")
147
+ res = await dev.set_alias(new_alias)
148
+ await dev.update()
149
+ echo(f"Alias set to: {dev.alias}")
150
+ return res
151
+
152
+ echo(f"Alias: {dev.alias}")
153
+ if dev.children:
154
+ for plug in dev.children:
155
+ echo(f" * {plug.alias}")
156
+
157
+ return dev.alias
158
+
159
+
160
+ @device.command()
161
+ @click.option("--delay", default=1)
162
+ @pass_dev
163
+ async def reboot(plug, delay):
164
+ """Reboot the device."""
165
+ echo("Rebooting the device..")
166
+ return await plug.reboot(delay)
167
+
168
+
169
+ @device.command()
170
+ @pass_dev
171
+ @click.option(
172
+ "--username", required=True, prompt=True, help="New username to set on the device"
173
+ )
174
+ @click.option(
175
+ "--password", required=True, prompt=True, help="New password to set on the device"
176
+ )
177
+ async def update_credentials(dev, username, password):
178
+ """Update device credentials for authenticated devices."""
179
+ if not isinstance(dev, SmartDevice):
180
+ error("Credentials can only be updated on authenticated devices.")
181
+
182
+ click.confirm("Do you really want to replace the existing credentials?", abort=True)
183
+
184
+ return await dev.update_credentials(username, password)
kasa/cli/discover.py ADDED
@@ -0,0 +1,142 @@
1
+ """Module for cli discovery commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+ import asyncclick as click
8
+ from pydantic.v1 import ValidationError
9
+
10
+ from kasa import (
11
+ AuthenticationError,
12
+ Credentials,
13
+ Device,
14
+ Discover,
15
+ UnsupportedDeviceError,
16
+ )
17
+ from kasa.discover import DiscoveryResult
18
+
19
+ from .common import echo
20
+
21
+
22
+ @click.command()
23
+ @click.pass_context
24
+ async def discover(ctx):
25
+ """Discover devices in the network."""
26
+ target = ctx.parent.params["target"]
27
+ username = ctx.parent.params["username"]
28
+ password = ctx.parent.params["password"]
29
+ discovery_timeout = ctx.parent.params["discovery_timeout"]
30
+ timeout = ctx.parent.params["timeout"]
31
+ port = ctx.parent.params["port"]
32
+
33
+ credentials = Credentials(username, password) if username and password else None
34
+
35
+ sem = asyncio.Semaphore()
36
+ discovered = dict()
37
+ unsupported = []
38
+ auth_failed = []
39
+
40
+ async def print_unsupported(unsupported_exception: UnsupportedDeviceError):
41
+ unsupported.append(unsupported_exception)
42
+ async with sem:
43
+ if unsupported_exception.discovery_result:
44
+ echo("== Unsupported device ==")
45
+ _echo_discovery_info(unsupported_exception.discovery_result)
46
+ echo()
47
+ else:
48
+ echo("== Unsupported device ==")
49
+ echo(f"\t{unsupported_exception}")
50
+ echo()
51
+
52
+ echo(f"Discovering devices on {target} for {discovery_timeout} seconds")
53
+
54
+ from .device import state
55
+
56
+ async def print_discovered(dev: Device):
57
+ async with sem:
58
+ try:
59
+ await dev.update()
60
+ except AuthenticationError:
61
+ auth_failed.append(dev._discovery_info)
62
+ echo("== Authentication failed for device ==")
63
+ _echo_discovery_info(dev._discovery_info)
64
+ echo()
65
+ else:
66
+ ctx.parent.obj = dev
67
+ await ctx.parent.invoke(state)
68
+ discovered[dev.host] = dev.internal_state
69
+ echo()
70
+
71
+ discovered_devices = await Discover.discover(
72
+ target=target,
73
+ discovery_timeout=discovery_timeout,
74
+ on_discovered=print_discovered,
75
+ on_unsupported=print_unsupported,
76
+ port=port,
77
+ timeout=timeout,
78
+ credentials=credentials,
79
+ )
80
+
81
+ for device in discovered_devices.values():
82
+ await device.protocol.close()
83
+
84
+ echo(f"Found {len(discovered)} devices")
85
+ if unsupported:
86
+ echo(f"Found {len(unsupported)} unsupported devices")
87
+ if auth_failed:
88
+ echo(f"Found {len(auth_failed)} devices that failed to authenticate")
89
+
90
+ return discovered
91
+
92
+
93
+ def _echo_dictionary(discovery_info: dict):
94
+ echo("\t[bold]== Discovery information ==[/bold]")
95
+ for key, value in discovery_info.items():
96
+ key_name = " ".join(x.capitalize() or "_" for x in key.split("_"))
97
+ key_name_and_spaces = "{:<15}".format(key_name + ":")
98
+ echo(f"\t{key_name_and_spaces}{value}")
99
+
100
+
101
+ def _echo_discovery_info(discovery_info):
102
+ # We don't have discovery info when all connection params are passed manually
103
+ if discovery_info is None:
104
+ return
105
+
106
+ if "system" in discovery_info and "get_sysinfo" in discovery_info["system"]:
107
+ _echo_dictionary(discovery_info["system"]["get_sysinfo"])
108
+ return
109
+
110
+ try:
111
+ dr = DiscoveryResult(**discovery_info)
112
+ except ValidationError:
113
+ _echo_dictionary(discovery_info)
114
+ return
115
+
116
+ echo("\t[bold]== Discovery Result ==[/bold]")
117
+ echo(f"\tDevice Type: {dr.device_type}")
118
+ echo(f"\tDevice Model: {dr.device_model}")
119
+ echo(f"\tIP: {dr.ip}")
120
+ echo(f"\tMAC: {dr.mac}")
121
+ echo(f"\tDevice Id (hash): {dr.device_id}")
122
+ echo(f"\tOwner (hash): {dr.owner}")
123
+ echo(f"\tHW Ver: {dr.hw_ver}")
124
+ echo(f"\tSupports IOT Cloud: {dr.is_support_iot_cloud}")
125
+ echo(f"\tOBD Src: {dr.obd_src}")
126
+ echo(f"\tFactory Default: {dr.factory_default}")
127
+ echo(f"\tEncrypt Type: {dr.mgt_encrypt_schm.encrypt_type}")
128
+ echo(f"\tSupports HTTPS: {dr.mgt_encrypt_schm.is_support_https}")
129
+ echo(f"\tHTTP Port: {dr.mgt_encrypt_schm.http_port}")
130
+ echo(f"\tLV (Login Level): {dr.mgt_encrypt_schm.lv}")
131
+
132
+
133
+ async def find_host_from_alias(alias, target="255.255.255.255", timeout=1, attempts=3):
134
+ """Discover a device identified by its alias."""
135
+ for _attempt in range(1, attempts):
136
+ found_devs = await Discover.discover(target=target, timeout=timeout)
137
+ for _ip, dev in found_devs.items():
138
+ if dev.alias.lower() == alias.lower():
139
+ host = dev.host
140
+ return host
141
+
142
+ return None