コード例 #1
0
ファイル: main.py プロジェクト: davea/sonoff-mqtt
def connect_and_subscribe():
    global client
    client = MQTTClient(machine_id, broker)
    client.set_callback(callback)
    client.connect()
    print("Connected to {}".format(broker))
    for topic in (b'config', b'control'):
        t = topic_name(topic)
        client.subscribe(t)
        print("Subscribed to {}".format(t))
コード例 #2
0
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()
コード例 #3
0
def main():
    print("initilising wifi")
    initiliseWifi()
    print("wifi initlised")
    time.sleep(2)
    defaultMsg()

    c = MQTTClient(server="io.adafruit.com",
                   client_id="LokeshR",
                   password="******")
    c.set_callback(callBack)
    c.connect()
    c.subscribe("LokeshR/feeds/switchcontrol")

    try:
        while True:
            c.wait_msg()
    finally:
        c.disconnect()
コード例 #4
0
def mqtt_connect():
    global config
    print('Setting up MQTT client...')

    CLIENT_ID = b"Huzzah-" + ubinascii.hexlify(machine.unique_id())
    c = MQTTClient(CLIENT_ID, config["MQTT_Broker"])

    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_callback)
    c.connect()
    c.subscribe(config["TOPIC"])
    print("Connected to {}, subscribed to {} topic.".format(
        config["MQTT_Broker"], config["TOPIC"]))

    while True:
        c.wait_msg()
    #c.check_msg()

    c.disconnect()
コード例 #5
0
 def get_mqtt_client(self, project_id, cloud_region, registry_id, device_id,
                     jwt):
     """Create our MQTT client. The client_id is a unique string that identifies
     this device. For Google Cloud IoT Core, it must be in the format below."""
     client_id = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(
         project_id, cloud_region, registry_id, device_id)
     print('Sending message with password {}'.format(jwt))
     client = MQTTClient(
         client_id.encode('utf-8'),
         server=config.google_cloud_config['mqtt_bridge_hostname'],
         port=config.google_cloud_config['mqtt_bridge_port'],
         user=b'ignored',
         password=jwt.encode('utf-8'),
         ssl=True)
     client.set_callback(on_message)
     client.connect()
     client.subscribe('/devices/{}/config'.format(device_id), 1)
     client.subscribe('/devices/{}/commands/#'.format(device_id), 1)
     return client
コード例 #6
0
def check_user_unlock(block): #connects to EERover broker and waits for a user responce with a code to disarm the device
	sta_if = network.WLAN(network.STA_IF); sta_if.active(True) #connect to EERover network
	sta_if.connect(BROKER_NAME,BROKER_PASSWORD)
	while sta_if.isconnected() == False: #wait for connectoin to be established
		time.sleep_ms(10)
	print("Broker Connected")
	client=MQTTClient(machine.unique_id(),"192.168.0.10")
	client.connect()
	client.set_callback(sub_cb)
	client.subscribe("esys/<team_little_boots>/unlock/1234") #subcribe to a topic with a specific code (here 1234) would be different for different units
	if(block):
		client.wait_msg() #blocking message receive function that waits until the topic is recieved
	else: #blocks operation but only for 1 minute
		rtc.datetime((2017, 5, 1, 4, 13, 0, 0, 0))
		while((rtc.datetime()[5] < 1) and (ALARM_RESET == False)):
			client.check_msg()
			time.sleep_ms(10)
	client.disconnect() #disconnect from broker and network
	sta_if.disconnect()
コード例 #7
0
def main(server="mqtt.just4fun.site"):
    c = MQTTClient("umqtt_client", server)
    c.set_callback(sub_cb)
    c.connect()
    #c.subscribe(b"/test_umqtt")
    c.subscribe(b"/test_umqtt", qos=1)
    while True:
        if True:
            # Blocking wait for message
            print("running...")
            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()
