def mqtt(self): if not hasattr(self, '_mqtt_client'): self.responses = {} self.ready = False client = MQTTClient() client.username_pw_set(self.apikey) client.on_connect = self._on_connect client.on_message = self._on_message client.on_subscribe = self._on_subscribe client.connect(self.client.endpoint.replace('mqtt://', '')) self._mqtt_client = client # Start the loop and wait for the connection to be ready self._mqtt_client.loop_start() while not self.ready: time.sleep(.1) return self._mqtt_client
retain=True) def on_publish(mqttc, obj, mid): print("on publish") def on_subscribe(mqttc, obj, mid, granted_qos): pass def on_log(mqttc, obj, level, string): print(string) mqttc = Client() mqttc.on_message = on_message mqttc.on_connect = on_connect mqttc.on_publish = on_publish mqttc.on_subscribe = on_subscribe mqttc.connect("localhost", 1883, 60) sleep(0.5) mqttc.subscribe("/sparti/android/sleep", 0) sleep(0.5) mqttc.loop_forever()
print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("my/test") def on_subscribe(client, userdata, mid, granted_qos): print(f'subscribed to topic: {mid}') # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) client = Client() client.on_connect = on_connect client.on_message = on_message client.on_subscribe = on_subscribe # client.connect("test.mosquitto.org") # client.connect("iot.eclipse.org") client.connect("broker.hivemq.com") # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()