renpho-api 0.1.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.
- renpho/__init__.py +24 -0
- renpho/cli.py +111 -0
- renpho/client.py +267 -0
- renpho/constants.py +45 -0
- renpho/crypto.py +54 -0
- renpho/export.py +95 -0
- renpho_api-0.1.0.dist-info/METADATA +159 -0
- renpho_api-0.1.0.dist-info/RECORD +11 -0
- renpho_api-0.1.0.dist-info/WHEEL +5 -0
- renpho_api-0.1.0.dist-info/entry_points.txt +2 -0
- renpho_api-0.1.0.dist-info/top_level.txt +1 -0
renpho/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""renpho - Unofficial Python client for the Renpho Health API.
|
|
2
|
+
|
|
3
|
+
Pull body composition measurements from Renpho smart scales.
|
|
4
|
+
|
|
5
|
+
Quick start::
|
|
6
|
+
|
|
7
|
+
from renpho import RenphoClient
|
|
8
|
+
|
|
9
|
+
client = RenphoClient("user@example.com", "password")
|
|
10
|
+
client.login()
|
|
11
|
+
measurements = client.get_all_measurements()
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from .client import RenphoAPIError, RenphoClient
|
|
15
|
+
from .export import format_measurement, format_timestamp, save_csv, save_json
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"RenphoClient",
|
|
19
|
+
"RenphoAPIError",
|
|
20
|
+
"format_measurement",
|
|
21
|
+
"format_timestamp",
|
|
22
|
+
"save_csv",
|
|
23
|
+
"save_json",
|
|
24
|
+
]
|
renpho/cli.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Command-line interface for pulling Renpho scale data."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from dotenv import load_dotenv
|
|
9
|
+
|
|
10
|
+
load_dotenv()
|
|
11
|
+
except ImportError:
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
from .client import RenphoClient
|
|
15
|
+
from .export import format_measurement, save_csv, save_json
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def main(argv: list[str] | None = None) -> None:
|
|
19
|
+
"""Entry point for the ``renpho`` CLI command."""
|
|
20
|
+
email = os.getenv("RENPHO_EMAIL", "")
|
|
21
|
+
password = os.getenv("RENPHO_PASSWORD", "")
|
|
22
|
+
debug = os.getenv("RENPHO_DEBUG", "").lower() in ("1", "true", "yes")
|
|
23
|
+
output_dir = Path(os.getenv("RENPHO_OUTPUT_DIR", "renpho_data"))
|
|
24
|
+
|
|
25
|
+
if not email or not password:
|
|
26
|
+
print("Missing credentials!\n")
|
|
27
|
+
print("Create a .env file with:")
|
|
28
|
+
print(" RENPHO_EMAIL=your@email.com")
|
|
29
|
+
print(" RENPHO_PASSWORD=your_plain_text_password")
|
|
30
|
+
print(" RENPHO_DEBUG=1 # optional")
|
|
31
|
+
sys.exit(1)
|
|
32
|
+
|
|
33
|
+
client = RenphoClient(email, password, debug=debug)
|
|
34
|
+
|
|
35
|
+
# Step 1: Login
|
|
36
|
+
print(f"Logging in as {email}...")
|
|
37
|
+
client.login()
|
|
38
|
+
print(f"Logged in! User ID: {client.user_id}")
|
|
39
|
+
|
|
40
|
+
# Step 2: Device info
|
|
41
|
+
print("Getting device info...")
|
|
42
|
+
device_info = client.get_device_info()
|
|
43
|
+
|
|
44
|
+
if not device_info:
|
|
45
|
+
print("Could not get device info")
|
|
46
|
+
sys.exit(1)
|
|
47
|
+
|
|
48
|
+
save_json(device_info, output_dir / "device_info.json")
|
|
49
|
+
|
|
50
|
+
scales = device_info.get("scale", [])
|
|
51
|
+
if not scales:
|
|
52
|
+
print("No scales found in device info")
|
|
53
|
+
print(f" Device info keys: {list(device_info.keys())}")
|
|
54
|
+
sys.exit(1)
|
|
55
|
+
|
|
56
|
+
print(f"\nFound {len(scales)} scale table(s):")
|
|
57
|
+
for i, scale in enumerate(scales):
|
|
58
|
+
table = scale.get("tableName", "unknown")
|
|
59
|
+
count = scale.get("count", 0)
|
|
60
|
+
uids = scale.get("userIds", [])
|
|
61
|
+
print(f" [{i}] table={table}, records={count}, users={uids}")
|
|
62
|
+
|
|
63
|
+
# Step 3: Fetch measurements
|
|
64
|
+
all_measurements: list[dict] = []
|
|
65
|
+
for scale in scales:
|
|
66
|
+
table_name = scale.get("tableName")
|
|
67
|
+
count = scale.get("count", 0)
|
|
68
|
+
user_ids = scale.get("userIds", [])
|
|
69
|
+
|
|
70
|
+
if not table_name or count == 0:
|
|
71
|
+
continue
|
|
72
|
+
|
|
73
|
+
uid = client.user_id
|
|
74
|
+
if user_ids and uid not in user_ids:
|
|
75
|
+
uid = user_ids[0]
|
|
76
|
+
|
|
77
|
+
print(f"Fetching measurements (table: {table_name}, total: {count})...")
|
|
78
|
+
measurements = client.get_measurements(table_name, uid, count)
|
|
79
|
+
all_measurements.extend(measurements)
|
|
80
|
+
|
|
81
|
+
if not all_measurements:
|
|
82
|
+
print("\nNo measurements found.")
|
|
83
|
+
print(" Try setting RENPHO_DEBUG=1 to see API responses.")
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
# Sort newest first
|
|
87
|
+
all_measurements.sort(
|
|
88
|
+
key=lambda m: m.get("timeStamp", 0) or 0,
|
|
89
|
+
reverse=True,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
print(f"\nTotal: {len(all_measurements)} measurement(s)")
|
|
93
|
+
|
|
94
|
+
# Display most recent 5
|
|
95
|
+
for i, m in enumerate(all_measurements[:5]):
|
|
96
|
+
print(f"\n{'=' * 55}")
|
|
97
|
+
print(f" Measurement #{i + 1}")
|
|
98
|
+
print(f"{'=' * 55}")
|
|
99
|
+
print(format_measurement(m))
|
|
100
|
+
|
|
101
|
+
if len(all_measurements) > 5:
|
|
102
|
+
print(f"\n ... and {len(all_measurements) - 5} more")
|
|
103
|
+
|
|
104
|
+
# Save data
|
|
105
|
+
save_json(all_measurements, output_dir / "measurements.json")
|
|
106
|
+
save_csv(all_measurements, output_dir / "measurements.csv")
|
|
107
|
+
|
|
108
|
+
if client.user_info:
|
|
109
|
+
save_json(client.user_info, output_dir / "user_profile.json")
|
|
110
|
+
|
|
111
|
+
print(f"\nDone! Data saved to '{output_dir}/' folder.")
|
renpho/client.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Renpho API client for fetching scale measurements."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from .constants import (
|
|
9
|
+
API_BASE_URL,
|
|
10
|
+
APP_VERSION,
|
|
11
|
+
BODY_WEIGHT_SCALES,
|
|
12
|
+
ENDPOINTS,
|
|
13
|
+
PLATFORM,
|
|
14
|
+
SUCCESS_CODES,
|
|
15
|
+
)
|
|
16
|
+
from .crypto import (
|
|
17
|
+
decrypt_response,
|
|
18
|
+
encrypt_empty_bytes,
|
|
19
|
+
encrypt_empty_object,
|
|
20
|
+
encrypt_request,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RenphoAPIError(Exception):
|
|
25
|
+
"""Raised when the Renpho API returns an error response."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, context: str, code, msg: str):
|
|
28
|
+
self.context = context
|
|
29
|
+
self.code = code
|
|
30
|
+
self.msg = msg
|
|
31
|
+
super().__init__(f"{context} failed: code={code}, msg={msg}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _check_response(result: dict, context: str = "API call") -> None:
|
|
35
|
+
"""Raise :class:`RenphoAPIError` if the response indicates failure."""
|
|
36
|
+
code = result.get("code")
|
|
37
|
+
msg = result.get("msg", "")
|
|
38
|
+
if msg.lower() == "success" or code in SUCCESS_CODES:
|
|
39
|
+
return
|
|
40
|
+
raise RenphoAPIError(context, code, msg)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RenphoClient:
|
|
44
|
+
"""Client for the Renpho cloud API.
|
|
45
|
+
|
|
46
|
+
Example::
|
|
47
|
+
|
|
48
|
+
client = RenphoClient("user@example.com", "password")
|
|
49
|
+
client.login()
|
|
50
|
+
measurements = client.get_all_measurements()
|
|
51
|
+
for m in measurements:
|
|
52
|
+
print(m["weight"], m.get("bodyfat"))
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self, email: str, password: str, *, debug: bool = False):
|
|
56
|
+
self.email = email
|
|
57
|
+
self.password = password
|
|
58
|
+
self.debug = debug
|
|
59
|
+
self.token: str | None = None
|
|
60
|
+
self.user_id: int | str | None = None
|
|
61
|
+
self.user_info: dict | None = None
|
|
62
|
+
self._session = requests.Session()
|
|
63
|
+
|
|
64
|
+
# ----- internal helpers -----
|
|
65
|
+
|
|
66
|
+
def _post(self, endpoint: str, body: dict, *, auth: bool = True) -> dict:
|
|
67
|
+
"""Make an encrypted POST request to the Renpho API."""
|
|
68
|
+
url = f"{API_BASE_URL}/{endpoint}"
|
|
69
|
+
headers: dict[str, str] = {}
|
|
70
|
+
if auth and self.token:
|
|
71
|
+
headers["token"] = self.token
|
|
72
|
+
headers["userId"] = str(self.user_id)
|
|
73
|
+
headers["appVersion"] = APP_VERSION
|
|
74
|
+
headers["platform"] = PLATFORM
|
|
75
|
+
|
|
76
|
+
if self.debug:
|
|
77
|
+
print(f" POST {url}")
|
|
78
|
+
if auth and self.token:
|
|
79
|
+
print(f" Headers: token={self.token[:20]}..., userId={self.user_id}")
|
|
80
|
+
|
|
81
|
+
resp = self._session.post(url, json=body, headers=headers)
|
|
82
|
+
|
|
83
|
+
if self.debug:
|
|
84
|
+
print(f" Status: {resp.status_code}")
|
|
85
|
+
print(f" Response: {resp.text[:300]}")
|
|
86
|
+
|
|
87
|
+
resp.raise_for_status()
|
|
88
|
+
return resp.json()
|
|
89
|
+
|
|
90
|
+
# ----- public API -----
|
|
91
|
+
|
|
92
|
+
def login(self) -> dict:
|
|
93
|
+
"""Authenticate and store the session token.
|
|
94
|
+
|
|
95
|
+
Returns the full decrypted login response (includes user profile).
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
RenphoAPIError: If the API rejects the credentials.
|
|
99
|
+
requests.HTTPError: On transport-level failures.
|
|
100
|
+
"""
|
|
101
|
+
login_payload = {
|
|
102
|
+
"questionnaire": {},
|
|
103
|
+
"login": {
|
|
104
|
+
"password": self.password,
|
|
105
|
+
"areaCode": "US",
|
|
106
|
+
"appRevision": APP_VERSION,
|
|
107
|
+
"cellphoneType": "PythonScript",
|
|
108
|
+
"systemType": "11",
|
|
109
|
+
"email": self.email,
|
|
110
|
+
"platform": PLATFORM,
|
|
111
|
+
},
|
|
112
|
+
"bindingList": {
|
|
113
|
+
"deviceTypes": BODY_WEIGHT_SCALES,
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
encrypted_body = encrypt_request(login_payload)
|
|
118
|
+
result = self._post(ENDPOINTS["login"], encrypted_body, auth=False)
|
|
119
|
+
_check_response(result, "Login")
|
|
120
|
+
|
|
121
|
+
user_data = decrypt_response(result["data"])
|
|
122
|
+
|
|
123
|
+
if self.debug:
|
|
124
|
+
print(f" Decrypted login: {json.dumps(user_data, indent=2)[:500]}")
|
|
125
|
+
|
|
126
|
+
login_info = user_data.get("login", {})
|
|
127
|
+
self.token = login_info.get("token")
|
|
128
|
+
self.user_id = login_info.get("id")
|
|
129
|
+
self.user_info = login_info
|
|
130
|
+
|
|
131
|
+
if not self.token:
|
|
132
|
+
raise RenphoAPIError("Login", None, "No token in login response")
|
|
133
|
+
|
|
134
|
+
return user_data
|
|
135
|
+
|
|
136
|
+
def get_device_info(self) -> dict:
|
|
137
|
+
"""Get device info including scale table names and record counts.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
Decrypted device info dict (contains ``scale`` list among others).
|
|
141
|
+
|
|
142
|
+
Raises:
|
|
143
|
+
RenphoAPIError: On API-level failure.
|
|
144
|
+
"""
|
|
145
|
+
for attempt, body_fn in enumerate([encrypt_empty_bytes, encrypt_empty_object]):
|
|
146
|
+
encrypted_body = body_fn()
|
|
147
|
+
try:
|
|
148
|
+
result = self._post(ENDPOINTS["device_info"], encrypted_body)
|
|
149
|
+
break
|
|
150
|
+
except requests.exceptions.HTTPError as e:
|
|
151
|
+
if attempt == 0:
|
|
152
|
+
if self.debug:
|
|
153
|
+
print(f" Attempt 1 failed ({e}), retrying with empty object...")
|
|
154
|
+
continue
|
|
155
|
+
raise
|
|
156
|
+
|
|
157
|
+
_check_response(result, "GetDeviceInfo")
|
|
158
|
+
data = decrypt_response(result["data"])
|
|
159
|
+
|
|
160
|
+
if self.debug:
|
|
161
|
+
print(f" Device info: {json.dumps(data, indent=2)[:500]}")
|
|
162
|
+
|
|
163
|
+
return data
|
|
164
|
+
|
|
165
|
+
def get_measurements(
|
|
166
|
+
self, table_name: str, user_id, total_count: int, *, page_size: int = 50
|
|
167
|
+
) -> list[dict]:
|
|
168
|
+
"""Fetch measurements from a specific scale table with pagination.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
table_name: Dynamic table name from :meth:`get_device_info`.
|
|
172
|
+
user_id: The user ID to query for.
|
|
173
|
+
total_count: Total records available (from device info).
|
|
174
|
+
page_size: Records per page (default 50).
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
List of measurement dicts.
|
|
178
|
+
"""
|
|
179
|
+
all_measurements: list[dict] = []
|
|
180
|
+
page = 1
|
|
181
|
+
|
|
182
|
+
while len(all_measurements) < total_count:
|
|
183
|
+
request_data = {
|
|
184
|
+
"pageNum": page,
|
|
185
|
+
"pageSize": page_size,
|
|
186
|
+
"userIds": [str(user_id)],
|
|
187
|
+
"tableName": table_name,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if self.debug:
|
|
191
|
+
print(f" Page {page} (got {len(all_measurements)} so far)...")
|
|
192
|
+
|
|
193
|
+
encrypted_body = encrypt_request(request_data)
|
|
194
|
+
result = self._post(ENDPOINTS["measurements"], encrypted_body)
|
|
195
|
+
_check_response(result, f"Measurements page {page}")
|
|
196
|
+
|
|
197
|
+
if not result.get("data"):
|
|
198
|
+
break
|
|
199
|
+
|
|
200
|
+
page_data = decrypt_response(result["data"])
|
|
201
|
+
|
|
202
|
+
if self.debug:
|
|
203
|
+
if isinstance(page_data, list):
|
|
204
|
+
print(f" Got {len(page_data)} records")
|
|
205
|
+
else:
|
|
206
|
+
print(f" Response type: {type(page_data)}")
|
|
207
|
+
|
|
208
|
+
records = self._extract_records(page_data)
|
|
209
|
+
if records is None:
|
|
210
|
+
break
|
|
211
|
+
|
|
212
|
+
all_measurements.extend(records)
|
|
213
|
+
page += 1
|
|
214
|
+
|
|
215
|
+
return all_measurements
|
|
216
|
+
|
|
217
|
+
def get_all_measurements(self) -> list[dict]:
|
|
218
|
+
"""High-level helper: fetch device info then pull all measurements.
|
|
219
|
+
|
|
220
|
+
Calls :meth:`login` first if no token is set.
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
List of measurement dicts sorted by timestamp (newest first).
|
|
224
|
+
"""
|
|
225
|
+
if not self.token:
|
|
226
|
+
self.login()
|
|
227
|
+
|
|
228
|
+
device_info = self.get_device_info()
|
|
229
|
+
scales = device_info.get("scale", [])
|
|
230
|
+
|
|
231
|
+
all_measurements: list[dict] = []
|
|
232
|
+
for scale in scales:
|
|
233
|
+
table_name = scale.get("tableName")
|
|
234
|
+
count = scale.get("count", 0)
|
|
235
|
+
user_ids = scale.get("userIds", [])
|
|
236
|
+
|
|
237
|
+
if not table_name or count == 0:
|
|
238
|
+
continue
|
|
239
|
+
|
|
240
|
+
uid = self.user_id
|
|
241
|
+
if user_ids and uid not in user_ids:
|
|
242
|
+
uid = user_ids[0]
|
|
243
|
+
|
|
244
|
+
measurements = self.get_measurements(table_name, uid, count)
|
|
245
|
+
all_measurements.extend(measurements)
|
|
246
|
+
|
|
247
|
+
all_measurements.sort(
|
|
248
|
+
key=lambda m: m.get("timeStamp", 0) or 0,
|
|
249
|
+
reverse=True,
|
|
250
|
+
)
|
|
251
|
+
return all_measurements
|
|
252
|
+
|
|
253
|
+
@staticmethod
|
|
254
|
+
def _extract_records(page_data) -> list[dict] | None:
|
|
255
|
+
"""Extract measurement records from a page response."""
|
|
256
|
+
if isinstance(page_data, list):
|
|
257
|
+
return page_data if page_data else None
|
|
258
|
+
|
|
259
|
+
if isinstance(page_data, dict):
|
|
260
|
+
for key in ("list", "data", "records", "measurements"):
|
|
261
|
+
if key in page_data and isinstance(page_data[key], list):
|
|
262
|
+
return page_data[key] if page_data[key] else None
|
|
263
|
+
|
|
264
|
+
if "weight" in page_data:
|
|
265
|
+
return [page_data]
|
|
266
|
+
|
|
267
|
+
return None
|
renpho/constants.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Constants and configuration for the Renpho API."""
|
|
2
|
+
|
|
3
|
+
# API connection
|
|
4
|
+
API_BASE_URL = "https://cloud.renpho.com"
|
|
5
|
+
ENCRYPTION_KEY = "ed*wijdi$h6fe3ew" # 16-byte AES-128 key
|
|
6
|
+
APP_VERSION = "6.6.0"
|
|
7
|
+
PLATFORM = "android"
|
|
8
|
+
|
|
9
|
+
# API endpoints (from RenphoApiEndpoints.cs)
|
|
10
|
+
ENDPOINTS = {
|
|
11
|
+
"login": "renpho-aggregation/user/login",
|
|
12
|
+
"token_time": "RenphoHealth/app/sync/getTokenTime",
|
|
13
|
+
"device_info": "renpho-aggregation/device/count",
|
|
14
|
+
"family": "RenphoHealth/centerUser/queryFamilyMemberList",
|
|
15
|
+
"measurements": "RenphoHealth/scale/queryAllMeasureDataList",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
# Body weight scale device types
|
|
19
|
+
BODY_WEIGHT_SCALES = [
|
|
20
|
+
"01", "02", "03", "04", "05", "06", "07", "08", "09", "0A",
|
|
21
|
+
"0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
# Measurement display metadata: (api_key, label, unit)
|
|
25
|
+
METRICS = [
|
|
26
|
+
("weight", "Weight", "kg"),
|
|
27
|
+
("bmi", "BMI", ""),
|
|
28
|
+
("bodyfat", "Body Fat", "%"),
|
|
29
|
+
("water", "Body Water", "%"),
|
|
30
|
+
("muscle", "Muscle Mass", "%"),
|
|
31
|
+
("bone", "Bone Mass", "%"),
|
|
32
|
+
("bmr", "BMR", "kcal/day"),
|
|
33
|
+
("visfat", "Visceral Fat", "level"),
|
|
34
|
+
("subfat", "Subcutaneous Fat", "%"),
|
|
35
|
+
("protein", "Protein", "%"),
|
|
36
|
+
("bodyage", "Body Age", "years"),
|
|
37
|
+
("sinew", "Lean Body Mass", "kg"),
|
|
38
|
+
("fatFreeWeight", "Fat Free Weight", "kg"),
|
|
39
|
+
("heartRate", "Heart Rate", "bpm"),
|
|
40
|
+
("cardiacIndex", "Cardiac Index", ""),
|
|
41
|
+
("bodyShape", "Body Shape", ""),
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
# Success codes returned by the API
|
|
45
|
+
SUCCESS_CODES = {0, "0", 101, "101", 200, "200", 20000, "20000"}
|
renpho/crypto.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""AES-128-ECB encryption utilities for the Renpho API.
|
|
2
|
+
|
|
3
|
+
The Renpho cloud API encrypts all request/response payloads using
|
|
4
|
+
AES-128-ECB with PKCS7 padding, base64-encoded for transport.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
from Crypto.Cipher import AES
|
|
11
|
+
from Crypto.Util.Padding import pad, unpad
|
|
12
|
+
|
|
13
|
+
from .constants import ENCRYPTION_KEY
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def aes_encrypt(plaintext: str, key: str = ENCRYPTION_KEY) -> str:
|
|
17
|
+
"""Encrypt a string with AES-128-ECB + PKCS7 padding, return base64."""
|
|
18
|
+
cipher = AES.new(key.encode("utf-8"), AES.MODE_ECB)
|
|
19
|
+
padded = pad(plaintext.encode("utf-8"), AES.block_size)
|
|
20
|
+
encrypted = cipher.encrypt(padded)
|
|
21
|
+
return base64.b64encode(encrypted).decode("utf-8")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def aes_decrypt(encrypted_b64: str, key: str = ENCRYPTION_KEY) -> str:
|
|
25
|
+
"""Decrypt a base64 AES-128-ECB + PKCS7 string."""
|
|
26
|
+
cipher = AES.new(key.encode("utf-8"), AES.MODE_ECB)
|
|
27
|
+
encrypted = base64.b64decode(encrypted_b64)
|
|
28
|
+
decrypted = unpad(cipher.decrypt(encrypted), AES.block_size)
|
|
29
|
+
return decrypted.decode("utf-8")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def encrypt_request(obj: dict, key: str = ENCRYPTION_KEY) -> dict:
|
|
33
|
+
"""Encrypt a request payload into ``{"encryptData": "..."}`` format."""
|
|
34
|
+
serialized = json.dumps(obj, separators=(",", ":"))
|
|
35
|
+
return {"encryptData": aes_encrypt(serialized, key)}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def encrypt_empty_object(key: str = ENCRYPTION_KEY) -> dict:
|
|
39
|
+
"""Encrypt an empty JSON object ``{}``."""
|
|
40
|
+
return encrypt_request({}, key)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def encrypt_empty_bytes(key: str = ENCRYPTION_KEY) -> dict:
|
|
44
|
+
"""Encrypt an empty byte array (used by some endpoints)."""
|
|
45
|
+
cipher = AES.new(key.encode("utf-8"), AES.MODE_ECB)
|
|
46
|
+
padded = pad(b"", AES.block_size)
|
|
47
|
+
encrypted = cipher.encrypt(padded)
|
|
48
|
+
return {"encryptData": base64.b64encode(encrypted).decode("utf-8")}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def decrypt_response(encrypted_data: str, key: str = ENCRYPTION_KEY):
|
|
52
|
+
"""Decrypt the ``data`` field from an API response and parse as JSON."""
|
|
53
|
+
decrypted = aes_decrypt(encrypted_data, key)
|
|
54
|
+
return json.loads(decrypted)
|
renpho/export.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Helpers for formatting, displaying, and exporting Renpho measurements."""
|
|
2
|
+
|
|
3
|
+
import datetime
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .constants import METRICS
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def format_timestamp(ts) -> str:
|
|
11
|
+
"""Convert a Renpho timestamp (seconds or milliseconds) to a readable string."""
|
|
12
|
+
if ts is None:
|
|
13
|
+
return "unknown"
|
|
14
|
+
ts = int(ts)
|
|
15
|
+
if ts > 1e12:
|
|
16
|
+
ts = ts // 1000
|
|
17
|
+
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def format_measurement(m: dict) -> str:
|
|
21
|
+
"""Return a human-readable string for a single measurement."""
|
|
22
|
+
ts = m.get("timeStamp") or m.get("time_stamp")
|
|
23
|
+
local = m.get("localCreatedAt", "")
|
|
24
|
+
scale = m.get("scaleName", "")
|
|
25
|
+
|
|
26
|
+
lines = [f" Date: {format_timestamp(ts)}"]
|
|
27
|
+
if local:
|
|
28
|
+
lines.append(f" Local time: {local}")
|
|
29
|
+
if scale:
|
|
30
|
+
lines.append(f" Scale: {scale}")
|
|
31
|
+
|
|
32
|
+
for key, label, unit in METRICS:
|
|
33
|
+
value = m.get(key)
|
|
34
|
+
if value is not None and value != 0 and value != 0.0:
|
|
35
|
+
unit_str = f" {unit}" if unit else ""
|
|
36
|
+
lines.append(f" {label:<22} {value}{unit_str}")
|
|
37
|
+
|
|
38
|
+
return "\n".join(lines)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def save_json(data, filepath: str | Path) -> Path:
|
|
42
|
+
"""Write *data* as pretty-printed JSON.
|
|
43
|
+
|
|
44
|
+
Parent directories are created automatically.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
The resolved :class:`~pathlib.Path` that was written.
|
|
48
|
+
"""
|
|
49
|
+
filepath = Path(filepath)
|
|
50
|
+
filepath.parent.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
with open(filepath, "w") as f:
|
|
52
|
+
json.dump(data, f, indent=2, default=str)
|
|
53
|
+
return filepath
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def save_csv(measurements: list[dict], filepath: str | Path) -> Path | None:
|
|
57
|
+
"""Write measurements to a CSV file.
|
|
58
|
+
|
|
59
|
+
Columns are ordered with the most useful metrics first, followed by any
|
|
60
|
+
remaining keys in alphabetical order.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
The resolved :class:`~pathlib.Path` that was written, or ``None`` if
|
|
64
|
+
*measurements* is empty.
|
|
65
|
+
"""
|
|
66
|
+
if not measurements:
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
filepath = Path(filepath)
|
|
70
|
+
filepath.parent.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
|
|
72
|
+
priority = [
|
|
73
|
+
"timeStamp", "localCreatedAt",
|
|
74
|
+
*(key for key, _, _ in METRICS),
|
|
75
|
+
"scaleName", "height", "gender",
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
all_keys: set[str] = set()
|
|
79
|
+
for m in measurements:
|
|
80
|
+
all_keys.update(m.keys())
|
|
81
|
+
|
|
82
|
+
columns = [k for k in priority if k in all_keys]
|
|
83
|
+
columns += sorted(k for k in all_keys if k not in columns)
|
|
84
|
+
|
|
85
|
+
with open(filepath, "w") as f:
|
|
86
|
+
f.write(",".join(columns) + "\n")
|
|
87
|
+
for m in measurements:
|
|
88
|
+
row = []
|
|
89
|
+
for k in columns:
|
|
90
|
+
val = m.get(k, "")
|
|
91
|
+
val_str = str(val).replace(",", ";") if val is not None else ""
|
|
92
|
+
row.append(val_str)
|
|
93
|
+
f.write(",".join(row) + "\n")
|
|
94
|
+
|
|
95
|
+
return filepath
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: renpho-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Unofficial Python client for the Renpho Health API — pull body composition data from Renpho smart scales.
|
|
5
|
+
Author: danvaneijck
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/danvaneijck/renpho-api
|
|
8
|
+
Keywords: renpho,health,body-composition,smart-scale,api-client
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
Requires-Dist: requests>=2.28
|
|
20
|
+
Requires-Dist: pycryptodome>=3.15
|
|
21
|
+
Provides-Extra: dotenv
|
|
22
|
+
Requires-Dist: python-dotenv>=1.0; extra == "dotenv"
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
25
|
+
|
|
26
|
+
# renpho
|
|
27
|
+
|
|
28
|
+
Unofficial Python client for the Renpho Health API. Pull body composition measurements from Renpho smart scales programmatically.
|
|
29
|
+
|
|
30
|
+
Based on reverse-engineering from [RenphoGarminSync-CLI](https://github.com/forkerer/RenphoGarminSync-CLI).
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install .
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
For `.env` file support (recommended for CLI usage):
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install ".[dotenv]"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## CLI Usage
|
|
45
|
+
|
|
46
|
+
1. Create a `.env` file (or export the variables):
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
RENPHO_EMAIL=your@email.com
|
|
50
|
+
RENPHO_PASSWORD=your_plain_text_password
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
2. Run the CLI:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
renpho
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
This will log in, discover your scales, fetch all measurements, print the 5 most recent, and save everything to `renpho_data/` as JSON and CSV.
|
|
60
|
+
|
|
61
|
+
### Environment variables
|
|
62
|
+
|
|
63
|
+
| Variable | Required | Description |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `RENPHO_EMAIL` | Yes | Your Renpho account email |
|
|
66
|
+
| `RENPHO_PASSWORD` | Yes | Your Renpho account password |
|
|
67
|
+
| `RENPHO_DEBUG` | No | Set to `1` to print API request/response details |
|
|
68
|
+
| `RENPHO_OUTPUT_DIR` | No | Output directory (default: `renpho_data`) |
|
|
69
|
+
|
|
70
|
+
## Library Usage
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from renpho import RenphoClient
|
|
74
|
+
|
|
75
|
+
client = RenphoClient("user@example.com", "password")
|
|
76
|
+
client.login()
|
|
77
|
+
|
|
78
|
+
# Fetch all measurements in one call
|
|
79
|
+
measurements = client.get_all_measurements()
|
|
80
|
+
|
|
81
|
+
for m in measurements:
|
|
82
|
+
print(m["weight"], m.get("bodyfat"), m.get("muscle"))
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Step-by-step control
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from renpho import RenphoClient, save_json, save_csv
|
|
89
|
+
|
|
90
|
+
client = RenphoClient("user@example.com", "password")
|
|
91
|
+
client.login()
|
|
92
|
+
|
|
93
|
+
# Get device/scale info
|
|
94
|
+
device_info = client.get_device_info()
|
|
95
|
+
scales = device_info["scale"]
|
|
96
|
+
|
|
97
|
+
# Fetch from a specific scale table
|
|
98
|
+
table = scales[0]
|
|
99
|
+
measurements = client.get_measurements(
|
|
100
|
+
table_name=table["tableName"],
|
|
101
|
+
user_id=client.user_id,
|
|
102
|
+
total_count=table["count"],
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# Export
|
|
106
|
+
save_json(measurements, "my_data.json")
|
|
107
|
+
save_csv(measurements, "my_data.csv")
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### Error handling
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from renpho import RenphoClient, RenphoAPIError
|
|
114
|
+
|
|
115
|
+
client = RenphoClient("user@example.com", "wrong_password")
|
|
116
|
+
try:
|
|
117
|
+
client.login()
|
|
118
|
+
except RenphoAPIError as e:
|
|
119
|
+
print(f"API error: {e}")
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Available Metrics
|
|
123
|
+
|
|
124
|
+
Each measurement dict can contain these fields (availability depends on your scale model):
|
|
125
|
+
|
|
126
|
+
| Key | Description | Unit |
|
|
127
|
+
| --- | --- | --- |
|
|
128
|
+
| `weight` | Weight | kg |
|
|
129
|
+
| `bmi` | BMI | |
|
|
130
|
+
| `bodyfat` | Body Fat | % |
|
|
131
|
+
| `water` | Body Water | % |
|
|
132
|
+
| `muscle` | Muscle Mass | % |
|
|
133
|
+
| `bone` | Bone Mass | % |
|
|
134
|
+
| `bmr` | Basal Metabolic Rate | kcal/day |
|
|
135
|
+
| `visfat` | Visceral Fat | level |
|
|
136
|
+
| `subfat` | Subcutaneous Fat | % |
|
|
137
|
+
| `protein` | Protein | % |
|
|
138
|
+
| `bodyage` | Body Age | years |
|
|
139
|
+
| `sinew` | Lean Body Mass | kg |
|
|
140
|
+
| `fatFreeWeight` | Fat Free Weight | kg |
|
|
141
|
+
| `heartRate` | Heart Rate | bpm |
|
|
142
|
+
| `cardiacIndex` | Cardiac Index | |
|
|
143
|
+
| `bodyShape` | Body Shape | |
|
|
144
|
+
|
|
145
|
+
## Project Structure
|
|
146
|
+
|
|
147
|
+
```
|
|
148
|
+
renpho-api/
|
|
149
|
+
├── pyproject.toml # Package config & dependencies
|
|
150
|
+
├── README.md
|
|
151
|
+
├── renpho/
|
|
152
|
+
│ ├── __init__.py # Public API exports
|
|
153
|
+
│ ├── client.py # RenphoClient class
|
|
154
|
+
│ ├── cli.py # CLI entry point
|
|
155
|
+
│ ├── constants.py # API endpoints, device types, metrics
|
|
156
|
+
│ ├── crypto.py # AES encryption/decryption
|
|
157
|
+
│ └── export.py # JSON/CSV export helpers
|
|
158
|
+
└── .gitignore
|
|
159
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
renpho/__init__.py,sha256=DCTXlSyeSIEHjwy6yTCUS0-h8KXggLUZbnYeqTYn_RQ,577
|
|
2
|
+
renpho/cli.py,sha256=qzKcR-5elrAzqXvie_4Ci6NZfz7lmHqPTjAbslXN8fo,3402
|
|
3
|
+
renpho/client.py,sha256=sF_iYxN68tPeJ2RBwUwU7xroGa30GO3WjVI4g538zB4,8396
|
|
4
|
+
renpho/constants.py,sha256=m24--lcaSDTyDYXQEJqoeXclJLrr0rPGs9SUXSwVcXs,1506
|
|
5
|
+
renpho/crypto.py,sha256=bUxDKBvApp2Yecv-uLW_llqAI8tMY727AmNl7PPh1_4,1984
|
|
6
|
+
renpho/export.py,sha256=v-yTgQfuQBVkgvoBm2J0iiPieh8L9HRpz3XBHlu4ZX4,2784
|
|
7
|
+
renpho_api-0.1.0.dist-info/METADATA,sha256=ZHI26Ige7kIPG0bN_SUKYl48zGyo6UdZ6d2xEiN3C1c,4333
|
|
8
|
+
renpho_api-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
|
|
9
|
+
renpho_api-0.1.0.dist-info/entry_points.txt,sha256=WwzgR408BL15AZ7hsgqvYQovrIpD6y1u2RBnS6VkaLo,43
|
|
10
|
+
renpho_api-0.1.0.dist-info/top_level.txt,sha256=4Fx37UUXPT1K_IYsJnxDaGbvbssufPBZZCpYG-Zw4Bs,7
|
|
11
|
+
renpho_api-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
renpho
|