Ejemplo n.º 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)
Ejemplo n.º 2
0
def main(led_pin):
    i2c = I2C(-1, scl=Pin(5), sda=Pin(4))
    pca = Servos(i2c, min_us=500, max_us=2500)

    def domoticz_out(topic, msg):
        data = json.loads(msg)
        if data['idx'] == settings.CURTAIN_IDX:
            if data['nvalue'] == 1:
                pca.position(0, us=500)
            else:
                pca.position(0, us=1500)

    mqtt = MQTTClient(settings.CLIENT_ID,
                      settings.MQTT_SERVER,
                      user=settings.MQTT_USER,
                      password=settings.MQTT_PASSWD)
    mqtt.set_callback(domoticz_out)
    mqtt.connect()
    mqtt.subscribe(settings.SUB_TOPIC)
    print('Connected to {}, subscribed to {} topic'.format(
        settings.MQTT_SERVER, settings.SUB_TOPIC))

    while True:
        led_pin.value(0)
        mqtt.check_msg()
        lightsleep(100)
        led_pin.value(1)
        lightsleep(1000)
Ejemplo n.º 3
0
    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()
Ejemplo n.º 4
0
    def __init__(self):
        self.keys = [Pin(p, Pin.IN) for p in [35, 36, 39, 34]]
        self.keymatch = ["Key1", "Key2", "Key3", "Key4"]
        self.select = 1
        self.displayInit()
        self.wifi_name = "NEUI"

        self.wifi_SSID = "NEUI3187"
        #MQTT服务端信息
        self.SERVER = "192.168.5.121"  #MQTT服务器地址
        self.SERVER_PORT = 1883  #MQTT服务器端口
        self.contentEVICE_ID = "wc001"  #设备ID
        self.TOPIC1 = b"/cloud-skids/online/dev/" + self.contentEVICE_ID
        self.TOPIC2 = b"/cloud-skids/message/server/" + self.contentEVICE_ID
        self.CLIENT_ID = "7e035cd4-15b4-4d4b-a706-abdb8151c57d"
        self.uart = UART(1,
                         baudrate=115200,
                         bits=8,
                         parity=0,
                         rx=18,
                         tx=19,
                         stop=1)
        #设备状态
        self.ON = "1"
        self.OFF = "0"

        self.content = " "  #初始化要发送的信息

        self.client = MQTTClient(self.CLIENT_ID, self.SERVER,
                                 self.SERVER_PORT)  #定义一个mqtt实例
Ejemplo n.º 5
0
    def __init__(self, config, data_collector, logger):
        self.sensor = data_collector
        self.Config = config
        self.Logger = logger
        self.AIO_SERVER = config["adafruit"]["AIO_SERVER"]
        self.AIO_PORT = config["adafruit"]["AIO_PORT"]
        self.AIO_USER = config["adafruit"]["AIO_USER"]
        self.AIO_KEY = config["adafruit"]["AIO_KEY"]
        self.AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id())
        self.AIO_CONTROL_FEED = config["adafruit"]["AIO_CONTROL_FEED"]
        self.AIO_MOVEMENT_FEED = config["adafruit"]["AIO_MOVEMENT_FEED"]
        self.AIO_GPS_FEED = config["adafruit"]["AIO_GPS_FEED"]
        self.AIO_ACCELERATION_FEED = config["adafruit"][
            "AIO_ACCELERATION_FEED"]
        self.last_random_sent_ticks = config["adafruit"][
            "last_random_sent_ticks"]
        self.post_per_minute = config["adafruit"]["post_per_minute"]
        """Finding and connecting to network"""
        self.wlan = WLAN(mode=WLAN.STA)
        nets = self.wlan.scan()
        print("Scanning for Wifi")
        for net in nets:
            for knowNet in self.Config["network"]:
                if net.ssid == knowNet["name"]:
                    print(net.ssid + ' found!')
                    self.wlan.connect(net.ssid,
                                      auth=(net.sec, knowNet["password"]),
                                      timeout=5000)
                    while not self.wlan.isconnected():
                        machine.idle()  # save power while waiting
                    print('WLAN connection succeeded!')
                    break

        self.client = MQTTClient(self.AIO_CLIENT_ID, self.AIO_SERVER,
                                 self.AIO_PORT, self.AIO_USER, self.AIO_KEY)
