main.lua 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. max = 1,
  15. auth = wifi.AUTH_OPEN
  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, wifi_default(function()
  21. return nil --nil function to use decorator side effects: code smell
  22. end))
  23. func(...)
  24. end
  25. function wifi_default(func, ...)
  26. server.stop()
  27. wifi.setmode(wifi.STATION)
  28. wifi.sleeptype(wifi.NONE_SLEEP)
  29. func(...)
  30. wifi.sleeptype(wifi.MODEM_SLEEP)
  31. end
  32. function handle_short_press()
  33. wifi_default(yo.yo, read.yo_recipient(), read.api_key())
  34. end
  35. function handle_long_press()
  36. wifi_setup(server.start)
  37. end
  38. function handle_button_flip()
  39. local long_press_time = 3000 -- 3 seconds
  40. local level = gpio.read(button_pin)
  41. debug_message('handle_button_flip: ' .. level)
  42. if level == 1 then -- button depressed
  43. debug_message('handle_button_flip: pressed: start long press timer')
  44. tmr.alarm(TIMERS.interrupt, long_press_time, 0, function()
  45. debug_message('handle_button_flip: long press!')
  46. if server.is_serving() then
  47. debug_message('handle_button_flip: toggle setup OFF')
  48. handle_short_press()
  49. else
  50. debug_message('handle_button_flip: toggle setup ON')
  51. handle_long_press()
  52. end
  53. end)
  54. else -- button released
  55. debug_message('handle_button_flip: released: end long press timer')
  56. tmr.stop(TIMERS.interrupt)
  57. if not server.is_serving() then
  58. debug_message('handle_button_flip: short press!')
  59. handle_short_press()
  60. end
  61. end
  62. end
  63. function debounce(delay, func)
  64. local last = 0
  65. return function(...)
  66. local now = tmr.now()
  67. if now - last < delay then
  68. debug_message("debounce: prevent")
  69. return
  70. end
  71. last = now
  72. debug_message("debounce: allow")
  73. return func(...)
  74. end
  75. end
  76. handle_short_press = debounce(3000000, handle_short_press) --3 seconds
  77. gpio.mode(button_pin, gpio.INT, gpio.FLOAT)
  78. gpio.trig(button_pin, "both", debounce(50000, handle_button_flip)) --50 ms