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()
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 Product(): def __init__(self, server="183.230.40.39", client_id="524485249", 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.username = username self.password = password #上传数据变量 self.value_data = 0 self.c = MQTTClient(self.CLIENT_ID, self.SERVER, 6002, 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)) #上传 if check == 1: _thread.start_new_thread(self.keep_alive, ()) _thread.start_new_thread(self.wait_listen, ()) def keep_alive(self): while 1: #self.c.publish('$dp',self.pubdata()) #上传 self.c.ping() time.sleep(30) 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 blinker: ''' # key:密码 #devTpye 设置设备类型:电灯:light,插座:outlet,多个插座:multi_outlet,传感器:sensor #cb 回调函数 例如 def cb(topic, msg): ''' def __init__(self,key,cb,devTpye="light"): self.blinker_path='blinker_'+key+'.py' self.keepalive=120 self.connect_count=0 self.devTpye=devTpye self.key=key self.info= self.read_conf() self.SERVER = "public.iot-as-mqtt.cn-shanghai.aliyuncs.com" self.USER=self.info['detail']['iotId'] self.PWD=self.info['detail']['iotToken'] self.CLIENT_ID = self.info['detail']['deviceName'] self.c=MQTTClient(client_id=self.CLIENT_ID,server=self.SERVER,user=self.USER,password=self.PWD,keepalive=self.keepalive) self.c.DEBUG = True self.cb=cb self.c.set_callback(self.p_data) self.subtopic="/"+self.info['detail']['productKey']+"/"+self.info['detail']['deviceName']+"/r" self.pubtopic=b"/"+self.info['detail']['productKey']+"/"+self.info['detail']['deviceName']+"/s" self.pubtopic_rrpc='' #获取登录信息 def getInfo(self,auth,type_="light"): log("getInfo:抓取登录信息") host = 'https://iot.diandeng.tech' url = '/api/v1/user/device/diy/auth?authKey=' + auth + "&miType="+type_+"&version=0.1.0" log("url:",url) data = get(host + url).text log("data:",data) fo = open(self.blinker_path, "w") fo.write(str(data)) fo.close() return data def p_data(self,tpc,msg): log("接收: ",msg) msg=eval(msg.decode()) type=msg['fromDevice'] if len(msg['fromDevice'])!=32 else 'DiyArduino' try: button=list(msg['data'].keys())[0] action=msg['data'][button] button={'deviceType':type,'data':[button,action]} except: button={'deviceType':type,'data':msg['data']} self.cb(tpc,button) #MQQT 连接 def connect(self): log("connect:准备连接....") if DEBUG: log("user:"******"CLIENT_ID:",self.CLIENT_ID,self.subtopic,"/r",self.pubtopic) try: if not self.c.connect(clean_session=False): try: self.c.subscribe(self.subtopic) self.connect_count+=1 self.log() log("新会话已连接.") except: log("连接失败") self.getInfo(self.key,self.devTpye) self.__init__(self.key,self.devTpye) except: log("检查网络或登录信息") #mqtt 信息轮询 def log(self): if DEBUG: log("连接: ",self.connect_count," 次") def check_msg(self): try: self.c.check_msg() except OSError as e: self.connect() #mqtt 心跳回复 def ping(self): # try: self.c.ping() if DEBUG: print("Mqtt Ping") except OSError as e: self.connect() def onLine(self): try: self.publish({"state":"online"}) except OSError as e: self.connect() #数据整合成特定json def playload(self,msg,toDevice="",deviceType='OwnApp'): if toDevice=="": toDevice=self.info['detail']['uuid'] _data= ujson.dumps({ 'fromDevice': self.info['detail']['deviceName'] , 'toDevice': toDevice, 'data': msg , 'deviceType': deviceType}) return _data #mqtt 发布消息 def publish(self,dict,toDevice="app"): pt=self.pubtopic if toDevice=="app": toDevice='' deviceType='OwnApp' if toDevice=="mi": toDevice='MIOT_r' deviceType='vAssistant' pt=self.pubtopic_rrpc try: self.c.publish(pt,self.playload(dict,toDevice,deviceType)) if DEBUG: log ("Mqtt发送>>>>",pt, dict) except OSError as e: if DEBUG: log ("publish:",e) self.connect() def read_conf(self): """ 从文件中获取json数据 :param path: 文件路径 :return json_data: 返回转换为json格式后的json数据 """ log("读取登录数据....") try: with open(self.blinker_path, 'r+') as f: try: json_data = ujson.load(f) except Exception as e: log('不是json文件' + str(e)) log("文件内容:",json_data) return json_data except Exception as e: log("文件不存在!") self.getInfo(self.key,self.devTpye) return self.read_conf()
class M5mqtt: def __init__(self, client_id, server, port, user=None, password=None, keepalive=300): if m5base.get_start() != 1: autoConnect(lcdShow=True) lcd.clear() else: raise ImportError('mqtt need download...') if user == '': user = None if password == '': password = None self.mqtt = MQTTClient(client_id, server, port, user, password, keepalive) self.mqtt.set_callback(self._on_data) try: self.mqtt.connect() except: lcd.clear() lcd.font(lcd.FONT_DejaVu24) lcd.setTextColor(lcd.RED) lcd.print('connect fail', lcd.CENTER, 100) self.topic_callback = {} self.mqttState = True self.ping_out_time = time.ticks_ms() + 60000 def _msg_deal(self, param): state, msg = self.mqtt.topic_get() if state == 0: pass elif state == 1: # receive req self.ping_out_time = time.ticks_ms() + 60000 elif state == 2: self.ping_out_time = time.ticks_ms() + 60000 topic = msg[0] if type(msg[0]) == str else msg[0].decode('utf-8') data = self.mqtt.topic_msg_get(msg[1]) self._on_data(topic, data.decode()) def _on_data(self, topic, data): self.topic_callback[topic](data) def on_connect(self): for i in self.topic_callback.keys(): self.mqtt.subscribe(i) def _daemonTask(self): timeBegin = time.ticks_ms() while True: if time.ticks_ms() - timeBegin > 10000: timeBegin = time.ticks_ms() try: if self.mqtt.ping(): self.ping_out_time = time.ticks_ms() + 2000 else: self.mqttState = False self.mqtt.lock_msg_rec() except: self.mqttState = False self.mqtt.lock_msg_rec() # ping ok, but not receive req if time.ticks_ms() > self.ping_out_time: self.mqttState = False self.mqtt.lock_msg_rec() if self.mqttState == False: if wlan_sta.isconnected(): try: self.mqtt.set_block(True) self.mqtt.connect() self.on_connect() self.mqtt.set_block(False) self.mqtt.unlock_msg_rec() self.mqttState = True self.ping_out_time = time.ticks_ms() + 60000 except Exception as e: pass else: reconnect() self._msg_deal(1) time.sleep_ms(100) def start(self): _thread.start_new_thread(self._daemonTask, ()) def subscribe(self, topic, callback): self.mqtt.subscribe(topic) self.topic_callback[topic] = callback def unsubscribe(self, topic): pass def publish(self, topic, data): if type(topic) is int: topic = str(topic) if type(data) is int: data = str(data) if self.mqttState: try: self.mqtt.publish(topic, data) except: self.mqttState = False