Example #1
1
import lirc

sockid = lirc.init("dashboard")
print(lirc.nextcode())
lirc.deinit()
Example #2
0
def coletar_digitos(mensagem):
    lcd.clear()
    lcd.message(mensagem + "\n")
    codigo = nextcode()
    senha = ""
    while codigo != ["KEY_OK"]:
        if codigo != []:
            if codigo[0][-1] in "01234356789":
                senha += codigo[0][-1]
                lcd.message("*")
        codigo = nextcode()
    return senha
Example #3
0
    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 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)
Example #5
0
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()
Example #6
0
    def main_loop(self, lirc_socket=None):
        # Hide mouse cursor
        pygame.mouse.set_visible(False)

        clear = self.screen.copy()
        clear.fill((0, 0, 0))

        self.hw.enable_screen(True)

        while self.running:
            mode = self.modes[self.current_mode]

            for event in pygame.event.get():
                self.process_event(event)
                mode.process_event(event)
            if lirc_socket:
                keys = lirc.nextcode()
                if keys:
                    event = self.lirc2pygame(keys)
                    if event:
                        self.process_event(event)
                        mode.process_event(event)

            if self.standby:
                self.clock.tick(5)
            else:
                self.screen.blit(clear, (0, 0))
                mode.loop(self.screen)
                pygame.display.flip()

                self.clock.tick(mode.preferred_fps())
                pygame.display.set_caption("fps: %.2f" % self.clock.get_fps())
Example #7
0
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)
Example #8
0
    def start(self):
        while True:
            c = lirc.nextcode()

            if len(c) != 0:
                self.current['dockSignal']['time'] = time.time()

                if c[0] == "power":
                    # consider sending Shutdown here
                    break
                if c[0] == "left_signal":
                    self.current['dockSignal']['left'] = 1
                elif c[0] == "right_signal":
                    self.current['dockSignal']['right'] = 1
                self.subscriber(self.current)
            else:
                t = time.time()
                if t - self.current['dockSignal']['time'] > self.timeToLive:
                    if self.current['dockSignal']['left'] == 1 or \
                            self.current['dockSignal']['right'] == 1:
                        self.current['dockSignal']['time'] = time.time()
                        self.current['dockSignal']['left'] = 0
                        self.current['dockSignal']['right'] = 0
                        self.subscriber(self.current)

            time.sleep(self.sampleInterval)

        lirc.deinit()
        return
Example #9
0
def process_code():
    last_code_time = time.time()
    while True:
        time.sleep(0.2)

        code = lirc.nextcode()

        if not code:
            continue

        press_count = count_presses()

        # Power all on
        if press_count is 1:
            log_and_print("Powering on all!")
            power_tv()
            power_receiver()
            power_pc(True)

        # Power all off
        elif press_count is 2:
            log_and_print("Powering off all!")
            power_tv()
            power_receiver()
            power_pc(False)

        # Power only media PC
        elif press_count is 3:
            print("PC Power: ", check_pc_power())
            power_pc(not check_pc_power())
Example #10
0
 def processIRInput(self):
     if lircinstalled:
         i = lirc.nextcode()
         if len(i)>0:
             self.interpret(i[0])
     else:
         time.sleep(1)
Example #11
0
  def readIRCode(self):
    sockid = lirc.init("myprogram")
    print("Ready")

    while True:
      code = lirc.nextcode()
      if code: print(code[0])
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)
Example #13
0
	def run(self):
		while (True):
			code = lirc.nextcode()
			action = self.resolve_action(code)
			logger.info("Action: %s" % (action))
			if action != None:
				self.client.send_action(action)
Example #14
0
    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...")
Example #15
0
 def run(self):
     try:
         while (True):
             if (self.stopped()):
                 break
             list = lirc.nextcode()
             if len(list) != 0:
                 if list[0] == self.POWER:
                     self._on_power()
                 elif list[0] == self.INPUT:
                     self._on_menu()
                 elif list[0] == self.TREBLE_DOWN:
                     self._on_left()
                 elif list[0] == self.TREBLE_UP:
                     self._on_right()
                 elif list[0] == self.VOL_DOWN:
                     self._on_vol_down()
                 elif list[0] == self.VOL_UP:
                     self._on_vol_up()
                 elif list[0] == self.MUTE:
                     self._on_mute()
                 elif list[0] == self.BASS_DOWN:
                     self._on_preset(-1)
                 elif list[0] == self.BASS_UP:
                     self._on_preset(1)
             else:
                 time.sleep(0.1)
     except Exception as inst:
         logging.error(inst)
     lirc.deinit()
Example #16
0
 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]]()
Example #17
0
 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]]()
