示例#1
0
def main():
    try:
        global mqtt_hostname, mqtt_server, wifi_ap
        _thread.start_new_thread("led-animation", ledThread, ())
        _buttons.register(0)
        _buttons.attach(0, buttonHandler)
        mqtt = MQTTClient(mqtt_hostname, mqtt_server)
        mqtt.set_callback(mqttHandler)

        while True:
            if wifi_ap:
                mqtt.disconnect()
                break
            if not wifi.status():
                connectToWiFi()
                mqtt.connect()
                mqtt.subscribe(b"hoera10jaar/+")
            else:
                mqtt.check_msg()
            time.sleep(0.1)
    except BaseException as e:
        print("MAIN THREAD CRASHED")
        print(e)
        time.sleep(2)
        system.home()
示例#2
0
def subscribe_test(client_id=CLIENT_ID,
                   hostname=AWS_ENDPOINT,
                   sslp=SSL_PARAMS,
                   msg_limit=2):
    """
    Connects to AWS, subscribes to a topic and starts listening for messages.

    :param client_id: Unique identifier for the device connected.
    :param hostname: AWS hostname to connect to.
    :param sslp: SSL certificate parameters.
    :param msg_limit: Maximum number of messages to receive before
        disconnecting from AWS..
    """

    global msgs_received

    # Connect to AWS.
    client = MQTTClient(client_id, hostname, ssl=True, ssl_params=sslp)
    client.set_callback(sub_cb)
    print("- Connecting to AWS... ", end="")
    client.connect()
    print("[OK]")
    # Subscribe to topic.
    print("- Subscribing to topic '%s'... " % TOPIC, end="")
    client.subscribe(TOPIC)
    print("[OK]")
    # Wait for messages.
    msgs_received = 0
    print('- Waiting for messages...')
    while msgs_received < msg_limit:
        client.check_msg()
        time.sleep(1)
    # Disconnect.
    client.disconnect()
    print("- Done")
示例#3
0
def mqtt_sub():
    import time
    from umqtt.simple import MQTTClient

    # Received messages from subscriptions will be delivered to this callback
    def sub_callback(topic, msg):
        print((topic, msg))

    _broker = '192.168.0.100'
    _port = 1883
    _topic = b'Debug'

    _client = MQTTClient(client_id="ESP8266", server=_broker, port=_port)
    _client.set_callback(sub_callback)
    _client.connect()
    _client.subscribe(_topic)
    while True:
        if True:
            # Blocking wait for message
            _client.wait_msg()
        else:
            # Non-blocking wait for message
            _client.check_msg()

            # Sleep to avoid 100% CPU usage
            time.sleep_ms(500)
    _client.disconnect()
示例#4
0
    def run(self, server=SERVER):
        """ Connects to Homeassistant, listen for changes and update led """
        led = Led()
        rainbow = Rainbow()

        c = MQTTClient(CLIENT_ID, server)
        c.set_callback(self.sub_callback)
        c.connect()
        c.subscribe(TOPIC)
        print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

        try:
            while True:
                c.check_msg()
                if self.updated == True:
                    led.update_colors(self.red, self.green, self.blue)
                    self.updated = False

                if ure.match('OFF', self.ledstate): 
                    led.turn_off()
                elif ure.match('rainbow', self.effect):
                    rainbow.show(60)
                elif ure.match('rainbow_slow', self.effect):
                    rainbow.show(100)
                elif ure.match('rainbow_fast', self.effect):
                    rainbow.show(30)
                else:
                    led.change_nyance()
                    time.sleep_ms(10)

        finally:
            c.disconnect()
示例#5
0
def main(mqtt_broker='test.mosquitto.org',
         mqtt_port=1883,
         mqtt_user=None,
         mqtt_password=None,
         client_id=None,
         command_topic=None):

    global COMMAND_TOPIC, CLIENT_ID

    if client_id:
        CLIENT_ID = client_id
    if command_topic:
        COMMAND_TOPIC = command_topic

    mqtt = MQTTClient(CLIENT_ID, mqtt_broker, mqtt_port, mqtt_user,
                      mqtt_password)
    mqtt.set_callback(mqtt_cb)
    mqtt.connect()
    mqtt.subscribe(COMMAND_TOPIC)

    print("链接到服务器:{s},端口:{p}".format(s=mqtt_broker, p=mqtt_port))
    print("接受命令topic:开关({c})".format(c=COMMAND_TOPIC))

    while True:
        mqtt.check_msg()
