Example #1
0
    def test_construction(self):
        """ 生成テスト """
        # 接続ピン
        PIN_LD = 23
        PIN_PR = 10

        # 周辺設定
        led = LED(PIN_LD)

        # 期待値
        valueLDExpctd = False # black

        # ターゲット生成
        photoref  = Button(PIN_PR,active_state=True,pull_up=None)

        # 接続
        led.source = photoref

        # 実際値
        valueLDActual = led.value

        # 評価
        try:
            self.assertEqual(valueLDActual,valueLDExpctd)
            sleep(0.1)
        finally:
            led.close()
            photoref.close()
Example #2
0
class RaspberryPiIO(AbstractIO):
    def __init__(self, camera: AbstractCamera, system: AbstractSystem,
                 config: Config):
        super().__init__(camera, system, config)
        self.button = Button(config['GPIO_SWITCH'], bounce_time=0.2)

    def start_monitoring(self):
        super().start_monitoring()
        self.button.when_pressed = self._start_recording_handler
        self.button.when_released = self._stop_recording_handler

        if self.button.is_pressed:
            self._camera.start_recording()

    def _start_recording_handler(self):
        self._camera.start_recording()

    def _stop_recording_handler(self):
        self._camera.stop_recording()
        sleep(1)
        self._system.halt_system()

    def close(self):
        super().close()
        self.button.close()
        self.button = None
Example #3
0
class PiPadButtons :

    # initialization
    def __init__(self) :

        # buttons
        log.debug("Initializing Buttons...")
        log.debug("> button 1 pin: " + str(_conf['btn1_pin']))
        self.btn1 = Button(_conf['btn1_pin'])
        log.debug("> button 2 pin: " + str(_conf['btn2_pin']))
        self.btn2 = Button(_conf['btn2_pin'])
        log.debug("...init done!")

    # is button 1 pressed ?
    def is_button1_pressed(self) :
        return self.btn1.is_pressed

    # is button 2 pressed ?
    def is_button2_pressed(self) :
        return self.btn2.is_pressed

    # terminate
    def terminate(self) :
        log.debug("Buttons termination...")
        self.btn1.close()
        self.btn2.close()
Example #4
0
class PitchKey():
    def __init__(self, port, synth, note):
        self.button = Button(port)
        self.device = synth
        self.note = note

    def check(self, val1, val2, val3):
        self.button.when_pressed = self.play(val1, val2, val3)
        self.button.when_released = self.stop

    def play(self, val1, val2, val3):
        if val1 == 1:
            self.device.noteon(self.note)
        if val2 == 1:
            self.device.noteon(self.note + 12)
        if val3 == 1:
            self.device.noteon(self.note + 24)

    def stop(self):
        self.device.noteoff(self.note)
        self.device.noteoff(self.note + 12)
        self.device.noteoff(self.note + 24)

    def close(self):
        self.button.close()
Example #5
0
class HardwareController(object):

    def __init__(self):

        self.button = Button(pin=BUTTON_PIN, hold_time=1, hold_repeat=True)
        self.status_led = LED(STATUS_LED_PIN)
        self.button_led = LED(BUTTON_LED_PIN)

        self.button.when_pressed = self.button_pressed
        self.button.when_released = self.button_released
        self.button.when_held = self.button_held
        self.hold_time = 0

        self.status_led.blink(on_time=0.1, off_time=0.1, n=5, background=False)
        self.status_led.on()

        return

    def close(self):

        self.button.close()
        self.button_led.close()
        self.status_led.close()

        return

    def button_held(self):

        logger.debug("button held")
        self.hold_time = self.button.active_time
        self.button_led.blink(on_time=0.25, off_time=0.1, n=1)

        return

    def button_pressed(self):

        logger.debug("button pressed")
        self.hold_time = 0

        return

    def button_released(self):

        increments = int(self.hold_time / BUTTON_HOLD_INCREMENTS)
        logger.debug("button released. Held for {0} increments".format(increments))

        if increments > 0:
            time.sleep(2)
            self.button_led.blink(on_time=0.5, off_time=0.5, n=increments, background=False)
            time.sleep(1)

            if increments == 1:
                logger.info("Shutdown called via button press")
                check_call(['sudo', 'poweroff'])
            elif increments == 2:
                logger.info("Reboot called via button press")
                check_call(['sudo', 'reboot'])

        return
class GoogleAIYVoicehat(MycroftSkill):
    def __init__(self):
        MycroftSkill.__init__(self)

    def initialize(self):
        self.time_held = 100
        self.short_press = 2
        self.button = Button(23, hold_time = 7)
        self.led = LED(25)
        self.schedule_repeating_event(self.handle_button, None, 0.01, 'buttonpress')

    def handle_button(self):
        self.button.when_pressed = self.start_timer
        self.button.when_held = self.graceful_exit
        self.button.when_released = self.stop_timer
        self.add_event('recognizer_loop:record_begin', self.handle_listener_started)
        self.add_event('recognizer_loop:record_end', self.handle_listener_ended)

    def start_timer(self):
        self.time_held = time.time()

    def stop_timer(self):
        self.time_held = time.time() - self.time_held
        if self.time_held < self.short_press:
            self.bus.emit(Message('mycroft.mic.listen'))
        elif self.time_held < self.button.hold_time:
            self.bus.emit(Message('mycroft.stop'))

    def handle_listener_started(self):
        self.led.on()

    def handle_listener_ended(self):
        self.led.off()

    # In truth, this is a not-so-graceful power down.
    # Emitting message 'system.shutdown' doesn't work on Picroft.
    def graceful_exit(self):
        self.blink()
        self.log.info('Forcing a linux shutdown ...')
        subprocess.call(['sudo', 'shutdown', '-h', 'now'])

    def blink(self):
        for i in range(6):
            self.led.toggle()
            time.sleep(0.5)

    def shutdown(self):
        self.cancel_scheduled_event('buttonpress')
        self.button.close()
        self.led.close()
Example #7
0
class Counter (threading.Thread):
    """ """
    def __init__ (self):
        threading.Thread.__init__(self)
        self.sender = Sender()
        self.last_pressed = datetime.now()
        self.button = Button(4)
        self.button.when_pressed = lambda: self.pressed()
        signal.signal(signal.SIGUSR1, lambda s, f: self.pressed())
        self._running = False

    def display (self):
        display.print(f"Rounds: {statistics.rounds}",
                      f"IP: {MyIP()}",
                      f"Time: {datetime.now().strftime('%H:%M:%S')}")

    def sound (self):
        subprocess.run(["mpg321", "-g 100", "-q", "gong.mp3"])
        subprocess.run(["mpg321", "-g 100", "-q", "applause3.mp3"])

    def pressed (self):
        if not statistics.started:
            Log("Not started.")
        elif (datetime.now()-self.last_pressed).seconds > 2:  # Debouncing
            self.last_pressed = datetime.now()
            statistics.rounds += 1

            # Have applause and updating data/csv in parallel #
            t = threading.Thread(name=f"thread-mpg321", target=self.sound)
            t.start()
            self.sender.send(Data())
            t.join()
        else:
            Log("Do not press button too fast!")

    def run (self):
        # Send initial data (0 rounds, 0 km) on start of program. #
        self.sender.send(Data())
        self._running = True
        while self._running:
            self.display()
            time.sleep(0.1)

        self.button.close()
        display.off()

    def stop (self):
        self._running = False
Example #8
0
class ActionPiIO(object):
    def __init__(self, camera, gpio):
        self.camera = camera
        self.button = Button(gpio)

    def start_monitoring(self):
        logging.info("Start monitoring GPIO {}".format(self.button.pin.number))
        self.button.when_pressed = self.camera.start_recording()
        self.button.when_released = self.camera.stop_recording()

        if self.button.is_pressed:
            self.camera.start_recording()

    def close(self):
        self.button.close()
        self.button = None
