Beispiel #1
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)
Beispiel #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
Beispiel #3
0
    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 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)
Beispiel #5
0
def main(server=SERVER):
    c = MQTTClient(CLIENT_ID, server)
    c.connect()
    print("Connected to %s, waiting for timer" % server)
    fail = False
    count = 0
    while True:
        count += 1
        time.sleep_ms(5000)
        value = str(adc.read())
        print("Time to publish")
        try:
            if fail:
                print('Attempt to reconnect')
                c.connect()
                print('Reconnected to Huzzah')
        except OSError:
            print('Reconnect fail')
        try:
            c.publish(TOPIC, (value + ' count ' + str(count)).encode('UTF8'))
            print('Publish ' + value)
            fail = False
        except OSError:
            fail = True

    c.disconnect()
Beispiel #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)
Beispiel #7
0
    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
Beispiel #8
0
def connect2Client(server="io.adafruit.com", user=user1, password=pwd):
    c = MQTTClient("umqtt_client",
                   server,
                   user=user,
                   password=password,
                   keepalive=3600)
    c.connect()
    return c
Beispiel #9
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")
Beispiel #10
0
def send_mq():
    h, t = do_dht()
    print("h=%s,t=%s" % (h, t))
    m = MQTTClient('nodemcu', '192.168.1.112')
    m.connect()
    m.publish('hh', h)
    time.sleep(0.2)
    m.publish('tt', t)
    m.disconnect()
Beispiel #11
0
 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 = {}
Beispiel #12
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)
Beispiel #13
0
 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
Beispiel #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()
Beispiel #15
0
 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)
Beispiel #16
0
def connect_and_subscribe():
    global client_id, mqtt_server, topic_sub
    client = MQTTClient(client_id, mqtt_server)
    client.set_last_will(topic='hack42/tele/loungeledjes/status',
                         msg='offline',
                         retain=True)
    client.connect()
    client.publish('hack42/tele/loungeledjes/ifconfig',
                   str(sta_if.ifconfig()),
                   retain=True)
    client.publish('hack42/tele/loungeledjes/status', 'online', retain=True)
    return client
 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 connect_mqtt():
    server = "server IP"
    global client_id
    client_id = "client"  #insert your client ID
    username = '******'  #insert your MQTT username
    password = '******'  #insert your MQTT password
    global topic
    topic = ('sensor/temperature')
    global c
    c = MQTTClient(client_id, server, 0, username, password)
    c.connect()
    time.sleep(3)
Beispiel #19
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())
Beispiel #20
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
Beispiel #21
0
def mqtt_onenet(server=SERVER):
    c = MQTTClient(CLIENT_ID, server, 6002, username, password)
    strftime = "%04u-%02u-%02uT%02u:%02u:%02u" % time.localtime()[0:6]
    msg1 = b'Hello #%s' % (strftime)
    c.connect()
    c.publish(b"ttt",msg1)
    c.disconnect()
Beispiel #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()
Beispiel #23
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)
Beispiel #24
0
class MQTT_CLI:
    def __init__(self, wl, name, server):
        self._cli = MQTTClient(name, server)
        if not wl.isconnected():
            wl.connect()
        self._cli.connect()
        self._cli.disconnect()

    def publish(self, topic, msgobj):
        try:
            self._cli.connect()
            msgstr = json.dumps(msgobj)
            self._cli.publish(topic.encode(), msgstr.encode())
            self._cli.disconnect()
        except:
            pass
Beispiel #25
0
    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=True)
                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)
Beispiel #26
0
 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=''
Beispiel #27
0
def publish_msg(topic, msg):
    if topic and msg:
        try:
            c = MQTTClient("umqtt_client", "0.0.0.0")
            c.connect()
            c.publish(topic, msg)
            c.disconnect()
        except Exception as e:
            print(e)
            time.sleep(3)
            machine.idle()
Beispiel #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 + "/" + DeviceName +
                     "/thing/service/property/set")  #订阅主题
    print("mqtt connect done")

    while True:
        client.wait_msg()
Beispiel #29
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)
Beispiel #30
0
def main(server=SERVER):
    c = MQTTClient(CLIENT_ID, server)
    c.connect()
    print("Connected to %s, waiting for button presses" % server)
    while True:
        while True:
            if button.value() == 0:
                break
            time.sleep_ms(20)
        print("Button pressed")
        c.publish(TOPIC, b"toggle")
        time.sleep_ms(200)

    c.disconnect()
Beispiel #31
0
def publishMessage(clientID, serverIP, username, password, topicName, message):
  try:
     c = MQTTClient(clientID, serverIP,1883,username,password)
     if ( 0 == c.connect() ):
       c.publish(topicName, message, False)
       c.disconnect()
       print("publish ok")
     else:
       print("connect failed")
  except Exception:
      print("publishMessage failed")
Beispiel #32
0
 def __init__(self, serverAddress, clientId):
     self.mqttClient = MQTTClient(clientId, serverAddress)
     self.mqttClient.connect()
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()
Beispiel #34
0
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()