示例#6
0
def sub_topic(server="localhost"):
    client  = MQTTClient(machine.unique_id(), '192.168.0.10')
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(b"ESYS/netball")
    client.check_msg()
    client.disconnect()
示例#7
0
def main(server=SERVER):
    global newmessage
    out()
    do_connect()
    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.check_msg()
            #print (type(c.check_msg()))
            #a = c.check.msg()
            #if a is not None:
            #    newmessage = True
            #elif c.check.msg() is None:
            #    newmessage = False
            time.sleep(1)

    finally:
        c.disconnect()
示例#8
0
def main():
    client = MQTTClient(client_id=config['id'],
                        server=config['broker'],
                        user=config['user'],
                        password=config['key'])
    client.set_callback(subCallback)
    client.connect()
    client.subscribe(config['topic'])

    try:
        while True:
            client.check_msg()
            time.sleep(2)
    except KeyboardInterrupt:
        print('bye')
    except OSError as ex:
        print(ex.args[0])
        if ex.args[0] == -1:
            print('woooops')
            gc.collect()
            time.sleep(1)
            main()
        # ---
    finally:
        client.disconnect()
示例#9
0
class Mimqtt():
    def __init__(self):
        id_cliente = "12hi3b1i2n98dno2jnd921"
        mqtt_server = "broker.hivemq.com"
        self.client = MQTTClient(id_cliente, mqtt_server)
        self.client.set_callback(self.mqtt_callback)
        self.client.connect()
        self.client.subscribe(b'curso_eoi')

    def enviar_mqtt(self, nombre, metodo, tiempo):
        topic = b'curso_eoi'
        datos = {"Nombre": nombre, "Metodo": metodo, "Tiempo": tiempo}
        datos = json.dumps(datos)
        self.client.publish(topic, datos)

    def mqtt_callback(self, topic, msg):
        try:
            datos = json.loads(msg.decode())
        except ValueError:
            print("mensaje invalido")
        print("me llego por '{}' esto: {}".format(topic, msg))

    def comprobar_mensajes(self):
        for i in range(10):
            self.client.check_msg()
            time.sleep_ms(10)
示例#10
0
文件: main.py 项目: Nordln/HackyLEDS
def main(server=SERVER, port=PORT, user=USER, password=PASSWORD):
    global MSGQ
    print("Connecting")
    c = MQTTClient(CLIENT_ID, server, port, user, password)
    try:
        c.connect()
    except OSError as exc:
        machine.reset()

    print("Connected to %s" % server)
    c.set_callback(sub_cb)
    c.subscribe(COMMAND_TOPIC_PWR)
    c.subscribe(COMMAND_TOPIC_DIMMER)
    c.subscribe(COMMAND_TOPIC_EFFECT)
    c.subscribe(COMMAND_TOPIC_RGB)

    # set to off on connect
    pin_red.duty(0)
    pin_green.duty(0)
    pin_blue.duty(0)

    while True:
        c.check_msg()
        if MSGQ != []:
            currItem = MSGQ.pop()
            c.publish(currItem[0], currItem[1])
    c.disconnect()
示例#11
0
class IOClient:

    def __init__(self):
        self._client = ubinascii.hexlify(machine.unique_id())
        self._feed = credentials.adafruitUsername + "/feeds/"
        self._url = "io.adafruit.com"
        self._sta_if = network.WLAN(network.STA_IF)
        self._io = MQTTClient(self._client, self._url, 0, credentials.adafruitUsername, credentials.adafruitAioKey)
        self._data = dict([('temperature', 0), ('humidity', 0), ('pressure', 0), ('gas', 0), ('battery', 0)])

    def publish(self):
        if not self._sta_if.isconnected():
            self._sta_if.active(True)
            self._sta_if.connect(credentials.wifiSsid, credentials.wifiPassword)
            while not self._sta_if.isconnected():
                pass

        self._io.connect()
        for k, v in self._data.items():
            feed = self._feed + k
            self._io.publish(feed, str(v))

        self._io.check_msg()
        self._io.disconnect()
        self._sta_if.disconnect()
        self._sta_if.active(False)

    def update(self, t, h, p, g, b):
        self._data['temperature'] = t
        self._data['humidity'] = h
        self._data['pressure'] = p
        self._data['gas'] = g
        self._data['battery'] = b
