コード例 #1
0
async def wifi_config():
    global cfg
    global client
    global CLIENT_ID
    print('load configuration')
    f = open('config.json')
    cfg = json.loads(f.read())
    f.close()
    print(cfg)
    print('starting wifi connection')
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(cfg['ap']['ssid'], cfg['ap']['pwd'])
    while not wlan.isconnected():
        print('wait connection...')
        await asyncio.sleep(1)
    wlan.ifconfig()
    mqtt_cfg = cfg['mqtt']
    client = MQTTClient(
        CLIENT_ID, mqtt_cfg["broker"], 
        port=mqtt_cfg["port"], 
        keepalive=mqtt_cfg["keepalive"])
    will_msg = {'id': CLIENT_ID, 
        'status': False, 
        'msg': 'The connection from this device is lost:('
    }
    client.set_last_will('/device/will/status', json.dumps(will_msg))
    client.set_callback(on_message)
    client.connect()
    client.subscribe('/device/{0}/switch'.format(CLIENT_ID.decode("utf-8")), 0)
コード例 #2
0
def connected():
    global client
    client = MQTTClient(CLIENT_ID, 'q.emqtt.com', port=1883, keepalive=20)
    will_msg = {'id': CLIENT_ID, 'status': False, 'msg': 'The connection from this device is lost:('}
    client.set_last_will('/device/will/status', json.dumps(will_msg))
    client.set_callback(on_message)
    client.connect()
    client.subscribe('/device/12345/switch', 0)
    client.subscribe('/device/4567/switch', 0)     
コード例 #3
0
def mqtt_connection(cfg):
    global client
    global CLIENT_ID
    client = MQTTClient(CLIENT_ID,
                        cfg["broker"],
                        port=cfg["port"],
                        keepalive=cfg["keepalive"])
    will_msg = {
        'id': CLIENT_ID,
        'status': False,
        'msg': 'The connection from this device is lost:('
    }
    client.set_last_will('/device/will/status', json.dumps(will_msg))
    client.set_callback(on_message)
    client.connect()
    client.subscribe('/device/{0}/switch'.format(CLIENT_ID.decode("utf-8")), 0)
コード例 #4
0
class MQTT:
    def __init__(self, led_control, device_name):
        """
        Constructor
        """

        self.led_control    = led_control
        self.topic          = mqtt_config['topic']
        self.resp_topic     = mqtt_config['resp_topic']
        self.device_name    = device_name

    def start(self):
        """
        Initialize MQTT Connection
        """
        print ("Creating client")
        self.client = MQTTClient(
                                client_id   = self.device_name,
                                server      = mqtt_config['address'],
                                user        = mqtt_config['username'],
                                password    = mqtt_config['user_key'],
                                port        = mqtt_config['port'])
        print ("Setting timeout")
        self.client.settimeout = self.set_timeout
        print ("Setting callback")
        self.client.set_callback(self.sub_cb)
        print ("Connecting mqtt", mqtt_config['address'], mqtt_config['username'], mqtt_config['user_key'], mqtt_config['port'])
        res = self.client.connect()
        if (res == -1):
            print ("Failed to connect")
            pycom.rgbled(0xB900B9)
            return
        print ("Subscribing")
        self.client.subscribe(topic=self.topic)

        self.client.set_last_will(self.resp_topic, "Bye")

        print ("Listening")
        pycom.rgbled(0x00ff00)

        Timer.Alarm(self.check_new_messages, 0.0075, periodic=True)

        gc.collect()

    def stop(self):
        """
        Disconnect and stop listening
        """
        self.client.disconnect()

    def send_data(self, data):
        self.client.publish(topic=self.resp_topic, msg=data)

    def sub_cb(self, topic, message):
        """
        """
        if message is None: return
        else: self.parse_input_data(message)

    def set_timeout(duration):
        """
        """
        pass

    def parse_input_data(self, data):
        """
        Chooses correct response for new characteristic value
        """
        decoded = data.decode('utf-8')
        #Echo data back to MQTT backend

        if "status" in decoded:
            resp_data = self.led_control.compose_status_response()
            self.send_data("resp:" + resp_data)
            return

        # print (decoded)

        self.send_data("resp:" + decoded)

        if ";" in decoded:
            self.led_control.set_route(decoded)
            return
        if ("," not in decoded): return
        data = decoded.split(",")
        #print (data)
        size = len(data)
        if (size == 0):
            print ("bad input")
            return

        if (size == 1):
            self.led_control.turn_off_leds()
        elif (size == 2):
            self.led_control.set_new_data((data[0], data[1], data[1], data[1]))
        elif (size == 4):
            self.led_control.set_new_data((data[0], data[1], data[2], data[3]))

    def check_new_messages(self, alarm):
        self.client.check_msg()
コード例 #5
0
gc.collect()
scl = Pin(2)
sda = Pin(0)
gpio4 = Pin(4, Pin.OUT)
gpio13 = Pin(13, Pin.OUT)
i2c = I2C(scl=scl, sda=sda, freq=100000)
oled = SSD1306_I2C(128, 64, i2c)
oled.fill(0)
oled.text('ESP8266', 35, 5)
oled.text('MicroPython', 20, 20)
oled.show()

d = dht.DHT22(Pin(5))
client = MQTTClient(CLIENT_ID, 'q.emqtt.com', port=1883, keepalive=20)
will_msg = {'id': CLIENT_ID, 'status': False, 'msg': 'The connection from this device is lost:('}
client.set_last_will('/device/will/status', json.dumps(will_msg))
client.connect()
tim0 = Timer(0)

def display():
    d.measure()
    oled.fill(0)
    oled.text('ESP8266', 35, 5)
    oled.text('MicroPython', 20, 20)
    oled.text('T:{0:.2f} C'.format(d.temperature()), 3, 35) 
    oled.text('H:{0:.2f} %'.format(d.humidity()), 3, 50)
    oled.show()
    msg =  json.dumps({
        'heap': gc.mem_free(),
        'Type':7,
        'Id': CLIENT_ID,