├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── apps.py ├── buttons.py ├── clock.py ├── display.py ├── ds3231_port.py ├── main.py ├── pomodoro.py ├── rtc.py ├── run ├── scheduler.py ├── speaker.py ├── time_set.py └── util.py /.gitignore: -------------------------------------------------------------------------------- 1 | LASTRUN 2 | venv 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | * **2021/10/05**: Unified interface for the app classes 4 | * **2021/10/02**: Add basic time-set app 5 | * **2021/10/01**: Improved 'app' functionality 6 | Top button switches between apps 7 | * **2021/09/19**: Added 'Pomodoro timer' app 8 | * **2021/09/19**: Updated scheduler to know about "apps" 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MicroPython Pico-Clock-Green example 2 | 3 | Python port of the C code for the Waveshare [Pico-Clock-Green](https://www.waveshare.com/wiki/Pico-Clock-Green) product. 4 | 5 | > **Status**: So far, the code in this repo covers much of the basics, but the 6 | core functionality of the clock (alarms/time setting, etc) remains to be 7 | implemented. 8 | 9 | > **Status**: This code is changing a lot at present, as all the necessary features 10 | are added. Please expect change, and please expect classes and APIs to change. 11 | 12 | ## Instructions (Linux) 13 | * Flash MicroPython onto the Pico. 14 | * Install `ampy` from AdaFruit. 15 | * Execute the `run` bash script to upload Python files and execute 16 | main.py 17 | 18 | ## Instructions (Windows) 19 | If not running on Linux, use your usual method for uploading code to the Pico. 20 | 21 | ## Changelog 22 | See [CHANGELOG.md](CHANGELOG.md) for a list of updates. 23 | -------------------------------------------------------------------------------- /apps.py: -------------------------------------------------------------------------------- 1 | from buttons import Buttons 2 | from display import Display 3 | 4 | 5 | class App: 6 | def __init__(self, name, label): 7 | self.name = name 8 | self.label = label 9 | self.active = False 10 | self.grab_top_button = False 11 | 12 | def top_button(self, t): 13 | print("top_button not implemented for " + self.name) 14 | 15 | 16 | class Apps: 17 | def __init__(self, scheduler): 18 | self.display = Display(scheduler) 19 | self.buttons = Buttons(scheduler) 20 | self.apps = [] 21 | self.current_app = 0 22 | self.buttons.add_callback(1, self.next, max=500) 23 | self.buttons.add_callback(1, self.previous, min=500) 24 | self.buttons.add_callback(1, self.exit, min=500) 25 | 26 | def add(self, app): 27 | if len(self.apps) == 0: 28 | app.enable() 29 | self.apps.append(app) 30 | 31 | def next(self, t): 32 | print("NEXT") 33 | if len(self.apps) == 0: 34 | return 35 | 36 | app = self.apps[self.current_app] 37 | if app.active and app.grab_top_button: 38 | app.top_button(t) 39 | return 40 | 41 | self.apps[self.current_app].disable() 42 | self.buttons.clear_callbacks(2) 43 | self.buttons.clear_callbacks(3) 44 | self.display.clear() 45 | self.current_app = (self.current_app + 1) % len(self.apps) 46 | print("SWITCHING TO", self.apps[self.current_app].name) 47 | self.apps[self.current_app].enable() 48 | 49 | def previous(self, t): 50 | print("PREVIOUS") 51 | if len(self.apps) > 0: 52 | self.apps[self.current_app].disable() 53 | self.current_app = (self.current_app - 1) % len(self.apps) 54 | self.apps[self.current_app].enable() 55 | 56 | def exit(self, t): 57 | if len(self.apps) > 0: 58 | self.apps[self.current_app].disable() 59 | self.current_app = 0 60 | self.apps[self.current_app].enable() 61 | -------------------------------------------------------------------------------- /buttons.py: -------------------------------------------------------------------------------- 1 | from machine import Pin 2 | import time 3 | 4 | from util import singleton 5 | 6 | STATE_UNPRESSED = 1 7 | STATE_PRESSED = 2 8 | 9 | PINS = { 10 | 1: 2, 11 | 2: 17, 12 | 3: 15, 13 | } 14 | 15 | 16 | @singleton 17 | class Buttons: 18 | class Button: 19 | class Callback: 20 | def __init__(self, callback, min=0, max=-1): 21 | self.callback = callback 22 | self.min = min 23 | self.max = max 24 | 25 | def __init__(self, number): 26 | self.pin = Pin(PINS[number], Pin.IN, Pin.PULL_UP) 27 | self.number = number 28 | self.state = STATE_UNPRESSED 29 | self.callbacks = [] 30 | self.pressed_time = None 31 | 32 | def add_callback(self, callback, min=0, max=-1): 33 | callback_obj = self.Callback(callback, min, max) 34 | self.callbacks.append(callback_obj) 35 | return callback_obj 36 | 37 | def remove_callback(self, callback, min=0, max=-1): 38 | for callback in self.callbacks: 39 | if callback.callback == callback and callback.min == min and callback.max == max: 40 | self.callback.remove(callback) 41 | break 42 | 43 | def clear_callbacks(self): 44 | self.callbacks = [] 45 | 46 | def __init__(self, scheduler): 47 | self.buttons = [ 48 | self.Button(number) for number in (1, 2, 3) 49 | ] 50 | scheduler.schedule("button-press", 1, self.millis_callback) 51 | 52 | def add_callback(self, number, callback, min=0, max=-1): 53 | self.buttons[number - 1].add_callback(callback, min, max) 54 | 55 | def remove_callback(self, number, callback, min=0, max=-1): 56 | self.buttons[number - 1].remove_callback(callback, min, max) 57 | 58 | def clear_callbacks(self, number): 59 | self.buttons[number - 1].clear_callbacks() 60 | 61 | def get_button(self, number): 62 | return self.buttons[number - 1] 63 | 64 | def millis_callback(self, t): 65 | for button in self.buttons: 66 | if len(button.callbacks) > 0: 67 | if button.state == STATE_UNPRESSED and button.pin.value() == 0: 68 | button.state = STATE_PRESSED 69 | button.pressed = time.ticks_ms() 70 | elif button.state == STATE_PRESSED and button.pin.value() == 1: 71 | button.state = STATE_UNPRESSED 72 | tm = time.ticks_ms() 73 | press_duration = time.ticks_diff(tm, button.pressed) 74 | print("Button %d pressed for %dms" % (button.number, press_duration)) 75 | for callback in button.callbacks: 76 | if callback.min < press_duration and ( 77 | callback.max == -1 or press_duration <= callback.max): 78 | callback.callback(t) 79 | break 80 | button.pressed = None 81 | -------------------------------------------------------------------------------- /clock.py: -------------------------------------------------------------------------------- 1 | import time 2 | from apps import App 3 | from display import Display 4 | from rtc import RTC 5 | from buttons import Buttons 6 | 7 | 8 | class Clock(App): 9 | def __init__(self, scheduler): 10 | App.__init__(self, "Clock", "clock") 11 | self.display = Display(scheduler) 12 | self.rtc = RTC() 13 | self.enabled = True 14 | self.buttons = Buttons(scheduler) 15 | scheduler.schedule("clock-second", 1000, self.secs_callback) 16 | scheduler.schedule("clock-minute", 60000, self.mins_callback) 17 | 18 | def enable(self): 19 | self.enabled = True 20 | self.update_time() 21 | self.buttons.add_callback(3, self.backlight_callback, max=500) 22 | 23 | def disable(self): 24 | self.enabled = False 25 | 26 | def secs_callback(self, t): 27 | if self.enabled: 28 | t = time.time() 29 | if t % 2 == 0: 30 | self.display.show_char(":", pos=10) 31 | else: 32 | self.display.show_char(" :", pos=10) 33 | 34 | def mins_callback(self, t): 35 | if self.enabled: 36 | self.update_time() 37 | 38 | def update_time(self): 39 | t = self.rtc.get_time() 40 | now = "%02d:%02d" % (t[3], t[4]) 41 | self.display.show_day(t[6]) 42 | self.display.show_text(now) 43 | if self.display.auto_backlight: 44 | self.display.show_icon("AutoLight") 45 | 46 | def backlight_callback(self, t): 47 | self.display.switch_backlight() 48 | 49 | -------------------------------------------------------------------------------- /display.py: -------------------------------------------------------------------------------- 1 | from machine import Pin, ADC 2 | 3 | from util import singleton 4 | from utime import sleep_us 5 | 6 | @singleton 7 | class Display: 8 | def __init__(self, scheduler): 9 | self.a0 = Pin(16, Pin.OUT) 10 | self.a1 = Pin(18, Pin.OUT) 11 | self.a2 = Pin(22, Pin.OUT) 12 | 13 | self.oe = Pin(13, Pin.OUT) 14 | 15 | self.sdi = Pin(11, Pin.OUT) 16 | self.clk = Pin(10, Pin.OUT) 17 | self.le = Pin(12, Pin.OUT) 18 | 19 | self.ain = ADC(26) 20 | 21 | self.row = 0 22 | self.count = 0 23 | self.leds = [[0] * 32 for i in range(0, 8)] 24 | self.leds_changed = False 25 | self.disp_offset = 2 26 | self.initialise_fonts() 27 | self.initialise_icons() 28 | 29 | self.scheduler = scheduler 30 | 31 | # CPU freq needs to be increase to 250 for better results 32 | self.backlight_sleep = [10, 100, 300, 1500] # From 10 (low) to 1500(High) 33 | self.current_backlight = 3 34 | self.auto_backlight = True 35 | self.show_icon("AutoLight") 36 | self.update_auto_backlight_value(None) 37 | self.scheduler.schedule("enable-leds", 1, self.enable_leds) 38 | self.scheduler.schedule("update_auto_backlight_value", 1000, self.update_auto_backlight_value) 39 | 40 | def enable_leds(self, t): 41 | self.count += 1 42 | self.row = (self.row + 1) % 8 43 | led_row = self.leds[self.row] 44 | if True: 45 | for col in range(32): 46 | self.clk.value(0) 47 | self.sdi.value(led_row[col]) 48 | self.clk.value(1) 49 | self.le.value(1) 50 | self.le.value(0) 51 | self.leds_changed = False 52 | 53 | self.a0.value(1 if self.row & 0x01 else 0) 54 | self.a1.value(1 if self.row & 0x02 else 0) 55 | self.a2.value(1 if self.row & 0x04 else 0) 56 | self.oe.value(0) 57 | sleep_us(self.backlight_sleep[self.current_backlight]) 58 | self.oe.value(1) 59 | 60 | def clear(self, x=0, y=0, w=24, h=7): 61 | for yy in range(y, y + h + 1): 62 | for xx in range(x, x + w + 1): 63 | self.leds[yy][xx] = 0 64 | 65 | def show_char(self, character, pos): 66 | pos += self.disp_offset # Plus the offset of the status indicator 67 | char = self.ziku[character] 68 | for row in range(1, 8): 69 | byte = char.rows[row - 1] 70 | for col in range(0, char.width): 71 | self.leds[row][pos + col] = (byte >> col) % 2 72 | self.leds_changed = True 73 | 74 | def show_text(self, text, pos=0): 75 | i = 0 76 | while i < len(text): 77 | if text[i:i + 2] in self.ziku: 78 | c = text[i:i + 2] 79 | i += 2 80 | else: 81 | c = text[i] 82 | i += 1 83 | char = self.ziku[c] 84 | self.show_char(c, pos) 85 | width = self.ziku[c].width 86 | pos += width + 1 87 | 88 | def show_icon(self, name): 89 | icon = self.Icons[name] 90 | for w in range(icon.width): 91 | self.leds[icon.y][icon.x + w] = 1 92 | self.leds_changed = True 93 | 94 | def hide_icon(self, name): 95 | icon = self.Icons[name] 96 | for w in range(icon.width): 97 | self.leds[icon.y][icon.x + w] = 0 98 | self.leds_changed = True 99 | 100 | def sidelight_on(self): 101 | self.leds[0][2] = 1 102 | self.leds[0][5] = 1 103 | 104 | def sidelight_off(self): 105 | self.leds[0][2] = 0 106 | self.leds[0][5] = 0 107 | 108 | def switch_backlight(self): 109 | if self.auto_backlight: 110 | self.auto_backlight = False 111 | self.hide_icon("AutoLight") 112 | self.current_backlight = 0 113 | self.scheduler.remove("update_auto_backlight_value") 114 | elif self.current_backlight == 3: 115 | self.show_icon("AutoLight") 116 | self.auto_backlight = True 117 | self.update_auto_backlight_value(None) 118 | self.scheduler.schedule("update_auto_backlight_value", 1000, self.update_auto_backlight_value) 119 | else: 120 | self.current_backlight += 1 121 | 122 | def update_auto_backlight_value(self, t): 123 | aim = self.ain.read_u16() 124 | if aim > 60000: # Low light 125 | self.current_backlight = 0 126 | elif aim > 58000: 127 | self.current_backlight = 1 128 | elif aim > 40000: 129 | self.current_backlight = 2 130 | else: 131 | self.current_backlight = 3 132 | 133 | def print(self): 134 | for row in range(0, 8): 135 | for pos in range(0, 24): 136 | print("X" if self.leds[row][pos] == 1 else " ", end="") 137 | print("") 138 | 139 | def square(self): 140 | ''' 141 | Prints a crossed square. For debugging purposes. 142 | ''' 143 | for row in range(1, 8): 144 | self.leds[row][2] = 1 145 | self.leds[row][23] = 1 146 | for col in range(2, 23): 147 | self.leds[1][col] = 1 148 | self.leds[7][col] = 1 149 | self.leds[int(col / 24 * 7) + 1][col] = 1 150 | self.leds[7 - int(col / 24 * 7)][col] = 1 151 | 152 | class Character: 153 | def __init__(self, width, rows, offset=2): 154 | self.width = width 155 | self.rows = rows 156 | self.offset = offset 157 | 158 | class Icon: 159 | def __init__(self, x, y, width=1): 160 | self.x = x 161 | self.y = y 162 | self.width = width 163 | 164 | def initialise_icons(self): 165 | self.Icons = { 166 | "MoveOn": self.Icon(0, 0, width=2), 167 | "AlarmOn": self.Icon(0, 1, width=2), 168 | "CountDown": self.Icon(0, 2, width=2), 169 | "°F": self.Icon(0, 3), 170 | "°C": self.Icon(1, 3), 171 | "AM": self.Icon(0, 4), 172 | "PM": self.Icon(1, 4), 173 | "CountUp": self.Icon(0, 5, width=2), 174 | "Hourly": self.Icon(0, 6, width=2), 175 | "AutoLight": self.Icon(0, 7, width=2), 176 | "Mon": self.Icon(3, 0, width=2), 177 | "Tue": self.Icon(6, 0, width=2), 178 | "Wed": self.Icon(9, 0, width=2), 179 | "Thur": self.Icon(12, 0, width=2), 180 | "Fri": self.Icon(15, 0, width=2), 181 | "Sat": self.Icon(18, 0, width=2), 182 | "Sun": self.Icon(21, 0, width=2), 183 | } 184 | day_of_week = { 185 | 0: "Mon", 186 | 1: "Tue", 187 | 2: "Wed", 188 | 3: "Thur", 189 | 4: "Fri", 190 | 5: "Sat", 191 | 6: "Sun" 192 | } 193 | def show_day(self, int): 194 | self.clear() 195 | self.show_icon(self.day_of_week[int]) 196 | 197 | # Derived from c code created by yufu on 2021/1/23. 198 | # Modulus method: negative code, reverse, line by line, 4X7 font 199 | def initialise_fonts(self): 200 | self.ziku = { 201 | "all": self.Character(width=3, rows=[0x05,0x05,0x03,0x03,0x03,0x03,0x03]), 202 | "0": self.Character(width=4, rows=[0x06,0x09,0x09,0x09,0x09,0x09,0x06]), 203 | "1": self.Character(width=4, rows=[0x04,0x06,0x04,0x04,0x04,0x04,0x0E]), 204 | "2": self.Character(width=4, rows=[0x06,0x09,0x08,0x04,0x02,0x01,0x0F]), 205 | "3": self.Character(width=4, rows=[0x06,0x09,0x08,0x06,0x08,0x09,0x06]), 206 | "4": self.Character(width=4, rows=[0x08,0x0C,0x0A,0x09,0x0F,0x08,0x08]), 207 | "5": self.Character(width=4, rows=[0x0F,0x01,0x07,0x08,0x08,0x09,0x06]), 208 | "6": self.Character(width=4, rows=[0x04,0x02,0x01,0x07,0x09,0x09,0x06]), 209 | "7": self.Character(width=4, rows=[0x0F,0x09,0x04,0x04,0x04,0x04,0x04]), 210 | "8": self.Character(width=4, rows=[0x06,0x09,0x09,0x06,0x09,0x09,0x06]), 211 | "9": self.Character(width=4, rows=[0x06,0x09,0x09,0x0E,0x08,0x04,0x02]), 212 | "A": self.Character(width=4, rows=[0x06,0x09,0x09,0x0F,0x09,0x09,0x09]), 213 | "B": self.Character(width=4, rows=[0x07,0x09,0x09,0x07,0x09,0x09,0x07]), 214 | "C": self.Character(width=4, rows=[0x06,0x09,0x01,0x01,0x01,0x09,0x06]), 215 | "D": self.Character(width=4, rows=[0x07,0x09,0x09,0x09,0x09,0x09,0x07]), 216 | "E": self.Character(width=4, rows=[0x0F,0x01,0x01,0x0F,0x01,0x01,0x0F]), 217 | "F": self.Character(width=4, rows=[0x0F,0x01,0x01,0x0F,0x01,0x01,0x01]), 218 | "H": self.Character(width=4, rows=[0x09,0x09,0x09,0x0F,0x09,0x09,0x09]), 219 | "L": self.Character(width=4, rows=[0x01,0x01,0x01,0x01,0x01,0x01,0x0F]), 220 | "N": self.Character(width=4, rows=[0x09,0x09,0x0B,0x0D,0x09,0x09,0x09]), 221 | "O": self.Character(width=4, rows=[0x0F,0x09,0x09,0x09,0x09,0x09,0x0F]), 222 | "P": self.Character(width=4, rows=[0x07,0x09,0x09,0x07,0x01,0x01,0x01]), 223 | "U": self.Character(width=4, rows=[0x09,0x09,0x09,0x09,0x09,0x09,0x06]), 224 | ":": self.Character(width=2, rows=[0x00,0x03,0x03,0x00,0x03,0x03,0x00]), #2×7 225 | " :": self.Character(width=2, rows=[0x00,0x00,0x00,0x00,0x00,0x00,0x00]), # colon width space 226 | "°C": self.Character(width=4, rows=[0x01,0x0C,0x12,0x02,0x02,0x12,0x0C]), # celcuis 5×7 227 | "°F": self.Character(width=4, rows=[0x01,0x1E,0x02,0x1E,0x02,0x02,0x02]), # farenheit 228 | " ": self.Character(width=4, rows=[0x00,0x00,0x00,0x00,0x00,0x00,0x00]), # space 229 | "Y": self.Character(width=4, rows=[0x1F,0x04,0x04,0x04,0x04,0x04,0x04]), # 5*7 230 | ".": self.Character(width=1, rows=[0x00,0x00,0x00,0x00,0x00,0x00,0x01]), # 1×7 231 | "-": self.Character(width=2, rows=[0x00,0x00,0x00,0x03,0x00,0x00,0x00]), # 2×7 232 | "M": self.Character(width=4, rows=[0x00,0x11,0x1B,0x15,0x11,0x11,0x11,0x11]), # 5×7 233 | "/": self.Character(width=2, rows=[0x02,0x02,0x02,0x01,0x01,0x01,0x01,0x01]), # 3×7 234 | "°C2": self.Character(width=4, rows=[0x00,0x01,0x0C,0x12,0x02,0x02,0x12,0x0C]), # 5×7 235 | "°F2": self.Character(width=4, rows=[0x00,0x01,0x1E,0x02,0x1E,0x02,0x02,0x02]), 236 | "V": self.Character(width=5, rows=[0x11,0x11,0x11,0x11,0x11,0x0A,0x04]), # 5×7 237 | "W": self.Character(width=5, rows=[0x11,0x11,0x11,0x15,0x15,0x1B,0x11]), # 5×7 238 | } 239 | self.digital_tube = { 240 | "0": [0x0F, 0x09, 0x09, 0x09, 0x09, 0x09, 0x0F], 241 | "1": [0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08], 242 | "2": [0x0F, 0x08, 0x08, 0x0F, 0x01, 0x01, 0x0F], 243 | "3": [0x0F, 0x08, 0x08, 0x0F, 0x08, 0x08, 0x0F], 244 | "4": [0x09, 0x09, 0x09, 0x0F, 0x08, 0x08, 0x08], 245 | "5": [0x0F, 0x01, 0x01, 0x0F, 0x08, 0x08, 0x0F], 246 | "6": [0x0F, 0x01, 0x01, 0x0F, 0x09, 0x09, 0x0F], 247 | "7": [0x0F, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08], 248 | "8": [0x0F, 0x09, 0x09, 0x0F, 0x09, 0x09, 0x0F], 249 | "9": [0x0F, 0x09, 0x09, 0x0F, 0x08, 0x08, 0x0F], 250 | "A": [0x0F, 0x09, 0x09, 0x0F, 0x09, 0x09, 0x09], 251 | "B": [0x01, 0x01, 0x01, 0x0F, 0x09, 0x09, 0x0F], 252 | "C": [0x0F, 0x01, 0x01, 0x01, 0x01, 0x01, 0x0F], 253 | "D": [0x08, 0x08, 0x08, 0x0F, 0x09, 0x09, 0x0F], 254 | "E": [0x0F, 0x01, 0x01, 0x0F, 0x01, 0x01, 0x0F], 255 | "F": [0x0F, 0x01, 0x01, 0x0F, 0x01, 0x01, 0x01], 256 | "H": [0x09, 0x09, 0x09, 0x0F, 0x09, 0x09, 0x09], 257 | "L": [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x0F], 258 | "N": [0x0F, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09], 259 | "P": [0x0F, 0x09, 0x09, 0x0F, 0x01, 0x01, 0x01], 260 | "U": [0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x0F], 261 | ":": [0x00, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00], # 2×7 262 | "°C": [0x01, 0x1E, 0x02, 0x02, 0x02, 0x02, 0x1E], # celcius 5×7 263 | "°F": [0x01, 0x1E, 0x02, 0x1E, 0x02, 0x02, 0x02], # farenheit 264 | " ": [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 265 | "T": [0x1F, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04], # 5*7 266 | ".": [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], # 2×7 267 | "-": [0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00], # 2×7 268 | "M": [0x00, 0x11, 0x1B, 0x15, 0x11, 0x11, 0x11, 0x11], # 5×7 269 | "/": [0x00, 0x04, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01], # 3×7 270 | "°C2": [0x00, 0x01, 0x0C, 0x12, 0x02, 0x02, 0x12, 0x0C], # celcuis 5x7 271 | "°F2": [0x00, 0x01, 0x1E, 0x02, 0x1E, 0x02, 0x02, 0x02], # farenheit 272 | "V": [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1F], # 5×7 273 | "W": [0x11, 0x11, 0x11, 0x15, 0x15, 0x1B, 0x11], # 5×7 274 | } 275 | -------------------------------------------------------------------------------- /ds3231_port.py: -------------------------------------------------------------------------------- 1 | # FROM HERE: https://github.com/peterhinch/micropython-samples/tree/master/DS3231 2 | 3 | # ds3231_port.py Portable driver for DS3231 precison real time clock. 4 | # Adapted from WiPy driver at https://github.com/scudderfish/uDS3231 5 | 6 | # Author: Peter Hinch 7 | # Copyright Peter Hinch 2018 Released under the MIT license. 8 | 9 | import utime 10 | import machine 11 | import sys 12 | DS3231_I2C_ADDR = 104 13 | 14 | try: 15 | rtc = machine.RTC() 16 | except: 17 | print('Warning: machine module does not support the RTC.') 18 | rtc = None 19 | 20 | def bcd2dec(bcd): 21 | return (((bcd & 0xf0) >> 4) * 10 + (bcd & 0x0f)) 22 | 23 | def dec2bcd(dec): 24 | tens, units = divmod(dec, 10) 25 | return (tens << 4) + units 26 | 27 | def tobytes(num): 28 | return num.to_bytes(1, 'little') 29 | 30 | class DS3231: 31 | def __init__(self, i2c): 32 | self.ds3231 = i2c 33 | self.timebuf = bytearray(7) 34 | if DS3231_I2C_ADDR not in self.ds3231.scan(): 35 | raise RuntimeError("DS3231 not found on I2C bus at %d" % DS3231_I2C_ADDR) 36 | 37 | def get_time(self, set_rtc=False): 38 | if set_rtc: 39 | self.await_transition() # For accuracy set RTC immediately after a seconds transition 40 | else: 41 | self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf) # don't wait 42 | return self.convert(set_rtc) 43 | 44 | def convert(self, set_rtc=False): # Return a tuple in localtime() format (less yday) 45 | data = self.timebuf 46 | ss = bcd2dec(data[0]) 47 | mm = bcd2dec(data[1]) 48 | if data[2] & 0x40: 49 | hh = bcd2dec(data[2] & 0x1f) 50 | if data[2] & 0x20: 51 | hh += 12 52 | else: 53 | hh = bcd2dec(data[2]) 54 | wday = data[3] 55 | DD = bcd2dec(data[4]) 56 | MM = bcd2dec(data[5] & 0x1f) 57 | YY = bcd2dec(data[6]) 58 | if data[5] & 0x80: 59 | YY += 2000 60 | else: 61 | YY += 1900 62 | # Time from DS3231 in time.localtime() format (less yday) 63 | result = YY, MM, DD, hh, mm, ss, wday, 0 64 | if set_rtc: 65 | if rtc is None: 66 | # Best we can do is to set local time 67 | secs = utime.mktime(result) 68 | utime.localtime(secs) 69 | else: 70 | rtc.datetime((YY, MM, DD, wday, hh, mm, ss, 0)) 71 | return result 72 | 73 | def save_time(self, t): 74 | (YY, MM, mday, hh, mm, ss, wday, yday) = t 75 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 0, tobytes(dec2bcd(ss))) 76 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 1, tobytes(dec2bcd(mm))) 77 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 2, tobytes(dec2bcd(hh))) # Sets to 24hr mode 78 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 3, tobytes(dec2bcd(wday))) # 0 == Monday, 6 == Sunday 79 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 4, tobytes(dec2bcd(mday))) # Day of month 80 | if YY >= 2000: 81 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, tobytes(dec2bcd(MM) | 0b10000000)) # Century bit 82 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, tobytes(dec2bcd(YY-2000))) 83 | else: 84 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, tobytes(dec2bcd(MM))) 85 | self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, tobytes(dec2bcd(YY-1900))) 86 | 87 | # Wait until DS3231 seconds value changes before reading and returning data 88 | def await_transition(self): 89 | self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf) 90 | ss = self.timebuf[0] 91 | while ss == self.timebuf[0]: 92 | self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf) 93 | return self.timebuf 94 | 95 | # Test hardware RTC against DS3231. Default runtime 10 min. Return amount 96 | # by which DS3231 clock leads RTC in PPM or seconds per year. 97 | # Precision is achieved by starting and ending the measurement on DS3231 98 | # one-seond boundaries and using ticks_ms() to time the RTC. 99 | # For a 10 minute measurement +-1ms corresponds to 1.7ppm or 53s/yr. Longer 100 | # runtimes improve this, but the DS3231 is "only" good for +-2ppm over 0-40C. 101 | def rtc_test(self, runtime=600, ppm=False, verbose=True): 102 | if rtc is None: 103 | raise RuntimeError('machine.RTC does not exist') 104 | verbose and print('Waiting {} minutes for result'.format(runtime//60)) 105 | factor = 1_000_000 if ppm else 114_155_200 # seconds per year 106 | 107 | self.await_transition() # Start on transition of DS3231. Record time in .timebuf 108 | t = utime.ticks_ms() # Get system time now 109 | ss = rtc.datetime()[6] # Seconds from system RTC 110 | while ss == rtc.datetime()[6]: 111 | pass 112 | ds = utime.ticks_diff(utime.ticks_ms(), t) # ms to transition of RTC 113 | ds3231_start = utime.mktime(self.convert()) # Time when transition occurred 114 | t = rtc.datetime() 115 | rtc_start = utime.mktime((t[0], t[1], t[2], t[4], t[5], t[6], t[3], 0)) # y m d h m s wday 0 116 | 117 | utime.sleep(runtime) # Wait a while (precision doesn't matter) 118 | 119 | self.await_transition() # of DS3231 and record the time 120 | t = utime.ticks_ms() # and get system time now 121 | ss = rtc.datetime()[6] # Seconds from system RTC 122 | while ss == rtc.datetime()[6]: 123 | pass 124 | de = utime.ticks_diff(utime.ticks_ms(), t) # ms to transition of RTC 125 | ds3231_end = utime.mktime(self.convert()) # Time when transition occurred 126 | t = rtc.datetime() 127 | rtc_end = utime.mktime((t[0], t[1], t[2], t[4], t[5], t[6], t[3], 0)) # y m d h m s wday 0 128 | 129 | d_rtc = 1000 * (rtc_end - rtc_start) + de - ds # ms recorded by RTC 130 | d_ds3231 = 1000 * (ds3231_end - ds3231_start) # ms recorded by DS3231 131 | ratio = (d_ds3231 - d_rtc) / d_ds3231 132 | ppm = ratio * 1_000_000 133 | verbose and print('DS3231 leads RTC by {:4.1f}ppm {:4.1f}mins/yr'.format(ppm, ppm*1.903)) 134 | return ratio * factor 135 | 136 | 137 | def _twos_complement(self, input_value: int, num_bits: int) -> int: 138 | mask = 2 ** (num_bits - 1) 139 | return -(input_value & mask) + (input_value & ~mask) 140 | 141 | 142 | def get_temperature(self): 143 | t = self.ds3231.readfrom_mem(DS3231_I2C_ADDR, 0x11, 2) 144 | i = t[0] << 8 | t[1] 145 | return self._twos_complement(i >> 6, 10) * 0.25 146 | 147 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from scheduler import Scheduler 2 | from clock import Clock 3 | from apps import Apps 4 | from pomodoro import Pomodoro 5 | from time_set import TimeSet 6 | import machine 7 | machine.freq(250_000_000) 8 | 9 | APP_CLASSES = [ 10 | Clock, 11 | Pomodoro, 12 | TimeSet, 13 | ] 14 | 15 | scheduler = Scheduler() 16 | apps = Apps(scheduler) 17 | for App in APP_CLASSES: 18 | apps.add(App(scheduler)) 19 | 20 | print("STARTING...") 21 | scheduler.start() 22 | -------------------------------------------------------------------------------- /pomodoro.py: -------------------------------------------------------------------------------- 1 | import time 2 | from apps import App 3 | from buttons import Buttons 4 | from display import Display 5 | from speaker import Speaker 6 | 7 | 8 | class Pomodoro: 9 | def __init__(self, scheduler): 10 | App.__init__(self, "Pomodoro", "pomod") 11 | self.display = Display(scheduler) 12 | self.speaker = Speaker(scheduler) 13 | self.scheduler = scheduler 14 | self.buttons = Buttons() 15 | self.enabled = False 16 | self.started = False 17 | self.start_time = None 18 | self.time_left = None 19 | scheduler.schedule("pomodoro-second", 1000, self.secs_callback) 20 | self.pomodoro_duration=25*60 # 25 mins 21 | 22 | def enable(self): 23 | self.enabled = True 24 | t = "%02d:%02d" % (self.pomodoro_duration // 60, self.pomodoro_duration % 60) 25 | self.display.show_text(t) 26 | self.buttons.add_callback(2, self.start_callback, max=500) 27 | self.buttons.add_callback(2, self.clear_callback, min=500) 28 | 29 | def disable(self): 30 | self.enabled = False 31 | self.started = False 32 | self.start_time = None 33 | 34 | def start(self): 35 | self.started = True 36 | self.start_time = time.ticks_ms() 37 | if not self.time_left: 38 | self.time_left = self.pomodoro_duration 39 | 40 | def _time_left(self): 41 | return self.time_left - (time.ticks_diff(time.ticks_ms(), self.start_time)/1000) 42 | 43 | def stop(self): 44 | self.started = False 45 | self.time_left = self._time_left() 46 | 47 | def secs_callback(self, t): 48 | if self.enabled and self.started: 49 | now = int(self._time_left()) 50 | t = "%02d:%02d" % (now // 60, now % 60) 51 | self.display.show_text(t) 52 | if now <=0: 53 | self.speaker.beep(1000) 54 | self.started = False 55 | self.start_time = None 56 | self.time_left = None 57 | 58 | def start_callback(self, t): 59 | if self.enabled and self.started: 60 | self.stop() 61 | else: 62 | print("START POMODORO") 63 | self.start() 64 | 65 | def clear_callback(self, t): 66 | self.stop() 67 | self.enable() 68 | -------------------------------------------------------------------------------- /rtc.py: -------------------------------------------------------------------------------- 1 | from machine import SoftI2C 2 | from machine import Pin 3 | from ds3231_port import DS3231 4 | from util import singleton 5 | 6 | 7 | @singleton 8 | class RTC: 9 | def __init__(self): 10 | rtc_i2c = SoftI2C(scl=Pin(7), sda=Pin(6), freq=100000) 11 | self.ds = DS3231(rtc_i2c) 12 | pass 13 | 14 | def get_time(self): 15 | return self.ds.get_time() 16 | 17 | def save_time(self, t): 18 | return self.ds.save_time(t) 19 | -------------------------------------------------------------------------------- /run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import argparse 3 | import contextlib 4 | import os 5 | import subprocess 6 | from datetime import datetime 7 | from pathlib import Path 8 | 9 | parser = argparse.ArgumentParser() 10 | parser.add_argument('--device', action='store_true', default="/dev/ttyACM0") 11 | args = parser.parse_args() 12 | 13 | CURRENT_DIR = Path(__file__).parent 14 | NOW = datetime.now() 15 | with contextlib.suppress(FileNotFoundError): 16 | LASTRUN = datetime(year=2000, month=1, day=1) 17 | with open("LASTRUN") as last_run_file: 18 | LASTRUN = datetime.utcfromtimestamp(int(last_run_file.read())) 19 | with open("LASTRUN", "w") as last_run_file: 20 | last_run_file.write(NOW.strftime("%s")) 21 | 22 | for file in os.listdir(CURRENT_DIR): 23 | if file.split(".")[-1] == "py": 24 | if datetime.utcfromtimestamp(os.path.getmtime(CURRENT_DIR.joinpath(file))) > LASTRUN: 25 | print(f"copy: {file}") 26 | subprocess.run(["ampy", "--port", args.device, "put", file, f"/{file}"]) 27 | else: 28 | print(f"up to date: {file}") 29 | 30 | subprocess.run(["ampy", "--port", args.device, "run", "main.py"]) -------------------------------------------------------------------------------- /scheduler.py: -------------------------------------------------------------------------------- 1 | from machine import Timer 2 | import time 3 | 4 | 5 | class Scheduler: 6 | class Schedule: 7 | def __init__(self, name, duration, callback): 8 | self.name = name 9 | self.duration = duration 10 | self.callback = callback 11 | self.lastrun = time.ticks_ms() 12 | 13 | count = 0 14 | 15 | def __init__(self): 16 | self.schedules = [] 17 | 18 | def start(self): 19 | self.start = time.ticks_ms() 20 | self.timer = Timer(period=1, callback=self.event_callback) 21 | 22 | def schedule(self, name, duration, callback): 23 | self.schedules.append(self.Schedule(name, duration, callback)) 24 | 25 | def remove(self, name): 26 | for schedule in self.schedules: 27 | if schedule.name == name: 28 | self.schedules.remove(schedule) 29 | 30 | def event_callback(self, t): 31 | for schedule in self.schedules: 32 | if schedule.duration == 1: 33 | schedule.callback(t) 34 | else: 35 | tm = time.ticks_ms() 36 | if time.ticks_diff(tm, schedule.lastrun) > schedule.duration: 37 | schedule.callback(t) 38 | schedule.lastrun = tm 39 | -------------------------------------------------------------------------------- /speaker.py: -------------------------------------------------------------------------------- 1 | from machine import Pin, Timer 2 | import time 3 | 4 | from util import singleton 5 | 6 | 7 | @singleton 8 | class Speaker: 9 | def __init__(self, scheduler): 10 | self.buzz = Pin(14, Pin.OUT) 11 | self.buzz.value(0) 12 | self.buzz_start = 0 13 | self.duration = 0 14 | scheduler.schedule("beeps", 1, self.beep_callback) 15 | 16 | def beep(self, duration): 17 | self.buzz.value(1) 18 | self.buzz_start = time.ticks_ms() 19 | self.duration = duration 20 | 21 | def beep_off(self, t): 22 | self.buzz.value(0) 23 | self.duration = 0 24 | self.buzz_start = 0 25 | 26 | def beep_callback(self, t): 27 | if self.buzz_start != 0: 28 | tm = time.ticks_ms() 29 | if time.ticks_diff(tm, self.buzz_start) > self.duration: 30 | self.beep_off(t) -------------------------------------------------------------------------------- /time_set.py: -------------------------------------------------------------------------------- 1 | from apps import App 2 | from buttons import Buttons 3 | from display import Display 4 | from rtc import RTC 5 | 6 | month_max = { 7 | 1: 31, # January 8 | 2: 29, # February 9 | 3: 31, # March 10 | 4: 30, # April 11 | 5: 31, # May 12 | 6: 30, # June 13 | 7: 31, # July 14 | 8: 31, # August 15 | 9: 30, # September 16 | 10: 31, # October 17 | 11: 30, # November 18 | 12: 31, # December 19 | } 20 | 21 | class TimeSet(App): 22 | class State: 23 | def __init__(self, name, position, panel, index, max, length=2, offset=0): 24 | self.name = name 25 | self.position = position 26 | self.panel = panel 27 | self.index = index 28 | self.max = max 29 | self.length = length 30 | self.offset = offset 31 | 32 | def __init__(self, scheduler): 33 | App.__init__(self, "Time Set", "timeset") 34 | 35 | self.display = Display(scheduler) 36 | self.scheduler = scheduler 37 | self.buttons = Buttons(scheduler) 38 | self.rtc = RTC() 39 | self.grab_top_button = True 40 | self.enabled = False 41 | self.state = None 42 | self.state_index = -1 43 | self.flash_count = 0 44 | self.flash_state = False 45 | scheduler.schedule("time-set-half-second", 500, self.half_secs_callback) 46 | scheduler.schedule("time-set-minute", 60000, self.mins_callback) 47 | self.initialise_states() 48 | 49 | def initialise_states(self): 50 | self.states = [ 51 | TimeSet.State("hours", 0, "time", 3, 24), 52 | TimeSet.State("minutes", 13, "time", 4, 60), 53 | TimeSet.State("year", 0, "year", 0, 3000, length=4), 54 | TimeSet.State("month", 0, "date", 1, 12, offset=1), 55 | TimeSet.State("day", 13, "date", 2, -1, offset=1), 56 | ] 57 | 58 | def enable(self): 59 | self.enabled = True 60 | self.state_index = 0 61 | self.state = self.states[self.state_index] 62 | self.update_display() 63 | self.buttons.add_callback(2, self.up_callback, max=500) 64 | self.buttons.add_callback(3, self.down_callback, max=500) 65 | 66 | def disable(self): 67 | self.active = False 68 | self.enabled = False 69 | self.state = None 70 | 71 | def half_secs_callback(self, t): 72 | if self.enabled: 73 | self.flash_count = (self.flash_count+1)%3 74 | if self.flash_count == 2: 75 | if self.state.length == 2: 76 | self.display.show_text(" ", pos=self.state.position) 77 | elif self.state.length == 4: 78 | self.display.show_text(" ", pos=self.state.position) 79 | self.flash_state = False 80 | else: 81 | if not self.flash_state: 82 | self.flash_state = True 83 | if self.state.length == 2: 84 | self.display.show_text("%02d" % self.time[self.state.index], pos=self.state.position) 85 | elif self.state.length == 4: 86 | self.display.show_text("%04d" % self.time[self.state.index], pos=self.state.position) 87 | 88 | def mins_callback(self, t): 89 | if self.enabled: 90 | self.update_display() 91 | 92 | def update_display(self): 93 | self.time = self.rtc.get_time() 94 | self.display.clear() 95 | if self.state.panel == "time": 96 | t = self.rtc.get_time() 97 | now = "%02d:%02d" % (t[3], t[4]) 98 | self.display.show_text(now) 99 | 100 | elif self.state.panel == "year": 101 | t = self.rtc.get_time() 102 | now = "%04d" % (t[0]) 103 | self.display.show_text(now) 104 | 105 | elif self.state.panel == "date": 106 | t = self.rtc.get_time() 107 | now = "%02d/%02d" % (t[1], t[2]) 108 | self.display.show_text(now) 109 | 110 | def up_callback(self, t): 111 | self.active = True 112 | t = list(self.rtc.get_time()) 113 | max = self.state.max 114 | if max ==-1: 115 | # This is "day of month", which varies 116 | month = t[1] 117 | max = month_max[month] 118 | 119 | t[self.state.index] = (t[self.state.index]+1-self.state.offset) % max + self.state.offset 120 | self.rtc.save_time(tuple(t)) 121 | self.flash_count = 0 122 | self.update_display() 123 | 124 | def down_callback(self, t): 125 | self.active = True 126 | t = list(self.rtc.get_time()) 127 | max = self.state.max 128 | if max ==-1: 129 | # This is "day of month", which varies 130 | month = t[1] 131 | max = month_max[month] 132 | 133 | t[self.state.index] = (t[self.state.index]-1-self.state.offset) % max + self.state.offset 134 | self.rtc.save_time(tuple(t)) 135 | self.flash_count = 0 136 | self.update_display() 137 | 138 | def stop_callback(self, t): 139 | self.scheduler.disable_app(self.name) 140 | 141 | def top_button(self, t): 142 | self.flash_count = 0 143 | self.state_index = (self.state_index + 1) % len(self.states) 144 | self.state = self.states[self.state_index] 145 | self.display.clear() 146 | self.update_display() 147 | -------------------------------------------------------------------------------- /util.py: -------------------------------------------------------------------------------- 1 | def singleton(class_): 2 | instances = {} 3 | def getinstance(*args, **kwargs): 4 | if class_ not in instances: 5 | instances[class_] = class_(*args, **kwargs) 6 | return instances[class_] 7 | return getinstance --------------------------------------------------------------------------------