#! /usr/bin/python ''' Credits: CocoaSequenceGrabber and example Objective-C code by Tim Omernick on 3/18/05. Copyright 2005 Tim Omernick. All rights reserved. PySight and example code translation by Dethe Elza on 2005-05-09 Copyright 2005 Dethe Elza ''' from Foundation import * from PySight import * from PyObjCTools import AppHelper import os class Controller(NSObject): def init(self): self = super(Controller, self).init() if self is None: return None # start frame grabbing self.camera = CSGCamera.alloc().init() self.camera.setDelegate_(self) # we only need 1 pixel; to grab a full frame, use: (640, 480) self.camera.startWithSize_((1, 1)) # init signal processing stuff self.oldsum = 0 self.olddif = 0 self.movwin = [0 for i in range(5)] # magnitude of light change required to trigger action; # modify as needed self.threshold = 20 return self # CSGCamera delegate # This method is called when the sequence grabber has a new frame (30 FPS) def camera_didReceiveFrame_(self, aCamera, aFrame): imageRep = aFrame.representations()[0] # aFrame is an NSImage # returns python buffer, 4 bytes per pixel; # not sure why the buffer is returning more than 4 bytes for 1x1 camera size; # this doesn't happen when I run in Xcode w/ GUI code imageData = imageRep.bitmapData() data = [ord(imageData[i]) for i in range(3)] # rgb; don't need the alpha channel self.signalDetection(data) # Crude signal detection routine. Someone please improve! def signalDetection(self, data): self.movwin += [sum(data)] self.movwin.pop(0) newsum = sum(self.movwin) newdif = newsum - self.oldsum # uncomment this line for a stripchart of changes from ambient #chart = list('|'.center(51)); chart[25 + newdif/30] = '*'; print ''.join(chart) if self.thresholdcrossing(newdif, self.olddif) == 1: self.doSomething() self.oldsum = newsum self.olddif = newdif def thresholdcrossing(self, a, b): if a > self.threshold and b < self.threshold: return 1 elif a < self.threshold and b > self.threshold: return -1 else: return 0 def doSomething(self): # Toggle iTunes os.popen('''osascript -e 'tell application "iTunes"' -e "playpause" -e 'end tell' ''') c = Controller.alloc().init() AppHelper.runConsoleEventLoop(installInterrupt=True)