0

This is one of the so many questions asked in the forums. I've a script that runs perfectly if I run it from the linux terminal. However when I let it run from crontab at a reboot it doesn't work. I programmed a simple script that runs from the same directory as my script that doen't run, this script runs perfectly well. The script is executeble an readeble for anyone (chmod 777). I think the problem is somewhere with sql code. I red a lot about it but couldn't find the problem for my script, that why I "re"asked this question. thanks in advance!

ps: this script is far (read far) from perfect, just a running script that needs to be optimized

code for the crontab:

@reboot sudo /usr/bin/python /home/pi/AansturingLedGesturctureerd.py

scriptcode:

#! /usr/bin/env python
import RPi.GPIO as GPIO
import sys
import time
import MySQLdb
import datetime


# RGB LED pinnen configureren.
pinRood = 27
pinGroen = 22
pinBlauw = 17

# GPIO setup.
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# Zet de GPIO pinnen als uitgang.
GPIO.setup(pinRood, GPIO.OUT)
GPIO.setup(pinGroen, GPIO.OUT)
GPIO.setup(pinBlauw, GPIO.OUT)

# Gebruik PWM op de pinnen.
ROOD = GPIO.PWM(pinRood, 1000)
GROEN = GPIO.PWM(pinGroen, 1000)
BLAUW = GPIO.PWM(pinBlauw, 1000)
ROOD.start(0)
GROEN.start(0)
BLAUW.start(0)

#defienieren functies

def dataUitlezenFile():
    global dataAansturingLedGesplitst
    bestandAansturingLed = open("/var/www/html/v1.11_layout_aanpassen_login_form_3/extraBestanden/ledAansturing.txt", "r")
    dataAansturingLed = bestandAansturingLed.read()
    dataAansturingLedGesplitst = dataAansturingLed.split()
    #print(dataAansturingLedGesplitst[3])

def dataWissen():
    dataWissenFile = open("/var/www/html/v1.11_layout_aanpassen_login_form_3/extraBestanden/ledAansturing.txt", "w")
    dataWissenFile.truncate(0)
    dataWissenFile.write("0 0 0 niks")
    dataWissenFile.close()



