-
Notifications
You must be signed in to change notification settings - Fork 23
improvements to HR demo for HN video #2362
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
armanjindal
wants to merge
6
commits into
main
Choose a base branch
from
hr-demo-hn-update
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4836010
improvements to HR demo for HN video
b0775da
added the simple apple watch BT client
9cd18b3
Merge branch 'main' into hr-demo-hn-update
armanjindal 588b9dc
working bt client
d2e8143
fix readme
fcb1d35
update readme again
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -38,4 +38,5 @@ wheels | |
| *.egg-info/ | ||
| .installed.cfg | ||
| *.egg | ||
| MANIFEST | ||
| MANIFEST | ||
| .cursor | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 7 additions & 0 deletions
7
templates/live-heartrate-leaderboard/app/datamodels/AppleWatchHRPacket.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| from pydantic import BaseModel | ||
| from moose_lib import Key | ||
| from typing import List | ||
|
|
||
| class AppleWatchHRPacket(BaseModel): | ||
| device_id: Key[str] | ||
| heart_rate_data: int |
4 changes: 3 additions & 1 deletion
4
templates/live-heartrate-leaderboard/app/datamodels/RawAntHRPacket.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,9 @@ | ||
| from pydantic import BaseModel | ||
| from moose_lib import Key | ||
| from typing import Optional | ||
|
|
||
| class RawAntHRPacket(BaseModel): | ||
| device_id: Key[int] | ||
| packet_count: int | ||
| ant_hr_packet: list[int] | ||
| ant_hr_packet: list[int] | ||
| timestamp: Optional[float] = None |
3 changes: 2 additions & 1 deletion
3
templates/live-heartrate-leaderboard/app/datamodels/UnifiedHRPacket.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,15 @@ | ||
| from moose_lib import Key | ||
| from pydantic import BaseModel | ||
| from datetime import datetime | ||
| from typing import Optional | ||
|
|
||
| class UnifiedHRPacket(BaseModel): | ||
| user_id: Key[int] | ||
| user_name: str | ||
| device_id: int | ||
| hr_timestamp_seconds: float | ||
| hr_value: float | ||
| rr_interval_ms: float | ||
| rr_interval_ms: Optional[float] | ||
| processed_timestamp: datetime | ||
| # hr_max: float | ||
| # hr_zone: int |
48 changes: 48 additions & 0 deletions
48
templates/live-heartrate-leaderboard/app/functions/applewatch_to_unified_packet.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| from app.datamodels.AppleWatchHRPacket import AppleWatchHRPacket | ||
| from app.datamodels.UnifiedHRPacket import UnifiedHRPacket | ||
| from typing import Optional | ||
| from datetime import datetime, timezone | ||
| from pathlib import Path | ||
| import json | ||
| from moose_lib import Logger, Key | ||
|
|
||
| def load_device_dict(): | ||
| json_path = Path(__file__).parents[2] / 'mock-user-db.json' | ||
| logger = Logger(action="SF") | ||
| # logger.info(f'Starting streaming function and loading mock user db from {json_path}') | ||
|
|
||
| with open(json_path) as f: | ||
| device_dict = json.load(f) | ||
| # Filter to only include devices marked as live bluetooth devices | ||
| device_dict = {k: v for k, v in device_dict.items() if v.get('live_bt_device') == "True"} | ||
|
|
||
| return device_dict | ||
|
|
||
| all_bluetooth_device_dict = load_device_dict() | ||
|
|
||
| logger = Logger(action="SF") | ||
| # logger.info(f'all_bluetooth_device_dict: {all_bluetooth_device_dict}') | ||
|
|
||
| # Capture the moment this module is first imported as the streaming start time (UTC) | ||
| stream_start_time = datetime.now(timezone.utc) | ||
| # logger.info(f"Apple Watch streaming function start time: {stream_start_time.isoformat()}") | ||
|
|
||
| def apple_watch_to_unified(source: AppleWatchHRPacket) -> UnifiedHRPacket: | ||
| device_id_str = str(source.device_id) | ||
| device_dict = all_bluetooth_device_dict[device_id_str] | ||
| logger.info(f"device_dict: {device_dict}") | ||
| user_name = device_dict.get('user_name') | ||
| user_id = device_dict.get('user_id') # This should already be an integer | ||
|
|
||
| # Time elapsed (in seconds) since the streaming function/module was first loaded | ||
| elapsed_seconds = (datetime.now(timezone.utc) - stream_start_time).total_seconds() | ||
|
|
||
| return UnifiedHRPacket( | ||
| user_id=user_id, # UnifiedHRPacket will handle the Key[int] conversion | ||
| user_name=user_name, | ||
| device_id=user_id, # Convert to plain int | ||
| hr_timestamp_seconds=elapsed_seconds, | ||
| hr_value=source.heart_rate_data, | ||
| rr_interval_ms=0, # not included in apple watch | ||
| processed_timestamp=datetime.now(timezone.utc), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
83 changes: 83 additions & 0 deletions
83
...s/live-heartrate-leaderboard/app/scripts/apple_watch_hr_client/apple_heart_rate_client.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| #!/usr/bin/env python3 | ||
| # Requirements: bleak, requests | ||
| import asyncio | ||
| from bleak import BleakScanner, BleakClient | ||
| import requests | ||
| from moose_lib import task, Logger | ||
|
|
||
| HEART_RATE_CHAR_UUID = "00002a37-0000-1000-8000-00805f9b34fb" | ||
| INGEST_URL = "http://localhost:4000/ingest/apple_health_watch_packet" | ||
|
|
||
| def parse_heart_rate(data): | ||
| # Standard BLE Heart Rate Measurement characteristic parsing | ||
| # See: https://www.bluetooth.com/specifications/specs/heart-rate-profile-1-0/ | ||
| flag = data[0] | ||
| hr_format = flag & 0x01 | ||
| if hr_format == 0: | ||
| hr_value = data[1] | ||
| else: | ||
| hr_value = int.from_bytes(data[1:3], byteorder='little') | ||
| return hr_value | ||
|
|
||
| @task | ||
| async def apple_watch_hr_client(): | ||
| logger = Logger("apple_watch_hr_client") | ||
| logger.info("Scanning for Apple Watch devices...") | ||
| devices = await BleakScanner.discover() | ||
| if not devices: | ||
| logger.error("No BLE devices found.") | ||
| return | ||
|
|
||
| device = None | ||
| for d in devices: | ||
| if d.name and "iphone" in d.name.lower(): | ||
| device = d | ||
| break | ||
|
|
||
| if not device: | ||
| logger.error("No iPhone found. Available devices:") | ||
| for d in devices: | ||
| logger.info(f" {d.name} ({d.address})") | ||
| return | ||
|
|
||
| logger.info(f"Connecting to: {device.name} ({device.address})") | ||
|
|
||
| async with BleakClient(device) as client: | ||
| logger.info(f"Connected: {client.is_connected}") | ||
|
|
||
| def hr_callback(sender, data): | ||
| try: | ||
| heart_rate = parse_heart_rate(data) | ||
| payload = { | ||
| "device_id": device.address, | ||
| "heart_rate_data": heart_rate | ||
| } | ||
| response = requests.post(INGEST_URL, json=payload) | ||
| if response.status_code == 200: | ||
| logger.info(f"Sent: {payload}") | ||
| else: | ||
| logger.error(f"Failed to send data: {response.status_code} {response.text}") | ||
| except Exception as e: | ||
| logger.error(f"Error in callback: {e}") | ||
|
|
||
| logger.info(f"Subscribing to heart rate notifications on {HEART_RATE_CHAR_UUID}...") | ||
| try: | ||
| await client.start_notify(HEART_RATE_CHAR_UUID, hr_callback) | ||
| except Exception as e: | ||
| logger.error(f"Error subscribing to heart rate notifications: {e}") | ||
| return | ||
| logger.info("Subscribed! Waiting for data...") | ||
| try: | ||
| while True: | ||
| await asyncio.sleep(1) | ||
| except KeyboardInterrupt: | ||
| logger.info("Disconnecting...") | ||
| await client.stop_notify(HEART_RATE_CHAR_UUID) | ||
| logger.info("Disconnected.") | ||
|
|
||
| return { | ||
| "task": "apple_watch_hr_client", | ||
| "data": { | ||
| "device_id": device.address | ||
| } | ||
| } |
5 changes: 5 additions & 0 deletions
5
templates/live-heartrate-leaderboard/app/scripts/apple_watch_hr_client/config.toml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| name = 'apple_watch_hr_client' | ||
| schedule = '' | ||
| retries = 3 | ||
| timeout = '1h' | ||
| tasks = ['apple_watch_hr_client'] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo in comment: correct "Appple" to "Apple".
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch