Asymic
Posts: 29
Joined: Sun Jun 16, 2019 8:28 am

Daemon - module not found

Sun Aug 18, 2019 6:48 am

I started a post on designing a dash for my home made Pi Tablet, which has evolved quite well. I have now written some code to use as a daemon to monitor button pushes, screen idle etc.

The following code works fine when running in the Python IDLE:-

Code: Select all

#!/usr/bin/python
import RPi.GPIO as GPIO
from time import sleep
import subprocess
import rpi_backlight as bl
import spidev
import os, sys
from random import *
from subprocess import PIPE, run


GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(6, GPIO.IN,pull_up_down=GPIO.PUD_UP)    # button 1
GPIO.setup(13, GPIO.IN,pull_up_down=GPIO.PUD_UP)   # button 2
GPIO.setup(19, GPIO.IN,pull_up_down=GPIO.PUD_UP)   # button 3
GPIO.setup(17, GPIO.IN,pull_up_down=GPIO.PUD_UP)   # PowerBoost LBO, low when <3.2V
GPIO.setup(23, GPIO.OUT)                           # used as dimming ok flag in Dash

Beeped = 0

spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz = 500000
DEBUG = 0

def get_adc(channel):                              # MCP3002
        if ((channel > 1) or (channel < 0)):
                return -1

        r = spi.xfer2([1,(2+channel)<<6,0])
        ret = ((r[1]&31) << 6) + (r[2] >> 2)
        return ret


while True:
    if GPIO.input(17) == 0:                        # PBoost LBO, battery crit low
#            print("lbo is low")
            subprocess.Popen(["shutdown", "now"])
        
    if GPIO.input(6) == 0:                         # button 1 pressed
        sleep(0.6)
        if GPIO.input(6) == 0:
#            print("1                       long Press")
            bl.set_brightness(40)
        else:
#            print("1 short press")
            temp = bl.get_actual_brightness()
            temp +=10
            bl.set_brightness(temp)
        sleep(0.5)
#    else:
#        print("1 Released")
     
    if GPIO.input(13) ==0:                         # button 2
        sleep(0.6)
        if GPIO.input(13) ==0:
#            print("2                       long Press")
            subprocess.Popen(["/usr/bin/amixer", "set", "PCM", "80%"])
        else:
#            print("2 short press")
            subprocess.Popen(["/usr/bin/amixer", "set", "PCM", "90%"])
        sleep(0.5)
#    else:
#        print("2 Released")
    
    if GPIO.input(19) ==0:                         # button 3
        sleep(0.6)
        if GPIO.input(19) ==0:
#            print("3                       long Press")
            subprocess.Popen(['TabDash'])
        else:
#            print("3 short press")
            subprocess.Popen(['matchbox-keyboard'])
        sleep(0.5)
#    else:
#        print("3 Released")
#    print(" ")

    # if idle>setTime & DimOk then dim scn, else bright:-

    DimOk = GPIO.input(23)  # check tick box in Dash
    if DimOk:
#        print("Dim OK!")

        command = ['xprintidle']
        result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        idle = result.stdout

        dim_time = 60 # in seconds

        if int(idle) > (dim_time * 1000) and dimmed == 0:
            oBrite = bl.get_actual_brightness()      # save orig brightness
            bl.set_brightness(30)
#            canvas.create_text(110, 170, anchor="w", font="Arial",text= "Dimmed!")
            dimmed = 1

        elif dimmed == 1 and int(idle) < (dim_time * 1000) :
            bl.set_brightness(oBrite)
#            canvas.create_rectangle(105, 155, 190, 180, outline="#ddd", fill="#ddd")
            dimmed = 0


    # measure batt volts and beep if low:-

    A = get_adc(0)
    V = A * 0.00484                  # scale ADC to volts
    if V < 3.4 and not Beeped:
        Beeped = 1
        os.system('omxplayer /home/pi/Downloads/beep-01a.mp3')
     #  sys.exit()
    #break

