randomsync / robotframework-mqttlibrary

MQTT Keyword Library for Robot Framework
Apache License 2.0
25 stars 30 forks source link

Payloads without topics #32

Open DanielHJacobsen opened 7 months ago

DanielHJacobsen commented 7 months ago

From a subscribing to a wildcard-topic (#) cannot be determined from which topic a message received from.

Known which topic a message is received from would be a useful feature. Especially when the topics include auto-generated IDs.(cannot be predicted)

For now I have created my own implementation for this issue with the _on_message_list-method:

def _on_message_list(self, client, userdata, message):
    payload = message.payload.decode('utf-8')
    logger.debug('Received message: %s on topic: %s with QoS: %s' % (payload, message.topic, str(message.qos)))
    if message.topic not in self._messages: 
        self._messages[message.topic] = []
    for sub in self._messages:
        if topic_matches_sub(sub, message.topic):
            appended_msg = '{"topic":"' + topic + '", "payload":' + payload + '}' if self._is_returning_topic_n_value else payload
            self._messages[sub].append(appended_msg)

The messages are returned in JSON-format:

{
   "topic": "some/mqtt/topic/ID", 
   "payload": "payload", 
}

The _is_returning_topic_n_value-field is set within the connection. Default is False (To avoid breaking change)

def connect(self, broker, port=1883, client_id="", clean_session=True, is_returning_topic_n_value=False):
    ...
    """
    `is_returning_topic_n_value` specifies the format of the returned messages on subscription. Either just the values within the topics or the topics and values.
    """
    ...
    self._is_returning_topic_n_value = is_returning_topic_n_value

I hope this helps.

Best regards Daniel