Skip to content

Instantly share code, notes, and snippets.

@blippy
Created June 16, 2020 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blippy/eb1dd77244072683757a00acedef4603 to your computer and use it in GitHub Desktop.
Save blippy/eb1dd77244072683757a00acedef4603 to your computer and use it in GitHub Desktop.
Crude demo of using wifi on ESP8266 Lua
-----------------------------------------------
--- Set Variables ---
-----------------------------------------------
--- WIFI CONFIGURATION ---
WIFI_SSID = ""
WIFI_PASSWORD = ""
WIFI_SIGNAL_MODE = wifi.PHYMODE_N
--- IP CONFIG (Leave blank to use DHCP) ---
ESP8266_IP="192.168.0.30"
ESP8266_NETMASK="255.255.255.0"
ESP8266_GATEWAY="192.168.0.1"
-----------------------------------------------
--- Connect to the wifi network ---
wifi.setmode(wifi.STATION)
wifi.setphymode(WIFI_SIGNAL_MODE)
--wifi.sta.config(WIFI_SSID, WIFI_PASSWORD)
station_cfg={}
station_cfg.ssid=WIFI_SSID
station_cfg.pwd=WIFI_PASSWORD
wifi.sta.config(station_cfg, true)
wifi.sta.connect()
if ESP8266_IP ~= "" then
wifi.sta.setip({ip=ESP8266_IP,netmask=ESP8266_NETMASK,gateway=ESP8266_GATEWAY})
end
-----------------------------------------------
--- Check the IP Address ---
print(wifi.sta.getip())
--local inputbuffer = ""
function get(host, port, url, args, callback)
conn=net.createConnection(net.TCP, false)
local inputbuffer = ""
local argsstr = ""
argsstr = url_encode_table(args)
if (argsstr ~= "") then
argsstr = "?"..argsstr
end
conn:on("receive", function(conn, payload)
inputbuffer = inputbuffer..payload
end)
conn:on("disconnection", function(conn)
conn = nil
inputbuffer = string.sub(inputbuffer,string.find(inputbuffer,"\r\n\r\n") + 4)
callback(inputbuffer)
end)
conn:on("connection", function(conn)
conn:send("GET /"..url..argsstr.." HTTP/1.0\r\n"..
"Host: "..host.."\r\n"..
"Connection: close\r\n"..
"Accept-Charset: utf-8\r\n"..
"Accept-Encoding: \r\n"..
"Accept: */*\r\n\r\n")
end)
conn:connect(port,host)
end
function url_encode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
function url_encode_table(t)
local argts = {}
local i = 1
for k, v in pairs(t) do
argts[i]=url_encode(k).."="..url_encode(v)
i=i+1
end
return table.concat(argts,'&')
end
get("192.168.0.27", 3000, "/index.html", {foo = "bar"}, function (payload)
print(payload)
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment