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(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(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 main(server=SERVER): #端口号为:6002 c = MQTTClient(CLIENT_ID, server, 6002, username, password) c.set_callback(sub_cb) c.connect() print("Connected to %s" % server) 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) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) try: while 1: c.wait_msg() finally: c.disconnect()
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 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 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=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(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 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 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 + "/" + DeviceName + "/thing/service/property/set") #订阅主题 print("mqtt connect done") while True: client.wait_msg()
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 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")
print(dic) refind(dic) def refind(dicc): match0 = re.search(r"{\"powerstate\":(.*?)}", dicc) #获取灯的开关信息 if match0: value0 = eval(match0.group(1)) led.value(value0) try: client = MQTTClient(CLIENT_ID, SERVER, PORT, username, password, 60) print(client) client.set_callback(sub_cb) client.connect() #connect mqtt client.subscribe(subscribe_TOPIC) print("Connected to %s, subscribed to %s topic" % (SERVER, subscribe_TOPIC)) timer = Timer(0) timer.init(mode=Timer.PERIODIC, period=5000, callback=Dataupload) while True: client.wait_msg() except Exception as ex_results: print('exception1', ex_results) finally: if (client is not None): client.disconnect()