Skip to content

src/robot/mqtt & mqtt_client.py #33

Closed

Description

@KavinduMethpura
No description provided.

Activity

  1. changed the title [-]src/robot/mqtt[/-] [+]src/robot/mqtt & mqtt_client.py[/+] on Nov 5, 2025
  2. TharinduHimantha commented on Nov 13, 2025

    @TharinduHimantha

    Reviewed

  3. Rinali-P commented on Nov 14, 2025

    @Rinali-P

    In src/robot/mqtt/init.py :
    Provides clear package exports, and requires no modifications.

    In src/robot/mqtt/mqtt_msg.py :
    MODIFICATION #1: Make _next_id thread-safe to prevent race conditions when multiple threads create messages simultaneously.

    import threading
    
    class MqttMsg:
        _next_id = 0
        _lock = threading.Lock()
    
        def __init__(self, topic: str, message: str, qos: int = 0):
            # Thread-safe ID increment
            with MqttMsg._lock:
                self.id = MqttMsg._next_id
                MqttMsg._next_id += 1
    
            self.topic = topic
            self.message = message
            self.topic_groups = topic.split("/")
            self.channel = self.topic_groups[0] if len(self.topic_groups) > 1 else ""
            self.qos = qos
    

    In src/robot/mqtt/robot_mqtt_client.py :

    Problem: Connection is not guaranteed yet. Should wait for _on_connect callback to confirm success.

    MODIFICATION #1: Set _connected = True only after successful connection in _on_connect(). (set _connected = True only in _on_connect())

    def _connect(self):
        try:
            if self.user_name:
                self._client.username_pw_set(self.user_name, self.password)
            self._client.connect(self.server, self.port, keepalive=60)
            self._client.loop_start()
            print("Connecting to MQTT broker...")
        except Exception as e:
            print(f"MQTT connection error: {e}")
    
    def _on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            self._connected = True
        else:
            print(f"MQTT: Connection failed with code {rc}")
    

    MODIFICATION #2: Add automatic reconnect in _on_disconnect() to handle network drops.

    def _on_disconnect(self, client, userdata, rc):
        self._connected = False
        print("Connection lost, retrying...")
        while not self._connected:
            try:
                self._client.reconnect()
            except Exception:
                time.sleep(5)
    

    MODIFICATION #3: Validate QoS values in publish() or subscribe(). By validating the value before sending, the client prevents invalid QoS settings that would otherwise cause broker errors or message delivery failures.

    if qos not in [0, 1, 2]:
        raise ValueError("QoS must be 0, 1, or 2")
    
  4. TharinduHimantha commented on Nov 15, 2025

    @TharinduHimantha

    When a custom robot is created as an object, it fails with an exception since topic "v1/localization/update" doesn't exist during the very first instance. Therefore, initially a message had to be published to the mentioned topic before testing #my_test_robot.py in order to work as intended.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions