py-uconnect 1.0.0__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.
@@ -0,0 +1,41 @@
1
+ """Async Python client for the FCA/Stellantis Uconnect cloud API"""
2
+
3
+ from .api import API
4
+ from .brands import BRANDS, Brand
5
+ from .client import Client
6
+ from .command import COMMANDS, COMMANDS_BY_NAME, Command, TemperatureUnit, hvac_params
7
+ from .exceptions import (
8
+ APIError,
9
+ AuthenticationError,
10
+ CommandError,
11
+ CommandTimeoutError,
12
+ PinAuthenticationError,
13
+ UconnectConnectionError,
14
+ UconnectError,
15
+ )
16
+ from .models import ChargingLevel, Location, TheftAlarmSuppression, Vehicle
17
+
18
+ __version__ = "1.0.0"
19
+
20
+ __all__ = [
21
+ "API",
22
+ "BRANDS",
23
+ "COMMANDS",
24
+ "COMMANDS_BY_NAME",
25
+ "APIError",
26
+ "AuthenticationError",
27
+ "Brand",
28
+ "ChargingLevel",
29
+ "Client",
30
+ "Command",
31
+ "CommandError",
32
+ "CommandTimeoutError",
33
+ "Location",
34
+ "PinAuthenticationError",
35
+ "TemperatureUnit",
36
+ "TheftAlarmSuppression",
37
+ "UconnectConnectionError",
38
+ "UconnectError",
39
+ "Vehicle",
40
+ "hvac_params",
41
+ ]
@@ -0,0 +1,135 @@
1
+ """Command line interface, run ``python -m py_uconnect --help``"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import inspect
8
+ import json
9
+ import logging
10
+ import os
11
+ import sys
12
+ from typing import Any
13
+
14
+ from . import __version__
15
+ from .api import API
16
+ from .brands import BRANDS
17
+ from .client import Client
18
+ from .command import COMMANDS_BY_NAME
19
+ from .exceptions import UconnectError
20
+
21
+
22
+ def _required_params(fn: Any) -> list[str]:
23
+ return [
24
+ name
25
+ for name, p in inspect.signature(fn).parameters.items()
26
+ if p.default is inspect.Parameter.empty
27
+ ]
28
+
29
+
30
+ # Read-only API methods that only need a VIN
31
+ GETTERS = sorted(
32
+ name
33
+ for name, fn in inspect.getmembers(API, inspect.iscoroutinefunction)
34
+ if name.startswith("get_") and _required_params(fn) == ["self", "vin"]
35
+ )
36
+
37
+
38
+ def _parser() -> argparse.ArgumentParser:
39
+ p = argparse.ArgumentParser(
40
+ prog="uconnect",
41
+ description="Query and control FCA/Stellantis vehicles via the Uconnect "
42
+ "cloud. Credentials can also be passed as UCONNECT_EMAIL, "
43
+ "UCONNECT_PASSWORD, UCONNECT_PIN and UCONNECT_BRAND environment variables.",
44
+ )
45
+ p.add_argument("--version", action="version", version=__version__)
46
+ p.add_argument(
47
+ "-b",
48
+ "--brand",
49
+ default=os.environ.get("UCONNECT_BRAND"),
50
+ choices=sorted(BRANDS),
51
+ metavar="BRAND",
52
+ help=f"one of: {', '.join(sorted(BRANDS))}",
53
+ )
54
+ p.add_argument("-u", "--email", default=os.environ.get("UCONNECT_EMAIL"))
55
+ p.add_argument("-p", "--password", default=os.environ.get("UCONNECT_PASSWORD"))
56
+ p.add_argument("--pin", default=os.environ.get("UCONNECT_PIN"))
57
+ p.add_argument("-v", "--verbose", action="store_true", help="debug logging")
58
+
59
+ sub = p.add_subparsers(dest="action", required=True)
60
+
61
+ s = sub.add_parser("vehicles", help="show the vehicles and their state")
62
+ s.add_argument("--raw", action="store_true", help="include raw API responses")
63
+
64
+ s = sub.add_parser("get", help="call a read-only endpoint for a vehicle")
65
+ s.add_argument("endpoint", choices=GETTERS)
66
+ s.add_argument("vin")
67
+
68
+ s = sub.add_parser("command", help="send a remote command (needs the PIN)")
69
+ s.add_argument("vin")
70
+ s.add_argument("command", choices=sorted(COMMANDS_BY_NAME))
71
+ s.add_argument("--no-wait", action="store_true", help="do not wait for the result")
72
+
73
+ s = sub.add_parser("raw", help="send a request to an arbitrary API path")
74
+ s.add_argument("method", type=str.upper)
75
+ s.add_argument("path", help="e.g. /v1/accounts/{uid}/vehicles/VIN/vhr/")
76
+ s.add_argument("--body", type=json.loads, help="JSON request body")
77
+ s.add_argument(
78
+ "--param", action="append", default=[], help="query parameter KEY=VALUE"
79
+ )
80
+
81
+ return p
82
+
83
+
84
+ def _print(v: Any) -> None:
85
+ print(json.dumps(v, indent=2, ensure_ascii=False))
86
+
87
+
88
+ async def _run(args: argparse.Namespace) -> int:
89
+ async with Client(
90
+ args.email, args.password, args.pin, BRANDS[args.brand]
91
+ ) as client:
92
+ if args.action == "vehicles":
93
+ vehicles = await client.refresh()
94
+ _print([v.to_dict(raw=args.raw) for v in vehicles.values()])
95
+ elif args.action == "get":
96
+ _print(await getattr(client.api, args.endpoint)(args.vin))
97
+ elif args.action == "command":
98
+ cmd = COMMANDS_BY_NAME[args.command]
99
+ if args.no_wait:
100
+ print(await client.command(args.vin, cmd))
101
+ else:
102
+ ok = await client.command_verify(args.vin, cmd)
103
+ print("success" if ok else "failed")
104
+ return 0 if ok else 1
105
+ elif args.action == "raw":
106
+ params = dict(x.split("=", 1) for x in args.param)
107
+ _print(
108
+ await client.api.request(
109
+ args.method, args.path, params=params, body=args.body
110
+ )
111
+ )
112
+
113
+ return 0
114
+
115
+
116
+ def main() -> None:
117
+ """Entry point of the ``uconnect`` command"""
118
+
119
+ args = _parser().parse_args()
120
+
121
+ missing = [x for x in ("brand", "email", "password") if not getattr(args, x)]
122
+ if missing:
123
+ _parser().error(f"missing {', '.join(missing)}")
124
+
125
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING)
126
+
127
+ try:
128
+ sys.exit(asyncio.run(_run(args)))
129
+ except UconnectError as err:
130
+ print(f"error: {err}", file=sys.stderr)
131
+ sys.exit(1)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
py_uconnect/_http.py ADDED
@@ -0,0 +1,41 @@
1
+ """HTTP helpers shared by the authentication flow and the API client"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import uuid
7
+ from typing import Any
8
+
9
+ from .brands import Brand
10
+
11
+ # The API keys used by the library belong to the web portal, so requests look
12
+ # like they come from a desktop browser.
13
+ USER_AGENT = (
14
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
15
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
16
+ "Chrome/126.0.0.0 Safari/537.36"
17
+ )
18
+
19
+
20
+ def api_headers(brand: Brand, api_key: str) -> dict[str, str]:
21
+ """Headers expected by the Uconnect API gateways"""
22
+
23
+ return {
24
+ "User-Agent": USER_AGENT,
25
+ "Content-Type": "application/json",
26
+ "x-clientapp-name": "CWP",
27
+ "x-clientapp-version": "1.0",
28
+ "x-originator-type": "web",
29
+ "clientrequestid": uuid.uuid4().hex.upper()[:16],
30
+ "x-api-key": api_key,
31
+ "locale": brand.locale,
32
+ }
33
+
34
+
35
+ def parse_json(text: str) -> Any:
36
+ """Decodes a JSON response body, returns None if it is not valid JSON"""
37
+
38
+ try:
39
+ return json.loads(text)
40
+ except ValueError:
41
+ return None