main.lua 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. TIMERS = {
  2. interrupt = 0,
  3. setup_timeout = 1
  4. }
  5. local yo = require('yo')
  6. local server = require('server')
  7. local read = require('read')
  8. local button_pin = 6
  9. function wifi_setup(func, ...)
  10. wifi.setmode(wifi.STATIONAP)
  11. wifi.ap.config({
  12. ssid = "YoButton-" .. node.chipid(),
  13. pwd = "yobutton",
  14. auth = wifi.AUTH_OPEN,
  15. max = 1
  16. })
  17. wifi.ap.dhcp.start()
  18. wifi.sleeptype(wifi.NONE_SLEEP)
  19. --wifi_setup inactivity timeout: 5 minutes
  20. tmr.alarm(TIMERS.setup_timeout, 60*5*1000, tmr.ALARM_SINGLE, function()
  21. wifi_default(function()
  22. debug_message('wifi_setup: timeout')
  23. return nil --nil function to use decorator side effects: code smell
  24. end)
  25. end)
  26. func(...)
  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, tmr.ALARM_SINGLE, 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. wifi.setmode(wifi.STATION)
  80. handle_short_press = debounce(3000000, handle_short_press) --3 seconds
  81. gpio.mode(button_pin, gpio.INT, gpio.FLOAT)
  82. gpio.trig(button_pin, "both", debounce(50000, handle_button_flip)) --50 ms