Ejemplo n.º 6
0
    def _init_mqtt(self):
        self.bs_config = bluestone_config.BluestoneConfig(
            'bluestone_config.json')
        self.bs_data_config = bluestone_config.BluestoneConfig(
            'bluestone_data.json')
        self.bs_gpio = bluestone_gpio.BluestoneGPIO()
        self.bs_pwm = bluestone_pwm.BluestonePWM()
        self.bs_fota = bluestone_fota.BluestoneFOTA()
        self.bs_uart = bluestone_uart.BlueStoneUart(None)

        # 创建一个MQTT实例
        self.client = MQTTClient(client_id=self.client_id,
                                 server=self.server,
                                 port=self.port,
                                 user=self.user,
                                 password=self.password,
                                 keepalive=30)
        _mqtt_log.info(
            "Start a new mqtt client, id:{}, server:{}, port:{}".format(
                self.client_id, self.server, self.port))

        self.client.set_callback(self._sub_callback)  # 设置消息回调
        self.client.connect()  # 建立连接

        #sub_topic = self.subscribe_topic.format(self.sn)
        _mqtt_log.info("Subscribe topic is {}".format(self.subscribe_topic))
        self.client.subscribe(self.subscribe_topic)  # 订阅主题
Ejemplo n.º 7
0
def wifi():
    global client
    global CLIENT_ID    
    client = MQTTClient(CLIENT_ID, '27.254.63.34', port=1883, user='******', password='******')
    client.connect() 
    print("MQTT client id:", CLIENT_ID)
    time.sleep(2)
    run()
Ejemplo n.º 8
0
def wifi():
    global client
    global CLIENT_ID    
    client = MQTTClient(CLIENT_ID, 'q.emqtt.com', port=1883)
    client.connect() 
    print("MQTT client id:", CLIENT_ID)
    time.sleep(2)
    run()
Ejemplo n.º 9
0
def wifi():
    global client
    global CLIENT_ID
    client = MQTTClient(CLIENT_ID, config.BROKER)
    client.connect()
    print("MQTT client id:", CLIENT_ID)
    time.sleep(2)
    run()
Ejemplo n.º 10
0
def mqtt_connect():
  client = MQTTClient(CLIENT_ID, SERVER, port=1883)
  client.set_callback(mqtt_callback)
  client.connect()
  print("mqtt connect success")
  client.subscribe(TOPIC)
  while True:
    client.check_msg()
    time.sleep(1)
    print("wait ...")
Ejemplo n.º 11
0
 def __init__(self):
     # 创建一个mqtt实例
     self.client_id = "868540051778302"
     self.downtopic = "quec/868540051778302/down"
     self.uptopic = "quec/868540051778302/up"
     self.mqttserver = "southbound.quectel.com"
     self.mqttport = 1883
     self.uername = "868540051778302"
     self.passwd = "d40332b8211097ffbb0e2645c2efec95"
     self.mqtt_client = MQTTClient(self.client_id, self.mqttserver,
                                   self.mqttport, self.uername, self.passwd)
Ejemplo n.º 12
0
def wifi(cfg):
    global client
    global CLIENT_ID
    client = MQTTClient(CLIENT_ID,
                        cfg['broker'],
                        port=cfg['port'],
                        keepalive=cfg["keepalive"])
    client.connect()
    print("MQTT client id:", CLIENT_ID)
    time.sleep(2)
    run()
Ejemplo n.º 13
0
def serverConnect():
    global CLIENT_ID
    CLIENT_ID = "fipy-pycom"  # The name you want to call your device.
    SERVER = "things.ubidots.com"  # The address to the Ubidots server.
    PORT = 1883
    USER = keys.ubidots_token()  # Your Ubidots token.
    KEY = ""  # Should be left empty.
    # END OFF SETTINGS

    # Using the MQTT protocol to connect to Ubidots.
    global client
    client = MQTTClient(CLIENT_ID, SERVER, PORT, USER, KEY)
    client.connect()  # Establishes the connection to Ubidots.
Ejemplo n.º 14
0
def sendmq(msg):
    UNIQUE_ID = ubinascii.hexlify(machine.unique_id())
    MQTT_BROKER = "192.168.2.68"
    MQTT_PORT = 1883
    MQTT_TOPIC = "iot-2/type/lopy/id/" + "buhardilla" + "/evt/presence1/fmt/json"
    print(MQTT_TOPIC)
    mqtt_client = MQTTClient(UNIQUE_ID, MQTT_BROKER, port=MQTT_PORT)
    mqtt_client.settimeout = settimeout
    mqtt_client.set_callback(t3_publication)
    mqtt_client.connect()
    result = mqtt_client.publish(MQTT_TOPIC, json.dumps(msg))
    mqtt_client.disconnect()
    return result