示例#12
0
def main(server=env['MQTT_SERVER'],
         user=env['MQTT_USER'],
         password=env['MQTT_PASSWORD'],
         port=env['MQTT_PORT']):

    c = MQTTClient("umqtt_client",
                   server,
                   user=user,
                   password=password,
                   port=port)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(bytes(env['TW_STREAM_TOPIC']))
    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()
示例#13
0
class MqttClient:
    def __init__(self, client_id, host, port, user=None, password=None):
        self.client = MQTTClient(client_id,
                                 host,
                                 port=port,
                                 user=user,
                                 password=password)
        self.client.set_callback(self.sub_cb)
        self.client.connect()

    def subscribe(self, topic):
        self.client.subscribe(topic.encode())

    def sub_cb(self, topic, msg):
        topic = topic.decode("utf-8").lower()
        msg = msg.decode("utf-8").lower()
        if topic == "klo/switch":
            global led
            if msg == "on":
                led.switch_on()
            elif msg == "off":
                led.switch_off()

    def check_msg(self):
        self.client.check_msg()
        time.sleep_ms(100)

    def publish(self, topic, msg):
        self.client.publish(topic, msg.encode())
示例#14
0
def main(mqtt_broker='test.mosquitto.org',
         mqtt_port=1883,
         mqtt_user=None,
         mqtt_password=None,
         client_id=CLIENT_ID):

    global mqtt

    # 此处增加keepalive=60,表示60秒以上未通讯,客户端为断开
    mqtt = MQTTClient(client_id,
                      mqtt_broker,
                      mqtt_port,
                      mqtt_user,
                      mqtt_password,
                      keepalive=60)
    mqtt.set_callback(mqtt_cb)
    # 设置lastwill,相应消息会在断开mqtt连接后自动在服务器端发布
    # 注:在connect之前设置lastwill
    mqtt.set_last_will(AVAILABILITY_TOPIC, b"offline", retain=True)

    mqtt.connect()
    mqtt.subscribe(COMMAND_TOPIC)
    mqtt.publish(AVAILABILITY_TOPIC, b"online", retain=True)
    state = b"ON" if LED.value() == 1 else b"OFF"
    mqtt.publish(STATE_TOPIC, state, retain=True)

    print("链接到服务器:{s},端口:{p}".format(s=mqtt_broker, p=mqtt_port))
    print("接受命令topic:开关({c})".format(c=COMMAND_TOPIC))

    while True:
        mqtt.check_msg()
示例#15
0
 def connect(self):
     fail_notified = False
     while True:
         try:
             c = MQTTClient(self.uuid,
                            self.ip,
                            self.port,
                            self.user,
                            self.password,
                            keepalive=120)
             c.set_callback(self.callback)
             c.connect()
             c.subscribe(self.topic)
             try:
                 while True:
                     fail_notified = False
                     if True:
                         c.wait_msg()
                     else:
                         c.check_msg()
                         time.sleep(1)
             except Exception as e:
                 if not fail_notified:
                     fail_notified = True
                     log("Subscribe: {}".format(e))
                     c.disconnect()
         except Exception as e:
             if not fail_notified:
                 fail_notified = True
                 log("Subscribe-connection: {}".format(e))
         time.sleep(5)
