├── .gitignore ├── LICENSE ├── README.md ├── demo.gif ├── example.py ├── main.py └── unicornclock ├── __init__.py ├── brightness.py ├── clock.py ├── common.py ├── effects.py ├── fontdriver.py ├── fonts.py ├── utils.py └── widgets.py /.gitignore: -------------------------------------------------------------------------------- 1 | secrets.py 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Charles R. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UnicornClock 2 | 3 | ![Unicorn Clock Example](demo.gif) 4 | 5 | [Example video](https://www.youtube.com/watch?v=Gvnccr2_wY0) 6 | 7 | ## Features 8 | 9 | * NTP time 10 | * Brightness adjustement (manually or automatically) 11 | * Character animation / effect 12 | * Set the position of the clock 13 | * Change the background color, the text, each letters 14 | * You can change the spacing between each letters 15 | * Create your own font 16 | * Easily hackable 17 | * Display a calendar frame 18 | 19 | ## Compatibility 20 | 21 | - Pimoroni Galactic Unicorn 22 | - Work in progress for the Pimoroni Cosmic Unicorn 23 | 24 | ## Installation 25 | 26 | Copy the files into the device via [Thonny](https://thonny.org/) or the way 27 | you want. 28 | 29 | Create a `secrets.py` file: 30 | 31 | ```python 32 | WLAN_SSID = 'Your WLAN SSID' 33 | WLAN_PASSWORD = 'Your secrets password' 34 | ``` 35 | 36 | ### Example 37 | 38 | The [example.py](example.py) display the calendar widget and the clock with an effect when 39 | number changes. 40 | 41 | * Adjust the brightness with the dedicated buttons 42 | * Change the clock and calendar positions with A button 43 | * Change the effect with B button 44 | 45 | ## Use 46 | 47 | Here is a detailed example explaining how to use this project. 48 | 49 | ```python 50 | import uasyncio as asyncio 51 | 52 | # This imports is useful to configure the screen 53 | from galactic import GalacticUnicorn 54 | from picographics import DISPLAY_GALACTIC_UNICORN, PicoGraphics 55 | 56 | # We want to update the brightness and change the position 57 | from unicornclock import Brightness, Clock, Position 58 | 59 | # Import the rainbow move effect 60 | from unicornclock.effects import RainbowMoveEffect 61 | 62 | # Load the GalacticUnicorn and PicoGraphics 63 | galactic = GalacticUnicorn() 64 | graphics = PicoGraphics(DISPLAY_GALACTIC_UNICORN) 65 | 66 | # Here, we declare a rainbow clock by using the RainbowMoveEffect with Clock 67 | class RainbowMoveEffectClock(RainbowMoveEffect, Clock): 68 | pass 69 | 70 | async def example(): 71 | # Create Brightness object for handling the brightness of the screen 72 | # depending of the brightness of the piece (screens have light sensors). 73 | brightness = Brightness(galactic) 74 | 75 | # Creating the Clock 76 | clock = RainbowMoveEffectClock( 77 | galactic, 78 | graphics, 79 | x=Position.CENTER, 80 | show_seconds=True, 81 | am_pm_mode=False, 82 | ) 83 | 84 | # And now, we creating the 2 tasks 85 | asyncio.create_task(brightness.run()) 86 | asyncio.create_task(clock.run()) 87 | 88 | loop = asyncio.get_event_loop() 89 | loop.run_until_complete(example()) 90 | loop.run_forever() 91 | ``` 92 | 93 | ## TODO 94 | 95 | Here is what I plan to add and feel free to make suggestions or code submissions. 96 | 97 | * PID controlled brightness for auto mode 98 | * ~~Save the calendar position / effect and restore it on the boot~~ 99 | * Ability to drive the screen by an HTTP API 100 | * Handle sound 101 | 102 | ## Contribute 103 | 104 | * Your code must respects `flake8` and `isort` tools 105 | * Format your commits with `Commit Conventional` (https://www.conventionalcommits.org/en/v1.0.0/) 106 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugokernel/UnicornClock/90ff471694d05ee8349e2cbff61a159b3be362b7/demo.gif -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | import json 2 | import machine 3 | import network 4 | import time 5 | import uasyncio as asyncio 6 | from galactic import GalacticUnicorn 7 | from machine import Pin 8 | from picographics import DISPLAY_GALACTIC_UNICORN, PicoGraphics 9 | 10 | from unicornclock import Brightness, Clock, Position 11 | from unicornclock.effects import ( 12 | CharacterSlideDownEffect, 13 | RainbowCharEffect, 14 | RainbowPixelEffect, 15 | RainbowMoveEffect, 16 | ) 17 | from unicornclock.utils import debounce, set_time 18 | from unicornclock.widgets import Calendar 19 | 20 | 21 | try: 22 | from secrets import WLAN_SSID, WLAN_PASSWORD 23 | except ImportError: 24 | print("Create secrets.py with WLAN_SSID and WLAN_PASSWORD information.") 25 | raise 26 | 27 | # overclock to 200Mhz 28 | machine.freq(200000000) 29 | 30 | # create galactic object and graphics surface for drawing 31 | galactic = GalacticUnicorn() 32 | graphics = PicoGraphics(DISPLAY_GALACTIC_UNICORN) 33 | 34 | BLACK = graphics.create_pen(0, 0, 0) 35 | BLUE = graphics.create_pen(0, 0, 255) 36 | GREEN = graphics.create_pen(0, 255, 0) 37 | GREY = graphics.create_pen(100, 100, 100) 38 | ORANGE = graphics.create_pen(255, 128, 0) 39 | RED = graphics.create_pen(255, 0, 0) 40 | WHITE = graphics.create_pen(255, 255, 255) 41 | 42 | 43 | UTC_OFFSET = 2 44 | 45 | SETTINGS_FILE = 'demo.json' 46 | 47 | 48 | def wlan_connection(): 49 | """WLAN connection 50 | 51 | During the connection, a colored progress is displayed. 52 | 53 | Color signification: 54 | - RED: Starting the connection 55 | - BLUE: Waiting for WLAN connection 56 | - ORANGE: Waiting for NTP update 57 | - GREEN: Done 58 | """ 59 | width, height = graphics.get_bounds() 60 | 61 | x = 0 62 | def wait(color): 63 | nonlocal x 64 | graphics.set_pen(color) 65 | graphics.rectangle(x, 0, 2, height) 66 | galactic.update(graphics) 67 | x += 2 68 | if x >= width: 69 | x = 0 70 | graphics.set_pen(BLACK) 71 | graphics.clear() 72 | 73 | wait(RED) 74 | 75 | sta_if = network.WLAN(network.STA_IF) 76 | 77 | if not sta_if.isconnected(): 78 | print('Connecting to %s network...' % WLAN_SSID) 79 | sta_if.active(True) 80 | sta_if.connect(WLAN_SSID, WLAN_PASSWORD) 81 | 82 | while not sta_if.isconnected(): 83 | wait(BLUE) 84 | time.sleep(0.25) 85 | 86 | print('Connected to %s network' % WLAN_SSID) 87 | print('Network config:', sta_if.ifconfig()) 88 | 89 | wait(ORANGE) 90 | 91 | set_time(UTC_OFFSET) 92 | 93 | wait(GREEN) 94 | 95 | graphics.set_pen(BLACK) 96 | graphics.clear() 97 | 98 | 99 | class NoSpaceClock(Clock): 100 | space_between_char = lambda _, index, char: 1 if index in (0, 3, 6) else 0 101 | 102 | 103 | class SimpleClock(NoSpaceClock): 104 | 105 | def callback_write_char(self, char, index): 106 | colors = [ 107 | GREY, WHITE, 108 | RED, 109 | GREY, WHITE, 110 | RED, 111 | GREY, WHITE, 112 | ] 113 | graphics.set_pen(colors[index]) 114 | 115 | 116 | class RainbowCharEffectClock( 117 | RainbowCharEffect, 118 | CharacterSlideDownEffect, 119 | NoSpaceClock, 120 | ): 121 | pass 122 | 123 | 124 | class RainbowPixelEffectClock( 125 | RainbowPixelEffect, 126 | CharacterSlideDownEffect, 127 | NoSpaceClock, 128 | ): 129 | pass 130 | 131 | 132 | class RainbowMoveEffectClock(RainbowMoveEffect, NoSpaceClock): 133 | pass 134 | 135 | 136 | effects = [ 137 | SimpleClock, 138 | RainbowCharEffectClock, 139 | RainbowPixelEffectClock, 140 | RainbowMoveEffectClock, 141 | ] 142 | 143 | clock = None 144 | 145 | async def load_example(effect_index, **kwargs): 146 | global clock 147 | 148 | if clock: 149 | clock.is_running = False 150 | 151 | graphics.remove_clip() 152 | graphics.set_pen(BLACK) 153 | graphics.clear() 154 | 155 | default_kwargs = { 156 | 'x': Position.RIGHT, 157 | 'show_seconds': True, 158 | 'am_pm_mode': False, 159 | } 160 | 161 | if kwargs: 162 | default_kwargs.update(kwargs) 163 | 164 | clock = effects[effect_index]( 165 | galactic, 166 | graphics, 167 | **default_kwargs, 168 | ) 169 | 170 | asyncio.create_task(clock.run()) 171 | 172 | mode = 0 173 | effect = 0 174 | 175 | try: 176 | print('Restoring the settings...', end='') 177 | with open(SETTINGS_FILE, 'r') as f: 178 | d = json.loads(f.read()) 179 | except (OSError, ValueError): 180 | print('[ERROR]') 181 | else: 182 | mode = d.get('mode', 0) 183 | effect = d.get('effect', 0) 184 | print('[OK]') 185 | 186 | 187 | async def buttons_handler(brightness, calendar, update_calendar): 188 | clock_kwargs = {} 189 | 190 | @debounce() 191 | def switch_mode(p): 192 | global mode 193 | mode = (mode + 1) % 4 194 | 195 | @debounce() 196 | def switch_effect(p): 197 | global effect 198 | effect = (effect + 1) % len(effects) 199 | 200 | @debounce() 201 | def brightness_down(p): 202 | brightness.adjust(-5) 203 | brightness.update() 204 | 205 | @debounce() 206 | def brightness_up(p): 207 | brightness.adjust(5) 208 | brightness.update() 209 | 210 | Pin(GalacticUnicorn.SWITCH_A, Pin.IN, Pin.PULL_UP) \ 211 | .irq(trigger=Pin.IRQ_FALLING, handler=switch_mode) 212 | 213 | Pin(GalacticUnicorn.SWITCH_B, Pin.IN, Pin.PULL_UP) \ 214 | .irq(trigger=Pin.IRQ_FALLING, handler=switch_effect) 215 | 216 | Pin(GalacticUnicorn.SWITCH_BRIGHTNESS_DOWN, Pin.IN, Pin.PULL_UP) \ 217 | .irq(trigger=Pin.IRQ_FALLING, handler=brightness_down) 218 | 219 | Pin(GalacticUnicorn.SWITCH_BRIGHTNESS_UP, Pin.IN, Pin.PULL_UP) \ 220 | .irq(trigger=Pin.IRQ_FALLING, handler=brightness_up) 221 | 222 | async def load_current_example(): 223 | nonlocal current_effect, current_mode 224 | 225 | print('Change (mode %i, effect %i)' % (mode, effect)) 226 | 227 | if mode == 0: 228 | calendar.set_position(Position.LEFT) 229 | clock_kwargs = { 230 | 'x': Position.RIGHT, 231 | 'callback_hour_change': update_calendar, 232 | } 233 | elif mode == 1: 234 | calendar.set_position(Position.RIGHT) 235 | clock_kwargs = { 236 | 'x': Position.LEFT, 237 | 'callback_hour_change': update_calendar, 238 | } 239 | elif mode == 2: 240 | clock_kwargs = { 241 | 'x': Position.CENTER, 242 | 'callback_hour_change': None, 243 | 'space_between_char': 2, 244 | } 245 | elif mode == 3: 246 | clock_kwargs = { 247 | 'show_seconds': False, 248 | 'x': Position.CENTER, 249 | 'callback_hour_change': None, 250 | 'space_between_char': 2, 251 | } 252 | 253 | await load_example(effect, **clock_kwargs) 254 | 255 | current_mode = mode 256 | current_effect = effect 257 | 258 | current_effect = 0 259 | current_mode = 0 260 | 261 | await load_current_example() 262 | 263 | last_change_time = None 264 | while True: 265 | if mode != current_mode or effect != current_effect: 266 | await load_current_example() 267 | 268 | last_change_time = time.time() 269 | 270 | if last_change_time and last_change_time + 5 < time.time(): 271 | print('Saving the settings file') 272 | with open(SETTINGS_FILE, 'w') as f: 273 | f.write(json.dumps({'mode': mode, 'effect': effect})) 274 | 275 | last_change_time = None 276 | 277 | await asyncio.sleep(0.25) 278 | 279 | 280 | async def example(): 281 | brightness = Brightness(galactic, offset=20) 282 | brightness.update() 283 | 284 | wlan_connection() 285 | 286 | calendar = Calendar(galactic, graphics) 287 | 288 | def update_calendar(*args): 289 | calendar.draw_all() 290 | 291 | asyncio.create_task(brightness.run()) 292 | asyncio.create_task(buttons_handler(brightness, calendar, update_calendar)) 293 | 294 | await load_example(0, callback_hour_change=update_calendar) 295 | 296 | 297 | def main(): 298 | loop = asyncio.get_event_loop() 299 | loop.run_until_complete(example()) 300 | loop.run_forever() 301 | 302 | 303 | if __name__ == '__main__': 304 | main() -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | 2 | from example import main 3 | 4 | main() -------------------------------------------------------------------------------- /unicornclock/__init__.py: -------------------------------------------------------------------------------- 1 | from .brightness import Brightness 2 | from .clock import Clock 3 | from .common import Clip, Position 4 | -------------------------------------------------------------------------------- /unicornclock/brightness.py: -------------------------------------------------------------------------------- 1 | import uasyncio as asyncio 2 | 3 | # Todo: 4 | # - Change the brightness smoothly 5 | 6 | def mapval(value, in_min, in_max, out_min, out_max): 7 | return ( 8 | (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min 9 | ) 10 | 11 | 12 | class Brightness: 13 | 14 | MODE_AUTO = 0 15 | MODE_MANUAL = 1 16 | 17 | mode = MODE_AUTO 18 | level = 50 19 | offset = 0 20 | 21 | def __init__( 22 | self, 23 | galactic, 24 | level=50, 25 | mode=MODE_AUTO, 26 | offset=20, 27 | ): 28 | self.galactic = galactic 29 | self.level = level 30 | self.mode = mode 31 | self.offset = offset 32 | 33 | def export(self): 34 | return { 35 | 'mode': 'manual', 36 | 'level': self.level, 37 | 'current': self.galactic.get_brightness(), 38 | } if self.mode == self.MODE_MANUAL else { 39 | 'mode': 'auto', 40 | 'level': self.get_auto_level(), 41 | 'offset': self.offset, 42 | 'current': self.galactic.get_brightness(), 43 | } 44 | 45 | def get_corrected_level(self, level): 46 | return mapval(level, 0, 100, 0, 1) 47 | 48 | def get_auto_level(self): 49 | return mapval(self.galactic.light(), 0, 4095, 1, 100) 50 | 51 | def update(self): 52 | value = self.level if self.mode == self.MODE_MANUAL else \ 53 | self.get_auto_level() 54 | 55 | self.galactic.set_brightness( 56 | self.get_corrected_level(value + self.offset) 57 | ) 58 | 59 | def set_mode(self, mode, offset=0): 60 | """Set the brightness mode 61 | `mode` is MODE_AUTO or MODE_MANUAL 62 | """ 63 | self.mode = mode 64 | self.offset = offset 65 | 66 | def set_level(self, level): 67 | """Set the brightness level 68 | `level` need to be integer between 0 and 100 69 | """ 70 | self.level = level 71 | 72 | def adjust(self, value): 73 | """Adjust the brightness 74 | `level` need to be integer between 0 and 100 75 | """ 76 | if self.mode == self.MODE_MANUAL: 77 | self.galactic.adjust_brightness(self.get_corrected_level(value)) 78 | else: 79 | self.offset += value 80 | 81 | async def run(self): 82 | while True: 83 | self.update() 84 | await asyncio.sleep(1) -------------------------------------------------------------------------------- /unicornclock/clock.py: -------------------------------------------------------------------------------- 1 | import uasyncio as asyncio 2 | 3 | from .common import Clip, ClockMixin, Position 4 | from .fonts import default as default_font 5 | from .fontdriver import FontDriver 6 | 7 | # Todo: 8 | # Add await on callback_hour_changed 9 | # Rename callback_hour_change to callback_hour_changed ? 10 | 11 | class Clock(ClockMixin, FontDriver): 12 | 13 | show_seconds = False 14 | font_color = None 15 | background_color = None 16 | 17 | callback_after_init = None 18 | callback_hour_change = None 19 | callback_time_updated = None 20 | 21 | is_running = True 22 | 23 | loop_sleep = 0.1 24 | 25 | def __init__( 26 | self, 27 | galactic, 28 | graphics, 29 | x=0, 30 | y=0, 31 | show_seconds=False, 32 | am_pm_mode=False, 33 | font_color=None, 34 | background_color=None, 35 | font=default_font, 36 | rtc=None, 37 | callback_hour_change=None, 38 | space_between_char=None, 39 | ): 40 | super().__init__(galactic, graphics, font) 41 | self.requested_x, self.requested_y = x, y 42 | self.show_seconds = show_seconds 43 | self.am_pm_mode = am_pm_mode 44 | self.font_color = font_color 45 | self.background_color = background_color 46 | self.callback_hour_change = callback_hour_change 47 | if space_between_char: 48 | self.space_between_char = space_between_char 49 | 50 | if rtc is None: 51 | import machine 52 | self.rtc = machine.RTC() 53 | 54 | self.update_settings() 55 | 56 | def update_settings(self): 57 | """Update settings 58 | 59 | Initialize variables and calculate the position, chars bound, etc... 60 | """ 61 | if self.font_color is None: 62 | self.font_color = self.graphics.create_pen(255, 255, 255) 63 | 64 | if self.background_color is None: 65 | self.background_color = self.graphics.create_pen(0, 0, 0) 66 | 67 | self.format_string = '{:02}:{:02}:{:02}' if self.show_seconds else \ 68 | '{:02}:{:02}' 69 | 70 | self.chars_bounds = [ 71 | x for x in self.get_chars_bounds( 72 | self.format_string.format('0', '0', '0'), 73 | ) 74 | ] 75 | 76 | _, total, width = self.chars_bounds[-1] 77 | self.width = total + width 78 | 79 | self.screen_width, self.screen_height = self.graphics.get_bounds() 80 | 81 | self.set_position(self.requested_x, self.requested_y) 82 | 83 | # Used mainly to initialize data in effect class 84 | if self.callback_after_init: 85 | self.callback_after_init() 86 | 87 | def format_time(self, hour, minute, second): 88 | if self.am_pm_mode: 89 | hour = hour % 12 if hour != 12 else hour 90 | else: 91 | hour = hour % 24 92 | return self.format_string.format(hour, minute, second) 93 | 94 | def callback_write_char(self, char, index): 95 | self.graphics.set_pen(self.font_color) 96 | 97 | def iter_on_changes(self, time): 98 | """Get information about the changes between last_time and time""" 99 | for i, (last_char, char) in enumerate( 100 | zip(self.last_time if self.last_time else time, time) 101 | ): 102 | if self.last_time is None or last_char != char: 103 | yield ( 104 | i, 105 | self.chars_bounds[i][1], 106 | self.chars_bounds[i][2], 107 | last_char, 108 | char, 109 | ) 110 | 111 | def write_time(self, time): 112 | self.graphics.set_pen(self.font_color) 113 | self.write_text(time, self.x, self.y) 114 | self.galactic.update(self.graphics) 115 | 116 | last_time = None 117 | async def update_time(self, time): 118 | for index, offset, size, _, character in self.iter_on_changes(time): 119 | with Clip(self.graphics, self.x + offset, 0, size, 120 | self.screen_height): 121 | self.graphics.set_pen(self.background_color) 122 | self.graphics.clear() 123 | 124 | self.callback_write_char(character, index) 125 | self.write_char(character, self.x + offset, self.y) 126 | 127 | self.galactic.update(self.graphics) 128 | 129 | self.last_time = time 130 | 131 | def full_update(self): 132 | self.last_time = None 133 | 134 | def get_time(self): 135 | _, _, _, _, hour, minute, second, _ = self.rtc.datetime() 136 | return hour, minute, second 137 | 138 | last_second = None 139 | last_hour = None 140 | async def need_update(self, hour, minute, second): 141 | return second != self.last_second 142 | 143 | async def run(self): 144 | while self.is_running: 145 | hour, minute, second = self.get_time() 146 | 147 | if not await self.need_update(hour, minute, second): 148 | asyncio.sleep(0.25) 149 | continue 150 | 151 | if hour != self.last_hour and self.callback_hour_change: 152 | self.callback_hour_change(hour) 153 | 154 | await self.update_time(self.format_time( 155 | hour, 156 | minute, 157 | second, 158 | )) 159 | 160 | if self.callback_time_updated: 161 | await self.callback_time_updated(hour, minute, second) 162 | 163 | self.last_second = second 164 | self.last_hour = hour 165 | 166 | await asyncio.sleep(self.loop_sleep) 167 | 168 | async def test(self): 169 | """Test method 170 | 171 | Used to do some test when debugging animation or what you want... 172 | Call this method instead run. 173 | """ 174 | second = minute = hour = 0 175 | while True: 176 | second += 1 177 | if second == 60: 178 | minute += 1 179 | second = 0 180 | if minute == 60: 181 | hour += 1 182 | minute = 0 183 | 184 | time = '{:02}:{:02}:{:02}'.format(hour, minute, second) 185 | print(time) 186 | asyncio.sleep(0.01) 187 | await self.update_time(self.format_time( 188 | hour, 189 | minute, 190 | second, 191 | )) -------------------------------------------------------------------------------- /unicornclock/common.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Clip: 4 | 5 | def __init__(self, graphics, x, y, width, height): 6 | self.graphics = graphics 7 | self.x = x 8 | self.y = y 9 | self.width = width 10 | self.height = height 11 | 12 | def __enter__(self): 13 | self.graphics.set_clip(self.x, self.y, self.width, self.height) 14 | 15 | def __exit__(self, *args): 16 | self.graphics.remove_clip() 17 | 18 | 19 | class Position: 20 | LEFT = '__left__' 21 | CENTER = '__center__' 22 | RIGHT = '__right__' 23 | 24 | 25 | class ClockMixin: 26 | 27 | x = 0 # Calculated x position 28 | y = 0 # Calculated y position 29 | 30 | def set_position(self, x, y=None): 31 | if x == Position.LEFT: 32 | self.x = 0 33 | elif x in (Position.CENTER, Position.RIGHT): 34 | self.x = self.galactic.WIDTH - self.width 35 | if x == Position.CENTER: 36 | self.x = int(self.x / 2) 37 | else: 38 | self.x = x 39 | 40 | if y is not None: 41 | self.y = y 42 | -------------------------------------------------------------------------------- /unicornclock/effects.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | 3 | from .common import Clip 4 | from .utils import from_hsv 5 | 6 | 7 | class CharacterSlideEffect: 8 | """Character slide effect""" 9 | 10 | # True: Down, False: Up 11 | direction = 1 12 | 13 | async def update_time(self, time): 14 | if self.last_time is None: 15 | self.write_time(time) 16 | self.last_time = time 17 | 18 | _, HEIGHT = self.graphics.get_bounds() 19 | 20 | y = self.y 21 | if not self.direction: 22 | y += HEIGHT + 1 23 | 24 | for i in range( 25 | (HEIGHT * 2 if self.direction else HEIGHT + 1) + 1 26 | ): 27 | for index, offset, size, a, b in self.iter_on_changes(time): 28 | character = a if i <= HEIGHT else b 29 | 30 | with Clip(self.graphics, self.x + offset, 0, size, HEIGHT): 31 | self.graphics.set_pen(self.background_color) 32 | self.graphics.clear() 33 | 34 | self.callback_write_char(character, index) 35 | self.write_char(character, self.x + offset, y) 36 | 37 | self.galactic.update(self.graphics) 38 | 39 | if self.direction: 40 | y += 1 41 | if y >= HEIGHT: 42 | y = -HEIGHT 43 | else: 44 | y -= 1 45 | 46 | sleep(0.01) 47 | 48 | self.last_time = time 49 | 50 | 51 | class CharacterSlideDownEffect(CharacterSlideEffect): 52 | direction = True 53 | 54 | 55 | class CharacterSlideUpEffect(CharacterSlideEffect): 56 | direction = False 57 | 58 | 59 | class RainbowMixin: 60 | 61 | hue_offset = 0 62 | hue_map = [] 63 | 64 | def callback_after_init(self): 65 | info = self.chars_bounds[-1] 66 | self.width = info[1] + info[2] 67 | self.hue_map = [ 68 | from_hsv(x / self.width, 1.0, 1.0) for x in range(self.width) 69 | ] 70 | 71 | self.separator_color = self.graphics.create_pen(255, 255, 255) 72 | 73 | def set_pen(self, char, i): 74 | color = self.separator_color 75 | 76 | if char != ':': 77 | colour = self.hue_map[ 78 | int((i + (self.hue_offset * self.width)) % self.width) 79 | ] 80 | color = self.graphics.create_pen( 81 | int(colour[0]), int(colour[1]), int(colour[2]) 82 | ) 83 | 84 | self.graphics.set_pen(color) 85 | 86 | 87 | class RainbowCharEffect(RainbowMixin): 88 | """Rainbow Char Effect 89 | 90 | Each character color come from a rainbow. 91 | """ 92 | 93 | def callback_write_char(self, char, index): 94 | self.set_pen(char, index) 95 | 96 | 97 | class RainbowPixelEffect(RainbowMixin): 98 | """Rainbow Pixel Effect 99 | 100 | Each pixel column color of character come from a rainbow. 101 | """ 102 | 103 | def callback_set_pixel(self, char, x, y): 104 | self.set_pen(char, x) 105 | 106 | 107 | class RainbowMoveEffect(RainbowMixin): 108 | """Rainbow move effect 109 | 110 | Colorize the characters as a rainbow and move it. 111 | """ 112 | 113 | loop_sleep = 0.01 114 | 115 | def callback_set_pixel(self, char, x, y): 116 | self.set_pen(char, x) 117 | 118 | async def update_time(self, time): 119 | for character, offset, size in self.get_chars_bounds(time): 120 | with Clip(self.graphics, self.x + offset, self.y, size, 121 | self.screen_height): 122 | self.graphics.set_pen(self.background_color) 123 | self.graphics.clear() 124 | 125 | self.write_char(character, self.x + offset, self.y) 126 | 127 | self.galactic.update(self.graphics) 128 | 129 | async def callback_time_updated(self, hour, minute, second): 130 | self.hue_offset += 0.01 131 | 132 | async def need_update(self, hour, minute, second): 133 | return True 134 | -------------------------------------------------------------------------------- /unicornclock/fontdriver.py: -------------------------------------------------------------------------------- 1 | 2 | class FontDriver: 3 | 4 | # Save the start / end of each characters 5 | chars_font_bounds = {} 6 | 7 | space_between_char = 1 8 | 9 | callback_write_char = None 10 | callback_set_pixel = None 11 | 12 | def __init__(self, galactic, graphics, font): 13 | self.galactic = galactic 14 | self.graphics = graphics 15 | self.font = font 16 | 17 | self.load_chars_font_bounds() 18 | 19 | def iter_pixel(self, char): 20 | """Iter pixel 21 | Yield only lighted pixel 22 | """ 23 | for y, c in enumerate(self.font[char]): 24 | for bit in range(8): 25 | if c & (1 << bit): 26 | yield (bit, y) 27 | 28 | def load_chars_font_bounds(self): 29 | self.chars_font_bounds = {} 30 | for char in self.font: 31 | min_x = 1000 32 | max_x = 0 33 | for (pos_x, pos_y) in self.iter_pixel(char): 34 | min_x = min(min_x, pos_x) 35 | max_x = max(max_x, pos_x) 36 | self.chars_font_bounds[char] = (min_x, max_x) 37 | 38 | def iter_chars(self, text): 39 | """Iters on chars in the text argument 40 | 41 | Returns a tuple of values: 42 | - Current character 43 | - Offset (the position of the character) 44 | - Size (the full size of the character) 45 | """ 46 | offset = 0 47 | for i, char in enumerate(text): 48 | dims = self.chars_font_bounds[char] 49 | 50 | # The `+1` is because we come from position to have a width 51 | character_width = dims[1] - dims[0] + 1 52 | 53 | yield (char, offset, character_width) 54 | 55 | space_between_char = self.space_between_char(i, char) \ 56 | if callable(self.space_between_char) \ 57 | else self.space_between_char 58 | 59 | offset += character_width + space_between_char 60 | 61 | def get_chars_bounds(self, text): 62 | yield from self.iter_chars(text) 63 | 64 | def write_char(self, char, x, y=0): 65 | char = str(char) 66 | 67 | try: 68 | self.font[str(char)] 69 | except KeyError: 70 | raise Exception("Character '%s' not found in font." % char) 71 | 72 | start, _ = self.chars_font_bounds[char] 73 | for (px, py) in self.iter_pixel(char): 74 | if self.callback_set_pixel: 75 | self.callback_set_pixel(char, x + px, y + py) 76 | 77 | self.graphics.pixel(x + px - start, y + py) 78 | 79 | def write_text(self, text, x, y): 80 | for i, (char, offset, _) in enumerate(self.iter_chars(text)): 81 | if self.callback_write_char: 82 | self.callback_write_char(char, i) 83 | 84 | self.write_char(char, x + offset, y) 85 | -------------------------------------------------------------------------------- /unicornclock/fonts.py: -------------------------------------------------------------------------------- 1 | bignum = { 2 | '0': [ 0x1e, 0x3f, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3f, 0x1e ], 3 | '1': [ 0x08, 0x0c, 0x0f, 0x0f, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x3f, 0x3f ], 4 | '2': [ 0x1e, 0x3f, 0x33, 0x30, 0x30, 0x1c, 0x0e, 0x07, 0x03, 0x3f, 0x3f ], 5 | '3': [ 0x1e, 0x3f, 0x33, 0x30, 0x3c, 0x3c, 0x30, 0x30, 0x33, 0x3f, 0x1e ], 6 | '4': [ 0x30, 0x38, 0x3c, 0x36, 0x33, 0x33, 0x3f, 0x3f, 0x30, 0x30, 0x30 ], 7 | '5': [ 0x3f, 0x3f, 0x03, 0x03, 0x1f, 0x3e, 0x30, 0x33, 0x33, 0x3f, 0x1e ], 8 | '6': [ 0x1c, 0x3e, 0x07, 0x03, 0x03, 0x1f, 0x3f, 0x33, 0x33, 0x3f, 0x1e ], 9 | '7': [ 0x3f, 0x3f, 0x30, 0x30, 0x18, 0x0c, 0x06, 0x06, 0x06, 0x06, 0x06 ], 10 | '8': [ 0x1e, 0x3f, 0x33, 0x33, 0x3f, 0x1e, 0x3f, 0x33, 0x33, 0x3f, 0x1e ], 11 | '9': [ 0x1e, 0x3f, 0x33, 0x33, 0x3f, 0x3e, 0x30, 0x30, 0x33, 0x3f, 0x1e ], 12 | ':': [ 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x00, 0x04, 0x04 ], 13 | '°': [ 0x06, 0x06 ], 14 | ' ': [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ], 15 | '.': [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06 ], 16 | } 17 | 18 | default = bignum 19 | -------------------------------------------------------------------------------- /unicornclock/utils.py: -------------------------------------------------------------------------------- 1 | import machine 2 | import math 3 | import ntptime 4 | import time 5 | 6 | 7 | def debounce(ms=250): 8 | """Button debounce 9 | 10 | The args `ms` is the delay in milliseconds below which 11 | the function call is ignored. 12 | """ 13 | timeout = time.ticks_ms() 14 | 15 | def decorator(func): 16 | def wrapper(*args, **kwargs): 17 | nonlocal timeout 18 | 19 | if time.ticks_diff(time.ticks_ms(), timeout) < ms: 20 | return 21 | 22 | func(*args, **kwargs) 23 | 24 | timeout = time.ticks_ms() 25 | return wrapper 26 | 27 | return decorator 28 | 29 | 30 | @micropython.native # noqa: F821 31 | def from_hsv(h, s, v): 32 | i = math.floor(h * 6.0) 33 | f = h * 6.0 - i 34 | v *= 255.0 35 | p = v * (1.0 - s) 36 | q = v * (1.0 - f * s) 37 | t = v * (1.0 - (1.0 - f) * s) 38 | 39 | i = int(i) % 6 40 | if i == 0: 41 | return int(v), int(t), int(p) 42 | if i == 1: 43 | return int(q), int(v), int(p) 44 | if i == 2: 45 | return int(p), int(v), int(t) 46 | if i == 3: 47 | return int(p), int(q), int(v) 48 | if i == 4: 49 | return int(t), int(p), int(v) 50 | if i == 5: 51 | return int(v), int(p), int(q) 52 | 53 | 54 | def set_time(utc_offset=0): 55 | # There is no timezone support in Micropython, 56 | # we need to use tricks 57 | 58 | ntptime.settime() 59 | 60 | rtc = machine.RTC() 61 | 62 | y, mo, d, wd, h, m, s, ss = rtc.datetime() 63 | 64 | mktime = time.mktime((y, mo, d, h, m, s, wd, None)) 65 | 66 | mktime += utc_offset * 3600 67 | 68 | y, mo, d, h, m, s, _, _ = time.localtime(mktime) 69 | 70 | rtc.datetime((y, mo, d, wd, h, m, s, ss)) 71 | -------------------------------------------------------------------------------- /unicornclock/widgets.py: -------------------------------------------------------------------------------- 1 | import uasyncio as asyncio 2 | 3 | from .common import Clip, ClockMixin, Position 4 | 5 | 6 | class Calendar(ClockMixin): 7 | """Calendar widget 8 | 9 | Draw a calendar frame with the day 10 | """ 11 | 12 | width = 12 13 | height = 11 14 | banner_height = 3 15 | 16 | def __init__( 17 | self, 18 | galactic, 19 | graphics, 20 | x=0, 21 | y=0, 22 | background_color=None, 23 | banner_color=None, 24 | day_color=None, 25 | rtc=None, 26 | ): 27 | self.galactic = galactic 28 | self.graphics = graphics 29 | self.background_color = background_color 30 | self.banner_color = banner_color 31 | self.day_color = day_color 32 | 33 | if self.background_color is None: 34 | self.background_color = self.graphics.create_pen(255, 255, 255) 35 | 36 | if self.banner_color is None: 37 | self.banner_color = self.graphics.create_pen(255, 0, 0) 38 | 39 | if self.day_color is None: 40 | self.day_color = self.graphics.create_pen(0, 0, 255) 41 | 42 | self.set_position(x, y) 43 | 44 | if rtc is None: 45 | import machine 46 | self.rtc = machine.RTC() 47 | 48 | def get_day(self): 49 | _, _, day, _, _, _, _, _ = self.rtc.datetime() 50 | return day 51 | 52 | def draw_frame(self): 53 | with Clip(self.graphics, self.x, self.y, self.width, self.height): 54 | self.graphics.set_pen(self.banner_color) 55 | self.graphics.rectangle(self.x, self.y, self.width, 56 | self.banner_height) 57 | 58 | self.graphics.set_pen(self.background_color) 59 | self.graphics.rectangle(self.x, self.y + self.banner_height, 60 | self.width, 61 | self.height - self.banner_height) 62 | 63 | def draw_day(self, day): 64 | width = self.graphics.measure_text(day, 1) 65 | 66 | # We are trying to center the day 67 | offset = 0 68 | if width < 6: 69 | offset = 3 70 | elif width < 7: 71 | offset = 2 72 | elif width in (8, 9): 73 | offset = 1 74 | 75 | self.graphics.set_pen(self.day_color) 76 | self.graphics.text(day, self.x + 1 + offset, self.y + 3, -1, 1) 77 | 78 | def draw_all(self, day=None): 79 | self.draw_frame() 80 | 81 | self.draw_day(str(day if day else self.get_day())) 82 | 83 | async def run(self): 84 | while True: 85 | self.draw_all() 86 | 87 | self.galactic.update(self.graphics) 88 | 89 | await asyncio.sleep(30) 90 | --------------------------------------------------------------------------------