예제 #1
0
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)
예제 #2
0
def getMQTT(callbackFunction=None):
    global mqttClient 
    if mqttClient is None:
       mqttClient = MQTTClient(clientID,broker,port=brokerPort,user=user,password=password)
       if callbackFunction is not None:
          mqttClient.set_callback(callbackFunction)
    return mqttClient
예제 #3
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()
예제 #4
0
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()
예제 #5
0
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)
예제 #6
0
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)
예제 #7
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()
예제 #8
0
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
예제 #9
0
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)
예제 #10
0
	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()
예제 #11
0
def config_mqtt_client():
    global c_mqtt

    try:
        # c_mqtt = MQTTClient(CONFIG['client_id'], CONFIG['broker'], CONFIG['port'], timeout=1, sbt=CONFIG['topic'], debug=False)
        c_mqtt = MQTTClient(CONFIG['client_id'], CONFIG['broker'], CONFIG['port'])
        c_mqtt.set_callback(sub_cb)
    except (OSError, ValueError):
        print("Couldn't connect to MQTT")
예제 #12
0
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()
예제 #13
0
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)
예제 #14
0
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()
예제 #15
0
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()
예제 #16
0
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()
예제 #17
0
파일: mqtt.py 프로젝트: radiumray/mdxly
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()
예제 #18
0
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()
예제 #19
0
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)
예제 #20
0
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())
예제 #21
0
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()
예제 #22
0
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()
예제 #23
0
 def mqttMain(self):
     try:
         c =MQTTClient("umqtt_client", server=self._host,port=1883)
         self.c = c
         self.ledTrue(5,0.2)
         # c =MQTTClient("umqtt_client", server="192.168.50.53",port=1883)
         c.set_callback(self.sub_cb)
         c.connect()
         # c.subscribe("001")
         print('mqtt connect ok')
         self.ledTrue(5,0.1)
         return c
     except OSError as e:
         self.ledTrue(3,0.1)
         self.mqttMain()
예제 #24
0
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()
예제 #25
0
def mqtt_connect():
    # mqtt初始化
    print("mqtt_broker:%s" % config['mqtt_broker'])
    client = MQTTClient(client_id=config['mqtt_client_id'],
                        server=config['mqtt_broker'],
                        port=config['mqtt_port'],
                        user=config['mqtt_user'],
                        password=config['mqtt_pwd'],
                        keepalive=120)
    # 设置mqtt订阅回调
    client.set_callback(mqtt_callback)
    # 设置遗言
    # 向主题/{dev_id}/devstate ,发送{"dev_id":2,"dev_state":"offline"}
    last_will = json.dumps({"dev_id": DEVICE_ID, "dev_state": 'off'})
    client.set_last_will(DEVICE_ID + '/devstate', last_will)
    return client
예제 #26
0
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()
예제 #27
0
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()
예제 #28
0
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)
예제 #29
0
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
예제 #30
0
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)
예제 #31
0
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()
예제 #32
0
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)
예제 #33
0
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")