Ejemplo n.º 15
0
 def MQTTclient(self):
     "Protocolo MQTT en modo cliente, Configuración"
     from ubinascii import hexlify
     from machine import unique_id
     from umqtt import MQTTClient  # import socket library (umqtt)
     # Config
     SERVER = "172.24.1.1"  # <----------------------------CONFIGURE: BROKER
     CLIENT_ID = hexlify(unique_id())
     self.TOPIC1 = b"/cultivo/temp"
     self.TOPIC2 = b"/cultivo/hum"
     self.TOPIC3 = b"/sensor1/set/temp"
     self.TOPIC4 = b"/sensor1/set/hum"
     self.TOPIC5 = b"/sensor1/alarma"
     self.client_mqtt = MQTTClient(CLIENT_ID, SERVER)
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
def connect_and_subscribe():
    global client
    client = MQTTClient(CONFIG['client_id'], CONFIG['broker'])
    client.set_callback(callback)
    client.connect()
    print("Connected to {}".format(CONFIG['broker']))
    topic = topic_name(b"control")
    client.subscribe(topic)
    print("Subscribed to {}".format(topic))
Ejemplo n.º 18
0
def envioMQTT(server=SERVER, topic="/foo", dato=None):
    try:
        c = MQTTClient(CLIENT_ID, server)
        c.connect()
        c.publish(topic, dato)
        sleep_ms(200)
        c.disconnect()
        #led.value(1)
    except Exception as e:
        pass
Ejemplo n.º 19
0
 def __init__(self, playerName, computerName):  #初始化
     #网络设定
     #WiFi名称和密码
     self.wifi_name = "NEUI"
     self.wifi_SSID = "NEUI3187"
     #MQTT服务端信息
     SERVER = "112.125.89.85"  #MQTT服务器地址
     SERVER_PORT = 3881  #MQTT服务器端口
     DEVICE_ID = "wc001"  #设备ID
     TOPIC1 = b"/cloud-skids/online/dev/" + DEVICE_ID
     self.TOPIC2 = b"/cloud-skids/message/server/" + DEVICE_ID
     CLIENT_ID = "f25410646a8348f8a1726a3890ad8f82"
     #设备状态
     ON = "1"
     OFF = "0"
     #对方的选择
     self.d = ["1", "2", "3"]
     self.choose = 0
     self.mark = 0
     #启动网络连接
     self.do_connect()
     gc.collect()
     self.client = MQTTClient(CLIENT_ID, SERVER, SERVER_PORT)
     self.client.set_callback(self.sub_cb)  #设置回调
     self.client.connect()
     print("连接到服务器:%s" % SERVER)
     self.client.publish(TOPIC1, ON)  #发布“1”到TOPIC1
     self.client.subscribe(self.TOPIC2)  #订阅TOPIC
     #游戏设定
     self.gameStart = False
     self.playerName = playerName
     self.computerName = computerName
     self.playerScore = 0
     self.computerScore = 0
     self.equalNum = 0
     self.playerStatus = 0
     self.playerMessage = ""
     self.computerStatus = 0
     self.computerMessage = ""
     for p in pins:
         keys.append(Pin(p, Pin.IN))
     self.displayInit()
Ejemplo n.º 20
0
    def connect(self):
        """ Attempts to establish a connection to Losant.
        Will be blocking or non-blocking depending on the value of
        the 'blocking' argument.  When non-blocking, the 'loop' function
        must be called to perform network activity.
        """
        if self._mqtt_client:
            return

        self._initial_connect = True

        port = 1883

        self._mqtt_client = MQTTClient(self._device_id, self.mqtt_endpoint,
                                       port, self._key, self._secret)

        print("Connecting to Losant as {}".format(self._device_id))

        resp = self._mqtt_client.connect()
        self._cb_client_connect(resp)
Ejemplo n.º 21
0
def envioMQTT(server=SERVER, topic="/foo", dato=None):
    try:
        c = MQTTClient(CLIENT_ID, server)
        c.connect()
        c.publish(topic, dato)
        sleep_ms(200)
        c.disconnect()
        #led.value(1)
    except Exception as e:
        pass
Ejemplo n.º 22
0
 def connect(self, keepAlive, clean_session):
     self.formatConnectInfo()
     mqtt_client = MQTTClient(self.clientid, self.mqtt_server, 1883,
                              self.username, self.password, keepAlive)
     mqtt_client.connect(clean_session=clean_session)
     mqtt_client.set_callback(self.proc)
     return mqtt_client
