-
Notifications
You must be signed in to change notification settings - Fork 95
Add support for receiving basic fragmented messages #669
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
52f5382
add basic fragmentation support
tkulin ea38115
add basic fragmentation support (remembering to cleanup leftover frag…
tkulin 04ae89b
code cleanup and improved partial fragment removal
tkulin c91fd30
minor change to frag ack callback handling, added test case for fragm…
tkulin 13c376a
added more tests
tkulin e94d817
Use generic types in favor of `typing`
puddly 74f26cf
Use an instance-specific fragment manager instance instead of a global
puddly 034be12
Keep track of fragmentation ACK tasks in an instance variable
puddly 08bd4d3
Clean up formatting a little
puddly 6f2fcc0
Fix unit tests
puddly 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 |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| """ | ||
| Implements APS fragmentation reassembly on the EZSP Host side, | ||
| mirroring the logic from fragmentation.c in the EmberZNet stack. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import logging | ||
| from collections import defaultdict | ||
| from typing import Optional, Dict, Tuple | ||
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
| # The maximum time (in seconds) we wait for all fragments of a given message. | ||
| # If not all fragments arrive within this time, we discard the partial data. | ||
| FRAGMENT_TIMEOUT = 10 | ||
|
|
||
| # store partial data keyed by (sender, aps_sequence, profile_id, cluster_id) | ||
| FragmentKey = Tuple[int, int, int, int] | ||
|
|
||
| class _FragmentEntry: | ||
| def __init__(self, fragment_count: int): | ||
| self.fragment_count = fragment_count | ||
| self.fragments_received = 0 | ||
| self.fragment_data = {} | ||
| self.start_time = asyncio.get_event_loop().time() | ||
|
|
||
| def add_fragment(self, index: int, data: bytes) -> None: | ||
| if index not in self.fragment_data: | ||
| self.fragment_data[index] = data | ||
| self.fragments_received += 1 | ||
|
|
||
| def is_complete(self) -> bool: | ||
| return self.fragments_received == self.fragment_count | ||
|
|
||
| def assemble(self) -> bytes: | ||
| return b''.join(self.fragment_data[i] for i in sorted(self.fragment_data.keys())) | ||
|
|
||
| class FragmentManager: | ||
| def __init__(self): | ||
| self._partial: Dict[FragmentKey, _FragmentEntry] = {} | ||
|
|
||
| def handle_incoming_fragment(self, sender_nwk: int, aps_sequence: int, profile_id: int, cluster_id: int, | ||
| group_id: int, payload: bytes) -> Tuple[bool, Optional[bytes], int, int]: | ||
| """ | ||
| Handle a newly received fragment. The group_id field | ||
| encodes high byte = total fragment count, low byte = current fragment index. | ||
|
|
||
| :param sender_nwk: NWK address or the short ID of the sender. | ||
| :param aps_sequence: The APS sequence from the incoming APS frame. | ||
| :param profile_id: The APS frame's profileId. | ||
| :param cluster_id: The APS frame's clusterId. | ||
| :param group_id: The APS frame's groupId (used to store fragment # / total). | ||
| :param payload: The fragment of data for this message. | ||
| :return: (complete, reassembled_data, fragment_count, fragment_index) | ||
| complete = True if we have all fragments now, else False | ||
| reassembled_data = the final complete payload (bytes) if complete is True | ||
| fragment_coutn = the total number of fragments holding the complete packet | ||
| fragment_index = the index of the current received fragment | ||
| """ | ||
| fragment_count = (group_id >> 8) & 0xFF | ||
| fragment_index = group_id & 0xFF | ||
|
|
||
| key: FragmentKey = (sender_nwk, aps_sequence, profile_id, cluster_id) | ||
|
|
||
| # If we have never seen this message, create a reassembly entry. | ||
| if key not in self._partial: | ||
| entry = _FragmentEntry(fragment_count) | ||
| self._partial[key] = entry | ||
| else: | ||
| entry = self._partial[key] | ||
|
|
||
| LOGGER.debug("Received fragment %d/%d from %s (APS seq=%d, cluster=0x%04X)", | ||
| fragment_index, fragment_count, sender_nwk, aps_sequence, cluster_id) | ||
|
|
||
| entry.add_fragment(fragment_index, payload) | ||
|
|
||
| if entry.is_complete(): | ||
| reassembled = entry.assemble() | ||
| del self._partial[key] | ||
| LOGGER.debug("Message reassembly complete. Total length=%d", len(reassembled)) | ||
| return (True, reassembled, fragment_count, fragment_index) | ||
| else: | ||
| return (False, None, fragment_count, fragment_index) | ||
|
|
||
| def cleanup_expired(self) -> None: | ||
puddly marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| now = asyncio.get_event_loop().time() | ||
| to_remove = [] | ||
| for k, entry in self._partial.items(): | ||
| if now - entry.start_time > FRAGMENT_TIMEOUT: | ||
| to_remove.append(k) | ||
| for k in to_remove: | ||
| del self._partial[k] | ||
| LOGGER.debug("Removed stale fragment reassembly for key=%s", k) | ||
|
|
||
| # Create a single global manager instance | ||
| fragment_manager = FragmentManager() | ||
|
|
||
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.
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.