Example #9
0
class Switch(Device):
    def launch_function(self):
        if self.function:
            self.function(*self.args, **self.kwargs)

    def __init__(self,
                 input_pin,
                 function=None,
                 active_high=True,
                 *args,
                 **kwargs):
        if not Device.list_pin[input_pin]:
            self.function = function
            self.state = False
            Device.list_pin[input_pin] = True
            self.args = args
            self.kwargs = kwargs
            self.input_pin = input_pin
            self.button = Button(input_pin, pull_up=True)
            self.set_active_high(active_high)

        else:
            raise RuntimeError('pin already in use')

    def set_function(self, function, *args, **kwargs):
        self.function = function
        self.kwargs = kwargs
        self.args = args

    def set_active_high(self, active_high):
        if active_high:
            self.button.when_pressed = self.launch_function
            self.button.when_released = None
        else:
            self.button.when_pressed = None
            self.button.when_released = self.launch_function

    def close(self):
        Device.list_pin[self.input_pin] = False
        self.button.close()
Example #10
0
    def test_callback(self):
        """ コールバックテスト """
        # 接続ピン
        PIN_LD = 23
        PIN_PR = 10

        # 周辺設定
        led = LED(PIN_LD)

        # 期待値
        highLDExpctd = True # white
        lowLDExpctd = False # black

        # ターゲット生成
        photoref  = Button(PIN_PR,active_state=True,pull_up=None)
        photoref_pin = Device.pin_factory.pin(PIN_PR)

        # コールバック関数設定
        photoref.when_pressed = led.on
        photoref.when_released = led.off

        # Highでフォトリフレクタを駆動(白)
        photoref_pin.drive_high()
        sleep(0.1)
        highLDActual = led.value

        # Low でフォトリフレクタを駆動(黒)
        photoref_pin.drive_low()
        sleep(0.1)
        lowLDActual = led.value

        # 評価
        try:
            self.assertEqual(highLDActual,highLDExpctd)
            self.assertEqual(lowLDActual,lowLDExpctd)
            sleep(0.1)
        finally:
            led.close()
            photoref.close()
Example #11
0
class PowerButton():
    def __init__(self, port):
        self.button = Button(port)

    def check(self):
        self.button.when_pressed = self.warning()
        self.button.when_released = self.shutdown()

    def warning(self):
        print("Shutdown Requested")

    def shutdown(self):
        print("Shutting down the Calebrator...")
        fs.noteon(0, 72, 100)
        sleep(0.5)
        fs.noteon(0, 60, 100)
        sleep(0.5)
        fs.noteoff(0, 60)
        fs.noteoff(0, 72)
        shutdownCycle()

    def close(self):
        self.button.close()
Example #12
0
def listen(func):
    button_map = { 5: "A", 6: "B", 16: "X", 24: "Y"}

    button_a = Button(5)
    button_b = Button(6)
    button_x = Button(16)
    button_y = Button(24)

    def on_press(button): func(button_map[button.pin.number])

    try:
        button_a.when_pressed = on_press
        button_b.when_pressed = on_press
        button_x.when_pressed = on_press
        button_y.when_pressed = on_press
        pause()

    except KeyboardInterrupt:
        button_a.close()
        button_b.close()
        button_x.close()
        button_y.close()
Example #13
0
try:
    button_a.when_pressed = pressed
    button_b.when_pressed = pressed
    button_x.when_pressed = pressed
    button_y.when_pressed = pressed

    while True:
        if splash_time > 0:
            splash_x, splash_y = splash_origin
            splash_progress = time.time() - splash_time
            for x in range(width):
                for y in range(height):
                    d = distance(x, y, splash_x, splash_y)
                    if (d / 30.0) < splash_progress and splash_progress < 0.6:
                        h = d / 20.0
                        h += 0.1
                        h = min(1, h)
                        scrollphathd.set_pixel(x, y, h)
                    elif (d / 30.0) < splash_progress - 0.6:
                        scrollphathd.set_pixel(x, y, 0)

        scrollphathd.show()

        time.sleep(1.0 / 60.0)

except KeyboardInterrupt:
    button_a.close()
    button_b.close()
    button_x.close()
    button_y.close()
Example #14
0
class Controller:
    """Manages all the other components and signalling"""

    BTN_UP_TO_DISPLAY_SIG = "HELLO-DISPLAY-IM-BTN-UP"
    BTN_DOWN_TO_DISPLAY_SIG = "HELLO-DISPLAY-IM-BTN-DOWN"
    startTargetTemp = 20

    def __init__(self):
        self.thermostat = ThermostatSensor(18, 23)
        dispatcher.connect(self.signalHandler,
                           signal=self.thermostat.THERMOSTAT_TO_CONTROLLER_SIG,
                           sender=dispatcher.Any)
        print "Thermostat init"

        self.startTargetTemp = self._fetchTargetTemp(self.startTargetTemp)
        self.display = DisplayDevice(0x3F, self.thermostat,
                                     self.startTargetTemp, self)
        print "Display init"

        self.btnUp = Button(8)
        self.btnDown = Button(7)
        self.btnUp.when_pressed = self._sendIncrease
        self.btnDown.when_pressed = self._sendDecrease
        print "Buttons init"

        self.isActive = 0
        print "Launching getTemp().."
        self.thermostat.readTemp.start()
        print "Launched!"

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.thermostat.close()
        self.display.close()
        self.btnDown.close()
        self.btnUp.close()

    def signalHandler(self, sender, param):
        """
        Here we should act differently according to which is the sender: param
        may contain different data based on which component sent the signal
        """
        if sender == self.thermostat:
            # Save into temperature_log the temp and a time record
            conn = sqlite3.connect("thermostat.db")
            conn.execute("BEGIN EXCLUSIVE TRANSACTION")
            cur = conn.cursor()
            sql = """
                    INSERT INTO temperature_log(temp, timeRecord, isActive)
                    VALUES(?, ?, ?)
                """
            cur.execute(sql, (param['temp'], time.time(), self.isActive))
            if cur.rowcount != 1:
                conn.rollback()
            else:
                conn.commit()
        else:
            print "Wrong sender"

    def _fetchTargetTemp(self, target):
        now = time.time()
        todayWeekDay = datetime.datetime.today().weekday() + 1
        todayHour = time.strftime("%H")
        sql = """   SELECT targetTemp FROM program
                    WHERE weekDay = ?
                    AND hour = ?
            """
        conn = sqlite3.connect("thermostat.db")
        cur = conn.cursor()
        cur.execute(sql, (todayWeekDay, todayHour))
        result = cur.fetchone()
        if result is not None:
            return result[0]
        else:
            return targetTemp

    def _sendIncrease(self):
        dispatcher.send(signal=self.BTN_UP_TO_DISPLAY_SIG,
                        sender=self,
                        param=1)

    def _sendDecrease(self):
        dispatcher.send(signal=self.BTN_DOWN_TO_DISPLAY_SIG,
                        sender=self,
                        param=-1)