コード例 #8
0
 def mqtt_main_thread():
     global c, uM
     while True:
         gc.collect()
         func(None, None, 'MQTT START.')
         if inif['mqtt_state'] == 0:
             try:
                 c = MQTTClient(inif['mqttClientId'],
                                inif['strBroker'],
                                inif['Brokerport'],
                                inif['mqttUsername'],
                                inif['mqttPassword'],
                                keepalive=120)
                 c.set_callback(sub_cb)
                 c.connect()
                 inif['mqtt_state'] = 1
                 uM = 0
                 func(None, None, 'MQTT TOPIC ING.')
                 c.subscribe(inif['sysTOPIC'])  #上传消息成功收到回复消息
                 c.subscribe(inif['getTOPIC'])  #接收服务器自定义消息
                 func(None, None, 'MQTT OK.')
                 while True:
                     try:
                         c.wait_msg()
                     except:
                         if inif['mqtt_state'] == 1:
                             inif['mqtt_state'] = 0
                         try:
                             c.disconnect()  #断开连接释放资源
                         except:
                             pass
                         break
             except:
                 func(None, None, 'MQTT OVER.')
                 if inif['mqtt_state'] == 1:
                     inif['mqtt_state'] = 0
                     try:
                         c.disconnect()  #断开连接释放资源
                     except:
                         pass
                 time.sleep(5)
         else:
             time.sleep(5)
コード例 #9
0
def init_client():
    global client

    print("Trying to connect to mqtt broker.")
    wifi.connect()
    try:
        client = MQTTClient(config.mqtt_client_id, config.mqtt_broker, user=config.mqtt_user,
                            password=config.mqtt_password)
        client.set_callback(callback)
        client.connect()
        print("Connected to {}".format(config.mqtt_broker))
        t = config.mqtt_topic + b"/#"
        client.subscribe(t)
        print("Subscribed to %s topic" % t)
    #        client.subscribe(command_topic)
    #        client.subscribe(brightness_command_topic)
    #        client.subscribe(rgb_command_topic)
    except:
        print("Trouble to init mqtt.")
コード例 #10
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(10)
    except Exception as e:
        print(e.args[0])
        client.disconnect()
        print('bye!')
        if e.args[0] == '-1':
            main()
コード例 #11
0
def mqtt_connect_and_subscribe():
    global mqtt_client
    global retries
    if retries < 300:
        try:
            mqtt_client = MQTTClient(client_id, mqtt_server_ip)
            mqtt_client.connect()
            mqtt_client.set_callback(mqtt_on_message)
            mqtt_client.subscribe(light.tc_set)
            mqtt_client.subscribe(esp8266_set)
            print('connected to mqtt server at {}'.format(mqtt_server_ip))
            retries = 0
        except OSError:
            time.sleep(1)
            retries += 1
            print('connection to mqtt server failed, retrying')
            mqtt_connect_and_subscribe()
    else:
        print('could not connect to mqtt_server at {}'.format(mqtt_server_ip))
コード例 #12
0
ファイル: boot.py プロジェクト: thestumbler/mqtt-demo
class mqtt_client:
    def __init__(self, client_id, broker):
        self.client_id = client_id
        self.broker = broker
        self.mogi = MQTTClient(self.client_id, self.broker)

    def set_callback(self, callback):
        self.mogi.set_callback(callback)

    def connect(self):
        self.mogi.connect()

    def subscribe(self, topic):
        self.mogi.subscribe(topic)

    def publish(self, topic, value, retain=True):
        self.mogi.publish(topic, value, retain)

    def check_msg(self):
        self.mogi.check_msg()
