def setup(): GPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location GPIO.setup(IrPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setwarnings(False) os.system("python2 lcd1602.py 0") pylirc.init("pylirc", "./conf", blocking)
def run(self): GPIO.setmode(GPIO.BCM) #pylirc.init("pylirc","./irc_conf",blocking) pylirc.init("pylirc", "./irc_conf") allow = pylirc.blocking(0) while True: time.sleep(1) s = pylirc.nextcode() while (s): time.sleep(1) for (code) in s: #print 'Command: ',code["config"] print 'CommandS: ', s lirchar = s[0] print 'Command1:', lirchar self._char = lirchar if self._char == self._quitKey: pylirc.exit() print "QUIT!" return if self._char in self._handlersMap: self._handlersMap[self._char]() if (not blocking): s = pylirc.nextcode() else: s = []
def resume(self): """ (re-)initialize pylirc, e.g. after calling close() """ _debug_('Lirc.resume()', 2) pylirc.init('freevo', config.LIRCRC) pylirc.blocking(0)
def main(): signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) pylirc.init("front-panel-interface", "/etc/front-panel/pylirc.conf", 0) # non-blocking ip = commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1][5:] # use P1 header pin numbering convention GPIO.setmode(GPIO.BOARD) panel = FrontPanel.FrontPanel() panel.turn_on() while True: panel.check_for_input() # panel.display_text(ip, 1, 0) panel.display_clock() panel.display_respource_usage() panel.display_song() time.sleep(0.1)
def main(): lirc.init("radio") while 1: ir_codes = lirc.nextcode() if ir_codes != None: print(ir_codes) time.sleep(0.1)
def setup(): GPIO.setmode(GPIO.BOARD) #GPIO.setmode(GPIO.BCM) GPIO.setup(7, GPIO.OUT) GPIO.setup(11, GPIO.OUT) GPIO.setup(22, GPIO.OUT) GPIO.output(22, GPIO.LOW) pylirc.init("pylirc", "./conf", blocking)
def start(): try: pylirc.init('freevo', config.LIRCRC) pylirc.blocking(1) except RuntimeError: print 'WARNING: Could not initialize PyLirc!' sys.exit(0) except IOError: print 'WARNING: %s not found!' % config.LIRCRC sys.exit(0)
def setup(self): try: # open lirc pylirc.init("pylirc",os.path.dirname(__file__) + "/" + "../python_modules/" + "keys.conf",0) except Exception: import traceback print traceback.format_exc() sys.exit(1) self.connectClient()
def activate(self): """ Activate the infrared sensor. """ super(Infrared_Sensor, self).activate() self._active = True configuration_file = "{}/remotes/{}.lircrc".format(self._base_path, self._remote) pylirc.init(self._program, configuration_file, False) thread.start_new_thread(self._loop, ())
def __init__(self, app, config): conffile = config['configuration'] name = config['name'] if conffile: self._lirc = pylirc.init(name, conffile) else: self._lirc = pylirc.init(name) if not self._lirc: raise LircError('Cannot init pylirc')
def __init__(self): self.events = [] self.lastkey = False self.lasttime = time.time() global LIRC if LIRC: try: LIRC.init('pypilot') self.lirctime = False except: print('failed to initialize lirc. is .lircrc missing?') LIRC = None
def startReading(self): if self._fd != -1: try: os.fstat(self.fileno()) abstract.FileDescriptor.startReading(self) return except OSError: pass if self._lirc_config is not None: self._fd = pylirc.init(self._program_name, self._lirc_config) else: self._fd = pylirc.init(self._program_name) pylirc.blocking(0) self.protocol.connectionMade() abstract.FileDescriptor.startReading(self)
def setup(): global p_R, p_G, p_B GPIO.setmode(GPIO.BCM) GPIO.setup(Rpin, GPIO.OUT) GPIO.setup(Gpin, GPIO.OUT) GPIO.setup(Bpin, GPIO.OUT) p_R = GPIO.PWM(Rpin, 2000) # Set Frequece to 2KHz p_G = GPIO.PWM(Gpin, 2000) p_B = GPIO.PWM(Bpin, 2000) p_R.start(100) p_G.start(100) p_B.start(100) pylirc.init("pylirc", "./conf", blocking)
def startRemoteControll(self, dataQueue): dataQueue.put(['pid', getpid()]) try: if(pylirc.init('mediacatalog', self.config, self.blocking)): self.configuration.getLogger().info('Remote control process was started') dataQueue.put(['status', 0]) code = "" isTerminate = False DEVNULL = open(os.devnull, 'w') while not isTerminate: codesList = pylirc.nextcode(1) out = subprocess.Popen(['/bin/sh', '-c', 'ps -ae | grep `xdotool getwindowfocus getwindowpid` | grep mediacatalog.py'], stdout=subprocess.PIPE) isHasFocus = out.communicate()[0].rstrip() if (isHasFocus != ""): self.configuration.getLogger().debug('Application has focus') if(codesList): for code in codesList: self.configuration.getLogger().info('Command: %s, Repeat: %d' % (code['config'], code['repeat'])) if code['config'] != None: if code['repeat'] > 1: for i in range(code['repeat']-1): xmacroProc = subprocess.Popen(['xmacroplay', ':0.0'], stdin=subprocess.PIPE, stdout=DEVNULL, stderr=subprocess.STDOUT) xmacroProc.communicate('KeyStrPress ' + code['config'] + ' KeyStrRelease ' + code['config']) else: xmacroProc = subprocess.Popen(['xmacroplay', ':0.0'], stdin=subprocess.PIPE, stdout=DEVNULL, stderr=subprocess.STDOUT) xmacroProc.communicate('KeyStrPress ' + code['config'] + ' KeyStrRelease ' + code['config']) else: self.configuration.getLogger().debug('Application has not focus') except RuntimeError: dataQueue.put(['status', 1]) self.configuration.getLogger().error('Remote control not initialized') self.configuration.getLogger().error(sys.exc_info()[1])
def __init__(self, config, notifier): if not pylirc: return self.notifier = notifier rc_file = config.get("lirc", "keymap") self.socket = pylirc.init('radioplayer', rc_file)
def startPyLirc(self): if(pylirc.init(LIRC_PROG_NAME, self.configFile, 0)): while(self.frontendActive): s = pylirc.nextcode(1) self.handleNextCode(s) sleep(0.1) pylirc.exit()
def __init__(self, dest, name, config): self.dest = dest sock = pylirc.init(name, config) pylirc.blocking(False) super(client, self).__init__(sock, Qt.QSocketNotifier.Read, dest) self.setEnabled(True) self.activated.connect(self.read_nextcode)
def run(self): try: global lastInput global stopThreads if (pylirc.init("lircidle", "/home/myth/scripts/lircrc_lircidle", 0) == 0): syslog.syslog('lircidle.py: unable to init lirc') print('lircidle.py: unable to init lirc') sys.exit(1) while 1: time.sleep(1) c = pylirc.nextcode() if c is not None: #for (code) in c: # syslog.syslog('lircidle.py (debug): code received (' + str(code["config"]) + ')') # print('lircidle.py (debug): code received (' + str(code["config"]) + ')') lastInput = time.time() if stopThreads != 0: break except: syslog.syslog('lircidle.py: unexpected exception: ' + str(sys.exc_info())) print('lircidle.py: unexpected exception: ' + str(sys.exc_info())) finally: pylirc.exit() syslog.syslog('lircidle.py: exiting lirc thread') print('lircidle.py: exiting lirc thread')
def work(self): blocking = 0 run = 1 try: if pylirc.init(self.prog, self.tempFile.name): while run: if not blocking: self.plugin.workerLock.acquire() run = self.plugin.workerRunning self.plugin.workerLock.release() if run: time.sleep(0.5) else: break s = pylirc.nextcode(1) blocking = 0 while s: for code in s: self.plugin.send_ir_command(code["config"]) blocking = 1 s = [] except RuntimeError as e: self.logger.warning('LIRC Plugin could not be loaded. Retrying in 5 seconds. %s' % e) pylirc.exit() time.sleep(5) self.work()
def init(appname = None, cfg = None): """ Init pylirc and connect to the mainloop. """ global _dispatcher if _dispatcher: # already running return False if not pylirc: # not installed return False if cfg == None: cfg = os.path.expanduser("~/.lircrc") if appname == None: appname = "kaa" try: fd = pylirc.init(appname, cfg) except IOError: # something went wrong return False if not fd: # something went wrong return False pylirc.blocking(0) _dispatcher = kaa.IOMonitor(_handle_lirc_input) _dispatcher.register(fd) kaa.main.signals["shutdown"].connect(stop) return True
def browser(args): browser = subprocess.Popen(["/usr/local/bin/mozilla-firefox/firefox"] + args[1:]) time.sleep(5) p1 = subprocess.Popen(["xdotool", "search", "--name", "Mozilla Firefox"], stdout = subprocess.PIPE) p1.wait() windows = p1.stdout.readline().split() for window in windows: print "'%s'" % window subprocess.Popen(["xdotool", "windowfocus", str(window)]) subprocess.Popen(["xdotool", "key", "F11"]) try: if not pylirc.init("mozilla-firefox", "/etc/lirc/lircrc", 1): return "Failed" stop = False while not stop: codes = pylirc.nextcode(1) if codes is None: continue for code in codes: print code if code is None: continue config = code["config"].split() if config[0] == "EXIT": stop = True break if config[0] == "mousestepreset": mousestep = 0 elif config[0] == "mousemove_relative": if mousestep < 10: mousestep += 1 config[2] = str(int(config[2]) * mousestep ** 2) config[3] = str(int(config[3]) * mousestep ** 2) subprocess.Popen(["xdotool"] + config) except KeyboardInterrupt: print "Exiting...." p1 = subprocess.Popen(["xdotool", "search", "--name", "Mozilla Firefox"], stdout = subprocess.PIPE) p1.wait() windows = p1.stdout.readline().split() for window in windows: print "'%s'" % window subprocess.Popen(["xdotool", "windowfocus", str(window)]) subprocess.Popen(["xdotool", "key", "Ctrl+Shift+W"]) # If we found windows and they're still running, wait 3 seconds if len(windows) != 0 and browser.poll() is None: for i in range(30): time.sleep(.1) if browser.poll() is not None: break # Okay now we can forcibly kill browser if browser.poll() is None: browser.terminate() return 0
def resume(self): """ (re-)initialize pylirc, e.g. after calling close() """ logger.log(9, 'Lirc.resume()') fd = pylirc.init('freevo', config.LIRCRC) self.dispatcher = kaa.IOMonitor(self._handle_lirc_input) self.dispatcher.register(fd)
def resume(self): """ (re-)initialize pylirc, e.g. after calling close() """ logger.log( 9, 'Lirc.resume()') fd = pylirc.init('freevo', config.LIRCRC) self.dispatcher = kaa.IOMonitor(self._handle_lirc_input) self.dispatcher.register(fd)
def __init__(self): config = ConfigParser.SafeConfigParser() config.read('example.cfg') try: lirc_socket = pylirc.init("yavdr-dock") gobject.io_add_watch(lirc_socket, gobject.IO_IN, self.lirc_handler) except: syslog.syslog("LIRC initialization error!") # create the main window, and attach delete_event signal to terminating # the application self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_position(gtk.WIN_POS_CENTER_ALWAYS) color = gtk.gdk.color_parse('#000000') self.window.modify_bg(gtk.STATE_NORMAL, color) self.window.set_border_width(0) self.window.set_has_frame(False) self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN) self.window.set_decorated(False) self.window.show() # a horizontal box to hold the buttons self.hbox = gtk.HBox() self.hbox.show() self.window.add(self.hbox) focus_is_not_set = True for section in config.sections(): # create several images with data from files and load images into # buttons image = gtk.Image() image.set_from_file(config.get(section, 'Image')) image.show() # a button to contain the image widget bgcolor = gtk.gdk.color_parse('#020507') fgcolor = gtk.gdk.color_parse('#004466') accolor = gtk.gdk.color_parse('#FFFFFF') self.button = gtk.Button() style = self.button.get_style().copy() style.bg[gtk.STATE_NORMAL] = bgcolor style.bg[gtk.STATE_SELECTED] = accolor style.bg[gtk.STATE_ACTIVE] = accolor style.bg[gtk.STATE_PRELIGHT] = fgcolor #set the button's style to the one you created self.button.set_style(style) self.button.props.relief = gtk.RELIEF_NONE self.button.add(image) self.button.show() self.hbox.pack_start(self.button) self.button.connect("clicked", self.button_clicked, config.get(section, 'Exec')) if focus_is_not_set: self.button.grab_focus() focus_is_not_set = False
def __init__(self, poll): thisdir = os.path.dirname(__file__) config = os.path.join(thisdir, "lirc.rc") self._fd = pylirc.init("headless-home-music", config, False) if self._fd == 0: raise RuntimeError("pylirc failed to initialized") poll.add_fd(self._fd, select.POLLIN | select.POLLHUP, self._cb) self._poller = poll
def __init__(self, fullscreen = True, size = None): """ Screen.__init__([fullscreen [,size]]) -- initialize screen Starts up the display screen, optionally in window and mode with specified size. """ checkpoint('first') pygame.font.init() pygame.display.init() pygame.event.set_allowed(None) pygame.event.set_allowed((pygame.QUIT, pygame.KEYDOWN)) pygame.event.set_grab(False) pygame.mouse.set_visible(False) self.fullscreen = fullscreen if size: self.rsize = size else: self.rsize = pygame.display.list_modes()[0] if fullscreen else (800, 600) # TODO: generalize detection of dualhead configs if self.rsize == (2704, 1050): self.size = (1680, 1050) else: self.size = self.rsize checkpoint('pygame init') self.fonts = [ {'name': 'arialbd', 'size': self.size[0]/24}, {'name': 'arial', 'size': self.size[0]/33}, {'name': 'arial', 'size': self.size[0]/47}, ] self.load_fonts() self.load_shapes() self.deactivate_screensaver() if not hasattr(self, 'lircsock') and 'pylirc' in sys.modules: self.lircsock = pylirc.init('cmus-fullscreen') pygame.display.set_caption('cmus fullscreen interface') # TODO: set window icon? self.screen = pygame.display.set_mode(self.rsize, \ pygame.FULLSCREEN if fullscreen else 0) checkpoint('window') self.back = self.draw_background() # TODO: only make browsurf as big as needed self.browsurf = Surface(self.size, pygame.SRCALPHA) self.surf = Surface(self.size, pygame.SRCALPHA) try: self.st = cmus.Status() except: # TODO: print this onscreen and retry raise Exception('cmus not started') self.start_thread() self.first = True
def start_main_loop(self): """ Read lirc config file and start main pylirc main loop. """ if pylirc.init("tvtuner", "~/.lircrc", False): try: self._lirc_main_loop() except KeyboardInterrupt: self._osd.hide() pylirc.exit() del self._osd logging.debug('Exiting..')
def __init__(self): threading.Thread.__init__(self) self.lock = threading.Lock() self.daemon = True self.MAIN_THREAD_DELAY = 0.01 self.lircConnected = True try: self.sockid = pylirc.init("myamp", "/root/.lircrc") pylirc.blocking(0) except: print "error connecting to lircd!" self.lircConnected = False self.code = None
def runPylirc(configuration): if pylirc is None: logger.debug('Not initializing pylirc') yield return logger.debug('Initializing pylirc with configuration: ' + configuration) fd = pylirc.init('browser', configuration) if not fd: raise RuntimeError('Failed to initialize pylirc') try: yield fd finally: pylirc.exit()
def __init__(self, name = "irUI"): self.pub_btn = rospy.Publisher('/arom/UI/buttons', String, queue_size=10) self.pub_beep = rospy.Publisher('/beeper/preset', String, queue_size=5) rospy.init_node('irUI') self.set_feature('remoteCtrl',{'type': "odroid"}) blocking = 0; rate = rospy.Rate(10) pylirc.init("pylirc", "/home/odroid/robozor/station/irConf.conf", blocking) while not rospy.is_shutdown(): try: s = pylirc.nextcode(1) if s: rospy.loginfo(s[0]['config']) self.pub_btn.publish(s[0]['config']) self.pub_beep.publish('btn') s = [] except Exception, e: rospy.logerr(e) rate.sleep()
def ir_codes(): global read_ir_key_val GPIO.setup(26, GPIO.IN) pylirc.init("my_lirc", ir_conf_path, 0) ir_codes = pylirc.nextcode(1) # while with time out timeout_start = time.time() while True: ir_codes = pylirc.nextcode(1) if ir_codes != None: conf_key = ir_codes[0]['config'] #print("ircodes = %s"%ir_codes) #print(type(conf_key)) pylirc.exit() read_ir_key_val = conf_key return conf_key elif (time.time() - timeout_start > ir_time_out): pylirc.exit() read_ir_key_val = None print "time out" return -1 time.sleep(0.05)
def ffox(args): ffox = subprocess.Popen(["/usr/bin/firefox"] + args[1:]) try: if not pylirc.init("firefox", "~/.lircrc", 1): return "Failed" stop = False while not stop: codes = pylirc.nextcode(1) if codes is None: continue for code in codes: #print code if code is None: continue config = code["config"].split() if config[0] == "EXIT": stop = True break if config[0] == "mousestepreset": mousestep = 0 elif config[0] == "mousemove_relative": if mousestep < 10: mousestep += 1 config[2] = str(int(config[2]) * mousestep ** 2) config[3] = str(int(config[3]) * mousestep ** 2) subprocess.Popen(["xdotool"] + config) except KeyboardInterrupt: print "Exiting...." p1 = subprocess.Popen(["xdotool", "search", "--title", "Mozilla Firefox"], stdout = subprocess.PIPE) p1.wait() windows = p1.stdout.readline().split() for window in windows: #print "'%s'" % window subprocess.Popen(["xdotool", "windowfocus", str(window)]) subprocess.Popen(["xdotool", "key", "ctrl+q"]) # If we found windows and they're still running, wait 3 seconds if len(windows) != 0 and ffox.poll() is None: for i in range(30): time.sleep(.1) if ffox.poll() is not None: break # Okay now we can forcibly kill it if ffox.poll() is None: ffox.terminate() return 0
def setup(): global p_R, p_G, p_B GPIO.setmode(GPIO.BCM) GPIO.setup(Rpin, GPIO.OUT) GPIO.setup(Gpin, GPIO.OUT) GPIO.setup(Bpin, GPIO.OUT) p_R = GPIO.PWM(Rpin, 2000) # Set Frequece to 2KHz p_G = GPIO.PWM(Gpin, 2000) p_B = GPIO.PWM(Bpin, 2000) p_R.start(100) p_G.start(100) p_B.start(100) err = pylirc.init("ircontrol", "./lircrc", blocking) print(err) if (err == 0): raise IOError("IR init error!")
def test(self): blocking = 0; # if(pylirc.init("pylirc", "./conf", blocking)): code = {"config" : ""} while(code["config"] != "quit"): # Very intuitive indeed if(not blocking): print "." # Delay... time.sleep(1) # Read next code s = pylirc.nextcode(1) # Loop as long as there are more on the queue # (dont want to wait a second if the user pressed many buttons...) while(s): # Print all the configs... for (code) in s: print "Command: %s, Repeat: %d" % (code["config"], code["repeat"]) if(code["config"] == "blocking"): blocking = 1 pylirc.blocking(1) elif(code["config"] == "nonblocking"): blocking = 0 pylirc.blocking(0) # Read next code? if(not blocking): s = pylirc.nextcode(1) else: s = [] # Clean up lirc pylirc.exit()
def listener(): try: if use_pylirc: sockid = pylirc.init("piradio", lircrc, blocking) else: # The following line is for Jessie and Stretch only sockid = lirc.init("piradio", lircrc, blocking) log.message("Listener on socket " + str(socket) + " established", log.DEBUG) # Main Listen loop print("Listening for input on IR sensor") while True: #pdb.set_trace() if use_pylirc: nextcode = pylirc.nextcode() else: nextcode = lirc.nextcode() # For Jessie amend pylirc.nextcode to lirc.nextcode if nextcode != None and len(nextcode) > 0: if remote_led > 0: GPIO.output(remote_led, True) button = nextcode[0] log.message(button, log.DEBUG) print(button) udpSend(button) # Send to radiod program if remote_led > 0: GPIO.output(remote_led, False) else: time.sleep(0.2) except Exception as e: log.message(str(e), log.ERROR) print(str(e)) mesg = "Possible configuration error, check /etc/lirc/lircd.conf" log.message(mesg, log.ERROR) print(mesg) mesg = "Activation IR Remote Control failed - Exiting" log.message(mesg, log.ERROR) print(mesg) sys.exit(1)
def init(appname=None, cfg=None): """ Initialize lirc and begin monitoring for events. :param appname: the name of the program that corresponds to the *prog* value in the lircrc file (default: kaa) :param cfg: the path to the lircrc config file (default: ~/.lircrc). See http://www.lirc.org/html/configure.html for more details. :raises: ImportError if pylirc is not installed. """ global _dispatcher if _dispatcher: # already running return False # This will raise if pylirc isn't available, however if it is, this will # already be imported, so there is no risk of this being imported from a # thread. import pylirc if cfg == None: cfg = os.path.expanduser("~/.lircrc") if appname == None: appname = "kaa" try: fd = pylirc.init(appname, cfg) except IOError: # something went wrong return False if not fd: # something went wrong return False pylirc.blocking(0) _dispatcher = kaa.IOMonitor(_handle_lirc_input) _dispatcher.register(fd) kaa.main.signals["shutdown"].connect(stop) return True
def run(self): if self.config_file: x = XKeys() import pylirc #try: if (pylirc.init("irkeys", self.config_file, 0)): while True: s = pylirc.nextcode(1) if s: for evt in s: command = evt["config"] print "IR recived :: " + command x.SendKeyPress(command) time.sleep(0.1) x.SendKeyRelease(command)
def run(self): if self.config_file: x = XKeys() import pylirc #try: if(pylirc.init("irkeys", self.config_file, 0)): while True: s = pylirc.nextcode(1) if s: for evt in s: command = evt["config"] print "IR recived :: " + command x.SendKeyPress( command ) time.sleep(0.1) x.SendKeyRelease( command )
def run(self): try: lirchandle = pylirc.init("ude-dbus-lirc-bridge", "/usr/share/ude/dbus-lirc-bridge/lircrc", True) if lirchandle: while True: if self.stopped(): break try: timeout = select.select([lirchandle], [], [], 1) == ([], [], []) except Exception, e: print "IRWorker Exception", e continue if not timeout: s = pylirc.nextcode() if s: for code in s: if dbusobj: dbusobj.IREvent(code) # print "cmd",code pylirc.exit()
def run(self): try: lirchandle = pylirc.init("ude-dbus-lirc-bridge", "/usr/share/ude/dbus-lirc-bridge/lircrc", True) if lirchandle: while True: if self.stopped(): break try: timeout = select.select([lirchandle], [], [], 1) == ([], [], []) except Exception, e: print "IRWorker Exception", e continue if not timeout: s = pylirc.nextcode() if s: for code in s: if dbusobj: dbusobj.IREvent(code) #print "cmd",code pylirc.exit()
def run(self): try: global lastInput global stopThreads if (pylirc.init("lircidle","/home/myth/scripts/lircrc_lircidle",0) == 0): syslog.syslog('lircidle.py: unable to init lirc') print('lircidle.py: unable to init lirc') sys.exit(1) while 1: time.sleep(1) c = pylirc.nextcode() if c is not None: #for (code) in c: # syslog.syslog('lircidle.py (debug): code received (' + str(code["config"]) + ')') # print('lircidle.py (debug): code received (' + str(code["config"]) + ')') lastInput = time.time() if stopThreads != 0: break except: syslog.syslog('lircidle.py: unexpected exception: ' + str(sys.exc_info())) print('lircidle.py: unexpected exception: ' + str(sys.exc_info())) finally: pylirc.exit() syslog.syslog('lircidle.py: exiting lirc thread') print('lircidle.py: exiting lirc thread')
def loop(): while True: s = pylirc.nextcode(1) while (s): for (code) in s: myCar = Car() myCar.stop() print('Command: ', code["config"]) IR(code["config"]) if (not blocking): s = pylirc.nextcode(1) else: s = [] def destroy(): GPIO.cleanup() pylirc.exit() if __name__ == '__main__': setup() keysacn() print("setup ok") pylirc.init("pylirc", "./conf", blocking) try: loop() except KeyboardInterrupt: destroy()
Adapted excerpt from Getting Started with Raspberry Pi by Matt Richardson Modified by Rui Santos Complete project details: http://randomnerdtutorials.com ''' import pylirc import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # Create a dictionary called pins to store the pin number, name, and pin state: f = open('/home/pi/webserver/pin_status.csv', 'r') pins = eval(f.read()) f.close() pylirc.init('pylirc', '/home/pi/pylirc.conf', 0) # Set each pin as an output and make it low: for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, pins[pin]['state']) while (True): s = pylirc.nextcode(1) command = None if (s): for (code) in s: f = open('/home/pi/webserver/pin_status.csv', 'r') pins = eval(f.read()) f.close() print(code["config"])
def startPyLirc(self): lircHandle = pylirc.init(LIRC_PROG_NAME, self.configFile, 0) if (lircHandle != 0): while (self.frontendActive): self.consumePylirc(lircHandle) pylirc.exit()
def main(): usage = "usage: pstream3_client_lirc [options]" parser = OptionParser(usage) parser.add_option("--daemon", help="Run me as daemon", action="store_true", dest="daemon") parser.add_option("--ip", help="Ip where should i listen", dest="ip") parser.add_option("--port", help="Port where should i bind", dest="port") parser.add_option("--dump", help="Folder where should i dump", dest="dump") parser.add_option("--lirc-config", help="Path to lirc config", dest="lirc_config") parser.add_option("--pid", help="Process pid", dest="pid") (options, args) = parser.parse_args() if options.daemon: ret= createDaemon() if options.pid: pid= os.getpid() f= open(options.pid, "w") f.write(str(pid)) f.close() if options.ip and options.port: ip= options.ip port= options.port else: ip= "localhost" port= str(8400) client = xmlrpclib.ServerProxy("http://%s:%s/" % (ip, port)) h264_client= None blocking= 1 if options.lirc_config: lirc_path= options.lirc_config else: lirc_path="/etc/pstream/conf" if(pylirc.init("pylirc", lirc_path, blocking)): code= {"config": ""} while(code["config"] != "quit"): #Read next code s= pylirc.nextcode(1) #Right now i don't care what you press on remote. code["config"]= "start_stream" status= None if(code["config"] == "start_stream"): try: status=h264_client.GetAppRunStatus() except: status=None if (status!=AppStatus.RUNNING) or not status: print("Creating new app") h264= client.CreateApp("h264Stream") notifyCopyProcess= client.CreateApp("NotifyCopyProcess") notifyCopyProcess_client= xmlrpclib.ServerProxy("http://%s:%s/" % (ip,port) + str(notifyCopyProcess)) print h264, client.GetAppInstances() h264_client= xmlrpclib.ServerProxy("http://%s:%s/" % (ip,port) + str(h264)) h264_client.SetAppValue("auto_restart", 1) if options.dump: h264_client.SetAppValue("dumpfolder", options.dump) else: h264_client.SetAppValue("dumpfolder", "/home/recode/dump") h264_client.StartApp() else: print("Stoping stream") client.DestroyInstance(h264) client.DestroyInstance(notifyCopyProcess) continue while h264_client.GetAppRunStatus()!=AppStatus.RUNNING: print "here" sleep(.5) print("Next code") client.DestroyInstances() pylirc.exit()
players = [] notDone = True i = 1 while notDone: name = raw_input('Enter player %i name: '%i) if name == '': confirm = raw_input('Please confirm (y/n) ') if confirm == 'y': notDone = False else: player = {'name':name, 'score':0} players.append(player) i = i + 1 roundd = 1 sockid = pylirc.init('any') pygame.init() displayInfo = pygame.display.Info() width = displayInfo.current_w height = displayInfo.current_h buttonDelay = 0.01 screen = pygame.display.set_mode([width,height], pygame.FULLSCREEN) pygame.mouse.set_visible(0) screen.fill([255, 255, 255]) pygame.display.flip() font = pygame.font.Font(None, 100) scoreFont = pygame.font.Font(None, 50)
def __init__(self, app, conf): if not pylirc.init(app, conf, 1): raise Exception("Unable to init pylirc"); pylirc.blocking(0)
def setup(): global state GPIO.setmode(GPIO.BOARD) GPIO.setup(STERO, GPIO.OUT) pylirc.init("pylirc", "./conf", blocking)
def run(self): global code print "IRRrec awaits IR commands" if (select.select([self.lirchandle], [], [], 6) == ([], [], [])): print "IRRrec timed out" else: s = pylirc.nextcode() if (s): # Print all the configs... for code in s: print code lirchandle = pylirc.init("pylirc", "./conf", blocking) if (lirchandle): print "Succesfully opened lirc, handle is " + str(lirchandle) tim = Timer() tim.start() irrec = IRRec(lirchandle) irrec.start() code = "" while (code != "quit"): if (irrec.isAlive() == 0): irrec = IRRec(lirchandle)
# Revision 1.7 2003/02/22 22:12:40 mccabe # Testprogram to test pylirc in multiple threads # # Revision 1.6 2002/12/21 20:30:26 mccabe # Added id and log entries to most files # import pylirc, time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) blocking = 0 # if pylirc.init("pylirc", "./conf", blocking): code = {"config": ""} while code["config"] != "quit": # Very intuitive indeed if not blocking: print "." # Delay... time.sleep(1) # Read next code s = pylirc.nextcode(1) # Loop as long as there are more on the queue