websocket2.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. function trace(text)
  2. local f = io.open("websocket2.trace", "a")
  3. f:write(os.date() .. " - " .. text .. "\n")
  4. f:close()
  5. end
  6. function iswebsocket()
  7. return mg.lua_type == "websocket"
  8. end
  9. trace("called with Lua type " .. tostring(mg.lua_type))
  10. if not iswebsocket() then
  11. trace("no websocket")
  12. mg.write("HTTP/1.0 403 Forbidden\r\n")
  13. mg.write("Connection: close\r\n")
  14. mg.write("\r\n")
  15. mg.write("forbidden")
  16. return
  17. end
  18. -- Serialize table to string
  19. function ser(val)
  20. local t
  21. if type(val) == "table" then
  22. for k,v in pairs(val) do
  23. if t then
  24. t = t .. ", " .. ser(k) .. "=" .. ser(v)
  25. else
  26. t = "{" .. ser(k) .. "=" .. ser(v)
  27. end
  28. end
  29. t = t .. "}"
  30. else
  31. t = tostring(val)
  32. end
  33. return t
  34. end
  35. -- table of all active connection
  36. allConnections = {}
  37. -- function to get a client identification string
  38. function who(tab)
  39. local ri = allConnections[tab.client].request_info
  40. return ri.remote_addr .. ":" .. ri.remote_port
  41. end
  42. -- Callback to accept or reject a connection
  43. function open(tab)
  44. allConnections[tab.client] = tab
  45. trace("open[" .. who(tab) .. "]: " .. ser(tab))
  46. return true -- return true to accept the connection
  47. end
  48. -- Callback for "Websocket ready"
  49. function ready(tab)
  50. trace("ready[" .. who(tab) .. "]: " .. ser(tab))
  51. mg.write(tab.client, "text", "Websocket ready")
  52. mg.write(tab.client, 1, "-->h 180");
  53. mg.write(tab.client, "-->m 180");
  54. senddata()
  55. mg.set_interval(timer, 1)
  56. return true -- return true to keep the connection open
  57. end
  58. -- Callback for "Websocket received data"
  59. function data(tab)
  60. trace("data[" .. who(tab) .. "]: " .. ser(tab))
  61. senddata()
  62. return true -- return true to keep the connection open
  63. end
  64. -- Callback for "Websocket is closing"
  65. function close(tab)
  66. trace("close[" .. who(tab) .. "]: " .. ser(tab))
  67. mg.write("text", "end")
  68. allConnections[tab.client] = nil
  69. end
  70. function senddata()
  71. local date = os.date('*t');
  72. local hand = (date.hour%12)*60+date.min;
  73. mg.write("text", string.format("%u:%02u:%02u", date.hour, date.min, date.sec));
  74. if (hand ~= lasthand) then
  75. mg.write(1, string.format("-->h %f", hand*360/(12*60)));
  76. mg.write( string.format("-->m %f", date.min*360/60));
  77. lasthand = hand;
  78. end
  79. if bits and content then
  80. data(bits, content)
  81. end
  82. end
  83. function timer()
  84. trace("timer")
  85. senddata()
  86. return true -- return true to keep an interval timer running
  87. end