def run(imgFile='lofi.png'): unicornhathd.rotation(0) unicornhathd.brightness(0.6) width, height = unicornhathd.get_shape() img = Image.open(imgFile) a_list = [] threading.Thread(target=input_thread, args=(a_list, )).start() while not a_list: for o_x in range(int(img.size[0] / width)): for o_y in range(int(img.size[1] / height)): valid = False for x in range(width): for y in range(height): pixel = img.getpixel( ((o_x * width) + y, (o_y * height) + x)) r, g, b = int(pixel[0]), int(pixel[1]), int(pixel[2]) if r or g or b: valid = True unicornhathd.set_pixel(x, y, r, g, b) if valid: unicornhathd.show() time.sleep(0.5) unicornhathd.off()
def init(): print('initializing..') unicornhathd.clear() unicornhathd.rotation(270) unicornhathd.brightness(1.0) scroll_text("Hola! Hola! Hola! Hola!", NEUTRAL) unicornhathd.brightness(0.5)
def mainloop(config): unicornhathd.rotation(config["unicornhathd"]["rotation"]) unicornhathd.brightness(config["unicornhathd"]["brightness"]) rss_feeds = [] rss_feeds.append("https://feeds.bbci.co.uk/news/rss.xml") rss_feeds.append("https://feeds.bbci.co.uk/news/world/rss.xml") rss_feeds.append("https://feeds.bbci.co.uk/news/uk/rss.xml") rss_feeds.append("https://feeds.bbci.co.uk/news/business/rss.xml") rss_feeds.append("https://feeds.bbci.co.uk/news/politics/rss.xml") rss_feeds.append("https://feeds.bbci.co.uk/news/health/rss.xml") rss_feeds.append("https://feeds.bbci.co.uk/news/education/rss.xml") rss_feeds.append( "https://feeds.bbci.co.uk/news/science_and_environment/rss.xml") rss_feeds.append("https://feeds.bbci.co.uk/news/technology/rss.xml") rss_feeds.append( "https://feeds.bbci.co.uk/news/entertainment_and_arts/rss.xml") # rss_feeds.append("http://www.eurogamer.net/?format=rss&platform=PS4") rss = [] while True: for rss_feed in rss_feeds: xml_data = get_xml_request(rss_feed) if xml_data: rss.extend(get_data_list(xml_data)) for text in rss: output_text = u"{}: {} ==> {}".format( time.strftime("%d/%m/%Y %H:%M:%S"), text[0], text[1]) scroll_text(output_text) time.sleep(0.25)
def set_attribute(self, imagename, type, speed, brightness): # set attributes from bluetooth data if self._IsInturrpt is True: return if imagename != LED_PASS_ATTRIBUTE: self._curImageName = imagename if type != LED_PASS_ATTRIBUTE: self._curType = type if speed != LED_PASS_ATTRIBUTE: self._curSpeed = speed if brightness != LED_PASS_ATTRIBUTE: self._curBright = brightness unicornhathd.brightness(brightness) obj_LED = {} obj_LED['LED_STATE'] = [] obj_LED['LED_STATE'].append({ 'index': self._curImageName, 'type': self._curType, 'speed': self._curSpeed, 'brightness': self._curBright }) self._saveStateCb(obj_LED)
def show(): text = open('./isaax-project.env', 'r').readlines()[0] matchObj = re.match(r'.*?="(.*)"$', text) lines = matchObj.group(1).split(',') colours = [ tuple([ int(n * 255) for n in colorsys.hsv_to_rgb(x / float(len(lines)), 1.0, 1.0) ]) for x in range(len(lines)) ] FONT = ("/usr/share/fonts/truetype/roboto/Roboto-Bold.ttf", 10) unicornhathd.rotation(0) unicornhathd.brightness(1.0) width, height = unicornhathd.get_shape() text_x = width text_y = 2 font_file, font_size = FONT font = ImageFont.truetype(font_file, font_size) text_width, text_height = width, 0 for line in lines: w, h = font.getsize(line) text_width += w + width text_height = max(text_height, h) text_width += width + text_x + 1 image = Image.new("RGB", (text_width, max(16, text_height)), (0, 0, 0)) draw = ImageDraw.Draw(image) offset_left = 0 for index, line in enumerate(lines): draw.text((text_x + offset_left, text_y), line, colours[index], font=font) offset_left += font.getsize(line)[0] + width for scroll in range(text_width - width): for x in range(width): for y in range(height): pixel = image.getpixel((x + scroll, y)) r, g, b = [int(n) for n in pixel] unicornhathd.set_pixel(width - 1 - x, y, r, g, b) unicornhathd.show() time.sleep(0.01) unicornhathd.off() return True
def __init__(self): unicornhathd.clear() unicornhathd.set_all(10, 0, 10) unicornhathd.show() unicornhathd.rotation(270) # Rotation unicornhathd.brightness(.75) unicornhathd.show()
def calibrate_preview(): '''Opens a preview for user focusing, then takes series of pics for averaging and background subtraction''' with picamera.PiCamera() as camera: camera.resolution = (1664, 1232) camera.awb_mode = 'off' camera.awb_gains = (1.2, 1.2) camera.framerate = 30 camera.start_preview() pihat.brightness(1.0) pihat.clear() for y in range(16): for x in range(16): v = display[x, y] # brightness depends on range if v == 0: red = int(255) # makes 0-1 range > 0-255 range green = int(255) blue = int(255) elif v == 1: red = int(0) green = int(0) blue = int(0) elif v == 2: red = int(0) green = int(0) blue = int(0) pihat.set_pixel(x, y, red, green, blue) # sets pixels on the hat pihat.rotation(180) pihat.show() # show the pixels GPIO.output(VALVE, True) time.sleep(20) GPIO.output(VALVE, False) pihat.clear() pihat.off() camera.stop_preview()
def available_status(): text = "I am currently available. Feel freeto enter :)" unicornhathd.clear() unicornhathd.brightness(.6) for xValue in range(0, 15): for yValue in range(0, 15): unicornhathd.set_pixel(xValue, yValue, 0, 255, 0) try: while True: for xValue in range(0, 15): for yValue in range(0, 15): unicornhathd.set_pixel(xValue, yValue, 0, 255, 0) unicornhathd.show() time.sleep(4) unicornhathd.clear() unicornhathd.off() print_status(text, 255, 0, 0) unicornhathd.clear() time.sleep(2) except KeyboardInterrupt: print("error") unicornhathd.off()
def display_animation(image, brightness): #displays a animation as multi png unicornhathd.rotation(90) unicornhathd.brightness(brightness) width, height = unicornhathd.get_shape() img = Image.open(image) try: while True: for o_x in range(int(img.size[0] / width)): for o_y in range(int(img.size[1] / height)): valid = False for x in range(width): for y in range(height): pixel = img.getpixel( ((o_x * width) + y, (o_y * height) + x)) r, g, b = int(pixel[0]), int(pixel[1]), int( pixel[2]) if r or g or b: valid = True unicornhathd.set_pixel(x, y, r, g, b) if valid: unicornhathd.show() time.sleep(1) except KeyboardInterrupt: unicornhathd.off() return
def run_ticker(bg_color, text): FONT = ("DejaVuSans-Bold.ttf", 10) unicornhathd.rotation(90) unicornhathd.brightness(0.6) width, height = unicornhathd.get_shape() text_x = width text_y = 2 font_file, font_size = FONT font = ImageFont.truetype(font_file, font_size) text_width, text_height = width, 0 w, h = font.getsize(text) text_width += w + width text_height = max(text_height, h) text_width += width + text_x + 1 image = Image.new('RGB', (text_width, max(16, text_height)), color) draw = ImageDraw.Draw(image) offset_left = 0 draw.text((text_x + offset_left, text_y), text, fill="white", font=font) offset_left += font.getsize(text)[0] + width while True: for scroll in range(text_width - width): for x in range(width): for y in range(height): pixel = image.getpixel((x + scroll, y)) r, g, b = [int(n) for n in pixel] unicornhathd.set_pixel(width - 1 - x, y, r, g, b) unicornhathd.show() time.sleep(0.01)
def __init__(self, rotation): unicornhathd.brightness(0.6) unicornhathd.clear() unicornhathd.rotation(rotation) #(x|colonne, y|lignes) (0,0): en bas à gauche self.c_gris_fonce = [20,20,10] self.c_rouge = [255,0,0] self.c_orange = [240,150,28] self.c_vert = [0,255,0] self.c_bleu = [23,7,238] self.c_jaune = [100,100,0] self.hue_min = 0.33 # color HSV: vert pour un niveau 0% self.hue_max = 1.0 # color HSV: rouge pour un niveau 100% self.hue_delta = self.hue_max - self.hue_min # calculé une fois pour toutes self.msg = Msg() #initialisation de l'affichage self.animation_start() self.draw_titles(self.c_orange) #dessine les titres persistants 4 premières lignes self.draw_level(0,1,6) #fond niveau CPU0 self.draw_level(0,2,6) #fond niveau CPU1 self.draw_level(0,3,6) #fond niveau CPU2 self.draw_level(0,4,6) #fond niveau CPU3 self.draw_level(0,7,6) #fond niveau RAM self.draw_fullbox(10, 6, 14, 10 ,self.c_gris_fonce) #fond niveau DISK self.draw_level(0,1,0) #fond niveau T° unicornhathd.show()
def showSpans(spans): for (startTime, image, brightness) in spans: unicorn.brightness(brightness) showTime(startTime) curImage = showImage(image) unicorn.show() time.sleep(3)
def doClock(clock, spans, stepTime=0.04, showClockTime=datetime.timedelta(seconds=60)): tick = 0 prev = datetime.datetime.fromtimestamp(0) while True: if tick == 0: today = clock.today().replace(hour=0, minute=0, second=0, microsecond=0).date() now = clock.now() # Every minute, show the time if now - prev >= showClockTime: showTime(now) prev = now curSpan = None for (startTime, image, brightness) in spans: st = clock.combine(today, startTime) if st < now: curSpan = (startTime, image, brightness) if curSpan is None: curSpan = spans[-1] (_, image, brightness) = curSpan unicorn.brightness(brightness) curImage = showImage(image) # drawComet(tick, (255, 0, 0), 20, curImage) blinkEye(tick, (255, 0, 0), (20, 0, 0), 10, 3) tick += 1 if (tick >= (width*4)-3): # That is, has gone all the way around. tick = 0 time.sleep(stepTime) unicorn.show()
def display_remote_image(url: str, brightness: float = 0.3) -> None: import unicornhathd response = requests.get(url) source = Image.open(BytesIO(response.content)) unicornhathd.rotation(0) unicornhathd.brightness(brightness) width, height = unicornhathd.get_shape() sat_booster = ImageEnhance.Color(source) img = sat_booster.enhance(1.25) # increase contrast of image contr_booster = ImageEnhance.Contrast(img) img = contr_booster.enhance(1.2) # reduce the number of colors used in picture img = img.convert("P", palette=Image.ADAPTIVE, colors=10) img = source.resize((width, height), resample=Image.BICUBIC) img = ImageOps.mirror(img) for x in range(width): for y in range(height): pixel = img.getpixel((x, y)) r, g, b = int(pixel[0]), int(pixel[1]), int(pixel[2]) unicornhathd.set_pixel(x, y, r, g, b) unicornhathd.show()
def __init__(self, oversample): self.oversample = oversample self.size = 16 * self.oversample self.initGrid() # fire up the unicorn hat unicorn.rotation(90) unicorn.brightness(1) self.width, self.height = unicorn.get_shape()
def setBrightness(currenttime): currenthour = currenttime.tm_hour # if it's between 10 am and 8 pm, # use dimmer brightness if (currenthour < 10 or currenthour > 20): unicorn.brightness(0.5) else: unicorn.brightness(0.8)
def display_text(lines, colors): # Use `fc-list` to show a list of installed fonts on your system, # or `ls /usr/share/fonts/` and explore. FONT = ("/usr/share/fonts/truetype/freefont/FreeSansBold.ttf", 12) # sudo apt install fonts-droid #FONT = ("/usr/share/fonts/truetype/droid/DroidSans.ttf", 12) # sudo apt install fonts-roboto #FONT = ("/usr/share/fonts/truetype/roboto/Roboto-Bold.ttf", 10) unicornhathd.rotation(90) unicornhathd.brightness(1.0) width, height = unicornhathd.get_shape() text_x = width text_y = 2 font_file, font_size = FONT font = ImageFont.truetype(font_file, font_size) text_width, text_height = width, 0 for line in lines: w, h = font.getsize(line) text_width += w + width text_height = max(text_height, h) text_width += width + text_x + 1 image = Image.new("RGB", (text_width, max(16, text_height)), (0, 0, 0)) draw = ImageDraw.Draw(image) offset_left = 0 for index, line in enumerate(lines): draw.text((text_x + offset_left, text_y), line, colors[index], font=font) offset_left += font.getsize(line)[0] + width for scroll in range(text_width - width): for x in range(width): for y in range(height): pixel = image.getpixel((x + scroll, y)) r, g, b = [int(n) for n in pixel] unicornhathd.set_pixel(width - 1 - x, y, r, g, b) unicornhathd.show() time.sleep(0.02) unicornhathd.off()
def __init__(self): self._lock_ui = _thread.allocate_lock() unicorn.rotation(270) unicorn.brightness(0.5) self._unicorn_width, self._unicorn_height = unicorn.get_shape() self._default_font_file = 'fonts/Hack-Regular.ttf' self._default_font_size = 12 self._default_font = ImageFont.truetype(self._default_font_file, self._default_font_size)
def __init__(self): unicorn.brightness(1) unicorn.rotation(180) self.xDim = 16 self.yDim = 16 self.xMax = self.xDim -1 self.xMin = 0 self.yMax = self.yDim -1 self.yMin = 0 self.debugMe = False
def unicorn_init(): unicorn.brightness(BRIGHTNESS) if UNICORN_VERSION == "HD": unicorn.rotation(0) elif UNICORN_VERSION == "SD": unicorn.rotation(90) else: log_string( 'No valid Unicorn Version found in config file - use "SD" or "HD"') unicorn.clear() unicorn.show()
def startup(): brightness_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8] colour_list = [[185, 185, 185], [0, 0, 185], [128, 28, 200], [0, 185, 0], [255, 255, 255], [185, 0, 0], [185, 153, 26], [185, 80, 0]] random.shuffle(colour_list) for count in range(0, 8): unicornhathd.brightness(brightness_list[count]) ui_utils.set_all_pixel_to(colour_list[count][0], colour_list[count][1], colour_list[count][2], unicornhathd) unicornhathd.show() time.sleep(0.5)
def unicorn_init(): unicorn.brightness(BRIGHTNESS) if UNICORN_VERSION == "HD": unicorn.rotation(0) elif UNICORN_VERSION == "SD": unicorn.rotation(90) else: log_string('No valid Unicorn Version found in config file - use "SD" or "HD"') unicorn.clear() unicorn.show()
def set_brightness(): """Set the Unicorn hat's brightness according to the current sunrise/sunset time""" now = datetime.datetime.now() latitude, longitude = get_current_location() loc = LocationInfo(latitude=latitude, longitude=longitude) sunInfo = sun.sun(loc.observer, date=now.date(), tzinfo=get_localzone_name()) utcNow = datetime.datetime.now(datetime.timezone.utc) if utcNow < sunInfo["sunrise"] or utcNow > sunInfo["sunset"]: unicorn.brightness(0.10) else: unicorn.brightness(0.75)
def display_text(data): text = "{} from {} backers = {}%!".format(data['pledged'], data['backers'], data['percent']) colours = [ tuple([int(n * 255) for n in colorsys.hsv_to_rgb(x / 1.0, 1.0, 1.0)]) for x in range(1) ] FONT = ("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 12) unicornhathd.rotation(0) unicornhathd.brightness(1.0) width, height = unicornhathd.get_shape() text_x = width text_y = 2 font_file, font_size = FONT font = ImageFont.truetype(font_file, font_size) text_width, text_height = width, 0 w, h = font.getsize(text) text_width += w + width text_height = max(text_height, h) text_width += width + text_x + 1 image = Image.new("RGB", (text_width, max(16, text_height)), (0, 0, 0)) draw = ImageDraw.Draw(image) offset_left = 0 draw.text((text_x, text_y), text, colours[index], font=font) for scroll in range(text_width - width): for x in range(width): for y in range(height): pixel = image.getpixel((x + scroll, y)) r, g, b = [int(n) for n in pixel] unicornhathd.set_pixel(width - 1 - x, y, r, g, b) unicornhathd.show() time.sleep(0.01) unicornhathd.off() return
def display_clock( hours, minutes, brightness, cycle, color_width ): #temperature has tobe string with at least two chars (add whitspace before)| add color coutner which is counted in main FONT = ("/home/pi/.fonts/fixed.ttf", 10) #also time font in file unicornhathd.rotation(0) unicornhathd.brightness(brightness) width, height = unicornhathd.get_shape() text_x = width text_y = 0 font_file, font_size = FONT font = ImageFont.truetype(font_file, font_size) w, text_height = font.getsize(hours) image = Image.new("RGB", (16, max(16, text_height)), (0, 0, 0)) draw = ImageDraw.Draw(image) draw.fontmode = "1" #turn antialiasing off for pixel fonts #draw.line(((11,0),(11,15)),(0,0,255),1) #draw.text((-1, 1), hours, (255,255,0), font=font) #todo change rand int colours draw.text((-1, 0), hours, (0, 255, 0), font=font) draw.text((-1, 9), minutes, (0, 255, 0), font=font) for x in range(12): for y in range(16): pixel = image.getpixel((x, y)) r, g, b = [int(n) for n in pixel] if r > 0 or g > 0 or b > 0: r, g, b = [ int(n * 255) for n in colorsys.hsv_to_rgb((y + cycle) / float(color_width), 1.0, 1.0) ] unicornhathd.set_pixel(-x - 1, y, r, g, b) #unicornhathd.show() return
def tidal_handler(*args): try: unicornhathd.brightness(1) red = 0 blue = 0 green = 0 crush = False sustain = 1 ldecay = 0.05 for num, arg in enumerate(args, start=1): ## print("{0}: {1}".format(num, arg)) if arg == "red": red = int(args[num]) elif arg == "green": green = int(args[num]) elif arg == "blue": blue = int(args[num]) elif arg == "ldecay": ldecay = float(args[num]) elif arg == "sustain": sustain = float(args[num]) elif arg == "crush": crush = True print("r: {0}, g: {1}, b: {2}, crush: {3}, sustain: {4}, ldecay: {5}". format(red, green, blue, crush, sustain, ldecay)) if crush == True: red = 255 blue = 255 green = 255 ldecay = 1.0 unicornhathd.set_all(red, green, blue) unicornhathd.show() ## print("about to sleep for {0}".format(ldecay * sustain)) time.sleep(ldecay * sustain) ## print(".....awake!") unicornhathd.off() except KeyboardInterrupt: unicornhathd.off()
def display_data(data): width, height = unicornhathd.get_shape() num_pix = width * height unicornhathd.rotation(90) unicornhathd.brightness(0.5) percent = floor(float(data['percent']) * float(num_pix)) for x in range(width): for y in range(height): pix = x * width + y if pix < percent: unicornhathd.set_pixel(x, y, 255, 255, 255) else: unicornhathd.set_pixel(x, y, 0, 0, 0) unicornhathd.show() return
def start(): threading.Timer(3.0, start).start() FONT = ('/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', 12) width, height = unicornhathd.get_shape() text_x = width text_y = 2 font_file, font_size = FONT font = ImageFont.truetype(font_file, font_size) text_width, text_height = width, 0 lines = str(datetime.datetime.now())[10:-10] colours = [tuple([int(n * 255) for n in colorsys.hsv_to_rgb(x / float(len(lines)), 1.0, 1.0)]) for x in range(len(lines))] unicornhathd.rotation(90) if (int(lines[:3])>=21 or int(lines[:3])<9): unicornhathd.brightness(0.01) else: unicornhathd.brightness(1) for line in lines: w, h = font.getsize(line) text_width += w + width text_height = max(text_height, h) text_width += width + text_x + 1 image = Image.new('RGB', (text_width, max(16, text_height)), (0, 0, 0)) draw = ImageDraw.Draw(image) offset_left = 0 for index, line in enumerate(lines): draw.text((text_x + offset_left, text_y), line, colours[index], font=font) offset_left += font.getsize(line)[0] + 1 for scroll in range(text_width - width): for x in range(width): for y in range(height): pixel = image.getpixel((x + scroll, y)) r, g, b = [int(n) for n in pixel] unicornhathd.set_pixel(width - 1 - x, y, r, g, b) unicornhathd.show()
def prepareImage(self): self.width, self.height = unicornhathd.get_shape() unicornhathd.brightness(0.5) text_x = 1 text_y = 2 # Load the font using PIL's ImageFont font = ImageFont.truetype(self.font, self.font_size) # Ask the loaded font how big our text will be self.text_width, self.text_height = font.getsize(self.text) # Make sure we accommodate enough width to account for our text_x left offset self.text_width += self.width + text_x # Now let's create a blank canvas wide enough to accomodate our text self.image = Image.new('RGB', (self.text_width, max(self.height, self.text_height)), (0, 0, 0)) # To draw on our image, we must use PIL's ImageDraw draw = ImageDraw.Draw(self.image) # And now we can draw text at our desited (text_x, text_y) offset, using our loaded font draw.text((text_x, text_y), self.text, fill=(255, 255, 255), font=font)
def __init__(self, state, save_stat_cb): if state is not None: for ledState in state['LED_STATE']: self._curImageName = ledState['index'] self._curType = float(ledState['type']) self._curSpeed = float(ledState['speed']) self._curBright = float(ledState['brightness']) unicornhathd.brightness(self._curBright) else: self._curImageName = LED_DEFAULT_NAME self._curType = LED_DEFAULT_TYPE self._curSpeed = LED_DEFAULT_SPEED self._curBright = LED_DEFAULT_BRIGHT unicornhathd.brightness(LED_DEFAULT_BRIGHT) self._IsInturrpt = False self._saveStateCb = save_stat_cb
def do_light_thing(context): unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(.40) width, height = unicorn.get_shape() while True: if context.current_color == "green": set_color(0, 255, 0) elif context.current_color == "red": set_color(255, 0, 0) elif context.current_color == "blue": set_color(0, 0, 255) elif context.current_color == "yellow": set_color(255, 255, 0) else: unicorn.clear() unicorn.show() time.sleep(0.05)