Skip to content
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

bring http client closes to websocket client #64

Merged
merged 4 commits into from
Jan 8, 2025

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Jan 8, 2025

add on_mycroft

Summary by CodeRabbit

  • Documentation

    • Updated README with rebranded library name "Hivemind Bus Client"
    • Expanded installation and usage instructions
    • Added new code examples for HTTP and WebSocket interactions
    • Introduced "Simple Chat" and "Remote TTS" usage scenarios
  • New Features

    • Enhanced HTTP client with Mycroft message handling
    • Added support for registering and removing Mycroft event handlers
    • Implemented handshake waiting mechanism for client connections
  • Bug Fixes

    • Simplified message key handling
    • Improved message formatting and protocol compatibility

Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

This pull request introduces significant changes to the Hivemind Bus Client library, focusing on rebranding, documentation updates, and enhanced client functionality. The modifications include renaming the package from "Hivemind Websocket Client" to "Hivemind Bus Client", updating README documentation, and improving the HTTP client with new Mycroft message handling capabilities. The changes aim to provide clearer usage instructions and more flexible message handling for developers.

Changes

File Change Summary
README.md - Rebranded from "Hivemind Websocket Client" to "Hivemind Bus Client"
- Updated installation instructions
- Added new usage examples for HTTP and WebSocket protocols
- Introduced "Simple Chat" and "Remote TTS" examples
hivemind_bus_client/http_client.py - Added _agent_handlers for Mycroft message management
- Implemented wait_for_handshake() method
- Added on_mycroft() and remove_mycroft() methods
- Enhanced message handling and emission logic

Sequence Diagram

sequenceDiagram
    participant Client as HiveMindHTTPClient
    participant Server as HiveMind Server
    
    Client->>Server: Initiate Connection
    Client->>Server: Wait for Handshake
    Server-->>Client: Handshake Complete
    Client->>Server: Register Mycroft Handlers
    Client->>Server: Emit Mycroft Message
    Server-->>Client: Process Message
Loading

Possibly related issues

Possibly related PRs

Suggested labels

fix

Poem

🐰 Hop, hop, a client reborn!
Websockets dance, new protocols sworn
Messages fly with Mycroft's might
Hivemind Bus, a coder's delight
Code evolves, rabbit's glee 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@JarbasAl JarbasAl marked this pull request as ready for review January 8, 2025 20:27
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (7)
hivemind_bus_client/http_client.py (5)

81-87: Consider improving handshake timeout handling.

The recursive wait_for_handshake implementation could potentially lead to infinite recursion if the handshake consistently fails. Consider adding a maximum retry count or implementing an exponential backoff strategy.

 def wait_for_handshake(self, timeout=5):
     self.connected.wait(timeout=timeout)
     self.handshake_event.wait(timeout=timeout)
     if not self.handshake_event.is_set():
+        max_retries = 3  # Add max retries
+        if not hasattr(self, '_handshake_attempts'):
+            self._handshake_attempts = 0
+        self._handshake_attempts += 1
+        if self._handshake_attempts >= max_retries:
+            raise ConnectionError("Failed to establish handshake after maximum retries")
         self.protocol.start_handshake()
         self.wait_for_handshake()
+        self._handshake_attempts = 0  # Reset counter on successful handshake
     time.sleep(1) # let server process our "hello" response

265-268: Add type hints for better code maintainability.

Consider adding type hints to improve code maintainability and IDE support.

-    def on_mycroft(self, event_name: str, func: Callable):
+    def on_mycroft(self, event_name: str, func: Callable[[MycroftMessage], None]) -> None:
         if event_name not in self._agent_handlers:
             self._agent_handlers[event_name] = []
         self._agent_handlers[event_name].append(func)

225-230: Enhance error handling with more context.

The error handling could be more informative by including the event name and message details in the error log.

 if message.msg_type == HiveMessageType.BUS and message.payload.msg_type in self._agent_handlers:
     for handler in self._agent_handlers[message.payload.msg_type]:
         try:
             handler(message.payload)
         except Exception as e:
-            LOG.error(f"Error in agent message handler: {handler} - {e}")
+            LOG.error(f"Error in agent message handler for event '{message.payload.msg_type}': {handler.__name__} - {e}")
+            LOG.debug(f"Message payload: {message.payload}")

434-437: Avoid using global variables in example code.

The example code uses global variables which is not a recommended practice. Consider using a class to manage state.

+class ChatHandler:
+    def __init__(self):
+        self.answer = None
+        self.answered = threading.Event()
+
+    def handle_speak(self, message: MycroftMessage):
+        self.answer = message.data['utterance']
+
+    def utt_handled(self, message: MycroftMessage):
+        self.answered.set()

398-399: Consider using a more verbose log level for development.

Setting the log level to "ERROR" might hide important debugging information. Consider using "INFO" or "DEBUG" during development.

 init_service_logger("HiveMindHTTP")
-LOG.set_level("ERROR")
+LOG.set_level("INFO")  # Use more verbose logging during development
README.md (2)

13-14: Add links to protocol documentation.

Consider adding links to protocol documentation or specifications to help users understand the differences between HTTP and WebSocket protocols.


54-60: Add error handling examples in documentation.

The chat example could benefit from showing how to handle connection errors and timeouts.

try:
    client.emit(HiveMessage(HiveMessageType.BUS,
                Message("recognizer_loop:utterance", {"utterances": [utt]})))
    if not answered.wait(timeout=30):  # Add timeout
        print("Timeout waiting for response")
except ConnectionError as e:
    print(f"Connection error: {e}")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc32a4c and 40d4810.

📒 Files selected for processing (2)
  • README.md (2 hunks)
  • hivemind_bus_client/http_client.py (8 hunks)

@JarbasAl JarbasAl merged commit f4dca85 into dev Jan 8, 2025
2 checks passed
@JarbasAl JarbasAl deleted the feat/http_clientimprove branch January 8, 2025 21:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant