check current playing disc
This commit is contained in:
parent
375a8261ae
commit
35725aa381
66
lib/mqtt.py
66
lib/mqtt.py
@ -1,17 +1,18 @@
|
|||||||
import paho.mqtt.client as mqtt
|
import paho.mqtt.client as mqtt
|
||||||
|
import paho.mqtt.subscribe as subscribe
|
||||||
import json
|
import json
|
||||||
|
|
||||||
def create_client(broker:str, port:int, username:str, password:str)-> mqtt:
|
def create_client(broker: str, port: int, username: str, password: str) -> mqtt.Client:
|
||||||
"""_summary_
|
"""Create an MQTT client and connect it to the broker
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
broker (str): _description_
|
broker (str): MQTT broker address
|
||||||
port (int): _description_
|
port (int): MQTT broker port
|
||||||
username (str): _description_
|
username (str): Username for MQTT broker
|
||||||
password (str): _description_
|
password (str): Password for MQTT broker
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
mqtt: _description_
|
mqtt.Client: Connected MQTT client instance
|
||||||
"""
|
"""
|
||||||
# Create a new MQTT client instance
|
# Create a new MQTT client instance
|
||||||
client = mqtt.Client()
|
client = mqtt.Client()
|
||||||
@ -24,11 +25,11 @@ def create_client(broker:str, port:int, username:str, password:str)-> mqtt:
|
|||||||
|
|
||||||
return client
|
return client
|
||||||
|
|
||||||
def create_config(client:mqtt)->None:
|
def create_config(client: mqtt.Client) -> None:
|
||||||
"""Create Home Assistant discovery topics
|
"""Create Home Assistant discovery topics
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
client (mqtt): MQTT Client
|
client (mqtt.Client): MQTT Client
|
||||||
"""
|
"""
|
||||||
# Device-specific information for multiple sensors
|
# Device-specific information for multiple sensors
|
||||||
node_id = "floppy_player" # Unique device ID
|
node_id = "floppy_player" # Unique device ID
|
||||||
@ -70,24 +71,59 @@ def create_config(client:mqtt)->None:
|
|||||||
client.publish(discovery_topic_disc, json.dumps(disc_config), retain=True)
|
client.publish(discovery_topic_disc, json.dumps(disc_config), retain=True)
|
||||||
client.publish(discovery_topic_status, json.dumps(status_config), retain=True)
|
client.publish(discovery_topic_status, json.dumps(status_config), retain=True)
|
||||||
|
|
||||||
def update_disc(client:mqtt, disc_message:dict)->None:
|
|
||||||
|
def check_current_disc(client: mqtt.Client) -> str:
|
||||||
|
"""Check the current loaded disc by subscribing to the retained message on the state topic.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
client (mqtt.Client): MQTT Client
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: Current object at current_disc/state
|
||||||
|
"""
|
||||||
|
def on_message(client, userdata, message):
|
||||||
|
"""Callback function to handle received MQTT messages."""
|
||||||
|
userdata['message'] = message.payload.decode()
|
||||||
|
|
||||||
|
# Create a dictionary to store the message
|
||||||
|
userdata = {'message': None}
|
||||||
|
|
||||||
|
# Set the user data and the on_message callback
|
||||||
|
client.user_data_set(userdata)
|
||||||
|
client.on_message = on_message
|
||||||
|
|
||||||
|
# Subscribe to the topic
|
||||||
|
client.subscribe("homeassistant/sensor/floppy_player/current_disc/state")
|
||||||
|
|
||||||
|
# Run the loop manually until we receive a message
|
||||||
|
timeout = 5 # Timeout after 5 seconds
|
||||||
|
while userdata['message'] is None and timeout > 0:
|
||||||
|
client.loop(timeout=0.1) # Process network events for a short time
|
||||||
|
timeout -= 0.1
|
||||||
|
|
||||||
|
# Check if we received the message
|
||||||
|
if userdata['message'] is None:
|
||||||
|
raise TimeoutError("No retained message was found.")
|
||||||
|
|
||||||
|
return userdata['message']
|
||||||
|
|
||||||
|
|
||||||
|
def update_disc(client: mqtt.Client, disc_message: dict) -> None:
|
||||||
"""Update current disc.
|
"""Update current disc.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
client (mqtt): MQTT Client
|
client (mqtt.Client): MQTT Client
|
||||||
disc_message (dict): Current disc information
|
disc_message (dict): Current disc information
|
||||||
"""
|
"""
|
||||||
client.publish("homeassistant/sensor/floppy_player/current_disc/state", json.dumps(disc_message), retain=True)
|
client.publish("homeassistant/sensor/floppy_player/current_disc/state", json.dumps(disc_message), retain=True)
|
||||||
print(f"Published current disc: {disc_message}")
|
print(f"Published current disc: {disc_message}")
|
||||||
|
|
||||||
|
def control_player(client: mqtt.Client, state: str) -> None:
|
||||||
def control_player(client:mqtt, state:str)->None:
|
|
||||||
"""Control the player
|
"""Control the player
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
client (mqtt): MQTT Client
|
client (mqtt.Client): MQTT Client
|
||||||
state (str): Player State
|
state (str): Player State
|
||||||
"""
|
"""
|
||||||
client.publish("homeassistant/sensor/floppy_player/status/state", state, retain=True)
|
client.publish("homeassistant/sensor/floppy_player/status/state", state, retain=True)
|
||||||
print(f"Published status: {state}")
|
print(f"Published status: {state}")
|
||||||
|
|
18
main.py
18
main.py
@ -2,7 +2,7 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
import json
|
import json
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from lib.mqtt import create_client, update_disc, control_player, create_config
|
from lib.mqtt import create_client, update_disc, control_player, create_config, check_current_disc
|
||||||
|
|
||||||
# Load the .env file
|
# Load the .env file
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
@ -27,16 +27,26 @@ if len(sys.argv) > 1:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# Convert the JSON string into a dictionary
|
# Convert the JSON string into a dictionary
|
||||||
disc_data = json.loads(json_str)
|
disc_data = json.loads(json_str.replace("'",'"'))
|
||||||
|
# Check if disc is the same as last inserted
|
||||||
|
if (disc_data == json.loads(check_current_disc(client))):
|
||||||
|
# If disc is the same, PLAY
|
||||||
|
control_player(client, "PLAY")
|
||||||
|
else:
|
||||||
# Pass the parsed data to the update_disc function
|
# Pass the parsed data to the update_disc function
|
||||||
|
control_player(client, "PLAY")
|
||||||
update_disc(client, disc_data)
|
update_disc(client, disc_data)
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
try:
|
try:
|
||||||
if json_str == "EJECT":
|
if json_str == "EJECT":
|
||||||
control_player(client, "EJECT")
|
# PAUSE the current playing item
|
||||||
update_disc(client, {"type": "album", "id": "EJECT"})
|
control_player(client, "PAUSE")
|
||||||
elif json_str == "PLAY":
|
elif json_str == "PLAY":
|
||||||
|
# PLAY the current playing item
|
||||||
control_player(client, "PLAY")
|
control_player(client, "PLAY")
|
||||||
|
elif json_str == "PAUSE":
|
||||||
|
# PAUSE the current playing item
|
||||||
|
control_player(client, "PAUSE")
|
||||||
else:
|
else:
|
||||||
print(f"Can't process {json_str}")
|
print(f"Can't process {json_str}")
|
||||||
except Exception:
|
except Exception:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user