Ejemplo n.º 23
0
 def connect(self, mqt_id, secret, hmac_msg, keepAlive, clean_session, ssl):
     mqt_server = MQTT_SERVER.format(self.productKey)
     self.password = hmac.new(bytes(secret, "utf8"),
                              msg=bytes(hmac_msg, "utf8"),
                              digestmod=sha256).hexdigest()
     mqtt_client = MQTTClient(mqt_id,
                              mqt_server,
                              self.port,
                              self.username,
                              self.password,
                              keepAlive,
                              ssl=ssl)
     mqtt_client.set_callback(self.proc)
     mqtt_client.connect(clean_session=clean_session)
     return mqtt_client
Ejemplo n.º 24
0
class pics():
    def __init__(self):
        self.keys = [Pin(p, Pin.IN) for p in [35, 36, 39, 34]]
        self.keymatch = ["Key1", "Key2", "Key3", "Key4"]
        self.select = 1
        self.displayInit()
        self.wifi_name = "NEUI"

        self.wifi_SSID = "NEUI3187"
        #MQTT服务端信息
        self.SERVER = "192.168.5.121"  #MQTT服务器地址
        self.SERVER_PORT = 1883  #MQTT服务器端口
        self.contentEVICE_ID = "wc001"  #设备ID
        self.TOPIC1 = b"/cloud-skids/online/dev/" + self.contentEVICE_ID
        self.TOPIC2 = b"/cloud-skids/message/server/" + self.contentEVICE_ID
        self.CLIENT_ID = "7e035cd4-15b4-4d4b-a706-abdb8151c57d"
        self.uart = UART(1,
                         baudrate=115200,
                         bits=8,
                         parity=0,
                         rx=18,
                         tx=19,
                         stop=1)
        #设备状态
        self.ON = "1"
        self.OFF = "0"

        self.content = " "  #初始化要发送的信息

        self.client = MQTTClient(self.CLIENT_ID, self.SERVER,
                                 self.SERVER_PORT)  #定义一个mqtt实例

    def drawInterface(self):  #界面初始化

        bmp1 = ubitmap.BitmapFromFile("pic/boy")

        bmp2 = ubitmap.BitmapFromFile("pic/girl")
        bmp1.draw(20, 200)  #显示boy图片
        bmp2.draw(140, 200)  #显示girl图片
        screen.drawline(0, 160, 240, 160, 2, 0xff0000)

    def do_connect(self):
        sta_if = network.WLAN(network.STA_IF)  #STA模式
        ap_if = network.WLAN(network.AP_IF)  #AP模式
        if ap_if.active():
            ap_if.active(False)  #关闭AP
        if not sta_if.isconnected():
            print('Connecting to network...')
        sta_if.active(True)  #激活STA
        sta_if.connect(self.wifi_name, self.wifi_SSID)  #WiFi的SSID和密码
        while not sta_if.isconnected():
            pass
        print('Network config:', sta_if.ifconfig())
        gc.collect()

    def selectInit(self):  #选择表情初始化
        screen.drawline(20, 200, 92, 200, 2, 0xff0000)
        screen.drawline(92, 200, 92, 272, 2, 0xff0000)
        screen.drawline(92, 272, 20, 272, 2, 0xff0000)
        screen.drawline(20, 272, 20, 200, 2, 0xff0000)

    def displayInit(self):  #初始化
        screen.clear()
        self.drawInterface()
        self.selectInit()

    def esp(self):
        self.client.set_callback(self.sub_cb)  #设置回调
        self.client.connect()
        print("连接到服务器:%s" % self.SERVER)
        self.client.publish(self.TOPIC1, self.ON)  #发布“1”到TOPIC1
        self.client.subscribe(self.TOPIC2)  #订阅TOPIC
        #display.text("从微信取得信息", 20, 20, 0xf000, 0xffff)

    def keyboardEvent(self, key):
        if self.keymatch[key] == "Key1":  #右移键,选择要发送的表情
            if self.select % 2 == 1:  #用红色框选中boy表情
                screen.drawline(20, 200, 92, 200, 2, 0xffffff)
                screen.drawline(92, 200, 92, 272, 2, 0xffffff)
                screen.drawline(92, 272, 20, 272, 2, 0xffffff)
                screen.drawline(20, 272, 20, 200, 2, 0xffffff)
                screen.drawline(140, 200, 212, 200, 2, 0xff0000)
                screen.drawline(212, 200, 212, 272, 2, 0xff0000)
                screen.drawline(212, 272, 140, 272, 2, 0xff0000)
                screen.drawline(140, 272, 140, 200, 2, 0xff0000)
                self.select += 1
            else:  #用红色框选中girl表情
                screen.drawline(140, 200, 212, 200, 2, 0xffffff)
                screen.drawline(212, 200, 212, 272, 2, 0xffffff)
                screen.drawline(212, 272, 140, 272, 2, 0xffffff)
                screen.drawline(140, 272, 140, 200, 2, 0xffffff)
                screen.drawline(20, 200, 92, 200, 2, 0xff0000)
                screen.drawline(92, 200, 92, 272, 2, 0xff0000)
                screen.drawline(92, 272, 20, 272, 2, 0xff0000)
                screen.drawline(20, 272, 20, 200, 2, 0xff0000)
                self.select += 1
        if self.keymatch[key] == "Key3":  #发送表情按键
            if self.select % 2 == 1:  #显示已发送boy表情
                bmp1 = ubitmap.BitmapFromFile("pic/boy")

                bmp1.draw(140, 40)

                self.content = "001"

                self.client.publish(self.TOPIC2, self.content)  #给服务器发送boy表情的号码

            else:  #显示已发送girl表情

                bmp2 = ubitmap.BitmapFromFile("pic/girl")

                bmp2.draw(140, 40)

                self.content = "002"
                self.client.publish(self.TOPIC2,
                                    self.content)  #给服务器发送girl表情的号码

    def sub_cb(self, topic, message):  #从服务器接受信息
        message = message.decode()
        print("服务器发来信息:%s" % message)
        #global count
        if message == "001":  #收到boy表情号码显示boy表情
            bmp1 = ubitmap.BitmapFromFile("pic/boy")
            bmp1.draw(140, 40)
        elif message == "002":  #收到girl表情号码显示girl表情
            bmp1 = ubitmap.BitmapFromFile("pic/girl")
            bmp1.draw(140, 40)

    def start(self):
        try:
            while True:
                self.client.check_msg()  #检查是否收到信息
                i = 0  #用来辅助判断那个按键被按下
                j = -1
                for k in self.keys:  #检查按键是否被按下
                    if (k.value() == 0):  ##如果按键被按下

                        if i != j:
                            j = i
                            self.keyboardEvent(i)  #触发相应按键对应事件
                    i = i + 1
                    if (i > 3):
                        i = 0
                time.sleep_ms(130)
        finally:
            self.client.disconnect()
            print("MQTT连接断开")
