Logo MichaelPlaza

raspberry pi infrarood ontvanger

Welkom terug Raspberry Pi engineer!

 

Het volgende script draaien we als service. Hierin zit ook de code verwerkt die de button afhandelt, een LED aanstuurt om aan te geven of de wifi in client of access point mode staat en commando's uit de web interface uitleest.

 

import os, sys, time, StringIO, contextlib, RPi.GPIO as GPIO, subprocess

# ===== CONFIGURATION =====

# Log file
filePathLog = "/var/www/html/commandFileLog.txt"

# infra red receiver
ir_gpioPin = 25

# 23 = button
btn_gpioPin = 23

# 24 = led
led_gpioPin_yellow = 24
led_gpioPin_red = 17
led_gpioPin_green = 27

# signal timeout in microseconds - how much time to wait before signal is marked as ended
ir_signalTimeout = 300000

# ===== GPIO setup =====

GPIO.setmode(GPIO.BCM)
GPIO.setup(btn_gpioPin,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(led_gpioPin_yellow,GPIO.OUT)
GPIO.setup(led_gpioPin_red,GPIO.OUT)
GPIO.setup(led_gpioPin_green,GPIO.OUT)
GPIO.setup(ir_gpioPin,GPIO.IN)


# ===== Global variables =====

ir_pulseStream = [] # array of pulses that will be extended by the ir_gpio_on_both thread

# ===== Logging =====

@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old


def log_writeLine(message):
with open(filePathLog, "a") as commandFileLog:
commandFileLog.write(time.strftime("%Y-%m-%d %H:%M:%S") + " " + message + "\n")
commandFileLog.close()

# ===== Functions =====

def buttonpressed(channel):
# with stdoutIO() as s:
print "button pressed"

GPIO.output(led_gpioPin_yellow,GPIO.HIGH)

start = time.time()

while GPIO.input(btn_gpioPin) == GPIO.LOW and time.time() - start < 2:
# print time.time() - start
time.sleep(0.1)

duration = time.time() - start

# print "Button-up " + str(duration)

if duration > 0.2:
print "Button pressed: " + str(duration)

GPIO.output(led_gpioPin_yellow,GPIO.LOW)

strAction = ""
if duration > 2:
led_blink_yellow(0.1, 10)
strAction = "shutdown"
os.system("shutdown -h now")

elif duration > 0:
strAction = "restart"
cmd_restart()
print "Action: " + strAction

def buttonreleased(channel):
print "b-up"

def ir_gpio_on_both(channel):
# global ir_pulseStream
ir_pulseStream.append( (GPIO.input(channel), time.time()) )

def ir_getGroupCode(value,pulseLength):
if value == 1:
# second char in :ab:
if pulseLength > ir_signalTimeout or pulseLength==0:
return "_" # invalid-high-pulseLength
elif pulseLength > 200000:
return "i"
elif pulseLength > 64000:
return "h"
elif pulseLength > 63000:
return "g"
elif pulseLength > 43000:
return "f"
elif pulseLength > 4500:
return "e"
elif pulseLength > 3600:
return "d"
elif pulseLength > 2800:
return "c"
elif pulseLength > 1900:
return "b"
else:
return "a"
elif value == 0:
# first char in :ab:
if pulseLength > ir_signalTimeout or pulseLength==0:
return "_" # invalid-low-pulseLength
elif pulseLength > 4600:
return "f"
elif pulseLength > 3800:
return "e"
elif pulseLength > 2900:
return "d"
elif pulseLength > 2100:
return "c"
elif pulseLength > 1300:
return "b"
else:
return "a"
else:
return "!"

# clean raw array of pulses
def ir_getPulses(arrPulses):
# global ir_pulseStream
arrGroupPulses = [] # list of pulses belonging to one group (button press)

# if the last signal was received less than -timeout- microsettings ago, stop
intElapsed = int(1000000 * (time.time() - arrPulses[len(arrPulses)-1][1]))
if intElapsed < ir_signalTimeout:
return arrGroupPulses

if len(arrPulses) == 0:
return arrGroupPulses

pulse = arrPulses.pop(0)
prevPulse = None

while pulse:

pulseValue = pulse[0]
pulseTime = pulse[1]

if prevPulse is None:
pulseLength = 0
else:
pulseLength = pulseTime - prevPulse[1]
pulseLength = int(1000000 * pulseLength)

if len(arrGroupPulses)==0 or pulseLength > ir_signalTimeout:
# create new group
arrGroupPulses.append([])
pulseLength = 0

# append to latest group
arrGroupPulses[len(arrGroupPulses)-1].append((pulseValue, pulseLength))

prevPulse = pulse
if len(arrPulses)>0:
pulse = arrPulses.pop(0)
else:
pulse = None
return arrGroupPulses


# convert array of pulses to a string command
def ir_getPulseCommand(arrPulses):
strPulseCommand = ""
for i in range(len(arrPulses)):
if i%2 == 0 and i!=0: # and i<len(arrPulses)-1
strPulseCommand += ":"
strPulseCommand += ir_getGroupCode(arrPulses[i][0],arrPulses[i][1])
return strPulseCommand

def ir_getKey(strCommand):
if strCommand == "_a:aa:ab:ae:ba:aa:aa:ba:ba:fa:aa:ab:ae:ca:aa:aa:ba:ba":
print("on")
cmd_restart()
elif strCommand == "_a:aa:ab:aa:ab:ab:aa:aa:ba:ba:fa:aa:ab:aa:ab:aa:aa:aa":
print("off")
cmd_shutdown()
elif strCommand == "_a:aa:ab:aa:ac:ab:aa:aa:ba:ba:fa:aa:ab:aa:ac:aa:aa:aa":
print("return")
elif strCommand == "_a:aa:aa:aa:aa:aa:aa:ab:aa:aa:ba:ba:fa:aa:aa:aa:aa:aa":
print("up")
elif strCommand == "_a:aa:ab:aa:ba:cb:aa:aa:ba:ba:fa:aa:ab:aa:ba:ca:aa:aa":
print("menu")
elif strCommand == "_a:aa:aa:ba:aa:aa:ab:aa:aa:ba:ba:fa:aa:aa:ba:aa:aa:aa":
print("left")
elif strCommand == "_a:aa:ab:aa:ac:ba:aa:aa:ba:ba:fa:aa:ab:aa:ac:ca:aa:aa":
print("enter")
elif strCommand == "_a:aa:aa:ca:aa:aa:ab:aa:aa:ba:ba:fa:aa:aa:ca:aa:aa:aa":
print("right")
elif strCommand == "_a:aa:ab:aa:ab:ca:aa:aa:ba:ba:fa:aa:ab:aa:ab:da:aa:aa":
print("vol_plus")
led_blink_yellow(0.4, 2)
elif strCommand == "_a:aa:ab:aa:aa:aa:ab:aa:aa:ba:ba:fa:aa:ab:aa:aa:aa:aa":
print("down")
elif strCommand == "_a:aa:ab:aa:aa:ca:aa:aa:ba:ba:fa:aa:ab:aa:aa:da:aa:aa":
print("ch_up")
elif strCommand == "_a:aa:ab:aa:aa:aa:ba:aa:aa:ba:ba:fa:aa:ab:aa:aa:aa:ca":
print("vol_minus")
led_blink_yellow(0.4, 2)
elif strCommand == "_a:aa:aa:ca:aa:aa:ba:aa:aa:ba:ba:fa:aa:aa:ca:aa:aa:ca":
print("mute")
elif strCommand == "_a:aa:ab:ac:da:aa:aa:ba:ba:fa:aa:ab:ac:ea:aa:aa:ba:ba":
print("ch_down")
elif strCommand == "_a:aa:aa:bd:bb:aa:aa:ba:ba:fa:aa:aa:bd:ba:aa:aa:aa:ba":
print("rewind")
cmd_wifi_acp()
elif strCommand == "_a:aa:aa:aa:ad:bb:aa:aa:ba:ba:fa:aa:aa:aa:ad:ba:aa:aa":
print("play")
elif strCommand == "_a:aa:aa:cd:bb:aa:aa:ba:ba:fa:aa:aa:cd:ba:aa:aa:aa:ba":
print("forward")
cmd_wifi_cli()
elif strCommand == "_a:aa:aa:aa:aa:bb:ba:aa:aa:ba:ba:fa:aa:aa:aa:aa:bb:ca":
print("go")
led_blink_yellow(2, 1)

else:
print("unknown: " + strCommand)
led_blink_yellow(0.1, 5)

def led_blink_yellow(intSpeed, intTimes):
for i in range(intTimes):
GPIO.output(led_gpioPin_yellow,GPIO.HIGH)
time.sleep(intSpeed)
GPIO.output(led_gpioPin_yellow,GPIO.LOW)
time.sleep(intSpeed)

def led_blink_green(intSpeed, intTimes):
for i in range(intTimes):
GPIO.output(led_gpioPin_green,GPIO.HIGH)
time.sleep(intSpeed)
GPIO.output(led_gpioPin_green,GPIO.LOW)
time.sleep(intSpeed)

def led_blink_red(intSpeed, intTimes):
for i in range(intTimes):
GPIO.output(led_gpioPin_red,GPIO.HIGH)
time.sleep(intSpeed)
GPIO.output(led_gpioPin_red,GPIO.LOW)
time.sleep(intSpeed)

# Wifi in access point mode: red led / rewind ir button
# Wifi in client mode: green led / forward ir button
def check_wifi_mode():
output = subprocess.check_output(['ps', '-A'])
if 'hostapd' in output:
GPIO.output(led_gpioPin_red,GPIO.HIGH)

if 'dhcpcd' in output:
GPIO.output(led_gpioPin_green,GPIO.HIGH)

# ===== Commands =====

def cmd_restart():
led_blink_yellow(0.1, 5)
with stdoutIO() as s:
os.system("shutdown -r now")
log_writeLine(s.getvalue())

def cmd_shutdown():
led_blink_yellow(0.1, 5)
with stdoutIO() as s:
os.system("shutdown -h now")
log_writeLine(s.getvalue())

def cmd_wifi_acp():
print("starting wifi ap mode")
led_blink_red(0.4, 3)
with stdoutIO() as s:
os.system("/home/pi/scripts/wifi_acp.sh")
log_writeLine(s.getvalue())

def cmd_wifi_cli():
print("starting wifi client mode")
led_blink_green(0.4, 3)
with stdoutIO() as s:
os.system("/home/pi/scripts/wifi_cli.sh")
log_writeLine(s.getvalue())

try:
log_writeLine("watchCommandFile service started")
GPIO.add_event_detect(btn_gpioPin,GPIO.FALLING,callback=buttonpressed,bouncetime=200)
GPIO.add_event_detect(ir_gpioPin,GPIO.BOTH,callback=ir_gpio_on_both)
check_wifi_mode()
while True:
filePath = "/var/www/html/commandFile.txt"
if os.path.isfile(filePath):
# print "File found"
if os.stat(filePath)[6]>0:
with open(filePath, "r") as commandFile:
fileContent = commandFile.readlines()
commandFile.close()

# clear log file, so only the last action is logged
# open(filePathLog, "w").close()

# clear file content
open(filePath, "w").close()

for line in fileContent:
log_writeLine("Command: " + line.strip())
if line.strip()=="led":
led_blink_yellow(2, 1)
elif line.strip()=="restart":
cmd_restart()
elif line.strip()=="shutdown":
cmd_shutdown()
else:
# print "File not found"
GPIO.cleanup()
log_writeLine("watchCommandFile service stopped")
sys.exit()

if len(ir_pulseStream)>0:
arrGroupedPulses = ir_getPulses(ir_pulseStream)
for i in range(len(arrGroupedPulses)):
strCommand = ir_getPulseCommand(arrGroupedPulses[i])
# print("Group " + str(i) + ": " + strCommand)
log_writeLine("InfraRed command detect: " + strCommand)
ir_getKey(strCommand[0:53])

time.sleep(0.2)
except KeyboardInterrupt, e:
GPIO.cleanup()
log_writeLine("watchCommandFile service stopped")
sys.exit()

GPIO.cleanup()
log_writeLine("watchCommandFile service stopped")
Zoeken



Pagina's
raspberry pi lcd Hallo Raspberry Pi liefhebber, Voor minder dan...
raspberry pi... Hallo Raspberry Pi liefhebber, Onze Raspberry Pi...
raspberry pi... Hallo Raspberry Pi knutselaar! Een aantal projecten...
raspberry pi... Welkom terug Raspberry Pi engineer!  ...
raspberry pi... Hallo Raspberry Pi liefhebber. Maak gebruik van...