def dataUitlezenSQL(dataAansturingLedGesplitst):

    global speelTijdActief
    global ingesteldeTijd
    global tijdDatabase
    global tijdVerlopen


    #connecteer met de database
    connection = MySQLdb.connect (host = "localhost",
        user = "******",
        passwd = "****",
        db = "test")

    cursor = connection.cursor()
    sqlQuerry = "SELECT stopTijd FROM gespeeldetijd WHERE naam = '" + "Emile"  +  "' ORDER BY ID DESC LIMIT 1"
    rows_count = cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
    row = cursor.fetchone()

    if (rows_count >= 1):
        tijdDatabase = row[0]
        #print("true")
    else:
        tijdDatabase = datetime.datetime.strptime("1685-06-29 08:15:27", '%Y-%m-%d %H:%M:%S')



    tijdNu = datetime.datetime.now() #haal de huidige tijd op
    #print(tijdNu)

    #print(tijdDatabase)
    #print(tijdNu)

    tijdNu = datetime.datetime.now() #haal de huidige tijd op

    cursor = connection.cursor()   #ophalen tijd om de relais en de hdmi connector aan te zetten of te onderbreken
    sqlQuerry = "SELECT tijd FROM extra WHERE functie = 'uitschakelTijd'"
    cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
    row = cursor.fetchone()
    uitschakeltijd = row[0]
    uitschakeltijdString = str(uitschakeltijd)

    h, m, s = uitschakeltijdString.split(':')
    uitschakeltijdSecondes = int(h) * 3600 + int(m) * 60 + int(s)
    uitschakeltijdSecondesNegate = uitschakeltijdSecondes * -1


    cursor = connection.cursor() #uitschakeltijd ophalen
    sqlQuerry = "SELECT stopTijd FROM gespeeldetijd WHERE naam = 'Emile' ORDER BY ID DESC LIMIT 1"
    cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
    row = cursor.fetchone()
    row_count = cursor.rowcount

    if row_count == 0:
        tijdDatabaseLaatsteTijd = datetime.datetime.strptime("1685-06-29 08:15:27", '%Y-%m-%d %H:%M:%S')
    else:
        tijdDatabaseLaatsteTijd = row[0]




    if (tijdDatabaseLaatsteTijd < tijdNu): # controleer of de eindtijd is bereikt
        #print("eindtijd bereikt")

        tijdDatabaseCorrecteNotatie = datetime.datetime.strptime(str(tijdDatabaseLaatsteTijd), '%Y-%m-%d %H:%M:%S') #vorm de tijd om van de database naar een juistee notatie
        huidigeTijdCorrecteNotatie =  datetime.datetime.now() # correcte notatie van de huidige tijd
        overigeTijdSeconden = ((tijdDatabaseCorrecteNotatie-huidigeTijdCorrecteNotatie).total_seconds()) #berekenen van het overige aantal seconden


        #print(overigeTijdSeconden)
        #print(uitschakeltijdSecondesNegate)


        if (overigeTijdSeconden <= uitschakeltijdSecondesNegate): #controleer of de eindtijd al meer als 5 minuten is verlopen  
            tijdVerlopen = "verlopen"
            #print("veel meer seconden verlopen!")
        else:
            tijdVerlopen = "uitschakeltijd"
            #print(tijdVerlopen)
            #print("zit nog in de fase")

    else:
        tijdVerlopen = "verlopen"
        #print(tijdVerlopen)


    if(tijdVerlopen == "verlopen"):
        if (tijdDatabase > tijdNu): # controleer of er een tijd lopende is
            speelTijdActief = "actief"
            cursor = connection.cursor()
            sqlQuerry = "SELECT tijd FROM gespeeldetijd WHERE naam = '" + "Emile"  +  "' ORDER BY ID DESC LIMIT 1"
            rows_count = cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
            #print(rows_count)
            row = cursor.fetchone()
            genre_id_val = cursor.fetchone()
            if (rows_count >= 1):
                ingesteldeTijd = row[0]
                #print("true")
            else:
                ingesteldeTijd = "00:00:00"
        else:   
            cursor = connection.cursor()
            sqlQuerry = "SELECT stopTijd FROM gespeeldetijd WHERE naam = '" + "Thomas"  +  "' ORDER BY ID DESC LIMIT 1"
            rows_count = cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
            row = cursor.fetchone()
            genre_id_val = cursor.fetchone()
            #print(rows_count)
            if (rows_count >= 1):
                tijdDatabase = row[0]
                #print(" 3")
            else:
                tijdDatabase = datetime.datetime.strptime("1685-06-29 08:15:27", '%Y-%m-%d %H:%M:%S')
                #print(" 4")

            #print(tijdDatabase)

            tijdNu = datetime.datetime.now() #haal de huidige tijd op
            #print(tijdNu)

            #print(tijdDatabase)
            #print(tijdNu)

            cursor = connection.cursor()   #ophalen tijd om de relais en de hdmi connector aan te zetten of te onderbreken
            sqlQuerry = "SELECT tijd FROM extra WHERE functie = 'uitschakelTijd'"
            cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
            row = cursor.fetchone()
            uitschakeltijd = row[0]
            uitschakeltijdString = str(uitschakeltijd)

            h, m, s = uitschakeltijdString.split(':')
            uitschakeltijdSecondes = int(h) * 3600 + int(m) * 60 + int(s)
            uitschakeltijdSecondesNegate = uitschakeltijdSecondes * -1

            cursor = connection.cursor() #uitschakeltijd ophalen
            sqlQuerry = "SELECT stopTijd FROM gespeeldetijd WHERE naam = '" + "Thomas"  +  "' ORDER BY ID DESC LIMIT 1"
            cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
            row = cursor.fetchone()

            if (row == "none"):
                tijdDatabaseLaatsteTijd = row[0]
            else:
                tijdDatabaseLaatsteTijd = datetime.datetime.strptime("1685-06-29 08:15:27", '%Y-%m-%d %H:%M:%S')

            if (tijdDatabaseLaatsteTijd < tijdNu): # controleer of de eindtijd is bereikt
                #print("tijd is verlopen, nu gaat andere tijd in")
                tijdDatabaseCorrecteNotatie = datetime.datetime.strptime(str(tijdDatabaseLaatsteTijd), '%Y-%m-%d %H:%M:%S') #vorm de tijd om van de database naar een juistee notatie
                huidigeTijdCorrecteNotatie =  datetime.datetime.now() # correcte notatie van de huidige tijd
                overigeTijdSeconden = ((tijdDatabaseCorrecteNotatie-huidigeTijdCorrecteNotatie).total_seconds()) #berekenen van het overige aantal seconden
                #print(tijdDatabaseCorrecteNotatie) 
                #print(huidigeTijdCorrecteNotatie)  
                #print(overigeTijdSeconden)     
                if (overigeTijdSeconden >= uitschakeltijdSecondesNegate): #controleer of de eindtijd al meer als 5 minuten is verlopen  
                    tijdVerlopen = "uitschakeltijd"
                    #print(tijdVerlopen)
                else:
                    tijdVerlopen = "verlopen"
                    #print(tijdVerlopen)

            else:
                tijdVerlopen = "verlopen"
                #print(tijdVerlopen)

            tijdNu = datetime.datetime.now() #haal de huidige tijd op
            if (tijdDatabase > tijdNu): # controleer of er een tijd lopende is

                speelTijdActief = "actief"
                cursor = connection.cursor()
                sqlQuerry = "SELECT tijd FROM gespeeldetijd WHERE naam = '" + "Thomas"  +  "' ORDER BY ID DESC LIMIT 1"
                rows_count = cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
                row = cursor.fetchone()
                genre_id_val = cursor.fetchone()
                if (rows_count >= 1):
                    ingesteldeTijd = row[0]

                else:
                    ingesteldeTijd = "00:00:00"
            else:
                ingesteldeTijd = "00:00:00"
                speelTijdActief = "nietActief"

    cursor.close()
    connection.close()