However when I make this an exectable and write a service script, then it fails. Initially the error is for importing the rpi-backlight module.

I then commented out all backlight code and tried again. Now it reports it can not find PIPE and run when importing these items.

Can anyone tell me how to get round these problems?

Thank you.

gordon77
Posts: 4292
Joined: Sun Aug 05, 2012 3:12 pm

Re: Daemon - module not found

Sun Aug 18, 2019 9:14 am

Try #!/usr/bin/python3

and run it with python3

Asymic
Posts: 29
Joined: Sun Jun 16, 2019 8:28 am

Re: Daemon - module not found

Tue Aug 20, 2019 4:59 am

Thank you, that has worked. I also had to put a "3" in the service file.

The daemon now starts at boot and my buttons work the brightness and volume fine, however when the screen diming is activated the line starting:--

if int(idle) > (dim_time….

fails with the error "invalid literal for int()"

I did see on some posts people have used int(float(some_var)) to get round some problem, but as I did a trial run on this part of the program I can see that 'idle' does appear to be an integer. (or string of an integer) then I can not see this being a cure. I therefore suspect that the string is coming back empty.

Any further ideas?

gordon77
Posts: 4292
Joined: Sun Aug 05, 2012 3:12 pm

Re: Daemon - module not found

Tue Aug 20, 2019 7:30 am

One possible issue is it's not getting a valid result from xprintidle but l am not sure why that would be the case.

Maybe put a short delay to await for the response.

command = ['xprintidle']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
time.sleep(.1)
idle = result.stdout

Asymic
Posts: 29
Joined: Sun Jun 16, 2019 8:28 am

Re: Daemon - module not found

Wed Aug 21, 2019 6:29 am

I tried the time delay, with no change, still the same error. I will write a few lines to export the result of idle to a file and see what is appearing.

More later...

gordon77
Posts: 4292
Joined: Sun Aug 05, 2012 3:12 pm

Re: Daemon - module not found

Wed Aug 21, 2019 7:16 am

You could try..

Code: Select all

command = 'xprintidle > /run/shm/idle.txt'
os.system(command)
with open("/run/shm/idle.txt", "r") as file:
       idle = int(file.readline())
Could you provide details how you are running your codes.

Asymic
Posts: 29
Joined: Sun Jun 16, 2019 8:28 am

Re: Daemon - module not found

Wed Aug 21, 2019 5:16 pm

I will try this.

here is my service code:-

Code: Select all

[Unit]
Description=Tablet Daemon
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/pi/TabDmon.py
Restart=on-abort

[Install]
WantedBy=multi-user.target


and here is the latest Daemon:-

Code: Select all

#!/usr/bin/python3
import RPi.GPIO as GPIO
from time import sleep
import subprocess
import rpi_backlight as bl
import spidev
import os, sys
from random import *
from subprocess import PIPE, run


GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(6, GPIO.IN,pull_up_down=GPIO.PUD_UP)    # button 1
GPIO.setup(13, GPIO.IN,pull_up_down=GPIO.PUD_UP)   # button 2
GPIO.setup(19, GPIO.IN,pull_up_down=GPIO.PUD_UP)   # button 3
GPIO.setup(17, GPIO.IN,pull_up_down=GPIO.PUD_UP)   # PowerBoost LBO, low when <3.2V
GPIO.setup(23, GPIO.OUT)                           # used as dimming ok flag in Dash

Beeped = 0

spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz = 500000
DEBUG = 0

def get_adc(channel):                              # MCP3002
        if ((channel > 1) or (channel < 0)):
                return -1

        r = spi.xfer2([1,(2+channel)<<6,0])
        ret = ((r[1]&31) << 6) + (r[2] >> 2)
        return ret


while True:
    if GPIO.input(17) == 0:                        # PBoost LBO, battery crit low
#            print("lbo is low")
            subprocess.Popen(["shutdown", "now"])
        
    if GPIO.input(6) == 0:                         # button 1 pressed
        sleep(0.6)
        if GPIO.input(6) == 0:
            print("1                       long Press")
#            bl.set_brightness(40)
            subprocess.call(["rpi-backlight", "-b", "40"])
        else:
#            print("1 short press")
            temp = bl.get_actual_brightness()
            temp +=10
            bl.set_brightness(temp)
#            subprocess.call(["rpi-backlight", "-b", "140"])
        sleep(0.5)
#    else:
#        print("1 Released")
     
    if GPIO.input(13) ==0:                         # button 2
        sleep(0.6)
        if GPIO.input(13) ==0:
#            print("2                       long Press")
            subprocess.Popen(["/usr/bin/amixer", "set", "PCM", "80%"])
        else:
#            print("2 short press")
            subprocess.Popen(["/usr/bin/amixer", "set", "PCM", "90%"])
        sleep(0.5)
#    else:
#        print("2 Released")
    
    if GPIO.input(19) ==0:                         # button 3
        sleep(0.6)
        if GPIO.input(19) ==0:
#            print("3                       long Press")
#            subprocess.Popen(['TabDash'])
            path = "sudo /usr/bin/python3 /home/pi/TabDash.py"
            os.system (path)

        else:
#            print("3 short press")
            subprocess.Popen(['matchbox-keyboard'])
        sleep(0.5)
#    else:
#        print("3 Released")
#    print(" ")

    # if idle>setTime & DimOk then dim scn, else bright:-

    DimOk = GPIO.input(23)  # check tick box in Dash
    if DimOk:
#        print("Dim OK!")

        command = ['xprintidle']
        result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        sleep(1)
        idle = result.stdout

        dim_time = 60 # in seconds

        if int(idle) > (dim_time * 1000) and dimmed == 0:
            oBrite = bl.get_actual_brightness()      # save orig brightness
            bl.set_brightness(30)
#            canvas.create_text(110, 170, anchor="w", font="Arial",text= "Dimmed!")
            dimmed = 1

        elif dimmed == 1 and int(idle) < (dim_time * 1000) :
            bl.set_brightness(oBrite)
#            canvas.create_rectangle(105, 155, 190, 180, outline="#ddd", fill="#ddd")
            dimmed = 0


    # measure batt volts and beep if low:-

    A = get_adc(0)
    V = A * 0.00484                  # scale ADC to volts
    if V < 3.4 and not Beeped:
        Beeped = 1
        os.system('omxplayer /home/pi/Downloads/beep-01a.mp3')
     #  sys.exit()
    #break
    sleep(0.1)
    
I will post the results from you previous suggestion in the next few days.

Asymic
Posts: 29
Joined: Sun Jun 16, 2019 8:28 am

Re: Daemon - module not found

Sat Aug 24, 2019 6:11 am

Hi Gordon,

I have tried your suggestion, a few posts back, of writing the idle result to a file, and find that the file is empty, and looking at the status of the daemon service, the error is still the same.

As a further point I find that trying to load the dashboard, or bring up the matchbox-keyboard (button 3) do not work when this is run as a daemon (using python3), despite working fine in python IDLE. I have tried both Popen, call, and the path methods.

I begin to think that the daemon has a restricted set of abilities - but then this is the first daemon I have ever written - so I haven't a clue really!

Grant

gordon77
Posts: 4292
Joined: Sun Aug 05, 2012 3:12 pm

Re: Daemon - module not found

Sat Aug 24, 2019 7:24 am

I've never used daemon. It looks like there are quite a few 'rules' to it.

https://stackoverflow.com/questions/473 ... -in-python

Do you need a daemon?

Asymic
Posts: 29
Joined: Sun Jun 16, 2019 8:28 am

Re: Daemon - module not found

Sun Aug 25, 2019 2:10 pm

Hi Gordon,

I think you have just made me realize I do not need a daemon, I can do it all in the "Dash" code.

I guess I went down this route because I had to start some where, not knowing what I was doing!

I have glued all the pieces together, but returned to the "Dash" thread with a slight snag...

Thank you,
Grant

Return to “Python”