Skip to content

Commit

Permalink
Support connecting to MQTT brokers on non-standard ports
Browse files Browse the repository at this point in the history
This patch makes the broker port configurable by adding a 'port' field to Settings.MQTT.
It incorporates parts of 2f2d5c9.

Signed-off-by: Timo Beckers <timo@incline.eu>
  • Loading branch information
ti-mo committed Sep 22, 2023
1 parent 2055002 commit f3b1be4
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
19 changes: 13 additions & 6 deletions ha_mqtt_discoverable/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ class MQTT(BaseModel):
"""Connection settings for the MQTT broker"""

host: str
port: Optional[int] = 1883
username: Optional[str] = None
password: Optional[str] = None
client_name: Optional[str] = None
Expand Down Expand Up @@ -668,11 +669,13 @@ def _setup_client(self, on_connect: Optional[Callable] = None) -> None:
mqtt_settings = self._settings.mqtt
logger.debug(
f"Creating mqtt client({mqtt_settings.client_name}) for "
"{mqtt_settings.host}"
"{mqtt_settings.host}:{mqtt_settings.port}"
)
self.mqtt_client = mqtt.Client(mqtt_settings.client_name)
if mqtt_settings.tls_key:
logger.info(f"Connecting to {mqtt_settings.host} with SSL")
logger.info(
f"Connecting to {mqtt_settings.host}:{mqtt_settings.port} with SSL"
)
logger.debug(f"ca_certs={mqtt_settings.tls_ca_cert}")
logger.debug(f"certfile={mqtt_settings.tls_certfile}")
logger.debug(f"keyfile={mqtt_settings.tls_key}")
Expand All @@ -684,7 +687,9 @@ def _setup_client(self, on_connect: Optional[Callable] = None) -> None:
tls_version=ssl.PROTOCOL_TLS,
)
else:
logger.debug(f"Connecting to {mqtt_settings.host} without SSL")
logger.debug(
f"Connecting to {mqtt_settings.host}:{mqtt_settings.port} without SSL"
)
if mqtt_settings.username:
self.mqtt_client.username_pw_set(
mqtt_settings.username, password=mqtt_settings.password
Expand All @@ -699,7 +704,9 @@ def _setup_client(self, on_connect: Optional[Callable] = None) -> None:
def _connect_client(self) -> None:
"""Connect the client to the MQTT broker, start its onw internal loop in
a separate thread"""
result = self.mqtt_client.connect(self._settings.mqtt.host)
result = self.mqtt_client.connect(
self._settings.mqtt.host, self._settings.mqtt.port
)
# Check if we have established a connection
if result != mqtt.MQTT_ERR_SUCCESS:
raise RuntimeError("Error while connecting to MQTT broker")
Expand Down Expand Up @@ -749,7 +756,7 @@ def delete(self) -> None:
config_message = ""
logger.info(
f"Writing '{config_message}' to topic {self.config_topic} on "
"{self._settings.mqtt.host}"
"{self._settings.mqtt.host}:{self._settings.mqtt.port}"
)
self.mqtt_client.publish(self.config_topic, config_message, retain=True)

Expand Down Expand Up @@ -783,7 +790,7 @@ def write_config(self):

logger.debug(
f"Writing '{config_message}' to topic {self.config_topic} on "
"{self._settings.mqtt.host}"
"{self._settings.mqtt.host}:{self._settings.mqtt.port}"
)
self.wrote_configuration = True
self.config_message = config_message
Expand Down
1 change: 1 addition & 0 deletions ha_mqtt_discoverable/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def create_base_parser(description: str = "Base parser"):
parser.add_argument("--mqtt-user", type=str, help="MQTT user.")
parser.add_argument("--mqtt-password", type=str, help="MQTT password.")
parser.add_argument("--mqtt-server", type=str, help="MQTT server.")
parser.add_argument("--mqtt-port", type=str, help="MQTT port.", default=1883)
parser.add_argument("--settings-file", type=str, help="Settings file.")

parser.add_argument("--use-tls", "--use-ssl", action="store_true", help="Use TLS.")
Expand Down
8 changes: 7 additions & 1 deletion ha_mqtt_discoverable/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

from ha_mqtt_discoverable.utils import read_yaml_file


logger = logging.getLogger(__name__)


Expand All @@ -43,6 +42,7 @@ def load_mqtt_settings(path: str = None, cli=None) -> dict:
settings["mqtt_password"] = cli.mqtt_password
settings["mqtt_prefix"] = cli.mqtt_prefix
settings["mqtt_server"] = cli.mqtt_server
settings["mqtt_port"] = cli.mqtt_port
settings["mqtt_user"] = cli.mqtt_user

# Optional settings - make sure we don't raise an exception if they're unset
Expand Down Expand Up @@ -73,6 +73,8 @@ def load_mqtt_settings(path: str = None, cli=None) -> dict:
raise RuntimeError("No device_name was specified")
if "mqtt_prefix" not in settings:
raise RuntimeError("You need to specify an mqtt prefix")
if "mqtt_port" not in settings:
raise RuntimeError("You need to specify an mqtt port")
if "mqtt_user" not in settings:
raise RuntimeError("No mqtt_user was specified")
if "mqtt_password" not in settings:
Expand Down Expand Up @@ -105,6 +107,8 @@ def sensor_delete_settings(path: str = None, cli=None) -> dict:
settings["mqtt_prefix"] = cli.mqtt_prefix
if cli.mqtt_server:
settings["mqtt_server"] = cli.mqtt_server
if cli.mqtt_port:
settings["mqtt_port"] = cli.mqtt_port
if cli.mqtt_user:
settings["mqtt_user"] = cli.mqtt_user

Expand All @@ -117,6 +121,8 @@ def sensor_delete_settings(path: str = None, cli=None) -> dict:
raise RuntimeError("No device_name was specified")
if "mqtt_prefix" not in settings:
raise RuntimeError("You need to specify an mqtt prefix")
if "mqtt_port" not in settings:
raise RuntimeError("You need to specify an mqtt port")
if "mqtt_user" not in settings:
raise RuntimeError("No mqtt_user was specified")
if "mqtt_password" not in settings:
Expand Down

0 comments on commit f3b1be4

Please sign in to comment.