Hello!
I’ll start from the beginning.
I use Raspberry Pi as a bluetooth speaker. Thanks to the guy who made this simple demon.
My goal: to create a media player card in Lovelace UI to control playback on Raspberry Pi.
I upgraded the code from here and create a REST API for it. Now I can remotely control playback from bluetooth by HTTP.
Sample Code
from flask import Flask
import dbus, dbus.mainloop.glib, sys
from gi.repository import GLib
app = Flask(__name__)
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
obj = bus.get_object('org.bluez', "/")
mgr = dbus.Interface(obj, 'org.freedesktop.DBus.ObjectManager')
player_iface = None
transport_prop_iface = None
for path, ifaces in mgr.GetManagedObjects().items():
if 'org.bluez.MediaPlayer1' in ifaces:
player_iface = dbus.Interface(
bus.get_object('org.bluez', path),
'org.bluez.MediaPlayer1')
elif 'org.bluez.MediaTransport1' in ifaces:
transport_prop_iface = dbus.Interface(
bus.get_object('org.bluez', path),
'org.freedesktop.DBus.Properties')
if not player_iface:
sys.exit('Error: Media Player not found.')
if not transport_prop_iface:
sys.exit('Error: DBus.Properties iface not found.')
@app.route('/control/<command>', methods=["GET", "POST"])
def on_playback_control(command):
if command == 'play':
player_iface.Play()
return 'play'
if command == 'pause':
player_iface.Pause()
return 'pause'
if command == 'next':
player_iface.Next()
return 'next'
if command == 'prev':
player_iface.Previous()
return 'previous'
@app.route('/volume/<vol>', methods=["GET", "POST"])
def on_volume_set(vol):
vol = int(vol)
if vol in range(0, 128):
transport_prop_iface.Set(
'org.bluez.MediaTransport1',
'Volume',
dbus.UInt16(vol))
return 'ok'
else:
return 'not ok'
# Run in HTTP
app.run(host='0.0.0.0', port='5000')
For Home Assistant I tried to connect the rest_commands and a universal media player, but this is wrong.
Can someone help connecting this API in Home Assistant?