-
Notifications
You must be signed in to change notification settings - Fork 0
Maintenance: dependency updates and bug fixes #79
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
eman
wants to merge
10
commits into
main
Choose a base branch
from
maintenance/bug-fixes
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 all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4e287bd
Maintenance: fix hypothesis import and bump awsiotsdk minimum version
eman 8074d14
Bug hunt fixes: 5 bugs corrected
eman eaaa6f3
Address PR review feedback
eman 3592b48
Update changelog with unreleased maintenance fixes
eman f150f33
Fix timezone-naive datetimes, duplicate MQTT resubscribe; add firmwar…
eman 3122c8f
Potential fix for pull request finding 'CodeQL / Clear-text logging o…
eman cb0ee20
Potential fix for pull request finding 'CodeQL / Clear-text logging o…
eman eea01f5
Potential fix for pull request finding 'CodeQL / Clear-text logging o…
eman 5f7c30d
Fix firmware_payload_capture: restore mac variable, use redact() for …
eman 96716fa
Fix timezone-naive issued_at backward compat and BaseException in fac…
eman 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
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,211 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Firmware Payload Capture Tool. | ||
|
|
||
| Captures raw MQTT payloads for all scheduling-related topics and dumps them | ||
| to a timestamped JSON file. Use this to detect changes introduced by firmware | ||
| updates by diffing captures taken before and after an update. | ||
|
|
||
| Specifically captures: | ||
| - Weekly reservations (rsv/rd) | ||
| - Time-of-Use schedule (tou/rd) | ||
| - Device info (firmware versions, capabilities) | ||
| - Device status (current operating state) | ||
| - All other response/event topics (via wildcards) | ||
|
|
||
| Usage: | ||
| NAVIEN_EMAIL=your@email.com NAVIEN_PASSWORD=password python3 firmware_payload_capture.py | ||
|
|
||
| Output: | ||
| payload_capture_YYYYMMDD_HHMMSS.json — all captured payloads with topics | ||
| and timestamps. Sensitive fields | ||
| (MAC address, session IDs, client | ||
| IDs) are redacted in the output. | ||
|
|
||
| Comparing two captures to find firmware changes: | ||
| diff <(jq '.payloads[] | select(.topic | contains("rsv"))' before.json) \\ | ||
| <(jq '.payloads[] | select(.topic | contains("rsv"))' after.json) | ||
| """ | ||
|
|
||
| import asyncio | ||
| import json | ||
| import logging | ||
| import os | ||
| import sys | ||
| from datetime import UTC, datetime | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from nwp500 import NavienAPIClient, NavienAuthClient, NavienMqttClient | ||
| from nwp500.models import DeviceFeature | ||
| from nwp500.mqtt.utils import redact, redact_topic | ||
| from nwp500.topic_builder import MqttTopicBuilder | ||
|
|
||
| logging.basicConfig( | ||
| level=logging.WARNING, | ||
| format="%(asctime)s %(levelname)s %(name)s: %(message)s", | ||
| ) | ||
| _logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class PayloadCapture: | ||
| """Captures and records raw MQTT payloads.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self.payloads: list[dict[str, Any]] = [] | ||
|
|
||
| def record(self, topic: str, message: dict[str, Any]) -> None: | ||
| entry = { | ||
| "timestamp": datetime.now(UTC).isoformat(), | ||
| "topic": topic, | ||
| "payload": message, | ||
| } | ||
| self.payloads.append(entry) | ||
| print(f" ← {redact_topic(topic)}") | ||
|
|
||
| def save(self, path: Path) -> None: | ||
| # Redact sensitive fields (MAC, session IDs, client IDs) before saving | ||
| # so the output file is safe to share. Protocol structure and payload | ||
| # field values used for firmware analysis are preserved. | ||
| redacted_payloads = [ | ||
| { | ||
| "timestamp": e["timestamp"], | ||
| "topic": redact_topic(e["topic"]), | ||
| "payload": redact(e["payload"]), | ||
| } | ||
| for e in self.payloads | ||
| ] | ||
| data = { | ||
| "captured_at": datetime.now(UTC).isoformat(), | ||
| "total_payloads": len(self.payloads), | ||
| "payloads": redacted_payloads, | ||
| } | ||
| path.write_text(json.dumps(data, indent=2, default=str)) | ||
| print(f"\nSaved {len(self.payloads)} payloads → {path}") | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| email = os.getenv("NAVIEN_EMAIL") | ||
| password = os.getenv("NAVIEN_PASSWORD") | ||
|
|
||
| if not email or not password: | ||
| print("Error: set NAVIEN_EMAIL and NAVIEN_PASSWORD environment variables") | ||
| sys.exit(1) | ||
|
|
||
| capture = PayloadCapture() | ||
|
|
||
| async with NavienAuthClient(email, password) as auth_client: | ||
| api_client = NavienAPIClient(auth_client=auth_client) | ||
| device = await api_client.get_first_device() | ||
| if not device: | ||
| print("No devices found for this account") | ||
| return | ||
|
|
||
| device_type = str(device.device_info.device_type) | ||
| mac = device.device_info.mac_address | ||
| print(f"Device: {device.device_info.device_name} [{device_type}]") | ||
|
|
||
| mqtt_client = NavienMqttClient(auth_client) | ||
| await mqtt_client.connect() | ||
|
|
||
| client_id = mqtt_client.client_id | ||
|
|
||
| # --- Wildcard subscriptions to catch everything --- | ||
|
|
||
| # All response messages back to this client | ||
| res_wildcard = MqttTopicBuilder.response_topic(device_type, client_id, "#") | ||
| # All event messages pushed by the device | ||
| evt_wildcard = MqttTopicBuilder.event_topic(device_type, mac, "#") | ||
|
|
||
eman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| print( | ||
| f"\nSubscribing to:\n {redact_topic(res_wildcard)}\n" | ||
| f" {redact_topic(evt_wildcard)}\n" | ||
Check failureCode scanning / CodeQL Clear-text logging of sensitive information High
This expression logs
sensitive data (private) Error loading related location Loading This expression logs sensitive data (private) Error loading related location Loading This expression logs sensitive data (private) Error loading related location Loading |
||
eman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
| print("Captured topics:") | ||
|
|
||
| await mqtt_client.subscribe(res_wildcard, capture.record) | ||
| await mqtt_client.subscribe(evt_wildcard, capture.record) | ||
|
|
||
| # --- Step 1: fetch device info (needed for firmware version + serial) --- | ||
| device_info_event: asyncio.Event = asyncio.Event() | ||
| device_feature: DeviceFeature | None = None | ||
|
|
||
| def on_feature(feature: DeviceFeature) -> None: | ||
| nonlocal device_feature | ||
| device_feature = feature | ||
| device_info_event.set() | ||
|
|
||
| await mqtt_client.subscribe_device_feature(device, on_feature) | ||
| await mqtt_client.control.request_device_info(device) | ||
| await asyncio.wait_for(device_info_event.wait(), timeout=30.0) | ||
|
|
||
| if device_feature: | ||
| print( | ||
| f"\nFirmware: controller={device_feature.controller_sw_version} " | ||
| f"panel={device_feature.panel_sw_version} " | ||
| f"wifi={device_feature.wifi_sw_version}" | ||
| ) | ||
|
|
||
| # --- Step 2: request device status --- | ||
| await mqtt_client.control.request_device_status(device) | ||
| await asyncio.sleep(3) | ||
|
|
||
| # --- Step 3: request reservation (weekly) schedule --- | ||
| print("\nRequesting weekly reservation schedule...") | ||
| await mqtt_client.control.request_reservations(device) | ||
| await asyncio.sleep(5) | ||
|
|
||
| # --- Step 4: request TOU schedule (requires controller serial number) --- | ||
| if device_feature and device_feature.program_reservation_use: | ||
| serial = device_feature.controller_serial_number | ||
| if serial: | ||
| print("Requesting TOU schedule...") | ||
| try: | ||
| await mqtt_client.control.request_tou_settings(device, serial) | ||
| await asyncio.sleep(5) | ||
| except Exception as exc: | ||
| print(f" TOU request failed: {exc}") | ||
|
|
||
| # --- Step 5: wait a bit more to catch any late-arriving messages --- | ||
| print("\nWaiting for any remaining messages...") | ||
| await asyncio.sleep(5) | ||
|
|
||
| await mqtt_client.disconnect() | ||
|
|
||
| # --- Save results --- | ||
| timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S") | ||
| output_path = Path(f"payload_capture_{timestamp}.json") | ||
| capture.save(output_path) | ||
|
|
||
| # Print a summary grouped by topic | ||
| print("\n--- Summary by topic ---") | ||
| by_topic: dict[str, int] = {} | ||
| for entry in capture.payloads: | ||
| by_topic[entry["topic"]] = by_topic.get(entry["topic"], 0) + 1 | ||
| for topic, count in sorted(by_topic.items()): | ||
| print(f" {count:2d}x {redact_topic(topic)}") | ||
|
|
||
| if device_feature: | ||
| print( | ||
| f"\nFirmware captured: controller_sw_version=" | ||
| f"{device_feature.controller_sw_version}" | ||
| ) | ||
| print( | ||
| "Compare this file against a capture from a different firmware version " | ||
| "to detect scheduling changes.\n" | ||
| "Useful diff command:\n" | ||
| " diff <(jq '.payloads[] | select(.topic | contains(\"rsv\"))' " | ||
| f"before.json) \\\n" | ||
| " <(jq '.payloads[] | select(.topic | contains(\"rsv\"))' " | ||
| f"{output_path})" | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| try: | ||
| asyncio.run(main()) | ||
| except KeyboardInterrupt: | ||
| print("\nCancelled by user") | ||
| except TimeoutError: | ||
| print("\nError: timed out waiting for device response. Is the device online?") | ||
| sys.exit(1) | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.