예제 #1
0
def buzzers():
    buzzer = TonalBuzzer(15)

    while True:
        buzzer.play("A3")
        time.sleep(1)
        if onStopEvent.is_set():
            buzzer.stop()
            break
def transmission_start_end():
    tbuzzer = TonalBuzzer(22)
    led.blink(0.025, 0.025)
    tbuzzer.play(Tone(frequency=500))
    sleep(3)
    led.off()
    tbuzzer.stop()
    tbuzzer.close()
    return render_template('json.html')
예제 #3
0
class ResultsBuzzer:
    def __init__(self, pin):
        self.buzzer = TonalBuzzer(pin)
        self.min = Tone(self.buzzer.min_tone).frequency
        self.max = Tone(self.buzzer.max_tone).frequency
        self.conversion = (self.max - self.min) / 100

    def update(self, light_value):
        # light_value goes from 0 to 100,
        # so we need to convert it first
        value = round(self.max - light_value * self.conversion)
        self.buzzer.play(Tone(frequency=value))
예제 #4
0
파일: leds.py 프로젝트: gugumice/kiosk
class buzzer(object):
    def __init__(self,pin=12,seq=(70,80)):
        self._buzzer=TonalBuzzer(pin)
        self.seq=seq
    def beep(self,n=1,t=.1):
       for i in range(0,n):
          for tn in self.seq:
              try:
                  self._buzzer.play(Tone(midi=tn))
              except:
                  pass
              sleep(t)
              self._buzzer.stop()
예제 #5
0
def get_tag():
    buzzer = TonalBuzzer(17)
    buzzer.play(220)
    clf = nfc.ContactlessFrontend('tty:AMA2:pn532')
    target = None
    while target is None:
        target = clf.sense(nfc.clf.RemoteTarget('106A'), nfc.clf.RemoteTarget('106B'),
                                nfc.clf.RemoteTarget('212F'))
        if target is None:
            pass
        else:
            buzzer.stop()
            tag = nfc.tag.activate(clf, target)
            clf.close()
            return str(tag).split("ID=")[1]
예제 #6
0
def main():
    # 各ピンをbuzzer設定
    factory = PiGPIOFactory()
    buzzer = TonalBuzzer(BUZZER_PIN, pin_factory=factory)

    # 音を鳴らす
    try:
        # 音符指定
        for onpu in ONPUS:
            buzzer.play(Tone(onpu))
            sleep(0.5)
        buzzer.stop()
        sleep(0.5)

        # midi note指定 (!!!57-81の範囲のみ指定可能)
        for note_no in range(60, 80, 5):
            buzzer.play(Tone(midi=note_no)) # middle C in MIDI notation
            sleep(0.5)
        buzzer.stop()
        sleep(0.5)

        # 周波数指定
        for freq in range(300, 400, 100):
            buzzer.play(Tone(frequency=freq))
            sleep(0.5)
        buzzer.stop()
        sleep(0.5)
    except:
        buzzer.stop()
        print("stop")

    return
예제 #7
0
def alarm_buzzer_melody():
    tone_buzzer = TonalBuzzer(27)

    for _ in range(5):
        tone_buzzer.play(Tone("C4"))
        sleep(0.15)
        tone_buzzer.play(Tone("G4"))
        sleep(0.15)
        tone_buzzer.play(Tone("F4"))
        sleep(0.15)

        tone_buzzer.stop()
        sleep(2)
예제 #8
0
            haveKey = member['value']
        if member['name'] == 'haveMotion':
            haveMotion = member['value']
    print("Have key: ", haveKey)
    print("Have motion: ", haveMotion)
    #Security mode
    if ((haveKey == False) and (haveMotion == False)):
        #Make have Motion true
        if pir.motion_detected:
            put_motion = requests.put(
                'http://localhost:5000/info/security/haveMotion', data=None)
            print("Motion detected!")
            notify = False
    elif ((haveMotion == True) and (haveKey == False)):
        print("Motion detected!")
        bz.play("C4")
        filename = "/home/pi/Desktop/SmartHome/images/" + (
            time.strftime("%y%b%d_%H:%M:%S")) + ".jpg"
        camera.capture(filename)
        #result = authenticate()
        get_keys = requests.get('http://localhost:5000/info/security/keys')
        keys = get_keys.json()

        status, TagType = reader.read_no_block()
        if status == None:
            continue
        else:
            id, text = reader.read()
            bz.play("A4")
            for member in keys:
                if member['key'] == id:
예제 #9
0
### TonalBuzzer not support PiGPIO
#from gpiozero.pins.pigpio import PiGPIOFactory
from gpiozero import TonalBuzzer
from time import sleep

#tones = ["C4", "E4", "G4"]
tones = ["G4", "C4", "A4", "F4", "E4", "C4", "D4"]

tbz = TonalBuzzer(12)

for tone in tones:
    tbz.play(tone)
    sleep(1)
    tbz.stop()
    sleep(0.1)
