Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hot tub unresponsive #68

Merged
merged 3 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.DS_Store
# -*- mode: gitignore; -*-
*~
\#*\#
Expand Down
9 changes: 5 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
FROM python:alpine as base
FROM python:3.10-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

RUN pip3 install -r requirements.txt

ADD app/*.py ./
ENTRYPOINT ["python3"]
CMD ["-u","docker_mqtt_app.py"]
ENTRYPOINT ["python3", "docker_mqtt_app.py"]
CMD ["-u"]
103 changes: 46 additions & 57 deletions app/docker_mqtt_app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import os
import sys
import asyncio
import paho.mqtt.client as mqtt
import jacuzziRS485
Expand All @@ -8,74 +9,60 @@
logging.basicConfig(level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s")
log = logging.getLogger("__name__")

# Environment variable checks
if "MQTT_IP" not in os.environ:
log.error(
"MQTT IP not provided, please provide IP address or hostname of your MQTT server."
)
log.error("MQTT IP not provided. Please provide the MQTT server address.")
sys.exit(1)
else:
mqtt_ip = os.environ.get("MQTT_IP")

if "MQTT_USER" not in os.environ:
log.error("MQTT user not provided, please provide username of your MQTT server.")
log.error("MQTT user not provided. Please provide the username for MQTT server.")
sys.exit(1)
else:
mqtt_user = os.environ.get("MQTT_USER")

if "MQTT_PASSWORD" not in os.environ:
log.error(
"MQTT password not provided, please provide password of your MQTT server."
)
log.error("MQTT password not provided. Please provide the MQTT server password.")
sys.exit(1)
else:
mqtt_password = os.environ.get("MQTT_PASSWORD")

if "JACUZZI_IP" not in os.environ:
log.error(
"Jacuzzi IP not provided, please provide IP address or hostname of your Prolink or RS485 Module."
)
log.error("Jacuzzi IP not provided. Please provide the Jacuzzi module address.")
sys.exit(1)
else:
jacuzzi_ip = os.environ.get("JACUZZI_IP")

if "MQTT_PORT" not in os.environ:
mqtt_port = 1883
else:
mqtt_port = int(os.environ.get("MQTT_PORT"))

if "JACUZZI_PORT" not in os.environ:
jacuzzi_port = 4257
else:
jacuzzi_port = int(os.environ.get("JACUZZI_PORT"))
mqtt_port = int(os.environ.get("MQTT_PORT", 1883))
jacuzzi_port = int(os.environ.get("JACUZZI_PORT", 4257))


# MQTT Client setup
def on_connect(mqttc, obj, flags, rc):
"""This is triggered whenever we connect to MQTT"""
"""Triggered when connected to MQTT"""
log.info("Connected to MQTT broker.")
# Subscribe to MQTT
mqtt_client.subscribe("homie/hot_tub/jacuzzi/set_temperature/set")


def on_message(mqttc, obj, msg):
"""This is triggered whenever we receive a message on MQTT"""
async def on_message(mqttc, obj, msg):
"""Triggered upon receiving an MQTT message"""
global spa
log.info(
f"MQTT message received on topic: {msg.topic} with value: {msg.payload.decode()}"
)
log.info(f"Received MQTT message on {msg.topic}: {msg.payload.decode()}")
if msg.topic == "homie/hot_tub/jacuzzi/set_temperature/set":
new_temp = float(msg.payload.decode())
asyncio.run(spa.send_temp_change(new_temp))
await spa.send_temp_change(new_temp) # Awaiting the async function directly
else:
log.debug(f"Unhandled MQTT message on topic {msg.topic}.")
log.debug(f"Unhandled MQTT topic: {msg.topic}")


async def read_spa_data(spa, lastupd):
"""This is triggered whenever spa data has changed"""
await asyncio.sleep(1)
"""Reads and publishes spa data changes to MQTT"""
await asyncio.sleep(3)
if spa.lastupd != lastupd:
lastupd = spa.lastupd
log.info(
f"Jacuzzi temperature is set to {spa.get_settemp()}, actual temperature is {spa.curtemp}"
f"Set temperature: {spa.get_settemp()}, current temperature: {spa.curtemp}"
)

mqtt_client.publish(
Expand All @@ -95,22 +82,14 @@ async def read_spa_data(spa, lastupd):
return lastupd


async def start_mqtt():
global mqtt_client
mqtt_client = mqtt.Client("jacuzzi_rs485")
mqtt_client.username_pw_set(username=mqtt_user, password=mqtt_password)
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.connect(mqtt_ip, mqtt_port)
mqtt_client.loop_start()

# Initial MQTT publishes
def start_mqtt():
"""Sets up MQTT topics and publishes initial state"""
mqtt_client.publish("homie/hot_tub/$homie", payload="3.0", qos=0, retain=False)
mqtt_client.publish("homie/hot_tub/$name", payload="Jacuzzi", qos=0, retain=False)
mqtt_client.publish("homie/hot_tub/$state", payload="ready", qos=0, retain=False)
mqtt_client.publish("homie/hot_tub/$nodes", payload="jacuzzi", qos=0, retain=False)

# Setting up temperature-related MQTT topics
# Set temperature-related topics
mqtt_client.publish(
"homie/hot_tub/jacuzzi/set_temperature/$name",
payload="Set Temperature",
Expand All @@ -133,7 +112,7 @@ async def start_mqtt():
retain=False,
)

# Setting up current temperature-related MQTT topics
# Current temperature-related topics
mqtt_client.publish(
"homie/hot_tub/jacuzzi/temperature/$name",
payload="Temperature",
Expand All @@ -157,23 +136,33 @@ async def start_mqtt():
)


async def start_app():
global spa
# Connect to MQTT
await start_mqtt()
async def main():
global spa # Define spa here or import from jacuzziRS485 if required

# Connect to Jacuzzi
spa = jacuzziRS485.JacuzziRS485(jacuzzi_ip, jacuzzi_port)
# Initialize MQTT client
global mqtt_client
mqtt_client = mqtt.Client("jacuzzi_rs485")
mqtt_client.username_pw_set(username=mqtt_user, password=mqtt_password)
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.connect(mqtt_ip, mqtt_port)

# Start background tasks
asyncio.ensure_future(spa.check_connection_status())
asyncio.ensure_future(spa.listen())
# Start MQTT in a separate thread and set up initial topics
mqtt_client.loop_start()
start_mqtt()

lastupd = 0
# Initialize spa and last update
spa = jacuzziRS485.Spa(jacuzzi_ip, jacuzzi_port) # Adjust as needed
last_update = None

while True:
lastupd = await read_spa_data(spa, lastupd)
try:
# Main loop to periodically read and publish spa data
while True:
last_update = await read_spa_data(spa, last_update)
await asyncio.sleep(5) # Throttle loop delay
finally:
mqtt_client.loop_stop() # Stop MQTT loop cleanly on exit


if __name__ == "__main__":
asyncio.run(start_app())
# Run the main async function
asyncio.run(main())
Loading