Example #18
0
 def key_pressed(self):
     key = None
     key = lirc.nextcode()
     if key is None:
         return False
     if len(key) == 0:
         return False
     return True
Example #19
0
def watch_ir_events(event_queue):
    """Waits for IR code events and places them on the event queue.

    :param event_queue: A queue to put events on.
    :type event_queue: :py:class:`multiprocessing.Queue`
    """
    while True:
        for ir_code in lirc.nextcode():
            event_queue.put(IREvent(ir_code))
Example #20
0
def watch_ir_events(event_queue):
    """Waits for IR code events and places them on the event queue.

    :param event_queue: A queue to put events on.
    :type event_queue: :py:class:`multiprocessing.Queue`
    """
    while True:
        for ir_code in lirc.nextcode():
            event_queue.put(IREvent(ir_code))
Example #21
0
    def test_nonblocking_nextcode(self):
        print("Don't press anything yet...")
        start_time = time.time()
        end_time = start_time + 1  # 1 second in the future
        pressed = False
        while not pressed and time.time() < end_time:
            if lirc.nextcode() == ["horses"]:
                pressed = True
        self.assertFalse(pressed)

        print("Press 1 on your remote.")
        start_time = time.time()
        end_time = start_time + 5  # 5 seconds in the future
        pressed = False
        while not pressed and time.time() < end_time:
            if lirc.nextcode() == ["horses"]:
                pressed = True
        self.assertTrue(pressed)
Example #22
0
def getIrKeyPress():
    while True:
        code = lirc.nextcode()
        if len(code) > 0:
            code = code[0]
            print(code)
            eel.getKeyPressed(code)
            if ( code == "key_ok"):
                break
Example #23
0
    def read_ir_code(self):

        code = lirc.nextcode()

        if len(code) > 0 and code[0] in self.events:
            return_code = str(code[0])
        else:
            return_code = None

        return return_code
 def run(self):
     print "Starting" + self.name
     while self.energy and self.signal:
         hit = lirc.nextcode()
         if not hit :
             print ("not hit")
         else :
             self.energy = self.energy - 10
             print ("hit: %s , energy: %d" % (hit , self.energy))
         time.sleep(0.2)
     print "Exiting" + self.name
Example #25
0
def LircDecode():
    #Init motor pin
    print "++++++Start run programe++++"
    Motors = HBridge(27, 22, 23, 24, 19, 26)
    Car = SmartCar(Motors)
    try:
        while True:
            codeIR = lirc.nextcode()
            if codeIR != []:
                Car.SmartCarAction(codeIR[0])
    except KeyboardInterrupt:
        Motors.exit()
Example #26
0
 def checkcodes(self, q):
     th = threading.currentThread()
     while getattr(th, "do_run", True):
         try:
             x = lirc.nextcode()
             y = ""
             for n in x:
                 y = x[0].encode('utf-8')
             q.put(y)
             time.sleep(.1)
         except KeyboardInterrupt:
             break
Example #27
0
def coletar_digitos(mensagem):
    lcd.clear()
    lcd.message(mensagem + "\n")
    senha = ""
    while True:
        codigo = nextcode()
        if codigo != []:
            if codigo[0] == "KEY_OK":
                return senha
            else:
                senha += codigo[0][-1]
                lcd.message("*")
Example #28
0
def LircDecode():
    #Init motor pin
    print "++++++Start run programe++++"
    Motors = HBridge(27, 22, 23, 24, 19, 26)
    Car = SmartCar(Motors)
    try :
        while True:
            codeIR = lirc.nextcode()
            if codeIR != []:
                Car.SmartCarAction(codeIR[0])
    except KeyboardInterrupt:
        Motors.exit()
Example #29
0
def alert(pixels):
    alertMode = True
    while alertMode:
        code = lirc.nextcode()
        if code != []:
            alertMode = False
        pixels.fill((255, 255, 255))
        pixels.show()
        time.sleep(1)
        pixels.fill((0, 0, 0))
        pixels.show()
        time.sleep(1)
def main_pub_cmd_vornado():

    try:
        while True:
            cmdArray = lirc.nextcode()
            # lirc sends an empty array when a button is held down
            # ignore those
            if len(cmdArray) > 0:
                sendCommand(cmdArray)

    except KeyboardInterrupt:
        print("Exit by KeyboardInterrupt\n")
Example #31
0
def armagedon(pixels):
    alertMode = True
    while alertMode:
        code = lirc.nextcode()
        if code != []:
            alertMode = False
        for i in range(255):
            pixels.fill((i, 0, 0))
            pixels.show()
        for i in range(255):
            pixels.fill((255 - i, 0, 0))
            pixels.show()
