def run(): global state, connection while True: while state != CONNECTED: try: state = CONNECTING connection = MQTTClient(client_id=config.CLIENT_ID, server=config.AWS_HOST, port=config.AWS_PORT, keepalive=10000, ssl=True, ssl_params={ "certfile": config.AWS_CLIENT_CERT, "keyfile": config.AWS_PRIVATE_KEY, "ca_certs": config.AWS_ROOT_CA }) connection.connect() state = CONNECTED except: print('Could not establish MQTT connection') time.sleep(0.5) continue print('MQTT LIVE!') # Subscribe for messages connection.set_callback(_recv_msg_callback) connection.subscribe(config.TOPIC) while state == CONNECTED: try: connection.check_msg() except: pass time.sleep(0.1)
def read_send(): instruction(light_on) data_frame = instruction(read_instruct) if data_frame[0] == 255 and data_frame[1] == 135: data_g = (data_frame[2] * 256 + data_frame[3]) / 1000 data_t = (data_frame[8] << 8 | data_frame[9]) / 100 data_h = (data_frame[10] << 8 | data_frame[11]) / 100 dataframe = { "params": { "data_g": data_g, "data_t": data_t, "data_h": data_h } } tvoc_mqtt = MQTTClient(client_id=mqttClientId, server=server, port=port, user=mqttUsername, password=mqttPassword, keepalive=60) tvoc_mqtt.set_callback(callback) tvoc_mqtt.connect() time.sleep(1) tvoc_mqtt.publish(topic_p, json.dumps(dataframe)) time.sleep(1) tvoc_mqtt.subscribe(topic_s) time.sleep(1)
def main(quit=True): global t c = MQTTClient(CLIENT_ID, SERVER) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC, qos = QOS) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC)) n = 0 pubs = 0 try: while 1: n += 1 if not n % 100: t = ticks_ms() c.publish(TOPIC, str(pubs).encode('UTF8'), retain = False, qos = QOS) c.wait_msg() pubs += 1 if not pubs % 100: print('echo received in max {} ms min {} ms'. format(maxt, mint)) if quit: return sleep(0.05) c.check_msg() finally: c.disconnect()
def main(): global NEW_DATA_FLAG # 初始化定时器 tim.init(period=10000, mode=Timer.PERIODIC, callback=temprature_measure) # 初始化MQTT客户端 client = MQTTClient(CLIENTID, SERVER, PORT, USERNAME, PSW) client.set_callback(subscribe_callback) client.connect() client.subscribe(TOPIC_DOWNLINK) print("Connected to MQTT server: %s, topic:%s" % (SERVER, TOPIC_DOWNLINK)) try: while True: # 主循环 client.check_msg() if NEW_DATA_FLAG: led.off() msg = "T:%s,H:%s" % (dht.temperature(), dht.humidity()) tem = "%s" % (dht.temperature()) humi = "%s" % (dht.humidity()) client.publish(TOPIC_UPLINK_T, tem) client.publish(TOPIC_UPLINK_H, humi) print("Send MSG: -> TOPIC:%s MSG:%s" % ("REMIX_TOPIC", msg)) NEW_DATA_FLAG = False led.on() time.sleep_ms(100) finally: client.disconnect()
def do_mqtt(): client_id = ubinascii.hexlify(machine.unique_id()) client = MQTTClient(client_id, "172.20.10.3") client.set_callback(subscribe_callback) client.connect() client.subscribe("light") return client
def run(): global state global connection while True: # Wait for connection while state != CONNECTED: try: state = CONNECTING connection = MQTTClient(DEVICE_ID, server=HOST, port=8883) connection.connect(ssl=True, certfile='/flash/cert/certificate.crt', keyfile='/flash/cert/privateKey.key', ca_certs='/flash/cert/root-CA.cer') state = CONNECTED except: print('Error connecting to the server') time.sleep(0.5) continue print('Connected!') # Subscribe for messages connection.set_callback(_recv_msg_callback) connection.subscribe(TOPIC_DOWNLOAD) while state == CONNECTED: connection.check_msg() msg = '{"Name":"Pycom", "Data":"Test"}' print('Sending: ' + msg) _send_msg(msg) time.sleep(2.0)
def main(quit=True): global t c = MQTTClient(CLIENT_ID, SERVER) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC, qos=QOS) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC)) n = 0 pubs = 0 try: while 1: n += 1 if not n % 100: t = ticks_ms() c.publish(TOPIC, str(pubs).encode('UTF8'), retain=False, qos=QOS) c.wait_msg() pubs += 1 if not pubs % 100: print('echo received in max {} ms min {} ms'.format( maxt, mint)) if quit: return sleep(0.05) c.check_msg() finally: c.disconnect()
def setup(): global c connectWifi(SSID, PASSWORD) server = SERVER c = MQTTClient(CLIENT_ID, server, 0, username, password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC)
def loop(self): c = MQTTClient(self.id, self.host) #建立一个MQTT客户端,传入连接id号和主机 c.set_callback(self.sub_cb) #设置回调函数 c.connect() #建立连接 c.subscribe(self.topic) #监控这个通道,接收控制命令, while True: c.check_msg() if utime.time() % 10 == 0: c.ping()
def main(server=SERVER): #端口号为:6002 c = MQTTClient(CLIENT_ID, server, 6002, username, password) # 控制开关 c.set_callback(sub_cb) c.connect() # 数据推送 def upload_temperature_humidity(temp): # 温湿度测量 data = dht.DHT11(p5) data.measure() temperature = data.temperature() humidity = data.humidity() # 一氧化碳测量 Carbon_monoxide = adc.read() message = { 'datastreams': [{ 'id': 'humidity', 'datapoints': [{ 'value': humidity }] }, { 'id': 'temperature', 'datapoints': [{ 'value': temperature }] }, { 'id': 'Carbon_monoxide', 'datapoints': [{ 'value': Carbon_monoxide }] }] } c.publish('$dp', pubdata(message)) print('publish message:', message) temperature_humidity_tim = Timer(-1) # 新建一个虚拟定时器 温湿度定时器 # temperature_humidity_tim.init(period=5000, mode=Timer.ONE_SHOT, callback=upload_temperature_humidity) temperature_humidity_tim.init(period=5000, mode=Timer.PERIODIC, callback=upload_temperature_humidity) c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) try: while True: c.wait_msg() finally: c.disconnect()
def a(): server = SERVER c = MQTTClient(CLIENT_ID, server) #create a mqtt client c.set_callback(sub_cb) #set callback c.connect() #connect mqtt c.subscribe(TOPIC) #client subscribes to a topic print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) while True: c.check_msg() #wait message time.sleep(1)
def main(server, port, USER, PWD): c = MQTTClient("umqtt_client", server, port, USER, PWD) c.set_callback(sub_cb) c.connect() c.subscribe("foo_topic") while True: if True: c.wait_msg() else: c.check_msg() time.sleep(1) c.disconnect()
def main(server=SERVER): #端口号为:6002 c = MQTTClient(CLIENT_ID, server, 6002, username, password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) try: while 1: c.wait_msg() finally: c.disconnect()
def main(server=SERVER): #6002 do_connect() c = MQTTClient(CLIENT_ID, server,6002,username,password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) try: while 1: c.wait_msg() finally: c.disconnect()
def mqtt_connect(): global client client = MQTTClient( config['settings']['mqtt_clientid'].encode(), config['settings']['mqtt_server'], 1883, config['settings']['mqtt_user'].encode(), config['settings']['mqtt_pass'].encode()) client.set_callback(mqtt_callback) client.connect() client.subscribe('sleep2mqtt/control'.encode()) client.subscribe('hass/status'.encode())
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)) try: while 1: #micropython.mem_info() c.wait_msg() finally: c.disconnect()
def main(server="0.0.0.0"): try: c = MQTTClient("yitian-it", server) c.set_callback(sub_cb) time.sleep(4) c.connect() c.subscribe(b"toilet") while True: c.check_msg() time.sleep(1.5) except Excepthion as e: print(e) c.disconnect() machine.reset()
def mqttconfig(v): global mqttobject if wlan.isconnected(): mqttconn.deinit() mqttobject = MQTTClient(secrets["devicename"], secrets["mqttserver"], port=1883, user=secrets["mqttusername"], password=secrets["mqttpass"]) mqttobject.set_callback(mqttcallback) mqttobject.connect() mqttobject.subscribe(secrets["topicsub"]) mqttpublisher() mqttconn.init(period=150, mode=Timer.PERIODIC, callback=newmsg)
class MqttHelper: def __init__(self, serverAddress, clientId): self.mqttClient = MQTTClient(clientId, serverAddress) self.mqttClient.connect() def Publish(self, topic, message): self.mqttClient.publish(topic, message) def Subscribe(self, topic, callback): self.mqttClient.set_callback(callback) self.mqttClient.subscribe(topic) def CheckForMessage(self): self.mqttClient.check_msg()
def main(server=SERVER): #端口号为:6002 c = MQTTClient(CLIENT_ID, server, 6002, username, password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) #publish报文上传数据点 c.publish('$dp', pubdata(message)) print('publish message:', message) try: while 1: c.wait_msg() finally: c.disconnect()
def main(server=SERVER): # 端口号为:6002 c = MQTTClient(CLIENT_ID, server, 6002, username, password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) tim_pubDate.init(period=5000, mode=Timer.PERIODIC, callback=lambda t: pubData(c, t)) pubData(c, 10) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) try: while 1: c.wait_msg() finally: print('mqtt closed') c.disconnect()
def main(start='start'): c = MQTTClient("umqtt_client", server, port, user, password) c.set_callback(sub_cb) c.connect() c.subscribe(btopic) 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 mqtt_connect(): print("clientid:", ClientId, "\n", "Broker:", strBroker, "\n", "User Name:", user_name, "\n", "Password:"******"\n") client = MQTTClient(client_id=ClientId, server=strBroker, port=Brokerport, user=user_name, password=user_password, keepalive=60) client.set_callback(recvMessage) #设置回调函数 #please make sure keepalive value is not 0 client.connect() client.subscribe("/sys/" + ProductKey + "/test1/thing/service/property/set") #订阅主题 while True: time.sleep(3)
def main(server=SERVER): #端口号为:6002 c = MQTTClient(CLIENT_ID, server,6002,username,password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) while 1: # c.wait_msg() try: l,t,p,h,H=read() rsp = http_put_data(l,'light intensity') rsp = http_put_data(t,'temperature') rsp = http_put_data(p,'pressure') rsp = http_put_data(h,'humidity') rsp = http_put_data(H,'altitude') time.sleep(2) except TypeError: pass
class mqtt: def __init__(self,oled, client_id='', username='', password='',macs=[],BROADCAST_IP='192.168.1.255',BROADCAST_PORT=40000): self.failed_count = 0 self.oled = oled self.cs = check_status(oled=oled) self.server = "183.230.40.39" self.client_id = client_id self.username = username self.password = password self.topic = (chipid() + '-sub').encode('ascii') if client_id == '' else (client_id + '-' + chipid() + '-sub').encode('ascii') self.mqttClient = MQTTClient(self.client_id, self.server,6002,self.username,self.password) self.wakeonline = WAKE_ON_LINE(macs,BROADCAST_IP,BROADCAST_PORT) def sub_callback(self, topic, msg): cmd = msg.decode() if cmd == 'wakeup': self.oled.write_lines(line2='send wol package...') self.wakeonline.send() self.oled.write_lines(line2='') def ping(self,t): self.mqttClient.ping() self.cs.display_status() def connect(self): self.mqttClient.set_callback(self.sub_callback) self.mqttClient.connect() tim = Timer(-1) tim.init(period=30000, mode=Timer.PERIODIC, callback=self.ping) #Timer.PERIODIC Timer.ONE_SHOT self.mqttClient.subscribe(self.topic) # print("Connected to %s, subscribed to %s topic." % (self.server, self.topic)) try: while 1: msg = self.mqttClient.check_msg() print (msg) finally: self.mqttClient.disconnect() print('mqtt closed') tim.deinit()
class Cn2Mqtt(): # Class functionality variables. # This variable holds the mqtt connection. mqtt = "" def connect(self): """ connect function. This function is used to connect ESP8266 to the MQTT network. """ state = 0 while state != 2: try: self.mqtt = MQTTClient(client_id="CN2", server=BROKER_IP, port=BROKER_PORT, user=BROKER_USERNAME, password=BROKER_PASSWORD, ssl=False) self.mqtt.connect() state = 2 except: print('Error connecting to the broker') time.sleep(0.5) continue print("Connected to MQTT network") self.mqtt.set_callback(self.on_message) def on_message(self, topic, payload): print((topic, payload)) def publish(self, topic, msg, retain, qos): self.mqtt.publish(topic, msg, retain, qos) print("Message published successfully.") def subscribe(self, topic, qos): self.mqtt.subscribe(topic, qos) print("Subscribed to topic: " + topic)
def read_send(): data_pm=bytearray(32) pm.readinto(data_pm) instruction_voc(light_on_voc) data_voc = instruction_voc(read_instruct_voc) if data_voc[0] == 255 and data_voc[1] == 135 and data_pm[0]==66 and data_pm[1]==77: data_g = (data_voc[2] * 256 + data_voc[3]) / 1000 data_t = (data_voc[8] << 8 | data_voc[9]) / 100 data_h = (data_voc[10] << 8 | data_voc[11]) / 100 data_pm2_5 = data_pm[6]<<8 | data_pm[7] data_pm10 = data_pm[8] << 8 | data_pm[9] dataframe = {"params": {"concentration": data_g, "temperature": data_t, "humidity": data_h, "pm2_5":data_pm2_5,"pm10":data_pm10}} tvoc_mqtt = MQTTClient(client_id=mqttClientId, server=server, port=port, user=mqttUsername, password=mqttPassword,keepalive=60) tvoc_mqtt.set_callback(callback) tvoc_mqtt.connect() time.sleep(1) tvoc_mqtt.publish(topic_p,json.dumps(dataframe)) time.sleep(1) tvoc_mqtt.subscribe(topic_s) time.sleep(1)
class Product(): def __init__(self, server="45.199.111.5", client_id="524485249", port=61613, topic=b"topic1", username='******', password='******', check=1): # Default MQTT server to connect to self.SERVER = server self.CLIENT_ID = client_id self.TOPIC = topic self.PORT = port self.username = username self.password = password #上传数据变量 self.value_data = 0 self.c = MQTTClient(self.CLIENT_ID, self.SERVER, self.PORT, self.username, self.password) self.c.set_callback(self.sub_cb) self.c.connect() self.c.subscribe(self.TOPIC) #self.c.publish('$dp',self.pubdata("temp0",self.value_data)) #上传 #self.push_data(content='1234') # if check == 1: # _thread.start_new_thread(self.keep_alive,()) # _thread.start_new_thread(self.wait_listen,()) def push_data(self, topic='topic1', content=''): #str str self.c.publish(topic, content) #上传 def keep_alive(self): while 1: #self.c.publish('$dp',self.pubdata()) #上传 self.c.publish(b'topic2', 'a') #self.c.ping() time.sleep(15) def wait_listen(self): while 1: self.c.wait_msg() # def pubdata(self,id,up_data): # data = {'datastreams':[{'id':str(id),'datapoints':[{'value':str(up_data)}] } ]} # j_d = json.dumps(data) # j_l = len(j_d) # arr = bytearray(j_l + 3) # arr[0] = 1 #publish数据类型为json # arr[1] = int(j_l / 256) # json数据长度 高位字节 # arr[2] = j_l % 256 # json数据长度 低位字节 # arr[3:] = j_d.encode('ascii') # json数据 # return arr def sub_cb(self, topic, msg): print((topic, msg)) if msg == b"off": print("1") elif msg == b"on": print("0")
class Cn2Mqtt(): """ This class serves as a bridge between the mqtt part of the program and the rest of the code. It is used to serve all basic functions needed in the network. """ # Class functionality variables. # This variable holds the mqtt connection. mqtt = None # The topic and the payload of the incoming message. r_topic = None r_message = None def connect(self): """ connect function. This function is used to connect ESP8266 to the MQTT network. """ state = 0 while state != 2: try: # connection object instance self.mqtt = MQTTClient(client_id="CN2", server=BROKER_IP, port=BROKER_PORT, user=BROKER_USERNAME, password=BROKER_PASSWORD, ssl=True) # connection to network self.mqtt.connect() state = 2 except: print('Error connecting to the broker') time.sleep(0.5) continue print("Connected to MQTT network") # Set function "on_message" to work as a callback. self.mqtt.set_callback(self.on_message) def standby_loop(self): """ standby_loop function. This function the basic looping function for every incomming MQTT message. """ if True: # Blocking wait for message self.mqtt.wait_msg() else: # Non-blocking wait for message self.mqtt.check_msg() time.sleep(1) def on_message(self, topic, msg): """on_message function. This function runs when a new message arrives. Args: param1 (byte): The message topic in byte format. param2 (byte): The message payload in byte format. """ print("Message arrived...") # class variables are set in order to share the message with other classes Cn2Mqtt.r_topic = topic.decode("utf-8") Cn2Mqtt.r_message = msg.decode("utf-8") def publish(self,topic, msg, retain, qos): """publish function. This function is used to publish a message. Args: param1 (str): The message topic. param2 (str): The message payload. param3 (Boolean): Retain flag. param4 (int): The qos level. """ self.mqtt.publish(topic, msg, retain, qos) print("Message published successfully.") def subscribe(self, topic, qos): """subscribe function. This function is used to publish a message. Args: param1 (str): The message topic. param2 (int): The qos level. """ self.mqtt.subscribe(topic, qos) print("Subscribed to topic: " + topic) def disconnect(self): """ disconnect function. This function is used to disconnect ESP8266 from the MQTT network. """ print("Disconnecting from Broker") self.mqtt.disconnect()
class Blocky: def __init__(self, config): self.config = config self.state = 0 self.has_msg = False self.topic = '' self.msg = '' self.mqtt = MQTTClient(CHIP_ID, BROKER, 0, CHIP_ID, self.config['auth_key'], 1883) self.message_handlers = {} def on_message(self, topic, msg): print('On new message topic: ' + topic.decode()) self.has_msg = True self.topic = topic.decode() self.msg = msg.decode() def connect(self): print('Connecting to broker') self.mqtt.set_callback(self.on_message) try: self.mqtt.connect() except Exception as error: print('Failed to connect to broker') return False register_data = { 'event': 'register', 'chipId': CHIP_ID, 'firmwareVersion': '1.0', 'name': self.config.get('device_name', 'Blocky_' + CHIP_ID), 'type': 'esp32' } self.mqtt.publish(topic=self.config['auth_key'] + '/sys/', msg=ujson.dumps(register_data)) self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/ota/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/run/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/rename/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/reboot/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/upload/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/upgrade/#') self.state = 1 print('Connected to broker') return True def process(self): if self.state != 1: return self.mqtt.check_msg() self.handle_msg() def handle_msg(self): if not self.has_msg: return print('Receive new message with topic: ' + self.topic) print('Message: ' + self.msg) sysPrefix = self.config['auth_key'] + '/sys/' + CHIP_ID + '/' userPrefix = self.config['auth_key'] + '/user/' if self.topic.startswith(sysPrefix): if self.topic == sysPrefix + 'ota': print('Receive OTA message') f = open('user_code.py', 'w') f.write(self.msg) f.close() otaAckMsg = {'chipId': CHIP_ID, 'event': 'ota_ack'} self.mqtt.publish(topic=self.config['auth_key'] + '/sys/', msg=ujson.dumps(otaAckMsg)) time.sleep_ms(500) machine.reset() elif self.topic == sysPrefix + 'run': print('Receive RUN message') exec(self.msg, globals()) elif self.topic == sysPrefix + 'reboot': print('Receive REBOOT message') machine.reset() elif self.topic == sysPrefix + 'upload': print('Receive UPLOAD message') elif self.topic == sysPrefix + 'upgrade': print('Receive UPGRADE message') elif self.topic.startswith(userPrefix): for t in self.message_handlers: format_topic = t.replace('/+', '/[a-zA-Z0-9_]+') format_topic = format_topic.replace('/#', '/*') if re.match(format_topic, self.topic): self.message_handlers.get(t)(self.topic, self.msg) self.topic = '' self.msg = '' self.has_msg = False def send_message(self, topic, msg): if self.state != 1 or not topic or not msg: return topic = self.config['auth_key'] + '/user/' + topic self.mqtt.publish(topic=topic, msg=str(msg)) def log(self, text): if self.state != 1 or text is None or text == '': return sysPrefix = self.config['auth_key'] + '/sys/' + CHIP_ID + '/log' self.mqtt.publish(topic=sysPrefix, msg=str(text)) def subscribe(self, topic, cb): if self.state != 1 or not topic: return topic = self.config['auth_key'] + '/user/' + topic self.mqtt.subscribe(topic) self.message_handlers[topic] = cb
if "|" in msg: nu = msg.split("|") if (nu[1] == "1"): Pin(int(nu[0]), Pin.OUT).on() else: Pin(int(nu[0]), Pin.OUT).off() def do_connect(): sta_if = network.WLAN(network.STA_IF) ap_if = network.WLAN(network.AP_IF) if ap_if.active(): ap_if.active(False) if not sta_if.isconnected(): print('connectiong to network...') sta_if.active(True) sta_if.connect("nianse", "nianse12") # Connect to an AP while not sta_if.isconnected(): pass print('network config:', sta_if.ifconfig()) do_connect() # c = MQTTClient("esp01s_micropython_01", "192.168.0.106",1883,"esp01s_py","4L2XZLWVTRLR") c = MQTTClient("esp01s_micropython_01", "frp.soulfree.cn", 7084, "esp01s_py", "4L2XZLWVTRLR") c.set_callback(sub_cb) c.connect() c.subscribe(b"pin_control") while True: c.check_msg()
print((topic, msg)) # print(type(msg)) infor = msg.decode() print('infor is:' + infor) # print(type(infor)) inforJson = ujson.loads(infor) obj = ujson.loads(msg.decode()) #obj = ujson.loads(msg.decode()) # sensorsId1 = obj['ID'] # print(sensorsId1) valuel = obj['temp'] # print(str(valuel)) # print("温度传感器:"+str(sensorsId1)+"值为:"+str(valuel)+"摄氏度") print("温度传感器:" + str(valuel)) if valuel > 28: led.value(1) else: led.value(0) server = SERVER c = MQTTClient(CLIENT_ID, server) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s,subscribed to %s topic" % (server, TOPIC)) while True: c.check_msg() time.sleep(1)
return False #设置MQTT回调函数,有信息时候执行 def MQTT_callback(topic, msg): print('topic: {}'.format(topic)) print('msg: {}'.format(msg)) #接收数据任务 def MQTT_Rev(tim): client.check_msg() #执行WIFI连接函数并判断是否已经连接成功 if WIFI_Connect(): SERVER = 'mqtt.p2hp.com' PORT = 1883 CLIENT_ID = '01Studio-ESP8266' # 客户端ID TOPIC = '/public/01Studio/1' # TOPIC名称 client = MQTTClient(CLIENT_ID, SERVER, PORT) #建立客户端对象 client.set_callback(MQTT_callback) #配置回调函数 client.connect() client.subscribe(TOPIC) #订阅主题 #开启RTOS定时器,编号为-1,周期300ms,执行socket通信接收任务 tim = Timer(-1) tim.init(period=300, mode=Timer.PERIODIC, callback=MQTT_Rev)