main.lua 2.1 KB

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