Example #1
0
    def _mqtt_on_connect(self, _mqttc, _userdata, _flags, result_code):
        """On connect callback.

        Resubscribe to all topics we were subscribed to and publish birth
        message.
        """
        import paho.mqtt.client as mqtt

        if result_code != mqtt.CONNACK_ACCEPTED:
            _LOGGER.error('Unable to connect to the MQTT broker: %s',
                          mqtt.connack_string(result_code))
            self._mqttc.disconnect()
            return

        old_topics = self.topics

        self.topics = {key: value for key, value in self.topics.items()
                       if value is None}

        for topic, qos in old_topics.items():
            # qos is None if we were in process of subscribing
            if qos is not None:
                self.hass.add_job(self.async_subscribe, topic, qos)

        if self.birth_message:
            self.hass.add_job(self.async_publish(
                self.birth_message.get(ATTR_TOPIC),
                self.birth_message.get(ATTR_PAYLOAD),
                self.birth_message.get(ATTR_QOS),
                self.birth_message.get(ATTR_RETAIN)))
Example #2
0
    def _mqtt_on_connect(self, _mqttc, _userdata, _flags,
                         result_code: int) -> None:
        """On connect callback.

        Resubscribe to all topics we were subscribed to and publish birth
        message.
        """
        import paho.mqtt.client as mqtt

        if result_code != mqtt.CONNACK_ACCEPTED:
            _LOGGER.error('Unable to connect to the MQTT broker: %s',
                          mqtt.connack_string(result_code))
            self._mqttc.disconnect()
            return

        # Group subscriptions to only re-subscribe once for each topic.
        keyfunc = attrgetter('topic')
        for topic, subs in groupby(sorted(self.subscriptions, key=keyfunc),
                                   keyfunc):
            # Re-subscribe with the highest requested qos
            max_qos = max(subscription.qos for subscription in subs)
            self.hass.add_job(self._async_perform_subscription, topic, max_qos)

        if self.birth_message:
            self.hass.add_job(
                self.async_publish(*attr.astuple(self.birth_message)))
Example #3
0
    def __on_disconnect(self, client, userdata, result_code):
        # pylint: disable=W0613
        """
        Client has been disconnected from the server

        :param client: Client that received the message
        :param userdata: User data (unused)
        :param result_code: Disconnection reason (0: expected, 1: error)
        """
        if result_code:
            # rc != 0: unexpected disconnection
            _logger.error(
                "Unexpected disconnection from the MQTT server: %s (%d)",
                paho.connack_string(result_code),
                result_code,
            )

            # Try to reconnect
            self.__stop_timer()
            self.__start_timer(2)

        # Notify the caller, if any
        if self.on_disconnect is not None:
            try:
                self.on_disconnect(self, result_code)
            except Exception as ex:
                _logger.exception("Error notifying MQTT listener: %s", ex)
Example #4
0
def start_mqtt():
    global mqtt_client
    try:
        log.info('Start MQTT Client')

        # Create the MQTT Client
        mqtt_client = mqtt.Client(client_id=settings.MQTT_CLIENT_ID)

        # Turn on extr MQTT logging if enabled in the settings.
        if settings.MQTT_LOGGING:
            mqtt_client.enable_logger(AppLogger.logger)
        else:
            mqtt_client.disable_logger()

        # Assign callback functions
        mqtt_client.on_connect = on_connect
        mqtt_client.on_subscribe = on_subscribe
        mqtt_client.on_message = on_message

        # Connect to the MQTT broker using the server and port in the settings file.
        connack_code = mqtt_client.connect(settings.MQTT_SERVER, settings.MQTT_PORT)
        log.info('MQTT connect reply to {}, {}: {}'.format(settings.MQTT_SERVER, settings.MQTT_PORT,
                                                           mqtt.connack_string(connack_code)))

        # Blocking call that processes network traffic, dispatches callbacks and
        # handles reconnecting.
        mqtt_client.loop_forever()

    except Exception as ex:
        log.error('Exception in start_mqtt()! exception: {}'.format(ex))
        raise
Example #5
0
def start_mqtt():
    global mqtt_client
    try:
        log.debug('Start MQTT Client')

        mqtt_client = mqtt.Client(client_id=settings.MQTT_CLIENT_ID)

        if settings.MQTT_LOGGING:
            # Add MQTT logging to the app logs
            mqtt_client.enable_logger(AppLogger.logger)
        else:
            mqtt_client.disable_logger()

        # Assign callback functions
        mqtt_client.on_connect = on_connect
        mqtt_client.on_message = on_message
        mqtt_client.on_publish = on_publish
        mqtt_client.on_subscribe = on_subscribe

        # Set a Will to be sent by the broker in case the client disconnects unexpectedly.
        # QOS 2: The broker will deliver the message exactly once by using a four step handshake.
        mqtt_client.will_set('/will/oops', payload='{} has vanished!'.format(settings.MQTT_CLIENT_ID), qos=2)

        connack_code = mqtt_client.connect(settings.MQTT_SERVER, settings.MQTT_PORT)
        log.info('MQTT connect reply to {}, {}: {}'.format(settings.MQTT_SERVER, settings.MQTT_PORT,
                                                           mqtt.connack_string(connack_code)))
        # Blocking call that processes network traffic, dispatches callbacks and
        # handles reconnecting.
        mqtt_client.loop_forever()

    except Exception as ex:
        log.error('Exception in start_mqtt()! exception: {}'.format(ex))
        raise
Example #6
0
    def _on_disconnect(self, client, userdata, rc):
        """DISCONNECT received"""
        _log.debug('disconnected: %s', mqtt.connack_string(rc))

        self.adapter.stop()
        self.adapter = None
        self._schedule_reconnect()
Example #7
0
    def __on_connect(self, client, userdata, flags, result_code):
        # pylint: disable=W0613
        """
        Client connected to the server

        :param client: Connected Paho client
        :param userdata: User data (unused)
        :param flags: Response flags sent by the broker
        :param result_code: Connection result code (0: success, others: error)
        """
        if result_code:
            # result_code != 0: something wrong happened
            _logger.error(
                "Error connecting the MQTT server: %s (%d)",
                paho.connack_string(result_code),
                result_code,
            )
        else:
            # Connection is OK: stop the reconnection timer
            self.__stop_timer()

        # Notify the caller, if any
        if self.on_connect is not None:
            try:
                self.on_connect(self, result_code)
            except Exception as ex:
                _logger.exception("Error notifying MQTT listener: %s", ex)
Example #8
0
def on_connect(client, unused_userdata, unused_flags, rc):
    """Callback for when a device connects."""
    print('on_connect', mqtt.connack_string(rc))
    # After a successful connect, reset backoff time and stop backing off.
    global should_backoff
    global minimum_backoff_time
    should_backoff = False
    minimum_backoff_time = 1