Ejemplo n.º 25
0
def recepcionMQTT(server=SERVER, topic=TOPIC3):
    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:
        c.wait_msg()
    finally:
        c.disconnect()
Ejemplo n.º 26
0
while not wlan.isconnected():  # Code waits here until WiFi connects
    machine.idle()

print("Connected to Wifi")
print(wlan.ifconfig())
pycom.rgbled(0xf0d0000)  # Status orange: partially working
time.sleep(1)
pycom.rgbled(0x000000)

# Use the MQTT protocol to connect to Bluemix
print("Try to connect to IBM iot")
myiotorg = "5q6gu4"
client = MQTTClient("d:" + myiotorg + ":playbulb:playbulb30",
                    myiotorg + ".messaging.internetofthings.ibmcloud.com",
                    port=1883,
                    user="******",
                    password="******")
#client = MQTTClient(“d:<ORG Id>:<Device Type>:<Device Id>“, “<ORG Id>.messaging.internetofthings.ibmcloud.com”,user=”use-token-auth”, password=”<TOKEN>“, port=1883)
#print(client)
# Subscribed messages will be delivered to this callback
client.set_callback(sub_cb)
client.connect()
#client.subscribe(AIO_CONTROL_FEED)
#print("Connected to %s, subscribed to %s topic" % (AIO_SERVER, AIO_CONTROL_FEED))
print("Connected to Bluemix")
pycom.rgbled(0x00f000)  # Status green: online to Bluemix
#Publish a Hallo
#msg={"id":'+ubinascii.hexlify(network.LoRa().mac()).decode("utf-8")+',"value":"hello","type":"GW","msgid":0}
#o = json.loads(msg)
#o['type']="GW"
Ejemplo n.º 27
0
led = machine.Pin(2, machine.Pin.OUT, value=1)
s_dht = dht.DHT22(machine.Pin(4))
s_dht.measure()
print("Temperatura ", s_dht.temperature())  # Debug
print("Temperatura ", s_dht.humidity())  # Debug