コード例 #13
0
def subscribe_test(clientId="clientId",
                   hostname=aws_endpoint,
                   sslp=ssl_params,
                   msg_limit=2):
    # "clientId" should be unique for each device connected
    c = MQTTClient(clientId, hostname, ssl=True, ssl_params=sslp)
    c.set_callback(sub_cb)
    print("connecting...")
    c.connect()
    print("connected")
    c.subscribe("sample/xbee")
    print("subscribed")
    print('waiting...')
    global msgs_received
    msgs_received = 0
    while msgs_received < msg_limit:
        c.check_msg()
        time.sleep(1)
    c.disconnect()
    print("DONE")
コード例 #14
0
def main():
    global CLIENT
    CLIENT = MQTTClient(CLIENT_ID, SERVER)
    CLIENT.set_callback(new_msg)
    CLIENT.connect()

    CLIENT.subscribe(COMMAND_TOPIC)

    # Publish as available once connected
    CLIENT.publish(AVAILABILITY_TOPIC, "online")

    print("Connected to {}, subscribed to {} topic".format(
        SERVER, COMMAND_TOPIC))

    try:
        while 1:
            CLIENT.wait_msg()
    finally:
        CLIENT.publish(AVAILABILITY_TOPIC, "offline")
        CLIENT.disconnect()
コード例 #15
0
def main(server="alpcer0.local"):
    global blocking_wait
    c = MQTTClient("umqtt_client", server)
    c.set_callback(simple_sub_cb)
    c.connect()
    c.subscribe(b"foo_topic")
    while True:
        if blocking_wait:
            # Blocking wait for message
            c.wait_msg()
            c.publish(b'bar_topic', b'received a message')
        else:
            c.publish(b'bar_topic', b'checking for messages')
            # 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()
コード例 #16
0
def main(server=SERVER):
    c = MQTTClient(CLIENT_ID, server, PORT_NO, USERNAME, PASSWORD, 60)
    # 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))

    while (True):
        try:
            while 1:
                #micropython.mem_info()
                c.wait_msg()

        finally:
            print("finish!!!")
            time.sleep(2)
            machine.reset()

    c.disconnect()
コード例 #17
0
def main():
    client = MQTTClient(CLIENT_ID)
    client.connect(host=SERVER, user=USER, password=PASSWORD, port=PORT)
    print("Connected to MQTT broker ", SERVER)
    client.set_callback(sub_cb)
    client.subscribe("otto/#")
    global lifting
    global door_down
    last_door_down = 1
    last_lifting = 0
    try:
        while True:
            if opto_2 and not opto_1:
                door_up = True
            else:
                door_up = False
            if opto_2 and opto_1:
                door_down = True
            else:
                door_down = False
            if lifting != last_lifting:
                if lifting:
                entry = time.ticks_ms()
                   if time.ticks_ms() >= entry + 10000:
                        timeout = True
                    if door_up | timeout:
                        lifting = False
                        timeout = False
                        stop_now()
            if door_down != last_door_down:
                if door_down:
                    stop_now()
            last_lifting = lifting
            last_door_down = door_down
            client.check_msg()
    except KeyboardInterrupt:

        print("Graceful exit by keyboard interrupt")

    finally:
        print("Code stopped, idle now")
コード例 #18
0
ファイル: mqtt.py プロジェクト: bboortz/micropython-fun
class Mqtt:
    def __init__(self, client_name, server):
        self.__c = MQTTClient(client_name, server)
        self.__connected = False

    def is_connected(self):
        try:
            logger.print_cmd('Send MQTT ping')
            self.__c.ping()
            self.__connected = True
            logger.print_info('Connected from MQTT Broker')
        except:
            self.disconnect(False)
        return self.__connected

    def connect(self):
        logger.print_cmd('Connect to MQTT Broker')
        self.__c.connect()
        self.is_connected()

    def disconnect(self, force=False):
        if self.__connected or force:
            logger.print_cmd('Disconnected from MQTT Broker')
            self.__connected = False
            self.__c.disconnect()

    def publish(self, topic, msg):
        logger.print_cmd('Publish data vi MQTT')
        self.__c.publish(topic, msg)

    def subscribe(self, topic, message_func):
        logger.print_cmd('Subscribe data vi MQTT')
        self.__c.set_callback(message_func)
        self.__c.subscribe(topic)

    def wait_msg(self):
        try:
            while 1:
                self.__c.wait_msg()
        finally:
            self.__c.disconnect()