示例#16
0
def main( mqtt_broker='test.mosquitto.org', mqtt_port=1883, mqtt_user=None, mqtt_password=None, client_id=CLIENT_ID):

    global mqtt

    mqtt = MQTTClient( client_id, mqtt_broker, mqtt_port, mqtt_user, mqtt_password, keepalive=60 )
    mqtt.set_callback(mqtt_cb)
    mqtt.set_last_will( AVAILABILITY_TOPIC, b"offline", retain=True)

    mqtt.connect()
    mqtt.subscribe(COMMAND_TOPIC)

    #此处增加对亮度命令的订阅
    mqtt.subscribe(BRIGHTNESS_COMMAND_TOPIC)

    mqtt.publish( CONFIG_TOPIC, CONFIG_DATA.encode(), retain=True)
    mqtt.publish( AVAILABILITY_TOPIC, b"online", retain=True)

    mqtt.publish( STATE_TOPIC, light_state.encode(), retain=True )
    mqtt.publish( BRIGHTNESS_STATE_TOPIC, str(light_brightness).encode(), retain=True )

    print("链接到服务器:{s},端口:{p}".format(s=mqtt_broker,p=mqtt_port))
    print("接受开关命令topic:开关({c})".format(c=COMMAND_TOPIC))
    print("接受亮度命令topic:开关({c})".format(c=BRIGHTNESS_COMMAND_TOPIC))

    while True:
        mqtt.check_msg()
示例#17
0
def main(server=SERVER_IP):
    while True:
        client = MQTTClient(
            SERVER_NAME,
            server, port=1883,
            user=USER,
            password=PASSWD
        )
        client.set_callback(sub_cb)
        client.connect()
        client.subscribe(t_sub, qos=1)

        # Currently the two sleep calls below are necessary to get check_msg() to run.
        # Need to figure out why, because as it is right now it is possible to miss commands
        # between disconnect and reconnect.
        sleep(1)
        client.check_msg()
        sleep(1)

        if switch.value() == 0:
            pub = 'OPEN'
        elif switch.value() == 1:
            pub = 'CLOSED'
        else:
            pub = 'ERR'
        
        # Publish message based on above, and set quality of service to 1 (see mqtt docs).
        client.publish(topic=t_pub, msg=pub, qos=1)
        client.disconnect()
示例#18
0
def main():

    do_connect_wifi()

    c = MQTTClient(CLIENT_ID, SERVER, PORT, USER, PASSWORD)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect(clean_session=False)
    c.subscribe(TOPIC, qos=1)
    print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC))

    try:
        while 1:

            if not network.WLAN(network.STA_IF).isconnected():
                do_connect_wifi()

            try:
                print('check mensage...')
                c.check_msg()
            except:
                print('error on check mensage...')
                while 1:
                    try:
                        print('try reconnect...')
                        c.connect(False)
                        break
                    except:
                        print('error on reconnect...')

                    time.sleep(2)

            time.sleep(2)
    finally:
        c.disconnect()
示例#19
0
class AWSShadow:
    def __init__(self, client_id=imei, hostname=aws_endpoint, sslp=ssl_params):
        self.client = MQTTClient(client_id,
                                 hostname,
                                 ssl=True,
                                 ssl_params=sslp)
        self.client.set_callback(delta_callback)
        self.shadowpath = "$aws/things/{}/shadow/".format(imei)
        print(self.shadowpath)
        self.connected = False

    def is_connected(self):
        return self.connected

    def connect(self):
        try:
            print("trying MQTT")
            self.client.connect()
            self.connected = True
            self.client.subscribe(self.shadowpath + "update/delta")
            print("subscribed to {}".format(self.shadowpath + "update/delta"))
            print("connected to MQTT")
        except OSError as e:
            print_exception(e)
            self.connected = False

    @staticmethod
    def _get_on_off(value):
        if value:
            return 'on'
        else:
            return 'off'

    def update(self, light, nightlight, lumens):
        try:
            print("updating shadow")
            telemetry = {"lumens": lumens}
            state = {
                "state": {
                    "reported": {
                        "light_state": self._get_on_off(light),
                        "night_light_state": self._get_on_off(nightlight)
                    },
                    "desired": None
                }
            }
            telemetry_path = "smartswitch/{}/lumens/".format(imei)
            shadow_path = "$aws/things/{}/shadow/".format(imei)
            print(shadow_path)
            self.client.publish(telemetry_path, ujson.dumps(telemetry))
            print("updated {}".format(telemetry_path))
            self.client.publish(shadow_path + "update", ujson.dumps(state))
            print("updated {}".format(shadow_path))
            return True
        except OSError:
            self.connected = False

    def check(self):
        self.client.check_msg()
