Ejemplo n.º 1
0
 def __init__(self, host, port):
     self._topic = "default"
     self._un_ack_sub = list()
     self._observers: Set[Observer] = set()
     # Construct a Client
     self._client = mqtt.Client(
         client_id=mqtt.base62(uuid.uuid4().int, padding=22))
     self._client.username_pw_set("FebML")
     self._client.on_connect = self._on_connect
     self._client.on_disconnect = self._on_disconnect
     self._client.on_message = self._on_message
     self._client.on_subscribe = self._on_subscribe
     # connect broker,connect() or connect_async()
     self._client.connect(host, port, 60)
     self._client.loop_start()
Ejemplo n.º 2
0
    def init_client(self):
        """Initialize paho client."""
        # We don't import on the top because some integrations
        # should be able to optionally rely on MQTT.
        import paho.mqtt.client as mqtt  # pylint: disable=import-outside-toplevel

        if self.conf[CONF_PROTOCOL] == PROTOCOL_31:
            proto: int = mqtt.MQTTv31
        else:
            proto = mqtt.MQTTv311

        if (client_id := self.conf.get(CONF_CLIENT_ID)) is None:
            # PAHO MQTT relies on the MQTT server to generate random client IDs.
            # However, that feature is not mandatory so we generate our own.
            client_id = mqtt.base62(uuid.uuid4().int, padding=22)
Ejemplo n.º 3
0
 def __init__(self, host, port, topic='hello', client_id=None):
     self._unacked_sub = list()
     self._observers: List[Observer] = []
     self._topic = topic
     if client_id is None:
         self._client_id = mqtt.base62(uuid.uuid4().int, padding=22)
     else:
         self._client_id = client_id
     # Construct a Client
     self._client = mqtt.Client(client_id=self._client_id)
     self._client.on_connect = self._on_connect
     self._client.on_disconnect = self._on_disconnect
     self._client.on_message = self._on_message
     self._client.on_subscribe = self._on_subscribe
     # connect broker,connect() or connect_async()
     self._client.connect(host, port, 60)
     self._client.loop_start()
Ejemplo n.º 4
0
 def __init__(
     self,
     host: str,
     port: int = 1883,
     **client_options: Any,
 ) -> None:
     """Set up client."""
     self.host = host
     self.port = port
     if "client_id" not in client_options:
         client_options["client_id"] = mqtt.base62(uuid.uuid4().int, padding=22)
     if "logger" not in client_options:
         client_options["logger"] = PAHO_MQTT_LOGGER
     client_options["clean_session"] = True
     self.client_options = client_options
     self.asyncio_client: AsyncioClient = None
     self.create_client()
     self.reconnect_interval = 1
     self.publish_queue: asyncio.Queue = asyncio.Queue()
Ejemplo n.º 5
0
    async def _connect(self) -> None:
        """Connect to the broker."""
        self._client = AsyncioClient(
            self._host,
            self._port,
            client_id=mqtt.base62(uuid.uuid4().int, padding=22),
            logger=PAHO_MQTT_LOGGER,
            clean_session=True,
        )
        try:
            await self._client.connect(timeout=10)
        except MqttError as err:
            raise TransportError from err

        if self._incoming_task is not None:
            raise RuntimeError(
                "Client needs to disconnect before connecting again.")

        self._incoming_task = asyncio.create_task(self._handle_incoming())
Ejemplo n.º 6
0
def _setup_mqtt(url: str, passwort_file: Optional[str]) -> mqtt.Client:
    client_id = mqtt.base62(uuid.uuid4().int, padding=22)
    mqttc = mqtt.Client(client_id)
    mqttc.enable_logger(_LOGGER)
    parsed = urlparse(url)

    if parsed.scheme == "mqtts":
        mqttc.tls_set()
    port = parsed.port or 1883
    password = parsed.password
    if passwort_file:
        with open(passwort_file) as f:
            password = f.read()

    if parsed.username:
        mqttc.username_pw_set(parsed.username, password)
    _LOGGER.info(f"connect to {parsed.hostname}:{parsed.port}")
    mqttc.connect(parsed.hostname, port=port, keepalive=60)
    mqttc.loop_start()
    return mqttc
Ejemplo n.º 7
0
    def init_client(self):
        """Initialize paho client."""
        # We don't import on the top because some integrations
        # should be able to optionally rely on MQTT.
        import paho.mqtt.client as mqtt  # pylint: disable=import-outside-toplevel

        if self.conf[CONF_PROTOCOL] == PROTOCOL_31:
            proto: int = mqtt.MQTTv31
        else:
            proto = mqtt.MQTTv311

        client_id = self.conf.get(CONF_CLIENT_ID)
        if client_id is None:
            # PAHO MQTT relies on the MQTT server to generate random client IDs.
            # However, that feature is not mandatory so we generate our own.
            client_id = mqtt.base62(uuid.uuid4().int, padding=22)
        self._mqttc = mqtt.Client(client_id, protocol=proto)

        # Enable logging
        self._mqttc.enable_logger()

        username = self.conf.get(CONF_USERNAME)
        password = self.conf.get(CONF_PASSWORD)
        if username is not None:
            self._mqttc.username_pw_set(username, password)

        certificate = self.conf.get(CONF_CERTIFICATE)

        if certificate == "auto":
            certificate = certifi.where()

        client_key = self.conf.get(CONF_CLIENT_KEY)
        client_cert = self.conf.get(CONF_CLIENT_CERT)
        tls_insecure = self.conf.get(CONF_TLS_INSECURE)
        if certificate is not None:
            self._mqttc.tls_set(
                certificate,
                certfile=client_cert,
                keyfile=client_key,
                tls_version=ssl.PROTOCOL_TLS,
            )

            if tls_insecure is not None:
                self._mqttc.tls_insecure_set(tls_insecure)

        self._mqttc.on_connect = self._mqtt_on_connect
        self._mqttc.on_disconnect = self._mqtt_on_disconnect
        self._mqttc.on_message = self._mqtt_on_message
        self._mqttc.on_publish = self._mqtt_on_callback
        self._mqttc.on_subscribe = self._mqtt_on_callback
        self._mqttc.on_unsubscribe = self._mqtt_on_callback

        if (CONF_WILL_MESSAGE in self.conf
                and ATTR_TOPIC in self.conf[CONF_WILL_MESSAGE]):
            will_message = Message(**self.conf[CONF_WILL_MESSAGE])
        else:
            will_message = None

        if will_message is not None:
            self._mqttc.will_set(
                topic=will_message.topic,
                payload=will_message.payload,
                qos=will_message.qos,
                retain=will_message.retain,
            )
Ejemplo n.º 8
0
 def create_client_id(cls, value: str | None) -> str:
     # pylint: disable=no-self-argument
     return value or mqtt.base62(uuid.uuid4().int, padding=22)