Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ celerybeat-schedule
# dotenv
.env

*.pgen/
# virtualenv
venv/
ENV/
Expand Down
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,44 @@ Presets are classmethods on `SaicApiConfiguration`. Each takes `(username, passw
| `mg_eu()` | `https://gateway-mg-eu.soimt.com/api.app/v1/` | `eu` | `459771` | `com.saicmotor.europecar` |
| `mg_au()` | `https://gateway-mg-au.soimt.com/api.app/v1/` | `au` | `459771` | `com.saicmotor.europecar` |
| `mg_tr()` | `https://gateway-mg-tr.soimt.com/api.app/v1/` | `tr` | `459771` | `com.saicmotor.europecar` |
| `mg_th()` | `https://gateway-mg-th.soimt.com/api.app/v1/` | `th` | `459771` | `com.saicmotor.ismartthai` |
| `mg_br()` | `https://gateway-mg-br.soimt.com/api.app/v1/` | `br` | `459771` | `com.saicmotor.europecar` |
| `maxus_eu()` | `https://gateway-maxus-eu.soimt.com/api.app/v1/` | `eu` | `590224` | `com.saicmaxus.ismarteu` |

MAXUS Europe vehicles use the same API. The `maxus_eu()` values were confirmed by a live traffic capture of the MAXUS app.

For Thailand, supply `login_authorization` as the complete `Authorization` header
(`Basic ...`) from the app's login request. Keep it secret; do not commit it or the
traffic capture. For phone login, also set `username_is_email=False` and
`phone_country_code="66"`. For example:

```python
import os

from saic_ismart_client_ng.model import SaicApiConfiguration

config = SaicApiConfiguration.mg_th(
os.environ["SAIC_USERNAME"],
os.environ["SAIC_PASSWORD"],
username_is_email=False,
phone_country_code="66",
login_authorization=os.environ["SAIC_LOGIN_AUTHORIZATION"],
)
```

For the Thailand example, copy `examples/.env.example` to `examples/.env` and
set the complete authorization header there:

```dotenv
SAIC_LOGIN_AUTHORIZATION="Basic ..."
```

Existing environment variables take precedence over `.env`. The example's
username and password are configured separately in `examples/main.py`.
The example requests both vehicle status and charging management data for each
vehicle. If SAIC reports that vehicle access has been revoked, restore the
account's authorization to that vehicle in the app before retrying.

Supported functionality (partial list, check the code for more)

* login
Expand Down
9 changes: 8 additions & 1 deletion examples/.env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
SAIC_USER=
SAIC_PASS=
# SAIC_REGION=eu
# Full Basic authorization header for Thailand
SAIC_LOGIN_AUTHORIZATION=
# Optional overrides for examples/main.py (defaults are for Thailand)
# SAIC_USERNAME_IS_EMAIL=false
# SAIC_BASE_URI=https://gateway-mg-th.soimt.com/api.app/v1/
# SAIC_REGION=th
# SAIC_PHONE_COUNTRY_CODE=66
# SAIC_DEVICE_APP_ID=com.saicmotor.ismartthai
# SAIC_VIN=
# Only for examples/maxus_login.py (MAXUS Europe account)
# MAXUS_USER=
Expand Down
18 changes: 18 additions & 0 deletions examples/example_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from __future__ import annotations

import os
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from pathlib import Path


def load_env(path: Path) -> None:
if not path.exists():
raise SystemExit(f"Missing {path}; copy .env.example to .env and fill it in")
for line in path.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
os.environ.setdefault(key.strip(), value.strip().strip("\"'"))
46 changes: 40 additions & 6 deletions examples/main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,35 @@
from __future__ import annotations

import asyncio
from dataclasses import asdict
import logging
import os
from pathlib import Path
import sys

from saic_ismart_client_ng import SaicApi
from saic_ismart_client_ng.model import SaicApiConfiguration

if __package__:
from .example_env import load_env
else:
from example_env import load_env


