Hi there!
This is my first post here and I hope I can help someone with this thread.
So I have a python script that makes my audio system turn off after some time. Here it is:
from threading import Thread, Event
from subprocess import call
import datetime
import time
import sys
import RPi.GPIO as GPIO
import spotify
stdout_ = sys.stdout
sys.stdout = open("/home/pi/scripts/auto_off.log", 'a', buffering=0)
print("=================== RESTART ===================")
print("Restart time : " + datetime.datetime.now().strftime("%d %b %Y - %X"))
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT) #This is the pin to which the relay is connected
GPIO.output(7, True)
print("GPIO set up")
timer_minutes = 150 # 5 minutes = 300 seconds / 2 this program checks the status every 2 seconds
open("/home/pi/scripts/minutes.txt", 'w+').write("0\n") # And writes the elapsed time since the last playing status to a file
try:
spotify_client = spotify.SpopClient("localhost", 6602)
except:
print("Error while linking to Spotify")
sys.exit(1)
print("Linked to Spotify")
previous_status = 1
def check():
global previous_status
date = datetime.datetime.now()
minutes = int(open("/home/pi/scripts/minutes.txt").readlines()[0].strip())
spotify_status = spotify_client.status()
if spotify_status[u'status'] in ('stopped', 'paused'):
if minutes < timer_minutes:
open("/home/pi/scripts/minutes.txt", 'w+').write(str(minutes+1))
else:
if previous_status == 1:
GPIO.output(7, False) #Spegni
print("[" + date.strftime("%d %b %Y - %X") + "] ~ Stereo shut down")
previous_status = 0
#else:
# if date.minute >= 0 and date.hour >= 23:
# call("halt", shell=False)
else:
if previous_status == 0:
GPIO.output(7, True) #Turn on
print("[" + date.strftime("%d %b %Y - %X") + "] ~ Stereo turned on")
previous_status = 1
if spotify_status[u'status'] == 'playing': #Restarts the song
spotify_client.toggle()
time.sleep(2)
spotify_client.uplay(str(spotify_status[u'uri']))
open("/home/pi/scripts/minutes.txt", 'w+').write("0\n")
class checkThread(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
while not self.stopped.wait(2.0):
check()
stopEvent = Event()
thread = checkThread(stopEvent)
thread.start()
print("Thread started")
This code works flawlessly if I launch it from SSH. When I add the following line in /etc/rc.local “python /home/pi/scripts/auto_off.py &” the program does not start up properly.
I found that my log file normally showed the “==RESTART==” line but there was also an error while trying to connect to spotify (triggered by the try structure). My idea is that while rc.local launches the script, spop isn’t ready to accept requests yet or its service is not running yet.
How can I solve this problem? Is it possible to run the script only after spop is launched?