class KillTeam:
    def __init__(self):
        self.plusButton = Button(17)
        self.minusButton = Button(27)
        self.okButton = Button(22)

        self.canticleLed1 = PWMLED(5)  # IncantationOfTheIronSoul
        self.canticleLed2 = PWMLED(6)  # LitanyOfTheElectromancer
        self.canticleLed3 = PWMLED(13)  # Chant of the Remorseless Fist
        self.canticleLed4 = PWMLED(19)  # Shroudpsalm
        self.canticleLed5 = PWMLED(26)  # Invocation of Machine Might
        self.canticleLed6 = PWMLED(21)  # Benediction of the Omnissiah

        self.initiativeLed = PWMLED(23)
        self.movementLed = PWMLED(24)
        self.psychicLed = PWMLED(25)
        self.shootingLed = PWMLED(12)
        self.meleeLed = PWMLED(16)
        self.moraleLed = PWMLED(20)

        self.selected_canticle = INCANTATION_OF_THE_IRON_SOUL
        self.canticle1Used = False
        self.canticle2Used = False
        self.canticle3Used = False
        self.canticle4Used = False
        self.canticle5Used = False
        self.canticle6Used = False

        self.continueGame = True

    def select_canticles(self):
        self.initiativeLed.off()
        self.movementLed.off()
        self.psychicLed.off()
        self.shootingLed.off()
        self.meleeLed.off()
        self.moraleLed.off()

        self.plusButton.when_pressed = self.canticle_plus_button
        self.minusButton.when_pressed = self.canticle_minus_button
        self.okButton.when_pressed = self.canticle_ok_button

        self.display_canticle()

        self.okButton.wait_for_press()

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = None
        self.okButton.when_pressed = None
        sleep(0.5)

    def canticle_plus_button(self):
        self.selected_canticle += 1
        if self.selected_canticle == 8:
            self.selected_canticle = INCANTATION_OF_THE_IRON_SOUL
        self.display_canticle()

    def canticle_minus_button(self):
        self.selected_canticle -= 1
        if self.selected_canticle == -1:
            self.selected_canticle = BENEDICTION_OF_THE_OMNISSIAH
        self.display_canticle()

    def canticle_ok_button(self):
        if self.selected_canticle == 0 or self.selected_canticle == 7:
            self.selected_canticle = randint(1, 6)
        else:
            if self.selected_canticle == INCANTATION_OF_THE_IRON_SOUL:
                self.canticle1Used = True
            elif self.selected_canticle == LITANY_OF_THE_ELECTROMANCER:
                self.canticle2Used = True
            elif self.selected_canticle == CHANT_OF_THE_REMORSELESS_FIST:
                self.canticle3Used = True
            elif self.selected_canticle == SHROUDPSALM:
                self.canticle4Used = True
            elif self.selected_canticle == INVOCATION_OF_MACHINE_MIGHT:
                self.canticle5Used = True
            elif self.selected_canticle == BENEDICTION_OF_THE_OMNISSIAH:
                self.canticle6Used = True
        self.display_canticle(True)

    def initiative_phase(self):
        self.initiativeLed.on()
        self.movementLed.off()
        self.psychicLed.off()
        self.shootingLed.off()
        self.meleeLed.off()
        self.moraleLed.off()

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = None
        self.okButton.when_pressed = None
        self.okButton.wait_for_press()
        sleep(0.5)

    def movement_phase(self):
        self.initiativeLed.off()
        self.movementLed.on()
        self.psychicLed.off()
        self.shootingLed.off()
        self.meleeLed.off()
        self.moraleLed.off()

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = None
        self.okButton.when_pressed = None
        self.okButton.wait_for_press()
        sleep(0.5)

    def psychic_phase(self):
        self.initiativeLed.off()
        self.movementLed.off()
        self.psychicLed.on()
        self.shootingLed.off()
        self.meleeLed.off()
        self.moraleLed.off()

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = None
        self.okButton.when_pressed = None
        self.okButton.wait_for_press()
        sleep(0.5)

    def shooting_phase(self):
        self.initiativeLed.off()
        self.movementLed.off()
        self.psychicLed.off()
        self.shootingLed.on()
        self.meleeLed.off()
        self.moraleLed.off()

        if self.selected_canticle in [
                SHROUDPSALM, BENEDICTION_OF_THE_OMNISSIAH
        ]:
            self.display_canticle(True, True)

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = None
        self.okButton.when_pressed = None
        self.okButton.wait_for_press()

        if self.selected_canticle in [
                SHROUDPSALM, BENEDICTION_OF_THE_OMNISSIAH
        ]:
            self.display_canticle(True, False)
        sleep(0.5)

    def melee_phase(self):
        self.initiativeLed.off()
        self.movementLed.off()
        self.psychicLed.off()
        self.shootingLed.off()
        self.meleeLed.on()
        self.moraleLed.off()

        if self.selected_canticle in [
                LITANY_OF_THE_ELECTROMANCER, CHANT_OF_THE_REMORSELESS_FIST,
                INVOCATION_OF_MACHINE_MIGHT
        ]:
            self.display_canticle(True, True)

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = None
        self.okButton.when_pressed = None
        self.okButton.wait_for_press()

        if self.selected_canticle in [
                LITANY_OF_THE_ELECTROMANCER, CHANT_OF_THE_REMORSELESS_FIST,
                INVOCATION_OF_MACHINE_MIGHT
        ]:
            self.display_canticle(True, False)
        sleep(0.5)

    def morale_phase(self):
        self.initiativeLed.off()
        self.movementLed.off()
        self.psychicLed.off()
        self.shootingLed.off()
        self.meleeLed.off()
        self.moraleLed.on()

        if self.selected_canticle in [1]:
            self.display_canticle(True, True)

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = None
        self.okButton.when_pressed = None
        self.okButton.wait_for_press()

        if self.selected_canticle in [1]:
            self.display_canticle(True, False)
        sleep(0.5)

    def select_if_end_game(self):
        self.initiativeLed.pulse()
        self.movementLed.pulse()
        self.psychicLed.pulse()
        self.shootingLed.pulse()
        self.meleeLed.pulse()
        self.moraleLed.pulse()

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = self.end_game_select
        self.okButton.when_pressed = None

        self.okButton.wait_for_press()

        self.plusButton.when_pressed = None
        self.minusButton.when_pressed = None
        self.okButton.when_pressed = None
        sleep(0.5)

    def end_game_select(self):
        self.continueGame = not self.continueGame
        if self.continueGame:
            self.initiativeLed.pulse()
            self.movementLed.pulse()
            self.psychicLed.pulse()
            self.shootingLed.pulse()
            self.meleeLed.pulse()
            self.moraleLed.pulse()
        else:
            self.initiativeLed.off()
            self.movementLed.off()
            self.psychicLed.off()
            self.shootingLed.off()
            self.meleeLed.off()
            self.moraleLed.off()

    def close(self):
        self.initiativeLed.close()
        self.movementLed.close()
        self.psychicLed.close()
        self.shootingLed.close()
        self.meleeLed.close()
        self.moraleLed.close()
        self.canticleLed1.close()
        self.canticleLed2.close()
        self.canticleLed3.close()
        self.canticleLed4.close()
        self.canticleLed5.close()
        self.canticleLed6.close()
        self.plusButton.close()
        self.minusButton.close()
        self.okButton.close()

    def display_canticle(self, selected=False, blinking=False):
        if selected:
            self.canticleLed1.off()
            self.canticleLed2.off()
            self.canticleLed3.off()
            self.canticleLed4.off()
            self.canticleLed5.off()
            self.canticleLed6.off()
            if self.selected_canticle == 1:
                if blinking:
                    self.canticleLed1.pulse()
                else:
                    self.canticleLed1.on()
            elif self.selected_canticle == LITANY_OF_THE_ELECTROMANCER:
                if blinking:
                    self.canticleLed2.pulse()
                else:
                    self.canticleLed2.on()
            elif self.selected_canticle == CHANT_OF_THE_REMORSELESS_FIST:
                if blinking:
                    self.canticleLed3.pulse()
                else:
                    self.canticleLed3.on()
            elif self.selected_canticle == SHROUDPSALM:
                if blinking:
                    self.canticleLed4.pulse()
                else:
                    self.canticleLed4.on()
            elif self.selected_canticle == INVOCATION_OF_MACHINE_MIGHT:
                if blinking:
                    self.canticleLed5.pulse()
                else:
                    self.canticleLed5.on()
            elif self.selected_canticle == BENEDICTION_OF_THE_OMNISSIAH:
                if blinking:
                    self.canticleLed6.pulse()
                else:
                    self.canticleLed6.on()
        else:
            if not self.canticle1Used:
                self.canticleLed1.on()
            else:
                self.canticleLed1.off()
            if not self.canticle2Used:
                self.canticleLed2.on()
            else:
                self.canticleLed2.off()
            if not self.canticle3Used:
                self.canticleLed3.on()
            else:
                self.canticleLed3.off()
            if not self.canticle4Used:
                self.canticleLed4.on()
            else:
                self.canticleLed4.off()
            if not self.canticle5Used:
                self.canticleLed5.on()
            else:
                self.canticleLed5.off()
            if not self.canticle6Used:
                self.canticleLed6.on()
            else:
                self.canticleLed6.off()
            if self.selected_canticle == 1:
                self.canticleLed1.pulse()
            elif self.selected_canticle == LITANY_OF_THE_ELECTROMANCER:
                self.canticleLed2.pulse()
            elif self.selected_canticle == CHANT_OF_THE_REMORSELESS_FIST:
                self.canticleLed3.pulse()
            elif self.selected_canticle == SHROUDPSALM:
                self.canticleLed4.pulse()
            elif self.selected_canticle == INVOCATION_OF_MACHINE_MIGHT:
                self.canticleLed5.pulse()
            elif self.selected_canticle == BENEDICTION_OF_THE_OMNISSIAH:
                self.canticleLed6.pulse()
            else:
                self.canticleLed1.pulse()
                self.canticleLed2.pulse()
                self.canticleLed3.pulse()
                self.canticleLed4.pulse()
                self.canticleLed5.pulse()
                self.canticleLed6.pulse()
