Attention, this is no master piece of python programming, but it worked perfectly for my needs.
I also left out some parts, that are not necessary for debugging.
#!/usr/bin/python3
## Imports
import os, sys, time
import json, requests
## wakeonlan
import struct, socket
## PID handling
import psutil
## Logging konfigurieren
import logging
logger = **defined**
headers = {
"Authorization": "Bearer xxx",
"content-type": "application/json",
}
## Funktionen definieren
# pingcheck
def check_ping(host):
ping = os.system("ping -c 1 " + host + " > /dev/null")
return(ping)
# Funktionen fuer die unterschiedlichen Geraete
def get(endpoint, entity):
url = "http://localhost:8123/api/" + endpoint + "/" + entity
response = requests.get(url, headers=headers, timeout=5)
obj = json.loads(response.text)
try:
return(str(obj['state']))
except KeyError:
return("Da stimmt etwas nicht. Existiert die entity?")
def post(endpoint, service, entity_type, entity):
url = "http://localhost:8123/api/" + endpoint + "/" + service + "/" + entity_type
data = '{"entity_id": "' + entity + '"}'
requests.post(url, headers=headers, data=data, timeout=5)
def getPowerStatus():
url = 'http://ip-of-receiver:10000/sony/system'
data = '{"method":"getPowerStatus","id":55,"params":[],"version":"1.1"}'
try:
response = requests.post(url, headers=headers, data=data, timeout=5)
obj = json.loads(response.text)
status = obj['result'][0]['status']
except KeyError:
status = 'false'
logger.error("KeyError in getPowerStatus")
except OSError:
status = 'false'
logger.error("OSError in getPowerStatus")
return status
def setPowerStatus(status):
url = 'http://ip-of-receiver:10000/sony/system'
data = '{"method":"setPowerStatus","id":55,"params":[{"status":"' + status + '"}],"version":"1.1"}'
try:
requests.post(url, headers=headers, data=data, timeout=5)
except KeyError:
status = 'false'
logger.error("KeyError in setPowerStatus")
except OSError:
status = 'false'
logger.error("OSError in setPowerStatus")
def setPlayContent(command):
try:
url = 'http://ip-of-receiver:10000/sony/avContent'
data = '{"method":"setPlayContent","id":47,"params":[{"uri":"' + command + '"}],"version":"1.2"}'
requests.post(url, headers=headers, data=data, timeout=5)
except Error as e:
logger.error(e)
def setVolume(value):
url = 'http://ip-of-receiver:10000/sony/audio'
data = '{"method":"setAudioVolume","id":98,"params":[{"volume":"' + value + '","output":""}],"version":"1.1"}'
requests.post(url, headers=headers, data=data, timeout=5)
# radio
def radio():
logger.debug("Anfang def radio")
radioready = False
standbycounter = 0
# check Sony TV status
if get('states', 'media_player.sony_bravia_tv') == 'on':
logger.debug("def radio - media_player fĂĽr TV ausgeschaltet")
post('services', 'media_player', 'turn_off', 'media_player.sony_bravia_tv')
time.sleep(1)
# check Steckdosenstatus vom Sony Receiver
if get('states', 'switch.wohnzimmer_onkyo') == 'off':
post('services', 'switch', 'turn_on', 'switch.wohnzimmer_onkyo')
logger.debug("def radio - hass Schalter fĂĽr Receiver ein geschaltet")
time.sleep(1)
## wenn der Strom an ist, prĂĽfe auf IP
while check_ping('ip-of-receiver') > 0:
logger.debug("def radio - in der ping Schleife, warten bis IP erreichbar")
time.sleep(2)
if check_ping(ip-of-receiver') == 0:
logger.debug("def radio - checkping positiv")
else:
logger.debug("def radio - checkping negativ")
logger.debug("def radio - vor der radioready Schleife")
while radioready == False:
if getPowerStatus() == 'standby' and standbycounter <= 10:
standbycounter = standbycounter + 1
time.sleep(2)
elif getPowerStatus() == 'standby' and standbycounter >= 10:
setPowerStatus('active')
radioready = True
elif getPowerStatus() == 'active':
radioready = True
# wechsle zu Radio
if radioready == True:
setPlayContent('radio:fm')
time.sleep(1)
setVolume('13')
else:
logger.debug("def radio - irgendetwas ist am Ende schief gelaufen")
# check Steckdosenstatus vom Sony TV
if get('states', 'switch.wohnzimmer_tv') == 'on':
post('services', 'switch', 'turn_off', 'switch.wohnzimmer_tv')
logger.debug("def radio - hass Schalter fĂĽr TV aus geschaltet")
time.sleep(2)
logger.debug("Ende def radio")
# prüfe ob das Skript bereits läuft, anhand der PID
## PID Variablen
pidfile = "/tmp/wzmultimedia.pid"
if os.path.isfile(pidfile):
logger.warn("%s existiert bereits..." % pidfile)
file = open(pidfile, 'r')
pid = file.read()
file.close()
if psutil.pid_exists(pid):
logger.warn("ein Prozess mit der pid: %d läuft ebenfalls, breche ab.")
sys.exit()
else:
print("Ein Prozess mit der pid %d existiert nicht, lösche %s.")
os.remove(pidfile)
pid = str(os.getpid())
open(pidfile, 'w').write(pid)
## Start der AusfĂĽhrung
try:
if len(sys.argv) <= 1:
logger.error("Da wurde kein Parameter ĂĽbergeben.")
sys.exit()
elif sys.argv[1] == 'radio':
radio()
elif sys.argv[1] == 'tv':
tv()
elif sys.argv[1] == 'aus':
aus()
else:
logger.error("Irgendwie konnte kein Parameter zugeordnet werden.")
logger.error(sys.argv)
except Exception as e:
logger.error(e)
os.unlink(pidfile)
logger.info("## Skript ist mit Exception ausgestiegen.")
finally:
os.unlink(pidfile)
logger.info("## Skript ist zuende ##")