コード例 #19
0
ファイル: elServer.py プロジェクト: nodesign/weioESP
def start():
    global c

    # wait to connect to the network
    print("waiting to be connected")
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    while not (sta_if.isconnected()):
        time.sleep(0.3)
    print("connected to the network")
    print(sta_if.ifconfig())

    c = MQTTClient(CLIENT_ID, server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(REQUEST_TOPIC)
    print("entering loop")

    while True:
        #print("waiting for message")
        c.wait_msg()
コード例 #20
0
def show_mqtt():
    global scroller
    scroller = Scroller()

    mqtt = MQTTClient(b"scroller", b"mqtt")
    try:
        mqtt.connect()
    except:
        scroller.scroll("MQTT connect failed")
        return

    mqtt.set_callback(mqtt_cb)
    mqtt.subscribe(b"#")

    scroller.scroll("started")
    scroller.clear_up()
    try:
        while True:
            mqtt.wait_msg()
    finally:
        mqtt.disconnect()
コード例 #21
0
ファイル: tesmqtt.py プロジェクト: chalei/micropython
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'], "on")
    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())
    finally:
        client.disconnect()
コード例 #22
0
def inicializar_mqtt_controle():
    #dados do broker mqtt (nome do dispositivo, broker, usuario, senha, e porta)
    client = MQTTClient("esp-kaller", "ioticos.org",user="******", password="******", port=1883) 
    client.set_callback(sub_cb) 
    client.connect()
    client.subscribe(topic="snEwCneZjyGXl7B/led1")
    client2 = client
    client2.subscribe(topic="snEwCneZjyGXl7B/led2")
    def estou_conectado():
        while True: 
            client.publish(topic="snEwCneZjyGXl7B/conectado", msg="conectado")
            time.sleep(15)
    t =_thread.start_new_thread(led_on_1,())
    t2 =_thread.start_new_thread(led_on_2,())
    t3 =_thread.start_new_thread(estou_conectado,())

    while True: 
        client.wait_msg()
        time.sleep(1)
        client2.check_msg()
        time.sleep(1)  
コード例 #23
0
ファイル: mqtt.py プロジェクト: Amit2016-17/examples-2
def send(topic="test",
         data="hello world!",
         client_id='testmicropython',
         server='mqtt.flespi.io',
         port=1883,
         user='',
         password=''):
    from umqtt.simple import MQTTClient
    import time

    print(data)

    client = MQTTClient(client_id, server, port, user,
                        password)  # Create MQTT client
    client.set_callback(sub_cb)  # on message callback
    client.connect()  # connect to MQTT broker
    client.subscribe(topic)  # subscribe topic
    client.publish(topic, str(data))  # publish data to topic
    client.wait_msg()  # waiting for a message
    time.sleep(2)
    client.disconnect()  # disconnect
コード例 #24
0
def listen():

    #Create an instance of MQTTClient

    client = MQTTClient(CONFIG['CLIENT_ID'],
                        CONFIG['MQTT_BROKER'],
                        port=CONFIG['PORT'])

    # Attach call back handler to be called on receiving messages

    client.set_callback(onMessage)

    client.connect()

    client.publish("test1", "ESP8266 is Connected")

    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 msg1 == "on":

                client.publish("stat", "LED ON")

            if msg1 == "off":

                client.publish("stat", "LED OFF")

    finally:

        client.disconnect()