def statusSetup():
    global setupStatus
    #connecteer met de database
    connection = MySQLdb.connect (host = "localhost",
        user = "root",
        passwd = "*****",
        db = "test")
    cursor = connection.cursor()
    sqlQuerry = "SELECT status FROM extra WHERE functie = 'setup'"
    cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
    row = cursor.fetchone()
    dataSetup = row[0]

    if (dataSetup == "notCompleted"): # hier gaan we de variabele zetten die zal bepalen welke led aangat
        statusSetup = 'setUp'
    else:
        overbrugStatus = 'setUpCompleted'

    cursor.close()
    connection.close()

def statusOverbrug():
    global overbrugStatus
    #connecteer met de database
    connection = MySQLdb.connect (host = "localhost",
        user = "root",
        passwd = "****",
        db = "test")
    cursor = connection.cursor()
    sqlQuerry = "SELECT status FROM extra WHERE functie = 'overbrug'"
    cursor.execute (sqlQuerry) #haal de laatst gespeelde tijd op
    row = cursor.fetchone()
    dataSetup = row[0]

    if (dataSetup == "ingeschakeld"): # hier gaan we de variabele zetten die zal bepalen welke led aangat
        overbrugStatus = 'overbrug'
    else:
        overbrugStatus = 'nietOverbrugd'

    cursor.close()
    connection.close()