async def main() -> None:
load_env(Path(__file__).parent / ".env")
config = SaicApiConfiguration(
username="XXXXX@xxxx.com",
password="XXXXX",
username=os.environ.get("SAIC_USER"),
username_is_email=os.environ.get("SAIC_USERNAME_IS_EMAIL", "false").lower()
in ("1", "true", "yes"),
password=os.environ.get("SAIC_PASS"),
base_uri=os.environ.get(
"SAIC_BASE_URI", "https://gateway-mg-th.soimt.com/api.app/v1/"
),
region=os.environ.get("SAIC_REGION", "th"),
phone_country_code=os.environ.get("SAIC_PHONE_COUNTRY_CODE", "66"),
device_app_id=os.environ.get("SAIC_DEVICE_APP_ID", "com.saicmotor.ismartthai"),
login_authorization=os.environ.get("SAIC_LOGIN_AUTHORIZATION"),
)
saic_api = SaicApi(config)
await saic_api.login()
Expand All @@ -21,11 +39,27 @@ async def main() -> None:
cars = vehicle_list_rest.vinList
for car in cars:
vin_num = car.vin
# vehicle_status = await saic_api.get_vehicle_status(vin_num)
# logging.info("Battery voltage is %d", vehicle_status.basicVehicleStatus.batteryVoltage)
# charging_status = await saic_api.get_vehicle_charging_management_data(vin_num)
# logging.info("Current power is %d", charging_status.rvsChargeStatus.realtimePower)
if not vin_num:
logging.warning("Vehicle list entry has no VIN; skipping status requests")
continue
logging.info("My VIN is %s", vin_num)
vehicle_status = await saic_api.get_vehicle_status(vin_num)
if vehicle_status.basicVehicleStatus is None:
logging.info("No basicVehicleStatus")
else:
for name, value in asdict(vehicle_status.basicVehicleStatus).items():
logging.info("basicVehicleStatus.%s = %s", name, value)
charging_status = await saic_api.get_vehicle_charging_management_data(vin_num)

chrg_mgmt_data = charging_status.chrgMgmtData
if chrg_mgmt_data is None:
logging.info("No chrgMgmtData")
continue
for name, value in asdict(chrg_mgmt_data).items():
logging.info("chrgMgmtData.%s = %s", name, value)
logging.info("decoded_current = %s A", chrg_mgmt_data.decoded_current)
logging.info("decoded_voltage = %s V", chrg_mgmt_data.decoded_voltage)
logging.info("decoded_power = %s kW", chrg_mgmt_data.decoded_power)
await asyncio.sleep(10)


Expand Down
14 changes: 4 additions & 10 deletions examples/maxus_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,10 @@
from saic_ismart_client_ng import SaicApi
from saic_ismart_client_ng.model import SaicApiConfiguration


def load_env(path: Path) -> None:
if not path.exists():
raise SystemExit(f"Missing {path}; copy .env.example to .env and fill it in")
for line in path.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
os.environ.setdefault(key.strip(), value.strip().strip("\"'"))
if __package__:
from .example_env import load_env
else:
from example_env import load_env


async def main() -> None:
Expand Down
36 changes: 33 additions & 3 deletions src/saic_ismart_client_ng/api/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import base64
import binascii
from dataclasses import asdict
import datetime
import logging
Expand Down Expand Up @@ -55,10 +57,32 @@ async def close(self) -> None:
await self.__api_client.close()

