Beispiel #1
0
 def __init__(self, id, ip, topic_sub, robot):
     threading.Thread.__init__(self)
     self._client = MQTTClient(id, ip)
     self._client.set_callback(self.getmessages)
     self._client.connect()
     self._client.subscribe(topic_sub, qos=1)
     self._topic_sub = topic_sub
     self._id = id
     self._robot = robot
     self._delta_time = 1
     self._topics = []
Beispiel #2
0
def connect_and_subscribe():
    global client_id, mqtt_server, topic_sub
    client = MQTTClient(client_id, mqtt_server)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(topic_sub)
    client.subscribe(topic_sub1)

    print('Connected to %s MQTT broker, subscribed to %s topic' %
          (mqtt_server, topic_sub))
    return client
Beispiel #3
0
def mqttConnect(config):
    from umqtt.robust import MQTTClient

    # extract properties from JSON-parsed configuration
    brokerHost = str(config['mqtt']['brokerHost'])
    brokerPort = int(config['mqtt']['brokerPort'])
    print('Connecting to broker {}:{} as client ID={}'.format(
        brokerHost, brokerPort, getClientId()))

    global mqttClient
    mqttClient = MQTTClient(getClientId(), brokerHost, brokerPort)
    mqttClient.connect()
Beispiel #4
0
    def _init_mqtt(self):
        MQTT_USER = env['MQTT_USER'] if 'MQTT_USER' in env.keys() else None
        MQTT_PASSWORD = env['MQTT_PASSWORD'] if 'MQTT_PASSWORD' in env.keys(
        ) else None

        # Create an mqtt client
        self.mqtt = MQTTClient(self.hardware_id,
                               env['MQTT_HOST'],
                               user=MQTT_USER,
                               password=MQTT_PASSWORD)

        self.mqtt.set_callback(self._mqtt_callback)
Beispiel #5
0
 def __init__(self, chair, host):
     self.chair = chair
     self.chair.register_observer(self)
     self.client = MQTTClient(client_id='SmartChair',
                              server=host,
                              user=hassio_mqtt_user,
                              password=hassio_mqtt_pwd,
                              port=1883,
                              ssl=False)
     status = self.client.connect()
     if status != 0:
         print('Could not connect to MQTT broker')
def update():
    c = MQTTClient("umqtt_client", MQTT_HOST)
    c.connect()
    standard_data = fetch_standard_data()
    print("Publishing: {}".format(standard_data))

    c.publish("mc66c/energy", str(standard_data["energy"]), True)
    c.publish("mc66c/volume", str(standard_data["volume"]), True)
    c.publish("mc66c/temperature_flow", str(standard_data["temperature_flow"]),
              True)
    c.publish("mc66c/temperature_return",
              str(standard_data["temperature_return"]), True)
Beispiel #7
0
 def __init__(self, client, broker, id):
     self.uid = '{:02x}{:02x}{:02x}{:02x}'.format(id[0], id[1], id[2],
                                                  id[3])
     self.client = MQTTClient(client, broker)
     self.client.set_callback(self.mqtt_sub_cb)
     print('attempt to %s MQTT broker' % (broker))
     try:
         self.client.connect()
         print('Connected to %s MQTT broker' % (broker))
     except:
         print("error connecting to MQTT broker")
         pass