コード例 #25
0
def main():
    print('main called')
    # Wait up to 30s for connection
    start_ticks = time.ticks_ms()
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        while not wlan.isconnected() and (time.ticks_ms() <
                                          start_ticks + 30000):
            pass

    initPins()
    loadConfig()

    global redPWM, greenPWM, bluePWM, client
    client = MQTTClient(CONFIG['client_id'], CONFIG['broker'], 0,
                        CONFIG['mqtt_username'], CONFIG['mqtt_password'])
    client.connect()
    print("Connected to {}".format(CONFIG['broker']))

    # Listen for all the things
    client.set_callback(mqtt_sub_callback)
    client.subscribe(CONFIG['command_topic'])
    client.subscribe(CONFIG['brightness_command_topic'])
    client.subscribe(CONFIG['rgb_command_topic'])

    # Set the light's color so we know we're running
    redPWM.duty(250)

    try:
        while 1:
            client.wait_msg()
    finally:
        client.disconnect()
コード例 #26
0
ファイル: client.py プロジェクト: lhost/mqtt-robot-nodemcu
def mqtt_drive(server="localhost",
               robot_name='another robot',
               mqtt_user='******',
               mqtt_password='******'):
    global time_to_stop

    intro()

    motor.motor_a.stop()
    motor.motor_b.stop()

    print("I'm %s" % topic)

    time_to_announce = ticks_ms() + 15 * 1000

    c = MQTTClient(b"umqtt_client/%s" % robot_id, server, 1883, mqtt_user,
                   mqtt_password)
    c.set_callback(msg_callback)
    #    c.set_last_will(topic + "/$online$", "0", retain=1)
    c.connect()
    c.publish(topic + "/$online$", '1')
    c.publish(topic + "/$name$", robot_name, retain=1)
    c.subscribe(topic + '/#')
    while True:
        c.check_msg()
        if ticks_ms() > time_to_stop:
            motor.motor_a.stop()
            motor.motor_b.stop()
            c.ping()
            time_to_stop = ticks_ms() + 10 * TIMEOUT

        if ticks_ms() > time_to_announce:
            c.publish(topic + "/$online$", '1')
            time_to_announce = ticks_ms() + 16 * 1000

        # Then need to sleep to avoid 100% CPU usage (in a real
        # app other useful actions would be performed instead)
        time.sleep(0.005)

    c.disconnect()
コード例 #27
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()
コード例 #28
0
ファイル: main.py プロジェクト: docaboca/imu-tools
def mqtt_connect(config):
    mqtt_host = config["host"]
    mqtt_client = MQTTClient(
        DEVICE_ID,
        mqtt_host,
        port=config["port"],
        user=config["user"],
        password=config["password"],
    )
    broker_url = ("mqtt://{user}@{host}:{port}/".format(**config).replace(
        "//@", "").replace(":1883/", "/"))
    print("Connecting to " + broker_url, end="...")
    try:
        mqtt_client.connect()
        print("done.")
        publish_machine_identifier(mqtt_client)
        mqtt_client.set_callback(on_mqtt_message)
        mqtt_client.subscribe("imu/control/" + DEVICE_ID)
        mqtt_client.subscribe("imu/control/*")
    except OSError as err:
        print(err)
    return mqtt_client
コード例 #29
0
ファイル: mqtt.py プロジェクト: lamba09/mupy
def listen(onMessage, each_loop, config):
    #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.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()
            each_loop(client)
    finally:
        client.disconnect()
コード例 #30
0
ファイル: mqtt.py プロジェクト: swipswaps/robophery
class ModeMcuMqttComm(MqttComm):
    def __init__(self, *args, **kwargs):
        super(ModeMcuMqttComm, self).__init__(*args, **kwargs)
        self._client = MQTTClient(self._manager._name, self._host)
        self._client.set_callback(self._on_message)
        self._client.connect()
        self._client.subscribe(self._subscribe_topic)
        self._client.check_msg()

    def __del__(self):
        self._client.disconnect()

    def _on_message(self, topic, msg):
        """
        The callback for when a PUBLISH message is received from the broker.
        """
        self._log.debug("Received message {0} on topic {1}".format(msg, topic))
        self.receive_data(topic, msg)

    def send_datum(self, datum):
        self._client.publish(self._publish_topic, self._to_string(datum))
        self._log.debug("Published {0} to {1}.".format(datum, self._host))
