http сервер LUA
- Войдите на сайт для отправки комментариев
Пт, 16/06/2017 - 00:12
Помогите:
-- init.lua --
-- Global Variables (Modify for your network)
ssid = ""
pass = ""
-- Configure Wireless Internet
print('\nAll About Circuits init.lua\n')
wifi.setmode(wifi.STATION)
print('set mode=STATION (mode='..wifi.getmode()..')\n')
print('MAC Address: ',wifi.sta.getmac())
print('Chip ID: ',node.chipid())
print('Heap Size: ',node.heap(),'\n')
-- wifi config start
wifi.sta.config(ssid,pass)
-- wifi config end
-- Run the main file
dofile("main.lua")
-- main.lua --
-- Connect
print('\nAll About Circuits main.lua\n')
tmr.alarm(0, 1000, 1, function()
if wifi.sta.getip() == nil then
print("Connecting to AP...\n")
else
ip, nm, gw=wifi.sta.getip()
print("IP Info: \nIP Address: ",ip)
print("Netmask: ",nm)
print("Gateway Addr: ",gw,'\n')
tmr.stop(0)
end
end)
-- Start a simple http server
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
print(payload)
conn:send("<h1> Hello, NodeMCU!!! </h1>")
end)
conn:on("sent",function(conn) conn:close() end)
end)
Запрос по указанному ip адресу выдаёт Hello, NodeMCU!!!
Как сделать условие, чтобы при запросе /index выводился один текст, при запросе /123 другой и т п
Это троллинг? Вы занимаетесь этим уже три года!
Первый раз пробую lua.
Статьи которые нахожу, вразброс, без комментариев, что-то получается перевести.
Подскажите где почитать, посмотреть.
Подсказываю - http://www.esp8266.com/viewtopic.php?f=19&t=990
Гугл рулит !
Доэксперементировался...Сброс платы не помогает. В чём дело?
Откуда берётся main.lua если flash очищаю?
Модуль восстановил, новой прошивкой.
-- main.lua -- ---------------------------------- -- WiFi Connection Verification -- ---------------------------------- tmr.alarm(0, 1000, 1, function() if wifi.sta.getip() == nil then print("Connecting to AP...\n") else ip, nm, gw=wifi.sta.getip() print("IP Info: \nIP Address: ",ip) print("Netmask: ",nm) print("Gateway Addr: ",gw,'\n') tmr.stop(0) end end) ---------------- -- Web Server -- ---------------- srv = net.createServer(net.TCP, 30) srv:listen(80,function(conn) conn:on("receive", function(conn, payload) --print(payload) function esp_update() zagolovok=string.sub(payload,postparse[2]+1,#payload) if zagolovok == "perv" then otvet="Первая страничка" elseif zagolovok == "vtor" then otvet="Вторая страничка" else otvet="Иная страничка" end postparse={string.find(payload,"zapros=")} if postparse[2]~=nil then esp_update()end conn:send('HTTP/1.1 200 OK\n\n') conn:send('<!DOCTYPE HTML>\n') conn:send('<html>\n') conn:send('<head><meta content="text/html; charset=utf-8">\n') conn:send('<title>Demo</title></head>\n') conn:send('<body><h1>Проверка работы</h1>\n') conn:send('<p>'..otvet..'</p>\n') conn:send('</body></html>\n') conn:on("sent", function(conn) conn:close() end) end) end)слишком много end) в конце?
Вообще, писать по несколько операторов на строке, не разделяя их ничем - верный способ получить глюки
Почему много?
Почему много?
Просто предположил. Там еще один end на строку выше - его не забыли? Или он к function в той же строке относится?
Как я понимаю к той же строке относится
28ifzagolovok =="perv"then otvet="Первая страничка"29elseif zagolovok =="vtor"then otvet="Вторая страничка"30elseotvet="Иная страничка"31endend пропустил
-- main.lua -- ---------------------------------- -- WiFi Connection Verification -- ---------------------------------- tmr.alarm(0, 1000, 1, function() if wifi.sta.getip() == nil then print("Connecting to AP...\n") else ip, nm, gw=wifi.sta.getip() print("IP Info: \nIP Address: ",ip) print("Netmask: ",nm) print("Gateway Addr: ",gw,'\n') tmr.stop(0) end end) otvet="0000" ---------------- -- Web Server -- ---------------- srv = net.createServer(net.TCP, 30) srv:listen(80,function(conn) conn:on("receive", function(conn, payload) print(payload) function esp_update() zapros=string.sub(payload,postparse[2]+1,#payload) if zapros == "perv" then otvet="Первая" end if zapros == "vtor" then otvet="Вторая" end end postparse={string.find(payload,"zapros=")} if postparse[2]~=nil then esp_update()end conn:send('HTTP/1.1 200 OK\n\n') conn:send('<!DOCTYPE HTML>\n') conn:send('<html>\n') conn:send('<head><meta content="text/html; charset=utf-8">\n') conn:send('<title>Demo</title></head>\n') conn:send('<body><h1>Проверка работы</h1>\n') conn:send('<p>'..otvet..'</p>\n') conn:send('</body></html>\n') conn:on("sent", function(conn) conn:close() end) end) end)слишком много end) в конце?
Вообще, писать по несколько операторов на строке, не разделяя их ничем - верный способ получить глюки
Иш умный нашелся! А то что луа интерпретер и из-за этого хранит в модуле исходный код как есть а памяти там мизер не знаеш. И на разделители тратится - роскош непозволительная. Потому иной раз пишется даже так.
local WebSockAnsv="HTTP/1.1 101 Switching Protocols\r\n\Upgrade: websocket\r\n\Connection: Upgrade\r\n\Sec-WebSocket-Accept: " local WebSocketEnd="\r\n"; local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' local HTTP_html="HTTP/1.1 200 OK\nServer: ESP (nodeMCU)\nContent-Length: " local html=[[ <head><meta charset="utf-8"></head><h1>WebSocket for ESP8266</h1> <table><tr><td><input type="button" onclick="OpenWS()" value="Open"/></td><td> <input type="button" onclick="CloseWS()" value="Close"/> </td><td><input type="button" onclick="snd('?print(node.heap())')" value="Send"/> </td><td><input type="button" onclick="ld()" value="Load"/></td> </td></tr></table><input type="file" id="fn"/> <p style="color:red" id="time">--</p><p style="color:red" id="state">--</p> <table><tr><th>GPIO #</th><th>0</th><th>1</th><th>2</th><th>3</th></tr> <tr><td>Input</td><td><span id="g0">?</span></td><td><span id="g1">?</span></td> <td><span id="g2">?</span></td><td><span id="g3">?</span></td></tr> <tr><td rowspan="3">Set mode</td> <td><input type="button" onclick="snСкажите Sergeyevd, коего хера открыли новую тему а не старую по ESP подняли? У Вас необічный взгляд на уникальную проблему? Так нихрена такого. Из принципа не буду смотреть на ваш говнокод.
Не поднял старую так как не нашёл тему про LUA
Написал письмо администрации о перемещении в наиболее подходящую тему.
Разобрался немного"
-- main.lua -- tmr.alarm(0, 1000, 1, function() if wifi.sta.getip() == nil then print("Connecting to AP...\n") else ip, nm, gw=wifi.sta.getip() print("IP Info: \nIP Address: ",ip) print("Netmask: ",nm) print("Gateway Addr: ",gw,'\n') tmr.stop(0) end end) -- a simple http server srv = net.createServer(net.TCP, 30) srv:listen(80,function(conn) conn:on("receive",function(conn,get) --print(get) na=string.find(get,"z="); function zagolovok() con=string.find(get,"&"); zag=string.sub(get, na,con-1) if zag == "z=1" then text="Первая" elseif zag == "z=2" then text="Вторая" elseif zag == "z=3" then text="Третья" else text="Иная" end end if na~=nil then zagolovok() end conn:send("<!DOCTYPE html><html><head> <meta charset=\"windows-1251\">") conn:send("<title>Server</title></head><body>") conn:send("<h1>"..text.."</h1>") conn:send("</body></html>") conn:on("sent", function(conn) conn:close() end) end) end)Объясните пожалуйста текст вот этих строк кода:
srv = net.createServer(net.TCP, 30) --Создаю сервер с таймаутом 30 сек srv:listen(80,function(conn)--??? conn:on("receive", function(conn, get)--передаю данные в get? conn:on("sent", function(conn) conn:close() end)--??Ещё интересует из предыдущего кода:
mcu_do=string.sub(payload,postparse[2]+1,#payload) --зачем [2] в скобках? зачем символ #? postparse={string.find(payload,"mcu_do=")} --зачем эти {} скобки? if postparse[2]~=nil then esp_update()end --зачем [2] в скобках?И вопрос про датчик температуры (в продолжение темы, так как возможно я что-то не так сделал в коде сервера)
Получается что когда я делаю запрос по адресу 192.168.0.91/z=1& то функция GetSensorData() у меня выполняется не один раз.
Почему?
-- main.lua -- tmr.alarm(0, 1000, 1, function() if wifi.sta.getip() == nil then print("Connecting to AP...\n") else ip, nm, gw=wifi.sta.getip() print("IP Info: \nIP Address: ",ip) print("Netmask: ",nm) print("Gateway Addr: ",gw,'\n') tmr.stop(0) end end) -- a simple http server srv = net.createServer(net.TCP, 30) srv:listen(80,function(conn) conn:on("receive",function(conn,get) --print(get) na=string.find(get,"z="); function GetSensorData() print( "Trying to get temperature..." ) pin = 4 status, temp, humi, temp_dec, humi_dec = dht.read(pin) if status == dht.OK then text="Температура="..temp.."°C<br>Влажность="..humi.."%" elseif status == dht.ERROR_CHECKSUM then print( "DHT Checksum error." ) elseif status == dht.ERROR_TIMEOUT then print( "DHT timed out." ) end end function zagolovok() con=string.find(get,"&"); zag=string.sub(get, na,con-1) if zag == "z=1" then GetSensorData() elseif zag == "z=2" then text="Вторая" elseif zag == "z=3" then text="Третья" else text="Иная" end end if na~=nil then zagolovok() end conn:send("<!DOCTYPE html><html><head> <meta charset=\"windows-1251\">") conn:send("<title>Server</title></head><body>") conn:send("<p>"..text.."</p>") conn:send("</body></html>") conn:on("sent", function(conn) conn:close() end) end) end)