def run(self): client = paho.mqtt.client.Client("broker-monitor") client.connect("localhost", port=port) client.message_callback_add("$SYS/broker/store/messages/count", self.store_count) client.message_callback_add("$SYS/broker/store/messages/bytes", self.store_bytes) client.message_callback_add("$SYS/broker/publish/messages/dropped", self.publish_dropped) client.subscribe("$SYS/broker/store/messages/#") client.subscribe("$SYS/broker/publish/messages/dropped") while True: expect_drops = cq.get() self.cq.task_done() if expect_drops == "quit": break first = time.time() while self.stored < 0 or self.stored_bytes < 0 or (expect_drops and self.dropped < 0): client.loop(timeout=0.5) if time.time() - 10 > first: print("ABORT TIMEOUT") break if expect_drops: self.rq.put((self.stored, self.stored_bytes, self.dropped)) else: self.rq.put((self.stored, self.stored_bytes, 0)) self.stored = -1 self.stored_bytes = -1 self.dropped = -1 client.disconnect()
def btn_停止订阅被单击(): client.disconnect() client.loop_stop() print("已停止订阅并断开与服务器的连接") w.Scrolledtext1.insert(tk.END, "已停止订阅并断开与服务器的连接\n") w.TButton1.configure(state=tk.TRUE) w.TButton2.configure(state=tk.DISABLED)
def registerOfflineSubscriber(): """Just a durable client to trigger queuing""" client = paho.mqtt.client.Client("sub-qos1-offline", clean_session=False) client.connect("localhost", port=port) client.subscribe("test/publish/queueing/#", 1) client.loop() client.disconnect()
def MQTT_Proyector(estado): global test falcon_logger.info("Solicitando cambio estado proyector a %s" % estado) if (config.MQTT.POWER_CHECK): cur_stat=Estado_Proyector() if (estado == cur_stat): falcon_logger.info("El protector ya esta en %s. No hago nada" % estado) return estado else: falcon_logger.info("Power Control desactivado") falcon_logger.info("Enviando mensaje MQTT %sbroadlink/replay proyectoron" % test ) try: falcon_logger.info("Estableciendo conexion con %s:%s" % (config.MQTT.HOST,config.MQTT.PORT)) client.connect(host=config.MQTT.HOST, port=config.MQTT.PORT) client.publish("%sbroadlink/record" % test,"proyectoron" ) if (estado=="OFF"): time.sleep(1) client.publish("%sbroadlink/record" % test,"proyectoron" ) falcon_logger.error("Enviando mensaje MQTT %sbroadlink/replay proyectoron" % test ) client.disconnect() except Exception as e: falcon_logger.error("Error al conectar a MQTT. Mensaje no enviado %s" % str(e)) return 9,"Error de conexion" return 0,"ok"
def run(self): client = paho.mqtt.client.Client("broker-monitor") client.connect("localhost", port=port) client.message_callback_add("$SYS/broker/store/messages/count", self.store_count) client.message_callback_add("$SYS/broker/store/messages/bytes", self.store_bytes) client.message_callback_add("$SYS/broker/publish/messages/dropped", self.publish_dropped) client.subscribe("$SYS/broker/store/messages/#") client.subscribe("$SYS/broker/publish/messages/dropped") while True: expect_drops = cq.get() self.cq.task_done() if expect_drops == "quit": break first = time.time() while self.stored < 0 or self.stored_bytes < 0 or ( expect_drops and self.dropped < 0): client.loop(timeout=0.5) if time.time() - 10 > first: print("ABORT TIMEOUT") break if expect_drops: self.rq.put((self.stored, self.stored_bytes, self.dropped)) else: self.rq.put((self.stored, self.stored_bytes, 0)) self.stored = -1 self.stored_bytes = -1 self.dropped = -1 client.disconnect()
def btn_停止订阅被单击(): client.disconnect() client.loop_stop() print("已断开与服务器的连接") w.TButton_connect.configure(state=tk.TRUE) w.TButton_disconnect.configure(state=tk.DISABLED) w.TButton_send.configure(state=tk.DISABLED) showinfo("连接提示", "已断开与服务的连接!")
def main(): ident="test" lon=10.0 lat=44.0 value=100 dt=datetime.utcnow().replace(microsecond=0) datavar={"B20003":{"t": dt,"v": str(value)}} mqtt=rmapmqtt(ident=ident,lon=lon,lat=lat,network="rmap",host="rmap.cc",port=1883,prefix="test",maintprefix="test") mqtt.data(timerange="254,0,0",level="1,-,-,-",datavar=datavar) mqtt.disconnect()
def disconnect(text=""): global client, connect_flag btn_clearsub() client.disconnect() client.loop_stop() print("已断开与服务器的连接") w.Button_connect.configure(text='''开始连接''') w.Button_connect.configure(background="#00BFFF") w.Button_publish.configure(state="disabled") w.Button_addsub.configure(state="disabled") w.Button_cancelsub.configure(state="disabled") w.Button_clearsub.configure(state="disabled") showinfo("连接提示", "已断开与服务的连接!\n%s" % text) connect_flag = False
def loop(logger, topic, sensor=None, mqtt=None): global isRunning logger.info('Starting main loop') while isRunning: logger.debug('Reading sensor') if sensor is not None: temperature = sensor.readTemperature() pressure = sensor.readPressure() altitude = sensor.readAltitude() else: temperature = 24 pressure = 100700 altitude = 50.83 logger.debug("Temperature: %.2f °C" % temperature) logger.debug("Pressure: %.2f hPa" % humidity) logger.debug("Altitude: %.2f" % altitude) json_value = { 'temperature': temperature, 'pressure': pressure, 'altitude': altitude } logger.debug(json_value) if mqtt is not None: try: if isConnected is not True: logger.info("Reconnecting to MQTT server") mqtt.reconnect() mqtt.publish(topic, json.dumps(json_value)) except: logger.error("Publishing to MQTT server failed") logger.debug('---') time.sleep(2) if mqtt is not None: logger.debug("Disconnecting from MQTT") mqtt.disconnect()
def MQTT_Audio(estado): global test if (config.MQTT.POWER_CHECK): cur_stat=Estado_Audio() if (estado == cur_stat): falcon_logger.error("El Audio ya esta en %s. No hago nada" % estado) return estado else: falcon_logger.error("Power Control desactivado") falcon_logger.info("Enviando mensaje MQTT %scmnd/audio/power %s" % (test,estado )) try: falcon_logger.info("Estableciendo conexion con %s:%s" % (config.MQTT.HOST,config.MQTT.PORT)) client.connect(host=config.MQTT.HOST, port=config.MQTT.PORT) client.publish("%scmnd/audio/POWER" % test, estado) client.disconnect() except Exception as e: falcon_logger.error("Error al conectar a MQTT. Mensaje no enviado %s" % str(e)) return 9,"Error de conexion" return 0,"ok"
def loop(logger, topic, pin, sensor=None, mqtt=None): global isRunning logger.info('Starting main loop') while isRunning: logger.debug('Reading sensor') if sensor is not None: humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) else: humidity = 48.5 temperature = 24 logger.debug("Temperature: %s" % temperature) logger.debug("Humidity: %s" % humidity) json_value = {'temperature': temperature, 'humidity': humidity} logger.debug(json_value) if mqtt is not None: try: if isConnected is not True: logger.info("Reconnecting to MQTT server") mqtt.reconnect() mqtt.publish(topic, json.dumps(json_value)) except: logger.error("Publishing to MQTT server failed") logger.debug('---') time.sleep(2) if mqtt is not None: logger.debug("Disconnecting from MQTT") mqtt.disconnect()
def stop(client): client.disconnect() client.loop_stop() sys.exit()
def on_message(client, userdata, msg): assert msg.topic == topic client.disconnect()
def on_message(client, userdata, msg): with pytest.raises(UnicodeDecodeError): msg.topic client.disconnect()
max_magnet = np.linalg.norm(magnet_minmax[3:]) mqtt.publish('sensor/accel_g', max_accel) mqtt.publish('sensor/flux_t', max_magnet) #mqtt.publish('sensor/gyro_dps', np.linalg.norm(gyro_minmax[:3] - gyro_minmax[3:])) requests.post( 'http://192.168.0.200:8086/write?db=hosts', data= 'embedded,name=structure,area=hm17 mpu9250_degc={:f},mpu9250_mv={:d}' .format(temp, vcc)) monitor = SerialMonitor('/dev/ttyUSB0', 57600, parse_line) try: while True: time.sleep(5) accel_by_5s.append(max_accel) step += 1 if step == 4: for interval in intervals: index_interval = int(interval / 5) mqtt.publish('sensor/accel{}'.format(interval), max(accel_by_5s[-index_interval:])) accel_by_5s = accel_by_5s[-intervals[-1]:] step = 0 except KeyboardInterrupt: monitor.close() mqtt.disconnect()
def stop_pub():#断开与mq服务器的连接 client.disconnect() client.loop_stop() print("已断开与服务器的连接")
#! /usr/bin/python import paho.mqtt.client import time def mqtt_callback(client, user_data, message): print("Message with topic {} received: {}".format( message.topic, str(message.payload.decode("utf-8")))) device = "127.0.0.1" topic1 = "/junos/events/kernel/route/#" if __name__ == "__main__": print "connecting to MQTT brocker" client = paho.mqtt.client.Client() client.connect(device) client.loop_start() client.on_message = mqtt_callback client.subscribe(topic1) time.sleep(60) # raw_input("Press Enter to stop \n\n\n") client.loop_stop() client.disconnect()
def on_publish(mosq, userdata, mid): # Disconnect after our message has been sent. mqtt.disconnect()
def _on_publish(client, userdata, mid): client.disconnect()