class HackerLabState:
    def __init__(self):
        self.wlan = network.WLAN(network.STA_IF)
        self.wlan.active(True)

        ap = network.WLAN(network.AP_IF)
        ap.active(False)

        self.mqtt = MQTTClient(node_id, mqtt_host)

        self.do_connect()

        pin = Pin(button_pin, Pin.IN, Pin.PULL_UP)
        pin.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING,
                handler=self.state_changed)
        self.state = pin.value()

        while True:
            pass

    def do_connect(self):
        if not self.wlan.isconnected():
            print("Connecting to wifi...")
            self.wlan.connect(credentials.wifi_ssid, credentials.wifi_password)
            while not self.wlan.isconnected():
                pass
            print("Network config: ", self.wlan.ifconfig())

            print("Connecting to MQTT...")
            if not self.mqtt.connect():
                print("Connected")
            else:
                print("Could not connect")

    def state_changed(self, pin):
        pin_value = pin.value()
        active = 0
        while active < 100:
            if pin.value() != pin_value:
                active += 1
            else:
                active = 0
            sleep_ms(1)

        self.state = pin_value
        print("State ", self.state)
        self.mqtt.publish(mqtt_topic, b"1" if self.state == 1 else b"0")

        urequests.get(
            "https://slack.com/api/chat.postMessage?token=%s&channel=hackerlab&text=Hackerlab%%20is%%20%s"
            %
            (credentials.slack_token, "OPEN" if self.state == 1 else "CLOSED"))
Beispiel #9
0
def init_mqtt():
    log("MQTT Connecting")
    cli = MQTTClient(config.mqtt_name, config.mqtt_server)
    cli.DEBUG = True
    cli.set_callback(sub_cb)
    cli.connect()
    cli.subscribe(config.mqtt_subscribe)
    log("MQTT Connected")
    return cli
Beispiel #10
0
 def __init__(self):
     if config.POWER_ON_STATE:
         self.relay_control(1)
         self.led_control(0)
         self.device_status = "ON"
     self.mqtt_client = MQTTClient(client_id=config.DEVICE_NAME, server=config.MQTT_SERVER,
                     port=config.MQTT_PORT, user=config.MQTT_USER, passwd=config.MQTT_PASSWD,
                     keepalive=60)
     self.mqtt_client.set_callback(self.sub_callback)
     self.mqtt_client.set_last_will(config.AVAILABILITY_TOPIC, "offline")
     self.ping_mqtt = 0
     self.ping_fail = 0
     self.button_interrupt = 0
Beispiel #11
0
 def __init__(self):
     config = Config()
     self.heatmessage = {'Heating': ''}
     self.tempMessage = {'TempIN': '', 'TempOUT': ''}
     self.mqttID = config.mqttID
     self.mqttBroker = config.mqttBroker
     self.user = config.mqttUser
     self.password = config.mqttPassword
     self.client = MQTTClient(self.mqttID, self.mqttBroker, 1883, self.user,
                              self.password)
     self.client.connect()
     self.client.set_callback(sub_cb)
     self.client.subscribe(topic="home/attackHeater/stat")
Beispiel #12
0
def _connect():
    try:
        global client
        _log.info("Connecting to %s:%s" % (_broker, _port))
        client = MQTTClient(_client_id,
                            _broker,
                            user=_broker_username,
                            password=_broker_password,
                            port=_port)
        client.connect()
        _log.info("Connection successful")
    except Exception as ex:
        _log.error("error in _connect " + str(ex))