Example #9
0
def on_connect(client, userdata, flags, rc):
    print("Connected", connack_string(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    for t in args.t:
        print('subscribing to', t)
        client.subscribe(t)
Example #10
0
def on_connect(unused_client, unused_userdata, unused_flags, rc):
    print(dt.now(), ': on_connect', mqtt.connack_string(rc))

    # After a successful connect, reset backoff time and stop backing off.
    global should_backoff
    global minimum_backoff_time
    should_backoff = False
    minimum_backoff_time = 1
Example #11
0
    def _on_connect(self, client, userdata, flags, rc):

        if rc == mqttc.MQTT_ERR_SUCCESS:
            self.log.info("connected")
            self.state = self.state_connected
            # TODO deliver saved msgs
        else:
            self.log.error(mqttc.connack_string(rc))
def on_connect(client, userdata, flags, rc):
    logging.info("MQTT Connected with result code " + str(rc) + ": " +
                 mqtt.connack_string(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe(MQTT_PREFIX + "/switch/#")
    connect_topic = MQTT_PREFIX + "/status"
    mqtt_client.publish(connect_topic, payload="connected", qos=0, retain=True)
Example #13
0
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        logger.info('MQTT connection established.')
    else:
        logger.error('Connection error with result code {} - {}'.format(
            str(rc), mqtt.connack_string(rc)))
        #kill main thread
        os._exit(1)
Example #14
0
 def _cb_on_connect(self, mqtt_client, userdata, flags, rc):
     if rc == 0:
         LOG.info('MQTT connection attempt succeeded.')
         self._loop.call_soon_threadsafe(self._is_mqtt_connected.set)
     else:
         LOG.warning('MQTT connection attempt failed: %s',
                     mqtt.connack_string(rc))
         self._loop.call_soon_threadsafe(self._is_mqtt_connected.clear)
Example #15
0
def mqtt_connect(client, userdata, flags, rc):
    """Callback for MQTT connects."""

    print("MQTT connected: " + mqtt.connack_string(rc))
    if rc != 0:
        print("Could not connect. Error: " + str(rc))
    else:
        client.subscribe(args.rtl_topic)
Example #16
0
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print_line('MQTT connection established', console=True, sd_notify=True)
        print()
    else:
        print_line('Connection error with result code {} - {}'.format(str(rc), mqtt.connack_string(rc)), error=True)
        #kill main thread
        os._exit(1)
 def on_connect(client, userdata, flags, rc):
     print("Result from connect: {}".format(
         mqtt.connack_string(rc)))
     # Check whether the result form connect is the CONNACK_ACCEPTED  
     #connack code
     if rc == mqtt.CONNACK_ACCEPTED:
         # Subscribe to the commands topic filter
         client.subscribe(VehicleCommandProcessor.commands_topic, qos=2)
Example #18
0
def on_connect(client, userdata, flags, rc):
    """ Callback for when the client receives a CONNACK response from the server. """
    log.info("MQTT Connection: " + mqtt.connack_string(rc))
    if rc != 0:
        log.error("Could not connect. RC: " + str(rc))
        exit()
    # Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed.
    client.subscribe(MQTT_TOPIC_PREFIX)
Example #19
0
def on_connect(client, userdata, flags, rc):
    try:    
        print("Connect result: {}".format(mqtt.connack_string(rc)))
        client.connected_flag = True
        client.subscribe(MQ_TOPIC, qos=1)
        
    except Exception as e:
        print ("Exception", e)
Example #20
0
 def _mqtt_on_connect(self, client, userdata, flags_dict, rc):
     if rc == 0:
         logger.info('Connected to MQTT server')
         # subscribe
         self.mqtt_client.subscribe('/send_command/#')
     else:
         logger.error('Error connecting to MQTT server (%d): %s',
                      rc, paho.connack_string(rc))
Example #21
0
def on_connect(client, unused_userdata, unused_flags, rc):
    """Callback for when a device connects."""
    print('on_connect', mqtt.connack_string(rc))

    gateway_state.connected = True

    # Subscribe to the config topic.
    client.subscribe(gateway_state.mqtt_config_topic, qos=1)
Example #22
0
    def _on_disconnect(self, mqttclient, userdata, rc):
        """MQTT callback at disconnect.

        Method signature according to Paho documentation.

        """
        self.logger.warning("Now disconnected from MQTT broker. Host: {}, Port: {}, Result: '{}'".format(
                mqttclient._host, mqttclient._port, mqtt.connack_string(rc)))
        self._set_broker_connectionstatus(False)
Example #23
0
def on_connect(unused_client, unused_userdata, unused_flags, rc):
    """Callback for when a device connects."""
    logger.info('on_connect {}'.format(mqtt.connack_string(rc)))

    # After a successful connect, reset backoff time and stop backing off.
    global minimum_backoff_time
    minimum_backoff_time = 1

    gateway_state.connected = True
 def on_disconnect(self, client, userdata, rc):
     self.available = "offline"
     if rc != 0:
         self.logger.error(
             "[MQTT] on_disconnect - Unexpected disconnection." +
             mqtt.connack_string(rc))
     else:
         self.logger.warning(
             "[MQTT] on_disconnect - Successfully disconnect")
Example #25
0
    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            self.notify("mqttBridge", "(re)connected to server!")
            self.subscribe(self._topic, 0)

        # Not sure this will be triggered using client.loop_forever
        else:
            self.notify("mqttBridge",
                        "Connection failed: " + paho.connack_string(rc))
Example #26
0
def on_connect(client, user_data, flags, connection_result_code):

    if connection_result_code == 0:
        logger.info("Connected to MQTT Broker")
    else:
        logger.error("Failed to connect to MQTT Broker: " +
                     mqtt.connack_string(connection_result_code))

    client.subscribe(TOPIC)
Example #27
0
def _on_connect(client, userdata, flags, rc):
    """Internal callback"""
    #pylint: disable=invalid-name, unused-argument

    if rc == 0:
        if len(userdata) > 0:
            _do_publish(client)
    else:
        raise mqtt.MQTTException(paho.connack_string(rc))
Example #28
0
def on_connect(client, userdata, flags, result):
    # logger.debug("MQTT Connection result: " + pahomqtt.connack_string(result))
    if result == 0:
        # got connected OK
        logger.debug("MQTT Connected OK.")
        # subscribe here, so that we always renew subs after reconnecting
        paho_client.subscribe(MQTT_TOPIC_PREFIX + "/" + mac_address)
    else:
        logger.error("MQTT Connect failed: " + pahomqtt.connack_string(result) + " Check .env credentials.")
Example #29
0
 def on_connect(client, ud, flags, rc):
     terminal_label.config(text=mqtt.connack_string(rc))
     if rc == 5:
         add_worker_btn.config(state='disabled')
         pin_card_btn.config(state='disabled')
         stop_btn.config(state='disabled')
         remove_worker_btn.config(state='disabled')
         unpin_card_btn.config(state='disabled')
         make_report_btn.config(state='disabled')
Example #30
0
    def on_connect(self, client, userdata, flags, rc):
        log.log(logging.INFO if not rc else logging.ERROR,
                mqtt.connack_string(rc))
        if rc:
            return None
        self.connected = True

        self.subscriptions.clear()
        self.subscription_changed()
def _create_error_from_connack_rc_code(rc):
    """
    Given a paho CONNACK rc code, return an Exception that can be raised
    """
    message = mqtt.connack_string(rc)
    if rc in paho_connack_rc_to_error:
        return paho_connack_rc_to_error[rc](message)
    else:
        return exceptions.ProtocolClientError("Unknown CONNACK rc={}".format(rc))
Example #32
0
 def _on_connect(client, self, flags, rc):
     """Can't subscribe to a topic until after we're connected"""
     if rc == mqtt.MQTT_ERR_SUCCESS:
         LOGGER.info(
             "Successfully connected, subscribing to sensors channel")
         self.refresh_subscriptions()
     else:
         LOGGER.error("on_connect: received an error: %s",
                      mqtt.connack_string(rc))
def on_connect(unused_client, unused_userdata, unused_flags, rc):
    """Callback for when a device connects."""
    print('on_connect', mqtt.connack_string(rc))

    # After a successful connect, reset backoff time and stop backing off.
    global should_backoff
    global minimum_backoff_time
    should_backoff = False
    minimum_backoff_time = 1
Example #34
0
def _on_connect(client, userdata, flags, rc):
    """Internal callback"""
    #pylint: disable=invalid-name, unused-argument

    if rc == 0:
        if len(userdata) > 0:
            _do_publish(client)
    else:
        raise mqtt.MQTTException(paho.connack_string(rc))
Example #35
0
        def on_mqtt_connect(client, userdata, rc):
            logging.info("MQTT Connection returned result: " +
                         mqtt.connack_string(rc))

            # Subscribing in on_connect() means that if we lose the connection and
            # reconnect then subscriptions will be renewed.
            self.mqttc.subscribe(self.config.mqtt.display_topic + '/set')
            self.mqttc.subscribe(self.config.mqtt.light_topic + '/set')
            self.mqttc.subscribe(self.config.mqtt.brightness_topic + '/set')
Example #36
0
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print('MQTT connection established')
        print()
    else:
        print('Connection error with result code {} - {}'.format(
            str(rc), mqtt.connack_string(rc)))
        #kill main thread
        sys.exit(1)
Example #37
0
def mqtt_connect(client, userdata, flags, rc):
    """Callback for MQTT connects."""

    logging.info("MQTT connected: " + mqtt.connack_string(rc))
    if rc != 0:
        logging.error("Could not connect. Error: " + str(rc))
    else:
        logging.info("Subscribing to: " + args.rtl_topic)
        client.subscribe(args.rtl_topic)
Example #38
0
def on_connect(mosq, userdata, rc):
    logging.info("Connection to broker: %s", paho.connack_string(rc))
    if rc == 0:
        mqttc.publish("/clients/" + client_id, "Online")

        map = userdata['map']
        for topic in map:
            logging.info("Subscribing to topic %s" % topic)
            mqttc.subscribe(topic, 0)
Example #39
0
 def on_connect(client, userdata, flags, rc):
     print("Result from connect: {}".format(
         mqtt.connack_string(rc)))
     # Проверяем, получено ли при подключении от сервера CONNACK_ACCEPTED код (подтвреждающий успешное подключение)
     if rc == mqtt.CONNACK_ACCEPTED:
         # Подписываемся на соотвествующую тему mqtt
         client.subscribe(
             DeviceCommandProcessor.commands_topic, 
             qos=2)
Example #40
0
    def _mqtt_on_connect(self, _mqttc, _userdata, _flags,
                         result_code: int) -> None:
        """On connect callback.

        Resubscribe to all topics we were subscribed to and publish birth
        message.
        """
        # pylint: disable-next=import-outside-toplevel
        import paho.mqtt.client as mqtt

        if result_code != mqtt.CONNACK_ACCEPTED:
            _LOGGER.error(
                "Unable to connect to the MQTT broker: %s",
                mqtt.connack_string(result_code),
            )
            return

        self.connected = True
        dispatcher_send(self.hass, MQTT_CONNECTED)
        _LOGGER.info(
            "Connected to MQTT server %s:%s (%s)",
            self.conf[CONF_BROKER],
            self.conf[CONF_PORT],
            result_code,
        )

        # Group subscriptions to only re-subscribe once for each topic.
        keyfunc = attrgetter("topic")
        self.hass.add_job(
            self._async_perform_subscriptions,
            [
                # Re-subscribe with the highest requested qos
                (topic, max(subscription.qos for subscription in subs))
                for topic, subs in groupby(
                    sorted(self.subscriptions, key=keyfunc), keyfunc)
            ],
        )

        if (CONF_BIRTH_MESSAGE in self.conf
                and ATTR_TOPIC in self.conf[CONF_BIRTH_MESSAGE]):

            async def publish_birth_message(birth_message):
                await self._ha_started.wait(
                )  # Wait for Home Assistant to start
                await self._discovery_cooldown(
                )  # Wait for MQTT discovery to cool down
                await self.async_publish(
                    topic=birth_message.topic,
                    payload=birth_message.payload,
                    qos=birth_message.qos,
                    retain=birth_message.retain,
                )

            birth_message = PublishMessage(**self.conf[CONF_BIRTH_MESSAGE])
            asyncio.run_coroutine_threadsafe(
                publish_birth_message(birth_message), self.hass.loop)
Example #41
0
    def _on_connect(self, client, userdata, flags, return_code):
        logger.info('connected to mqtt broker: {}'.format(mqtt.connack_string(return_code)))

        if self._online_topic:
            logger.info('publishing to "{}"'.format(self._online_topic))
            self._client.publish(self._online_topic, '1', retain=True)

        if self._marquee_topic:
            logger.info('subscribing to "{}"'.format(self._marquee_topic))
            self._client.subscribe(self._marquee_topic)
Example #42
0
def _on_connect(c, userdata, flags, rc):
    """Internal callback"""
    if rc != 0:
        raise mqtt.MQTTException(paho.connack_string(rc))

    if type(userdata['topics']) is list:
        for t in userdata['topics']:
            c.subscribe(t, userdata['qos'])
    else:
        c.subscribe(userdata['topics'], userdata['qos'])
Example #43
0
    def on_connect(self, client, userdata, flags, rc):
        logging.debug("Connected with result code " + str(rc))
        logging.debug(mqtt.connack_string(rc))

        self.client.message_callback_add('crestron/button', self.cb_button)

        self.client.subscribe("crestron/#")
        self.connected = True

        self.crestron_connect()
Example #44
0
    def rcstr(cls, retcode):
        """
        Returns a string representation of the return code

        Args:
            retcode (int): MQTT Connection return code
        Returns:
            A string representation of the return code
        """
        return connack_string(retcode)
Example #45
0
    def _on_connect(self, mqttclient, userdata, flags, rc):
        """MQTT callback at connection attempts.

        This callback is responsible for doing the subscriptions, and to
        publish capabilities and default values.

        Method signature according to Paho documentation.

        """
        if rc != mqtt.CONNACK_ACCEPTED:
            self.logger.warning("  Failed connection to MQTT broker. Host: {}, Port: {}, Result: '{}'".format(
                mqttclient._host, mqttclient._port, mqtt.connack_string(rc)))
            self._set_broker_connectionstatus(False)
            return

        self.logger.info("  Successful connection to MQTT broker. Host: {}, Port: {}, Result: '{}'".format(
            mqttclient._host, mqttclient._port, mqtt.connack_string(rc)))
        self._set_broker_connectionstatus(True)
        self._subscribe_to_inputsignals()
        self._publish_capablities_and_defaultvalues()
Example #46
0
def _on_connect(client, userdata, rc):
    if rc == 0:
        msg = "Connected to mqtt broker with result code "+str(rc)
        logging.info(msg)
        if DeviceId is None:
            logging.info("device id not specified")
            raise Exception("DeviceId not specified")
        topic = "client/" + ClientId + "/in/device/" + DeviceId + "/asset/+/command"
        logging.info("subscribing to: " + topic)
        result = client.subscribe(topic)                                                    #Subscribing in _on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed.
        logging.info(str(result))                                                           # result is not a string on all platforms.
    else:
        logging.error("Failed to connect to mqtt broker: "  + mqtt.connack_string(rc))
Example #47
0
    def on_connect(self, client, userdata, flags, rc):
        """
        Invoked on successful connection to a broker after connection request

        :param client: The client instance for this callback
        :param userdata: The private user data as set in Client() or userdata_set()
        :param flags: Response flags sent by the broker
        :param rc: The connection result
        :return:
        """
        self._connect_result_code = rc
        self._disconnect_result_code = sys.maxsize
        log.info("Connected with result code : {0} : {1} ".format(str(rc), paho.connack_string(rc)))
Example #48
0
def on_connect(client, userdata, rc):
    if rc == 0:
        msg = "Connected to mqtt broker with result code "+str(rc)
        print(msg)
        if DeviceId is None:
            print("device id not specified")
            raise Exception("DeviceId not specified")
        topic = "client/" + ClientId + "/in/device/" + DeviceId + "/asset/+/command"
        print("subscribing to: " + topic)
        result = client.subscribe(topic)                                                    #Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed.
        print(result)
    else:
        print("Failed to connect to mqtt broker: "  + mqtt.connack_string(rc))
Example #49
0
 def disconnect(self):
     """
     Disconnects from MQTT Broker
     :return:
     """
     self._paho_client.disconnect()
     ten_ms_count = 0
     while (ten_ms_count != self._conn_disconn_timeout * 100) and (self._disconnect_result_code == sys.maxsize):
         ten_ms_count += 1
         time.sleep(0.01)
     if self._disconnect_result_code == sys.maxsize:
         log.error("Disconnect timeout.")
         raise Exception("Disconnection Timeout")
     elif self._disconnect_result_code == 0:
         log.info("Disconnected from MQTT Broker.")
         log.info("Disconnect time consumption: " + str(float(ten_ms_count) * 10) + "ms.")
         #  Disconnect is successful.  Stopping background network loop.
         self._paho_client.loop_stop()
     else:
         log.error("Disconnect error with result code : {0} : {1} ".
                   format(str(self._disconnect_result_code), paho.connack_string(self._disconnect_result_code)))
         raise Exception("Disconnect error with result code : {0} : {1} ".
                   format(str(self._disconnect_result_code), paho.connack_string(self._disconnect_result_code)))
Example #50
0
def on_connect(client, userdata, flags, rc):
    log.info("MQTT Client connection results: {}".format(mqtt.connack_string(rc)))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    # QOS 0: The broker will deliver the message once, with no confirmation.
    # QOS 1: The broker will deliver the message at least once, with confirmation required.
    # QOS 2: The broker will deliver the message exactly once by using a four step handshake.
    #
    # A list of tuples (i.e. topic, qos). Both topic and qos must be present in the tuple.

    try:
        client.subscribe(topics)
    except Exception as ex:
        log.error('Client Subscribe exception. ex={}'.format(ex))
Example #51
0
    def on_disconnect(self, client, userdata, rc):
        """
        Invoked when disconnected from broker.  Two scenarios are possible:

        1) Broker rejects a connection request
        2) Client initiated disconnect

        :param client: The client instance for this callback
        :param userdata: The private user data as set in Client() or userdata_set()
        :param rc: The connection result
        :return:
        """
        self._connect_result_code = sys.maxsize
        self._disconnect_result_code = rc
        log.info("Disconnected with result code : {0} : {1} ".format(str(rc), paho.connack_string(rc)))
Example #52
0
def on_connect(client, userdata, rc):
    if rc == 0:
        print( "Connected to mqtt broker with result code "+str(rc))

        ioMapOutput = bytearray.fromhex(ioMap)
        print("sending io map: " + str(ioMapOutput) + "topic = " + ioMapTopic)
        _mqttClient.publish(ioMapTopic, ioMapOutput, 0, False)
        print("sending outputs: " + str(outputs))
        _mqttClient.publish(outputsTopic, outputs, 0, False)
        print("sending relays: " + str(relays))
        _mqttClient.publish(relaysTopic, relays, 0, False)
        print("sending pin types: " + str(pinTypes))
        _mqttClient.publish(pinTypesTopic, pinTypes, 0, False)
        print "Messages sent"
        _mqttClient.disconnect()
        sys.exit()
        
    else:
        print("Failed to connect to mqtt broker: "  + mqtt.connack_string(rc))
Example #53
0
def on_connect(client, userdata, rc):
    global _mqttConnected
    try:
        if rc == 0:
            _mqttConnected = True
            logging.info("Connected to mqtt broker with result code "+str(rc))
            if _callbacks:
                for topic, definitions in _callbacks.iteritems():
                    _subscribe(topic)
                    for definition in definitions:
                        if definition.level == 'asset' and definition.direction == 'in' and definition.toMonitor == 'state':    # refresh the state of all assets being monitored when reconnecting. Other events can't be refreshed.
                            curVal = getAssetState(definition.id)
                            if curVal:
                                if 'state' in curVal:
                                    definition.callback(curVal['state'])
                                elif 'value' in curVal:
                                    definition.callback(curVal)
        else:
            logging.error("Failed to connect to mqtt broker: " + mqtt.connack_string(rc))
    except Exception:
        logging.exception("failed to connect")
Example #54
0
    def connect_soc(self):
        """
        Establishes connection with MQTT Broker
        :return:
        """
        # Set up TLS support
        if self.tls_conf:

            if self.identity is None:
                raise ValueError("Identity required to be set")

            # Creating the tls context
            if ssl is None:
                raise ValueError("This platform has no SSL/TLS")

            # Validate CA certificate path
            if self.identity.root_ca_cert is None and not hasattr(ssl.SSLContext, 'load_default_certs'):
                raise ValueError("Error : CA certificate path is missing")
            else:
                if self.identity.root_ca_cert and not (os.path.exists(self.identity.root_ca_cert)):
                    raise ValueError("Error : Wrong CA certificate path")

            if self.tls_conf.tls_version is None:
                tls_version = ssl.PROTOCOL_TLSv1_2
                # If the python version supports it, use highest TLS version automatically
                if hasattr(ssl, "PROTOCOL_TLS"):
                    tls_version = ssl.PROTOCOL_TLS
            else:
                tls_version = getattr(ssl, self.tls_conf.tls_version)
            context = ssl.SSLContext(tls_version)

            # Validate client certificate path
            if self.identity.cert_file:
                if os.path.exists(self.identity.cert_file):
                    client_cert_available = True
                else:
                    raise ValueError("Error : Wrong client certificate path")
            else:
                client_cert_available = False

            # Validate client key file path
            if self.identity.key_file:
                if os.path.exists(self.identity.key_file):
                    client_key_available = True
                else:
                    raise ValueError("Error : Wrong client key path.")
            else:
                client_key_available = False

            '''
                Multiple conditions for certificate validations
                # 1. Both Client certificate and key file should be present
                # 2. If client certificate is not there throw an error
                # 3. If client key is not there throw an error
                # 4. If both are not there proceed without client certificate and key
            '''
            if client_cert_available and client_key_available:
                context.load_cert_chain(self.identity.cert_file, self.identity.key_file)
            elif not client_cert_available and client_key_available:
                raise ValueError("Error : Client key found, but client certificate not found")
            elif client_cert_available and not client_key_available:
                raise ValueError("Error : Client certificate found, but client key not found")
            else:
                log.info("Client Certificate and Client Key are not provided")

            if getattr(ssl, self.tls_conf.cert_required) == ssl.CERT_NONE and hasattr(context, 'check_hostname'):
                context.check_hostname = False

            context.verify_mode = ssl.CERT_REQUIRED if self.tls_conf.cert_required is None else getattr(ssl,
                                                                                                        self.tls_conf.cert_required)

            if self.identity.root_ca_cert is not None:
                context.load_verify_locations(self.identity.root_ca_cert)
            else:
                context.load_default_certs()

            if self.tls_conf.cipher is not None:
                context.set_ciphers(self.tls_conf.ciphers)

            # Setting the verify_flags to VERIFY_CRL_CHECK_CHAIN in this mode
            # certificate revocation lists (CRLs) of all certificates in the
            # peer cert chain are checked if the path of CRLs in PEM or DER format
            # is specified
            crl_path = read_liota_config('CRL_PATH', 'crl_path')
            if crl_path and crl_path != "None" and crl_path != "":
                if os.path.exists(crl_path):
                    context.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN
                    context.load_verify_locations(cafile=crl_path)
                else:
                    raise ValueError("Error : Wrong Client CRL path {0}".format(crl_path))

            # Setting the tls context
            self._paho_client.tls_set_context(context)

            if getattr(ssl, self.tls_conf.cert_required) != ssl.CERT_NONE:
                # Default to secure, sets context.check_hostname attribute
                # if available
                self._paho_client.tls_insecure_set(False)
            else:
                # But with ssl.CERT_NONE, we can not check_hostname
                self._paho_client.tls_insecure_set(True)
        else:
            log.info("TLS configuration is not set")


        # Set up username-password
        if self.enable_authentication:
            if self.identity is None:
                raise ValueError("Identity required to be set")
            else:
                if self.identity.username is None:
                    raise ValueError("Username not found")
                elif self.identity.password is None:
                    raise ValueError("Password not found")
                else:
                    self._paho_client.username_pw_set(self.identity.username, self.identity.password)
        else:
            log.info("Authentication is disabled")

        if self.qos_details:
            # Set QoS parameters
            self._paho_client.max_inflight_messages_set(self.qos_details.in_flight)
            self._paho_client.max_queued_messages_set(self.qos_details.queue_size)
            self._paho_client.message_retry_set(self.qos_details.retry)

        # Connect with MQTT Broker
        self._paho_client.connect(host=self.url, port=self.port, keepalive=self.keep_alive)

        # Start network loop to handle auto-reconnect
        self._paho_client.loop_start()
        ten_ms_count = 0
        while (ten_ms_count != self._conn_disconn_timeout * 100) and (self._connect_result_code == sys.maxsize):
            ten_ms_count += 1
            time.sleep(0.01)
        if self._connect_result_code == sys.maxsize:
            log.error("Connection timeout.")
            #  Stopping background network loop as connection establishment failed.
            self._paho_client.loop_stop()
            raise Exception("Connection Timeout")
        elif self._connect_result_code == 0:
            log.info("Connected to MQTT Broker.")
            log.info("Connect time consumption: " + str(float(ten_ms_count) * 10) + "ms.")
        else:
            log.error("Connection error with result code : {0} : {1} ".
                      format(str(self._connect_result_code), paho.connack_string(self._connect_result_code)))
            #  Stopping background network loop as connection establishment failed.
            self._paho_client.loop_stop()
            raise Exception("Connection error with result code : {0} : {1} ".
                            format(str(self._connect_result_code), paho.connack_string(self._connect_result_code)))
Example #55
0
    def connect_soc(self):
        """
        Establishes connection with MQTT Broker
        :return:
        """
        # Set up TLS support
        if self.tls_details:

            # Validate CA certificate path
            if self.remote_system_identity.root_ca_cert:
                if not(os.path.exists(self.remote_system_identity.root_ca_cert)):
                    log.error("Error : Wrong CA certificate path.")
                    raise ValueError("Error : Wrong CA certificate path.")
            else:
                log.error("Error : Wrong CA certificate path.")
                raise ValueError("Error : CA certificate path is missing")

            # Validate client certificate path
            if self.edge_system_identity.cert_file:
                if os.path.exists(self.edge_system_identity.cert_file):
                    client_cert_available = True
                else:
                    log.error("Error : Wrong client certificate path.")
                    raise ValueError("Error : Wrong client certificate path.")
            else:
                client_cert_available = False

            # Validate client key file path
            if self.edge_system_identity.key_file:
                if os.path.exists(self.edge_system_identity.key_file):
                    client_key_available = True
                else:
                    log.error("Error : Wrong client key path.")
                    raise ValueError("Error : Wrong client key path.")
            else:
                client_key_available = False

            '''
                Multiple conditions for certificate validations
                # 1. Both Client certificate and key file should be present
                # 2. If both are not there proceed without client certificate and key
                # 3. If client certificate is not there throw an error
                # 4. If client key is not there throw an error
            '''

            if client_cert_available and client_key_available:
                log.debug("Certificates : ", self.remote_system_identity.root_ca_cert, self.edge_system_identity.cert_file,
                          self.edge_system_identity.key_file)

                self._paho_client.tls_set(self.remote_system_identity.root_ca_cert, self.edge_system_identity.cert_file,
                                          self.edge_system_identity.key_file,
                                          cert_reqs=getattr(ssl, self.tls_details.cert_required),
                                          tls_version=getattr(ssl, self.tls_details.tls_version),
                                          ciphers=self.tls_details.cipher)
            elif not client_cert_available and not client_key_available:
                self._paho_client.tls_set(self.remote_system_identity.root_ca_cert,
                                          cert_reqs=getattr(ssl, self.tls_details.cert_required),
                                          tls_version=getattr(ssl, self.tls_details.tls_version),
                                          ciphers=self.tls_details.cipher)
            elif not client_cert_available and client_key_available:
                log.error("Error : Client key found, but client certificate not found")
                raise ValueError("Error : Client key found, but client certificate not found")
            else:
                log.error("Error : Client key found, but client certificate not found")
                raise ValueError("Error : Client certificate found, but client key not found")
            log.info("TLS support is set up.")

        # Set up username-password
        if self.enable_authentication:
            if not self.remote_system_identity.username:
                log.error("Username not found")
                raise ValueError("Username not found")
            elif not self.remote_system_identity.password:
                log.error("Password not found")
                raise ValueError("Password not found")
            else:
                self._paho_client.username_pw_set(self.remote_system_identity.username, self.remote_system_identity.password)

        if self.qos_details:
            # Set QoS parameters
            self._paho_client.max_inflight_messages_set(self.qos_details.in_flight)
            self._paho_client.max_queued_messages_set(self.qos_details.queue_size)
            self._paho_client.message_retry_set(self.qos_details.retry)

        # Connect with MQTT Broker
        self._paho_client.connect(host=self.url, port=self.port, keepalive=self.keep_alive)

        # Start network loop to handle auto-reconnect
        self._paho_client.loop_start()
        ten_ms_count = 0
        while (ten_ms_count != self._conn_disconn_timeout * 100) and (self._connect_result_code == sys.maxsize):
            ten_ms_count += 1
            time.sleep(0.01)
        if self._connect_result_code == sys.maxsize:
            log.error("Connection timeout.")
            #  Stopping background network loop as connection establishment failed.
            self._paho_client.loop_stop()
            raise Exception("Connection Timeout")
        elif self._connect_result_code == 0:
            log.info("Connected to MQTT Broker.")
            log.info("Connect time consumption: " + str(float(ten_ms_count) * 10) + "ms.")
        else:
            log.error("Connection error with result code : {0} : {1} ".
                      format(str(self._connect_result_code), paho.connack_string(self._connect_result_code)))
            #  Stopping background network loop as connection establishment failed.
            self._paho_client.loop_stop()
            raise Exception("Connection error with result code : {0} : {1} ".
                      format(str(self._connect_result_code), paho.connack_string(self._connect_result_code)))
    def connect(self, keepalive=60):
        # tls
        try:
            self._iot_mqtt_client_handler.tls_set(self._cafile, self._cert, self._key, ssl.CERT_REQUIRED, ssl.PROTOCOL_SSLv23)
        except ValueError as ve:
            send_output(self.wrapper_debug, self.wrapper_Tx, "C F " + ve.message)
            return
        except:
            send_output(self.wrapper_debug, self.wrapper_Tx, "C F TLS Error")
            return

        # connect
        try:
            self._iot_mqtt_client_handler.connect(self._serverURL, self._serverPORT, keepalive)
            self._iot_mqtt_client_handler.loop_start()
        except BaseException as e:
            send_output(self.wrapper_debug, self.wrapper_Tx, "C F " + e.message)
            return

        cnt_sec = 0
        while cnt_sec < MAX_CONN_TIME and self.conn_res == -1:  # waiting for connecting to complete (on_connect)
            cnt_sec += 1
            time.sleep(1)

        if self.conn_res != -1:
            send_output(self.wrapper_debug, self.wrapper_Tx, "C " + str(self.conn_res) + " " + mqtt.connack_string(self.conn_res))  # 0 for connected
        else:
            send_output(self.wrapper_debug, self.wrapper_Tx, "C F Connection time out")
        return self.conn_res
Example #57
0
def _on_connect(c, userdata, flags, rc):
    """Internal callback"""
    if rc == 0:
        _do_publish(c)
    else:
        raise mqtt.MQTTException(paho.connack_string(rc))
Example #58
0
def on_connect(client, userdata, rc):
    print 'Connection result:', connack_string(rc)
Example #59
0
 def on_disconnect(client, userdata, rc):
     self.connected = False
     log.info('MQTT disconnect: {}'.format(mqtt.connack_string(rc)))