예제 #10
0
class Ticker:
    def __init__(self, lcd_rs, lcd_e, lcd_data, buzzer_pin, red_led_pin,
                 yellow_led_pin, green_led_pin, button_pins, fm_username: str,
                 fm_key: str, spot_client: str, spot_secret: str,
                 spot_refresh: str):
        self.lcd = CharLCD(numbering_mode=GPIO.BCM,
                           cols=lcd_width,
                           rows=2,
                           pin_rs=lcd_rs,
                           pin_e=lcd_e,
                           pins_data=lcd_data,
                           auto_linebreaks=True)
        self.lcd.cursor_mode = 'hide'
        self.leds = TrafficLights(red=red_led_pin,
                                  yellow=yellow_led_pin,
                                  green=green_led_pin,
                                  pwm=True)

        self.buzzer = TonalBuzzer(buzzer_pin)
        self.buzzer_lock = Lock()

        self.notif_button = Button(button_pins[0])
        self.notif_button.when_activated = self.handle_notif_click

        self.button2 = Button(button_pins[1])
        self.button2.when_activated = lambda: self.queue_text('hey', 'hey')

        self.button3 = Button(button_pins[2])
        self.button4 = Button(button_pins[3])
        self.button4.when_held = self.handle_network_hold

        self.location = DisplayLocation.home

        self.pulled_idle_text = dict()

        self.notification_queue = Queue()
        self.display_queue = Queue()
        self.display_thread = Thread(target=self.display_worker,
                                     name='display',
                                     daemon=True)

        self.network_active = True

        self.rsession = Session()
        self.fmnet = FMNetwork(username=fm_username, api_key=fm_key)
        self.spotnet = SpotNetwork(
            NetworkUser(client_id=spot_client,
                        client_secret=spot_secret,
                        refresh_token=spot_refresh)).refresh_access_token()

        self.network_pull_thread = Thread(target=self.network_pull_worker,
                                          name='puller',
                                          daemon=True)

    def start(self):
        logger.info('starting ticker')

        self.lcd.clear()
        self.display_thread.start()
        self.network_pull_thread.start()
        self.set_status(green=True)

    def set_status(self, green: bool = False, yellow: bool = False):
        self.leds.green.value = 1 if green else 0
        self.leds.yellow.value = 1 if yellow else 0

    # HANDLERS

    def handle_notif_click(self):
        if not self.notification_queue.empty():
            while not self.notification_queue.empty():
                self.display_queue.put(self.notification_queue.get())
            self.leds.red.off()
        else:
            self.queue_text('No Notifications', '', interrupt=True, time=1)

    def handle_network_hold(self):
        self.network_active = not self.network_active

        logger.info(f'setting network activity {self.network_active}')

        if self.network_active:
            self.set_status(green=True)
        else:
            self.set_status(yellow=True)

        self.beep()

    # THREADS

    def network_pull_worker(self):
        """thread function for pulling network display items and update cache"""
        while True:
            if self.network_active:
                try:
                    total = self.fmnet.get_scrobble_count_from_date(
                        input_date=date.today())
                    logger.debug(f'loaded daily scrobbles {total}')

                    # self.queue_text('Scrobbles Today', total)
                    self.pulled_idle_text['daily_scrobbles'] = DisplayItem(
                        'Scrobbles Today', str(total))
                except LastFMNetworkException as e:
                    logger.exception(e)
                    self.queue_text(
                        'Last.FM Error',
                        f'{e.http_code}, {e.error_code}, {e.message}')

                try:
                    artists = self.fmnet.get_top_artists(
                        period=FMNetwork.Range.WEEK, limit=3)
                    logger.debug(f'loaded top artists')

                    self.pulled_idle_text['weekly_artists'] = DisplayItem(
                        'Weekly Artists',
                        ', '.join([str(i) for i in artists]),
                        iterations=1)
                except LastFMNetworkException as e:
                    logger.exception(e)
                    self.queue_text(
                        'Last.FM Error',
                        f'{e.http_code}, {e.error_code}, {e.message}')

                # try:
                #     from_time = date.today()
                #     from_time = datetime(year=from_time.year, month=from_time.month, day=1)
                #
                #     to_time = datetime.now()
                #
                #     total = len(self.fmnet.get_recent_tracks(from_time=from_time, to_time=to_time, page_limit=200))
                #     logger.debug(f'loaded monthly scrobbles {total}')
                #
                #     # self.queue_text('Scrobbles Today', total)
                #     self.pulled_idle_text['monthly_scrobbles'] = DisplayItem('This Month', str(total))
                # except LastFMNetworkException as e:
                #     logger.exception(e)
                #     self.queue_text('Last.FM Error', f'{e.http_code}, {e.error_code}, {e.message}')

                try:
                    playlist_total = len(self.spotnet.get_user_playlists())
                    logger.debug(f'loaded daily scrobbles {playlist_total}')

                    self.pulled_idle_text['playlist_count'] = DisplayItem(
                        'Playlists', str(playlist_total))
                except SpotifyNetworkException as e:
                    logger.exception(e)
                    self.queue_text('Spotify Error',
                                    f'{e.http_code}, {e.message}')

            sleep(net_thread_interval)

    def display_worker(self):
        """LCD controller, reads queue for new items to display or roll over idle items"""
        while True:
            if not self.display_queue.empty():
                display_item = self.display_queue.get(block=False)
                logger.info(
                    f'dequeued {display_item}, size {self.display_queue.qsize()}'
                )

                self.write_display_item(display_item)
                self.display_queue.task_done()

            else:
                if len(self.idle_text
                       ) > 0 and self.location == DisplayLocation.home:
                    for key, item in self.idle_text.items():
                        if not self.display_queue.empty():
                            break

                        logger.debug(f'writing {key}')
                        self.write_display_item(item)
                else:
                    self.write_to_lcd(['Ticker...', ''])
            sleep(display_thread_interval)

    # DISPLAY

    def write_display_item(self, display_item):
        """write display item to LCD now"""
        if display_item.message is None:
            display_item.message = ''

        if len(display_item.message) > lcd_width:
            buffer = [display_item.title, '']
            self.write_to_lcd(buffer)
            self.loop_string(display_item.message,
                             buffer,
                             row=1,
                             iterations=display_item.iterations)
        else:
            buffer = [display_item.title, display_item.message]
            self.write_to_lcd(buffer)
            sleep(display_item.time)

    def queue_notification(self,
                           title,
                           message,
                           wrap_line=False,
                           iterations=2):
        logger.debug(
            f'queueing {title}/{message} {iterations} times, wrapped: {wrap_line}'
        )
        self.notification_queue.put(
            DisplayItem(title, str(message), wrap_line, iterations))
        self.leds.red.pulse()

    def queue_text(self,
                   title,
                   message,
                   wrap_line=False,
                   time=5,
                   iterations=2,
                   interrupt=False):
        logger.debug(
            f'queueing {title}/{message} {iterations} times, wrapped: {wrap_line}'
        )

        item = DisplayItem(title,
                           str(message),
                           wrap_line=wrap_line,
                           iterations=iterations,
                           time=time)
        if interrupt:
            self.write_display_item(item)
        else:
            self.display_queue.put(item)

    def write_to_lcd(self, framebuffer):
        """Write the framebuffer out to the specified LCD."""
        self.lcd.home()
        for row in framebuffer:
            self.lcd.write_string(row.ljust(lcd_width)[:lcd_width])
            self.lcd.write_string('\r\n')

    def loop_string(self, string, framebuffer, row, delay=0.4, iterations=2):
        padding = ' ' * lcd_width
        s = padding + string + padding
        for round_trip in range(iterations):
            for i in range(len(s) - lcd_width + 1):
                framebuffer[row] = s[i:i + lcd_width]
                self.write_to_lcd(framebuffer)
                sleep(delay)

    @property
    def idle_text(self) -> dict:
        """merge last pulled with system pullable text items"""
        system_idle = dict()

        now = datetime.now()
        system_idle['date'] = DisplayItem(title=now.strftime('%d.%m.%y'),
                                          message=now.strftime('%R'))

        return {**system_idle, **self.pulled_idle_text}

    # SOUND

    def beep(self):
        self.buzzer_lock.acquire()

        self.buzzer.play(Tone("A4"))
        sleep(0.1)
        self.buzzer.stop()
        sleep(0.1)

        self.buzzer_lock.release()