while True: 
    while True:

        #nakijken welke data we hebben

        #bekijk file die in de data zit
        dataUitlezenFile()
        dataUitlezenSQL(dataAansturingLedGesplitst)
        statusSetup()
        statusOverbrug()



        if (statusSetup == 'setUp' ):
            while True:
              # converteer de waarde 255 tot max 100 voor PWM.
              roodwaarde = 0
              groenwaarde = 0
              blauwwaarde = 100

              ROOD.ChangeDutyCycle(roodwaarde)
              GROEN.ChangeDutyCycle(groenwaarde)
              BLAUW.ChangeDutyCycle(blauwwaarde)
              dataUitlezenFile()
              dataUitlezenSQL(dataAansturingLedGesplitst)
              statusSetup()
              statusOverbrug()
              if (dataAansturingLedGesplitst[3] != 'setUp'):
                break

        if (speelTijdActief == "actief"):
            while True:

                tijdNu = datetime.datetime.now() #haal de huidige tijd op

                h, m, s = ingesteldeTijd.split(':')
                ingesteldeTijdSeconden = int(h) * 3600 + int(m) * 60 + int(s)



                if(tijdNu <= tijdDatabase):
                    overigeTijd = tijdDatabase - tijdNu
                    testTijd = str(overigeTijd)
                    gesplitsteTijd = testTijd.split('.')
                    tijdNodig = gesplitsteTijd[0]

                    h, m, s = tijdNodig.split(':')
                    overigeTijdSeconden = int(h) * 3600 + int(m) * 60 + int(s)
                else:
                    overigeTijdSeconden = 0





                if(ingesteldeTijdSeconden == 0):
                    percentageOver = -1
                else:                   
                    percentageOver = float(overigeTijdSeconden)/float(ingesteldeTijdSeconden)*float(100)

                print(percentageOver)


                if (percentageOver > 50.0):
                    roodwaarde = 0
                    groenwaarde = 100
                    blauwwaarde = 0
                    ROOD.ChangeDutyCycle(roodwaarde)
                    GROEN.ChangeDutyCycle(groenwaarde)
                    BLAUW.ChangeDutyCycle(blauwwaarde)

                if (percentageOver <= 50.0 and percentageOver >= 30.0):
                    roodwaarde = 100
                    groenwaarde = 100
                    blauwwaarde = 0
                    ROOD.ChangeDutyCycle(roodwaarde)
                    GROEN.ChangeDutyCycle(groenwaarde)
                    BLAUW.ChangeDutyCycle(blauwwaarde)

                if (percentageOver < 30.0 and percentageOver > 10.0):
                    roodwaarde = 100
                    groenwaarde = 50
                    blauwwaarde = 0
                    ROOD.ChangeDutyCycle(roodwaarde)
                    GROEN.ChangeDutyCycle(groenwaarde)
                    BLAUW.ChangeDutyCycle(blauwwaarde)



                if (percentageOver <= 10.0 and percentageOver > 0.0):
                    roodwaarde = 100
                    groenwaarde = 0
                    blauwwaarde = 0
                    ROOD.ChangeDutyCycle(roodwaarde)
                    GROEN.ChangeDutyCycle(groenwaarde)
                    BLAUW.ChangeDutyCycle(blauwwaarde)







                dataUitlezenFile()
                dataUitlezenSQL(dataAansturingLedGesplitst)
                statusSetup()
                statusOverbrug()


                if (speelTijdActief == "nietActief" or tijdVerlopen == "uitschakeltijd"):
                    break




        if (overbrugStatus == 'overbrug'):

            i = 0

            while (i <= 255):

                roodwaarde = 255
                groenwaarde = i
                blauwwaarde = 0

                ROOD.ChangeDutyCycle(roodwaarde*100/255)
                GROEN.ChangeDutyCycle(groenwaarde*100/255)
                BLAUW.ChangeDutyCycle(blauwwaarde*100/255)

                i = i + 1   


                dataUitlezenFile()
                dataUitlezenSQL(dataAansturingLedGesplitst)
                statusSetup()
                statusOverbrug()
                if (overbrugStatus != 'overbrug'):
                    break   

            i = 255

            while (i >= 0):

                roodwaarde = i
                groenwaarde = 255
                blauwwaarde = 0

                ROOD.ChangeDutyCycle(roodwaarde*100/255)
                GROEN.ChangeDutyCycle(groenwaarde*100/255)
                BLAUW.ChangeDutyCycle(blauwwaarde*100/255)

                i = i - 1


                dataUitlezenFile()
                dataUitlezenSQL(dataAansturingLedGesplitst)
                statusSetup()
                statusOverbrug()
                if (overbrugStatus != 'overbrug'):
                    break   

            i = 0

            while (i <= 255):

                roodwaarde = 0
                groenwaarde = 255
                blauwwaarde = i

                ROOD.ChangeDutyCycle(roodwaarde*100/255)
                GROEN.ChangeDutyCycle(groenwaarde*100/255)
                BLAUW.ChangeDutyCycle(blauwwaarde*100/255)

                i = i + 1


                dataUitlezenFile()
                dataUitlezenSQL(dataAansturingLedGesplitst)
                statusSetup()
                statusOverbrug()
                if (overbrugStatus != 'overbrug'):
                    break   

            i = 255

            while (i >= 0):

                roodwaarde = 0
                groenwaarde = i
                blauwwaarde = 255

                ROOD.ChangeDutyCycle(roodwaarde*100/255)
                GROEN.ChangeDutyCycle(groenwaarde*100/255)
                BLAUW.ChangeDutyCycle(blauwwaarde*100/255)

                i = i - 1


                dataUitlezenFile()
                dataUitlezenSQL(dataAansturingLedGesplitst)
                statusSetup()
                statusOverbrug()
                if (overbrugStatus != 'overbrug'):
                    break   





        if (dataAansturingLedGesplitst[3] == 'niks' and not statusSetup == 'setUp' and not speelTijdActief == "actief" and not overbrugStatus == 'overbrug'):
            while True:
                #print('uitvoeren')
                i = 212
                j = 33


                while (i >= 33):
                    while (j <= 212):

                        if (i >= 33):
                            groenwaarde = i
                        else:
                            groenwaarde = 33

                        if (j <= 183):
                            roodwaarde = j
                        else:
                            roodwaarde = 183

                        blauwwaarde = 255

                        i = i - 1       
                        j = j + 1

                        ROOD.ChangeDutyCycle(roodwaarde*100/255)
                        GROEN.ChangeDutyCycle(groenwaarde*100/255)
                        BLAUW.ChangeDutyCycle(blauwwaarde*100/255)
                        time.sleep(0.01)
                        dataUitlezenFile()
                        dataUitlezenSQL(dataAansturingLedGesplitst)
                        statusSetup()
                        statusOverbrug()

                        if (not dataAansturingLedGesplitst[3] == 'niks' or statusSetup == 'setUp' or speelTijdActief == "actief"):
                            break

                dataUitlezenFile()
                dataUitlezenSQL(dataAansturingLedGesplitst)
                statusSetup()
                statusOverbrug()
                time.sleep(1)   
                dataUitlezenFile()
                dataUitlezenSQL(dataAansturingLedGesplitst)
                statusSetup()
                statusOverbrug()

                if (not dataAansturingLedGesplitst[3] == 'niks' or statusSetup == 'setUp' or speelTijdActief == "actief" or overbrugStatus == 'overbrug'):
                    break

                if (not dataAansturingLedGesplitst[3] == 'niks' or statusSetup == 'setUp' or speelTijdActief == "actief"):
                    break
Kate
  • 849

1 Answers1

0

I see no exception handling in your code. A properly designed application should have exception handling and log errors to a file. You say your script runs if you remove parts of the code, so that means the cron is executing it, but if an error occurs you have no trace and investigation is difficult. If you had a log, maybe you would already have figured out the problem.

One thing I do sometimes is autostart a script in a GNU screen session, so I can attach to the screen console after startup and see the script in action.

Looking at your code, I see that you have a local Mysql instance. Maybe Mysql is not started yet when your script runs. Could be as simple as that. Many startup scripts wrongly assume that networking or some other service will always be available when they run.

A better way would be to create your own systemd service to run this script. It's not difficult. When you do that, you can establish dependencies, for example you can specify that your service should not be run before the Mysql service etc.

Now I suggest the following steps:

  • always log the output of your cron jobs to a file - your script is probably spitting out an error but you can't see it
  • improve your script by adding exception handling (10 lines of code would suffice)
  • when you have done that, the problem should become obvious, then ponder the rest of my advice
Kate
  • 849