Oh for crying out loud. No wonder I was hogging all the CPU I could find - it was only "sleep"ing when it detcted a button press. The rest of the time it was looping like crazy. Refactored code (with a time.sleep(0.1) and event detection brings CPU down from “whatever I can grab” to 0.2%.
Learning curve.
import RPi.GPIO as GPIO
import time
import urllib
isPlaying = False
isOn = True;
requestBody = ""
GPIO.setmode(GPIO.BCM)
GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def SendSlimRequest(requestType):
f = urllib.urlopen("http://127.0.0.1:9000/jsonrpc.js", requestType)
print f.read()
def myCallback(channel):
global isPlaying
global isOn
global requestBody
if channel == 6:
if isPlaying == False:
requestBody = "{\"method\":\"slim.request\",\"id\":1,\"params\":[\"b8:27:eb:9c:3c:8e\",[\"play\"]],\"result\":{}}"
isPlaying = True
else:
requestBody = "{\"method\":\"slim.request\",\"id\":1,\"params\":[\"b8:27:eb:9c:3c:8e\",[\"pause\"]],\"result\":{}}"
isPlaying = False
if channel == 12:
if isOn == False:
requestBody = "{\"id\":1,\"method\":\"slim.request\",\"params\":[\"b8:27:eb:9c:3c:8e\",[\"power\",\"1\"]]}"
isOn = True
else:
requestBody = "{\"id\":1,\"method\":\"slim.request\",\"params\":[\"b8:27:eb:9c:3c:8e\",[\"power\",\"0\"]]}"
isOn = False
if channel == 5:
requestBody = "{\"method\":\"slim.request\",\"result\":{},\"id\":1,\"params\":[\"b8:27:eb:9c:3c:8e\",[\"button\",\"jump_fwd\"]]}"
if channel == 13:
requestBody = "{\"method\":\"slim.request\",\"result\":{},\"id\":1,\"params\":[\"b8:27:eb:9c:3c:8e\",[\"button\",\"jump_rew\"]]}"
if channel == 16:
requestBody = "{\"id\":1,\"method\":\"slim.request\",\"params\":[\"b8:27:eb:9c:3c:8e\",[\"mixer\",\"volume\",\"+5\"]]}"
if channel == 26:
requestBody = "{\"id\":1,\"method\":\"slim.request\",\"params\":[\"b8:27:eb:9c:3c:8e\",[\"mixer\",\"volume\",\"-5\"]]}"
SendSlimRequest(requestBody)
GPIO.add_event_detect(5, GPIO.FALLING, callback=myCallback, bouncetime=200)
GPIO.add_event_detect(6, GPIO.FALLING, callback=myCallback, bouncetime=200)
GPIO.add_event_detect(13, GPIO.FALLING, callback=myCallback, bouncetime=200)
GPIO.add_event_detect(26, GPIO.FALLING, callback=myCallback, bouncetime=200)
GPIO.add_event_detect(12, GPIO.FALLING, callback=myCallback, bouncetime=50)
GPIO.add_event_detect(16, GPIO.FALLING, callback=myCallback, bouncetime=50)
while True:
pass
time.sleep(0.1)