示例#1
0
def inicializar():
    #leitura json
    with open('config.json', 'r') as config_file:
        dados = ujson.load(config_file)

    mqtt = dados['MQTT']
    usuario_mqtt = mqtt['usuario']
    senha_mqtt = mqtt['senha']
    topico = mqtt['topico']
    id = dados['ID']
    top = str(topico + "/" + id)
    
    #dados do broker mqtt (nome do dispositivo, broker, usuario, senha, e porta)
    client = MQTTClient("esp-kaller", "ioticos.org",user= usuario_mqtt, password=senha_mqtt, port=1883) 
    client.set_callback(sub_cb) 
    client.connect()
    client.subscribe(topic= str(top + "/cidade"))
    client2 = client
    client2.subscribe(topic= str(top + "/led2"))
    def estou_conectado():
        while True: 
            client.publish(topic=top + "/conectado", msg="conectado")
            time.sleep(15)
    #t =_thread.start_new_thread(mqtt_cidade,())
    #t2 =_thread.start_new_thread(led_on_2,())
    t =_thread.start_new_thread(estou_conectado,())

    while True: 
        client.wait_msg()
        time.sleep(1)
        client2.check_msg()
        time.sleep(1)
示例#2
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()
示例#3
0
文件: main.py 项目: topsai/esp-8266
def run_client():
    global c
    # 创建MQTT的客户端对象
    c = MQTTClient(CLIENT_ID,
                   CONFIG["broker"],
                   user=CONFIG["mqtt_user"],
                   password=CONFIG["mqtt_password"])
    # 设置当订阅的信息到达时的处理函数
    c.set_callback(sub_cb)
    # 连接MQTT代理服务器
    c.connect()
    # 订阅命令信息
    c.subscribe(rgb_command_topic)
    c.subscribe(switch_command_topic)
    c.publish(rgb_command_topic, b'{"state": "OFF"}')
    c.publish(switch_command_topic, b'OFF')
    tim.init(period=5000,
             mode=Timer.PERIODIC,
             callback=lambda t: c.publish(sensor_topic, opt.get_temp()))
    # c.subscribe(CONFIG["dht11_state"])
    try:
        while True:
            c.wait_msg()
    finally:
        c.disconnect()
示例#4
0
 def connect_and_subscribe(self):
     self.write_log("start connection to server")
     client = MQTTClient(self.configuration.mqtt.client_id, self.configuration.mqtt.mqtt_server)    
     self.write_log("setting callback")
     client.set_callback(self.sub_cb)
     
     retry = 0
     self.write_log("wifi status :" + str(self.wifi_connection.isconnected()))
     self.write_log("wifi config :" + str(self.wifi_connection.ifconfig()))
     while retry < 20: 
         try:
             while not client.connect():
                 time.sleep(4.5)
                 self.rgb_led.blink(self.rgb_led.blue_led)
                 msg = " hi from python :"+ str(retry)
                 self.write_log("connecting to server ....")
                 #client.publish(self.configuration.mqtt.topic_pub, msg)
                 client.subscribe(b"myfirst/test")
                 client.wait_msg()
                 reconection = False
         except Exception as e:
                 self.write_log("Can't connect to mqtt..... try:" + str(retry+1))
                 self.write_log(str(e))
                 self.rgb_led.blink(self.rgb_led.red_led)
         finally:
                 self.write_log("finish connection proccess ....")
                 retry+=1
                 pass
         time.sleep(5)
