main.lua 2.4 KB

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