예제 #11
0
class CozmarsServer:
    async def __aenter__(self):
        await self.lock.acquire()
        self.lmotor = Motor(*self.conf['motor']['left'])
        self.rmotor = Motor(*self.conf['motor']['right'])
        # self.reset_servos()
        self.reset_motors()
        self.lir = LineSensor(self.conf['ir']['left'],
                              queue_len=3,
                              sample_rate=10,
                              pull_up=True)
        self.rir = LineSensor(self.conf['ir']['right'],
                              queue_len=3,
                              sample_rate=10,
                              pull_up=True)
        sonar_cfg = self.conf['sonar']
        self.sonar = DistanceSensor(trigger=sonar_cfg['trigger'],
                                    echo=sonar_cfg['echo'],
                                    max_distance=sonar_cfg['max'],
                                    threshold_distance=sonar_cfg['threshold'],
                                    queue_len=5,
                                    partial=True)

        self._sensor_event_queue = None
        self._button_last_press_time = 0

        def cb(ev, obj, attr):
            return lambda: self._sensor_event_queue and self.event_loop.call_soon_threadsafe(
                self._sensor_event_queue.put_nowait, (ev, getattr(obj, attr)))

        def button_press_cb():
            if self._sensor_event_queue:
                now = time.time()
                if now - self._button_last_press_time <= self._double_press_max_interval:
                    ev = 'double_pressed'
                else:
                    ev = 'pressed'
                self.event_loop.call_soon_threadsafe(
                    self._sensor_event_queue.put_nowait, (ev, True))
                self._button_last_press_time = now

        self.lir.when_line = self.lir.when_no_line = cb(
            'lir', self.lir, 'value')
        self.rir.when_line = self.rir.when_no_line = cb(
            'rir', self.rir, 'value')
        self.button.hold_time = 1
        self.button.when_pressed = button_press_cb
        self.button.when_released = cb('pressed', self.button, 'is_pressed')
        self.button.when_held = cb('held', self.button, 'is_held')
        self.sonar.when_in_range = cb('in_range', self.sonar, 'distance')
        self.sonar.when_out_of_range = cb('out_of_range', self.sonar,
                                          'distance')
        self.screen.fill(0)
        self.screen_backlight.fraction = .05

        return self

    async def __aexit__(self, exc_type, exc, tb):
        self.stop_all_motors()
        self.buzzer.stop()
        for a in [
                self.sonar, self.lir, self.rir, self.lmotor, self.rmotor,
                self.cam
        ]:
            a and a.close()
        self.screen_backlight.fraction = None
        self.lock.release()

    def __del__(self):
        self.button.close()
        self.buzzer.close()

    def __init__(self, conf_path=util.CONF, env_path=util.ENV):
        with open(conf_path) as cf:
            self.conf = json.load(cf)

        with open(env_path) as ef:
            self.env = json.load(ef)

        self.lock = asyncio.Lock()
        self.event_loop = asyncio.get_running_loop()

        self.button = Button(self.conf['button'])
        self.buzzer = TonalBuzzer(self.conf['buzzer'])

        self.servokit = ServoKit(channels=16, freq=self.conf['servo']['freq'])

        self.screen_backlight = self.servokit.servo[self.conf['servo']
                                                    ['backlight']['channel']]
        self.screen_backlight.set_pulse_width_range(
            0, 100000 // self.conf['servo']['freq'])
        self.screen_backlight.fraction = 0
        spi = board.SPI()
        cs_pin = digitalio.DigitalInOut(
            getattr(board, f'D{self.conf["screen"]["cs"]}'))
        dc_pin = digitalio.DigitalInOut(
            getattr(board, f'D{self.conf["screen"]["dc"]}'))
        reset_pin = digitalio.DigitalInOut(
            getattr(board, f'D{self.conf["screen"]["rst"]}'))
        self.screen = st7789.ST7789(
            spi,
            rotation=90,
            width=135,
            height=240,
            x_offset=53,
            y_offset=40,
            cs=cs_pin,
            dc=dc_pin,
            rst=reset_pin,
            baudrate=24000000,
        )
        self.servo_update_rate = self.conf['servo']['update_rate']
        self._double_press_max_interval = .5
        self.reset_servos()
        self._head.angle = self.rarm.fraction = self.larm.fraction = 0
        time.sleep(.5)
        self.relax_lift()
        self.relax_head()
        self.cam = None

    @staticmethod
    def conf_servo(servokit, conf):
        servo = servokit.servo[conf['channel']]
        servo.set_pulse_width_range(conf['min_pulse'], conf['max_pulse'])
        return servo

    def reset_motors(self):
        self.motor_compensate = {
            'forward': list(self.conf['motor']['forward']),
            'backward': list(self.conf['motor']['backward'])
        }

    def reset_servos(self):
        self.rarm = CozmarsServer.conf_servo(self.servokit,
                                             self.conf['servo']['right_arm'])
        self.larm = CozmarsServer.conf_servo(self.servokit,
                                             self.conf['servo']['left_arm'])
        self._head = CozmarsServer.conf_servo(self.servokit,
                                              self.conf['servo']['head'])
        self._head.set_actuation_range(-20, 20)

    def save_conf(self, conf_path=util.CONF):
        # only servo and motor configs are changed
        for servo_name, servo in zip(('right_arm', 'left_arm', 'head'),
                                     (self.rarm, self.larm, self._head)):
            self.conf['servo'][servo_name]['max_pulse'] = servo.max_pulse
            self.conf['servo'][servo_name]['min_pulse'] = servo.min_pulse
        for dir in ('forward', 'backward'):
            self.conf['motor'][dir] = list(self.motor_compensate[dir])
        with open(conf_path, 'w') as f:
            json.dump(self.conf, f, indent=2)

    def calibrate_motor(self, direction, left, right):
        self.motor_compensate[direction] = [left, right]

    def calibrate_servo(self, channel, min_pulse=None, max_pulse=None):
        '''
        for s in self.conf['servo'].values():
            if isinstance(s, dict) and s.get('channel')==channel:
                s['min_pulse'] = min_pulse
                s['max_pulse'] = max_pulse
        '''
        servo = self.servokit.servo[channel]
        servo.set_pulse_width_range(min_pulse or servo.min_pulse, max_pulse
                                    or servo.max_pulse)

    def get_env(self, name):
        return self.env[name]

    def set_env(self, name, value):
        self.env[name] = value

    def del_env(self, name):
        del self.env[name]

    def save_env(self, env_path=util.ENV):
        with open(env_path, 'w') as f:
            json.dump(self.env, f, indent=2)

    def real_speed(self, sp):
        '''
        1. compensate for speed inbalance of two motors
        2. the motors won't run when speed is lower than .2,
            so we map speed from (0, 1] => (.2, 1], (0, -1] => (-.2, -1] and 0 => 0
        '''
        if not isinstance(sp, Iterable):
            sp = (sp, sp)
        sp = (s * self.motor_compensate['forward' if s > 0 else 'backward'][i]
              for i, s in enumerate(sp))
        return tuple((s * .8 + (.2 if s > 0 else -.2) if s else 0) for s in sp)

    def mapped_speed(self, sp):
        # real speed -> mapped speed
        if not isinstance(sp, Iterable):
            sp = (sp, sp)
        sp = (((s - ((.2 if s > 0 else -.2))) / .8 if s else 0) for s in sp)
        return tuple(
            max(
                -1,
                min(
                    1, s /
                    self.motor_compensate['forward' if s > 0 else 'backward']
                    [i])) for i, s in enumerate(sp))

    async def speed(self, speed=None, duration=None):
        if speed is None:
            return self.mapped_speed((self.lmotor.value, self.rmotor.value))
        speed = self.real_speed(speed)
        while (self.lmotor.value, self.rmotor.value) != speed:
            linc = speed[0] - self.lmotor.value
            if 0 < abs(linc) < .3:
                self.lmotor.value = speed[0]
            elif linc:
                self.lmotor.value += .3 if linc > 0 else -.3
            rinc = speed[1] - self.rmotor.value
            if 0 < abs(rinc) < .3:
                self.rmotor.value = speed[1]
            elif rinc:
                self.rmotor.value += .3 if rinc > 0 else -.3
            await asyncio.sleep(.05)
        if duration:
            await asyncio.sleep(duration)
            await self.speed((0, 0))

    def stop_all_motors(self):
        self.lmotor.value = self.rmotor.value = 0
        self.relax_lift()
        self.relax_head()

    async def backlight(self, *args):
        if not args:
            return self.screen_backlight.fraction or 0
        value = args[0]
        duration = speed = None
        try:
            duration = args[1]
            speed = args[2]
        except IndexError:
            pass
        if not (duration or speed):
            self.screen_backlight.fraction = value or 0
            return
        elif speed:
            if not 0 < speed <= 1 * self.servo_update_rate:
                raise ValueError(
                    f'Speed must be 0 ~ {1*self.servo_update_rate}')
            duration = (value - self.screen_backlight.fraction) / speed
        steps = int(duration * self.servo_update_rate)
        interval = 1 / self.servo_update_rate
        try:
            inc = (value - self.screen_backlight.fraction) / steps
            for _ in range(steps):
                await asyncio.sleep(interval)
                self.screen_backlight.fraction += inc
        except (ZeroDivisionError, ValueError):
            pass
        finally:
            self.screen_backlight.fraction = value

    def relax_lift(self):
        self.larm.relax()
        self.rarm.relax()

    def relax_head(self):
        self._head.relax()

    async def lift(self, *args):
        if not args:
            return self.rarm.fraction
        height = args[0]
        if height == None:
            self.rarm.fraction = self.larm.fraction = height
            return
        if not 0 <= height <= 1:
            raise ValueError('Height must be 0 to 1')
        duration = speed = None
        try:
            duration = args[1]
            speed = args[2]
        except IndexError:
            pass
        if not (self.rarm.fraction != None and (speed or duration)):
            self.rarm.fraction = height
            self.larm.fraction = height
            return
        elif speed:
            if not 0 < speed <= 1 * self.servo_update_rate:
                raise ValueError(
                    f'Speed must be 0 ~ {1*self.servo_update_rate}')
            duration = abs(height - self.larm.fraction) / speed
        if duration == 0:
            return
        steps = int(duration * self.servo_update_rate)
        interval = 1 / self.servo_update_rate
        try:
            inc = (height - self.larm.fraction) / steps
            for _ in range(steps):
                await asyncio.sleep(interval)
                self.larm.fraction += inc
                self.rarm.fraction += inc
        except (ZeroDivisionError, ValueError):
            pass
        finally:
            self.rarm.fraction = height
            self.larm.fraction = height

    async def head(self, *args):
        if not args:
            return self._head.angle
        angle = args[0]
        if angle == None:
            self._head.angle = None
            return
        if not -20 <= angle <= 20:
            raise ValueError('Angle must be -20 ~ 20')
        duration = speed = None
        try:
            duration = args[1]
            speed = args[2]
        except IndexError:
            pass
        if not (self._head.angle != None and (speed or duration)):
            self._head.angle = angle
            return
        elif speed:
            if not 0 < speed <= 80 * self.servo_update_rate:
                raise ValueError(
                    f'Speed must be 0 ~ {80*self.servo_update_rate}')
            duration = abs(angle - self._head.angle) / speed
        steps = int(duration * self.servo_update_rate)
        interval = 1 / self.servo_update_rate
        try:
            inc = (angle - self._head.angle) / steps
            for _ in range(steps):
                await asyncio.sleep(interval)
                self._head.angle += inc
        except (ZeroDivisionError, ValueError):
            pass
        finally:
            self._head.angle = angle

    def display(self, image_data, x, y, x1, y1):
        self.screen._block(x, y, x1, y1, image_data)

    def fill(self, color565, x, y, w, h):
        self.screen.fill_rectangle(x, y, w, h, color565)

    def pixel(self, x, y, color565):
        return self.screen.pixel(x, y, color565)

    def gif(self, gif, loop):
        #https://github.com/adafruit/Adafruit_CircuitPython_RGB_screen/blob/master/examples/rgb_screen_pillow_animated_gif.py
        raise NotImplemented

    async def play(self, *, request_stream):
        async for freq in request_stream:
            self.buzzer.play(
                Tone.from_frequency(freq)) if freq else self.buzzer.stop()

    async def tone(self, freq, duration=None):
        self.buzzer.play(
            Tone.from_frequency(freq)) if freq else self.buzzer.stop()
        if duration:
            await asyncio.sleep(duration)
            self.buzzer.stop()

    async def sensor_data(self, update_rate=None):
        timeout = 1 / update_rate if update_rate else None
        try:
            # if the below queue has a max size, it'd better be a `RPCStream` instead of `asyncio.Queue`,
            # and call `force_put_nowait` instead of `put_nowait` in `loop.call_soon_threadsafe`,
            # otherwise if the queue if full,
            # an `asyncio.QueueFull` exception will be raised inside the main loop!
            self._sensor_event_queue = asyncio.Queue()
            yield 'lir', self.lir.value
            yield 'rir', self.rir.value
            while True:
                try:
                    yield await asyncio.wait_for(
                        self._sensor_event_queue.get(), timeout)
                except asyncio.TimeoutError:
                    yield 'sonar', self.sonar.distance
        except Exception as e:
            self._sensor_event_queue = None
            raise e

    def double_press_max_interval(self, *args):
        if args:
            self._double_press_max_interval = args[0]
        else:
            return self._double_press_max_interval

    def hold_repeat(self, *args):
        if args:
            self.button.hold_repeat = args[0]
        else:
            return self.button.hold_repeat

    def hold_time(self, *args):
        if args:
            self.button.hold_time = args[0]
        else:
            return self.button.hold_time

    def threshold_distance(self, *args):
        if args:
            self.sonar.threshold_distance = args[0]
        else:
            return self.sonar.threshold_distance

    def max_distance(self, *args):
        if args:
            self.sonar.max_distance = args[0]
        else:
            return self.sonar.max_distance

    def distance(self):
        return self.sonar.distance

    def microphone_volume(self, *args):
        from subprocess import check_output
        if args:
            if 0 <= args[0] <= 100:
                check_output(f'amixer set Boost {args[0]}%'.split(' '))
            else:
                raise ValueError('volume must be 0 ~ 100')
        else:
            a = check_output('amixer get Boost'.split(' '))
            return int(a[a.index(b'[') + 1:a.index(b'%')])

    async def capture(self, options):
        import picamera, io
        if self.cam is None or self.cam.closed:
            self.cam = picamera.PiCamera()
            self.cam.vflip = self.cam.hflip = True
        delay = options.pop('delay', 0)
        standby = options.pop('standby', False)
        try:
            buf = io.BytesIO()
            delay and await asyncio.sleep(delay)
            self.cam.capture(buf, **options)
            buf.seek(0)
            return buf.read()
        finally:
            not standby and self.cam.close()

    async def camera(self, width, height, framerate):
        import picamera, io, threading, time
        try:
            queue = RPCStream(2)
            stop_ev = threading.Event()

            def bg_run(loop):
                nonlocal queue, stop_ev, width, height, framerate
                with picamera.PiCamera(resolution=(width, height),
                                       framerate=framerate) as cam:
                    # Camera warm-up time
                    time.sleep(2)
                    stream = io.BytesIO()
                    for _ in cam.capture_continuous(stream,
                                                    'jpeg',
                                                    use_video_port=True):
                        if stop_ev.isSet():
                            break
                        stream.truncate()
                        stream.seek(0)
                        loop.call_soon_threadsafe(queue.force_put_nowait,
                                                  stream.read())
                        # queue.put_nowait(stream.read())
                        stream.seek(0)

            loop = asyncio.get_running_loop()
            # threading.Thread(target=bg_run, args=[loop]).start()
            bg_task = loop.run_in_executor(None, bg_run, loop)

            while True:
                yield await queue.get()

        finally:
            stop_ev.set()
            await bg_task

    async def microphone(self,
                         samplerate=16000,
                         dtype='int16',
                         block_duration=.1):
        import sounddevice as sd
        channels = 1
        # blocksize_sec = .1
        # bytes_per_sample = dtype[-2:]//8
        # blocksize = int(blocksize_sec * channels * samplerate * bytes_per_sample)
        blocksize = int(block_duration * channels * samplerate)
        loop = asyncio.get_running_loop()
        queue = RPCStream(2)

        def cb(indata, frames, time, status):
            nonlocal queue, loop
            if status:
                print(status, file=sys.stderr)
                raise sd.CallbackAbort
            loop.call_soon_threadsafe(queue.force_put_nowait, bytes(indata))

        with sd.RawInputStream(callback=cb,
                               samplerate=samplerate,
                               blocksize=blocksize,
                               channels=channels,
                               dtype=dtype):
            while True:
                yield await queue.get()
예제 #12
0
from gpiozero import DistanceSensor
from time import sleep

from gpiozero import TonalBuzzer
from gpiozero.tones import Tone
b = TonalBuzzer(14)
b.play(Tone("A4"))
sleep(.1)
b.play(Tone("C4"))
sleep(.1)
b.stop()

sensorleft = DistanceSensor(echo=24, trigger=23, max_distance=3)
sensorright = DistanceSensor(echo=6, trigger=5, max_distance=3)

while True:
    print(
        f'DistanceLeft: {sensorleft.distance * 100:.2f}    DistanceRight: {sensorright.distance * 100:.2f}'
    )
    sleep(1.0)

exit(0)
예제 #13
0
from gpiozero import TonalBuzzer
from gpiozero.tones import Tone
from signal import pause
from time import sleep
b = TonalBuzzer(25)

b.play(Tone(220))
sleep(.1)
b.play(Tone(500))
sleep(.1)

예제 #14
0
class main_bot:
    def __init__(self, level='lvl0'):
        #instantiating all the motors and sensors on the bot
        self.robot = Robot(left=MOTOR_L, right=MOTOR_R)
        self.sonic = DistanceSensor(echo=SONIC_ECHO, trigger=SONIC_TRIG)
        self.ir_l = MCP3008(IR_L)
        self.ir_r = MCP3008(IR_R)
        self.button = MCP3008(BTN)
        self.bz = TonalBuzzer(BZ)
        self.led = RGBLED(R, G, B)
        #creating custom variables
        self.speed = self.get_speed(level)

    def get_sensor_info(self):
        #getting the the sonic info
        self.sonic_info = self.sonic.distance * 100
        #getting both ir values and putting it into a tuple
        self.ir_info = (0 if self.ir_l.value == 1 else 1,
                        0 if self.ir_r.value == 1 else 1)
        #getting the button value and storing it
        self.button_info = 1 if self.button.value == 1 else 0
        #returning a tuple of the info
        return (self.sonic_info, self.ir_info, self.button_info)

    def get_speed(self, level):
        default_speed = .4
        lvl_dict = {  #creating the levels and corrispondoing speeds
            '0': default_speed,
            '1': .5,
            '2': .6,
            '3': .7,
            '4': .8,
            '5': 1
        }

        if len(level) == 4:  #checking to see if level is written as lvl<int>
            lvl = level[-1]  #gets the last str
            try:  #tries to return a value within the dict
                return lvl_dict[
                    lvl]  #returns the value associated with the key lvl
            except:  #if the value selected wasnt in the dictionary
                warnings.warn(
                    'the selected lvl doesnt exists, defaulting to lvl0')
                return default_speed
        else:
            #creates a warning of missmatching vals and returns default speed
            warnings.warn('len(level)!=4, resulting to DEFAULT SPEED')
            return default_speed

    def start(self):  #starts the robot motors with selected speed
        print('##### starting the motors #####')
        sleep(3)
        self.robot.forward(self.speed)

    def action(self, value):  #function that controls the turn
        #checking the value of action and either turning, go forward or stopping
        if value == 0:
            self.robot.forward(self.speed)
        elif value == 1:
            self.robot.left(self.speed)
        elif value == 2:
            self.robot.right(self.speed)
        elif value == -1:
            self.robot.stop()
        else:
            raise ValueError(
                'The Hardware.action value was not 0, 1 or 2 or -1')

    def _test_sensors(self):  #testing all the sensors
        #initalizing all the gpio pins
        for _ in range(120):
            #printing all the values of the sensors
            print('SONIC: {}\t IR_LEFT: {}\t IR_RIGHT: {}\t \
             BUTTON: {}'.format(self.sonic.distance * 100, self.ir_l.value,
                                self.ir_r.value, self.button.value))
            sleep(.5)

    def _test_motors(self):  #testing motors
        print('testing motors')
        self.robot.left(self.speed)
        sleep(1)
        self.robot.right(self.speed)
        sleep(1)

    def _test_audio(self):  #testing audio
        print('testing audio')
        self.bz.play('A4')
        sleep(.2)
        self.bz.stop()

    def _test_audio_import(self):
        print('testing audio import')
        s_and_c.game_start_audio(self.bz)

    def _test_led_import(self):
        print('testing led')
        s_and_c.game_start_led(self.led)
예제 #15
0
from gpiozero import Robot
from time import sleep

# Wrong kind of buzzer
#from gpiozero import Buzzer
#bz = Buzzer(14)
#bz.on()

from gpiozero import TonalBuzzer
from gpiozero.tones import Tone
b = TonalBuzzer(14)
b.play(Tone("A4"))
sleep(.1)
b.play(Tone("C4"))
sleep(.1)
b.play(Tone("D4"))
sleep(.1)
b.play(Tone("E4"))
sleep(.1)
b.stop()

exit(0)
예제 #16
0
파일: buzzer.py 프로젝트: Mte90/Daployer
class Buzzer():
    def __init__(self, pin):
        self.buzzer = TonalBuzzer(pin)

    def beep(self):
        print('  Beep!')
        self.buzzer.play(Tone("A4"))

    def no(self):
        self.buzzer.stop()

    def siren(self):
        print('  Siren!')
        self.buzzer.source = sin_values()

    def scale(self, pick=1):
        music = ''
        pause = 1
        print('  Scale ' + str(pick) + '!')
        if pick == 1:
            music = 'C4 D4 E4 F4 G4 A4 B4 C5'
            pause = 0.5
        elif pick == 2:
            music = 'G4 C4 A4 F4 E4 C4 D4'
        for note in music.split():
            tone = Tone(note)
            self.buzzer.play(tone)
            sleep(pause)
            self.no()

    # from https://www.raspberrypi.org/magpi/hack-electronics-gpio-zero-1-5/
    def pinkpanther(self):
        print('  Pink Panther!')
        tune = [
            ('C#4', 0.2), ('D4', 0.2), (None, 0.2), ('Eb4', 0.2), ('E4', 0.2),
            (None, 0.6), ('F#4', 0.2), ('G4', 0.2), (None, 0.6), ('Eb4', 0.2),
            ('E4', 0.2), (None, 0.2), ('F#4', 0.2), ('G4', 0.2), (None, 0.2),
            ('C4', 0.2), ('B4', 0.2), (None, 0.2), ('F#4', 0.2), ('G4', 0.2),
            (None, 0.2), ('B4', 0.2), ('Bb4', 0.5), (None, 0.6), ('A4', 0.2),
            ('G4', 0.2), ('E4', 0.2), ('D4', 0.2), ('E4', 0.2)
        ]

        for note, duration in tune:
            self.buzzer.play(note)
            sleep(float(duration))
        self.no()

    # https://github.com/junhaoliao/raspi/blob/master/tonalBuzzer.py
    def twinkle_twinkle(self):
        print('  Twinkle Twinkle!')
        tune = [
            "C4",
            "C4",
            "G4",
            "G4",
            "A4",
            "A4",
            "G4",
            "F4",
            "F4",
            "E4",
            "E4",
            "D4",
            "D4",
            "C4",
            "G4",
            "G4",
            "F4",
            "F4",
            "E4",
            "E4",
            "D4",
            "G4",
            "G4",
            "F4",
            "F4",
            "E4",
            "E4",
            "D4",
            "C4",
            "C4",
            "G4",
            "G4",
            "A4",
            "A4",
            "G4",
            "F4",
            "F4",
            "E4",
            "E4",
            "D4",
            "D4",
            "C4",
        ]

        cnt = 0
        for note in tune:
            self.buzzer.play(note)
            sleep(0.15)
            self.no()
            sleep(0.03)
            cnt += 1
            if (cnt == 7):
                cnt = 0
                sleep(0.15)
                self.no()

    @threaded
    def for_seconds(self, seconds, sound='beep'):
        print('  Beep for ' + str(seconds) + ' seconds!')
        if sound == 'beep':
            self.beep()
        else:
            self.siren()
        sleep(seconds)
        self.no()
예제 #17
0
from time import sleep
from gpiozero import TonalBuzzer
from gpiozero.tones import Tone

buzzerPin = 'GPIO13'

buzzer = TonalBuzzer(buzzerPin, octaves=3)

crappy_jingle = [
    Tone('C#6'), 'P', 'P', 'P',
    Tone('C#5'),
    Tone('F#5'),
    Tone('C#5'),
    Tone('G#5')
]

for note in crappy_jingle:
    print(note)
    if note != 'P':
        buzzer.play(note)
    sleep(0.25)
예제 #18
0
class PomodoroTimer(object):
    def __init__(self):
        self.timer = None
        self.led = PWMLED(LIGHT_PIN)
        self.buzzer = TonalBuzzer(BUZZER_PIN)

    def times_up(self):
        print("Time's up")
        self.fin()

    def start_pomodoro(self, channel):
        print("Start Pomodoro")
        self.led.blink(on_time=0.3, off_time=0.3, n=5, background=True)

        if (self.timer != None):
            print("Pomodoro was re-started")
            self.timer.cancel()

        self.timer = Timer(5, self.times_up)
        self.timer.start()

    def play_note(self, note, duration=0.04):
        self.buzzer.play(Tone.from_note(note))
        sleep(duration)
        self.buzzer.stop()

    def ending_music(self):
        # Available Range
        # A3, B3, C4, D4, E4, F4, G4, A4, B4
        arpeggio = [
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "C4",
            "E4",
            "G4",
            "C4",
            "E4",
            "G4",
            "C4",
            "E4",
            "G4",
            "C4",
            "E4",
            "G4",
            "Cb4",
            "Eb4",
            "Gb4",
            "Cb4",
            "Eb4",
            "Gb4",
            "Cb4",
            "Eb4",
            "Gb4",
            "Cb4",
            "Eb4",
            "Gb4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A#3",
            "C#4",
            "E#4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
            "A3",
            "C4",
            "E4",
        ]

        for note in arpeggio:
            self.play_note(note)

        self.play_note("A3", duration=0.2)

    def fin(self):
        self.led.pulse()
        self.ending_music()
        self.led.off()

    def run(self):
        self.button = Button(BUTTON_PIN, pull_up=False)
        self.button.when_pressed = self.start_pomodoro

        pause()
예제 #19
0
#!/usr/bin/env python

from gpiozero import TonalBuzzer
from gpiozero.tones import Tone
from time import sleep

buzzer = TonalBuzzer(pin=21, initial_value=None, mid_tone=Tone('A4'), octaves=1)

print("Playing: A4...")
buzzer.play(Tone("A4"))
sleep(1)

print("...B4")
buzzer.play("B4")
sleep(0.5)

print("...C4")
buzzer.play(Tone(frequency=523))
sleep(0.5)

print("...E4")
buzzer.play("E4")
sleep(1)

print("Done, exiting...")
buzzer.stop()
buzzer.close()
exit()