Example #32
0
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)
Example #33
0
    def MayUpdateTarget(self):
        button = lirc.nextcode()
        if not button:
            return
        button = str(button[0])

        if button != 'load' and button != 'save':
            self._long_press_time = None

        for target_name, target_parameter in self._target_parameters.iteritems(
        ):
            if target_name == button:
                self._current_target_name = button
                print 'Selected target %s.' % button
                return self._target_parameters[self._current_target_name]

        # If the target is set to sun, we do not need to check the rest of the method.
        if self._current_target_name == 'sun':
            return

        if button == 'up':
            self._target_parameters[
                self._current_target_name].pitch += np.deg2rad(self._rate)
            return self.GetTarget()
        elif button == 'down':
            self._target_parameters[
                self._current_target_name].pitch -= np.deg2rad(self._rate)
            return self.GetTarget()
        elif button == 'right':
            self._target_parameters[
                self._current_target_name].yaw -= np.deg2rad(self._rate)
            return self.GetTarget()
        elif button == 'left':
            self._target_parameters[
                self._current_target_name].yaw += np.deg2rad(self._rate)
            return self.GetTarget()
        elif button == 'slow':
            self._rate = 1
        elif button == 'medium':
            self._rate = 5
        elif button == 'fast':
            self._rate = 10
        elif button == 'save' or button == 'load':
            if self._long_press_time is None:
                self._long_press_time = time.time()
            if time.time() - self._long_press_time > 3:  # seconds
                if button == 'save':
                    self.SaveConfig(self._config_filename)
                else:
                    self._target_parameters = self.LoadConfig(
                        self._config_filename)
                self._long_press_time = None
Example #34
0
    def Update(self):

        # Take as many IR input as possible.
        irReceived = lirc.nextcode()

        for ir in irReceived:
            # If the IR code is not in the received array yet
            # then put there. After a new element appended into
            # the IR received array `sort()` the array alphabetically.
            irS = str(ir).upper()
            if irS != "[]" and not irS in self.irReceivedDuringInterval:
                self.irReceivedDuringInterval.append(irS)
                self.irReceivedDuringInterval.sort()
Example #35
0
 def run(self):
     
     # initially turn on the lights
     self.command_processor.process_command("gpio lights-on")
     while True:
         codes = lirc.nextcode()
         if codes:
             for code in codes:
                 try:
                     self.command_processor.process_command(code)
                 except:
                     e = sys.exc_info()[0]
                     traceback.print_exc()
def coletar_digitos(mensagem):
    lcd.clear()
    lcd.message(mensagem +"\n")
    digitos = ""
    while True:
        codigo = nextcode()
        if codigo != []:
            if codigo[0] == "KEY_OK":
                return digitos
            else:
                digitos += codigo[0][-1]
                lcd.message("*")
                buzzer.beep(n=1, on_time=0.25)
 def run(self):
     print "Starting" + self.name
     while self.signal:
         hit = lirc.nextcode()
         if not hit :
             print ("not hit")
         else :
             self.HP = self.HP - 10
             if self.HP < 0:
                 self.HP = 0;
             notifyBattleCarHP(self.HP)
             print ("hit: %s , HP: %d" % (hit , self.HP))
         time.sleep(0.2)
     print "Exiting" + self.name
Example #38
0
 def run(self):
     """Main loop of LIRC interface thread."""
     import lirc
     while not self.stopped.isSet():
         code = lirc.nextcode()  # list; empty if no buttons pressed
         # interpret result from python-lirc
         if code:
             code = code[0]
             _LOGGER.info('Got new LIRC code %s', code)
             self.hass.bus.fire(EVENT_IR_COMMAND_RECEIVED,
                                {BUTTON_NAME: code})
         else:
             time.sleep(0.2)
     _LOGGER.info('LIRC interface thread stopped')
Example #39
0
 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])
Example #40
0
def coletar_digitos(mensagem):
    lcd.clear()
    lcd.message(mensagem + "\n")
    resultado = ""
    while True:
        codigos = nextcode()
        if (codigos != []):
            tecla = codigos[0]

            if (tecla[-1] == "K"):
                return resultado
            lcd.message("*")
            resultado = resultado + tecla[-1]

    return resultado
Example #41
0
 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)
Example #42
0
def start():
    """
    start() method start the listener for IR input from remote
    controller.
    """
    while True:
        try:
            current = datetime.now().microsecond
            code = lirc.nextcode()
            print(code[0])
            if code and code[0] in available:
                getattr(commands,code[0])()
            else:
                print("invalid command")
        except:
            continue
Example #43
0
def main():
    loop = True
    try:
        while loop:
            code = lirc.nextcode()
            if len(code) == 0:
                continue

            if code[0] in g_keypress_mappings:
                g_keypress_mappings[code[0]](code[0])
            else:
                print "Unknown command %s" % (code[0])
    except KeyboardInterrupt:
        print "Received keyboard interrupt..."
    finally:
        lirc.deinit()  # free up resources
