Загрузка исходника
This commit is contained in:
Executable
+282
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Controls the LEDs on the ReSpeaker 2mic HAT, inspired by smart speakers like Alexa and Alice."""
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from functools import partial
|
||||
from math import ceil
|
||||
from typing import Tuple, List, Optional
|
||||
import gpiozero
|
||||
import spidev
|
||||
from wyoming.asr import Transcript
|
||||
from wyoming.event import Event
|
||||
from wyoming.satellite import (
|
||||
RunSatellite,
|
||||
SatelliteConnected,
|
||||
SatelliteDisconnected,
|
||||
StreamingStarted,
|
||||
StreamingStopped,
|
||||
)
|
||||
from wyoming.server import AsyncEventHandler, AsyncServer
|
||||
from wyoming.vad import VoiceStarted, VoiceStopped
|
||||
from wyoming.wake import Detection
|
||||
_LOGGER = logging.getLogger()
|
||||
NUM_LEDS = 3
|
||||
LEDS_GPIO = 12
|
||||
RGB_MAP = {
|
||||
"rgb": [3, 2, 1],
|
||||
"rbg": [3, 1, 2],
|
||||
"grb": [2, 3, 1],
|
||||
"gbr": [2, 1, 3],
|
||||
"brg": [1, 3, 2],
|
||||
"bgr": [1, 2, 3],
|
||||
}
|
||||
async def main() -> None:
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--uri", required=True, help="unix:// or tcp://")
|
||||
parser.add_argument("--debug", action="store_true", help="Log DEBUG messages")
|
||||
parser.add_argument(
|
||||
"--led-brightness",
|
||||
type=int,
|
||||
choices=range(1, 32),
|
||||
default=31,
|
||||
help="LED brightness (integer from 1 to 31)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)
|
||||
_LOGGER.debug(args)
|
||||
_LOGGER.info("Ready")
|
||||
# Turn on power to LEDs
|
||||
led_power = gpiozero.LED(LEDS_GPIO, active_high=False)
|
||||
led_power.on()
|
||||
leds = APA102(num_led=NUM_LEDS, global_brightness=args.led_brightness)
|
||||
# Start server
|
||||
server = AsyncServer.from_uri(args.uri)
|
||||
try:
|
||||
await server.run(partial(LEDsEventHandler, args, leds))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
leds.cleanup()
|
||||
led_power.off()
|
||||
# -----------------------------------------------------------------------------
|
||||
_BLACK = (0, 0, 0)
|
||||
_WHITE = (255, 255, 255)
|
||||
_RED = (255, 0, 0)
|
||||
_YELLOW = (255, 255, 0)
|
||||
_BLUE = (0, 0, 255)
|
||||
_GREEN = (0, 255, 0)
|
||||
_PURPLE = (128, 0, 128)
|
||||
_ORANGE = (255, 165, 0)
|
||||
_CYAN = (0, 255, 255)
|
||||
class LEDsEventHandler(AsyncEventHandler):
|
||||
"""Event handler for clients, with animations inspired by Alexa and Alice."""
|
||||
def __init__(
|
||||
self,
|
||||
cli_args: argparse.Namespace,
|
||||
leds: "APA102",
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.cli_args = cli_args
|
||||
self.client_id = str(time.monotonic_ns())
|
||||
self.leds = leds
|
||||
self.voice_active = False
|
||||
self.voice_animation_task: Optional[asyncio.Task] = None
|
||||
self.streaming_active = False
|
||||
self.streaming_animation_task: Optional[asyncio.Task] = None
|
||||
_LOGGER.debug("Client connected: %s", self.client_id)
|
||||
async def handle_event(self, event: Event) -> bool:
|
||||
_LOGGER.debug(event)
|
||||
if StreamingStarted.is_type(event.type):
|
||||
self.streaming_active = True
|
||||
if self.streaming_animation_task is None or self.streaming_animation_task.done():
|
||||
self.streaming_animation_task = asyncio.create_task(self.streaming_animation_loop())
|
||||
elif Detection.is_type(event.type):
|
||||
# Как Alexa: directional blue spotlight for wake/listening
|
||||
await self.rotate_colors([_BLUE, _CYAN, _BLACK], rotations=5, delay=0.2) # Вращение для "просыпания"
|
||||
self.color(_BLACK)
|
||||
elif VoiceStarted.is_type(event.type):
|
||||
self.voice_active = True
|
||||
if self.voice_animation_task is None or self.voice_animation_task.done():
|
||||
self.voice_animation_task = asyncio.create_task(self.voice_animation_loop())
|
||||
elif Transcript.is_type(event.type):
|
||||
# Как Alexa/Alice: Зеленый успех или эмоция (мигание зеленым для подтверждения)
|
||||
await self.pulse_color(_GREEN, pulses=2, duration=0.8)
|
||||
self.color(_BLACK)
|
||||
elif VoiceStopped.is_type(event.type):
|
||||
self.voice_active = False
|
||||
if self.voice_animation_task:
|
||||
self.voice_animation_task.cancel()
|
||||
self.voice_animation_task = None
|
||||
await self.fade_out(_BLUE, steps=10, delay=0.15) # Затухание синего, как конец обработки
|
||||
elif StreamingStopped.is_type(event.type):
|
||||
self.streaming_active = False
|
||||
if self.streaming_animation_task:
|
||||
self.streaming_animation_task.cancel()
|
||||
self.streaming_animation_task = None
|
||||
await self.fade_out(_BLUE, steps=10, delay=0.15)
|
||||
elif RunSatellite.is_type(event.type):
|
||||
self.color(_BLACK)
|
||||
elif SatelliteConnected.is_type(event.type):
|
||||
# Разовая анимация при подключении, без loop, чтобы в idle не светилось
|
||||
await self.pulse_color(_GREEN, pulses=2, duration=1.5)
|
||||
self.color(_BLACK)
|
||||
elif SatelliteDisconnected.is_type(event.type):
|
||||
await self.pulse_color(_RED, pulses=3, duration=0.5) # Красный пульс для ошибки, как Alexa purple/red
|
||||
self.color(_BLACK)
|
||||
return True
|
||||
async def voice_animation_loop(self) -> None:
|
||||
"""Loop анимации для VoiceStarted: как Alexa listening/thinking - alternating blue/cyan."""
|
||||
try:
|
||||
while self.voice_active:
|
||||
await self.gradient([_BLUE, _CYAN, _BLUE], duration=1.5) # Градиент для "thinking"
|
||||
await self.rotate_colors([_CYAN, _BLUE, _BLACK], rotations=1, delay=0.3) # Вращение для активности
|
||||
await asyncio.sleep(0.2)
|
||||
except asyncio.CancelledError:
|
||||
self.color(_BLACK)
|
||||
async def streaming_animation_loop(self) -> None:
|
||||
"""Loop для StreamingStarted: pulsing blue как Alexa processing."""
|
||||
try:
|
||||
while self.streaming_active:
|
||||
await self.pulse_color(_BLUE, pulses=1, duration=0.8)
|
||||
await asyncio.sleep(0.2)
|
||||
except asyncio.CancelledError:
|
||||
self.color(_BLACK)
|
||||
def color(self, rgb: Tuple[int, int, int]) -> None:
|
||||
for i in range(NUM_LEDS):
|
||||
self.leds.set_pixel(i, rgb[0], rgb[1], rgb[2])
|
||||
self.leds.show()
|
||||
def set_colors(self, colors: List[Tuple[int, int, int]]) -> None:
|
||||
for i in range(min(NUM_LEDS, len(colors))):
|
||||
self.leds.set_pixel(i, colors[i][0], colors[i][1], colors[i][2])
|
||||
self.leds.show()
|
||||
async def pulse_color(self, rgb: Tuple[int, int, int], pulses: int = 3, duration: float = 0.5) -> None:
|
||||
steps = 10
|
||||
for _ in range(pulses):
|
||||
for bright in range(steps):
|
||||
self.set_pixel_bright(rgb, (bright + 1) / steps * 100)
|
||||
await asyncio.sleep(duration / (2 * steps))
|
||||
for bright in range(steps, 0, -1):
|
||||
self.set_pixel_bright(rgb, (bright - 1) / steps * 100)
|
||||
await asyncio.sleep(duration / (2 * steps))
|
||||
def set_pixel_bright(self, rgb: Tuple[int, int, int], bright_percent: float) -> None:
|
||||
for i in range(NUM_LEDS):
|
||||
self.leds.set_pixel(i, rgb[0], rgb[1], rgb[2], bright_percent)
|
||||
self.leds.show()
|
||||
async def rainbow_cycle(self, steps: int = 20, delay: float = 0.05) -> None:
|
||||
for step in range(steps):
|
||||
colors = []
|
||||
for i in range(NUM_LEDS):
|
||||
r = int((step + i * 85) % 255)
|
||||
g = int((step + i * 85 + 85) % 255)
|
||||
b = int((step + i * 85 + 170) % 255)
|
||||
colors.append((r, g, b))
|
||||
self.set_colors(colors)
|
||||
await asyncio.sleep(delay)
|
||||
self.color(_BLACK)
|
||||
async def gradient(self, colors: List[Tuple[int, int, int]], duration: float = 1.0) -> None:
|
||||
steps = 10
|
||||
for step in range(steps):
|
||||
blended_colors = []
|
||||
for i in range(NUM_LEDS):
|
||||
idx = i % len(colors)
|
||||
next_idx = (idx + 1) % len(colors)
|
||||
r = int(colors[idx][0] + (colors[next_idx][0] - colors[idx][0]) * step / steps)
|
||||
g = int(colors[idx][1] + (colors[next_idx][1] - colors[idx][1]) * step / steps)
|
||||
b = int(colors[idx][2] + (colors[next_idx][2] - colors[idx][2]) * step / steps)
|
||||
blended_colors.append((r, g, b))
|
||||
self.set_colors(blended_colors)
|
||||
await asyncio.sleep(duration / steps)
|
||||
async def fade_out(self, start_rgb: Tuple[int, int, int], steps: int = 10, delay: float = 0.1) -> None:
|
||||
for step in range(steps, 0, -1):
|
||||
r = int(start_rgb[0] * step / steps)
|
||||
g = int(start_rgb[1] * step / steps)
|
||||
b = int(start_rgb[2] * step / steps)
|
||||
self.color((r, g, b))
|
||||
await asyncio.sleep(delay)
|
||||
self.color(_BLACK)
|
||||
async def rotate_colors(self, colors: List[Tuple[int, int, int]], rotations: int = 3, delay: float = 0.2) -> None:
|
||||
current_colors = colors[:NUM_LEDS]
|
||||
for _ in range(rotations):
|
||||
self.set_colors(current_colors)
|
||||
await asyncio.sleep(delay)
|
||||
current_colors = current_colors[-1:] + current_colors[:-1]
|
||||
# -----------------------------------------------------------------------------
|
||||
class APA102:
|
||||
"""
|
||||
Driver for APA102 LEDS (aka "DotStar").
|
||||
(c) Martin Erzberger 2016-2017
|
||||
"""
|
||||
# Constants
|
||||
MAX_BRIGHTNESS = 0b11111 # Safeguard: Set to a value appropriate for your setup
|
||||
LED_START = 0b11100000 # Three "1" bits, followed by 5 brightness bits
|
||||
def __init__(
|
||||
self,
|
||||
num_led,
|
||||
global_brightness,
|
||||
order="rgb",
|
||||
bus=0,
|
||||
device=1,
|
||||
max_speed_hz=8000000,
|
||||
):
|
||||
self.num_led = num_led # The number of LEDs in the Strip
|
||||
order = order.lower()
|
||||
self.rgb = RGB_MAP.get(order, RGB_MAP["rgb"])
|
||||
# Limit the brightness to the maximum if it's set higher
|
||||
if global_brightness > self.MAX_BRIGHTNESS:
|
||||
self.global_brightness = self.MAX_BRIGHTNESS
|
||||
else:
|
||||
self.global_brightness = global_brightness
|
||||
_LOGGER.debug("LED brightness: %d", self.global_brightness)
|
||||
self.leds = [self.LED_START, 0, 0, 0] * self.num_led # Pixel buffer
|
||||
self.spi = spidev.SpiDev() # Init the SPI device
|
||||
self.spi.open(bus, device) # Open SPI port 0, slave device (CS) 1
|
||||
# Up the speed a bit, so that the LEDs are painted faster
|
||||
if max_speed_hz:
|
||||
self.spi.max_speed_hz = max_speed_hz
|
||||
def clock_start_frame(self):
|
||||
self.spi.xfer2([0] * 4) # Start frame, 32 zero bits
|
||||
def clock_end_frame(self):
|
||||
self.spi.xfer2([0xFF] * 4)
|
||||
def set_pixel(self, led_num, red, green, blue, bright_percent=100):
|
||||
if led_num < 0:
|
||||
return # Pixel is invisible, so ignore
|
||||
if led_num >= self.num_led:
|
||||
return # again, invisible
|
||||
brightness = int(ceil(bright_percent * self.global_brightness / 100.0))
|
||||
ledstart = (brightness & 0b00011111) | self.LED_START
|
||||
start_index = 4 * led_num
|
||||
self.leds[start_index] = ledstart
|
||||
self.leds[start_index + self.rgb[0]] = red
|
||||
self.leds[start_index + self.rgb[1]] = green
|
||||
self.leds[start_index + self.rgb[2]] = blue
|
||||
def set_pixel_rgb(self, led_num, rgb_color, bright_percent=100):
|
||||
self.set_pixel(
|
||||
led_num,
|
||||
(rgb_color & 0xFF0000) >> 16,
|
||||
(rgb_color & 0x00FF00) >> 8,
|
||||
rgb_color & 0x0000FF,
|
||||
bright_percent,
|
||||
)
|
||||
def rotate(self, positions=1):
|
||||
cutoff = 4 * (positions % self.num_led)
|
||||
self.leds = self.leds[cutoff:] + self.leds[:cutoff]
|
||||
def show(self):
|
||||
self.clock_start_frame()
|
||||
data = list(self.leds)
|
||||
while data:
|
||||
self.spi.xfer2(data[:32])
|
||||
data = data[32:]
|
||||
self.clock_end_frame()
|
||||
def cleanup(self):
|
||||
self.spi.close() # Close SPI port
|
||||
# -----------------------------------------------------------------------------
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
Executable
+293
@@ -0,0 +1,293 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Controls the LEDs on the ReSpeaker 4mic HAT."""
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from functools import partial
|
||||
from math import ceil
|
||||
from typing import Tuple
|
||||
|
||||
import gpiozero
|
||||
import spidev
|
||||
from wyoming.asr import Transcript
|
||||
from wyoming.event import Event
|
||||
from wyoming.satellite import (
|
||||
RunSatellite,
|
||||
SatelliteConnected,
|
||||
SatelliteDisconnected,
|
||||
StreamingStarted,
|
||||
StreamingStopped,
|
||||
)
|
||||
from wyoming.server import AsyncEventHandler, AsyncServer
|
||||
from wyoming.vad import VoiceStarted
|
||||
from wyoming.wake import Detection
|
||||
|
||||
_LOGGER = logging.getLogger()
|
||||
|
||||
NUM_LEDS = 12
|
||||
LEDS_GPIO = 5
|
||||
RGB_MAP = {
|
||||
"rgb": [3, 2, 1],
|
||||
"rbg": [3, 1, 2],
|
||||
"grb": [2, 3, 1],
|
||||
"gbr": [2, 1, 3],
|
||||
"brg": [1, 3, 2],
|
||||
"bgr": [1, 2, 3],
|
||||
}
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--uri", required=True, help="unix:// or tcp://")
|
||||
#
|
||||
parser.add_argument("--debug", action="store_true", help="Log DEBUG messages")
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)
|
||||
_LOGGER.debug(args)
|
||||
|
||||
_LOGGER.info("Ready")
|
||||
|
||||
# Turn on power to LEDs
|
||||
led_power = gpiozero.LED(LEDS_GPIO, active_high=True)
|
||||
led_power.on()
|
||||
|
||||
leds = APA102(num_led=NUM_LEDS)
|
||||
|
||||
# Start server
|
||||
server = AsyncServer.from_uri(args.uri)
|
||||
|
||||
try:
|
||||
await server.run(partial(LEDsEventHandler, args, leds))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
leds.cleanup()
|
||||
led_power.off()
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
_BLACK = (0, 0, 0)
|
||||
_WHITE = (255, 255, 255)
|
||||
_RED = (255, 0, 0)
|
||||
_YELLOW = (255, 255, 0)
|
||||
_BLUE = (0, 0, 255)
|
||||
_GREEN = (0, 255, 0)
|
||||
|
||||
|
||||
class LEDsEventHandler(AsyncEventHandler):
|
||||
"""Event handler for clients."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cli_args: argparse.Namespace,
|
||||
leds: "APA102",
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.cli_args = cli_args
|
||||
self.client_id = str(time.monotonic_ns())
|
||||
self.leds = leds
|
||||
|
||||
_LOGGER.debug("Client connected: %s", self.client_id)
|
||||
|
||||
async def handle_event(self, event: Event) -> bool:
|
||||
_LOGGER.debug(event)
|
||||
|
||||
if StreamingStarted.is_type(event.type):
|
||||
self.color(_YELLOW)
|
||||
elif Detection.is_type(event.type):
|
||||
self.color(_BLUE)
|
||||
await asyncio.sleep(1.0) # show for 1 sec
|
||||
elif VoiceStarted.is_type(event.type):
|
||||
self.color(_YELLOW)
|
||||
elif Transcript.is_type(event.type):
|
||||
self.color(_GREEN)
|
||||
await asyncio.sleep(1.0) # show for 1 sec
|
||||
elif StreamingStopped.is_type(event.type):
|
||||
self.color(_BLACK)
|
||||
elif RunSatellite.is_type(event.type):
|
||||
self.color(_BLACK)
|
||||
elif SatelliteConnected.is_type(event.type):
|
||||
# Flash
|
||||
for _ in range(3):
|
||||
self.color(_GREEN)
|
||||
await asyncio.sleep(0.3)
|
||||
self.color(_BLACK)
|
||||
await asyncio.sleep(0.3)
|
||||
elif SatelliteDisconnected.is_type(event.type):
|
||||
self.color(_RED)
|
||||
|
||||
return True
|
||||
|
||||
def color(self, rgb: Tuple[int, int, int]) -> None:
|
||||
for i in range(NUM_LEDS):
|
||||
self.leds.set_pixel(i, rgb[0], rgb[1], rgb[2])
|
||||
|
||||
self.leds.show()
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
class APA102:
|
||||
"""
|
||||
Driver for APA102 LEDS (aka "DotStar").
|
||||
(c) Martin Erzberger 2016-2017
|
||||
"""
|
||||
|
||||
# Constants
|
||||
MAX_BRIGHTNESS = 0b11111 # Safeguard: Set to a value appropriate for your setup
|
||||
LED_START = 0b11100000 # Three "1" bits, followed by 5 brightness bits
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_led,
|
||||
global_brightness=MAX_BRIGHTNESS,
|
||||
order="rgb",
|
||||
bus=0,
|
||||
device=1,
|
||||
max_speed_hz=8000000,
|
||||
):
|
||||
self.num_led = num_led # The number of LEDs in the Strip
|
||||
order = order.lower()
|
||||
self.rgb = RGB_MAP.get(order, RGB_MAP["rgb"])
|
||||
# Limit the brightness to the maximum if it's set higher
|
||||
if global_brightness > self.MAX_BRIGHTNESS:
|
||||
self.global_brightness = self.MAX_BRIGHTNESS
|
||||
else:
|
||||
self.global_brightness = global_brightness
|
||||
|
||||
self.leds = [self.LED_START, 0, 0, 0] * self.num_led # Pixel buffer
|
||||
self.spi = spidev.SpiDev() # Init the SPI device
|
||||
self.spi.open(bus, device) # Open SPI port 0, slave device (CS) 1
|
||||
# Up the speed a bit, so that the LEDs are painted faster
|
||||
if max_speed_hz:
|
||||
self.spi.max_speed_hz = max_speed_hz
|
||||
|
||||
def clock_start_frame(self):
|
||||
"""Sends a start frame to the LED strip.
|
||||
|
||||
This method clocks out a start frame, telling the receiving LED
|
||||
that it must update its own color now.
|
||||
"""
|
||||
self.spi.xfer2([0] * 4) # Start frame, 32 zero bits
|
||||
|
||||
def clock_end_frame(self):
|
||||
"""Sends an end frame to the LED strip.
|
||||
|
||||
As explained above, dummy data must be sent after the last real colour
|
||||
information so that all of the data can reach its destination down the line.
|
||||
The delay is not as bad as with the human example above.
|
||||
It is only 1/2 bit per LED. This is because the SPI clock line
|
||||
needs to be inverted.
|
||||
|
||||
Say a bit is ready on the SPI data line. The sender communicates
|
||||
this by toggling the clock line. The bit is read by the LED
|
||||
and immediately forwarded to the output data line. When the clock goes
|
||||
down again on the input side, the LED will toggle the clock up
|
||||
on the output to tell the next LED that the bit is ready.
|
||||
|
||||
After one LED the clock is inverted, and after two LEDs it is in sync
|
||||
again, but one cycle behind. Therefore, for every two LEDs, one bit
|
||||
of delay gets accumulated. For 300 LEDs, 150 additional bits must be fed to
|
||||
the input of LED one so that the data can reach the last LED.
|
||||
|
||||
Ultimately, we need to send additional numLEDs/2 arbitrary data bits,
|
||||
in order to trigger numLEDs/2 additional clock changes. This driver
|
||||
sends zeroes, which has the benefit of getting LED one partially or
|
||||
fully ready for the next update to the strip. An optimized version
|
||||
of the driver could omit the "clockStartFrame" method if enough zeroes have
|
||||
been sent as part of "clockEndFrame".
|
||||
"""
|
||||
|
||||
self.spi.xfer2([0xFF] * 4)
|
||||
|
||||
# Round up num_led/2 bits (or num_led/16 bytes)
|
||||
# for _ in range((self.num_led + 15) // 16):
|
||||
# self.spi.xfer2([0x00])
|
||||
|
||||
def set_pixel(self, led_num, red, green, blue, bright_percent=100):
|
||||
"""Sets the color of one pixel in the LED stripe.
|
||||
|
||||
The changed pixel is not shown yet on the Stripe, it is only
|
||||
written to the pixel buffer. Colors are passed individually.
|
||||
If brightness is not set the global brightness setting is used.
|
||||
"""
|
||||
if led_num < 0:
|
||||
return # Pixel is invisible, so ignore
|
||||
if led_num >= self.num_led:
|
||||
return # again, invisible
|
||||
|
||||
# Calculate pixel brightness as a percentage of the
|
||||
# defined global_brightness. Round up to nearest integer
|
||||
# as we expect some brightness unless set to 0
|
||||
brightness = int(ceil(bright_percent * self.global_brightness / 100.0))
|
||||
|
||||
# LED startframe is three "1" bits, followed by 5 brightness bits
|
||||
ledstart = (brightness & 0b00011111) | self.LED_START
|
||||
|
||||
start_index = 4 * led_num
|
||||
self.leds[start_index] = ledstart
|
||||
self.leds[start_index + self.rgb[0]] = red
|
||||
self.leds[start_index + self.rgb[1]] = green
|
||||
self.leds[start_index + self.rgb[2]] = blue
|
||||
|
||||
def set_pixel_rgb(self, led_num, rgb_color, bright_percent=100):
|
||||
"""Sets the color of one pixel in the LED stripe.
|
||||
|
||||
The changed pixel is not shown yet on the Stripe, it is only
|
||||
written to the pixel buffer.
|
||||
Colors are passed combined (3 bytes concatenated)
|
||||
If brightness is not set the global brightness setting is used.
|
||||
"""
|
||||
self.set_pixel(
|
||||
led_num,
|
||||
(rgb_color & 0xFF0000) >> 16,
|
||||
(rgb_color & 0x00FF00) >> 8,
|
||||
rgb_color & 0x0000FF,
|
||||
bright_percent,
|
||||
)
|
||||
|
||||
def rotate(self, positions=1):
|
||||
"""Rotate the LEDs by the specified number of positions.
|
||||
|
||||
Treating the internal LED array as a circular buffer, rotate it by
|
||||
the specified number of positions. The number could be negative,
|
||||
which means rotating in the opposite direction.
|
||||
"""
|
||||
cutoff = 4 * (positions % self.num_led)
|
||||
self.leds = self.leds[cutoff:] + self.leds[:cutoff]
|
||||
|
||||
def show(self):
|
||||
"""Sends the content of the pixel buffer to the strip.
|
||||
|
||||
Todo: More than 1024 LEDs requires more than one xfer operation.
|
||||
"""
|
||||
self.clock_start_frame()
|
||||
# xfer2 kills the list, unfortunately. So it must be copied first
|
||||
# SPI takes up to 4096 Integers. So we are fine for up to 1024 LEDs.
|
||||
data = list(self.leds)
|
||||
while data:
|
||||
self.spi.xfer2(data[:32])
|
||||
data = data[32:]
|
||||
self.clock_end_frame()
|
||||
|
||||
def cleanup(self):
|
||||
"""Release the SPI device; Call this method at the end"""
|
||||
|
||||
self.spi.close() # Close SPI port
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
name="$(cat)"
|
||||
echo "Wake word detected: ${name}"
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
echo 'Satellite has started.'
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
echo 'Audio streaming to server has started'
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
echo 'Audio streaming to server has stopped'
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
echo 'User has started speaking'
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
echo 'User has stopped speaking'
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
text="$(cat)"
|
||||
echo "Text to speech text: ${text}"
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
text="$(cat)"
|
||||
echo "Speech to text transcript: ${text}"
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
echo 'Text to speech response has started'
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
echo 'Text to speech response has stopped'
|
||||
Executable
+104
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Controls the LEDs on the ReSpeaker Mic Array v2.0 (USB) ."""
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from functools import partial
|
||||
|
||||
from pixel_ring import pixel_ring
|
||||
from wyoming.event import Event
|
||||
from wyoming.satellite import (
|
||||
SatelliteConnected,
|
||||
SatelliteDisconnected,
|
||||
StreamingStarted,
|
||||
StreamingStopped,
|
||||
)
|
||||
from wyoming.server import AsyncEventHandler, AsyncServer
|
||||
from wyoming.snd import Played
|
||||
from wyoming.vad import VoiceStarted, VoiceStopped
|
||||
from wyoming.wake import Detection
|
||||
|
||||
_LOGGER = logging.getLogger()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--uri", required=True, help="unix:// or tcp://")
|
||||
parser.add_argument("--debug", action="store_true", help="Log DEBUG messages")
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)
|
||||
_LOGGER.debug(args)
|
||||
|
||||
_LOGGER.info("Ready")
|
||||
|
||||
# Turn on power to LEDs
|
||||
pixel_ring.set_color_palette(0x0080FF, 0x007A37)
|
||||
pixel_ring.think()
|
||||
await asyncio.sleep(3)
|
||||
pixel_ring.off()
|
||||
|
||||
# Start server
|
||||
server = AsyncServer.from_uri(args.uri)
|
||||
|
||||
try:
|
||||
await server.run(partial(LEDsEventHandler, args))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
pixel_ring.off()
|
||||
|
||||
|
||||
class LEDsEventHandler(AsyncEventHandler):
|
||||
"""Event handler for clients."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cli_args: argparse.Namespace,
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.cli_args = cli_args
|
||||
self.client_id = str(time.monotonic_ns())
|
||||
|
||||
_LOGGER.debug("Client connected: %s", self.client_id)
|
||||
|
||||
async def handle_event(self, event: Event) -> bool:
|
||||
_LOGGER.debug(event)
|
||||
|
||||
if Detection.is_type(event.type):
|
||||
_LOGGER.debug("Detection")
|
||||
pixel_ring.wakeup()
|
||||
elif VoiceStarted.is_type(event.type):
|
||||
_LOGGER.debug("VoiceStarted")
|
||||
pixel_ring.speak()
|
||||
elif VoiceStopped.is_type(event.type):
|
||||
_LOGGER.debug("VoiceStopped")
|
||||
pixel_ring.spin()
|
||||
elif StreamingStopped.is_type(event.type):
|
||||
_LOGGER.debug("StreamingStopped")
|
||||
pixel_ring.off()
|
||||
elif SatelliteConnected.is_type(event.type):
|
||||
_LOGGER.debug("SatelliteConnected")
|
||||
pixel_ring.think()
|
||||
await asyncio.sleep(2)
|
||||
pixel_ring.off()
|
||||
elif Played.is_type(event.type):
|
||||
_LOGGER.debug("Played")
|
||||
pixel_ring.off()
|
||||
elif SatelliteDisconnected.is_type(event.type):
|
||||
_LOGGER.debug("SatelliteDisconnected")
|
||||
pixel_ring.mono(0xFF0000)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
websockets==12.0
|
||||
Executable
+100
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from functools import partial
|
||||
from typing import Optional
|
||||
|
||||
import websockets
|
||||
from wyoming.event import Event
|
||||
from wyoming.server import AsyncEventHandler, AsyncServer
|
||||
|
||||
_LOGGER = logging.getLogger()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--uri", required=True, help="unix:// or tcp://")
|
||||
parser.add_argument("--websocket-host", default="localhost")
|
||||
parser.add_argument("--websocket-port", type=int, default=8675)
|
||||
#
|
||||
parser.add_argument("--debug", action="store_true", help="Log DEBUG messages")
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)
|
||||
_LOGGER.debug(args)
|
||||
|
||||
_LOGGER.info("Ready")
|
||||
|
||||
# Start server
|
||||
server = AsyncServer.from_uri(args.uri)
|
||||
queue: "asyncio.Queue[Optional[Event]]" = asyncio.Queue()
|
||||
|
||||
try:
|
||||
async with websockets.serve(
|
||||
partial(websocket_connected, queue),
|
||||
args.websocket_host,
|
||||
args.websocket_port,
|
||||
):
|
||||
await server.run(partial(WebsocketEventHandler, args, queue))
|
||||
finally:
|
||||
queue.put_nowait(None)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def websocket_connected(queue: "asyncio.Queue[Optional[Event]]", websocket):
|
||||
try:
|
||||
while True:
|
||||
event = await queue.get()
|
||||
if event is None:
|
||||
# Stop signal
|
||||
break
|
||||
|
||||
await websocket.send(
|
||||
json.dumps(
|
||||
{"type": event.type, "data": event.data or {}}, ensure_ascii=False
|
||||
)
|
||||
)
|
||||
except websockets.ConnectionClosed:
|
||||
pass
|
||||
except Exception:
|
||||
_LOGGER.exception("Error in websocket handler")
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WebsocketEventHandler(AsyncEventHandler):
|
||||
"""Event handler for clients."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cli_args: argparse.Namespace,
|
||||
queue: "asyncio.Queue[Optional[Event]]",
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.cli_args = cli_args
|
||||
self.queue = queue
|
||||
|
||||
async def handle_event(self, event: Event) -> bool:
|
||||
_LOGGER.debug(event)
|
||||
self.queue.put_nowait(event)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
BIN
Binary file not shown.
Executable
+244
@@ -0,0 +1,244 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="Wyoming satellite timer example">
|
||||
<meta name="author" content="Michael Hansen">
|
||||
|
||||
<title>Wyoming Timer Example</title>
|
||||
<style>
|
||||
body {
|
||||
background-color: black;
|
||||
}
|
||||
|
||||
.timer-container {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.timer {
|
||||
display: flex;
|
||||
width: 100px;
|
||||
height: auto;
|
||||
flex-wrap:wrap;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background-color: #03a9f4;
|
||||
padding: 15px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
|
||||
color: white;
|
||||
margin-right: 20px
|
||||
}
|
||||
|
||||
.time {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.message {
|
||||
text-align: center;
|
||||
width: 90px;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.finished {
|
||||
background-color: red;
|
||||
}
|
||||
|
||||
.paused {
|
||||
background-color: yellow;
|
||||
color: black;
|
||||
}
|
||||
|
||||
.blink {
|
||||
animation: blink-animation 1s linear infinite;
|
||||
-webkit-animation: blink-animation 1s linear infinite;
|
||||
}
|
||||
@keyframes blink-animation {
|
||||
0%, 100% {opacity: 1;}
|
||||
50% {opacity: 0;}
|
||||
}
|
||||
@-webkit-keyframes blink-animation {
|
||||
0%, 100% {opacity: 1;}
|
||||
50% {opacity: 0;}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="timers" class="timer-container">
|
||||
</div>
|
||||
<audio id="audio-finished" hidden controls loop src="timer_finished.wav"></audio>
|
||||
|
||||
<script>
|
||||
let socket = new WebSocket("ws://localhost:8675")
|
||||
var timers = []
|
||||
var finished_timers = 0
|
||||
|
||||
function q(selector) {return document.querySelector(selector)}
|
||||
|
||||
socket.onopen = function(e) {
|
||||
console.log("Connected")
|
||||
};
|
||||
|
||||
socket.onmessage = function(event) {
|
||||
wyo_event = JSON.parse(event.data)
|
||||
if (wyo_event.type == "timer-started") {
|
||||
let timer_info = wyo_event.data
|
||||
timer_info.is_active = true
|
||||
console.log(timer_info)
|
||||
|
||||
timers.push(timer_info)
|
||||
|
||||
let timers_elem = q("#timers")
|
||||
let timer_div = document.createElement("div")
|
||||
timer_div.id = "timer-" + timer_info.id
|
||||
timer_div.classList.add("timer")
|
||||
|
||||
let message_div = document.createElement("div")
|
||||
message_div.classList.add("message")
|
||||
|
||||
if (timer_info.name) {
|
||||
message_div.innerHTML = timer_info.name
|
||||
} else {
|
||||
if (timer_info.start_hours) {
|
||||
message_div.innerHTML += timer_info.start_hours + " hr "
|
||||
}
|
||||
if (timer_info.start_minutes) {
|
||||
message_div.innerHTML += timer_info.start_minutes + " min "
|
||||
}
|
||||
if (timer_info.start_seconds) {
|
||||
message_div.innerHTML += timer_info.start_seconds + " sec "
|
||||
}
|
||||
}
|
||||
timer_div.appendChild(message_div)
|
||||
|
||||
let time_div = document.createElement("div")
|
||||
time_div.classList.add("time")
|
||||
|
||||
let hours = timer_info.start_hours ?? 0
|
||||
let minutes = timer_info.start_minutes ?? 0
|
||||
let seconds = timer_info.start_seconds ?? 0
|
||||
|
||||
time_div.innerHTML =
|
||||
hours.toString().padStart(2, 0) + ":" +
|
||||
minutes.toString().padStart(2, 0) + ":" +
|
||||
seconds.toString().padStart(2, 0);
|
||||
|
||||
timer_div.appendChild(time_div)
|
||||
|
||||
timers_elem.appendChild(timer_div)
|
||||
|
||||
setTimeout(update_timer, 1000, timer_info)
|
||||
}
|
||||
else if (wyo_event.type == "timer-cancelled") {
|
||||
let timer_info = wyo_event.data
|
||||
timers = timers.filter(t => t.id != timer_info.id)
|
||||
let timer_div = q("#timer-" + timer_info.id)
|
||||
if (timer_div) {
|
||||
timer_div.remove()
|
||||
}
|
||||
}
|
||||
else if (wyo_event.type == "timer-updated") {
|
||||
let timer_info = wyo_event.data
|
||||
for (i = 0; i < timers.length; i++) {
|
||||
if (timers[i].id == timer_info.id) {
|
||||
timers[i].is_active = timer_info.is_active
|
||||
timers[i].total_seconds = timer_info.total_seconds
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
let timer_div = q("#timer-" + timer_info.id)
|
||||
if (timer_div) {
|
||||
if (timer_info.is_active) {
|
||||
timer_div.classList.remove("paused")
|
||||
} else {
|
||||
timer_div.classList.add("paused")
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (wyo_event.type == "timer-finished") {
|
||||
let timer_info = wyo_event.data
|
||||
for (i = 0; i < timers.length; i++) {
|
||||
if (timers[i].id == timer_info.id) {
|
||||
timers[i].total_seconds = 0
|
||||
finished_timers += 1
|
||||
if (finished_timers == 1) {
|
||||
q("#audio-finished").play()
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
timers = timers.filter(t => t.id != timer_info.id)
|
||||
let timer_div = q("#timer-" + timer_info.id)
|
||||
if (timer_div) {
|
||||
timer_div.classList.add("finished")
|
||||
timer_div.classList.add("blink")
|
||||
|
||||
timer_div.onclick = function() {
|
||||
timer_div.remove()
|
||||
finished_timers = Math.max(0, finished_timers - 1)
|
||||
if (finished_timers == 0) {
|
||||
let audio = q("#audio-finished")
|
||||
audio.pause()
|
||||
audio.currentTime = 0
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let time_div = q("#timer-" + timer_info.id + " .time")
|
||||
if (time_div) {
|
||||
time_div.style.opacity = 0
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
socket.onclose = function(event) {
|
||||
console.log("Disconnected")
|
||||
};
|
||||
|
||||
socket.onerror = function(error) {
|
||||
};
|
||||
|
||||
function update_timer(timer_info) {
|
||||
if (timer_info.total_seconds < 0) {
|
||||
return
|
||||
}
|
||||
|
||||
let time_div = q("#timer-" + timer_info.id + " .time")
|
||||
if (!time_div) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!timer_info.is_active) {
|
||||
// Paused
|
||||
setTimeout(update_timer, 1000, timer_info)
|
||||
return
|
||||
}
|
||||
|
||||
if (timer_info.total_seconds > 0) {
|
||||
timer_info.total_seconds -= 1
|
||||
}
|
||||
let total_minutes = Math.floor(timer_info.total_seconds / 60)
|
||||
|
||||
let hours = Math.floor(total_minutes / 60)
|
||||
let minutes = total_minutes % 60
|
||||
let seconds = timer_info.total_seconds % 60
|
||||
|
||||
time_div.innerHTML =
|
||||
hours.toString().padStart(2, 0) + ":" +
|
||||
minutes.toString().padStart(2, 0) + ":" +
|
||||
seconds.toString().padStart(2, 0)
|
||||
|
||||
setTimeout(update_timer, 1000, timer_info)
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user