Beispiel #13
0
    def begin(self,
              username,
              password,
              clientid,
              hostname='mqtt.mydevices.com',
              port=1883):
        """Initializes the client and connects to Cayenne.
        
        username is the Cayenne username.
        password is the Cayenne password.
        clientID is the Cayennne client ID for the device.
        hostname is the MQTT broker hostname.
        port is the MQTT broker port.
        """

        self.rootTopic = "v1/%s/things/%s" % (username, clientid)
        self.client = MQTTClient(clientid, hostname, port, username, password)

        cayenne = self

        def lambda_on_message(topic, payload):
            #print("lambda_on_message")
            topic = str(topic.decode())
            payload = str(payload.decode())

            #print(topic)
            #print(payload)

            # CayenneMessage expect a msg object with topic and payload attributes
            class Msg:
                def __init__(self, topic, payload):
                    self.topic = topic
                    self.payload = payload

            on_message(cayenne.client, cayenne, Msg(topic, payload))

        self.client.set_callback(lambda_on_message)

        try:
            self.client.connect(clean_session=True)
        except MQTTException(e):
            print("MQTTException %s\n" % str(e))
        else:
            self.connected = True
            command_topic = self.getCommandTopic()
            print("SUB %s\n" % command_topic)
            self.client.subscribe(command_topic)
            self.mqttPublish("%s/sys/model" % self.rootTopic, "micropython")
            self.mqttPublish("%s/sys/version" % self.rootTopic, __version__)

        print("Connecting to %s..." % hostname)
 def __init__(self, user_settings_dict):
     settings = user_settings_dict.get('mqtt')
     server = settings.get('brokerAddr')
     port = settings.get('brokerPort')
     username = settings.get('username')
     password = settings.get('password')
     client_id = 'hydrometer-' + str(ubinascii.hexlify(machine.unique_id()),
                                     'UTF-8')
     self.enabled = settings.get('enabled')
     self.interval_ms = settings.get('pubIntervalMs')
     self.topic = settings.get('topic')
     if self.topic.endswith('/'):
         self.topic = self.topic[:-1]
     self.client = MQTTClient(client_id, server, port, username, password)
Beispiel #15
0
class MQTTWriter:
    __slots__ = ('host', 'port', 'topic', 'client')

    def __init__(self, name, host, port, topic):
        self.topic = topic
        self.host = host
        self.port = port
        self.client = MQTTClient(name, host, port)
        self._connect()

    def _connect(self):
        print("Connecting to %s:%s" % (self.host, self.port))
        self.client.connect()
        print("Connection successful")

    def on_next(self, x):
        data = bytes(json.dumps(x), 'utf-8')
        self.client.publish(bytes(self.topic, 'utf-8'), data)

    def on_completed(self):
        print("mqtt_completed, disconnecting")
        self.client.disconnect()

    def on_error(self, e):
        print("mqtt on_error: %s, disconnecting" % e)
        self.client.disconnect()
Beispiel #16
0
def device_connect():
    global MQTT_CLIENT

    try:  #all this below runs once ,equivalent to Arduino's "setup" function)
        with open(KEY_FILE, "r") as f:
            key = f.read()

        print("set private Key")

        with open(CERT_FILE, "r") as f:
            cert = f.read()

        print("set client Cert")

        MQTT_CLIENT = MQTTClient(client_id=MQTT_CLIENT_ID,
                                 server=MQTT_HOST,
                                 port=MQTT_PORT,
                                 keepalive=5000,
                                 ssl=True,
                                 ssl_params={
                                     "cert": cert,
                                     "key": key,
                                     "server_side": False
                                 })
        MQTT_CLIENT.connect()
        print('MQTT Connected')
        MQTT_CLIENT.set_callback(sub_cb)
        MQTT_CLIENT.subscribe(SUB_TOPIC)
        print('Subscribed to %s as the incoming topic' % (SUB_TOPIC))
        return MQTT_CLIENT
    except Exception as e:
        print('Cannot connect MQTT: ' + str(e))
        raise
Beispiel #17
0
class MQTTWriter:
  __slots__ = ('client')
  def __init__(self, id='1', server='io.adafruit.com', user='******',  password = '******', port=1883):
    self.client = MQTTClient(
    client_id=id, 
    server=server, 
    user=user, 
    password='******', 
    port=port
    )
    self._connect()

  def _connect(self):
    print("Connecting....."))
    self.client.connect()
    print("Connection successful")

  def on_next(self, topic, data):
    # data = bytes(json.dumps(x), 'utf-8')
    # self.client.publish(bytes(self.topic, 'utf-8'), data)
    self.client.publish(topic=topic, msg=data)

  def on_completed(self):
    print("mqtt_completed, disconnecting")
    self.client.disconnect()

  def on_error(self, e):
    print("mqtt on_error: %s, disconnecting" %e)
    self.client.disconnect()
