telnet.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. --[[SPLIT MODULE telnet]]
  2. --[[ A telnet server T. Ellison, June 2019
  3. This version of the telnet server demonstrates the use of the new stdin and stout
  4. pipes, which is a C implementation of the Lua fifosock concept moved into the
  5. Lua core. These two pipes are referenced in the Lua registry.
  6. ]]
  7. --luacheck: no unused args
  8. local M = {}
  9. local modname = ...
  10. local function telnet_session(socket)
  11. local node = node
  12. local stdout
  13. local function output_CB(opipe) -- upval: socket
  14. stdout = opipe
  15. local rec = opipe:read(1400)
  16. if rec and #rec > 0 then socket:send(rec) end
  17. return false -- don't repost as the on:sent will do this
  18. end
  19. local function onsent_CB(skt) -- upval: stdout
  20. local rec = stdout:read(1400)
  21. if rec and #rec > 0 then skt:send(rec) end
  22. end
  23. local function disconnect_CB(skt) -- upval: socket, stdout
  24. node.output()
  25. socket, stdout = nil, nil -- set upvals to nl to allow GC
  26. end
  27. node.output(output_CB, 0)
  28. socket:on("receive", function(_,rec) node.input(rec) end)
  29. socket:on("sent", onsent_CB)
  30. socket:on("disconnection", disconnect_CB)
  31. print(("Welcome to NodeMCU world (%d mem free, %s)"):format(
  32. node.heap(), wifi.sta.getip()))
  33. end
  34. function M.open(this, ssid, pwd, port)
  35. local tmr, wifi, uwrite = tmr, wifi, uart.write
  36. if ssid then
  37. wifi.setmode(wifi.STATION, false)
  38. wifi.sta.config { ssid = ssid, pwd = pwd, save = false }
  39. end
  40. local t = tmr.create()
  41. t:alarm(500, tmr.ALARM_AUTO, function()
  42. if (wifi.sta.status() == wifi.STA_GOTIP) then
  43. t:unregister()
  44. t=nil
  45. print(("Telnet server started (%d mem free, %s)"):format(
  46. node.heap(), wifi.sta.getip()))
  47. M.svr = net.createServer(net.TCP, 180)
  48. M.svr:listen(port or 23, telnet_session)
  49. else
  50. uwrite(0,".")
  51. end
  52. end)
  53. end
  54. function M.close(this)
  55. if this.svr then this.svr:close() end
  56. package.loaded[modname] = nil
  57. end
  58. return M
  59. --[[SPLIT HERE]]