예제 #1
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()
예제 #2
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()
예제 #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(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()
예제 #5
0
파일: main.py 프로젝트: neoleesky/ESP32F
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()
예제 #6
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()
예제 #7
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()
예제 #8
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()
예제 #9
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()
예제 #10
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")
예제 #11
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()
예제 #12
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()
예제 #13
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()
예제 #14
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()
예제 #15
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()
예제 #16
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()
예제 #17
0
파일: main.py 프로젝트: petonic/esp-dht22
def main():
    global wl_net
    # Initialize wireless network
    if not wl_net:
        wl_net = init_wifi()

    # Initialize DHT
    sensor = dht.DHT22(machine.Pin(4))

    # Main loop to read temp and send it
    # Read the temperature
    sensor.measure()
    temp = sensor.temperature() * 9.0 / 5.0 + 32.0
    humid = sensor.humidity()
    print('v1.2: Temp / Humid = {:2} / {:2}'.format(temp, humid))

    # Send it through MQTT
    mqtt_c = MQTTClient(MQ_CLIENT,
                        MQ_BROKER_IP,
                        user=MQ_USER,
                        password=MQ_PASSWORD)
    mqtt_c.connect()

    json_array = {
        "temp": "{}".format(temp),
        "hum": "{}".format(humid),
    }

    import ujson

    #    {"source":"TV (0)","pvr_status":"NONE","powerstate":"Normal","tv_mode":"Cable (1)","volume":"7","channel_number":"45","channel_name":"Nat Geo HD","program_name":"Personaje ale nazismului","resolution":"1920x1080","error":false}

    mqtt_c.publish(MQ_TOPIC.encode('utf-8'),
                   ujson.dumps(json_array),
                   retain=True)

    mqtt_c.disconnect()

    # configure RTC.ALARM0 to be able to wake the device
    rtc = machine.RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

    # set RTC.ALARM0 to fire after 10 seconds (waking the device)
    rtc.alarm(rtc.ALARM0, 10000)  # For debugging, 10 seconds
    # rtc.alarm(rtc.ALARM0, 1000 * DELAY_MLOOP)  # Default: 60 seconds
    # Make sure that the Node MCU has pin D0 (L15) wired to RST (R3)

    # put the device to sleep
    machine.deepsleep()
예제 #18
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()
예제 #19
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
예제 #20
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()
예제 #21
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()
예제 #22
0
def main(server=SERVER):
    wlan = network.WLAN(network.STA_IF)
    if not wlan.isconnected():
        wlan.active(True)
        wlan.connect('Micropython-wifi', '12345678')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())
    c = MQTTClient(CLIENT_ID, server)
    c.connect()
    print("Connected to %s, waiting for timer" % server)
    fail = False
    count = 0
    value = '0'
    data = uart.read(100)
    c.publish(TOPIC, value, retain=True)
    time.sleep(1)
    c.disconnect()
예제 #23
0
def main(server=SERVER):
    print(config.value)
    wlan = network.WLAN(network.STA_IF) 
    if not wlan.isconnected():
        wlan.active(True)
        wlan.connect(config.value[0][1], config.value[0][2])
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig()) 
    c = MQTTClient(CLIENT_ID, server)
    c.connect()
    print("Connected to %s, waiting for timer" % server)
    value = '0'
    data = uart.read(100)
    while wlan.isconnected():
        data = uart.read(100)
        if data != None:
            a = str(data[2:])
            b = a.split('\'')
            e = b[1].split('\\')
            d = e[0].split(',')
            if d[0]=='IR':
                print(d[0])
                print(d[1])
                if d[1] == '128':
                    c.publish(config.value[2][1],"ON",retain=True)
                    c.publish(config.value[1][1],"Remote",retain=True)
                    print(d[1])
                if d[1] == '129':
                    c.publish(config.value[2][1],"OFF",retain=True)
                    c.publish(config.value[1][1],"Remote",retain=True)
                    print(d[1])
                if d[1] == '130':
                    c.publish(config.value[2][2],"ON",retain=True)
                    c.publish(config.value[1][2],"Remote",retain=True)
                    print(d[1])
                if d[1] == '131':
                    c.publish(config.value[2][2],"OFF",retain=True)
                    c.publish(config.value[1][2],"Remote",retain=True)
                    print(d[1])
                print("Time to publish")      
    c.disconnect()
예제 #24
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()
예제 #25
0
파일: mqtttocc.py 프로젝트: mmggbe/Examples
from simple import MQTTClient

# Connection information
mqtthost = 'mqtt.enco.io'
mqttport = 8883
mqttssl = True
# Channel specific parameters
uname = '<< YOUR INFO HERE >>'
pwval = '<< YOUR INFO HERE >>'
topicName = '<< YOUR INFO HERE >>'
deviceId = '<< YOUR INFO HERE >>'

# Create an instance for further use, connect and use directly
connection = MQTTClient(client_id=deviceId,
                        server=mqtthost,
                        port=mqttport,
                        user=uname,
                        password=pwval,
                        ssl=mqttssl)
print('Connect to broker', mqtthost, ':', str(mqttport))
connection.connect()
print('Publish to ', topicName)
connection.publish(topicName, b'MQTTS Greetings from the WiPy !!')
print('Close')
connection.disconnect()
print('All done')
예제 #26
0
from simple import MQTTClient
import utime
import network
sta = network.WLAN(network.STA_IF)
sta.active(1)
sta.connect("Kritsnam_3", "hydro123")
utime.sleep_ms(6000)
c = MQTTClient(client_id="sahil12",
               server="172.26.83.102",
               port=1883,
               user="******",
               password="******")
c.connect()
f = 1
s = 'fej'
for i in range(1, 10):
    c.publish(topic="v1/devices/me/telemetry",
              msg='''{"firmware_version":'f', "serial_number":'s'}''')
    utime.sleep_ms(1000)
c.disconnect()
예제 #27
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()
예제 #28
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()
예제 #29
0
def mqtt_connect():

    c = MQTTClient("umqtt_client", "192.168.2.50")
    c.connect()
    c.publish(b"foo_topic", b"hello")
    c.disconnect()
예제 #30
0
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()
예제 #31
0
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()