示例#5
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()
示例#6
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()
示例#7
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)
示例#8
0
def main():
    global relay_pin

    client = MQTTClient(CLIENT_ID, SERVER)
    client.set_callback(new_msg)

    try:
        client.connect()
    except OSError:
        print("MQTT Broker seems down")
        print("Resetting after 20 seconds")
        time.sleep(20)
        machine.reset()

    client.subscribe(COMMAND_TOPIC)

    # Publish as available once connected
    client.publish(AVAILABILITY_TOPIC, "online", retain=True)

    switch_pin = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
    reed_switch = Switch(switch_pin)

    # Initialize state of garage door after booting up
    if switch_pin.value():
        client.publish(STATE_TOPIC, "open", retain=True)
    else:
        client.publish(STATE_TOPIC, "closed", retain=True)

    relay_pin = machine.Pin(4, machine.Pin.OUT, 0)

    try:
        while True:

            reed_switch_new_value = False

            # Disable interrupts for a short time to read shared variable
            irq_state = machine.disable_irq()
            if reed_switch.new_value_available:
                reed_switch_value = reed_switch.value
                reed_switch_new_value = True
                reed_switch.new_value_available = False
            machine.enable_irq(irq_state)

            # If the reed switch had a new value, publish the new state
            if reed_switch_new_value:
                if reed_switch_value:
                    client.publish(STATE_TOPIC, "open")
                else:
                    client.publish(STATE_TOPIC, "closed")

            # Process any MQTT messages
            if client.check_msg():
                client.wait_msg()

            time.sleep_ms(500)

    finally:
        client.publish(AVAILABILITY_TOPIC, "offline", retain=False)
        client.disconnect()
        machine.reset()
示例#9
0
 def connect_and_subscribe(self, client_id, host, topic):
     logger.info('connecting to mqtt broker...')
     client = MQTTClient(client_id, host)
     client.set_callback(self.on_message)
     client.connect()
     client.subscribe(topic)
     while True:
         client.wait_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
示例#11
0
def init(client_id,
         hostname='alpcer0.local',
         sub_topic='kybIntcpt',
         callback=simple_sub_cb):
    global mqtt_client
    mqtt_client = MQTTClient(client_id, hostname)
    mqtt_client.set_callback(callback)
    mqtt_client.connect()
    mqtt_client.subscribe(sub_topic)
    mqtt_client.ping()
    mqtt_client.wait_msg()
示例#12
0
def main():
    client = MQTTClient(CLIENT_ID, BROKER, 1883)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (BROKER, TOPIC))

    try:
        while 1:
            client.wait_msg()
    finally:
        client.disconnect()
示例#13
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()
示例#14
0
def main(server=SERVER):
    c = MQTTClient(client_id, mqtt_server, mqtt_port, mqtt_user, mqtt_password)
    # 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" % (mqtt_server, topic))

    try:
        while True:
            c.wait_msg()
    finally:
        c.disconnect()
示例#15
0
def main(server=SERVER):
    client = MQTTClient(CLIENT_ID, server)
    client.set_callback(led_callback)
    client.connect()
    client.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

    try:
        while 1:
            #micropython.mem_info()
            client.wait_msg()
    finally:
        client.disconnect()
示例#16
0
def subs(server="m15.cloudmqtt.com"):
    global client_id, mqtt_server, topic_sub

    c = MQTTClient(client_id=CLIENT_ID,
                   server='m15.cloudmqtt.com',
                   user='******',
                   password='******',
                   port='16060')
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"Sensor_Data")
    c.wait_msg()
    c.disconnect()
示例#17
0
def main(server=SERVER):
    c = MQTTClient(CLIENT_ID, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

    try:
        while 1:
            c.wait_msg()
    finally:
        c.disconnect()
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))

    try:
        while 1:
            #micropython.mem_info()
            c.wait_msg()
    finally:
        c.disconnect()