Beispiel #18
0
def main():
    config = utils.Config()

    # On board LED
    led = machine.Pin(2, machine.Pin.OUT, machine.Pin.PULL_UP)

    sensor = dht.DHT22(machine.Pin(config.get("dht_gpio", 4)))

    client_id = "esp8266_" + ubinascii.hexlify(machine.unique_id()).format()
    client = MQTTClient(client_id, config.get("mqtt_broker"),
                        config.get("mqtt_port"), config.get("mqtt_user"),
                        config.get("mqtt_passwd"))
    try:
        client.connect()
    except OSError as e:
        # Just report and continue, since publish will try to reconnect
        print("Error when connecting to the MQTT broker")
    else:
        print("Connected to {}".format(config.get("mqtt_broker")))

    # Iterate and publish
    while True:
        sensor.measure()
        led.low()
        client.publish("{}/temperature".format(config.get("mqtt_topic")),
                                      str(sensor.temperature()))
        client.publish("{}/humidity".format(config.get("mqtt_topic")),
                                      str(sensor.humidity()))
        led.high()
        time.sleep(5)
Beispiel #19
0
def send_mqtt(payload_out):
    global ip
    slimDNS = None

    try:
        slimDNS = SlimDNSServer(wlan.ifconfig()[0])
        host_address_bytes = slimDNS.resolve_mdns_address(MQTT_SERVER_MDNS_ADDRESS)
        print(host_address_bytes)
        if ip != None:
            print(ip)
        ip = bytes_to_dotted_ip(host_address_bytes)
    except Exception as e:
        print("Could not connect find mDNS address " + str(e))

    if ip != None:
        print('Connecting to MQTT server:', ip)
        mqtt = None
        try:
            mqtt = MQTTClient(client_id=unique_id, server=ip, port=1883)        
            mqtt.connect()
        except Exception as e:
            print('Could not connect to MQTT server')
            return

        try: 
            mqtt.publish("vendingmachine/sensors", payload_out)
            mqtt.disconnect()
        except Exception:
            print("Failed To Publish")
Beispiel #20
0
def initMQTT():
    topic = config.MQTT_TOPIC
    bTopic = bytes(topic, 'UTF-8')
    c = MQTTClient(config.MQTT_CLIENT_ID,
                   config.MQTT_SERVER,
                   user=secrets.MQTT_USER,
                   password=secrets.MQTT_PASS)
    # Print diagnostic messages when retries/reconnects happens
    c.DEBUG = False
    c.set_callback(sub_cb)
    # Connect to server, requesting not to clean session for this
    # client. If there was no existing session (False return value
    # from connect() method), we perform the initial setup of client
    # session - subscribe to needed topics. Afterwards, these
    # subscriptions will be stored server-side, and will be persistent,
    # (as we use clean_session=False).
    #
    # There can be a problem when a session for a given client exists,
    # but doesn't have subscriptions a particular application expects.
    # In this case, a session needs to be cleaned first. See
    # example_reset_session.py for an obvious way how to do that.
    #
    # In an actual application, it's up to its developer how to
    # manage these issues. One extreme is to have external "provisioning"
    # phase, where initial session setup, and any further management of
    # a session, is done by external tools. This allows to save resources
    # on a small embedded device. Another extreme is to have an application
    # to perform auto-setup (e.g., clean session, then re-create session
    # on each restart). This example shows mid-line between these 2
    # approaches, where initial setup of session is done by application,
    # but if anything goes wrong, there's an external tool to clean session.
    if not c.connect(clean_session=True):
        c.subscribe(bTopic)
    return c
Beispiel #21
0
    def __init__(self, server, user, password, sname):
        self.topic = bytes('{}/feeds/{}-{{:s}}'.format(user, sname.lower()),
                           'utf-8').format

        client_id = hexlify(unique_id()).upper()
        self.client = MQTTClient(client_id,
                                 server,
                                 user=user,
                                 password=password)
        self.client.set_callback(self.buttons_cb)
        self.client.connect()
        # Subscribe to topics
        LOG.debug("Subscribe: %s", self.topic('force'))
        self.client.subscribe(self.topic('force'))
