bluesound-speakers-api/bluesound.py
2024-07-03 21:12:23 +02:00

72 lines
2.1 KiB
Python
Executable file

import socket
import requests
import sys
def getMyIP():
# ip = socket.gethostbyname(socket.gethostname())
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
ip = s.getsockname()[0]
except:
ip = '127.0.0.1'
finally:
s.close()
ip = [int(part) for part in ip.split(".")]
return ip
def isBluesound(host, timeout=0.3):
try:
return requests.get("http://"+host+":11000/Status", timeout=timeout).status_code == 200
except:
return False
def scanNetwork(printProgress=False):
bluesounds = []
ip = getMyIP()
for i in range(256):
hostIP = ".".join(str(p) for p in ip[:-1]) + "." + str(i)
sys.stdout.write("\tProgress = "+ str(i)+"/255\t\r")
sys.stdout.flush()
if(isBluesound(hostIP)):
bluesounds.append(hostIP)
return bluesounds
def sendRequest(host, reqName, reqParameters = None):
reqUrl = "http://"+host+":11000/"+reqName
if(reqParameters is not None and len(reqParameters) > 0):
reqUrl += "?"
for k, v in reqParameters.items():
reqUrl += k+"="+v+"&"
reqUrl = reqUrl[:-1]
response = requests.get(reqUrl)
return response
def sendRequestToAll(hosts, reqName, reqParameters = None):
responses = {}
for host in hosts:
response = sendRequest(host, reqName, reqParameters)
responses[host] = response
return responses
def sendFuncToAll(hosts, func):
responses = {}
for host in hosts:
responses[host] = func(host)
return responses
def playNyan(host):
nyanUrl="https://www.albinoblacksheep.com/audio/mp3/Nyanyanyanyanyanyanya.mp3"
return sendRequest(host, "Play", {"url":nyanUrl})
print("Scanning the network...")
bluesounds = scanNetwork()
print("Found", len(bluesounds), "bluesound(s):", bluesounds)
print("\nSending request:")
# responses = sendRequestToAll(bluesounds, "Pause")
responses = sendFuncToAll(bluesounds, playNyan)
for host, response in responses.items():
print("\t", host)
print("\t\t"+response.text.replace("\n", "\n\t\t"))