Example #44
0
def main():
    loop = True
    try:
        while loop:
            code = lirc.nextcode()
            if len(code) == 0:
                continue

            if code[0] in g_keypress_mappings:
                g_keypress_mappings[code[0]](code[0])
            else:
                print "Unknown command %s"%(code[0])
    except KeyboardInterrupt:
        print "Received keyboard interrupt..."
    finally:
        lirc.deinit() # free up resources
Example #45
0
    def run(self):
        while True:

            codeIR = lirc.nextcode()
            if codeIR:
                event = codeIR[0]

                if event == LircEvents.KEY_POWER:
                    Register.EXIT_FLAG = True
                else:
                    Register.LIRC_EVENTS = event
                    #Helpers.log("dodanie lirc event : " + event)

            if Register.EXIT_FLAG:
                break
            time.sleep(0.05)
Example #46
0
 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()
Example #47
0
    def proccedEvent(self, event, isOnline):
        try:
###########################################################################
            if sys.platform == "linux":  # Only for Raspberry Pi
                code = lirc.nextcode()
            else:
                code = []
###########################################################################
            if len(code) == 0:
                return
            keyCode = code[0]
            if keyCode not in self._list:
                return
            values = self._list[keyCode].split(",")
            self._moduleList[values[0]].execute()

        except Exception as ex:
            self._logger.exception(ex)
Example #48
0
    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()
Example #49
0
 def run(self):
     """Run the loop of the LIRC interface thread."""
     import lirc
     _LOGGER.debug("LIRC interface thread started")
     while not self.stopped.isSet():
         try:
             code = lirc.nextcode()  # list; empty if no buttons pressed
         except lirc.NextCodeError:
             _LOGGER.warning("Error reading next code from LIRC")
             code = None
         # interpret result from python-lirc
         if code:
             code = code[0]
             _LOGGER.info("Got new LIRC code %s", code)
             self.hass.bus.fire(
                 EVENT_IR_COMMAND_RECEIVED, {BUTTON_NAME: code})
         else:
             time.sleep(0.2)
     lirc.deinit()
     _LOGGER.debug('LIRC interface thread stopped')
Example #50
0
def count_presses():
    press_start_time = time.time()
    press_end_time = time.time()
    counting = True
    log_and_print("Counting...")

    press_count = 1

    while counting:
        time.sleep(0.1)
        code = lirc.nextcode()
        if code:
            press_end_time = time.time()
            press_count += 1
            log_and_print("  Presses: " + str(press_count))
        elif time.time() - press_end_time > repeat_time:
            log_and_print("  Done.")
            counting = False

    log_and_print("Press count: " + str(press_count))
    return press_count
Example #51
0
def LircDecode():
    try :
        while True:
            codeIR = lirc.nextcode()
            if codeIR != []:
                if codeIR[0] == "KEY_UP":
                    print 'The car speed add 0.1'
                elif codeIR[0] == "KEY_DOWN":
                    print 'The car speed sub 0.1'
                elif codeIR[0] == "KEY_STOP":
                    print 'The car stop move'
                elif codeIR[0] == "KEY_START":
                    print 'The car start move '
                elif codeIR[0] == "KEY_GOTO":
                    print 'The car forward'
                elif codeIR[0] == "KEY_BACK":
                    print 'The car back'
                elif codeIR[0] == "KEY_LEFT":
                    print 'The car left'
                elif codeIR[0] == "KEY_RIGHT":
                    print 'The car right'
    except KeyboardInterrupt:
        Motors.exit()
Example #52
0
import lirc
sockid = lirc.init("python_remote")

while True:
    code = lirc.nextcode()
    if code:
        print(code[0])
        if code[0] == "KEY_POWER":
            break


Example #53
0
import lirc

sockid = lirc.init("myprogram")
# lirc.load_config_file("/root/lircd.conf")
lirc.nextcode()  # press 1 on remote after this
lirc.deinit()
Example #54
0
import lirc
import os
from time import sleep

sockid = lirc.init("myprogram")
flip = False
while(True):
	lirc.nextcode()
	sleep(1)
	if(flip == False):
		os.system('touch hooks/start_record')
		print "Working"
		flip = True
	else:
		os.system('touch hooks/stop_record')
		print "Stopping"
		flip = False
#!/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
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()
                continue

            if power_off:
                # If power is off then do not serve any command
                # and continue polling
                continue

            # program control will reach here only is power is on.
Example #57
0
				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:
					s.sensorupdate({'read_ir':""})

		# CREATE FOLDER TO SAVE PHOTOS IN
Example #58
0
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