# Config
SERVER = "192.168.31.16"
CLIENT_ID = hexlify(unique_id())
TOPIC1 = b"/cultivo/temp"
TOPIC2 = b"/cultivo/hum"
TOPIC3 = b"/sensor1/set/temp"
TOPIC4 = b"/sensor1/set/hum"
TOPIC5 = b"/cultivo/alarma"
state = 0
client_mqtt = MQTTClient(CLIENT_ID, SERVER)
# Envio
client_mqtt.connect()
client_mqtt.publish(TOPIC1, str(s_dht.temperature()))
client_mqtt.publish(TOPIC2, str(s_dht.humidity()))
sleep_ms(200)
client_mqtt.disconnect()


# Recepcion
def sub_cb(topic, msg):
    global state
    print((topic, msg))
    if msg == b"on":
        led.value(0)
        state = 1
Ejemplo n.º 28
0
from umqtt import MQTTClient
import machine, ubinascii
import time
import network

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('HUAWEI', '0000000000')
while not wlan.isconnected():
    print('Wait connection')
    time.sleep(1)


def on_message(topic, msg):
    print(topic, msg)


CLIENT_ID = ubinascii.hexlify(machine.unique_id())
client = MQTTClient(CLIENT_ID, 'iot.eclipse.org', port=1883)
client.set_callback(on_message)
client.connect()
client.subscribe('micro/python/test')

while True:
    client.wait_msg()
Ejemplo n.º 29
0
Archivo: code.py Proyecto: chain01/wiki
from umqtt import MQTTClient
state = 0


def sub_cb(topic, msg):
    global state
    print("subscribe recv:")
    print(topic, msg)
    state = 1


#创建一个 mqtt 实例
c = MQTTClient("umqtt_client", "mq.tongxinmao.com", '18830')
#设置消息回调
c.set_callback(sub_cb)
#建立连接
c.connect()
#订阅主题
c.subscribe(b"/public/TEST/quecpython")
print(
    "Connected to mq.tongxinmao.com, subscribed to /public/TEST/quecpython topic"
)
#发布消息
c.publish(b"/public/TEST/quecpython", b"my name is Kingka!")
print("Publish topic: /public/TEST/quecpython, msg: my name is Quecpython")

while True:
    c.wait_msg()  #阻塞函数,监听消息
    if state == 1:
        break
#关闭连接
Ejemplo n.º 30
0
def recepcionMQTT(server=SERVER, topic=TOPIC3):
    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:
        c.wait_msg()
    finally:
        c.disconnect()
Ejemplo n.º 31
0
from umqtt import MQTTClient
import machine, ubinascii
import time, gc
import network
import json, errno
from dht import DHT22
from machine import Pin, I2C, Timer, ADC
from ssd1306 import SSD1306_I2C
import _thread as th
a1 = ADC(Pin(32))
a2 = ADC(Pin(33))
a3 = ADC(Pin(34))
scl = Pin(22)
sda = Pin(21)
i2c = I2C(scl=scl, sda=sda, freq=100000) 
oled = SSD1306_I2C(128, 64, i2c)
oled.fill(0)
oled.text('ESP32', 45, 5)
oled.text('MicroPython', 20, 20)
oled.text('System Startimg', 3, 35) 
oled.show()
dhtPn = Pin(17)
d = DHT22(dhtPn)
tim0 = Timer(0)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('see_dum', '0863219053')
while not wlan.isconnected():
    print('Wait connection')
    time.sleep(1)
Ejemplo n.º 32
0
from machine import I2C, Pin
from dht12 import DHT12
from BH1750 import BH1750
import ssd1306
import time, json, machine, ubinascii
import _thread as th
from umqtt import MQTTClient
import wifi_connect as wlan
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
client = None
# OLED
rst = Pin(16, Pin.OUT)
rst.value(1)
oledScl = Pin(15, Pin.OUT, Pin.PULL_UP)
oledSda = Pin(4, Pin.OUT, Pin.PULL_UP)
i2cOled = I2C(scl=oledScl, sda=oledSda, freq=450000)
oled = ssd1306.SSD1306_I2C(128, 64, i2cOled, addr=0x3c)
oled.fill(0)
oled.text('SENSOR', 40, 5)
oled.text('MicroPython', 10, 20)
oled.text('Waiting...', 10, 35)
oled.show()
wlan.connect()
oled.text('{0}'.format(wlan.get_ip()), 10, 50)
oled.show()
# MQTTClient
time.sleep(3)

def on_message(topic, msg):
    print(topic, msg)