-1

I'm a trying to start a program at boot but without success. The program starts well but doesn't stay alive (it is supposed to be a infinite script). But when I start the program normally I don't have any problem! I don't get why when I run at reboot it doesn't work.

I use a cron tab like this:

@reboot sudo python /bin/gestion.py &

I can show you my code:

import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
import time
import socket
import threading
import sys

from os.path import expanduser
import datetime

print("DEBUT")

vitesse = 4
etat_moteur_droit = 0
etat_moteur_gauche = 0
data_thr = "Starting"
etat_thr = 1
HOST = '192.168.1.50'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

file = open('/home/log.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()

print("MID")

def main():
    global data_thr
    global etat_thr
    global etat_moteur_droit
    global etat_moteur_gauche
    global vitesse
    
    print("START")
    etat_moteur_droit=0
    setup_io()
    # gestion_bonus(0)
    # gestion_moteur_droit(4,0)
    # gestion_moteur_gauche(4,0)
    # avancer()
    # time.sleep(3)
    # tourner_a_gauche()
    # time.sleep(3)
    # tourner_a_droite()
    # time.sleep(3)
    # arreter()
    x = threading.Thread(target=thread_serveur)
    x.start()
    while True:
        try:
            data_thr = data_thr.partition('\n')[0]
            if(data_thr == ""):
                etat_thr = 0
            if(data_thr == "Fin thread"):
                x = threading.Thread(target=thread_serveur)
                x.start()
                data_thr = "Fin thread step 2"
            if(data_thr == "avance"):
                avancer()
            if(data_thr == "stop"):
                arreter()
            if(data_thr == "gauche"):
                tourner_a_gauche()
            if(data_thr == "droite"):
                tourner_a_droite()
            if(data_thr[:7] == "vitesse"):
                vitesse  = int(data_thr[8:10])
                if(etat_moteur_droit == 1):
                    PWM.set_duty_cycle("P9_14", vitesse)
                if(etat_moteur_gauche == 1):
                    PWM.set_duty_cycle("P8_19", vitesse)
        except:
            print("Erreur lors de reception message")
    print("FIN")
    file = open('/home/log.txt', 'w')
    file.write("FIN!\n" + str(datetime.datetime.now()))
    file.close()
    

def thread_serveur():
    global data_thr
    global etat_thr
    connected = 0
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
    while connected == 0:
        try :
            s.bind((HOST, PORT))
        except socket.error:
            pass
        finally:
            connected = 1
    s.listen(1)
    conn, addr = s.accept()
    print('Connected by', addr)
    timing = 0
    start = time.time()
    while etat_thr == 1:
        try:
            data_thr = conn.recv(1024)
            if not data_thr:
                break
            if data_thr != "":
                print(data_thr)
            conn.sendall("Bien recu")
        except:
            print("Erreur lecture thread")
    s.shutdown(socket.SHUT_RDWR)
    s.close()
    data_thr = "Fin thread"
    
def setup_io():
    GPIO.setup("P9_17", GPIO.OUT)
    GPIO.setup("P9_24", GPIO.OUT)
    GPIO.setup("P9_23", GPIO.OUT)
    PWM.start("P9_14", 0)
    PWM.stop("P9_14")
    PWM.start("P8_19", 0)
    PWM.stop("P8_19")
    PWM.cleanup()

def gestion_bonus(etat):
    if(etat == 1):
        GPIO.output("P9_17", GPIO.HIGH)
    else:
        GPIO.output("P9_17", GPIO.LOW)
    GPIO.cleanup()
    
def gestion_moteur_droit(vitesse,enable):
    global etat_moteur_droit
    
    if(enable == 1 and etat_moteur_droit == 0):
        PWM.start("P9_14", vitesse)
        GPIO.output("P9_24",GPIO.HIGH)
        etat_moteur_droit = 1
    elif(enable == 1 and etat_moteur_droit == 1):
        PWM.set_duty_cycle("P9_14", vitesse)
        GPIO.output("P9_24",GPIO.HIGH)
    elif(enable == 0):
        PWM.stop("P9_14")
        GPIO.output("P9_24",GPIO.LOW)
        etat_moteur_droit =0
    GPIO.cleanup()

def gestion_moteur_gauche(vitesse,enable):
    global etat_moteur_gauche
    
    if(enable == 1 and etat_moteur_gauche == 0):
        PWM.start("P8_19", vitesse)
        GPIO.output("P9_23",GPIO.HIGH)
        etat_moteur_gauche = 1
    elif(enable == 1 and etat_moteur_gauche == 1):
        PWM.set_duty_cycle("P8_19", vitesse)
        GPIO.output("P9_23",GPIO.HIGH)
    elif(enable == 0):
        PWM.stop("P8_19")
        GPIO.output("P9_23",GPIO.LOW)
        etat_moteur_gauche =0
    GPIO.cleanup()

def avancer():
    global vitesse
    gestion_moteur_droit(vitesse,1)
    gestion_moteur_gauche(vitesse,1)

def tourner_a_gauche():
    global vitesse
    gestion_moteur_droit(vitesse,1)
    gestion_moteur_gauche(vitesse,0)
    
def tourner_a_droite():
    global vitesse
    gestion_moteur_droit(vitesse,0)
    gestion_moteur_gauche(vitesse,1)

def arreter():
    global vitesse
    gestion_moteur_droit(vitesse,0)
    gestion_moteur_gauche(vitesse,0)
if __name__ == "__main__":
    main()

Can you help me please?

braX
  • 11,506
  • 5
  • 20
  • 33
hicode
  • 38
  • 5
  • Tangentially, 192.168.1.50 definitely isn't the standard loopback address. – tripleee May 26 '21 at 18:06
  • 3
    Without any debugging details, it's hard to even speculate. Running `sudo` from `cron` is probably not a good idea; either run this from the `crontab` of `root` (in which case no `sudo` is useful or necessary, or run it as yourself without `sudo` if the script can run unprivileged. There should be no need to run the process in the background either way; `cron` jobs already run without a terminal or other interactive facilities. – tripleee May 26 '21 at 18:10
  • Probably see also the guidance for providing a [mre]. Most of the code you posted is probably completely unrelated to the problem, and only obscures it. People are less likely to be able to help if reproducing your problem requires us to have exactly your equipment. – tripleee May 26 '21 at 18:12
  • Also tangentially, probably don't put your local stuff directly in `/bin`. The distro expects to be able to wipe this directory at any time - it probably won't, but many administrative tasks are easier if you follow useful conventions. Your local executables should be in `/usr/local/bin` (or `/opt` if you prefer) which exists specifically for this purpose. – tripleee May 26 '21 at 18:16
  • For troubleshooting, see also https://stackoverflow.com/questions/22743548/cronjob-not-running – tripleee May 26 '21 at 18:17
  • thank you for your feedback and edit on my post, i take note from your advices :) – hicode May 27 '21 at 12:27

