server.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. local read = require('read')
  2. local net = net
  3. local string = string
  4. local assert = assert
  5. local type = type
  6. local srv = nil
  7. local debug_message = debug_message
  8. module(...)
  9. local function connect(conn, data)
  10. local query_data
  11. conn:on('receive',
  12. function(cn, req_data)
  13. query_data = get_http_req(req_data)
  14. debug_message(query_data['METHOD'] .. ' ' .. ' ' .. query_data['User-Agent'])
  15. send_index(cn)
  16. -- Close the connection for the request
  17. cn:close()
  18. end
  19. )
  20. end
  21. -- Build and return a table of the http request data
  22. function get_http_req(instr)
  23. local t = {}
  24. local first = nil
  25. local key, v, strt_ndx, end_ndx
  26. for str in string.gmatch(instr, '([^\n]+)') do
  27. -- First line in the method and path
  28. if(first == nil) then
  29. first = 1
  30. strt_ndx, end_ndx = string.find(str, '([^ ]+)')
  31. v = trim(string.sub(str, end_ndx + 2))
  32. key = trim(string.sub(str, strt_ndx, end_ndx))
  33. t['METHOD'] = key
  34. t['REQUEST'] = v
  35. else -- Process and reamaining ':' fields
  36. strt_ndx, end_ndx = string.find(str, '([^:]+)')
  37. if(end_ndx ~= nil) then
  38. v = trim(string.sub(str, end_ndx + 2))
  39. key = trim(string.sub(str, strt_ndx, end_ndx))
  40. t[key] = v
  41. end
  42. end
  43. end
  44. return t
  45. end
  46. -- String trim left and right
  47. function trim(s)
  48. return(s:gsub('^%s*(.-)%s*$', '%1'))
  49. end
  50. function send_index(conn)
  51. debug_message('server.send_index')
  52. index = read.index()
  53. local settings = read.current_settings()
  54. assert(type(settings.ssid) == 'string', 'ssid must be a string')
  55. assert(type(settings.status) == 'string', 'status must be a string')
  56. assert(type(settings.yo_to) == 'string', 'yo_to must be a string')
  57. index = string.gsub(index, 'S_', settings.ssid)
  58. index = string.gsub(index, 'T_', settings.status)
  59. index = string.gsub(index, 'R_', settings.yo_to)
  60. debug_message('sending index')
  61. debug_message('____________')
  62. debug_message(index)
  63. debug_message('____________')
  64. conn:send('HTTP/1.1 200 OK\n\n' .. index)
  65. end
  66. function start()
  67. debug_message('server.start')
  68. debug_message(srv)
  69. if srv then
  70. srv = nil
  71. end
  72. srv = net.createServer(net.TCP, 30)
  73. srv:listen(80, connect)
  74. debug_message(srv)
  75. end
  76. function stop()
  77. debug_message('server.stop')
  78. debug_message(srv)
  79. if srv then
  80. srv:close()
  81. srv = nil
  82. end
  83. debug_message(srv)
  84. end