Python Forum

Full Version: Merge two simple scripts
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is so out of my league so i really need some help.
I want to merge theese two scripts.
There is a button function in the first script, wich i dont need in this one.

Is there a way to replace that button function with the one thats in the second script below?
I would truly appreciate any help i can get here, as this is something i know very little about.



import sys
sys.path.append("/home/pi/.local/lib/python2.7/site-packages")

from phue import Bridge
import RPi.GPIO as GPIO
import time
import datetime
import subprocess

# Since this code will run each time the Pi reboots, wait 30 sec for Pi to boot and get connected to the network before attempting to connect to the Philips Hue Bridge
print 'Waiting for network...'
time.sleep(3)
print 'The wait is over. It\'s showtime!'
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Read output from button.
b=Bridge('192.168.1.47')
try:
        b.connect()
except ImportError:
        print "Import error occurred!"
print "Connected to Hue bridge!"

#Check if lights are already on
lightson=b.get_light(5, "on")
if lightson: print "Lights are already on."
print 'Entering infinite loop...'

light_on_delay = 15  # time in min for light to stay on when button pressed
button_pressed = 0

while True:
    # check for button press
    input_state = GPIO.input(21)
    if input_state == False:
        print('Button Pressed')
        end = (light_on_delay * 60) + time.time()
        button_pressed = 1
        command =  {"on" : True, "bri" : 255, "sat" : 0, "hue" : 0}
        b.set_group(5, command)
        lightson=True
        print('Lights are on for 15 minutes')    
   
    # check if button has been pressed if it has check to see if time is up
    if button_pressed == 1:
        if time.time() > end:
            button_pressed = 0
        
    else:
    
        i=GPIO.input(4)
        if i==0:            #When output from motion sensor is LOW
            print ('No movement detected - Turning lights off')
            b.set_group(5, 'on', False) #Replace the number 1 with the light group number defined on Philips Hue. In my case Bedroom is 1.
            subprocess.call("sh monitor_off.sh", shell=True)
            lightson=False
            print ('Lights are off')
            time.sleep(0.1)
        else:               #When output from motion sensor is HIGH
            print ('Movement detected - Turning lights on')
            command =  {"on" : True, "bri" : 255, "sat" : 0, "hue" : 0}
            b.set_group(5, command)
            subprocess.call("sh monitor_on.sh", shell=True)
            lightson=True
            print ('Lights are on.')
            time.sleep(60 * 5)    

    # added delay to prevent program using 100% cpu time.
    time.sleep(0.5)
    GPIO.cleanup()
#!/usr/bin/python
# shutdown/reboot(/power on) Raspberry Pi with pushbutton

import RPi.GPIO as GPIO
from subprocess import call
from datetime import datetime
import time

# pushbutton connected to this GPIO pin, using pin 5 also has the benefit of
# waking / powering up Raspberry Pi when button is pressed
shutdownPin = 5

# if button pressed for at least this long then shut down. if less then reboot.
shutdownMinSeconds = 3

# button debounce time in seconds
debounceSeconds = 0.01

GPIO.setmode(GPIO.BOARD)
GPIO.setup(shutdownPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

buttonPressedTime = None


def buttonStateChanged(pin):
    global buttonPressedTime

    if not (GPIO.input(pin)):
        # button is down
        if buttonPressedTime is None:
            buttonPressedTime = datetime.now()
    else:
        # button is up
        if buttonPressedTime is not None:
            elapsed = (datetime.now() - buttonPressedTime).total_seconds()
            buttonPressedTime = None
            if elapsed >= shutdownMinSeconds:
                # button pressed for more than specified time, shutdown
                call(['shutdown', '-h', 'now'], shell=False)
            elif elapsed >= debounceSeconds:
                # button pressed for a shorter time, reboot
                call(['shutdown', '-r', 'now'], shell=False)


# subscribe to button presses
GPIO.add_event_detect(shutdownPin, GPIO.BOTH, callback=buttonStateChanged)

while True:
    # sleep to reduce unnecessary CPU usage
    time.sleep(5)
I can't test it right now, but you can test it and post here what is going on.

First lets try it without event, to keep your logic...
import sys
from phue import Bridge
import RPi.GPIO as GPIO
import time
import datetime
import subprocess

sys.path.append("/home/pi/.local/lib/python2.7/site-packages")

# pushbutton connected to this GPIO pin, using pin 5 also has the benefit of
# waking / powering up Raspberry Pi when button is pressed
my_button_pin = 21

# if button pressed for at least this long then shut down. if less then reboot.
shutdownMinSeconds = 3

# button debounce time in seconds
debounceSeconds = 0.01

buttonPressedTime = None


def buttonStateChanged(pin):
    global buttonPressedTime

    if not (GPIO.input(pin)):
        # button is down
        if buttonPressedTime is None:
            buttonPressedTime = datetime.datetime.now()
    else:
        # button is up
        if buttonPressedTime is not None:
            elapsed = (ddatetime.atetime.now() - buttonPressedTime).total_seconds()
            buttonPressedTime = None
            if elapsed >= shutdownMinSeconds:
                # button pressed for more than specified time, shutdown
                subprocess.call(['shutdown', '-h', 'now'], shell=False)
            elif elapsed >= debounceSeconds:
                # button pressed for a shorter time, reboot
                subprocess.call(['shutdown', '-r', 'now'], shell=False)


# Since this code will run each time the Pi reboots, wait 30 sec for Pi to boot and get connected to the network before attempting to connect to the Philips Hue Bridge
print 'Waiting for network...'
time.sleep(3)
print 'The wait is over. It\'s showtime!'
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN)  # Read output from PIR motion sensor
GPIO.setup(my_button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # Read output from button.
# GPIO.add_event_detect(my_button_pin, GPIO.BOTH, callback=buttonStateChanged)

b = Bridge('192.168.1.47')
try:
    b.connect()
except ImportError:
    print "Import error occurred!"
print "Connected to Hue bridge!"

# Check if lights are already on
lightson = b.get_light(5, "on")
if lightson:
    print "Lights are already on."
print 'Entering infinite loop...'

light_on_delay = 15  # time in min for light to stay on when button pressed
button_pressed = 0

while True:
    # check for button press
    input_state = GPIO.input(my_button_pin)
    if input_state == False:
        print('Button Pressed')
        buttonStateChanged(my_button_pin)
        end = (light_on_delay * 60) + time.time()
        button_pressed = 1
        command = {"on": True, "bri": 255, "sat": 0, "hue": 0}
        b.set_group(5, command)
        lightson = True
        print('Lights are on for 15 minutes')

    # check if button has been pressed if it has check to see if time is up
    if button_pressed == 1:
        if time.time() > end:
            button_pressed = 0

    else:

        i = GPIO.input(4)
        if i == 0:  # When output from motion sensor is LOW
            print('No movement detected - Turning lights off')
            b.set_group(5, 'on', False)  # Replace the number 1 with the light group number defined on Philips Hue. In my case Bedroom is 1.
            subprocess.call("sh monitor_off.sh", shell=True)
            lightson = False
            print('Lights are off')
            time.sleep(0.1)
        else:  # When output from motion sensor is HIGH
            print('Movement detected - Turning lights on')
            command = {"on": True, "bri": 255, "sat": 0, "hue": 0}
            b.set_group(5, command)
            subprocess.call("sh monitor_on.sh", shell=True)
            lightson = True
            print('Lights are on.')
            time.sleep(60 * 5)

    # added delay to prevent program using 100% cpu time.
    time.sleep(0.5)
    GPIO.cleanup()