main.lua 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. DEBUG = true
  2. TIMERS = {
  3. interrupt = 1
  4. }
  5. function debug_message(message)
  6. if DEBUG then
  7. print(message)
  8. end
  9. --TODO: rolling last 10
  10. end
  11. local yo = require('yo')
  12. local server = require('server')
  13. local read = require('read')
  14. local button_pin = 6
  15. function wifi_setup(func, ...)
  16. wifi.setmode(wifi.STATIONAP)
  17. wifi.ap.config({
  18. ssid = "YoButton-" .. node.chipid(),
  19. pwd = "yobutton",
  20. max = 1,
  21. auth = wifi.AUTH_OPEN
  22. })
  23. wifi.ap.dhcp.start()
  24. wifi.sleeptype(wifi.NONE_SLEEP)
  25. func(...)
  26. --TODO wifi_setup inactivity timeout
  27. end
  28. function wifi_default(func, ...)
  29. server.stop()
  30. wifi.setmode(wifi.STATION)
  31. wifi.sleeptype(wifi.NONE_SLEEP)
  32. func(...)
  33. wifi.sleeptype(wifi.MODEM_SLEEP)
  34. end
  35. function handle_short_press()
  36. wifi_default(yo.yo, read.yo_recipient(), read.api_key())
  37. end
  38. function handle_long_press()
  39. wifi_setup(server.start)
  40. end
  41. function handle_button_flip()
  42. local long_press_time = 3000 -- 3 seconds
  43. local level = gpio.read(button_pin)
  44. debug_message('handle_button_flip: ' .. level)
  45. if level == 1 then -- button depressed
  46. debug_message('handle_button_flip: pressed: start long press timer')
  47. tmr.alarm(TIMERS.interrupt, long_press_time, 0, function()
  48. debug_message('handle_button_flip: long press!')
  49. if server.is_serving() then
  50. debug_message('handle_button_flip: toggle setup OFF')
  51. handle_short_press()
  52. else
  53. debug_message('handle_button_flip: toggle setup ON')
  54. handle_long_press()
  55. end
  56. end)
  57. else -- button released
  58. debug_message('handle_button_flip: released: end long press timer')
  59. tmr.stop(TIMERS.interrupt)
  60. if not server.is_serving() then
  61. debug_message('handle_button_flip: short press!')
  62. handle_short_press()
  63. end
  64. end
  65. end
  66. function debounce(delay, func)
  67. local last = 0
  68. return function(...)
  69. local now = tmr.now()
  70. if now - last < delay then
  71. debug_message("debounce: prevent")
  72. return
  73. end
  74. last = now
  75. debug_message("debounce: allow")
  76. return func(...)
  77. end
  78. end
  79. handle_short_press = debounce(3000000, handle_short_press) --3 seconds
  80. gpio.mode(button_pin, gpio.INT, gpio.FLOAT)
  81. gpio.trig(button_pin, "both", debounce(50000, handle_button_flip)) --50 ms