vibrating_alarm_m5stickc.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. """
  2. tested on uiflow for stickc v1.8.1
  3. """
  4. import json
  5. # pylint: disable=import-error
  6. import esp32
  7. import m5ui
  8. import machine
  9. import micropython
  10. import utils
  11. import utime
  12. from m5stack import axp, btnA, btnB, lcd, rtc
  13. _LARGE_FONT = lcd.FONT_DejaVu40
  14. _SMALL_FONT = lcd.FONT_DejaVu18
  15. _DEFAULT_FONT_COLOR = lcd.WHITE
  16. _LEFT_PADDING = 8
  17. _ALARM_TIME_PATH = "alarm.json"
  18. _SCREEN_WIDTH, _SCREEN_HEIGHT = lcd.winsize()
  19. _AWAKE_SECONDS = 8
  20. def _handle_pending_events():
  21. # > [...] a millisecond sleep larger than 10ms will check for pending (soft)
  22. # > interrupts during the sleep. [...] The reason for the 10ms value is
  23. # > because the FreeRTOS tick is 10ms, [...]
  24. # https://github.com/micropython/micropython/issues/3493#issuecomment-352617624
  25. # https://github.com/micropython/micropython/commit/4ed586528047d3eced28a9f4af11dbbe64fa99bb
  26. utime.sleep_ms(11)
  27. class App:
  28. # pylint: disable=too-few-public-methods,too-many-instance-attributes
  29. def __init__(self) -> None:
  30. self._clock_text_box = None
  31. self._menu_position = 0
  32. self._wait_for_sleep_start_time_update = False
  33. self._sleep_start_time_seconds = 0.0
  34. self._alarm_hour = None
  35. self._alarm_minute = None
  36. self._alarm_hour_text_box = None
  37. self._alarm_minute_text_box = None
  38. self._alarm_timer = None
  39. self._battery_status_text_box = None
  40. @property
  41. def _now_time(self) -> int:
  42. # > [contradictory to] official micropython documentation, to set RTC,
  43. # > use particular tuple (year , month, day, week=0, hour, minute, second, timestamp=0)
  44. # https://community.m5stack.com/topic/3108/m5stack-core2-micropython-rtc-example
  45. hour, minute, seconds = rtc.now()[3:]
  46. return (hour * 60 + minute) * 60 + seconds
  47. @property
  48. def _alarm_time(self) -> int:
  49. return (self._alarm_hour * 60 + self._alarm_minute) * 60 # type: ignore
  50. def _load_alarm_time(self) -> None:
  51. with open(_ALARM_TIME_PATH, "r") as alarm_time_file:
  52. alarm_time = json.load(alarm_time_file)
  53. self._alarm_hour = alarm_time["hour"]
  54. self._alarm_minute = alarm_time["minute"]
  55. def _save_alarm_time(self) -> None:
  56. with open(_ALARM_TIME_PATH, "w") as alarm_time_file:
  57. json.dump(
  58. {"hour": self._alarm_hour, "minute": self._alarm_minute},
  59. alarm_time_file,
  60. )
  61. def _reschedule_sleep(self, interrupt: bool) -> None:
  62. if interrupt:
  63. self._wait_for_sleep_start_time_update = True
  64. micropython.schedule(self._reschedule_sleep, False)
  65. else:
  66. self._sleep_start_time_seconds = utime.time() + _AWAKE_SECONDS
  67. self._wait_for_sleep_start_time_update = False
  68. def _update_menu(self, event_arg: None) -> None:
  69. # pylint: disable=unused-argument; callback
  70. self._alarm_hour_text_box.setColor( # type: ignore
  71. lcd.GREEN
  72. if self._menu_position == 1
  73. else (lcd.RED if self._menu_position == 2 else _DEFAULT_FONT_COLOR)
  74. )
  75. self._alarm_minute_text_box.setColor( # type: ignore
  76. lcd.GREEN
  77. if self._menu_position == 3
  78. else (lcd.RED if self._menu_position == 4 else _DEFAULT_FONT_COLOR)
  79. )
  80. def _button_a_pressed(self) -> None:
  81. self._reschedule_sleep(interrupt=True)
  82. self._menu_position = (self._menu_position + 1) % 5
  83. # https://docs.micropython.org/en/latest/library/micropython.html#micropython.schedule
  84. micropython.schedule(self._update_menu, None)
  85. @staticmethod
  86. def _alert() -> None:
  87. print("ALARM")
  88. def _alarm(self, timer: machine.Timer) -> None:
  89. # pylint: disable=unused-argument; callback
  90. micropython.schedule(lambda n: self._alert(), None)
  91. micropython.schedule(lambda n: self._configure_alarm_timer(), None)
  92. def _configure_alarm_timer(self) -> None:
  93. seconds_until_alarm = (self._alarm_time - self._now_time - 1) % (
  94. 24 * 60 * 60
  95. ) + 1
  96. print("alarm in ", seconds_until_alarm / 60, " min")
  97. # TODO configure wake from sleep
  98. self._alarm_timer.init( # type: ignore
  99. period=seconds_until_alarm * 1000, # ms
  100. mode=machine.Timer.ONE_SHOT,
  101. callback=self._alarm,
  102. )
  103. def _update_alarm_time(self, event_arg: None) -> None:
  104. # pylint: disable=unused-argument; callback
  105. self._alarm_hour_text_box.setText( # type: ignore
  106. "{:02d}".format(self._alarm_hour) # type: ignore
  107. )
  108. self._alarm_minute_text_box.setText( # type: ignore
  109. "{:02d}".format(self._alarm_minute) # type: ignore
  110. )
  111. self._save_alarm_time()
  112. self._configure_alarm_timer()
  113. def _button_b_pressed(self) -> None:
  114. self._reschedule_sleep(interrupt=True)
  115. if self._menu_position == 1:
  116. self._alarm_hour += 1 # type: ignore
  117. elif self._menu_position == 2:
  118. self._alarm_hour -= 1 # type: ignore
  119. elif self._menu_position == 3:
  120. self._alarm_minute += 1 # type: ignore
  121. elif self._menu_position == 4:
  122. self._alarm_minute -= 1 # type: ignore
  123. self._alarm_hour %= 24 # type: ignore
  124. self._alarm_minute %= 60 # type: ignore
  125. micropython.schedule(self._update_alarm_time, None)
  126. @staticmethod
  127. def _format_time() -> str:
  128. return "{:02d}:{:02d}".format(*rtc.now()[3:5])
  129. def _setup_clock(self) -> None:
  130. # https://github.com/m5stack/UIFlow-Code/wiki/M5UI#textbox
  131. self._clock_text_box = m5ui.M5TextBox(
  132. _SCREEN_WIDTH - 1,
  133. _LEFT_PADDING,
  134. self._format_time(),
  135. _LARGE_FONT,
  136. _DEFAULT_FONT_COLOR,
  137. rotate=90,
  138. )
  139. machine.Timer(0).init(
  140. period=4000, # ms
  141. mode=machine.Timer.PERIODIC,
  142. callback=lambda t: self._clock_text_box.setText(self._format_time()), # type: ignore
  143. )
  144. def _setup_alarm(self) -> None:
  145. if not utils.exists(_ALARM_TIME_PATH):
  146. self._alarm_hour = self._alarm_minute = 0 # type: ignore
  147. self._save_alarm_time()
  148. else:
  149. self._load_alarm_time()
  150. self._alarm_hour_text_box = m5ui.M5TextBox(
  151. _SCREEN_WIDTH // 2,
  152. _LEFT_PADDING,
  153. "{:02d}".format(self._alarm_hour), # type: ignore
  154. _LARGE_FONT,
  155. _DEFAULT_FONT_COLOR,
  156. rotate=90,
  157. )
  158. m5ui.M5TextBox(
  159. _SCREEN_WIDTH // 2,
  160. _LEFT_PADDING + 53,
  161. ":",
  162. _LARGE_FONT,
  163. _DEFAULT_FONT_COLOR,
  164. rotate=90,
  165. )
  166. self._alarm_minute_text_box = m5ui.M5TextBox(
  167. _SCREEN_WIDTH // 2,
  168. _LEFT_PADDING + 66,
  169. "{:02d}".format(self._alarm_minute), # type: ignore
  170. _LARGE_FONT,
  171. _DEFAULT_FONT_COLOR,
  172. rotate=90,
  173. )
  174. # machine.Timer(1).init(...) breaks button handling
  175. self._alarm_timer = machine.Timer(2)
  176. self._configure_alarm_timer()
  177. def _update_battery_status_info(self) -> None:
  178. self._battery_status_text_box.setText( # type: ignore
  179. "{:.02f}V".format(axp.getBatVoltage())
  180. )
  181. def _setup_battery_status_info(self) -> None:
  182. self._battery_status_text_box = m5ui.M5TextBox(
  183. 12,
  184. _SCREEN_HEIGHT - 20,
  185. "",
  186. _SMALL_FONT,
  187. _DEFAULT_FONT_COLOR,
  188. rotate=0,
  189. )
  190. def run(self) -> None:
  191. m5ui.setScreenColor(0x000000) # clear screen
  192. self._setup_clock()
  193. self._setup_alarm()
  194. self._setup_battery_status_info()
  195. btnA.wasPressed(self._button_a_pressed)
  196. btnB.wasPressed(self._button_b_pressed)
  197. # not sure whether ext0 would be better
  198. esp32.wake_on_ext1([btnA.pin], esp32.WAKEUP_ALL_LOW)
  199. self._reschedule_sleep(interrupt=False)
  200. while True:
  201. self._update_battery_status_info()
  202. while utime.time() < self._sleep_start_time_seconds:
  203. utime.sleep(1) # seconds
  204. # TODO turn off display
  205. axp.setLcdBrightness(30)
  206. machine.lightsleep()
  207. # TODO turn on display
  208. axp.setLcdBrightness(100)
  209. print("wake reason:", machine.wake_reason())
  210. _handle_pending_events()
  211. while self._wait_for_sleep_start_time_update:
  212. _handle_pending_events()
  213. App().run()