class mqtt_client():
    def __init__(self, topics, callback, client_id, mqtt_server_ip):
        self.server_ip = mqtt_server_ip
        self.id = client_id
        self.__mqtt_client = MQTTClient(self.id, self.server_ip)
        self.topics = topics
        print(self.topics)
        self.__callback = callback
        self.connected = False
        self.__connect()

    def __connect(self):
        try:
            #            print('id', self.id, 'ip' , self.server_ip)
            myclient = MQTTClient(self.id, self.server_ip)
            self.__mqtt_client = MQTTClient(self.id, self.server_ip)
            self.__mqtt_client.set_callback(self.__callback)
            self.__mqtt_client.connect()
            for tpc in self.topics:
                print('subscribing to topic ', tpc)
                self.__mqtt_client.subscribe(tpc)
            print('connected to mqtt server at {}'.format(self.server_ip))
            self.connected = True
        except OSError:
            print('unable to connect to mqtt server')
            self.connected = False
            time.sleep_ms(1000)

    def check_msg(self):
        try:
            self.__mqtt_client.check_msg()
            self.connected = True
        except OSError:
            self.connected = False

    def wait_msg(self):
        try:
            self.__mqtt_client.wait_msg()
            self.connected = True
        except OSError:
            self.connected = False

    def send_msg(self, topic, message):
        tpc = topic
        msg = message
        try:
            self.__mqtt_client.publish(tpc, msg, 0, True)
            print('published topic {}, message {}'.format(topic, message))
            self.connected = True
        except OSError:
            self.connected = False

    def is_alive(self):
        # check if connected is true and reconnect if it is not. if succesful, the
        # function will return true, otherwise, false
        if not self.connected:
            self.__connect()
        return self.connected