1 Answers1

0

As I can see you are using some network service. Maybe when the cron run at @reboot, the network is not ready yet. It may worth a try to implement as service and run command on that way.

Example implementation

Create a file where the system daemon services can be found, e.g.: /lib/systemd/system/TestStartup.service. Example for content of member:

[Unit]
Description=Test service for startup
After=network.target

[Service]
User=root
ExecStart=/usr/bin/python /bin/gestion.py
Restart=on-failure
RestartSec=30

[Install]
WantedBy=multi-user.target

/usr/bin/pythn can be different as which version you are using and where it is installed on your machine, but you can check by whereis python command output:

ati@atihome:/lib/systemd/system$ whereis python
python: /usr/bin/python2.7 /usr/bin/python /usr/bin/python3.7 /usr/bin/python3.7m /usr/lib/python2.7 /usr/lib/python3.7 /etc/python2.7 /etc/python /etc/python3.7 /usr/local/lib/python2.7 /usr/local/lib/python3.7 /usr/share/python /usr/share/man/man1/python.1.gz

Then you need to reload system daemon and enable this service to allow to run after system startup. This service will start after Network is up. You can do by these commands:

systemctl daemon-reload
systemctl enable TestStartup (or how you named your member)

You can test, that start command is proper by this command:

systemctl start TestStartup

And check its status by this command:

systemctl status TestStartup

Then you can reboot the computer and check that it worked. I don't say that is is your solution for 100% but it may worth a try.

  • Hello, thanks for helping me ! You was right, its due tu network boot. I have tried your solution but without succes, to make it right i need to make a little edit on my code : changer the ip adresse to localhost "0.0.0.0" and its work ! I was having an issue on the bind part "cannot assign requested adress" . Thanks again :) – hicode May 27 '21 at 07:43