Skip to content

Commit

Permalink
Merge pull request #120 from pergolafabio/feat/mqtt_options
Browse files Browse the repository at this point in the history
External broker settings
  • Loading branch information
pergolafabio authored Jul 25, 2023
2 parents 4896c42 + 89251f7 commit eb1598d
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 16 deletions.
9 changes: 8 additions & 1 deletion hikvision-doorbell/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ options:
system:
log_level: INFO
sdk_log_level: NONE

mqtt: {}

# Schema for the options above
schema:
doorbells:
Expand All @@ -34,6 +35,12 @@ schema:
system:
log_level: match(^ERROR|WARNING|INFO|DEBUG$)
sdk_log_level: match(^NONE|ERROR|INFO|DEBUG$)?
mqtt:
host: "str?"
port: "int?"
ssl: "bool?"
username: "str?"
password: "str?"

# To request MQTT configuration using the supervisor API
services:
Expand Down
16 changes: 6 additions & 10 deletions hikvision-doorbell/docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,14 @@ python src/main.py
```

## VSCode
If using VSCode, there is a run configuration already provided.
First create a `development.env` file with your own values
```bash
cp development.env.example development.env
```

- If using VSCode, there is a run configuration already provided.
First create a `development.env` file with your own values, then run the application using the integrated VSCode debugger.
```bash
cp development.env.example development.env
```
Run the application using the integrated VSCode runner (under `Run and Debug`).

First create a `development.env` file with your own values, then run the application using the integrated VSCode debugger.
```bash
cp development.env.example development.env
```
- Run the application using the integrated VSCode runner (under `Run and Debug`).

## Testing the addon locally (VSCode devcontainer)
For more information see the official HA [guide](https://developers.home-assistant.io/docs/add-ons/testing).
Expand Down
22 changes: 21 additions & 1 deletion hikvision-doorbell/src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def mqtt_config_from_supervisor():
if service_response.status_code == 400:
# MQTT addon is not configured
logger.error("MQTT service not available")
raise RuntimeError("This addon need the mosquitto broker to work correctly. Please see the Documentation tab for details.")
raise RuntimeError("This addon needs the Mosquitto broker to work correctly. Please see the Documentation tab for details.")

if service_response.status_code != 200:
raise RuntimeError(f"Unexpected response while requesting MQTT service: {service_response.text}")
Expand Down Expand Up @@ -110,6 +110,26 @@ def from_string_to_enum(cls, v):
mqtt: Optional[MQTT] = Field(default_factory=mqtt_config_from_supervisor)
system: System

@validator('mqtt', pre=True)
def load_mqtt_config(cls, v):
'''
Load the MQTT configuration from the user-supplied values, if provided, or fallback to asking the HA supervisor for the integrated MQTT add-on
'''
# If we have no value in input, skip validation
if v is None:
return

# If the user supplied some configuration values, ues them
if v:
return v

# Try to load configuration from the HA supervisor, if running as an add-on
logger.debug("Loading MQTT configuration from supervisor")
config = mqtt_config_from_supervisor()
if not config:
raise ValueError("Cannot load MQTT configuration from supervisor")
return config

class Config:
env_nested_delimiter = "__"
# Name of the environment variable defining the path to the configuration file
Expand Down
15 changes: 12 additions & 3 deletions hikvision-doorbell/src/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import signal
import socket
import sys
from config import AppConfig
from doorbell import Doorbell, Registry
Expand All @@ -16,9 +17,13 @@
async def main():
"""Main entrypoint of the application"""

# Disable type warnings since the object is populated at runtime using goodconf library
config = AppConfig() # type:ignore
config.load()
try:
# Disable type warnings since the object is populated at runtime using goodconf library
config = AppConfig() # type:ignore
config.load()
except RuntimeError as e:
logger.error("Configuration error: {}", e)
sys.exit(1)

# Remove the default handler installed by loguru (it redirects to stderr)
logger.remove()
Expand Down Expand Up @@ -95,3 +100,7 @@ def signal_handler(task: asyncio.Task):
user_message, sdk_code, sdk_message = e.args
logger.error("{}: {} Error code:{}", user_message, sdk_message, sdk_code)
sys.exit(1)
except (OSError, ConnectionRefusedError) as e:
# Connection to MQTT broker failed
logger.error("Error while connecting to MQTT broker: {}", e.strerror)
sys.exit(1)
2 changes: 2 additions & 0 deletions hikvision-doorbell/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ def test_load_config_missing_token():
def test_load_config_mqtt():
config = AppConfig() # type: ignore
config.load("tests/assets/test_config_mqtt.json")
assert config.mqtt.host is not None
assert config.mqtt.port is not None
7 changes: 6 additions & 1 deletion hikvision-doorbell/translations/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,9 @@ configuration:
system:
name: "System options"
description: >-
Configure general options for the add-on itself, such as its logs. See the 'Documentation' tab for more details.
Configure general options for the add-on itself, such as its logs. See the 'Documentation' tab for more details.
mqtt:
name: "MQTT broker"
description: >-
Optional settings to configure the connection to an external broker. By default the add-on auto-discovers the Mosquitto add-on, if available.

0 comments on commit eb1598d

Please sign in to comment.