示例#21
0
def main(server):
    init()
    c = MQTTClient(CLIENT_ID, server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    while True:
        c.check_msg()
        dopattern()
    c.disconnect()
def mqtt_sub( server, topic, callback ):
    c = MQTTClient( "umqtt_client", server )
    c.set_callback( callback )
    c.connect()
    c.subscribe( topic )
    try:
        while True:
            c.check_msg()
    finally:
        c.disconnect()
示例#23
0
def mqttmain():
    SERVER = '192.168.3.104'
    CLIENT_ID = 'PYESPCAR_A1'
    TOPIC = b'carcontrol'
    client = MQTTClient(CLIENT_ID, SERVER)
    client.set_callback(mqtt_callback)
    client.connect()
    client.subscribe(TOPIC)
    while True:
        client.check_msg()
        time.sleep(1)
示例#24
0
class mqtt:
    def __init__(self, config, sub, receive):
        f = open('password.json', 'r')
        pwd = ujson.loads(f.read())
        f.close()

        self._client = MQTTClient(client_id=ubinascii.hexlify(
            machine.unique_id()),
                                  server=config["server"],
                                  user=pwd["user"],
                                  password=pwd["password"],
                                  keepalive=10)
        self._client.set_callback(self._callback)
        self._client.set_last_will(
            topic=self.tstatus,
            msg=b'{"battery":0.0,"connected":false,"load":0.0}',
            retain=True,
            qos=1)
        self._sub = sub
        self._receive = receive
        self.wait = 1

    def check(self):
        if self.wait == 1:
            try:
                self._client.connect()
                self._client.subscribe(self._sub)
                self.state = self._check
                self.wait = 0
            except Exception as e:
                print('connect', e)
                self.wait = 20
        elif self.wait > 0:
            self.wait -= 1
        else:
            try:
                self._client.check_msg()
            except Exception as e:
                print('check', e)
                self.wait = 4

    def publish(self, topic, msg, retain=False):
        try:
            self._client.publish(topic=topic, msg=msg, retain=retain)
            return True
        except Exception as e:
            print('publish', e)
            self.wait = 4
            return False

    def _callback(self, topic, msg):
        print('%s -> %s' % (topic, msg))
        if topic == self.tset:
            self._receive(msg)
示例#25
0
def main(clientID=CLIENTID, server=SERVER, topic=PUB_TOPIC):
    print("Sampling time (sec):", SAMPLING_TIME)
    obj = {"event_data": {}}

    print("Client ID: %s" % clientID)
    print("MQTT broker server: %s" % server)
    print("Topic: %s" % topic)
    c = MQTTClient(client_id=clientID,
                   server=server,
                   port=PORT,
                   user=MQTT_USERNAME,
                   password=MQTT_password,
                   ssl=True)
    c.set_callback(sub_cb)
    if c.connect() == 0:
        print('cCient connect status : Success')
    else:
        print('Client connect status : Failure')
    print('Publish data to the broker.')
    c.publish(topic, '{"event_data":{"connected":true}}')
    print('subscribe topic (%s)' % SUB_TOPIC)

    previous_time = utime.time()
    time_min = 0

    c.subscribe(SUB_TOPIC)
    while True:
        if False:
            #print ('Waiting for subscribe message')
            # blocking wait for message
            c.wait_msg()
        else:
            # non blocking wait for message
            #print ('Waiting for subscribe message Non-blocking')
            c.check_msg()
            utime.sleep_ms(10)  # 10ms for cpu process.
        # If button 0 is pressed, drop to REPL
        if repl_button.value() == 0:
            print("Dropping to REPL now")
            sys.exit()
        current_time = utime.time()
        if (current_time - previous_time) > SAMPLING_TIME:
            #if (current_time - previous_time) > 60:  # fix the time to 1 min
            time_min += 1
            print("Time (minutes) = ", time_min * SAMPLING_TIME / 60)
            previous_time = current_time
            obj['event_data']['heartbeat'] = 'true'
            print("Publish sensor data.")
            print(obj)
            c.publish(topic, json.dumps(obj))

    print('Client disconnect')
    c.disconnect()
示例#26
0
class BarsClient:
    def __init__(self, name, ip):
        self.c = MQTTClient(name, ip)
        self.c.connect(lambda topic, msg: print((topic, msg)))
        self.c.subscribe(b"int_resp")

    def __wait(self):
        resp = self.c.check_msg()
        if resp is None:
            pass
        else:
            return resp
        time.sleep(5)
        resp = self.c.check_msg()
        if resp is None:
            raise TimeoutError
        else:
            return resp

    def __send_msg(self, topic, msg):
        self.c.publish(topic, msg)

    def req_interval(self, batt):
        print("Requesting interval...")
        self.c.publish(b"interval", b"pls")
        self.c.publish(b"batt", batt)
        i = 0
        print("Attempting to receive response...")
        while i < 3:
            try:
                print("Checking response message, attempt No." + str(i + 1) +
                      "...")
                resp = self.__wait()
                print("Response received")
                return int(resp[1].decode('utf-8'))
            except TimeoutError:
                i += 1
                continue
        return None

    def send_counters(self, counters, batt):
        print("Sending counters...")
        for topic, msg in counters:
            self.__send_msg(topic, msg)
        self.c.publish(b"batt", batt)
        print("Waiting for response...")
        resp = self.__wait()
        print("Response received:")
        print(resp)
        return int(resp[1].decode('utf-8'))
示例#27
0
def mqtt_connect():
    print("Attempting connection to MQTT broker")
    c = MQTTClient(secrets.mqtt_clientid,
                   secrets.mqtt_host,
                   1883,
                   secrets.mqtt_username,
                   secrets.mqtt_password,
                   0,
                   ssl=False)
    c.set_callback(mqtt_callback)
    c.connect(clean_session=False)
    for topic, callback in SUBSCRIPTIONS:
        c.subscribe(topic)
    c.check_msg()
    return c
示例#28
0
def main(server="192.168.1.1"):
    utime.sleep(5)
    c = MQTTClient("umqtt_client", server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"bunnyuncle/msg")
    magicGPIO = 13
    magicbtn = machine.Pin(magicGPIO, machine.Pin.IN, machine.Pin.PULL_UP)
    while True:
        c.check_msg()
        utime.sleep(2)
        if magicbtn.value() == 0:
            stop_light()

    c.disconnect()
示例#29
0
def main(server=credentials.SERVER, port=credentials.PORT, user=credentials.USER, password=credentials.PASSWORD):
    client = MQTTClient(CLIENT_ID, server, port, user, password)
    client.set_callback(sub_cb)
    client.connect()
    print("Connected to MQTT broker ", SERVER)
    client.subscribe("otto/cmd")
    global lifting
    global door_down
    global incoming_msg
    global blank_incoming_msg
    last_door_down = 1
    last_lifting = 0
    try:
      while True:
        if opto_1 and not opto_2:
          door_up = True
        else:
          door_up = False
        if not opto_1 and not opto_2:
          door_down = True
        else:
            door_down = False
        if lifting | lowering:
            RLY_BEEPER.value(0)
        else:
            RLY_BEEPER.value(1)
        if lifting != last_lifting:
          if lifting:
            entry = time.ticks_ms()
        if lifting and (time.ticks_ms() >= entry + 7500):
          timeout = True
          lifting = False
          print("timeout!")
        if incoming_msg != blank_incoming_msg:
          client.publish(b"otto/stat", b"Got a new message")
        last_lifting = lifting
        last_door_down = door_down
        incoming_msg = ""
        blank_incoming_msg = ""
        client.check_msg()


    except KeyboardInterrupt:
      print("Graceful exit by keyboard interrupt")
      client.publish(b"otto/stat", b"Graceful exit by keyboard interrupt")
    finally:
      print("Code crashed, idle now")
      client.publish(b"otto/stat", b"Code stopped, ESP32 idle now")
def listen():
    #Create an instance of MQTTClient 
    client = MQTTClient(CONFIG['CLIENT_ID'], CONFIG['MQTT_BROKER'], user=CONFIG['USER'], password=CONFIG['PASSWORD'], port=CONFIG['PORT'])
    # Attach call back handler to be called on receiving messages
    client.set_callback(onMessage)
    client.connect()
    client.publish(CONFIG['TOPIC'], "ESP8266 is Connected")
    client.publish(CONFIG['TOPIC'], "off")
    client.subscribe(CONFIG['TOPIC'])
    print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC']))
 
    try:
        while True:
            #msg = client.wait_msg()
            msg = (client.check_msg())
            if button.value() == 1:
                print("Button pressed")
                display.fill(0)
                display.text('Pi4IoT', 30, 0) 
                if led.value() == 1:
                    client.publish(CONFIG['TOPIC'], b"off")
                    display.text('LED: OFF', 30, 20) 
                else: 
                    client.publish(CONFIG['TOPIC'], b"on") 
                    display.text('LED: ON', 30, 20)
                display.show()  
                time.sleep_ms(500)
    finally:
        client.disconnect()  
def main(server="localhost"):
    c = MQTTClient("umqtt_client", server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"foo_topic")
    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()
mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT)