async def login(self) -> LoginResp:
is_thai = self.__configuration.region.lower() == "th"
authorization = "Basic c3dvcmQ6c3dvcmRfc2VjcmV0"
if is_thai:
thai_authorization = self.__configuration.login_authorization
if not thai_authorization:
raise SaicApiException(
"Thai login requires login_authorization with the app's Basic authorization header."
)
scheme, separator, credentials = thai_authorization.partition(" ")
try:
decoded_credentials = base64.b64decode(credentials, validate=True)
except (binascii.Error, ValueError):
decoded_credentials = b""
if (
scheme.lower() != "basic"
or not separator
or b":" not in decoded_credentials
):
raise SaicApiException(
"login_authorization must be a valid Basic authorization header."
)
authorization = thai_authorization
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"Authorization": "Basic c3dvcmQ6c3dvcmRfc2VjcmV0",
"Authorization": authorization,
}
firebase_device_id = (
"simulator*********************************************"
Expand All @@ -67,11 +91,17 @@ async def login(self) -> LoginResp:
form_body = {
"grant_type": "password",
"username": self.__configuration.username,
"password": sha1_hex_digest(self.__configuration.password),
"password": (
base64.b64encode(self.__configuration.password.encode("utf-8")).decode(
"ascii"
)
if is_thai
else sha1_hex_digest(self.__configuration.password)
),
"scope": "all",
"deviceId": f"{firebase_device_id}###{self.__configuration.device_app_id}",
"deviceType": "0", # 2 for huawei
"language": "EN",
"language": "TH" if is_thai else "EN",
}

if self.__configuration.username_is_email:
Expand Down
17 changes: 17 additions & 0 deletions src/saic_ismart_client_ng/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
MG_EU_BASE_URI = "https://gateway-mg-eu.soimt.com/api.app/v1/"
MG_AU_BASE_URI = "https://gateway-mg-au.soimt.com/api.app/v1/"
MG_TR_BASE_URI = "https://gateway-mg-tr.soimt.com/api.app/v1/"
MG_TH_BASE_URI = "https://gateway-mg-th.soimt.com/api.app/v1/"
MG_BR_BASE_URI = "https://gateway-mg-br.soimt.com/api.app/v1/"
MAXUS_EU_BASE_URI = "https://gateway-maxus-eu.soimt.com/api.app/v1/"
MAXUS_EU_TENANT_ID = "590224"
MAXUS_EU_DEVICE_APP_ID = "com.saicmaxus.ismarteu"
MAXUS_TH_DEVICE_APP_ID = "com.saicmotor.ismartthai"


class SaicApiConfiguration:
Expand All @@ -25,6 +27,8 @@ def __init__(
sms_delivery_delay: float = 3.0,
read_timeout: float = 5.0,
device_app_id: str = "com.saicmotor.europecar",
*,
login_authorization: str | None = None,
) -> None:
self.__username = username
self.__password = password
Expand All @@ -36,6 +40,7 @@ def __init__(
self.__sms_delivery_delay = sms_delivery_delay
self.__read_timeout = read_timeout
self.__device_app_id = device_app_id
self.__login_authorization = login_authorization

@classmethod
def mg_eu(cls, username: str, password: str, **kwargs: Any) -> SaicApiConfiguration:
Expand All @@ -58,6 +63,14 @@ def mg_tr(cls, username: str, password: str, **kwargs: Any) -> SaicApiConfigurat
kwargs.setdefault("region", "tr")
return cls(username, password, **kwargs)

@classmethod
def mg_th(cls, username: str, password: str, **kwargs: Any) -> SaicApiConfiguration:
"""Build the configuration for MG iSMART in Thailand."""
kwargs.setdefault("base_uri", MG_TH_BASE_URI)
kwargs.setdefault("region", "th")
kwargs.setdefault("device_app_id", MAXUS_TH_DEVICE_APP_ID)
return cls(username, password, **kwargs)

@classmethod
def mg_br(cls, username: str, password: str, **kwargs: Any) -> SaicApiConfiguration:
"""Build the configuration for MG iSMART in Brazil (the "MG i-SMART LATAM" app)."""
Expand Down Expand Up @@ -122,3 +135,7 @@ def read_timeout(self) -> float:
@property
def device_app_id(self) -> str:
return self.__device_app_id

@property
def login_authorization(self) -> str | None:
return self.__login_authorization
4 changes: 3 additions & 1 deletion src/saic_ismart_client_ng/net/crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,9 @@ def encrypt_request(
original_request_headers["APP-CONTENT-ENCRYPTED"] = "1"
original_request_headers["tenant-id"] = tenant_id
original_request_headers["User-Type"] = "app"
original_request_headers["APP-LANGUAGE-TYPE"] = "en"
original_request_headers["APP-LANGUAGE-TYPE"] = (
"th" if region.lower() == "th" else "en"
)
if user_token:
original_request_headers["blade-auth"] = user_token
app_verification_string = get_app_verification_string(
Expand Down
Loading