-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathwithings_client.py
More file actions
256 lines (203 loc) · 8.31 KB
/
Copy pathwithings_client.py
File metadata and controls
256 lines (203 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""Simplified Withings client using .env configuration."""
import json
import logging
import os
import time
from datetime import datetime
from typing import Dict, List, Optional
import requests
logger = logging.getLogger(__name__)
AUTHORIZE_URL = "https://account.withings.com/oauth2_user/authorize2"
TOKEN_URL = "https://wbsapi.withings.net/v2/oauth2"
GETMEAS_URL = "https://wbsapi.withings.net/measure?action=getmeas"
class WithingsException(Exception):
"""Exception for Withings API errors."""
pass
class WithingsClient:
"""Simplified Withings client using .env configuration."""
def __init__(self):
# Load configuration from environment variables
self.client_id = os.getenv("WITHINGS_CLIENT_ID")
self.client_secret = os.getenv("WITHINGS_CLIENT_SECRET")
self.callback_url = os.getenv(
"WITHINGS_CALLBACK_URL", "http://localhost:8080/callback"
)
if not self.client_id or not self.client_secret:
raise WithingsException(
"Missing required environment variables:"
" WITHINGS_CLIENT_ID, WITHINGS_CLIENT_SECRET"
)
# User tokens file - store in project directory
self.tokens_file = ".withings_tokens.json"
self.tokens = self._load_tokens()
# Ensure we have valid tokens
self._ensure_authenticated()
def _load_tokens(self) -> Dict:
"""Load tokens from file."""
try:
with open(self.tokens_file, "r") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def _save_tokens(self):
"""Save tokens to file."""
with open(self.tokens_file, "w") as f:
json.dump(self.tokens, f, indent=2)
def _ensure_authenticated(self):
"""Ensure we have valid authentication tokens."""
if not self.tokens.get("access_token"):
if not self.tokens.get("auth_code"):
self.tokens["auth_code"] = self._get_auth_code()
self._get_access_token()
# Try to refresh token
self._refresh_access_token()
self._save_tokens()
def _get_auth_code(self) -> str:
"""Get authorization code from user."""
params = {
"response_type": "code",
"client_id": self.client_id,
"state": "OK",
"scope": "user.metrics",
"redirect_uri": self.callback_url,
}
url = AUTHORIZE_URL + "?" + "&".join([f"{k}={v}" for k, v in params.items()])
print("\n" + "=" * 60)
print("WITHINGS AUTHORIZATION REQUIRED")
print("=" * 60)
print("Open this URL in your browser and copy the authorization code:")
print(f"\n{url}\n")
print("You have 30 seconds to complete this process!")
print("=" * 60)
auth_code = input("Enter authorization code: ").strip()
if not auth_code:
raise WithingsException("No authorization code provided")
return auth_code
def _get_access_token(self):
"""Exchange authorization code for access token."""
params = {
"action": "requesttoken",
"grant_type": "authorization_code",
"client_id": self.client_id,
"client_secret": self.client_secret,
"code": self.tokens["auth_code"],
"redirect_uri": self.callback_url,
}
response = requests.post(TOKEN_URL, params=params)
data = response.json()
if data.get("status") != 0:
raise WithingsException(f"Token request failed: {data}")
body = data.get("body", {})
self.tokens.update(
{
"access_token": body.get("access_token"),
"refresh_token": body.get("refresh_token"),
"user_id": body.get("userid"),
}
)
logger.info("Successfully obtained access token")
def _refresh_access_token(self):
"""Refresh the access token."""
if not self.tokens.get("refresh_token"):
return
params = {
"action": "requesttoken",
"grant_type": "refresh_token",
"client_id": self.client_id,
"client_secret": self.client_secret,
"refresh_token": self.tokens["refresh_token"],
}
response = requests.post(TOKEN_URL, params=params)
data = response.json()
if data.get("status") == 0:
body = data.get("body", {})
self.tokens.update(
{
"access_token": body.get("access_token"),
"refresh_token": body.get("refresh_token"),
"user_id": body.get("userid"),
}
)
logger.info("Successfully refreshed access token")
else:
logger.warning(f"Token refresh failed: {data}")
def get_measurements(self, start_date: datetime, end_date: datetime) -> List[Dict]:
"""Get measurements from Withings API."""
params = {
"access_token": self.tokens["access_token"],
"category": 1, # All measurements
"startdate": int(start_date.timestamp()),
"enddate": int(end_date.timestamp()),
}
response = requests.post(GETMEAS_URL, params=params)
data = response.json()
if data.get("status") != 0:
raise WithingsException(f"Measurements request failed: {data}")
measurements = data.get("body", {}).get("measuregrps", [])
logger.info(f"Retrieved {len(measurements)} measurement groups")
return self._process_measurements(measurements)
def get_height(self) -> Optional[float]:
"""Get user's height."""
params = {
"access_token": self.tokens["access_token"],
"meastype": 4, # Height type
"category": 1,
}
response = requests.post(GETMEAS_URL, params=params)
data = response.json()
if data.get("status") != 0:
return None
measurements = data.get("body", {}).get("measuregrps", [])
if not measurements:
return None
# Get the latest height measurement
latest_height = None
latest_date = None
for group in measurements:
for measure in group.get("measures", []):
if measure.get("type") == 4: # Height
value = measure["value"] * (10 ** measure["unit"])
date = datetime.fromtimestamp(group["date"])
if latest_date is None or date > latest_date:
latest_height = value
latest_date = date
return latest_height
def _process_measurements(self, raw_measurements: List[Dict]) -> List[Dict]:
"""Process raw measurements into structured format."""
processed = []
for group in raw_measurements:
timestamp = datetime.fromtimestamp(group["date"])
measurements = {}
for measure in group.get("measures", []):
value = measure["value"] * (10 ** measure["unit"])
measure_type = measure["type"]
# Map measurement types to readable names
type_mapping = {
1: "weight",
4: "height",
5: "fat_free_mass",
6: "fat_ratio",
8: "fat_mass_weight",
9: "diastolic_bp",
10: "systolic_bp",
11: "heart_rate",
12: "temperature",
76: "muscle_mass",
77: "hydration",
88: "bone_mass",
}
if measure_type in type_mapping:
measurements[type_mapping[measure_type]] = round(value, 2)
if measurements:
processed.append({"timestamp": timestamp, "measurements": measurements})
return processed
def get_last_sync(self) -> int:
"""Get last sync timestamp."""
return self.tokens.get(
"last_sync", int(time.time()) - 86400
) # Default to 24h ago
def set_last_sync(self):
"""Set last sync timestamp to now."""
self.tokens["last_sync"] = int(time.time())
self._save_tokens()
logger.info("Updated last sync timestamp")