import lirc sockid = lirc.init("dashboard") print(lirc.nextcode()) lirc.deinit()
def __init__(self, the_queue): threading.Thread.__init__(self) print("LircInterface init") self.daemon = True self.stopped = threading.Event() self.the_queue = the_queue lirc.init('pyqtradio', blocking=False)
def cluc_game(message, *something): #Initialize lirc lirc.init("test05", blocking = False) disp_test01.print_disp("READY?","LEVEL 3") while True: codeIR = lirc.nextcode() if(codeIR != [] and codeIR[0] == "PLAY"): disp_test01.print_disp("GAME START!","") lirc.deinit() time.sleep(1) total_Number = 0 for i in range(8): disp_Number = random.randint(1,100) total_Number = total_Number + disp_Number disp_test01.print_disp(str(disp_Number),"") time.sleep(0.7) disp_test01.print_disp("","") file = open('/home/pi/teamB/SLACK_BOT_QUIZ.txt', 'w') #書き込みモードでオープン file.write(str(total_Number)) message.send("答えを入力してください") break else: time.sleep(3)
def lirc_listener_thread(self): """ Listen to infrared commands """ try: import lirc except ImportError: self.logger.warning("Unable to import module \"lirc\". " "If you want infrared remote control, " "please install \"python-lirc\".") else: try: from .lirc_config import get_lircrc_filename lirc.init("caissa", get_lircrc_filename(), blocking=False) except lirc.InitError: self.logger.warning("Exception occurred while trying to " "initialize infrared listener thread") else: import time while True: code_list = lirc.nextcode() for code in code_list: key_name = code.split(",")[0].strip() # add input event to queue self.event_queue.put(InfraredInputEvent(key_name)) time.sleep(0.05)
def activate(self): """When activated the :class:`IREventListener` will run callbacks associated with IR codes. """ lirc.init(self.prog, self.lircrc) self.dispatcher.start() self.detector.start()
def run(self): while True: version = 0 try: time.sleep(1) t0 = time.monotonic() import lirc as LIRC self.LIRC = LIRC version = 2 print('have lirc for remote control', time.monotonic()-t0) except Exception as e: print('failed to load lirc', e) try: import pylirc as LIRC self.LIRC = LIRC version = 1 print('have old lirc for remote control') except Exception as e: print('no lirc available', e) try: if version == 1: LIRC.init('pypilot') break elif version == 2: self.lircd = LIRC.RawConnection() break except Exception as e: print('failed to initialize lirc. is .lircrc missing?', e) time.sleep(2) self.version = version
def cluc_game(level): #Initialize lirc lirc.init("test05", blocking = False) disp_util.print_disp("READY?","LEVEL "+level) while True: codeIR = lirc.nextcode() # PLAYを押すと処理を開始する if(codeIR != [] and codeIR[0] == "PLAY"): disp_util.print_disp("GAME START!","") lirc.deinit() time.sleep(1) total_Number = 0 # 数字をランダムで数回表示し、その値を合算する for i in range(int(level)+2): disp_Number = random.randint(1,int(level)*int(level)*int(level)+8) total_Number = total_Number + disp_Number disp_util.print_disp(str(disp_Number),"") time.sleep(1.3-0.01*int(level)*int(level)) disp_util.print_disp("","") disp_util.print_disp("","") return str(total_Number) else: time.sleep(1)
def main(): while True: try: print("LIRC Init:") lirc.init(lirc_client) print("Find Sonos:") get_sonos(True) while True: print("Waiting for IR press") codes = lirc.nextcode() print("Got code: ", codes) for code in codes: print("Key press: ", code) if code in switcher.keys(): func = switcher.get(code) func() except Exception as e: print("Exception:") print(e) pass lirc.deinit()
def resp_aplha(message, *something): lirc.init("test05", blocking=False) chat_message, TEMP_DATA.context_info, TEMP_DATA.mode_info = chat.main( message.body['text'], None, None) print(message.body['ts']) print(message.body['channel']) print(message.body['text']) #re_message = slacker.chat.post_message(message.body['channel'], 'テストメッセージ', as_user=True) re_message = slacker.chat.post_message(message.body['channel'], 'テストメッセージ', as_user=True, attachments=attachments_json) #message.send(chat_message) print(re_message.body['ts']) #slacker.chat.update(message.body['channel'], re_message.body['ts'], 'やっぱり言うのやめた') subprocess.call('/home/pi/aquestalkpi/AquesTalkPi "' + chat_message + '" | aplay', shell=True)
def run(self): with tempfile.NamedTemporaryFile() as f: self._generate_lircrc(f) lirc.init(self._name, f.name) while True: x = lirc.nextcode() if x: self._endpoints[x[0]]()
def resp_gamma(message, *something): lirc.init("test05", blocking=False) chat_message = qaChat.main(message.body['text']) print(message.body['text']) message.send(chat_message) subprocess.call('/home/pi/aquestalkpi/AquesTalkPi "' + chat_message + '" | aplay', shell=True)
def resp_beta(message, *something): lirc.init("test05", blocking=False) chat_message, TEMP_DATA.context_info, TEMP_DATA.mode_info = chat.main( message.body['text'], TEMP_DATA.context_info, TEMP_DATA.mode_info) print(message.body['text']) message.send(chat_message) subprocess.call('/home/pi/aquestalkpi/AquesTalkPi "' + chat_message + '" | aplay', shell=True)
def __init__(self, client, identifier): lirc.init(identifier) self.client = client self.mapping = { 'KEY_PLAY' : 'play', 'KEY_PAUSE' : 'pause', 'KEY_NEXT' : 'next', 'KEY_PREVIOUS' : 'previous', 'KEY_STOP' : 'stop' }
def __init__(self, user_target_name, config_filename=_TARGET_PARAMETERS_CONFIG_FILENAME): if user_target_name is None: self._current_target_name = 'idle' else: self._current_target_name = user_target_name lirc.init('petitsoleil', blocking=False) self._rate = 5 self._config_filename = config_filename self._target_parameters = self.LoadConfig(self._config_filename) self._long_press_time = None
def main(): # now just write the code you would use in a real Raspberry Pi from Adafruit_CharLCD import Adafruit_CharLCD from gpiozero import Buzzer, LED, PWMLED, Button, DistanceSensor, LightSensor, MotionSensor from lirc import init, nextcode from py_irsend.irsend import send_once from time import sleep def show_sensor_values(): lcd.clear() lcd.message( "Distance: %.2fm\nLight: %d%%" % (distance_sensor.distance, light_sensor.value * 100) ) def send_infrared(): send_once("TV", ["KEY_4", "KEY_2", "KEY_OK"]) lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2) buzzer = Buzzer(16) led1 = LED(21) led2 = LED(22) led3 = LED(23) led4 = LED(24) led5 = PWMLED(25) led5.pulse() button1 = Button(11) button2 = Button(12) button3 = Button(13) button4 = Button(14) button1.when_pressed = led1.toggle button2.when_pressed = buzzer.on button2.when_released = buzzer.off button3.when_pressed = show_sensor_values button4.when_pressed = send_infrared distance_sensor = DistanceSensor(trigger=17, echo=18) light_sensor = LightSensor(8) motion_sensor = MotionSensor(27) motion_sensor.when_motion = led2.on motion_sensor.when_no_motion = led2.off init("default") while True: code = nextcode() if code != []: key = code[0] lcd.clear() lcd.message(key + "\nwas pressed!") sleep(0.2)
def start_listening(self): logger.info('Using lircrc.conf: %s', os.path.join(BASE_DIR, 'lircrc.conf')) lirc.init('mpc_lirc', os.path.join(BASE_DIR, 'lircrc.conf')) logger.info('Ready to receive key events.') while True: try: received = lirc.nextcode() except Exception as e: logger.warning('lirc: Failed to get next code: %s', e) time.sleep(3) else: if received: self.play_sound('received') self.key_pressed(received[0])
def cluc_game(message, *something): #Initialize lirc lirc.init("test05", blocking = False) chat.main() while True: if(str(message.body['text']) == 'お話終わり'): break else: # resp = chat.send_and_get(message) resp = chat.send_and_get(str(message.body['text'])) # print('Enemy : %s'%(resp)) message.send('Enemy : %s'%(resp))
def __init__(self, mainradiosystem): self.m = mainradiosystem src.logger.logInfo("Initializing IRInterface...") if lircinstalled: try: lirc.init(src.configs.Config.configDict["LIRC_CONFIG_PROGRAM_NAME"], src.configs.Config.configDict["LIRC_CONFIG_FILE"]) except AttributeError: src.logger.logFError("Module 'lirc' has no attribute 'init'. Please install latest version from: https://pypi.python.org/pypi/python-lirc/") src.logger.logFError("IRInterface initialization failed.") mainradiosystem.shutdown() self.counter = 3 self.channel = "" self.numkeys = ["key-zero","key-one","key-two","key-three","key-four","key-five","key-six","key-seven","key-eight","key-nine"] src.logger.logOk("IRInterface initialized.")
def init(self, modList): """Initializes (initialize internal variables)""" # Загружаем настройки section = self._setting.Configuration["IRBlock"] self._list = dict() for keyCode in section: self._list[keyCode.upper()] = section.get(keyCode) with open(CONFIG_FILE_NMAE, "w", encoding="utf-8") as file: for keyCode in self._list.keys(): file.write("begin\n\tprog={1}\n\tbutton={0}\n\tconfig={0}\n\trepeat=0\nend\n".format(keyCode, PROG_NAME)) self._moduleList = modList ########################################################################### if sys.platform == "linux": # Only for Raspberry Pi lirc.init(PROG_NAME, CONFIG_FILE_NMAE, blocking=False)
def __init__(self, ir_receiver_enabled, on_power, on_menu, on_left, on_right, on_vol_down, on_vol_up, on_mute, on_preset): super(IrReceiver, self).__init__() lirc.init(self.PROGRAM_NAME, blocking=False) self._on_power = on_power self._on_menu = on_menu self._on_left = on_left self._on_right = on_right self._on_vol_down = on_vol_down self._on_vol_up = on_vol_up self._on_mute = on_mute self._on_preset = on_preset if (ir_receiver_enabled): super(IrReceiver, self).start()
def run(self): """Loop until main wants to exit.""" # try: import lirc self.main.log.write(log.MESSAGE, "[THREAD] Lirc socket starting...") conf = self.main.settings.defvars['PYBLASTER_LIRC_CONF'] self.lircsock = lirc.init("pyblaster2", conf, blocking=False) while self.main.keep_run: # Nonblocking receive of IR signals read = lirc.nextcode() if len(read): self.queue_lock.acquire() self.queue.put(read[0]) self.queue_lock.release() time.sleep(0.05) # read each 50 ms lirc.deinit() self.main.log.write(log.MESSAGE, "[THREAD] Lirc socket leaving...")
def listen(self): if self.remote_led > 0: GPIO.setup(self.remote_led, GPIO.OUT) try: socket_name = config.getSocketName() sockid = lirc.init(socket_name, lircrc) print "Listener on socket " + str(socket) + " established" #Listen loop while True: nextcode = lirc.nextcode() if len(nextcode) > 0: if self.remote_led > 0: GPIO.output(self.remote_led, True) button = nextcode[0] self.callback(button) if self.remote_led > 0: time.sleep(0.1) GPIO.output(self.remote_led, False) except Exception as e: print str(e) mesg = "Possible configuration error, check /etc/lirc/lircd.conf" print mesg mesg = "Activation IR Remote Control failed - Exiting" print mesg sys.exit(1)
def readIRCode(self): sockid = lirc.init("myprogram") print("Ready") while True: code = lirc.nextcode() if code: print(code[0])
def __init__(self, screen_size=(1280, 720), framerate=30): pygame.init() if config.LIRC: lirc.init() #self.screen = pygame.display.set_mode(screen_size, pygame.FULLSCREEN|pygame.HWSURFACE|pygame.DOUBLEBUF) self.screen = pygame.display.set_mode(screen_size, pygame.NOFRAME) pygame.mouse.set_visible(0) #self.screen = pygame.display.set_mode(screen_size) self.clock = pygame.time.Clock() self.running = True self.current_page = None self.framerate = framerate self.tick_counter = 0 self.tick_interval = 1000 #: Interval at which to call self.tick() # Screensaver counters self.screensaver_timer = 0
def setup(hass, config): """Set up the LIRC capability.""" # blocking=True gives unexpected behavior (multiple responses for 1 press) # also by not blocking, we allow hass to shut down the thread gracefully # on exit. lirc.init("home-assistant", blocking=False) lirc_interface = LircInterface(hass) def _start_lirc(_event): lirc_interface.start() def _stop_lirc(_event): lirc_interface.stopped.set() hass.bus.listen_once(EVENT_HOMEASSISTANT_START, _start_lirc) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _stop_lirc) return True
def setup(opp, config): """Set up the LIRC capability.""" # blocking=True gives unexpected behavior (multiple responses for 1 press) # also by not blocking, we allow opp to shut down the thread gracefully # on exit. lirc.init("openpeerpower", blocking=False) lirc_interface = LircInterface(opp) def _start_lirc(_event): lirc_interface.start() def _stop_lirc(_event): lirc_interface.stopped.set() opp.bus.listen_once(EVENT_OPENPEERPOWER_START, _start_lirc) opp.bus.listen_once(EVENT_OPENPEERPOWER_STOP, _stop_lirc) return True
def __init__(self, robot=None, robot_url=None, user=None, token=None): super(DockSignal, self).__init__(robot, robot_url, user, token) self.sockid = lirc.init(robot, blocking=False) self.sampleInterval = 0.1 self.timeToLive = 1.5 self.stop = False self.current = {"dockSignal": {"left": 0, "right": 0, "time": 0}} self.setAuthToken(user, apitoken) print("\tdocksignal URL: {}".format(robot_url))
def setup(hass, config): """Set up the LIRC capability.""" import lirc # blocking=True gives unexpected behavior (multiple responses for 1 press) # also by not blocking, we allow hass to shut down the thread gracefully # on exit. lirc.init('home-assistant', blocking=False) lirc_interface = LircInterface(hass) def _start_lirc(_event): lirc_interface.start() def _stop_lirc(_event): lirc_interface.stopped.set() hass.bus.listen_once(EVENT_HOMEASSISTANT_START, _start_lirc) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _stop_lirc) return True
def __init__(self, host="localhost", port=5555): self.host = host self.port = port self.addr = "tcp://%s:%s" % (self.host, self.port) # Events that can be read from lirc configuration file self.events = [ "KEY_RIGHT", "KEY_LEFT", "KEY_UP", "KEY_DOWN", "KEY_STOP", "KEY_ENTER", "KEY_PLAYPAUSE" ] self.zmq_context = zmq.Context() self.socket = self.zmq_context.socket(zmq.PUSH) self.socket.connect(self.addr) # Initialize lirc lirc.init("ledmatrix", LIRC_CONFIG_FILE, blocking=False) log.info("Initialized IR Remote")
def __init__(self, system, config, window): if config.get().getboolean('Remote', 'UseLirc', fallback=False): print('Initialise IR remote ... ', end='') sockid = lirc.init(config.get().get('Remote', 'LircProgramName'), blocking=False, verbose=True) self.system = system self.config = config self.window = window self.player = 0 thread = Thread(target=self.run) thread.start() print('OK')
def __init__(self, configFile="conf/HtRoomControl.conf"): # read the configuration file self.config = ConfigParser.ConfigParser() self.config.read(configFile) self.program_name = self.config.get(_lirc_section, "program") self.lirc_config = self.config.get(_lirc_section, "config") self.command_processor = CommandProcessor.CommandProcessor(self.config) # initialize this lirc Client self.sock_id = lirc.init(self.program_name, self.lirc_config)
def main(): lirc.init("ledsign") parent_pipe, child_pipe = Pipe() remote_event = Event() param_event = Event() LED = LEDController() context = LEDContext(param_event, remote_event, child_pipe) p = Process(target=LED.process, args=(context, )) p.daemon = False p.start() # time.sleep(2) print('starting IR') while 1: c = get_input(False) if len(c) > 0: cmd = c[0] print(c[0], 'IR process') # if cmd == 'up' or cmd == 'down' or cmd == 'left' or cmd == 'right' or cmd == 'vol_up' or cmd == 'vol_down' or cmd == 'back': print('setting p') context.param_event.set() else: context.remote_event.set() parent_pipe.send(cmd) # if cmd == 'restart': # break # time.sleep(0.02) p.join()
def __init__(self, _threadName, _array, _iDB): # Restart LIRC service. # This is very important. subp.call([ "sudo /etc/init.d/lirc stop && timeout 2s mode2 -d /dev/lirc0 & wait && sudo /etc/init.d/lirc restart" ], shell=True) _array.append(self) mt.__init__(self, _array.index(self) + 1, _array.index(self) + 1, _threadName) self.iDB = _iDB self.MODULE_NAME = "ir" self.irReceivedDuringInterval = [ ] # Array for buffering incoming IR within the specified interval (default 1 second). self.tSC = tsc() # Timer for interval and database. lirc.init("pysoc", blocking=False)
def cluc_game_anser(anser): user_anser = "" regex = r'[0-9]' #Initialize lirc lirc.init("test05", blocking = False) disp_util.print_disp("Input Anser","") while True: codeIR = lirc.nextcode() # リモコンのボタンが押された場合 if codeIR != []: pattern = re.compile(regex) # PLAYが押された場合入力モードを終了する if str(codeIR[0]) == "PLAY": break # 1つ前の文字を削除する elif str(codeIR[0]) == "prev": if len(user_anser) != 0: user_anser = str(user_anser[0:len(user_anser)-1]) # 入力された文字を表示する elif re.match(regex, str(codeIR[0])): user_anser += str(codeIR[0]) disp_util.print_disp("Input Anser",user_anser) else: time.sleep(1) # ユーザの入力した値と答えが一致の場合、正解の表示をする if(user_anser == anser): disp_util.print_disp("Correct Answer", "Congratulations!") # ユーザの入力した値と答えが不一致の場合、不正解の表示をする else: disp_util.print_disp("Incorrect Answer", "Anser is "+anser)
def run(self): sockid = lirc.init("myprogram", "./pylircrc") ex = 0 while ex == 0: code = lirc.nextcode() if len(code) > 0: c = code[0] if c == "1": exiting = 1 ex = 1 elif c == "2": exiting = 1 ex = 1 elif c == "3": exiting = 1 ex = 1
def loop(self): try: sockid = lirc.init("mediacontroller", self.lircrc) except lirc.InitError: logging.error( 'Failed to initialize LIRC, from section [{}]'.format( self.section ) ) raise StopPlugin lirc.set_blocking(False, sockid) while True: code = lirc.nextcode()[0] if code: self.send(code[0]) time.sleep(0.1)
def IRControl(self): sockid = lirc.init("robot_ir", "lircrc") dist_per_leypress = 30.0 #cm while True: #self.motor.stop() code = lirc.nextcode()[0] print(code) if code == "FORWARD": self.motor.forward() time.sleep(dist_per_leypress / self.motor.DIST_PER_SEC) self.motor.stop() elif code == "LEFT_FORWARD": # 30 degree turn left, then stop self.motor.forwardRight() time.sleep(self.motor.SEC_PER_TURN / 360.0 * 30.0) self.motor.stop() elif code == "RIGHT_FORWARD": # 30 degree turn right, then stop self.motor.forwardLeft() time.sleep(self.motor.SEC_PER_TURN / 360.0 * 30.0) self.motor.stop() elif code == "LEFT": self.motor.forwardRight() time.sleep(self.motor.SEC_PER_TURN / 360.0 * 90.0) self.motor.stop() elif code == "RIGHT": self.motor.forwardLeft() time.sleep(self.motor.SEC_PER_TURN / 360.0 * 90.0) self.motor.stop() elif code == "BACKWARD": self.motor.backward() time.sleep(dist_per_leypress / self.motor.DIST_PER_SEC) self.motor.stop() elif code == "LEFT_BACKWARD": # 30 degree turn left back, then stop self.motor.backwardRight() time.sleep(self.motor.SEC_PER_TURN / 360.0 * 30.0) self.motor.stop() elif code == "RIGHT_BACKWARD": # 30 degree turn right back, then stop self.motor.backwardLeft() time.sleep(self.motor.SEC_PER_TURN / 360.0 * 30.0) self.motor.stop() elif code == "STOP": self.motor.stop() elif code == "LINE_FOLLOW_ON": self.lineFollowModeOn()
def main(fullscreen): pygame.init() lirc_socket = None if HAS_LIRC: lirc_socket = lirc.init("pySmartMirror", config_filename=os.path.join(assets_path, "lircrc"), blocking=False) ml = MainLoop(fullscreen=fullscreen) try: ml.main_loop(lirc_socket) finally: if HAS_LIRC: lirc.deinit() ml.hw.deinit() for m in ml.modes: m.deinit() pygame.quit()
def run(self): """ """ #if not self.main.settings.use_lirc: # return self.lircsock = lirc.init("pyblaster", "/root/.lircrc", blocking=False) while self.main.keep_run: read = lirc.nextcode() if len(read): self.queue_lock.acquire() self.queue.put(read[0]) self.queue_lock.release() time.sleep(0.05) # read each 50 ms lirc.deinit()
#!/usr/bin/python import lirc import subprocess from mpd import MPDClient camuma_id ="" sockid = lirc.init("camuma","/home/pi/camuma_lircrc") #lirc.load_config_file("/home/pi/tst_lircd2.conf") print "Reading IR..." client = MPDClient() #client.timeout = 10 # network timeout in seconds (floats allowed), default: None client.idletimeout = None # timeout for fetching the result of the idle command is handled seperately, default: None client.connect("localhost", 6600) # connect to localhost:6600 print(client.mpd_version) # print the MPD version client.disconnect() while True: code = lirc.nextcode() print code #print "." + code[0] + "." try: button = code[0] print "Button " + button except: print "Not recognized..."
def __init__(self, option_config_json): sockid = lirc.init("MediaKraken")
r = GPIO.PWM(pin_r, 60) g = GPIO.PWM(pin_g, 60) b = GPIO.PWM(pin_b, 60) r.start(100) g.start(100) b.start(100) def show(pin, color): dc = 100 - color pin.ChangeDutyCycle(dc) sockid = lirc.init("RPi.RGB") change_r = 0 change_g = 0 change_b = 0 while 1: a = lirc.nextcode() if a == ["R_UP"]: change_r += 5 if (change_r >= 0) and (change_r <= 100): show(r, change_r) print("R=%d G=%d B=%d" % (change_r, change_g, change_b)) elif a == ["R_DOWN"]: change_r -= 5 if (change_r >= 0) and (change_r <= 100): show(r, change_r)
""" Tiny test program to get IR codes from the input Must have LIRC setup and configured on the machine Also must have a ~/lircrc file such as this to get any output from below begin button = KEY_1 prog = testir config = one end begin button = KEY_NEXT prog = testir config = next end http://www.lirc.org/html/configure.html#lircrc_format """ import lirc lirc.init("testir") while True: code = lirc.nextcode() print( code )
#!/usr/bin/python2 import lirc from gpiozero import Robot motor = False sockid = lirc.init("robot", "lirc/robot-lircrc", blocking=False) # Using the lircd interface... while True: codeIR = lirc.nextcode() if codeIR: print("Received (", len(codeIR), "):", codeIR[0]) motor = True elif motor == True: print("Stop motor") motor = False
import lirc import time import RPi.GPIO as GPIO print "Setting up GPIO" LED_PIN = 17 #ledje aanzetten GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) GPIO.output(LED_PIN, True) sockid = lirc.init("rcled", blocking=False) while True: try: button = lirc.nextcode() print("Press RC button , die geconfigureerd staat in etc/lirc/lircrc!") GPIO.output(LED_PIN, True) if len(button) == 0: continue print(button[0]) print (len(button)) GPIO.output(LED_PIN, False) time.sleep(1) except KeyboardInterrupt: lirc.deinit() break #file : etc/lirc/lircrc #begin # button = KEY_0 # prog = rcled
import lirc import time import os CMD_CHK_MPC_STATE="mpc | grep \"\[p\" | cut -d \" \" -f 1 | sed 's/\[//g' | sed 's/\]//g'" CMD_MPC_PAUSE="mpc pause" CMD_MPC_PLAY="mpc play" CMD_MPC_PREV="mpc prev" CMD_MPC_NEXT="mpc next" playing = False mpc_mode = False sockid = lirc.init("mpd_remote", blocking=False) def chk_playing_status(): global playing status = os.popen(CMD_CHK_MPC_STATE).read() if status == "playing": playing = True else : playing = False chk_playing_status() while True: try: button = lirc.nextcode() if len(button) == 0: continue if button[0] == "KEY_NEXT" and mpc_mode: chk_playing_status() if not playing: playing=True
#!/usr/bin/env python import lirc import pika import sys sockid = lirc.init("/home/pi/kidsLights/IR.py","/home/pi/.lircrc") #print("IR Ready") connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='ChangeLights',type='topic') routing_key = '*.colour' while True: #wait for button press - this will need changing to queue to accept non IR changes code = lirc.nextcode() #check if out of range try: message = code[0] except IndexError: message = '0 0 0' connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='ChangeLights',type='topic') routing_key = '*.colour' channel.basic_publish(exchange='changeLights',routing_key=routing_key,body=message) print(" [x] Sent %r:%r" % (routing_key, message)) # connection.close() if code: print(code[0])
try: line=scratch_line.line_sensor_val_scratch() except: if en_debug: e = sys.exc_info()[1] print "Error reading Line sensor: " + str(e) if en_debug: print "Line Sensor Readings: " + str(line) if en_gpg: s.sensorupdate({'line':line}) elif msg.lower()=="READ_IR".lower(): print "READ_IR!" if en_ir_sensor==0: import lirc sockid = lirc.init("keyes", blocking = False) en_ir_sensor=1 try: read_ir= lirc.nextcode() # press 1 if len(read_ir) !=0: print read_ir[0] except: if en_debug: e = sys.exc_info()[1] print "Error reading IR sensor: " + str(read_ir) if en_debug: print "IR Recv Reading: " + str(read_ir) if en_gpg: if len(read_ir) !=0: s.sensorupdate({'read_ir':read_ir[0]}) else:
import lirc sockid = lirc.init("myprogram") # lirc.load_config_file("/root/lircd.conf") lirc.nextcode() # press 1 on remote after this lirc.deinit()
import sys import os try: sys.path.append(os.environ['HOME_BA']) except: print("error in HOME_BA environment variable") from bande_annonce import env_variables from bande_annonce.scripts import launch_automatic_ba, stop_and_shutdown, stop_automatic_ba from time import sleep import logging import logging.config logging.config.dictConfig(env_variables.LOGGING) import lirc lirc.init('telecommande', blocking=False) while True: ircode = lirc.nextcode() print(ircode) if len(ircode) != 0: if ircode[0] == 'play': print("PLAY") logging.info('play_ba depuis appui play / ok telecommande') logging.info("env_variables.lock.locked = %s" % env_variables.lock.locked()) if not env_variables.lock.locked(): launch_automatic_ba.main() elif ircode[0] == 'stop': print("STOP") logging.info('stop_ba depuis appui stop / ok telecommande') stop_automatic_ba.main()
#Картинки взяты отсюда: http://www.oocities.org/wraithfivexwing/asciiart/asciisouthpark.txt ############### ## Для работы этого скрипта надо сначала установить модуль lirc: sudo apt install python3-lirc ## И надо иметь корректные настройки самого lircd, lircrc ## За подробностями: ############### import lirc print("Данная программа демонстрирует работу lirc в связке с Python") print("Подключаемся к lirc...") socket = lirc.init("num") print("Сокет: {0}".format(socket)) counter = 0 print("У тебя {0} очков. Набей сто очков, нажимая цифровые клавиши.".format(counter)) while (counter < 100): answer = lirc.nextcode() if (len(answer) > 0): counter = counter + int(answer[0]) print ("Ты нажал {0}, твой счёт {1}".format(answer[0], str(counter))) lirc.deinit() print ("Отлично! Ты набил {0} очков, теперь я жду нажатия ОК для выхода".format(counter))
import lirc sockid = lirc.init("myprog") print("Ready") while True: code = lirc.nextcode() if code: print(code[0])
import lirc sockid = lirc.init("python_remote") while True: code = lirc.nextcode() if code: print(code[0]) if code[0] == "KEY_POWER": break
import lirc sockid = lirc.init("testlirc") while True: code = lirc.nextcode() if (len(code)>0): print ("Button pressed is "+code[0]) else: print ("Unknown button")
import math import gtk import re import lirc #Rough theory of operation: #Process apps, get icons #Take background, Gauss. Blur it, add some white to make it stand out #Put original background on screen #Take chunks of blurred background as backdrops for icons #Allow user to select app with LIRC. #Start lirc listener lirc.init("lirclauncher","./lircrc") def pilToPygame(img): mode = img.mode size = img.size data = img.tobytes() return pygame.image.fromstring(data, size, mode) #this is used to get icons. icon_theme = gtk.icon_theme_get_default() #Import our list of apps. apps_complete=[] apps=[] settingsFile=open("settings.config")
global power_off power_off = False if power_off else True ############# # Main Code # ############# # Setup GPIO pins gpio_setup() # Load persisted data load_data() # Wait some time to start and let things settle down time.sleep(0.5) """ Create a connection to lirc """ sock_id = lirc.init("speaker_remote", blocking = False) # Once the connection is established, # continuously keep polling for any remote inputs print 'Turn power on to start' try: while True: # Keep looking for commands from remote control_type = lirc.nextcode() # If control type is non 0 (command received) then enter in, # else continue polling if control_type: control_type = control_type[0] if control_type == 'power': toggle_power()