Skip to content

Instantly share code, notes, and snippets.

@banasiak banasiak/cheerlights.py
Last active Nov 23, 2019

Embed
What would you like to do?
A python script that polls the CheerLights API and sets the LEDs of a Blinkt! hat.
# curl https://get.pimoroni.com/blinkt | bash
import blinkt
import requests
from collections import deque
from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectionError
from sys import exit
from time import sleep
DIM = 0.1
BRIGHT = 1.0
adapter = HTTPAdapter(max_retries=10)
session = requests.Session()
session.mount("http://api.thingspeak.com", adapter)
def hex_to_rgb(hexcolor):
# strip the hash mark and convert hex value to an RGB array
hexcolor = hexcolor.lstrip("#")
return bytearray.fromhex(hexcolor)
def load_color_feed(colors):
# load full API with color history
r = session.get("http://api.thingspeak.com/channels/1417/feed.json", timeout=30)
feeds = r.json()["feeds"]
previous = None
# append new color to array if different from previous
for entry in feeds:
color = entry.get("field2")
if color != previous:
previous = color
colors.append(color)
# reverse the order of the list and truncate it to show the newest 8 colors
colors.reverse()
for i in range(0, len(colors) - blinkt.NUM_PIXELS):
colors.pop()
def load_newest_color(colors):
# load last API with the newest color
r = session.get("http://api.thingspeak.com/channels/1417/field/2/last.json", timeout=30)
color = r.json()["field2"]
previous = colors[0]
# prepend new color to array if different from previous
if color != previous:
print("new color: ", color)
previous = color
# shift the array to the right
colors.rotate(1)
# pop the color that wrapped around from the end
colors.popleft()
# put the new color in it's place
colors.appendleft(color)
# blink the LEDs with the new color
blink_color(color)
def set_pixel(pixel, color, brightness = DIM):
r, g, b = hex_to_rgb(color)
# set the pixel to the RGB value
blinkt.set_pixel(pixel, r, g, b, brightness)
blinkt.show()
def set_all_pixels(color = "#000000", brightness = DIM):
r, g, b = hex_to_rgb(color)
blinkt.set_all(r, g, b, brightness)
blinkt.show()
def set_colors(colors):
for i in range(blinkt.NUM_PIXELS):
c = colors[i]
set_pixel(i, c)
def blink_color(color):
set_all_pixels()
for i in range(3):
set_all_pixels(color, BRIGHT)
sleep(1)
set_all_pixels()
sleep(1)
try:
blinkt.set_brightness(DIM)
blinkt.set_clear_on_exit(True)
# store the colors in a "list-like container with fast appends and pops on either end"
colors = deque()
load_color_feed(colors)
set_colors(colors)
print("initial colors: ", colors)
sleep(10)
while True:
load_newest_color(colors)
set_colors(colors)
sleep(10)
except ConnectionError as e:
print(e)
except KeyboardInterrupt:
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.