Beispiel #22
0
def connect_and_subscribe(client_id, broker_ip, broker_port, sub_callback=None, 
  sub_topics=[]):
    # Set Options for MQTT-Broker
    client = MQTTClient(client_id, broker_ip, broker_port)
    # Set callback to handel Messages
    if sub_callback is not None:
        client.set_callback(sub_callback)
    # Connect
    client.connect(clean_session=False)
    for topic in sub_topics:
        client.subscribe(topic)
    time.sleep(3)
    client.check_msg()
    return client
Beispiel #23
0
    def __init__(self):              

        # Connect to MQTT broker.
        self.mqtt = MQTTClient( client_id="esp32_Upython",
                           server=HOST,
                           port = 8883,
                           keepalive = 10000,
                           ssl = True,
                           ssl_params={"cert": certificate,
                                       "key": private_key,
                                       "server_side":False }
                           )
        time.sleep(4)
        self.mqtt.connect()
        print('Connected to AWS cloud')
Beispiel #24
0
 def __init__(self, chair):
     self.chair = chair
     self.client = MQTTClient(client_id='SmartChair',
                              server='mqtt.thingspeak.com',
                              user=thingspeak_mqtt_user,
                              password=thingspeak_mqtt_pwd,
                              port=1883,
                              ssl=False)
     status = self.client.connect()
     if status != 0:
         print('Could not connect to MQTT broker')
     self.timer = Timer(1)
     self.timer.init(period=1000 * 60,
                     mode=Timer.PERIODIC,
                     callback=self.on_timer_tick)
Beispiel #25
0
  def __init__(self, server, user, password, sname):
    self.topic = bytes('/'.join([user, 'feeds/{}_{{:s}}'.format(sname)]), 'utf-8')

    client_id = hexlify(unique_id()).upper()
    self.client = MQTTClient(client_id, server, user=user, password=password)
    self.client.set_callback(self.buttons_cb)
    self.client.connect()
    # Subscribe to topics
    for topic in ['btn', 'sampling']:
      mqtt_button = self.topic.format(topic)
      self.client.subscribe(mqtt_button)

    self.sampling = SAMPLING
    mqtt_sampling = self.topic.format('sampling')
    self.client.publish(mqtt_sampling, bytes(str(self.sampling), 'utf-8'))
Beispiel #26
0
 def init(self, protocol):
     self._log.debug("Protocol " + name + ": Init")
     self._client_id = protocol['client_id']
     self._server = protocol['hostname']
     self._port = protocol['port']
     self._user = protocol['user']
     self._password = protocol['password']
     self._queue_out = protocol['publish']
     self._queue_in = protocol['subscribe']
     self._mq = MQTTClient(self._client_id, self._server, self._port,
                           self._user, self._password)
     # Print diagnostic messages when retries/reconnects happens
     #self._mq.DEBUG = True
     self._queue = queues.Queue(maxsize=100)
     return self._queue
Beispiel #27
0
    def __init__(self, led=None):
        self.led = led
        self.t = machine.Timer(0)
        self.a = machine.ADC(0)

        gc.collect()
        loops = 0
        self.m = MQTTClient(config.mqtt.id, config.mqtt.host, **config.mqtt["auth"])
        while True:
            try:
                self.m.connect()
            except (IndexError, OSError) as err:
                print("Retrying connect because of a {}...".format(str(err)))
                if loops > 10:
                    print("Resetting the board")
                    machine.reset()
            except MemoryError:
                print("Got a memory error. Resetting the board in 2 seconds")
                time.sleep(2)
                machine.reset()
            except:
                raise
            else:
                break
            loops += 1
            time.sleep(1)