Example #16
0
class PiPadRotary:

    # initialize
    def __init__(self) :

        # set PINs on BOARD
        log.debug("Initializing Rotary Encoder...")
        log.debug("> Button:" + str(_conf['btn_pin']))
        self.btn = Button(_conf['btn_pin'])
        log.debug("> Clock:" + str(_conf['clock_pin']))
        self.clock = InputDevice(_conf['clock_pin'])
        log.debug("> DT:" + str(_conf['dt_pin']))
        self.dt = InputDevice(_conf['dt_pin'])

        # values
        self.counter = Value('i', 0)

        # processes
        log.debug("Initializing Rotary processes...")
        self.process = Process(target=self.worker)
        self.process.start()
        log.debug("...init done!")

    # get counter
    def get_counter(self) :
        return self.counter.value

    # set counter
    def set_counter(self, value) :
        self.counter.value = value

    # reset counter
    def reset_counter(self) :
        self.counter.value = 0

    # check button pressed
    def is_pressed(self) :
        return self.btn.is_pressed

    # control rotary
    def worker(self) :
        try :
                clock_value = self.clock.value
                while True :

                    clock = self.clock.value
                    dt = self.dt.value
                    log.debug("Clock: " + str(clock_value))
                    log.debug("Current Clock: " + str(clock))
                    log.debug("DT: " + str(dt))
                    if clock != clock_value :
                        if dt != clock :
                            log.debug("!=")
                            self.counter.value += 1
                        else :
                            log.debug("==")
                            self.counter.value -= 1
                    clock_value = clock
                    sleep(_conf['clock_wait_time'])

        except KeyboardInterrupt:
            pass

    # terminate
    def terminate(self) :
        log.debug("Rotary Encoder termination...")
        self.btn.close()
        self.dt.close()
        self.clock.close()
        self.process.join()
        self.process.terminate()