コード例 #31
0
def mqttReceive():

    CLIENT_ID = hexlify(unique_id())
    #BROKER_ADDRESS = "192.168.0.10"
    BROKER_ADDRESS = "192.168.0.87"
    c =  MQTTClient(CLIENT_ID,BROKER_ADDRESS,port = 1883)
    print ('Waiting to recieve')
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"pikachu/rec")
    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)
            sleep_ms(1000)

    c.disconnect()
コード例 #32
0
ファイル: main.py プロジェクト: Karrot96/Embeded
def Main(i2cPort, address):
    global x
    c = MQTTClient(machine.unique_id(), '192.168.0.10')
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"ESYS/netball")
    while True:
            # Non-blocking wait for message
            c.check_msg()
            if Functions.fog(i2cPort, address):
                Functions.send(i2cPort, address)
            else if(x['RemoveFog'] == "true"):
                Functions.demist(i2cPort, address, False)
                x['RemoveFog'] = "false"
                c.disconnect()
                c.connect()
                c.subscribe(b"ESYS/netball")
            else if (x['WindowFogged'] == "true" && !Functions.fog(i2cPort,address)):
                Functions.send(i2cPort, address)
            time.sleep(5)

    c.disconnect()
コード例 #33
0
ファイル: main.py プロジェクト: mampersat/minions
# bin_walk_3()
hour_glass()

client.set_callback(gotMessage)

s = network.WLAN(network.STA_IF)
while not s.isconnected():
    # s.connect('ShArVa')
    print("Network not connected - sleeping")
    time.sleep(1)

print(s.ifconfig())

connected = False
while not connected:
    try:
        print("Connecting")
        client.connect()
    except:
        print("Connection Fail")
        time.sleep(1)
    else:
        connected = True

print("Connected")

client.subscribe(b"strip/anet")

while True:
    client.wait_msg()
    # messages are being sent at a high rate
    led.value(not led.value())


# Blink the LED every 100ms to indicate we made it into the main.py file
for _ in range(10):
    time.sleep_ms(100)
    led.value(not led.value()) # Toggle the LED
    time.sleep_ms(100)

# Make sure the LED is off
led.high()

# define a time, because we only want to send every 1s but received as fast as possible
# last_time = time.time()

mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT)
# Subscribed messages will be delivered to this callback
mqtt.set_callback(subscriction_callback)
mqtt.connect()
mqtt.subscribe(TOPIC)
print('Connected to {}, subscribed to {} topic.'.format(HOST, TOPIC))

try:
    while 1:
        #micropython.mem_info()
        mqtt.wait_msg()
finally:
    mqtt.disconnect()


# Make sure the LED is off
led.high()

# Create a MQTTClient instance.
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()
コード例 #36
0
ファイル: main.py プロジェクト: mampersat/minions
s = network.WLAN(network.STA_IF)
while not s.isconnected():
    # s.connect('ShArVa')
    print("Network not connected - sleeping")
    time.sleep(1)

print(s.ifconfig())

connected = False
while not connected:
    try:
        print("Connecting")
        client.connect()
    except:
        print("Connection Fail")
        time.sleep(1)
    else:
        connected = True

print("Connected")

client.subscribe(b"model/light/#")

party(np)
while True:

    client.wait_msg()

    print("Waiting")
    time.sleep(1)
コード例 #37
0
ファイル: main.py プロジェクト: mampersat/minions
        print(".")
        time.sleep(1)
    else:
        connected = True
publish("alive " + motd + ' ' + s.ifconfig()[0])

letters = "        "
if client_id in fleet:
    letters = fleet[client_id]

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()