Beispiel #28
0
class TelemetryTransportMQTT:
    def __init__(self, uri, format):
        self.uri = uri
        self.format = format
        self.scheme, self.netloc, self.path, self.query, self.fragment = urlsplit(
            self.uri)
        self.connection = MQTTClient("umqtt_client", self.netloc)
        self.connection.DEBUG = True
        self.connection.connect()

    def send(self, request_data):
        topic = self.path.lstrip('/')
        print('MQTT Topic:  ', topic)
        print('Payload:     ', request_data['payload'])
        self.connection.publish(topic, request_data['payload'])
        return True
Beispiel #29
0
    def __init__(self, server):
        self.station = network.WLAN(network.STA_IF)
        # self.station.ifconfig(
        #     ('192.168.3.201', '255.255.255.0', '192.168.3.1', '192.168.3.1'))
        self.server = server
        self.station.active(True)
        self.station.connect()
        while self.station.isconnected() == False:
            pass
        print('wifi connected')
        client_id = ubinascii.hexlify(machine.unique_id()) + '-bbb'
        print(client_id, self.server)

        self.client = MQTTClient(client_id, self.server)
        self.client.connect()
        print('mqtt connected')
 def __init__(self):
     self._client = MQTTClient(
         client_id=ubinascii.hexlify(machine.unique_id()),
         server="io.adafruit.com", 
         user=settings.ADAFRUIT_IO_USERNAME, 
         password=settings.ADAFRUIT_IO_KEY,
         ssl=False
     )
     self._temp_feed = bytes(
         settings.ADAFRUIT_IO_USERNAME + "/feeds/" + settings.ADAFRUIT_TEMP_FEED,
         "utf-8"
     )
     self._hum_feed = bytes(
         settings.ADAFRUIT_IO_USERNAME + "/feeds/" + settings.ADAFRUIT_HUM_FEED,
         "utf-8"
     )
Beispiel #31
0
    def connect(self, force_dps=False):
        creds = None

        if force_dps:
            self._logger.info("Refreshing credentials...")

        if self._storage is not None and force_dps is False:
            creds = self._storage.retrieve()

        if creds is None:
            prov = ProvisioningClient(self._id_scope, self._device_id,
                                      self._credentials_type,
                                      self._credentials, self._logger,
                                      self._model_id)
            creds = prov.register()

        self._mqtt_client = MQTTClient(self._device_id,
                                       creds.host,
                                       8883,
                                       creds.user,
                                       creds.password,
                                       ssl=True,
                                       keepalive=60)
        self._commands_regex = ure.compile(
            '\$iothub\/methods\/POST\/(.+)\/\?\$rid=(.+)')
        try:
            self._mqtt_client.connect(False)
            self._connected = True
            self._logger.info('Device connected!')
            if self._storage:
                self._storage.persist(creds)
            self._mqtt_client.set_callback(self._on_message)
            self._mqtt_client.subscribe(HubTopics.TWIN)
            self._mqtt_client.subscribe('{}/#'.format(HubTopics.PROPERTIES))
            self._mqtt_client.subscribe('{}/#'.format(HubTopics.COMMANDS))
            self._mqtt_client.subscribe('{}/#'.format(
                HubTopics.ENQUEUED_COMMANDS.format(self._device_id)))

            self._logger.debug(self._twin_request_id)
            self._mqtt_client.publish(
                HubTopics.TWIN_REQ.format(
                    self._twin_request_id).encode('utf-8'), '{{}}')
        except:
            self._logger.info("ERROR: Failed to connect to Hub")
            if force_dps is True:
                exit(1)
            self.connect(True)
Beispiel #32
0
    def mqtt_subscribe(self):
        client_id = b'tom_' + ubinascii.hexlify(machine.unique_id())
        self.mqtt = MQTTClient(client_id, self.config['host'],
                               port=int(self.config['port']))

        self.mqtt.set_callback(self.mqtt_callback)
        self.mqtt.connect()
        self.mqtt.subscribe(self.config['topic'])