# Subscribed messages will be delivered to this callback
mqtt.set_callback(subscriction_callback)

# Connect to the MQTT server
mqtt.connect()

# Define the topic to subscribe to
mqtt.subscribe(SUB_TOPIC)
print('\nMQTT:\n  Connected to: {}:{}\n  Subscribed to: {:s}\n  Publishing to: {:s}'.format(HOST, PORT, SUB_TOPIC, PUB_TOPIC))

try:
    while True:
        # This is the non-blocking method to check if there are MQTT messages
        mqtt.check_msg()
        
        # This attempts to read the UART until a newline character
        # Because we specified a timeout=0, when initializing the UART, it will
        # not block and instead returns the characters that it can read, even
        # if a newline isn't present. This means that we need to check for a newline
        # and be smart about processing the bytes/characters that were able 
        # to receive if one was not present.
        uart_message = uart.readline()

        if uart_message:
            # Toggle the LED for every piece of serial data received
            # This is useful for debugging, but you might want to disable
            # if the data rate is high
            led.value(not led.value()) 
示例#33
0
文件: main.py 项目: mampersat/minions
for i in range(0, len(letters)):
    nps[i] = neopixel.NeoPixel(machine.Pin(4), lights)
    set_char(letters[i], nps[i])

client.set_callback(gotMessage)
client.subscribe("/strip/command/" + client_id)

ntp_sync = False
while not ntp_sync:
    try:
        print("NTP time sync")
        ntptime.settime()
        ntp_sync = True
    except:
        print("NTP fail")


allOff()

while True:
    client.check_msg()
    if mode == "sleep":
        allOff()
        time.sleep(1)
    if mode == "cycle":
        cycle_pallet(15)
    if mode == "ho":
        ho()
    if mode == "test":
        test(1)