main.lua 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 short_press()
  36. wifi_default(yo.yo, read.yo_recipient(), read.api_key())
  37. end
  38. function long_press()
  39. wifi_setup(server.start)
  40. end
  41. function short_or_long_press()
  42. local long_press_time = 3000 -- 3 seconds
  43. local level = gpio.read(button_pin)
  44. debug_message('short_or_long_press: ' .. level)
  45. if level == 1 then -- button depressed
  46. debug_message('short_or_long_press: pressed: start long press timer')
  47. tmr.alarm(TIMERS.interrupt, long_press_time, 0, function()
  48. debug_message('short_or_long_press: long press!')
  49. if server.is_serving() then
  50. debug_message('short_or_long_press: toggle setup OFF')
  51. short_press()
  52. else
  53. debug_message('short_or_long_press: toggle setup ON')
  54. long_press()
  55. end
  56. end)
  57. else -- button released
  58. debug_message('short_or_long_press: released: end long press timer')
  59. tmr.stop(TIMERS.interrupt)
  60. if not server.is_serving() then
  61. debug_message('short_or_long_press: short press!')
  62. short_press()
  63. end
  64. end
  65. end
  66. function debounce(func)
  67. local last = 0 --units: microseconds
  68. local delay = 50000 --units: microseconds
  69. return function(...)
  70. local now = tmr.now()
  71. if now - last < delay then
  72. tmr.stop(TIMERS.interrupt)
  73. debug_message("debounce: prevented extra push")
  74. return
  75. end
  76. last = now
  77. debug_message("debounce: succeed")
  78. return func(...)
  79. end
  80. end
  81. gpio.mode(button_pin, gpio.INT, gpio.FLOAT)
  82. gpio.trig(button_pin, "both", debounce(short_or_long_press))