Beispiel #33
0
class MoistureMonitor():
    def __init__(self, led=None):
        self.led = led
        self.t = machine.Timer(0)
        self.a = machine.ADC(0)

        gc.collect()
        loops = 0
        self.m = MQTTClient(config.mqtt.id, config.mqtt.host, **config.mqtt["auth"])
        while True:
            try:
                self.m.connect()
            except (IndexError, OSError) as err:
                print("Retrying connect because of a {}...".format(str(err)))
                if loops > 10:
                    print("Resetting the board")
                    machine.reset()
            except MemoryError:
                print("Got a memory error. Resetting the board in 2 seconds")
                time.sleep(2)
                machine.reset()
            except:
                raise
            else:
                break
            loops += 1
            time.sleep(1)

    def start(self):
        self.m.publish(b'nodes', 'hi there')
        self.t.init(period=5000, mode=machine.Timer.PERIODIC, callback=lambda t: self.update())

    def stop(self):
        self.t.deinit()

    def update(self):
        now = time.localtime()
        tstamp = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(*now[0:6])

        val = { "m": self.a.read() / 1024, "t": tstamp }
        print("Updating moisture, new value is {}".format(val))

        self.m.publish(b"moisture", json.dumps(val).encode('utf-8'), retain=True)

        if self.led is not None:
            self.led(0)
            time.sleep(0.1)
            self.led(1)
Beispiel #34
0
class DoorAlarm(object):

    def __init__(self):
        self.config = None
        self.p0 = machine.Pin(2, machine.Pin.OUT)

    def load_config(self):
        with open('cfg.json', 'r') as cfg:
            self.config = ujson.load(cfg)

    def connect_wifi(self):
        ap_if = network.WLAN(network.AP_IF)
        ap_if.active(False)

        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(True)

        if sta_if.isconnected():
            sta_if.disconnect()

        sta_if.connect(self.config['ssid'], self.config['passwd'])

        for _ in range(20):
            time.sleep(1)

            if sta_if.isconnected():
                return

        print('Unable to connect to AP: {}'.format(ssid))
        sys.exit(1)

    def mqtt_callback(self, topic, msg):
        self.p0.value(not self.p0.value())

    def mqtt_subscribe(self):
        client_id = b'tom_' + ubinascii.hexlify(machine.unique_id())
        self.mqtt = MQTTClient(client_id, self.config['host'],
                               port=int(self.config['port']))

        self.mqtt.set_callback(self.mqtt_callback)
        self.mqtt.connect()
        self.mqtt.subscribe(self.config['topic'])
import time
from umqtt.robust import MQTTClient


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


c = MQTTClient("umqtt_client", "localhost")
# Print diagnostic messages when retries/reconnects happens
c.DEBUG = True
c.set_callback(sub_cb)
# Connect to server, requesting not to clean session for this
# client. If there was no existing session (False return value
# from connect() method), we perform the initial setup of client
# session - subscribe to needed topics. Afterwards, these
# subscriptions will be stored server-side, and will be persistent,
# (as we use clean_session=False).
#
# There can be a problem when a session for a given client exists,
# but doesn't have subscriptions a particular application expects.
# In this case, a session needs to be cleaned first. See
# example_reset_session.py for an obvious way how to do that.
#
# In an actual application, it's up to its developer how to
# manage these issues. One extreme is to have external "provisioning"
# phase, where initial session setup, and any further management of
# a session, is done by external tools. This allows to save resources
# on a small embedded device. Another extreme is to have an application
# to perform auto-setup (e.g., clean session, then re-create session
# on each restart). This example shows mid-line between these 2
Beispiel #36
0
from umqtt.robust import MQTTClient

import config

mqtt_client = MQTTClient(
    server=config.MQTT_SERVER,
    client_id=config.MQTT_CLIENT_ID,
    user=config.MQTT_USER,
    password=config.MQTT_PASSWORD,
)
mqtt_client.DEBUG = True