def MQTT_Init(): # 创建一个mqtt实例 c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=USER, password=PASSWORD, keepalive=30) # 必须要 keepalive=30 ,否则连接不上 # 设置消息回调 c.set_callback(sub_cb) # 建立连接 try: c.connect() except Exception as e: print('!!!,e=%s' % e) return # c.connect() # 订阅主题 c.subscribe(SUB_TOPIC.format(IMEI)) # 发布消息 Payload = '{"DeviceName":"{}","msg":"test publish"}'.format(IMEI) c.publish(PUB_TOPIC.format(IMEI), Payload) while True: c.wait_msg() if state == 1: break # 关闭连接 c.disconnect()
def recepcionMQTT(server=SERVER, topic=TOPIC3): c = MQTTClient(CLIENT_ID, server) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(topic) #print("Connected to %s, subscribed to %s topic" % (server, topic)) try: c.wait_msg() finally: c.disconnect()
class MqttClient(): ''' mqtt init ''' def __init__(self, clientid, server, port, pw): self.clientid = clientid self.pw = pw self.server = server self.port = port self.uasename = clientid self.client = None def connect(self): self.client = MQTTClient(self.clientid, self.server, self.port, self.uasename, self.pw, keepalive=300) self.client.set_callback(self.sub_cb) self.client.connect() def sub_cb(self, topic, msg): print("Subscribe Recv: %s, %s" % (topic.decode(), msg.decode())) def subscribe(self, topic, qos=0): self.client.subscribe(topic, qos) def publish(self, topic, msg, qos=0): self.client.publish(topic, msg, qos) def disconnect(self): self.disconnect() def __loop_forever(self, t): # print("loop_forever") try: self.client.ping() except: return -1 def __listen(self): while True: try: self.client.wait_msg() except OSError as e: return -1 def start(self): _thread.start_new_thread(self.__listen, ()) t = Timer(1) t.start(period=20000, mode=t.PERIODIC, callback=self.__loop_forever)
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"foo_topic") while True: if True: # Blocking wait for message c.wait_msg() else: # Non-blocking wait for message c.check_msg() # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep(1) c.disconnect()
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) np_clear() #np_status_blink() try: while 1: #micropython.mem_info() c.wait_msg() finally: c.disconnect()
def main(server="localhost"): c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=1883, user=USER, password=PASSWORD) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) while True: if True: # Blocking wait for message c.wait_msg() else: # Non-blocking wait for message c.check_msg() # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep(1) c.disconnect()
class Mqtt_Class(): def __init__(self): # 创建一个mqtt实例 self.client_id = "868540051778302" self.downtopic = "quec/868540051778302/down" self.uptopic = "quec/868540051778302/up" self.mqttserver = "southbound.quectel.com" self.mqttport = 1883 self.uername = "868540051778302" self.passwd = "d40332b8211097ffbb0e2645c2efec95" self.mqtt_client = MQTTClient(self.client_id, self.mqttserver, self.mqttport, self.uername, self.passwd) def mqtt_recv_callback(self, topic, msg): print("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) q_recv_thread.recv_thread.recv_callback(topic, msg.decode()) def mqtt_set_recv_callback(self): # 设置消息回调 self.mqtt_client.set_callback(self.mqtt_recv_callback) def connect(self): #建立连接 self.mqtt_client.connect() def sub_topic(self, topic): # 订阅主题 self.mqtt_client.subscribe(topic) def put_msg(self, msg, qos=0): # 发布消息 self.mqtt_client.publish(self.uptopic, msg, qos) def wait_msg(self): self.mqtt_client.wait_msg() def disconnect(self): # 关闭连接 self.mqtt_client.disconnect()
def MQTT_Init(): # 创建一个mqtt实例 c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=USER, password=PASSWORD, keepalive=30) # 必须要 keepalive=30 ,否则连接不上 # 设置消息回调 c.set_callback(sub_cb) # 建立连接 c.connect() # 订阅主题 c.subscribe('$oc/devices/{}/sys/messages/down'.format(DEVICE_ID)) msg = b'''{ "services": [{ "service_id": "WaterMeterControl", "properties": { "state": "T:15c, H: 85% " }, "event_time": "20151212T121212Z" } ] }''' # 发布消息 c.publish('$oc/devices/{}/sys/properties/report'.format(DEVICE_ID), msg) while True: c.wait_msg() if state == 1: break # 关闭连接 c.disconnect()
# Recepcion def sub_cb(topic, msg): global state print((topic, msg)) if msg == b"on": led.value(0) state = 1 elif msg == b"off": led.value(1) state = 0 elif msg == b"toggle": # LED is inversed, so setting it to current state # value will make it toggle led.value(state) state = 1 - state client_mqtt = MQTTClient(CLIENT_ID, SERVER) # Subscribed messages will be delivered to this callback client_mqtt.set_callback(sub_cb) client_mqtt.connect() client_mqtt.subscribe(TOPIC5) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC5)) try: while 1: # micropython.mem_info() client_mqtt.wait_msg() finally: client_mqtt.disconnect()
from umqtt import MQTTClient import machine, ubinascii import time import network wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect('HUAWEI', '0000000000') while not wlan.isconnected(): print('Wait connection') time.sleep(1) def on_message(topic, msg): print(topic, msg) CLIENT_ID = ubinascii.hexlify(machine.unique_id()) client = MQTTClient(CLIENT_ID, 'iot.eclipse.org', port=1883) client.set_callback(on_message) client.connect() client.subscribe('micro/python/test') while True: client.wait_msg()
state = 0 def sub_cb(topic, msg): global state print("subscribe recv:") print(topic, msg) state = 1 #创建一个 mqtt 实例 c = MQTTClient("umqtt_client", "mq.tongxinmao.com", '18830') #设置消息回调 c.set_callback(sub_cb) #建立连接 c.connect() #订阅主题 c.subscribe(b"/public/TEST/quecpython") print( "Connected to mq.tongxinmao.com, subscribed to /public/TEST/quecpython topic" ) #发布消息 c.publish(b"/public/TEST/quecpython", b"my name is Kingka!") print("Publish topic: /public/TEST/quecpython, msg: my name is Quecpython") while True: c.wait_msg() #阻塞函数,监听消息 if state == 1: break #关闭连接 c.disconnect()
class BluestoneMqtt(object): inst = None def __init__(self, client_id, server, port, user, password, sub_topic, pub_topic): BluestoneMqtt.inst = self self.bs_config = None self.bs_gpio = None self.bs_pwm = None self.bs_fota = None self.bs_uart = None self.sn = bluestone_common.BluestoneCommon.get_sn() self.client_id = client_id self.server = server self.port = port self.user = user self.password = password self.subscribe_topic = sub_topic self.publish_topic = pub_topic self.client = None self._is_sub_callback_running = False self._is_message_published = False def _init_mqtt(self): self.bs_config = bluestone_config.BluestoneConfig( 'bluestone_config.json') self.bs_data_config = bluestone_config.BluestoneConfig( 'bluestone_data.json') self.bs_gpio = bluestone_gpio.BluestoneGPIO() self.bs_pwm = bluestone_pwm.BluestonePWM() self.bs_fota = bluestone_fota.BluestoneFOTA() self.bs_uart = bluestone_uart.BlueStoneUart(None) # 创建一个MQTT实例 self.client = MQTTClient(client_id=self.client_id, server=self.server, port=self.port, user=self.user, password=self.password, keepalive=30) _mqtt_log.info( "Start a new mqtt client, id:{}, server:{}, port:{}".format( self.client_id, self.server, self.port)) self.client.set_callback(self._sub_callback) # 设置消息回调 self.client.connect() # 建立连接 #sub_topic = self.subscribe_topic.format(self.sn) _mqtt_log.info("Subscribe topic is {}".format(self.subscribe_topic)) self.client.subscribe(self.subscribe_topic) # 订阅主题 def _update_gpio_status(self, io_level_list): try: self.bs_data_config.update_config('gpio', io_level_list) message = {} message['gpio'] = io_level_list _mqtt_log.info("Data configuration is {}".format(message)) self.publish(message) except Exception as err: _mqtt_log.error( "Cannot update gpio level list, the error is {}".format(err)) def _handle_callback(self, key, config): result = False try: if key.startswith('uart'): # first payload then config payload = self.bs_config.get_value(config, "payload") if payload: self.bs_uart.uart_write(key, ujson.dumps(payload)) uart_config = self.bs_config.get_value(config, "config") if uart_config: self.bs_config.update_config(key, uart_config) self.bs_data_config.update_config(key, uart_config) result = True elif key.startswith('pwm'): id = self.bs_pwm.get_id_by_name(key) is_breathe = self.bs_config.get_int_value(config, "breathe") frequency = self.bs_config.get_int_value(config, "frequency") duty = self.bs_config.get_float_value(config, "duty") if is_breathe: self.bs_pwm.start_breathe(id, frequency) else: self.bs_pwm.start_once(id, frequency, duty) elif key.startswith('timer'): self.bs_config.update_config(key, config) self.bs_data_config.update_config(key, config) result = True elif key == 'gpio': io_level_list = self.bs_gpio.read_all() io_name_list = self.bs_gpio.get_io_name_list() for gpio_key in config.keys(): if gpio_key not in io_name_list: continue level = self.bs_config.get_int_value(config, gpio_key) if level is not None: id = self.bs_gpio.get_id_by_name(gpio_key) self.bs_gpio.write(id, level) io_level_list[gpio_key] = level self._update_gpio_status(io_level_list) elif key == 'fota': mode = self.bs_config.get_int_value(config, "mode") if mode == 0: url_list = self.bs_config.get_value(config, "url") self.bs_fota.start_fota_app(url_list) elif mode == 1: url = self.bs_config.get_value(config, "url") self.bs_fota.start_fota_firmware(url) result = True except Exception as err: _mqtt_log.error( "Cannot handle callback for mqtt, the error is {}".format(err)) return result def _sub_callback_internal(self, topic, msg): try: message = msg.decode() _mqtt_log.info("Subscribe received, topic={}, message={}".format( topic.decode(), message)) restart = False config_setting = ujson.loads(message) config_keys = config_setting.keys() for key in config_setting: config = config_setting[key] key_exist = self.bs_config.check_key_exist(key) if key_exist: if not restart: restart = self.bs_config.mqtt_check_key_restart(key) result = self._handle_callback(key, config) if result: restart = True if restart: restart = False _mqtt_log.info( "New configuration was received from mqtt, restarting system to take effect" ) Power.powerRestart() except Exception as err: _mqtt_log.error( "Cannot handle subscribe callback for mqtt, the error is {}". format(err)) finally: self._is_sub_callback_running = False # 云端消息响应回调函数 def _sub_callback(self, topic, msg): if self._is_sub_callback_running: _mqtt_log.error( "Subscribe callback function is running, skipping the new request" ) return self._is_sub_callback_running = True _thread.start_new_thread(self._sub_callback_internal, (topic, msg)) def _mqtt_publish(self, message): #pub_topic = self.publish_topic.format(self.sn) #message = {"Config":{},"message":"MQTT hello from Bluestone"} if self.client is not None: self.client.publish(self.publish_topic, message) self._is_message_published = True _mqtt_log.info("Publish topic is {}, message is {}".format( self.publish_topic, message)) def _wait_msg(self): while True: if self.client is not None: self.client.wait_msg() utime.sleep_ms(300) def is_message_published(self): return self._is_message_published def start(self): self._init_mqtt() _thread.start_new_thread(self._wait_msg, ()) def publish(self, message): network_state = bluestone_common.BluestoneCommon.get_network_state() if network_state != 1: _mqtt_log.error( "Cannot publish mqtt message, the network state is {}".format( network_state)) return #_mqtt_log.info("Publish message is {}".format(message)) #self._mqtt_publish(ujson.dumps(message)) self._is_message_published = False _thread.start_new_thread(self._mqtt_publish, ([ujson.dumps(message)])) def connect(self): if self.client is not None: self.client.connect() _mqtt_log.info("MQTT connected") def disconnect(self): if self.client is not None: self.client.disconnect() _mqtt_log.info("MQTT disconnected") def close(self): self.disconnect() self.client = None _mqtt_log.info("MQTT closed")