renpho-api 0.1.0__tar.gz

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,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,134 @@
1
+ # renpho
2
+
3
+ Unofficial Python client for the Renpho Health API. Pull body composition measurements from Renpho smart scales programmatically.
4
+
5
+ Based on reverse-engineering from [RenphoGarminSync-CLI](https://github.com/forkerer/RenphoGarminSync-CLI).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install .
11
+ ```
12
+
13
+ For `.env` file support (recommended for CLI usage):
14
+
15
+ ```bash
16
+ pip install ".[dotenv]"
17
+ ```
18
+
19
+ ## CLI Usage
20
+
21
+ 1. Create a `.env` file (or export the variables):
22
+
23
+ ```
24
+ RENPHO_EMAIL=your@email.com
25
+ RENPHO_PASSWORD=your_plain_text_password
26
+ ```
27
+
28
+ 2. Run the CLI:
29
+
30
+ ```bash
31
+ renpho
32
+ ```
33
+
34
+ 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.
35
+
36
+ ### Environment variables
37
+
38
+ | Variable | Required | Description |
39
+ | --- | --- | --- |
40
+ | `RENPHO_EMAIL` | Yes | Your Renpho account email |
41
+ | `RENPHO_PASSWORD` | Yes | Your Renpho account password |
42
+ | `RENPHO_DEBUG` | No | Set to `1` to print API request/response details |
43
+ | `RENPHO_OUTPUT_DIR` | No | Output directory (default: `renpho_data`) |
44
+
45
+ ## Library Usage
46
+
47
+ ```python
48
+ from renpho import RenphoClient
49
+
50
+ client = RenphoClient("user@example.com", "password")
51
+ client.login()
52
+
53
+ # Fetch all measurements in one call
54
+ measurements = client.get_all_measurements()
55
+
56
+ for m in measurements:
57
+ print(m["weight"], m.get("bodyfat"), m.get("muscle"))
58
+ ```
59
+
60
+ ### Step-by-step control
61
+
62
+ ```python
63
+ from renpho import RenphoClient, save_json, save_csv
64
+
65
+ client = RenphoClient("user@example.com", "password")
66
+ client.login()
67
+
68
+ # Get device/scale info
69
+ device_info = client.get_device_info()
70
+ scales = device_info["scale"]
71
+
72
+ # Fetch from a specific scale table
73
+ table = scales[0]
74
+ measurements = client.get_measurements(
75
+ table_name=table["tableName"],
76
+ user_id=client.user_id,
77
+ total_count=table["count"],
78
+ )
79
+
80
+ # Export
81
+ save_json(measurements, "my_data.json")
82
+ save_csv(measurements, "my_data.csv")
83
+ ```
84
+
85
+ ### Error handling
86
+
87
+ ```python
88
+ from renpho import RenphoClient, RenphoAPIError
89
+
90
+ client = RenphoClient("user@example.com", "wrong_password")
91
+ try:
92
+ client.login()
93
+ except RenphoAPIError as e:
94
+ print(f"API error: {e}")
95
+ ```
96
+
97
+ ## Available Metrics
98
+
99
+ Each measurement dict can contain these fields (availability depends on your scale model):
100
+
101
+ | Key | Description | Unit |
102
+ | --- | --- | --- |
103
+ | `weight` | Weight | kg |
104
+ | `bmi` | BMI | |
105
+ | `bodyfat` | Body Fat | % |
106
+ | `water` | Body Water | % |
107
+ | `muscle` | Muscle Mass | % |
108
+ | `bone` | Bone Mass | % |
109
+ | `bmr` | Basal Metabolic Rate | kcal/day |
110
+ | `visfat` | Visceral Fat | level |
111
+ | `subfat` | Subcutaneous Fat | % |
112
+ | `protein` | Protein | % |
113
+ | `bodyage` | Body Age | years |
114
+ | `sinew` | Lean Body Mass | kg |
115
+ | `fatFreeWeight` | Fat Free Weight | kg |
116
+ | `heartRate` | Heart Rate | bpm |
117
+ | `cardiacIndex` | Cardiac Index | |
118
+ | `bodyShape` | Body Shape | |
119
+
120
+ ## Project Structure
121
+
122
+ ```
123
+ renpho-api/
124
+ ├── pyproject.toml # Package config & dependencies
125
+ ├── README.md
126
+ ├── renpho/
127
+ │ ├── __init__.py # Public API exports
128
+ │ ├── client.py # RenphoClient class
129
+ │ ├── cli.py # CLI entry point
130
+ │ ├── constants.py # API endpoints, device types, metrics
131
+ │ ├── crypto.py # AES encryption/decryption
132
+ │ └── export.py # JSON/CSV export helpers
133
+ └── .gitignore
134
+ ```
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "renpho-api"
7
+ version = "0.1.0"
8
+ description = "Unofficial Python client for the Renpho Health API — pull body composition data from Renpho smart scales."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "danvaneijck" }]
13
+ keywords = ["renpho", "health", "body-composition", "smart-scale", "api-client"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Software Development :: Libraries",
23
+ ]
24
+ dependencies = [
25
+ "requests>=2.28",
26
+ "pycryptodome>=3.15",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ dotenv = ["python-dotenv>=1.0"]
31
+ dev = ["pytest>=7.0"]
32
+
33
+ [project.urls]
34
+ Repository = "https://github.com/danvaneijck/renpho-api"
35
+
36
+ [project.scripts]
37
+ renpho = "renpho.cli:main"
@@ -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
+ ]
@@ -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.")
@@ -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
@@ -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"}
@@ -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)
@@ -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,18 @@
1
+ README.md
2
+ pyproject.toml
3
+ renpho/__init__.py
4
+ renpho/cli.py
5
+ renpho/client.py
6
+ renpho/constants.py
7
+ renpho/crypto.py
8
+ renpho/export.py
9
+ renpho_api.egg-info/PKG-INFO
10
+ renpho_api.egg-info/SOURCES.txt
11
+ renpho_api.egg-info/dependency_links.txt
12
+ renpho_api.egg-info/entry_points.txt
13
+ renpho_api.egg-info/requires.txt
14
+ renpho_api.egg-info/top_level.txt
15
+ tests/test_client.py
16
+ tests/test_constants.py
17
+ tests/test_crypto.py
18
+ tests/test_export.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ renpho = renpho.cli:main
@@ -0,0 +1,8 @@
1
+ requests>=2.28
2
+ pycryptodome>=3.15
3
+
4
+ [dev]
5
+ pytest>=7.0
6
+
7
+ [dotenv]
8
+ python-dotenv>=1.0
@@ -0,0 +1 @@
1
+ renpho
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,64 @@
1
+ """Tests for renpho.client — RenphoClient unit tests."""
2
+
3
+ import json
4
+
5
+ import pytest
6
+
7
+ from renpho.client import RenphoAPIError, RenphoClient, _check_response
8
+ from renpho.constants import SUCCESS_CODES
9
+
10
+
11
+ class TestCheckResponse:
12
+ def test_success_by_msg(self):
13
+ _check_response({"code": 999, "msg": "success"})
14
+
15
+ @pytest.mark.parametrize("code", [0, "0", 200, "200", 20000, "20000"])
16
+ def test_success_by_code(self, code):
17
+ _check_response({"code": code, "msg": ""})
18
+
19
+ def test_raises_on_failure(self):
20
+ with pytest.raises(RenphoAPIError) as exc_info:
21
+ _check_response({"code": 401, "msg": "Unauthorized"})
22
+ assert exc_info.value.code == 401
23
+ assert "Unauthorized" in str(exc_info.value)
24
+
25
+
26
+ class TestExtractRecords:
27
+ def test_list_input(self):
28
+ records = [{"weight": 70}, {"weight": 71}]
29
+ assert RenphoClient._extract_records(records) == records
30
+
31
+ def test_empty_list(self):
32
+ assert RenphoClient._extract_records([]) is None
33
+
34
+ def test_dict_with_list_key(self):
35
+ data = {"list": [{"weight": 70}]}
36
+ assert RenphoClient._extract_records(data) == [{"weight": 70}]
37
+
38
+ def test_dict_with_data_key(self):
39
+ data = {"data": [{"weight": 70}]}
40
+ assert RenphoClient._extract_records(data) == [{"weight": 70}]
41
+
42
+ def test_single_measurement_dict(self):
43
+ data = {"weight": 70, "bmi": 22}
44
+ assert RenphoClient._extract_records(data) == [data]
45
+
46
+ def test_unknown_dict(self):
47
+ data = {"foo": "bar"}
48
+ assert RenphoClient._extract_records(data) is None
49
+
50
+ def test_none_input(self):
51
+ assert RenphoClient._extract_records(None) is None
52
+
53
+
54
+ class TestRenphoClient:
55
+ def test_init(self):
56
+ client = RenphoClient("test@example.com", "pass123")
57
+ assert client.email == "test@example.com"
58
+ assert client.password == "pass123"
59
+ assert client.token is None
60
+ assert client.debug is False
61
+
62
+ def test_init_debug(self):
63
+ client = RenphoClient("a@b.com", "p", debug=True)
64
+ assert client.debug is True
@@ -0,0 +1,33 @@
1
+ """Tests for renpho.constants — sanity checks on configuration."""
2
+
3
+ from renpho.constants import (
4
+ API_BASE_URL,
5
+ BODY_WEIGHT_SCALES,
6
+ ENCRYPTION_KEY,
7
+ ENDPOINTS,
8
+ METRICS,
9
+ )
10
+
11
+
12
+ def test_encryption_key_length():
13
+ assert len(ENCRYPTION_KEY) == 16 # AES-128 requires 16-byte key
14
+
15
+
16
+ def test_api_base_url_is_https():
17
+ assert API_BASE_URL.startswith("https://")
18
+
19
+
20
+ def test_endpoints_all_present():
21
+ required = {"login", "token_time", "device_info", "family", "measurements"}
22
+ assert required.issubset(ENDPOINTS.keys())
23
+
24
+
25
+ def test_body_weight_scales_nonempty():
26
+ assert len(BODY_WEIGHT_SCALES) > 0
27
+
28
+
29
+ def test_metrics_structure():
30
+ for key, label, unit in METRICS:
31
+ assert isinstance(key, str)
32
+ assert isinstance(label, str)
33
+ assert isinstance(unit, str)
@@ -0,0 +1,54 @@
1
+ """Tests for renpho.crypto — AES encrypt/decrypt round-trips."""
2
+
3
+ import json
4
+
5
+ from renpho.crypto import (
6
+ aes_decrypt,
7
+ aes_encrypt,
8
+ decrypt_response,
9
+ encrypt_empty_bytes,
10
+ encrypt_empty_object,
11
+ encrypt_request,
12
+ )
13
+
14
+
15
+ def test_aes_round_trip():
16
+ plaintext = "hello world"
17
+ encrypted = aes_encrypt(plaintext)
18
+ assert aes_decrypt(encrypted) == plaintext
19
+
20
+
21
+ def test_aes_round_trip_json():
22
+ payload = {"email": "test@example.com", "count": 42}
23
+ serialized = json.dumps(payload, separators=(",", ":"))
24
+ encrypted = aes_encrypt(serialized)
25
+ decrypted = aes_decrypt(encrypted)
26
+ assert json.loads(decrypted) == payload
27
+
28
+
29
+ def test_encrypt_request_format():
30
+ result = encrypt_request({"key": "value"})
31
+ assert "encryptData" in result
32
+ assert isinstance(result["encryptData"], str)
33
+ # Decrypt and verify
34
+ decrypted = decrypt_response(result["encryptData"])
35
+ assert decrypted == {"key": "value"}
36
+
37
+
38
+ def test_encrypt_empty_object():
39
+ result = encrypt_empty_object()
40
+ assert "encryptData" in result
41
+ decrypted = decrypt_response(result["encryptData"])
42
+ assert decrypted == {}
43
+
44
+
45
+ def test_encrypt_empty_bytes():
46
+ result = encrypt_empty_bytes()
47
+ assert "encryptData" in result
48
+ assert isinstance(result["encryptData"], str)
49
+
50
+
51
+ def test_custom_key():
52
+ key = "0123456789abcdef" # 16 bytes
53
+ encrypted = aes_encrypt("test", key=key)
54
+ assert aes_decrypt(encrypted, key=key) == "test"
@@ -0,0 +1,73 @@
1
+ """Tests for renpho.export — formatting and file export."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from renpho.export import format_measurement, format_timestamp, save_csv, save_json
7
+
8
+
9
+ def test_format_timestamp_seconds():
10
+ # 2024-01-15 12:00:00 UTC
11
+ assert "2024" in format_timestamp(1705320000)
12
+
13
+
14
+ def test_format_timestamp_milliseconds():
15
+ # Should auto-detect and convert ms to s
16
+ result = format_timestamp(1705320000000)
17
+ assert "2024" in result
18
+
19
+
20
+ def test_format_timestamp_none():
21
+ assert format_timestamp(None) == "unknown"
22
+
23
+
24
+ def test_format_measurement_basic():
25
+ m = {"timeStamp": 1705320000, "weight": 75.5, "bmi": 23.1}
26
+ result = format_measurement(m)
27
+ assert "75.5" in result
28
+ assert "23.1" in result
29
+ assert "Weight" in result
30
+ assert "BMI" in result
31
+
32
+
33
+ def test_format_measurement_skips_zero():
34
+ m = {"timeStamp": 1705320000, "weight": 75.5, "bodyfat": 0}
35
+ result = format_measurement(m)
36
+ assert "Body Fat" not in result
37
+
38
+
39
+ def test_save_json(tmp_path):
40
+ data = [{"weight": 70}, {"weight": 71}]
41
+ filepath = tmp_path / "out" / "data.json"
42
+ result = save_json(data, filepath)
43
+ assert result == filepath
44
+ assert filepath.exists()
45
+ loaded = json.loads(filepath.read_text())
46
+ assert loaded == data
47
+
48
+
49
+ def test_save_csv(tmp_path):
50
+ measurements = [
51
+ {"timeStamp": 1000, "weight": 70.5, "bmi": 22},
52
+ {"timeStamp": 2000, "weight": 71.0, "bmi": 22.5},
53
+ ]
54
+ filepath = tmp_path / "data.csv"
55
+ result = save_csv(measurements, filepath)
56
+ assert result == filepath
57
+ lines = filepath.read_text().strip().split("\n")
58
+ assert len(lines) == 3 # header + 2 rows
59
+ assert "timeStamp" in lines[0]
60
+ assert "weight" in lines[0]
61
+
62
+
63
+ def test_save_csv_empty(tmp_path):
64
+ filepath = tmp_path / "empty.csv"
65
+ assert save_csv([], filepath) is None
66
+ assert not filepath.exists()
67
+
68
+
69
+ def test_save_csv_creates_parents(tmp_path):
70
+ measurements = [{"weight": 70}]
71
+ filepath = tmp_path / "nested" / "dir" / "data.csv"
72
+ save_csv(measurements, filepath)
73
+ assert filepath.exists()