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()
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()
return btn = machine.Pin(BTN_INT_PIN, machine.Pin.IN, machine.Pin.PULL_UP) btn.callback(trigger=machine.Pin.IRQ_RISING, handler=IsrCallback) #Init py = Pysense() si = SI7006A20(py) li = LIS2HH12(py) lt = LTR329ALS01(py) mpp = MPL3115A2(py, mode=PRESSURE) #Main Cycle while 1: client.check_msg() #Checks if there is data to receive #Temperature Publish client.publish(topic=TOPIC_PUBLISH + TEMP_CH, msg="temp,c=" + str(si.temperature())) time.sleep_ms(10) #Limpar barramento I2C #Humidity Publish client.publish(topic=TOPIC_PUBLISH + HUMI_CH, msg="rel_hum,p=" + str(si.humidity())) time.sleep_ms(10) #Limpar barramento I2C #Accelerometer Publish x, y, z = li.acceleration() client.publish(topic=TOPIC_PUBLISH + ACCEL_X_CH, msg="analog_sensor=" + str(x))
print('topic: {}'.format(topic)) print('msg: {}'.format(msg)) #判断网络是否连接成功 if nic.isconnected(): print(nic.ifconfig()) #打印IP信息 #OLED数据显示 oled.fill(0) #清屏背景黑色 oled.text('IP/Subnet/GW:',0,0) oled.text(nic.ifconfig()[0], 0, 20) oled.text(nic.ifconfig()[1],0,38) oled.text(nic.ifconfig()[2],0,56) oled.show() SERVER = 'mqtt.p2hp.com' PORT = 1883 CLIENT_ID = '01Studio-pyBoard' # 客户端ID TOPIC = '/public/01Studio/1' # TOPIC名称 client = MQTTClient(CLIENT_ID, SERVER, PORT) client.set_callback(MQTT_callback) #配置回调函数 client.connect() client.subscribe(TOPIC) #订阅主题 while (True): client.check_msg() #检测是否收到信息,收到则执行回调函数打印。 time.sleep_ms(300) #接收间隔
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()
class mqtt: failed_count = 0 def __init__(self, client_id='', username='', password=''): 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.dht11 = dht.DHT11(Pin(14)) self.pid = 0 # publish count def isPin(self, pin='-1'): if int(pin) in (0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16): return int(pin) else: return -1 def pubData(self, t): self.dht11.measure() value = { 'datastreams': [{ "id": "temp", "datapoints": [{ "value": self.dht11.temperature() }] }, { "id": "humi", "datapoints": [{ "value": self.dht11.humidity() }] }] } jdata = json.dumps(value) jlen = len(jdata) bdata = bytearray(jlen + 3) bdata[0] = 1 # publish data in type of json bdata[1] = int(jlen / 256) # data lenght bdata[2] = jlen % 256 # data lenght bdata[3:jlen + 4] = jdata.encode('ascii') # json data #print(bdata) print('publish data', str(self.pid + 1)) try: self.mqttClient.publish('$dp', bdata) self.pid += 1 self.failed_count = 0 except Exception as ex: self.failed_count += 1 print('publish failed:', ex.message()) if self.failed_count >= 3: print('publish failed three times, esp resetting...') reset() def sub_callback(self, topic, msg): print((topic, msg)) cmd = msg.decode('ascii').split(" ") if len(cmd) == 3: if cmd[0] == 'pin' and self.isPin(cmd[1]) >= 0: value = Pin(int(cmd[1])).value() if cmd[2] == 'on': value = 1 elif cmd[2] == 'off': value = 0 elif cmd[2] == 'toggle': value = 0 if value == 1 else 1 pin = Pin(int(cmd[1]), Pin.OUT) #, value=(1 if cmd[2] == 'on' else 0)) pin.value(value) else: print('Pin number outof range.') 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.pubData) #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: #self.mqttClient.wait_msg() self.mqttClient.check_msg() finally: #self.mqttClient.unsubscribe(self.topic) self.mqttClient.disconnect() print('mqtt closed') tim.deinit()
class mqtt: def __init__(self, client_id='', username='', password=''): self.server = "183.230.40.39" self.client_id = "产品id" self.username = '******' self.password = '******' self.topic = b"TurnipRobot" # 随意名字 self.mqttClient = MQTTClient(self.client_id, self.server, 6002, self.username, self.password) self.dht11 = dht.DHT11(Pin(14)) self.pid = 0 # publish count self.num = 0 def isPin(self, pin='-1'): if int(pin) in (0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16): return int(pin) else: return -1 def pubData(self, kc): # self.dht11.measure() value = { 'datastreams': [{ "id": "hello", "datapoints": [{ "value": kc }] }] } # 你自己的数据流 jdata = json.dumps(value) jlen = len(jdata) bdata = bytearray(jlen + 3) bdata[0] = 1 # publish data in type of json bdata[1] = int(jlen / 256) # data lenght bdata[2] = jlen % 256 # data lenght bdata[3:jlen + 4] = jdata.encode('ascii') # json data # print(bdata) # print('publish data', str(self.pid + 1)) self.mqttClient.publish('$dp', bdata) self.pid += 1 def putt(self, t): # num = rtc.datetime()[6] # if num == 100: num = 0 self.pubData(66) def sub_callback(self, topic, msg): print((topic, msg)) cmd = (eval(bytes.decode(msg))) print(type(cmd)) print(cmd) # cmd = msg.decode('ascii').split(" ") print(cmd[0]) # try: print(8888888) if cmd[0] == 'pin': print(999999) if cmd[0] == 'pin' and self.isPin(cmd[1]) >= 0: value = Pin(int(cmd[1])).value() if cmd[2] == 'on': value = 1 elif cmd[2] == 'off': value = 0 elif cmd[2] == 'toggle': value = 0 if value == 1 else 1 pin = Pin(int(cmd[1]), Pin.OUT) # , value=(1 if cmd[2] == 'on' else 0)) pin.value(value) print('%s完毕' % cmd[1]) else: print('Pin number outof range.') # except: elif cmd[0]['key'] == '+': print(self.num) print(5666) self.num += 1 self.num = view(self.num) print(self.num) elif cmd[0]['key'] == '-': self.num -= 1 self.num = view(self.num) print(self.num) def connect(self): self.mqttClient.set_callback(self.sub_callback) self.mqttClient.connect() tim = Timer(1) tim.init(period=3000, mode=Timer.PERIODIC, callback=self.putt) self.mqttClient.subscribe(self.topic) print("连接到 %s, 订阅 %s 主题." % (self.server, self.topic)) try: while 1: # self.mqttClient.wait_msg() self.mqttClient.check_msg() finally: # self.mqttClient.unsubscribe(self.topic) self.mqttClient.disconnect() print('mqtt closed') tim.deinit()
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()
def sub_cb(topic,msg): print((topic,msg)) if topic == b'SwitchStatus' and msg == b'OFF': print('OFF') led.value(0) elif topic == b'SwitchStatus' and msg == b'ON': print('ON') led.value(1) else: None def restart(): time.sleep(10) machine.reset() connectWIFI() myIot = DFRobot_Iot(ONENET_SERVER, ProductID, DeviceId, ApiKey) client = MQTTClient(myIot.client_id, myIot.mqttserver, port = ONENET_PORT, user = myIot.username, password = myIot.password) client.set_callback(sub_cb) client.connect() client.subscribe(subTopic) while True: try: client.check_msg() except OSError as e: restart()
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()