refactor: pass default quos and retain

pull/106/head
Jeff Culverhouse 3 months ago
parent 9b064b2ec8
commit 8a9602af3b

1
.gitignore vendored

@ -27,6 +27,7 @@ npm-debug.log
NOTES
coverage/
dist/
tools/
# Apple
.DS_Store

@ -44,8 +44,9 @@ class Base:
self.service = self.mqtt_config["prefix"]
self.service_name = f"{self.service} service"
self.qos = self.mqtt_config["qos"]
self.mqtt_helper = MqttHelper(self.service)
self.mqtt_helper = MqttHelper(self.service, default_qos=self.qos, default_retain=True)
self.running = False
self.discovery_complete = False
@ -59,8 +60,6 @@ class Base:
self.mqtt_connect_time: datetime
self.client_id = self.mqtt_helper.client_id()
self.qos = self.mqtt_config["qos"]
self.storage_update_interval = self.amcrest_config.get("storage_update_interval", 900)
self.snapshot_update_interval = self.config["amcrest"].get("snapshot_update_interval", 300)

@ -27,6 +27,8 @@ class MqttError(ValueError):
class MqttMixin:
async def mqttc_create(self: Amcrest2Mqtt) -> None:
# lets use a new client_id for each connection attempt
self.client_id = self.mqtt_helper.client_id()
self.mqttc = mqtt.Client(
client_id=self.client_id,
callback_api_version=CallbackAPIVersion.VERSION2,
@ -60,7 +62,7 @@ class MqttMixin:
try:
host = self.mqtt_config["host"]
port = self.mqtt_config["port"]
self.logger.info(f"connecting to MQTT broker at {host}:{port} as {self.client_id}")
self.logger.info(f"connecting to MQTT broker at {host}:{port} as client_id: {self.client_id}")
props = Properties(PacketTypes.CONNECT)
props.SessionExpiryInterval = 0
@ -120,8 +122,6 @@ class MqttMixin:
self.logger.info("closed Mqtt connection")
if self.running and (self.mqtt_connect_time is None or datetime.now() > self.mqtt_connect_time + timedelta(seconds=10)):
# lets use a new client_id for a reconnect attempt
self.client_id = self.mqtt_helper.client_id()
await self.mqttc_create()
else:
self.logger.info("Mqtt disconnect — stopping service loop")

@ -118,13 +118,13 @@ class PublishMixin:
topic = self.mqtt_helper.disc_t("device", device_id)
payload = {k: v for k, v in device.items() if k != "platform"}
await asyncio.to_thread(self.mqtt_helper.safe_publish, topic, json.dumps(payload), retain=True)
await asyncio.to_thread(self.mqtt_helper.safe_publish, topic, json.dumps(payload))
self.upsert_state(device_id, internal={"discovered": True})
self.logger.debug(f"discovery published for {self.service} ({self.mqtt_helper.service_slug})")
async def publish_service_availability(self: Amcrest2Mqtt, status: str = "online") -> None:
await asyncio.to_thread(self.mqtt_helper.safe_publish, self.mqtt_helper.avty_t("service"), status, qos=self.qos, retain=True)
await asyncio.to_thread(self.mqtt_helper.safe_publish, self.mqtt_helper.avty_t("service"), status)
async def publish_service_state(self: Amcrest2Mqtt) -> None:
# we keep last_call_date in localtime so it rolls-over the api call counter
@ -148,8 +148,6 @@ class PublishMixin:
self.mqtt_helper.safe_publish,
self.mqtt_helper.stat_t("service", "service", key),
json.dumps(value) if isinstance(value, dict) else value,
qos=self.mqtt_config["qos"],
retain=True,
)
# Devices -------------------------------------------------------------------------------------
@ -160,14 +158,14 @@ class PublishMixin:
topic = self.mqtt_helper.disc_t("device", device_id)
component = self.get_component(device_id)
await asyncio.to_thread(self.mqtt_helper.safe_publish, topic, json.dumps(component), retain=True)
await asyncio.to_thread(self.mqtt_helper.safe_publish, topic, json.dumps(component))
self.upsert_state(device_id, internal={"discovered": True})
async def publish_device_availability(self: Amcrest2Mqtt, device_id: str, online: bool = True) -> None:
payload = "online" if online else "offline"
avty_t = self.get_device_availability_topic(device_id)
await asyncio.to_thread(self.mqtt_helper.safe_publish, avty_t, payload, retain=True)
await asyncio.to_thread(self.mqtt_helper.safe_publish, avty_t, payload)
async def publish_device_state(self: Amcrest2Mqtt, device_id: str, subject: str = "", sub: str = "") -> None:
if not self.is_discovered(device_id):
@ -184,7 +182,7 @@ class PublishMixin:
topic = self.mqtt_helper.stat_t(device_id, state, k)
if isinstance(v, list):
v = json.dumps(v)
await asyncio.to_thread(self.mqtt_helper.safe_publish, topic, v, retain=True)
await asyncio.to_thread(self.mqtt_helper.safe_publish, topic, v)
else:
topic = self.mqtt_helper.stat_t(device_id, state)
await asyncio.to_thread(self.mqtt_helper.safe_publish, topic, value, retain=True)
await asyncio.to_thread(self.mqtt_helper.safe_publish, topic, value)

@ -1,3 +0,0 @@
#!/bin/sh
((gtimeout 1 mosquitto_sub -h mosquitto -t '#' -v) | grep -E '^(amcrest2mqtt/|homeassistant/[^/]+/amcrest2mqtt_)' | awk '{print $1}' | xargs -I TOPIC mosquitto_pub -h mosquitto -t TOPIC -r -n) 2>/dev/null

@ -410,7 +410,7 @@ sdist = { url = "https://files.pythonhosted.org/packages/93/4b/979db9e44be09f71e
[[package]]
name = "mqtt-helper-graystorm"
version = "0.1.0"
source = { git = "https://github.com/weirdtangent/mqtt-helper.git?branch=main#68bc9405c3432c0e5a4f46b39436dcad3193f833" }
source = { git = "https://github.com/weirdtangent/mqtt-helper.git?branch=main#c4034f68f2492173ec0ff13d94eeab47d2bc7c09" }
dependencies = [
{ name = "logging" },
{ name = "paho-mqtt" },

Loading…
Cancel
Save