Usage of the MQTT-Package

Publishing MQTT Packages

# username and password required to connect to the broker
MQTT_USER = ""
MQTT_PASSWORD = ""

# address, port and virtual host of the broker to connect to
MQTT_BROKER = "127.0.0.1"
MQTT_PORT = 1883

# initialize publisher and connect to the broker
client = mqtt.MQTTPublisher()
client.connect(MQTT_BROKER, MQTT_PORT, MQTT_USER, MQTT_PASSWORD)

# create message and publish the message as UTF-8 encoded string
message = json.dumps({"value": [random.uniform(0, 5) for i in range(3)], "timestamp": datetime.datetime.utcnow().isoformat() + "Z",
                                  "covariance": [[2, 0, 0], [0, 2, 0], [0, 0, 0]], "nonce": str(uuid.uuid4()), "hash": None, "unit": "MTR"})
client.publish(MQTT_USER + "/channel-001", message.encode("utf-8"))

Receiving MQTT Messages

logger = mqtt.root_logger.get('Receiver')

# username and password required to connect to the broker
MQTT_USER = ""
MQTT_PASSWORD = ""

# address, port and virtual host of the broker to connect to
MQTT_BROKER = "127.0.0.1"
MQTT_PORT = 1883
MQTT_VHOST = "/"

topic = "#"  # set topic to subscribe according to MQTT syntax!
qos = 0  # set QoS according to MQTT specifications!


def print_mqtt_message(topic, message):
    logger.info("### {} ###\r\n{}\r\n".format(topic, message.decode("utf-8")))


if __name__ == "__main__":
    client = mqtt.MQTTSubscriber()
    client.connect(MQTT_BROKER, MQTT_PORT, MQTT_USER, MQTT_PASSWORD, vhost=MQTT_VHOST)

    client.set_callback("PRINT", print_mqtt_message)
    client.subscribe(topic, qos)

    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
        break