class GpiorgbcontrollerPlugin(octoprint.plugin.StartupPlugin,
							  octoprint.plugin.SettingsPlugin,
                              octoprint.plugin.AssetPlugin,
                              octoprint.plugin.TemplatePlugin,
							  octoprint.plugin.SimpleApiPlugin):

	def __init__(self):
		self.led = None
		self.color = '#FFFFFF'
		self.is_on = False
		self.btn = None
		self.is_btn_en = False
		self.gcode_command_enable = False
		self.gcode_index_enable = False
		self.gcode_rgb_index = 1
		self.pin_factory = RPiGPIOFactory()
	

	def init_rgb(self, red_pin, grn_pin, blu_pin):
		try:
			self.deinit_rgb()
			self.led = RGBLED(red=red_pin, green=grn_pin, blue=blu_pin, active_high=True, pin_factory=self.pin_factory)
			self._logger.info("LEDs initialized with pin factory: " + str(self.led.pin_factory))
		except:
			self._logger.error("Error occurred while initializing LEDs")


	def deinit_rgb(self):
		try:
			if(self.led is not None):
				self.led.close()
				self.led = None
				self._logger.info("LEDs deinitialized")
		except:
			self._logger.error("Error occurred while deinitializing LEDs")


	def init_btn(self, pin):
		try:
			self.deinit_btn()
			self.btn = Button(pin, pin_factory=self.pin_factory)
			self.btn.when_pressed = self.on_btn_press
			self.btn.when_released = self.on_btn_release
			self._logger.info("Button initialized with pin factory: " + str(self.btn.pin_factory) )
		except:
			self._logger.error("Error occurred while initializing button")


	def deinit_btn(self):
		try:
			if(self.btn is not None):
				self.btn.close()
				self.btn = None
				self._logger.info("Button deinitialized")
		except:
			self._logger.error("Error occurred while deinitializing button")


	def read_btn(self):
		if(self.btn is not None and self.is_btn_en):
			if(self.btn.is_pressed):
				self.on_btn_press()
			else:
				self.on_btn_release()


	def on_btn_press(self):
		if(self.is_btn_en):
			self.is_on = True
			self.update_rgb(self.color, self.is_on)


	def on_btn_release(self):
		if(self.is_btn_en):
			self.is_on = False
			self.update_rgb(self.color, self.is_on)
			

	def update_rgb(self, color, is_on):
		if(self.led is not None):
			rgb = int(color[1:], 16)
			red = ((rgb & 0xFF0000) >> 16) / 255
			grn = ((rgb & 0x00FF00) >> 8) / 255
			blu = ((rgb & 0x0000FF)) / 255
			if is_on:
				self.led.color = (red, grn, blu)
			else:
				self.led.color = (0, 0, 0)
		else:
			self._logger.error("Error occurred while updating RGB state")


	def on_after_startup(self):
		red_pin = self._settings.get_int(["red_pin"])
		grn_pin = self._settings.get_int(["grn_pin"])
		blu_pin = self._settings.get_int(["blu_pin"])
		color = self._settings.get(["color"])
		is_on = self._settings.get_boolean(["is_on"])
		if red_pin is not None and grn_pin is not None and blu_pin is not None:
			self.init_rgb(red_pin, grn_pin, blu_pin)
			if(is_on is not None and color is not None):
				self.color = color
				self.is_on = is_on
				self.update_rgb(self.color, self.is_on)
		btn_pin = self._settings.get_int(["btn_pin"])
		is_btn_en = self._settings.get_boolean(["is_btn_en"])
		if btn_pin is not None and is_btn_en is not None:
			self.init_btn(btn_pin)
			self.is_btn_en = is_btn_en
			self.read_btn()
		gcode_command_enable = self._settings.get_boolean(["gcode_command_enable"])
		if gcode_command_enable is not None:
			self.gcode_command_enable = gcode_command_enable
		gcode_index_enable = self._settings.get_boolean(["gcode_index_enable"])
		if gcode_index_enable is not None:
			self.gcode_index_enable = gcode_index_enable
		gcode_rgb_index = self._settings.get_int(["gcode_rgb_index"])
		if gcode_rgb_index is not None:
			self.gcode_rgb_index = gcode_rgb_index
		self._plugin_manager.send_plugin_message(self._identifier, dict(is_on=self.is_on, color=self.color))
		

	def on_settings_save(self, data):
		octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
		if 'red_pin' in data or 'grn_pin' in data or 'blu_pin' in data:
			red_pin = self._settings.get_int(["red_pin"])
			grn_pin = self._settings.get_int(["grn_pin"])
			blu_pin = self._settings.get_int(["blu_pin"])
			if(red_pin is not None and grn_pin is not None and blu_pin is not None):
				self.init_rgb(red_pin, grn_pin, blu_pin)
		color = self._settings.get(["color"])
		is_on = self._settings.get_boolean(["is_on"])
		if is_on is not None and color is not None:
			self.color = color
			self.is_on = is_on
			self.update_rgb(self.color, self.is_on)
		if 'btn_pin' in data or 'is_btn_en' in data:
			btn_pin = self._settings.get_int(["btn_pin"])
			is_btn_en = self._settings.get_boolean(["is_btn_en"])
			if(btn_pin is not None and is_btn_en is not None):
				self.init_btn(btn_pin)
				self.is_btn_en = is_btn_en
				self.read_btn()
		gcode_command_enable = self._settings.get_boolean(["gcode_command_enable"])
		if gcode_command_enable is not None:
			self.gcode_command_enable = gcode_command_enable
		gcode_index_enable = self._settings.get_boolean(["gcode_index_enable"])
		if gcode_index_enable is not None:
			self.gcode_index_enable = gcode_index_enable
		gcode_rgb_index = self._settings.get_int(["gcode_rgb_index"])
		if gcode_rgb_index is not None:
			self.gcode_rgb_index = gcode_rgb_index
		
	def get_settings_defaults(self):
		return dict(
			red_pin=20,
			grn_pin=25,
			blu_pin=5,
			color='#FFFFFF',
			is_on = False,
			btn_pin=21,
			is_btn_en=False,
			gcode_command_enable=False,
			gcode_index_enable=False,
			gcode_rgb_index=1,
		)


	def get_assets(self):
		# Define your plugin's asset files to automatically include in the
		# core UI here.
		return dict(
			js=["js/gpiorgbcontroller.js",  "js/jscolor.min.js"],
			css=["css/gpiorgbcontroller.css"],
			less=["less/gpiorgbcontroller.less"]
		)


	def get_template_configs(self):
		return [
			dict(type="settings", custom_bindings=False)
		]


	def get_api_commands(self):
		return dict(
			update_color=["color"],
			turn_on=[],
			turn_off=[]
		)


	def on_api_command(self, command, data):
		if command == "update_color":
			color = data.get('color', None)
			if color != None:
				self.color = color
		elif command == "turn_on":
			self.is_on = True
		elif command == "turn_off":
			self.is_on = False
		self.update_rgb(self.color, self.is_on)
		

	def gcode_parse_index(self, cmd):
		params = cmd.split("I")
		if len(params) != 2:
			return None
		else:
			try:
				index = int(params[1].split()[0])
				if index > 0:
					return index
				else:
					return None
			except:
				return None


	def gcode_parse_rgb_component(self, cmd, comp):
		try:
			comp_type = comp.upper()
			if comp_type != "R" and comp_type != "G" and comp_type != "B":
				return None
			delim = ""
			if comp_type == "R":
				delim = "R"
			elif comp_type == "G":
				delim = "U"
			elif comp_type == "B":
				delim = "B"
			params = cmd.split(delim)
			if len(params) != 2:
				return None
			else:
				color_int = int(params[1].split()[0])
				if color_int < 0 or color_int > 255:
					return None
				else:
					color_hex = "%02X" % color_int
					if len(color_hex) != 2:
						return None
					else:
						return color_hex
		except:
			return None


	def replace_color_component(self, color, value, comp):
		if len(color) != 7 or value is None:
			return color
		comp_type = comp.upper()
		if comp_type != "R" and comp_type != "G" and comp_type != "B":
			return color
		if len(value) != 2:
			return color
		old_r = color[1:3]
		old_g = color[3:5]
		old_b = color[5:7]
		new_color = color
		if comp_type == "R":
			new_color = "#" + value + old_g + old_b
		elif comp_type == "G":
			new_color = "#" + old_r + value + old_b
		elif comp_type == "B":
			new_color = "#" +old_r + old_g + value
		return new_color


	def on_gcode_command(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
		if not self.gcode_command_enable:
			return 
		if gcode and gcode.startswith("M150"):
			color = "#000000"
			red = self.gcode_parse_rgb_component(cmd, "R")
			color = self.replace_color_component(color, red, "R")
			grn = self.gcode_parse_rgb_component(cmd, "G")
			color = self.replace_color_component(color, grn, "G")
			blu = self.gcode_parse_rgb_component(cmd, "B")
			color = self.replace_color_component(color, blu, "B")
			if self.gcode_index_enable:
				index = self.gcode_parse_index(cmd)
				if index is not None and index == self.gcode_rgb_index and color is not None and len(color) == 7:
					self.color = color
					self.is_on = True
					self.update_rgb(self.color, self.is_on)
					self._plugin_manager.send_plugin_message(self._identifier, dict(is_on=self.is_on, color=self.color))
			else:
				if color is not None and len(color) == 7:
					self.color = color
					self.is_on = True
					self.update_rgb(self.color, self.is_on)
					self._plugin_manager.send_plugin_message(self._identifier, dict(is_on=self.is_on, color=self.color))
		

	def get_update_information(self):
		# Define the configuration for your plugin to use with the Software Update
		# Plugin here. See https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html
		# for details.
		return dict(
			gpiorgbcontroller=dict(
				displayName="Gpiorgbcontroller Plugin",
				displayVersion=self._plugin_version,

				# version check: github repository
				type="github_release",
				user="******",
				repo="OctoPrint-GpioRgbController",
				current=self._plugin_version,

				# update method: pip
				pip="https://github.com/z4gunn/OctoPrint-GpioRgbController/archive/{target_version}.zip"
			)
		)
  subprocess.run(['raspistill', '-n', '-t', '2s', '-o', '/tmp/out.jpeg'], check=True)
  subprocess.run(['convert', '/tmp/out.jpeg', '-resize', '128x64!', '/tmp/small.jpeg'])
  img = Image.open('/tmp/small.jpeg').convert('1')
  screen.display_image(img)


def release():
  led.off()

with open('db_config.json') as inf:
  dbconfig = json.load(inf)

repo = TemperatureRepository(**dbconfig)

temp_reader = BME280()
lux_reader = TSL2561()
button.when_pressed = button_press
button.when_released = release

try:
  while True:
    temp = temp_reader.read()
    repo.insert_temp(temp)
    lux = lux_reader.read()
    repo.insert_lux(lux)
    button.wait_for_press(300)
except KeyboardInterrupt:
  button.close()
  led.close()

def button_handler(wait_delay=60,
                   accept_led=None,
                   choice_led=None,
                   green_button_text="for Accept",
                   yellow_button_text="for more choice"):

    global button_input_received

    button_utils_logger = logging.getLogger('button_.button_handler')
    button_input_received = False

    if not test_environment:
        accept_button = Button(config.__GREEN_BUTTON__)
        accept_button.when_pressed = accept_button_callback
        choice_button = Button(config.__YELLOW_BUTTON__)
        choice_button.when_pressed = choice_button_callback

    button_utils_logger.info("Go ahead and press the appropriate button. ")

    profile_prompt = "Push Green button %s or Yellow button %s." % (
        green_button_text, yellow_button_text)
    if (green_button_text == "for Accept") and (yellow_button_text
                                                == "for more choice"):
        speech_file_name = "push_green_accept_yellow_choice.mp3"
    else:
        fname = profile_prompt.replace(" ", "_")
        fname = fname.replace(".", "")
        speech_file_name = "%s.mp3" % fname

    speech_file_path = generate_audio(speech_text=profile_prompt,
                                      filename=speech_file_name)
    button_utils_logger.info("Generated Audio now. Playing audio next: ")
    play_audio(file_path=speech_file_path)
    button_utils_logger.info("Audio played. Done!")

    while (wait_delay and (not button_input_received)):
        button_utils_logger.info("In button thread: waiting for button input")
        sleep(10)
        wait_delay -= 10

    if button_input_received:
        button_utils_logger.info("Button input was received successfully: %d" %
                                 button_input_received)
    else:
        button_utils_logger.info("No button press detected!")

        profile_prompt = "No button press was detected. Defaulting to an accept now."
        speech_file_path = generate_audio(
            speech_text=profile_prompt,
            filename="no_button_press_was_detected.mp3")
        play_audio(file_path=speech_file_path)

        button_input_received = 1

    if not test_environment:
        if button_input_received == 1:
            if accept_led:
                accept_led.on()
                choice_led.off()
        elif button_input_received == 2:
            if choice_led:
                choice_led.on()
                accept_led.off()

    if not test_environment:
        accept_button.close()
        choice_button.close()

    button_utils_logger.info("Done with button_handler.")

    return button_input_received
Example #20
0
class gpioDigtalInput():
    def init(self, db_config_id, config_db, flog):
        self.db_config_id = db_config_id
        self.config_db = config_db
        self.flog = flog
        self.gpio_pin = None

        # reading from database the pin number
        _id, gpio_pin_value, _label = self.config_db.strget(
            self.db_config_id, self.flog)
        flog.info(inspect.stack()[0][3] +
                  ": gpioDigtalInput gelezen uit database, pin nummer is " +
                  str(gpio_pin_value))
        # init the gpio pin
        if self.no_duplicate_use_of_pins_used_as_input() == True:
            self.gpio_pin = Button(int(gpio_pin_value),
                                   pull_up=True,
                                   hold_repeat=False)
        else:
            flog.info(
                inspect.stack()[0][3] +
                ": gpioDigtalInput niet gezet wegens dubbel gebruik van pin's "
                + str(gpio_pin_value))
            self.gpio_pin = None

    # True is an pulse, False not
    def gpioWaitRead(self):
        if self.gpio_pin.wait_for_press(timeout=10) == False:
            return False
        self.gpio_pin.wait_for_press()
        self.flog.debug(inspect.stack()[0][3] + ": press detected.")
        self.gpio_pin.wait_for_release()
        self.flog.debug(inspect.stack()[0][3] + ": press released.")
        return True

    def close(self):
        self.gpio_pin.close()

    def check_pin_from_db(self):
        #self.flog.info( inspect.stack()[0][3]+ ": entry." )
        # reading from database the pin number
        _id, gpio_pin_value, _label = self.config_db.strget(
            self.db_config_id, self.flog)
        if self.gpio_pin.pin.number != int(
                gpio_pin_value):  #check if pin is changed, in config
            #self.flog.info( inspect.stack()[0][3]+ ": entry 2." )
            self.gpio_pin.close()
            self.gpio_pin = Button(int(gpio_pin_value),
                                   pull_up=True,
                                   hold_repeat=False)
            self.flog.info(inspect.stack()[0][3] +
                           ": GPIO pin aangepast naar pin " +
                           str(gpio_pin_value))
            #self.flog.info( inspect.stack()[0][3]+ ": entry 3." )
        #self.flog.info( inspect.stack()[0][3]+ ": exit 4." )

    def no_duplicate_use_of_pins_used_as_input(self):
        # update this as the config.db is changed
        # curent config index's used
        # 85, 95 , 97  126 is input

        check_set = set()
        # we use a set because a set won't except double values, so when an pin is already used the
        # number of enteries wil be less then 4

        try:
            _id, gpio_pin_value_85, _label = self.config_db.strget(
                85, self.flog)  # GPIO 27 Default pin
            check_set.add(gpio_pin_value_85)
            _id, gpio_pin_value_95, _label = self.config_db.strget(
                95, self.flog)  # GPIO 22 Default pin
            check_set.add(gpio_pin_value_95)
            _id, gpio_pin_value_97, _label = self.config_db.strget(
                97, self.flog)  # GPIO 17 Default pin
            check_set.add(gpio_pin_value_97)
            _id, gpio_pin_value_126, _label = self.config_db.strget(
                126, self.flog)  # GPIO 26 Default pin
            check_set.add(gpio_pin_value_126)

            self.flog.debug( inspect.stack()[0][3] + ": gpio_pin_value_85=" + gpio_pin_value_85 + " gpio_pin_value_95="\
                 + gpio_pin_value_95 + " pio_pin_value_97=" + gpio_pin_value_97 + " gpio_pin_value_126=" + gpio_pin_value_126 )

            # none of the pins may be equal
            # we use a set because a set won't except double values, so when an pin is already used the
            # number of enteries wil be less then 4
            if len(check_set) != 4:
                return False
            return True
        except:
            return False
Example #21
0
class ScrollHatMiniInput(Input):
    """
    A way to get input from the the Pimoroni Scroll HAT Mini.
    """
    _A_BUTTON =  5
    _B_BUTTON =  6
    _X_BUTTON = 16
    _Y_BUTTON = 24

    def __init__(self,
                 state,
                 prefix  ='Dexter',
                 a_button='raise the volume',
                 b_button='lower the volume',
                 x_button='stop',
                 y_button='play or pause'):
        """
        @see Input.__init__()
        :type  prefix: str
        :param prefix:
            The prefix to use when sending the inputs.
        :type  a_button: str
        :param a_button:
            What string to send when the A button is pressed.
        :type  b_button: str
        :param b_button:
            What string to send when the B button is pressed.
        :type  x_button: str
        :param x_button:
            What string to send when the X button is pressed.
        :type  y_button: str
        :param y_button:
            What string to send when the Y button is pressed.
        """
        super(ScrollHatMiniInput, self).__init__(state)

        def tokenize(string):
            if string and str(string).strip():
                return [Token(word.strip(), 1.0, True)
                        for word in str(string).strip().split()
                        if word]
            else:
                return []

        # Our bindings etc.
        self._prefix = tokenize(prefix)
        self._bindings = {
            self._A_BUTTON : tokenize(a_button),
            self._B_BUTTON : tokenize(b_button),
            self._X_BUTTON : tokenize(x_button),
            self._Y_BUTTON : tokenize(y_button),
        }

        # The buttons, we will set these up in _start()
        self._a_button = None
        self._b_button = None
        self._x_button = None
        self._y_button = None

        # And where we put the tokens
        self._output = []


    def read(self):
        """
        @see Input.read
        """
        if len(self._output) > 0:
            try:
                return self._output.pop()
            except:
                pass


    def _start(self):
        """
        @see Component.start()
        """
        # Create the buttons
        self._a_button = Button(self._A_BUTTON)
        self._b_button = Button(self._B_BUTTON)
        self._x_button = Button(self._X_BUTTON)
        self._y_button = Button(self._Y_BUTTON)

        # And bind
        self._a_button.when_pressed = self._on_button
        self._b_button.when_pressed = self._on_button
        self._x_button.when_pressed = self._on_button
        self._y_button.when_pressed = self._on_button


    def _stop(self):
       """
       @see Input.stop
       """
       try:
           self._a_button.close()
           self._b_button.close()
           self._x_button.close()
           self._y_button.close()
       except:
           pass


    def _on_button(self, button):
        """
        Handle a button press.
        """
        number = button.pin.number
        LOG.info("Got button on pin GPIO%d" % (number,))
        tokens = self._bindings.get(number, [])
        if len(tokens) > 0:
            self._output.append(tuple(self._prefix + tokens))
Example #22
0
                self.lock.acquire()
                self.color = self.colors_list[self.cycle_count
                                              % len(self.colors_list)]
                self.cycle_count = self.cycle_count + 1
                self.lock.release()

                # Set the color for the LED
                RGB_LED.color = Color(self.color.lower())

                # Display the color for specified interval before switching again
                time.sleep(self.interval_ms/1000)

            # If button is pressed, display the current color for 5 seconds
            elif not self.keep_cycling and self.game_active:
                time.sleep(5)
                RGB_LED.off()
                self.lock.acquire()
                self.game_active = False
                self.lock.release()
            else:
                RGB_LED.off()
                time.sleep(0.1)


if __name__ == '__main__':
    try:
        ColorCyclerGadget().main()
    finally:
        RGB_LED.close()
        BUTTON.close()
Example #23
0
class Zoltar(object):
    def __init__(self, comm_client):
        print('Finally, a Zoltar!')
        self.is_moving = False
        self.left_eye = LED(LED1_GPIO)
        self.right_eye = LED(LED2_GPIO)
        self.button = Button(BUTTON_GPIO)
        self.button.when_pressed = self.stop_moving
        self.communications = comm_client

    def begin_moving(self):
        self.left_eye.on()
        self.right_eye.on()
        self.servo = AngularServo(SERVO_GPIO,
                                  min_angle=SERVO_MIN_ANGLE,
                                  max_angle=SERVO_MAX_ANGLE,
                                  initial_angle=SERVO_INITIAL_ANGLE)
        while self.is_moving:
            if self.communications.available():
                (origin, message) = self.communications.recv()
                if message == 'COIN':
                    break
            for x in reversed(range(0, 179)):
                self.servo.angle = x
                sleep(0.01)
            for x in range(0, 179):
                self.servo.angle = x
                if self.servo.angle == 0:
                    sleep(0.5)
                else:
                    sleep(0.01)
        self.finale()

    def eyes_off(self):
        self.right_eye.off()
        self.left_eye.off()

    def eyes_on(self):
        self.left_eye.on()
        self.right_eye.on()

    def finale(self):
        self.flashing_eyes()
        self.print_fortune()
        self.cleanup_gpio()

    def print_fortune(self):
        zoltar_dir = os.getenv('ZOLTAR_DIR')
        subprocess.Popen(['python', 'zoltar_print_fortune.py'], cwd=zoltar_dir)

    def flashing_eyes(self):
        self.eyes_off()
        sleep(1)
        self.eyes_on()
        sleep(1)
        self.eyes_off()
        sleep(1)
        self.eyes_on()
        sleep(1)
        self.eyes_off()

    def stop_moving(self):
        print('Button detected')
        self.is_moving = False

    def cleanup_gpio(self):
        self.left_eye.close()
        self.right_eye.close()
        self.servo.close()
        self.button.close()
Example #24
0
#!/usr/bin/env python3
from gpiozero import Button
from gpiozero import LED
from time import sleep

btn = Button(22)
btn2 = Button(24)
led = LED(16)

print("""
From left-to-right,
press button 1 for led 4,
button 2 to exit.
""")

while True:
  if btn.is_pressed:
    led.on()
    sleep(0.1)
    led.off()
  elif btn2.is_pressed:
    btn.close()
    led.close()
    print("done")
    exit(0)
Example #25
0
class PyTenki:
    def __init__(self, forecast=None, led_pins=None, button_pin=None):
        self._forecast = forecast
        self._leds = None
        self._button = None

        self._normalize_weather_str()
        self.assign_leds(led_pins)
        self.assign_button(button_pin)

    @property
    def forecast(self):
        return self._forecast

    @forecast.setter
    def forecast(self, forecast):
        self._forecast = forecast
        self._normalize_weather_str()

    def _normalize_weather_str(self):
        try:
            strings = (('大', ''), ('暴風', ''), ('雷', ''), ('一時', '時々'),
                       ('雨か雪', '雨'), ('雪か雨', '雪'))

            for before, after in strings:
                tmp = self._forecast['weather']
                self._forecast['weather'] = tmp.replace(before, after)
        except (AttributeError, TypeError):
            pass

    def _compose_forecast_summary(self):
        try:
            day = self._forecast.get('day')
            city = self._forecast.get('city')
            weather = self._forecast.get('weather')

            if all([day, city, weather]):
                fcast_weather = FCAST_WEATHER.format(day=day,
                                                     city=city,
                                                     weather=weather)
                fcast_max_temp = ''
                fcast_min_temp = ''

                temps = self._forecast.get('temp')
                max_temp = temps.get('max')
                min_temp = temps.get('min')

                if max_temp:
                    fcast_max_temp = FCAST_MAX_TEMP.format(max_temp=max_temp)

                if min_temp:
                    fcast_min_temp = FCAST_MIN_TEMP.format(min_temp=min_temp)

                return ''.join([fcast_weather, fcast_max_temp, fcast_min_temp])
        except AttributeError:
            pass

        return FCAST_SUM_ERR

    @_exc_attr_err
    def assign_leds(self, led_pins):
        self._close_leds()

        try:
            self._leds = LEDBoard(
                fine=led_pins.get('fine'),
                cloud=led_pins.get('cloud'),
                rain=led_pins.get('rain'),
                snow=led_pins.get('snow'),
                pwm=True,
            )
        except PinInvalidPin:
            pass

    @_exc_attr_err
    def _close_leds(self):
        self._leds.close()

    def assign_button(self, button_pin):
        try:
            self._close_button()
            self._button = Button(button_pin)
        except (GPIOPinMissing, PinInvalidPin):
            pass

    @_exc_attr_err
    def _close_button(self):
        self._button.close()

    @_exc_attr_err
    def tts_forecast_summary_after_button_press(self):
        self._button.when_pressed = self._tts_forecast_summary

    def _tts_forecast_summary(self):
        summary = self._compose_forecast_summary()

        try:
            p1 = subprocess.Popen(['echo', summary], stdout=subprocess.PIPE)
            p2 = subprocess.Popen([
                'open_jtalk', '-x', DIC_FPATH, '-m', VOICE_FPATH, '-ow',
                SPEECH_FPATH
            ],
                                  stdin=p1.stdout,
                                  stdout=subprocess.PIPE)

            p1.stdout.close()
            p2.communicate()
            p2.wait()

            subprocess.run(['aplay', '--quiet', SPEECH_FPATH])
            subprocess.run(['rm', '-f', SPEECH_FPATH])
        except OSError:
            pass

    def operate_all_weather_leds(self,
                                 on_time=1,
                                 off_time=1,
                                 fade_in_time=1,
                                 fade_out_time=1):
        self._operate_fine_led(on_time, off_time, fade_in_time, fade_out_time)
        self._operate_cloud_led(on_time, off_time, fade_in_time, fade_out_time)
        self._operate_rain_led(on_time, off_time, fade_in_time, fade_out_time)
        self._operate_snow_led(on_time, off_time, fade_in_time, fade_out_time)

    @_exc_attr_err
    def _operate_fine_led(self,
                          on_time=1,
                          off_time=1,
                          fade_in_time=1,
                          fade_out_time=1):
        weather = self._forecast.get('weather')

        if weather.startswith('晴'):
            self._leds.fine.on()
        elif 'のち晴' in weather:
            self._leds.fine.pulse(fade_in_time, fade_out_time)
        elif '時々晴' in weather:
            self._leds.fine.blink(on_time, off_time)
        else:
            self._leds.fine.off()

    @_exc_attr_err
    def _operate_cloud_led(self,
                           on_time=1,
                           off_time=1,
                           fade_in_time=1,
                           fade_out_time=1):
        weather = self._forecast.get('weather')

        if weather.startswith('曇'):
            self._leds.cloud.on()
        elif 'のち曇' in weather:
            self._leds.cloud.pulse(fade_in_time, fade_out_time)
        elif '時々曇' in weather:
            self._leds.cloud.blink(on_time, off_time)
        else:
            self._leds.cloud.off()

    @_exc_attr_err
    def _operate_rain_led(self,
                          on_time=1,
                          off_time=1,
                          fade_in_time=1,
                          fade_out_time=1):
        weather = self._forecast.get('weather')

        if weather.startswith('雨'):
            self._leds.rain.on()
        elif 'のち雨' in weather:
            self._leds.rain.pulse(fade_in_time, fade_out_time)
        elif '時々雨' in weather:
            self._leds.rain.blink(on_time, off_time)
        else:
            self._leds.rain.off()

    @_exc_attr_err
    def _operate_snow_led(self,
                          on_time=1,
                          off_time=1,
                          fade_in_time=1,
                          fade_out_time=1):
        weather = self._forecast.get('weather')

        if weather.startswith('雪'):
            self._leds.snow.on()
        elif 'のち雪' in weather:
            self._leds.snow.pulse(fade_in_time, fade_out_time)
        elif '時々雪' in weather:
            self._leds.snow.blink(on_time, off_time)
        else:
            self._leds.snow.off()
Example #26
0
class BixelRunner(object):
    def __init__(self, buttons, driver, matrix, delay=33, default_bright=2):
        self.buttons = buttons
        self.driver = driver
        self.matrix = matrix
        self.delay = delay
        self.brightness = default_bright

        self.games = []
        self.game_id = 0

        self.set_brightness(self.brightness)

        self.interval = IntervalRunner(self._run, self.delay)

        self.btn_bright = Button(16, bounce_time=0.01)
        self.btn_bright.when_pressed = self.brightness_pressed

        self.btn_menu = Button(20, bounce_time=0.01)
        self.btn_menu.when_pressed = self.show_menu

        self.in_menu = False
        self.menu_game = GameMenu(self.buttons.buttons, self.matrix)
        self.menu_game.setup(self)
        self.menu_game.reset()

    def show_menu(self):
        print('Entering Menu')
        self.menu_game.reset()
        self.in_menu = True

    def set_brightness(self, val):
        if val >= len(BRIGHT_LEVELS):
            print('Invalid Value')
        else:
            print('Brightness: {}/{}'.format(val + 1, len(BRIGHT_LEVELS)))
            self.driver.setMasterBrightness(BRIGHT_LEVELS[val])

    def brightness_pressed(self):
        self.brightness += 1
        if self.brightness >= len(BRIGHT_LEVELS):
            self.brightness = 0
        self.set_brightness(self.brightness)

    def add_game(self, game_class, args=(), kwargs={}):
        g = game_class(self.buttons.buttons, self.matrix)
        g.setup(*args, **kwargs)
        g.reset()
        self.games.append(g)
        return len(self.games) - 1

    def select_game(self, index):
        print('select: {}'.format(index))
        if index >= 0 and index < len(self.games):
            self.game_id = index
            self.games[self.game_id].reset()

    def start(self):
        if self.games:
            self.interval.start()

    def stop(self):
        self.btn_bright.close()

    def _run(self):
        self.buttons.get()
        if self.in_menu:
            self.menu_game.frame()
            if self.menu_game.selected is not None:
                self.matrix.clear()
                self.select_game(self.menu_game.selected)
                self.in_menu = False
                print('Switching to game: {}'.format(self.games[self.game_id].__class__.__name__))
        else:
            self.games[self.game_id].frame()
        self.driver.update()
Example #27
0
exit_switch = 13
is_lifted_playing = False
first_time = True
is_pressed_playing = False

headphone_button = Button(headphone_switch)
turnoff_button = Button(turnoff_switch)
exit_button = Button(exit_switch)
play_pressed = Player(play_path_video_is_pressed)
play_pressed.play()
try:
    while True:
        pass
except KeyboardInterrupt:
    print(''.join(['\n', '\n', 'INTERRUPTED', '\n']))
    if play_pressed.status() == 'playing':
        print('play_lifted Video is running, terminating now!')
        play_pressed.stop()
        #load_image().stop()
        #play_pressed.kill()
    else:
        print('no Video running, exiting now')

    headphone_button.close()
    turnoff_button.close()
    exit_button.close()

    pygame.quit()

    pi_
Example #28
0
            lcd.text('Passcode', 1)
            lcd.text('Correct!', 2)
            buzz.on()
            greenled.on()
            sleep(2)
            greenled.off()
            buzz.off()
            lcd.text('Initializing', 1)
            lcd.text('Face Scan...', 2)
            break
        else:
            lcd.text('Passcode', 1)
            lcd.text('Incorrect!', 2)
            buzz.on()
            redled.on()
            sleep(2)
            redled.off()
            buzz.off()
            userpass = []
    elif len(userpass) > len(password):
        lcd.clear()
        lcd.text('Please Try Again', 1)
        sleep(1)
        userpass = []

redled.close()
greenled.close()
buzz.close()
btn1.close()
btn2.close()
import faceunlock
Example #29
0
        if i12.value == 1:
            print("i12 pressed")
            o12.on()

        if fault.value == 0:
            print("SHORT CCT FAULT DETECTED!")
            print("RESET FAULT...")
            enable.off()
            sleep(5)
            enable.on()
            print("RESET COMPLETE")

        sleep(1)

    except KeyboardInterrupt:
        # required to close down program correctly in case of ctrl+c exit
        print("bye")
        i1.close()
        i2.close()
        i3.close()
        i4.close()
        i5.close()
        i6.close()
        i7.close()
        i8.close()
        i9.close()
        i10.close()
        i11.close()
        i12.close()
        sys.exit()
Example #30
0
class Hal(object):
    def __init__(self):
        
        self.led1_w = LED(17)
        self.led2_w = LED(11)
        self.sensor = Button(24)
        self.button = Button(23)
        self.button.when_pressed = self.__exit
        self.timers = {}
        self.timers[1] = time.time()
        self.leds = {}
        
        self.leds[1] = {'o': RGBLED(2, 3, 4, pwm=True, active_high=False), 'c': (1, 1, 1), 'b': 1.}
        self.leds[2] = {'o': RGBLED(10, 9, 25, pwm=True, active_high=False), 'c': (1, 1, 1), 'b': 1.}

    def __exit(self):
        self.button.close()
        self.sensor.close()
        self.leds[1]['o'].close()
        self.leds[2]['o'].close()
        time.sleep(1)
        sys.exit()


    def get_sensor_status(self):
        return self.sensor.is_pressed

    def set_color(self, x, color):
        rgb = self.hex_to_rgb(color)
        rgb_normalized = self.rgb_to_range(rgb)
        z = self.leds[x]['b']
        c = tuple(c * z for c in rgb_normalized)
        self.leds[x]['o'].color = c
        self.leds[x]['c'] = color

    def light_off(self, x):
        self.leds[x]['o'].off()
        
    def set_brightness(self, x, z):
        color = self.leds[x]['c']
        rgb = self.hex_to_rgb(color)
        rgb_normalized = self.rgb_to_range(rgb)
        z = z / 100.
        c = tuple(c * z for c in rgb_normalized)
        self.leds[x]['o'].color = c
        self.leds[x]['b'] = z

    def get_brightness(self, x):
        return self.leds[x]['b']*100.

    def blink(self, x, frequency, time):
        f = frequency*2.
        color = self.leds[x]['c']
        rgb = self.hex_to_rgb(color)
        rgb_normalized = self.rgb_to_range(rgb)
        z = self.leds[x]['b']
        c = tuple(c * z for c in rgb_normalized)
        self.leds[x]['o'].blink(1/f, 1/f, n=int(time*frequency), background=False, on_color=c)

    def dim(self, x, z1, z2, time):
        color = self.leds[x]['c']
        rgb = self.hex_to_rgb(color)
        rgb_normalized = self.rgb_to_range(rgb)
        z1 /= 100.
        z2 /= 100.
        z1_color = tuple(c * z1 for c in rgb_normalized)
        z2_color = tuple(c * z2 for c in rgb_normalized)
        if z1 < z2:
            self.leds[x]['o'].pulse(fade_in_time=time, fade_out_time=0, on_color=z2_color,
                                 off_color=z1_color, n=1, background=False)
        else:
            self.leds[x]['o'].pulse(fade_in_time=0, fade_out_time=time, on_color=z1_color,
                                 off_color=z2_color, n=1, background=False)

    def wait(self, timeSeconds):
        time.sleep(timeSeconds)

    def clear(self):
        pass

    def getTimerValue(self, timer):
        if timer in self.timers:
            return int((time.time() - self.timers[timer]))
        else:
            self.timers[timer] = time.time()
            return 0

    def resetTimer(self, timer):
        self.timers[timer] = time.time()

    def hex_to_rgb(self, hex):
        hex = hex.lstrip('#')
        hlen = len(hex)
        return tuple(int(hex[i:i+hlen/3], 16) for i in range(0, hlen, hlen/3))

    def rgb_to_range(self, rgb):
        return tuple(c / 255. for c in rgb)
class WatchDog:
    def __init__(self):
        self.__loop = asyncio.get_event_loop()
        self.__log = logging.getLogger(self.__class__.__name__)
        self.__stop = False
        self.__tasks = []

    def get_task(self):
        return self.__tasks

    async def __state_monitor(self):
        self.__log.info("Start Monitor state")
        try:
            self.__btn = Button(4)
            self.__current_state = self.__btn.value
            while self.__stop is False:
                await self.__watch_state()
                await asyncio.sleep(0.1)
        except asyncio.CancelledError:
            self.__log.info("Cancelled")
        except:
            self.__log.info(sys.exc_info()[0])
        finally:
            self.__btn.close()

    async def __watch_state(self):
        new_state = self.__btn.value

        if self.__current_state != new_state:
            self.__log.info("State change {} > {}".format(
                self.__current_state, new_state))

            if self.__current_state is True and new_state is False:
                self.__tasks["shutdown"] = asyncio.ensure_future(
                    self.__prepare_for_shutdown())
            elif self.__current_state is False and new_state is True:
                if "shutdown" in self.__tasks:
                    self.__tasks["shutdown"].cancel()
                self.__tasks["start"] = asyncio.ensure_future(
                    self.__prepare_to_start())

            self.__current_state = new_state

    async def __prepare_for_shutdown(self, timeout=10):
        try:
            while self.__stop is False:
                self.__log.info("Shutdown countdown {}".format(timeout))
                await asyncio.sleep(1)

                if timeout == 0:
                    self.__log.info("Shutting down")
                    sh = Shutdown()
                    sh.start()
                    break
                timeout -= 1
        except asyncio.CancelledError:
            self.__log.info("Shutdown Cancelled")

    async def __prepare_to_start(self):
        self.__log.info("Turn on")

    def start(self):
        self.__tasks = {
            "state_monitor": asyncio.ensure_future(self.__state_monitor())
        }

    def shutdown(self):
        self.__stop = True

        for key, task in self.__tasks.items():
            task.cancel()

        time.sleep(1)