示例#19
0
def main(server=config.mqtt_server):
    c = MQTTClient(clientname, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(topic)
    print("Connected to %s, subscribed to %s topic" % (server, topic))

    try:
        while 1:
            #micropython.mem_info()
            c.wait_msg()
    finally:
        c.disconnect()
示例#20
0
class UmqttBroker(object):
    """UmqttBroker"""
    def __init__(self):

        config = CONFIG.load_config()

        try:
            self.client_id = config["mqtt"]["client_id"]
            self.broker = config["mqtt"]["broker"]
            self.user = config["mqtt"]["user"]
            self.password = config["mqtt"]["password"]
            self.port = config["mqtt"]["port"]

        except:
            print(
                "Couldn't load mqtt config param (client_id, broker url, user, password, port) in config.json"
            )

        #Create an instance of MQTTClient
        self.client = MQTTClient(self.client_id,
                                 self.broker,
                                 user=self.user,
                                 password=self.password,
                                 port=self.port)

    @staticmethod
    def onMessage(topic, msg):
        # Generic callback.
        print("Topic: %s, Message: %s" % (topic, msg))

    def listen(self, topic):
        # Attach call back handler to be called on receiving messages
        self.client.set_callback(self.onMessage)
        self.client.connect()
        self.client.subscribe(topic)

        print("ESP8266 is Connected to %s and subscribed to %s topic" %
              (self.broker, topic))

        try:
            while True:
                self.client.wait_msg()
        finally:
            self.client.disconnect()

    def emit(self, data, topic):
        self.client.connect()
        self.client.publish('{}'.format(topic), bytes(str(data), 'utf-8'))
        print('Sensor state: {}'.format(data))
示例#21
0
def mqtt_connect():
    c = MQTTClient(mqtt_id, mqtt_server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(mqtt_callback)
    c.connect()
    c.subscribe(mqtt_topic)
    print("Connected to %s, subscribed to %s topic" %
          (mqtt_server, mqtt_topic))

    try:
        while 1:
            #micropython.mem_info()
            c.wait_msg()
    finally:
        c.disconnect()
示例#22
0
def main(server=SERVER):
    #括号里主要是客户端ID,服务器地址,服务器端口,用户产品ID,鉴权信息
    c = MQTTClient(CLIENT_ID, server, 6002, username, password)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

    try:
        while 1:
            #micropython.mem_info()
            c.wait_msg()
    finally:
        c.disconnect()
示例#23
0
def main(server=SERVER):
    #端口号为:6002
    c = MQTTClient(CLIENT_ID, server, 6002, username, password,
                   keepalive=10)  # 保持连接时间间隔设置10秒
    c.set_callback(sub_cb)
    c.connect()
    tim1 = Timer(1)  #创建定时器1
    tim1.init(period=2000, mode=Timer.PERIODIC,
              callback=lambda n: c.ping())  #  发送心跳包 ,保持连接
    print("Connected to %s" % server)
    try:
        while 1:
            c.wait_msg()
    finally:
        c.disconnect()
示例#24
0
 def main(self):
     """
     Main function runs the board test, connects to wifi and mqtt server
     and finally waits for oncoming messages
     :return:
     """
     self.boardTest()
     self.wifiConnect()
     print("INFO: Connecting to MQTT")
     client = MQTTClient("umqtt_client", self.host, self.port)
     client.set_callback(self.on_message)
     client.connect()
     print("INFO: Connected to MQTT")
     client.subscribe(self.topic)
     while True:
         client.wait_msg()
示例#25
0
def listen():
    global rec_msg
    client = MQTTClient(CONFIG['CLIENT_ID'],
                        CONFIG['MQTT_BROKER'],
                        port=CONFIG['PORT'])

    client.set_callback(onMessage)

    client.connect()

    client.publish("data", "ESP8266 is Connected")
    print(b"esp8266_" + ubinascii.hexlify(machine.unique_id()))
    client.subscribe(CONFIG['TOPIC'])

    print("ESP8266 is Connected to %s and subscribed to %s topic" %
          (CONFIG['MQTT_BROKER'], CONFIG['TOPIC']))

    try:

        while True:
            global rec_msg
            msg = client.wait_msg()
            if rec_msg is not None:
                client.publish("data", "ESP8266 is Recieved")
                rec_msg = None
    finally:
        client.disconnect()
def start(server=SERVER):
    #print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
    c = MQTTClient(CLIENT_ID, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

    try:
        while 1:
            #micropython.mem_info()
            c.wait_msg()
    finally:
        print("Disconnecting")
        c.disconnect()
示例#27
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()
示例#28
0
def subscribe(server="localhost"):
    c = MQTTClient(machine.unique_id(), '192.168.0.10')
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe("ESYS/netball")
    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()
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()
示例#30
0
def pircontrol(server="192.168.137.160"):
    c = MQTTClient("esp32_pir_mqttClient", server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"esp32/control")
    while True:
        if True:
            # Blocking wait for message
            c.wait_msg()
        else:
            # Non-blocking wait for message
            x = 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()
示例#31
0
def main(server="m24.cloudmqtt.com"):
    c = MQTTClient("umqtt_client", server, port, user, passw)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"$SYS/broker/load/connections/+")
    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()
    # 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()

示例#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()