Commit 6926c66b authored by galjonsfigur's avatar galjonsfigur Committed by Marcel Stör
Browse files

Polish Lua examples (#2846)

* Add missing globals from luacheck config

* Fix luacheck warnings in all lua files

* Re-enable luacheck in Travis

* Speed up Travis by using preinstalled LuaRocks

* Fix more luacheck warnings in httpserver lua module

* Fix DCC module and add appropriate definitions to luacheck config.

* Change inline comments from ignoring block to only ignore specific line

* Add Luacheck for Windows and enable it for both Windows and Linux

* Change luacheck exceptions and fix errors from 1st round of polishing

* Add retry and timeout params to wget
parent 36df8d00
do
wifi.setmode(wifi.SOFTAP) wifi.setmode(wifi.SOFTAP)
wifi.ap.config({ ssid = "test", pwd = "12345678" }) wifi.ap.config({ ssid = "test", pwd = "12345678" })
gpio.mode(1, gpio.OUTPUT) gpio.mode(1, gpio.OUTPUT)
srv = net.createServer(net.TCP) local srv = net.createServer(net.TCP)
srv:listen(80, function(conn) srv:listen(80, function(conn)
conn:on("receive", function(client, request) conn:on("receive", function(client, request)
local buf = "" local buf = ""
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP") local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP") -- luacheck: no unused
if (method == nil) then if (method == nil) then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP") _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP") -- luacheck: no unused
end end
local _GET = {} local _GET = {}
if (vars ~= nil) then if (vars ~= nil) then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v _GET[k] = v
end end
end end
buf = buf .. "<!DOCTYPE html><html><body><h1>Hello, this is NodeMCU.</h1><form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">" buf = buf .. "<!DOCTYPE html><html><body><h1>Hello, this is NodeMCU.</h1>"
.. "<form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">"
local _on, _off = "", "" local _on, _off = "", ""
if (_GET.pin == "ON") then if (_GET.pin == "ON") then
_on = " selected=true" _on = " selected=true"
...@@ -29,3 +32,4 @@ srv:listen(80, function(conn) ...@@ -29,3 +32,4 @@ srv:listen(80, function(conn)
end) end)
conn:on("sent", function(c) c:close() end) conn:on("sent", function(c) c:close() end)
end) end)
end
\ No newline at end of file
...@@ -33,14 +33,14 @@ local function read_data(ADDR, commands, length) ...@@ -33,14 +33,14 @@ local function read_data(ADDR, commands, length)
i2c.start(id) i2c.start(id)
i2c.address(id, ADDR,i2c.RECEIVER) i2c.address(id, ADDR,i2c.RECEIVER)
tmr.delay(200000) tmr.delay(200000)
c = i2c.read(id, length) local c = i2c.read(id, length)
i2c.stop(id) i2c.stop(id)
return c return c
end end
local function read_lux() local function read_lux()
dataT = read_data(GY_30_address, CMD, 2) local dataT = read_data(GY_30_address, CMD, 2)
--Make it more faster --Make it more faster
UT = dataT:byte(1) * 256 + dataT:byte(2) local UT = dataT:byte(1) * 256 + dataT:byte(2)
l = (UT*1000/12) l = (UT*1000/12)
return(l) return(l)
end end
......
...@@ -6,19 +6,17 @@ ...@@ -6,19 +6,17 @@
-- --
-- MIT license, http://opensource.org/licenses/MIT -- MIT license, http://opensource.org/licenses/MIT
-- *************************************************************************** -- ***************************************************************************
tmr.alarm(0, 10000, 1, function() local bh1750 = require("bh1750")
SDA_PIN = 6 -- sda pin, GPIO12 local sda = 6 -- sda pin, GPIO12
SCL_PIN = 5 -- scl pin, GPIO14 local scl = 5 -- scl pin, GPIO14
bh1750 = require("bh1750") do
bh1750.init(SDA_PIN, SCL_PIN) bh1750.init(sda, scl)
bh1750.read(OSS)
l = bh1750.getlux()
print("lux: "..(l / 100).."."..(l % 100).." lx")
-- release module tmr.create():alarm(10000, tmr.ALARM_AUTO, function()
bh1750 = nil bh1750.read()
package.loaded["bh1750"]=nil local l = bh1750.getlux()
print("lux: "..(l / 100).."."..(l % 100).." lx")
end) end)
end
...@@ -10,42 +10,42 @@ ...@@ -10,42 +10,42 @@
--Ps 需要改动的地方LW_GATEWAY(乐联的设备标示),USERKEY(乐联userkey) --Ps 需要改动的地方LW_GATEWAY(乐联的设备标示),USERKEY(乐联userkey)
--Ps You nees to rewrite the LW_GATEWAY(Lelian's Device ID),USERKEY(Lelian's userkey) --Ps You nees to rewrite the LW_GATEWAY(Lelian's Device ID),USERKEY(Lelian's userkey)
local bh1750 = require("bh1750")
tmr.alarm(0, 60000, 1, function()
SDA_PIN = 6 -- sda pin, GPIO12 local sda = 6 -- sda pin, GPIO12
SCL_PIN = 5 -- scl pin, GPIO14 local scl = 5 -- scl pin, GPIO14
local ServerIP
BH1750 = require("BH1750")
BH1750.init(SDA_PIN, SCL_PIN) do
BH1750.read(OSS) bh1750.init(sda, scl)
l = BH1750.getlux()
tmr.create():alarm(60000, tmr.ALARM_AUTO, function()
--定义数据变量格式 Define the veriables formate bh1750.read()
PostData = "[{\"Name\":\"T\",\"Value\":\"" ..(l / 100).."."..(l % 100).."\"}]" local l = bh1750.getlux()
--创建一个TCP连接 Create a TCP Connection --定义数据变量格式 Define the veriables formate
socket=net.createConnection(net.TCP, 0) local PostData = "[{\"Name\":\"T\",\"Value\":\"" ..(l / 100).."."..(l % 100).."\"}]"
--域名解析IP地址并赋值 DNS...it --创建一个TCP连接 Create a TCP Connection
socket:dns("www.lewei50.com", function(conn, ip) local socket = net.createConnection(net.TCP, 0)
ServerIP = ip --域名解析IP地址并赋值 DNS...it
print("Connection IP:" .. ServerIP) socket:dns("www.lewei50.com", function(_, ip)
end) ServerIP = ip
print("Connection IP:" .. ServerIP)
--开始连接服务器 Connect the sever end)
socket:connect(80, ServerIP)
socket:on("connection", function(sck) end) --开始连接服务器 Connect the sever
socket:connect(80, ServerIP)
--HTTP请求头定义 HTTP Head socket:on("connection", function() end)
socket:send("POST /api/V1/gateway/UpdateSensors/LW_GATEWAY HTTP/1.1\r\n" ..
"Host: www.lewei50.com\r\n" .. --HTTP请求头定义 HTTP Head
"Content-Length: " .. string.len(PostData) .. "\r\n" .. socket:send("POST /api/V1/gateway/UpdateSensors/LW_GATEWAY HTTP/1.1\r\n" ..
"userkey: USERKEY\r\n\r\n" .. "Host: www.lewei50.com\r\n" ..
PostData .. "\r\n") "Content-Length: " .. string.len(PostData) .. "\r\n" ..
"userkey: USERKEY\r\n\r\n" ..
--HTTP响应内容 Print the HTTP response PostData .. "\r\n")
socket:on("receive", function(sck, response)
print(response) --HTTP响应内容 Print the HTTP response
end) socket:on("receive", function(sck, response) -- luacheck: no unused
end) print(response)
end)
end)
end
t = require("ds18b20") local t = require("ds18b20")
pin = 3 -- gpio0 = 3, gpio2 = 4 local pin = 3 -- gpio0 = 3, gpio2 = 4
local function readout(temp) local function readout(temps)
if t.sens then if t.sens then
print("Total number of DS18B20 sensors: ".. #t.sens) print("Total number of DS18B20 sensors: ".. #t.sens)
for i, s in ipairs(t.sens) do for i, s in ipairs(t.sens) do
print(string.format(" sensor #%d address: %s%s", i, ('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(s:byte(1,8)), s:byte(9) == 1 and " (parasite)" or "")) print(string.format(" sensor #%d address: %s%s", i,
('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(s:byte(1,8)),
s:byte(9) == 1 and " (parasite)" or ""))
end end
end end
for addr, temp in pairs(temp) do
for addr, temp in pairs(temps) do
print(string.format("Sensor %s: %s °C", ('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(addr:byte(1,8)), temp)) print(string.format("Sensor %s: %s °C", ('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(addr:byte(1,8)), temp))
end end
...@@ -17,36 +20,35 @@ local function readout(temp) ...@@ -17,36 +20,35 @@ local function readout(temp)
--package.loaded["ds18b20"]=nil --package.loaded["ds18b20"]=nil
end end
t:enable_debug() do
file.remove("ds18b20_save.lc") -- remove saved addresses t:enable_debug()
print("=============================================", node.heap()) file.remove("ds18b20_save.lc") -- remove saved addresses
print("first call, no addresses in flash, search is performed") print("=============================================", node.heap())
t:read_temp(readout, pin, t.C) print("first call, no addresses in flash, search is performed")
t:read_temp(readout, pin, t.C)
tmr.create():alarm(2000, tmr.ALARM_SINGLE, function() tmr.create():alarm(2000, tmr.ALARM_SINGLE, function()
print("=============================================", node.heap()) print("=============================================", node.heap())
print("second readout, no new search, found addresses are used") print("second readout, no new search, found addresses are used")
t:read_temp(readout, pin) t:read_temp(readout, pin)
tmr.create():alarm(2000, tmr.ALARM_SINGLE, function() tmr.create():alarm(2000, tmr.ALARM_SINGLE, function()
print("=============================================", node.heap()) print("=============================================", node.heap())
print("force search again") print("force search again")
t:read_temp(readout, pin, nil, true) t:read_temp(readout, pin, nil, true)
tmr.create():alarm(2000, tmr.ALARM_SINGLE, function() tmr.create():alarm(2000, tmr.ALARM_SINGLE, function()
print("=============================================", node.heap()) print("=============================================", node.heap())
print("save search results") print("save search results")
t:read_temp(readout, pin, nil, false, true) t:read_temp(readout, pin, nil, false, true)
tmr.create():alarm(2000, tmr.ALARM_SINGLE, function() tmr.create():alarm(2000, tmr.ALARM_SINGLE, function()
print("=============================================", node.heap()) print("=============================================", node.heap())
print("use saved addresses") print("use saved addresses")
t.sens={} t.sens={}
t:read_temp(readout, pin) t:read_temp(readout, pin)
end) end)
end)
end) end)
end)
end) end
end)
t = require('ds18b20') local t = require('ds18b20')
port = 80 local port = 80
pin = 3 -- gpio0 = 3, gpio2 = 4 local pin = 3 -- gpio0 = 3, gpio2 = 4
gconn = {} -- global variable for connection local gconn = {} -- local variable for connection
function readout(temp) local function readout(temps)
local resp = "HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" .. local resp = "HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" ..
"<!DOCTYPE HTML>" .. "<!DOCTYPE HTML>" ..
"<html><body>" .. "<html><body>" ..
"<b>ESP8266</b></br>" "<b>ESP8266</b></br>"
for addr, temp in pairs(temp) do for addr, temp in pairs(temps) do
resp = resp .. string.format("Sensor %s: %s &#8451</br>", ('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X '):format(addr:byte(1,8)), temp) resp = resp .. string.format("Sensor %s: %s &#8451</br>",
('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X '):format(addr:byte(1,8)), temp)
end end
resp = resp .. resp = resp ..
"Node ChipID: " .. node.chipid() .. "<br>" .. "Node ChipID: " .. node.chipid() .. "<br>" ..
"Node MAC: " .. wifi.sta.getmac() .. "<br>" .. "Node MAC: " .. wifi.sta.getmac() .. "<br>" ..
"Node Heap: " .. node.heap() .. "<br>" .. "Node Heap: " .. node.heap() .. "<br>" ..
"Timer Ticks: " .. tmr.now() .. "<br>" .. "Timer Ticks: " .. tmr.now() .. "<br>" ..
"</html></body>" "</html></body>"
gconn:send(resp) gconn:send(resp)
gconn:on("sent",function(conn) conn:close() end) gconn:on("sent",function(conn) conn:close() end)
end end
srv=net.createServer(net.TCP) do
srv:listen(port, local srv = net.createServer(net.TCP)
function(conn) srv:listen(port,
gconn = conn function(conn)
-- t:read_temp(readout) -- default pin value is 3 gconn = conn
t:read_temp(readout, pin) -- t:read_temp(readout) -- default pin value is 3
end t:read_temp(readout, pin)
) end)
end
...@@ -3,23 +3,25 @@ ...@@ -3,23 +3,25 @@
-- NODEMCU TEAM -- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT -- LICENCE: http://opensource.org/licenses/MIT
-- @voborsky, @devsaurus, TerryE 26 Mar 2017 -- @voborsky, @devsaurus, TerryE 26 Mar 2017
---------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------
local modname = ... local modname = ...
-- Used modules and functions -- Used modules and functions
local table, string, ow, tmr, print, type, tostring, pcall, ipairs = local type, tostring, pcall, ipairs =
table, string, ow, tmr, print, type, tostring, pcall, ipairs type, tostring, pcall, ipairs
-- Local functions -- Local functions
local ow_setup, ow_search, ow_select, ow_read, ow_read_bytes, ow_write, ow_crc8, ow_reset, ow_reset_search, ow_skip, ow_depower = local ow_setup, ow_search, ow_select, ow_read, ow_read_bytes, ow_write, ow_crc8,
ow.setup, ow.search, ow.select, ow.read, ow.read_bytes, ow.write, ow.crc8, ow.reset, ow.reset_search, ow.skip, ow.depower ow_reset, ow_reset_search, ow_skip, ow_depower =
ow.setup, ow.search, ow.select, ow.read, ow.read_bytes, ow.write, ow.crc8,
ow.reset, ow.reset_search, ow.skip, ow.depower
local node_task_post, node_task_LOW_PRIORITY = node.task.post, node.task.LOW_PRIORITY local node_task_post, node_task_LOW_PRIORITY = node.task.post, node.task.LOW_PRIORITY
local string_char, string_dump = string.char, string.dump local string_char, string_dump = string.char, string.dump
local now, tmr_create, tmr_ALARM_SINGLE = tmr.now, tmr.create, tmr.ALARM_SINGLE local now, tmr_create, tmr_ALARM_SINGLE = tmr.now, tmr.create, tmr.ALARM_SINGLE
local table_sort, table_concat = table.sort, table.concat local table_sort, table_concat = table.sort, table.concat
local math_floor = math.floor local math_floor = math.floor
local file_open = file.open local file_open = file.open
local conversion
table, string, tmr, ow = nil, nil, nil, nil
local DS18B20FAMILY = 0x28 local DS18B20FAMILY = 0x28
local DS1920FAMILY = 0x10 -- and DS18S20 series local DS1920FAMILY = 0x10 -- and DS18S20 series
...@@ -50,8 +52,6 @@ local function to_string(addr, esc) ...@@ -50,8 +52,6 @@ local function to_string(addr, esc)
end end
end end
local conversion
local function readout(self) local function readout(self)
local next = false local next = false
local sens = self.sens local sens = self.sens
...@@ -62,7 +62,7 @@ local function readout(self) ...@@ -62,7 +62,7 @@ local function readout(self)
local addr = s:sub(1,8) local addr = s:sub(1,8)
ow_select(pin, addr) -- select the sensor ow_select(pin, addr) -- select the sensor
ow_write(pin, READ_SCRATCHPAD, MODE) ow_write(pin, READ_SCRATCHPAD, MODE)
data = ow_read_bytes(pin, 9) local data = ow_read_bytes(pin, 9)
local t=(data:byte(1)+data:byte(2)*256) local t=(data:byte(1)+data:byte(2)*256)
-- t is actually signed so process the sign bit and adjust for fractional bits -- t is actually signed so process the sign bit and adjust for fractional bits
...@@ -116,7 +116,7 @@ local function readout(self) ...@@ -116,7 +116,7 @@ local function readout(self)
end end
end end
conversion = function (self) conversion = (function (self)
local sens = self.sens local sens = self.sens
local powered_only = true local powered_only = true
for _, s in ipairs(sens) do powered_only = powered_only and s:byte(9) ~= 1 end for _, s in ipairs(sens) do powered_only = powered_only and s:byte(9) ~= 1 end
...@@ -125,7 +125,7 @@ conversion = function (self) ...@@ -125,7 +125,7 @@ conversion = function (self)
ow_reset(pin) ow_reset(pin)
ow_skip(pin) -- select the sensor ow_skip(pin) -- select the sensor
ow_write(pin, CONVERT_T, MODE) -- and start conversion ow_write(pin, CONVERT_T, MODE) -- and start conversion
for i, s in ipairs(sens) do status[i] = 1 end for i, _ in ipairs(sens) do status[i] = 1 end
else else
for i, s in ipairs(sens) do for i, s in ipairs(sens) do
if status[i] == 0 then if status[i] == 0 then
...@@ -140,12 +140,11 @@ conversion = function (self) ...@@ -140,12 +140,11 @@ conversion = function (self)
end end
end end
tmr_create():alarm(750, tmr_ALARM_SINGLE, function() return readout(self) end) tmr_create():alarm(750, tmr_ALARM_SINGLE, function() return readout(self) end)
end end)
local function _search(self, lcb, lpin, search, save) local function _search(self, lcb, lpin, search, save)
self.temp = {} self.temp = {}
if search then self.sens = {}; status = {} end if search then self.sens = {}; status = {} end
local temp = self.temp
local sens = self.sens local sens = self.sens
pin = lpin or pin pin = lpin or pin
...@@ -167,7 +166,7 @@ local function _search(self, lcb, lpin, search, save) ...@@ -167,7 +166,7 @@ local function _search(self, lcb, lpin, search, save)
-- search the first device -- search the first device
addr = ow_search(pin) addr = ow_search(pin)
else else
for i, s in ipairs(sens) do status[i] = 0 end for i, _ in ipairs(sens) do status[i] = 0 end
end end
local function cycle() local function cycle()
debugPrint("cycle") debugPrint("cycle")
......
local ds3231 = require("ds3231")
-- ESP-01 GPIO Mapping -- ESP-01 GPIO Mapping
gpio0, gpio2 = 3, 4 local gpio0, gpio2 = 3, 4
i2c.setup(gpio0, gpio2, scl, i2c.SLOW) -- call i2c.setup() only once
require("ds3231") do
i2c.setup(0, gpio0, gpio2, i2c.SLOW) -- call i2c.setup() only once
second, minute, hour, day, date, month, year = ds3231.getTime(); local second, minute, hour, day, date, month, year = ds3231.getTime(); -- luacheck: no unused
-- Get current time -- Get current time
print(string.format("Time & Date: %s:%s:%s %s/%s/%s", hour, minute, second, date, month, year)) print(string.format("Time & Date: %s:%s:%s %s/%s/%s", hour, minute, second, date, month, year))
-- Don't forget to release it after use -- Don't forget to release it after use
ds3231 = nil ds3231 = nil -- luacheck: no unused
package.loaded["ds3231"]=nil package.loaded["ds3231"] = nil
end
\ No newline at end of file
local ds3231 = require('ds3231')
-- ESP-01 GPIO Mapping -- ESP-01 GPIO Mapping
gpio0, gpio2 = 3, 4 local gpio0, gpio2 = 3, 4
i2c.setup(gpio0, gpio2, scl, i2c.SLOW) -- call i2c.setup() only once local port = 80
local days = {
require('ds3231') [1] = "Sunday",
[2] = "Monday",
port = 80 [3] = "Tuesday",
[4] = "Wednesday",
days = { [5] = "Thursday",
[1] = "Sunday", [6] = "Friday",
[2] = "Monday", [7] = "Saturday"
[3] = "Tuesday",
[4] = "Wednesday",
[5] = "Thursday",
[6] = "Friday",
[7] = "Saturday"
} }
months = { local months = {
[1] = "January", [1] = "January",
[2] = "Febuary", [2] = "Febuary",
[3] = "March", [3] = "March",
[4] = "April", [4] = "April",
[5] = "May", [5] = "May",
[6] = "June", [6] = "June",
[7] = "July", [7] = "July",
[8] = "August", [8] = "August",
[9] = "September", [9] = "September",
[10] = "October", [10] = "October",
[11] = "November", [11] = "November",
[12] = "December" [12] = "December"
} }
srv=net.createServer(net.TCP) do
srv:listen(port, i2c.setup(0, gpio0, gpio2, i2c.SLOW) -- call i2c.setup() only once
function(conn)
local srv = net.createServer(net.TCP)
second, minute, hour, day, date, month, year = ds3231.getTime() srv:listen(port, function(conn)
prettyTime = string.format("%s, %s %s %s %s:%s:%s", days[day], date, months[month], year, hour, minute, second) local second, minute, hour, day, date, month, year = ds3231.getTime()
local prettyTime = string.format("%s, %s %s %s %s:%s:%s",
conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" .. days[day], date, months[month], year, hour, minute, second)
"<!DOCTYPE HTML>" ..
"<html><body>" .. conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" ..
"<b>ESP8266</b></br>" .. "<!DOCTYPE HTML>" ..
"Time and Date: " .. prettyTime .. "<br>" .. "<html><body>" ..
"Node ChipID : " .. node.chipid() .. "<br>" .. "<b>ESP8266</b></br>" ..
"Node MAC : " .. wifi.sta.getmac() .. "<br>" .. "Time and Date: " .. prettyTime .. "<br>" ..
"Node Heap : " .. node.heap() .. "<br>" .. "Node ChipID : " .. node.chipid() .. "<br>" ..
"Timer Ticks : " .. tmr.now() .. "<br>" .. "Node MAC : " .. wifi.sta.getmac() .. "<br>" ..
"</html></body>") "Node Heap : " .. node.heap() .. "<br>" ..
conn:on("sent",function(conn) conn:close() end) "Timer Ticks : " .. tmr.now() .. "<br>" ..
end "</html></body>")
)
conn:on("sent",function(sck) sck:close() end)
end)
end
...@@ -114,7 +114,7 @@ function M.reloadAlarms () ...@@ -114,7 +114,7 @@ function M.reloadAlarms ()
i2c.write(id, 0x0F) i2c.write(id, 0x0F)
i2c.write(id, d) i2c.write(id, d)
i2c.stop(id) i2c.stop(id)
print('[LOG] Alarm '..almId..' reloaded') print('[LOG] Alarms reloaded')
end end
-- Enable alarmId bit. Let it to be triggered -- Enable alarmId bit. Let it to be triggered
......
...@@ -22,8 +22,6 @@ _G[moduleName] = M ...@@ -22,8 +22,6 @@ _G[moduleName] = M
local USERNAME = "" local USERNAME = ""
local PASSWORD = "" local PASSWORD = ""
local SERVER = ""
local PORT = ""
local TAG = "" local TAG = ""
local DEBUG = false local DEBUG = false
...@@ -45,10 +43,10 @@ end ...@@ -45,10 +43,10 @@ end
--- ---
-- @name display -- @name display
-- @description A generic IMAP response processing function. -- @description A generic IMAP response processing function.
-- Can disply the IMAP response if DEBUG is set to true. -- Can display the IMAP response if DEBUG is set to true.
-- Sets the reponse processed variable to true when the string "complete" -- Sets the response processed variable to true when the string "complete"
-- is found in the IMAP reply/response -- is found in the IMAP reply/response
local function display(socket, response) local function display(socket, response) -- luacheck: no unused
-- If debuggins is enabled print the IMAP response -- If debuggins is enabled print the IMAP response
if(DEBUG) then if(DEBUG) then
...@@ -67,7 +65,7 @@ end ...@@ -67,7 +65,7 @@ end
--- ---
-- @name config -- @name config
-- @description Initiates the IMAP settings -- @description Initiates the IMAP settings
function M.config(username,password,tag,debug) function M.config(username, password, tag, debug)
USERNAME = username USERNAME = username
PASSWORD = password PASSWORD = password
TAG = tag TAG = tag
...@@ -96,13 +94,13 @@ end ...@@ -96,13 +94,13 @@ end
-- @description Gets the most recent email number from the EXAMINE command. -- @description Gets the most recent email number from the EXAMINE command.
-- i.e. if EXAMINE returns "* 4 EXISTS" this means that there are 4 emails, -- i.e. if EXAMINE returns "* 4 EXISTS" this means that there are 4 emails,
-- so the latest/newest will be identified by the number 4 -- so the latest/newest will be identified by the number 4
local function set_most_recent_num(socket,response) local function set_most_recent_num(socket, response) -- luacheck: no unused
if(DEBUG) then if(DEBUG) then
print(response) print(response)
end end
local _, _, num = string.find(response,"([0-9]+) EXISTS(\.)") -- the _ and _ keep the index of the string found local _, _, num = string.find(response,"([0-9]+) EXISTS") -- the _ and _ keep the index of the string found
-- but we don't care about that. -- but we don't care about that.
if(num~=nil) then if(num~=nil) then
...@@ -117,7 +115,7 @@ end ...@@ -117,7 +115,7 @@ end
--- ---
-- @name examine -- @name examine
-- @description IMAP examines the given mailbox/folder. Sends the IMAP EXAMINE command -- @description IMAP examines the given mailbox/folder. Sends the IMAP EXAMINE command
function M.examine(socket,mailbox) function M.examine(socket, mailbox)
response_processed = false response_processed = false
socket:send(TAG .. " EXAMINE " .. mailbox .. "\r\n") socket:send(TAG .. " EXAMINE " .. mailbox .. "\r\n")
...@@ -135,7 +133,7 @@ end ...@@ -135,7 +133,7 @@ end
-- @name set_header -- @name set_header
-- @description Records the IMAP header field response in a variable -- @description Records the IMAP header field response in a variable
-- so that it may be read later -- so that it may be read later
local function set_header(socket,response) local function set_header(socket, response) -- luacheck: no unused
if(DEBUG) then if(DEBUG) then
print(response) print(response)
end end
...@@ -152,7 +150,7 @@ end ...@@ -152,7 +150,7 @@ end
-- @param socket The IMAP socket to use -- @param socket The IMAP socket to use
-- @param msg_number The email number to read e.g. 1 will read fetch the latest/newest email -- @param msg_number The email number to read e.g. 1 will read fetch the latest/newest email
-- @param field A header field such as SUBJECT, FROM, or DATE -- @param field A header field such as SUBJECT, FROM, or DATE
function M.fetch_header(socket,msg_number,field) function M.fetch_header(socket, msg_number, field)
header = "" -- we are getting a new header so clear this variable header = "" -- we are getting a new header so clear this variable
response_processed = false response_processed = false
socket:send(TAG .. " FETCH " .. msg_number .. " BODY[HEADER.FIELDS (" .. field .. ")]\r\n") socket:send(TAG .. " FETCH " .. msg_number .. " BODY[HEADER.FIELDS (" .. field .. ")]\r\n")
...@@ -171,7 +169,7 @@ end ...@@ -171,7 +169,7 @@ end
-- @name set_body -- @name set_body
-- @description Records the IMAP body response in a variable -- @description Records the IMAP body response in a variable
-- so that it may be read later -- so that it may be read later
local function set_body(socket,response) local function set_body(_, response)
if(DEBUG) then if(DEBUG) then
print(response) print(response)
...@@ -188,7 +186,7 @@ end ...@@ -188,7 +186,7 @@ end
-- @description Sends the IMAP command to fetch a plain text version of the email's body -- @description Sends the IMAP command to fetch a plain text version of the email's body
-- @param socket The IMAP socket to use -- @param socket The IMAP socket to use
-- @param msg_number The email number to obtain e.g. 1 will obtain the latest email -- @param msg_number The email number to obtain e.g. 1 will obtain the latest email
function M.fetch_body_plain_text(socket,msg_number) function M.fetch_body_plain_text(socket, msg_number)
response_processed = false response_processed = false
body = "" -- clear the body variable since we'll be fetching a new email body = "" -- clear the body variable since we'll be fetching a new email
socket:send(TAG .. " FETCH " .. msg_number .. " BODY[1]\r\n") socket:send(TAG .. " FETCH " .. msg_number .. " BODY[1]\r\n")
......
...@@ -11,7 +11,7 @@ local vprint = (verbose > 0) and print or function() end ...@@ -11,7 +11,7 @@ local vprint = (verbose > 0) and print or function() end
-- Mock up enough of the nodemcu tmr structure, but pretend that nothing -- Mock up enough of the nodemcu tmr structure, but pretend that nothing
-- happens between ticks. This won't exercise the optimistic corking logic, -- happens between ticks. This won't exercise the optimistic corking logic,
-- but that's probably fine. -- but that's probably fine.
-- -- luacheck: push ignore
tmr = {} tmr = {}
tmr.ALARM_SINGLE = 0 tmr.ALARM_SINGLE = 0
function tmr.create() function tmr.create()
...@@ -19,6 +19,7 @@ function tmr.create() ...@@ -19,6 +19,7 @@ function tmr.create()
function r:alarm(_i, _t, cb) vprint("TMR") cb() end function r:alarm(_i, _t, cb) vprint("TMR") cb() end
return r return r
end end
-- luacheck: pop
-- --
-- Mock up enough of the nodemcu net.socket type; have it log all the sends -- Mock up enough of the nodemcu net.socket type; have it log all the sends
...@@ -28,7 +29,7 @@ local outs = {} ...@@ -28,7 +29,7 @@ local outs = {}
local fakesock = { local fakesock = {
cb = nil, cb = nil,
on = function(this, _, cb) this.cb = cb end, on = function(this, _, cb) this.cb = cb end,
send = function(this, s) vprint("SEND", (verbose > 1) and s) table.insert(outs, s) end, send = function(this, s) vprint("SEND", (verbose > 1) and s) table.insert(outs, s) end -- luacheck: no unused
} }
local function sent() vprint("SENT") fakesock.cb() end local function sent() vprint("SENT") fakesock.cb() end
...@@ -68,25 +69,25 @@ sent() ; fchecke() ...@@ -68,25 +69,25 @@ sent() ; fchecke()
-- Hit default FSMALLLIM while building up -- Hit default FSMALLLIM while building up
fsendc("abracadabra lots small") fsendc("abracadabra lots small")
for i = 1, 32 do fsend("a") end for i = 1, 32 do fsend("a") end -- luacheck: no unused
nocoal() nocoal()
for i = 1, 4 do fsend("a") end for i = 1, 4 do fsend("a") end -- luacheck: no unused
sent() ; fcheck(string.rep("a", 32)) sent() ; fcheck(string.rep("a", 32))
sent() ; fcheck(string.rep("a", 4)) sent() ; fcheck(string.rep("a", 4))
sent() ; fchecke() sent() ; fchecke()
-- Hit string length while building up -- Hit string length while building up
fsendc("abracadabra overlong") fsendc("abracadabra overlong")
for i = 1, 10 do fsend(string.rep("a",32)) end for i = 1, 10 do fsend(string.rep("a",32)) end -- luacheck: no unused
sent() ; fcheck(string.rep("a", 320)) sent() ; fcheck(string.rep("a", 320))
sent() ; fchecke() sent() ; fchecke()
-- Hit neither before sending a big string -- Hit neither before sending a big string
fsendc("abracadabra mid long") fsendc("abracadabra mid long")
for i = 1, 6 do fsend(string.rep("a",32)) end for i = 1, 6 do fsend(string.rep("a",32)) end -- luacheck: no unused
fsend(string.rep("b", 256)) fsend(string.rep("b", 256))
nocoal() nocoal()
for i = 1, 6 do fsend(string.rep("c",32)) end for i = 1, 6 do fsend(string.rep("c",32)) end -- luacheck: no unused
sent() ; fcheck(string.rep("a", 192) .. string.rep("b", 256)) sent() ; fcheck(string.rep("a", 192) .. string.rep("b", 256))
sent() ; fcheck(string.rep("c", 192)) sent() ; fcheck(string.rep("c", 192))
sent() ; fchecke() sent() ; fchecke()
...@@ -109,33 +110,36 @@ sent() ; fcheck(string.rep("c",512)) ...@@ -109,33 +110,36 @@ sent() ; fcheck(string.rep("c",512))
sent() ; fchecke() sent() ; fchecke()
-- test a lazy generator -- test a lazy generator
local ix = 0 do
local function gen() vprint("GEN", ix); ix = ix + 1; return ("a" .. ix), ix < 3 and gen end local ix = 0
fsend(gen) local function gen() vprint("GEN", ix); ix = ix + 1; return ("a" .. ix), ix < 3 and gen end
fsend("b") fsend(gen)
fcheck("a1") fsend("b")
sent() ; fcheck("a2") fcheck("a1")
sent() ; fcheck("a3") sent() ; fcheck("a2")
sent() ; fcheck("b") sent() ; fcheck("a3")
sent() ; fchecke() sent() ; fcheck("b")
sent() ; fchecke()
end
-- test a completion-like callback that does send text -- test a completion-like callback that does send text
local ix = 0 do
local function gen() vprint("GEN"); ix = 1; return "efgh", nil end local ix = 0
fsend("abcd"); fsend(gen); fsend("ijkl") local function gen() vprint("GEN"); ix = 1; return "efgh", nil end
assert (ix == 0) fsend("abcd"); fsend(gen); fsend("ijkl")
fcheck("abcd"); assert (ix == 0) assert (ix == 0)
sent() ; fcheck("efgh"); assert (ix == 1); ix = 0 fcheck("abcd"); assert (ix == 0)
sent() ; fcheck("ijkl"); assert (ix == 0) sent() ; fcheck("efgh"); assert (ix == 1); ix = 0
sent() ; fchecke() sent() ; fcheck("ijkl"); assert (ix == 0)
sent() ; fchecke()
end
-- and one that doesn't -- and one that doesn't
local ix = 0 do
local function gen() vprint("GEN"); ix = 1; return nil, nil end local ix = 0
fsend("abcd"); fsend(gen); fsend("ijkl") local function gen() vprint("GEN"); ix = 1; return nil, nil end
assert (ix == 0) fsend("abcd"); fsend(gen); fsend("ijkl")
fcheck("abcd"); assert (ix == 0) assert (ix == 0)
sent() ; fcheck("ijkl"); assert (ix == 1); ix = 0 fcheck("abcd"); assert (ix == 0)
sent() ; fchecke() ; assert (ix == 0) sent() ; fcheck("ijkl"); assert (ix == 1); ix = 0
sent() ; fchecke() ; assert (ix == 0)
end
print("All tests OK") print("All tests OK")
...@@ -19,8 +19,8 @@ ...@@ -19,8 +19,8 @@
Note that FTP also exposes a number of really private properties (which Note that FTP also exposes a number of really private properties (which
could be stores in local / upvals) as FTP properties for debug purposes. could be stores in local / upvals) as FTP properties for debug purposes.
]] ]]
local file,net,wifi,node,string,table,tmr,pairs,print,pcall, tostring = local file, net, wifi, node, table, tmr, pairs, print, pcall, tostring =
file,net,wifi,node,string,table,tmr,pairs,print,pcall, tostring file, net, wifi, node, table, tmr, pairs, print, pcall, tostring
local post = node.task.post local post = node.task.post
local FTP, cnt = {client = {}}, 0 local FTP, cnt = {client = {}}, 0
...@@ -90,18 +90,18 @@ function FTP.createServer(user, pass, dbgFlag) -- upval: FTP (, debug, tostring ...@@ -90,18 +90,18 @@ function FTP.createServer(user, pass, dbgFlag) -- upval: FTP (, debug, tostring
-- debug("Sending: %s", rec) -- debug("Sending: %s", rec)
return CNX.cmdSocket:send(rec.."\r\n", cb) return CNX.cmdSocket:send(rec.."\r\n", cb)
end, --- send() end, --- send()
close = function(sock) -- upval: client, CNX (,debug, pcall, type) close = function(socket) -- upval: client, CNX (,debug, pcall, type)
-- debug("Closing CNX.socket=%s, sock=%s", tostring(CNX.socket), tostring(sock)) -- debug("Closing CNX.socket=%s, sock=%s", tostring(CNX.socket), tostring(sock))
for _,s in ipairs{'cmdSocket', 'dataServer', 'dataSocket'} do for _,s in ipairs{'cmdSocket', 'dataServer', 'dataSocket'} do
local sck; sck,CNX[s] = CNX[s], nil local sck; sck,CNX[s] = CNX[s], nil
-- debug("closing CNX.%s=%s", s, tostring(sck)) -- debug("closing CNX.%s=%s", s, tostring(sck))
if type(sck)=='userdata' then pcall(sck.close, sck) end if type(sck)=='userdata' then pcall(sck.close, sck) end
end end
client[sock] = nil client[socket] = nil
end -- CNX.close() end -- CNX.close()
} }
local function validateUser(sock, data) -- upval: CNX, FTP (, debug, processCommand) local function validateUser(socket, data) -- upval: CNX, FTP (, debug, processCommand)
-- validate the logon and if then switch to processing commands -- validate the logon and if then switch to processing commands
-- debug("Authorising: %s", data) -- debug("Authorising: %s", data)
...@@ -118,8 +118,8 @@ function FTP.createServer(user, pass, dbgFlag) -- upval: FTP (, debug, tostring ...@@ -118,8 +118,8 @@ function FTP.createServer(user, pass, dbgFlag) -- upval: FTP (, debug, tostring
elseif CNX.validUser and cmd == 'PASS' then elseif CNX.validUser and cmd == 'PASS' then
if arg == FTP.pass then if arg == FTP.pass then
CNX.cwd = '/' CNX.cwd = '/'
sock:on("receive", function(sock,data) socket:on("receive", function(socketObj, dataObj)
processCommand(CNX,sock,data) processCommand(CNX,socketObj, dataObj)
end) -- logged on so switch to command mode end) -- logged on so switch to command mode
msg = "230 Login successful. Username & password correct; proceed." msg = "230 Login successful. Username & password correct; proceed."
else else
...@@ -134,8 +134,8 @@ function FTP.createServer(user, pass, dbgFlag) -- upval: FTP (, debug, tostring ...@@ -134,8 +134,8 @@ function FTP.createServer(user, pass, dbgFlag) -- upval: FTP (, debug, tostring
return CNX.send(msg) return CNX.send(msg)
end end
local port,ip = sock:getpeer() local port,ip = sock:getpeer() -- luacheck: no unused
-- debug("Connection accepted: (userdata) %s client %s:%u", tostring(sock), ip, port) --debug("Connection accepted: (userdata) %s client %s:%u", tostring(sock), ip, port)
sock:on("receive", validateUser) sock:on("receive", validateUser)
sock:on("disconnection", CNX.close) sock:on("disconnection", CNX.close)
FTP.client[sock]=CNX FTP.client[sock]=CNX
...@@ -177,8 +177,8 @@ end -- FTP.close() ...@@ -177,8 +177,8 @@ end -- FTP.close()
-- --
-- Find strings are used do this lookup and minimise long if chains. -- Find strings are used do this lookup and minimise long if chains.
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
processCommand = function(cxt, sock, data) -- upvals: (, debug, processBareCmds, processSimpleCmds, processDataCmds) -- upvals: (, debug, processBareCmds, processSimpleCmds, processDataCmds)
processCommand = function(cxt, socket, data) -- luacheck: no unused
debug("Command: %s", data) debug("Command: %s", data)
data = data:gsub('[\r\n]+$', '') -- chomp trailing CRLF data = data:gsub('[\r\n]+$', '') -- chomp trailing CRLF
local cmd, arg = data:match('([a-zA-Z]+) *(.*)') local cmd, arg = data:match('([a-zA-Z]+) *(.*)')
...@@ -331,7 +331,7 @@ processDataCmds = function(cxt, cmd, arg) -- upval: FTP (, pairs, file, tostrin ...@@ -331,7 +331,7 @@ processDataCmds = function(cxt, cmd, arg) -- upval: FTP (, pairs, file, tostrin
pattern = arg:gsub('*','[^/%%.]*') pattern = arg:gsub('*','[^/%%.]*')
end end
for k,v in pairs(fileSize) do for k, _ in pairs(fileSize) do
if k:match(pattern) then if k:match(pattern) then
nameList[#nameList+1] = k nameList[#nameList+1] = k
else else
...@@ -341,8 +341,8 @@ processDataCmds = function(cxt, cmd, arg) -- upval: FTP (, pairs, file, tostrin ...@@ -341,8 +341,8 @@ processDataCmds = function(cxt, cmd, arg) -- upval: FTP (, pairs, file, tostrin
table.sort(nameList) table.sort(nameList)
function cxt.getData() -- upval: cmd, fileSize, nameList (, table) function cxt.getData() -- upval: cmd, fileSize, nameList (, table)
local list, user, v = {}, FTP.user local list, user = {}, FTP.user
for i = 1,10 do for i = 1,10 do -- luacheck: no unused
if #nameList == 0 then break end if #nameList == 0 then break end
local f = table.remove(nameList, 1) local f = table.remove(nameList, 1)
list[#list+1] = (cmd == "LIST") and list[#list+1] = (cmd == "LIST") and
...@@ -395,9 +395,9 @@ end -- processDataCmds(cmd, arg, send) ...@@ -395,9 +395,9 @@ end -- processDataCmds(cmd, arg, send)
-- --
---------------- Open a new data server and port --------------------------- ---------------- Open a new data server and port ---------------------------
dataServer = function(cxt, n) -- upval: (pcall, net, ftpDataOpen, debug, tostring) dataServer = function(cxt, n) -- upval: (pcall, net, ftpDataOpen, debug, tostring)
local dataServer = cxt.dataServer local dataSrv = cxt.dataServer
if dataServer then -- close any existing listener if dataSrv then -- close any existing listener
pcall(dataServer.close, dataServer) pcall(dataSrv.close, dataSrv)
end end
if n then if n then
-- Open a new listener if needed. Note that this is only used to establish -- Open a new listener if needed. Note that this is only used to establish
...@@ -425,10 +425,11 @@ ftpDataOpen = function(cxt, dataSocket) -- upval: (debug, tostring, post, pcall) ...@@ -425,10 +425,11 @@ ftpDataOpen = function(cxt, dataSocket) -- upval: (debug, tostring, post, pcall)
cxt.dataServer = nil cxt.dataServer = nil
local function cleardown(skt,type) -- upval: cxt (, debug, tostring, post, pcall) local function cleardown(skt,type) -- upval: cxt (, debug, tostring, post, pcall)
-- luacheck: push no unused
type = type==1 and "disconnection" or "reconnection" type = type==1 and "disconnection" or "reconnection"
local which = cxt.setData and "setData" or (cxt.getData and cxt.getData or "neither") local which = cxt.setData and "setData" or (cxt.getData and cxt.getData or "neither")
-- debug("Cleardown entered from %s with %s", type, which) --debug("Cleardown entered from %s with %s", type, which)
-- luacheck: pop
if cxt.setData then if cxt.setData then
cxt.fileClose() cxt.fileClose()
cxt.setData = nil cxt.setData = nil
...@@ -446,8 +447,9 @@ ftpDataOpen = function(cxt, dataSocket) -- upval: (debug, tostring, post, pcall) ...@@ -446,8 +447,9 @@ ftpDataOpen = function(cxt, dataSocket) -- upval: (debug, tostring, post, pcall)
local on_hold = false local on_hold = false
dataSocket:on("receive", function(skt, rec) --upval: cxt, on_hold (, debug, tstring, post, node, pcall) dataSocket:on("receive", function(skt, rec) --upval: cxt, on_hold (, debug, tstring, post, node, pcall)
local which = cxt.setData and "setData" or (cxt.getData and cxt.getData or "neither")
-- debug("Received %u data bytes with %s", #rec, which) local which = cxt.setData and "setData" or (cxt.getData and cxt.getData or "neither")-- luacheck: no unused
--debug("Received %u data bytes with %s", #rec, which)
if not cxt.setData then return end if not cxt.setData then return end
...@@ -476,7 +478,8 @@ ftpDataOpen = function(cxt, dataSocket) -- upval: (debug, tostring, post, pcall) ...@@ -476,7 +478,8 @@ ftpDataOpen = function(cxt, dataSocket) -- upval: (debug, tostring, post, pcall)
function cxt.sender(skt) -- upval: cxt (, debug) function cxt.sender(skt) -- upval: cxt (, debug)
debug ("entering sender") debug ("entering sender")
if not cxt.getData then return end if not cxt.getData then return end
local rec, skt = cxt.getData(), cxt.dataSocket skt = skt or cxt.dataSocket
local rec = cxt.getData()
if rec and #rec > 0 then if rec and #rec > 0 then
-- debug("Sending %u data bytes", #rec) -- debug("Sending %u data bytes", #rec)
skt:send(rec) skt:send(rec)
......
HDC1000 = require("HDC1000") local HDC1000 = require("HDC1000")
sda = 1 local sda, scl = 1, 2
scl = 2 local drdyn = false
drdyn = false
i2c.setup(0, sda, scl, i2c.SLOW) -- call i2c.setup() only once do
HDC1000.setup(drdyn) i2c.setup(0, sda, scl, i2c.SLOW) -- call i2c.setup() only once
HDC1000.config() -- default values are used if called with no arguments. prototype is config(address, resolution, heater) HDC1000.setup(drdyn)
-- prototype is config(address, resolution, heater)
HDC1000.config() -- default values are used if called with no arguments.
print(string.format("Temperature: %.2f °C\nHumidity: %.2f %%", HDC1000.getTemp(), HDC1000.getHumi())) print(string.format("Temperature: %.2f °C\nHumidity: %.2f %%", HDC1000.getTemp(), HDC1000.getHumi()))
HDC1000 = nil -- Don't forget to release it after use
package.loaded["HDC1000"]=nil HDC1000 = nil -- luacheck: no unused
package.loaded["HDC1000"] = nil
end
\ No newline at end of file
...@@ -40,9 +40,9 @@ local HDC1000_TEMP_HUMI_14BIT = 0x00 ...@@ -40,9 +40,9 @@ local HDC1000_TEMP_HUMI_14BIT = 0x00
local function read16() local function read16()
i2c.start(id) i2c.start(id)
i2c.address(id, HDC1000_ADDR, i2c.RECEIVER) i2c.address(id, HDC1000_ADDR, i2c.RECEIVER)
data_temp = i2c.read(0, 2) local data_temp = i2c.read(0, 2)
i2c.stop(id) i2c.stop(id)
data = bit.lshift(string.byte(data_temp, 1, 1), 8) + string.byte(data_temp, 2, 2) local data = bit.lshift(string.byte(data_temp, 1, 1), 8) + string.byte(data_temp, 2, 2)
return data return data
end end
......
...@@ -8,7 +8,7 @@ require("httpserver").createServer(80, function(req, res) ...@@ -8,7 +8,7 @@ require("httpserver").createServer(80, function(req, res)
-- analyse method and url -- analyse method and url
print("+R", req.method, req.url, node.heap()) print("+R", req.method, req.url, node.heap())
-- setup handler of headers, if any -- setup handler of headers, if any
req.onheader = function(self, name, value) req.onheader = function(self, name, value) -- luacheck: ignore
print("+H", name, value) print("+H", name, value)
-- E.g. look for "content-type" header, -- E.g. look for "content-type" header,
-- setup body parser to particular format -- setup body parser to particular format
...@@ -21,7 +21,7 @@ require("httpserver").createServer(80, function(req, res) ...@@ -21,7 +21,7 @@ require("httpserver").createServer(80, function(req, res)
-- end -- end
end end
-- setup handler of body, if any -- setup handler of body, if any
req.ondata = function(self, chunk) req.ondata = function(self, chunk) -- luacheck: ignore
print("+B", chunk and #chunk, node.heap()) print("+B", chunk and #chunk, node.heap())
if not chunk then if not chunk then
-- reply -- reply
......
...@@ -48,7 +48,7 @@ do ...@@ -48,7 +48,7 @@ do
csend("\r\n") csend("\r\n")
end end
end end
local send_header = function(self, name, value) local send_header = function(self, name, value) -- luacheck: ignore
-- NB: quite a naive implementation -- NB: quite a naive implementation
csend(name) csend(name)
csend(": ") csend(": ")
...@@ -88,13 +88,13 @@ do ...@@ -88,13 +88,13 @@ do
local req, res local req, res
local buf = "" local buf = ""
local method, url local method, url
local ondisconnect = function(conn) local ondisconnect = function(connection)
conn:on("sent", nil) connection.on("sent", nil)
collectgarbage("collect") collectgarbage("collect")
end end
-- header parser -- header parser
local cnt_len = 0 local cnt_len = 0
local onheader = function(conn, k, v) local onheader = function(connection, k, v) -- luacheck: ignore
-- TODO: look for Content-Type: header -- TODO: look for Content-Type: header
-- to help parse body -- to help parse body
-- parse content length to know body length -- parse content length to know body length
...@@ -111,19 +111,19 @@ do ...@@ -111,19 +111,19 @@ do
end end
-- body data handler -- body data handler
local body_len = 0 local body_len = 0
local ondata = function(conn, chunk) local ondata = function(connection, chunk) -- luacheck: ignore
-- feed request data to request handler -- feed request data to request handler
if not req or not req.ondata then return end if not req or not req.ondata then return end
req:ondata(chunk) req:ondata(chunk)
-- NB: once length of seen chunks equals Content-Length: -- NB: once length of seen chunks equals Content-Length:
-- ondata(conn) is called -- ondata(conn) is called
body_len = body_len + #chunk body_len = body_len + #chunk
-- print("-B", #chunk, body_len, cnt_len, node.heap()) -- print("-B", #chunk, body_len, cnt_len, node.heap())
if body_len >= cnt_len then if body_len >= cnt_len then
req:ondata() req:ondata()
end end
end end
local onreceive = function(conn, chunk) local onreceive = function(connection, chunk)
-- merge chunks in buffer -- merge chunks in buffer
if buf then if buf then
buf = buf .. chunk buf = buf .. chunk
...@@ -139,12 +139,12 @@ do ...@@ -139,12 +139,12 @@ do
buf = buf:sub(e + 2) buf = buf:sub(e + 2)
-- method, url? -- method, url?
if not method then if not method then
local i local i, _ -- luacheck: ignore
-- NB: just version 1.1 assumed -- NB: just version 1.1 assumed
_, i, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$") _, i, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$")
if method then if method then
-- make request and response objects -- make request and response objects
req = make_req(conn, method, url) req = make_req(connection, method, url)
res = make_res(csend, cfini) res = make_res(csend, cfini)
end end
-- spawn request handler -- spawn request handler
...@@ -156,17 +156,17 @@ do ...@@ -156,17 +156,17 @@ do
-- header seems ok? -- header seems ok?
if k then if k then
k = k:lower() k = k:lower()
onheader(conn, k, v) onheader(connection, k, v)
end end
-- headers end -- headers end
else else
-- NB: we feed the rest of the buffer as starting chunk of body -- NB: we feed the rest of the buffer as starting chunk of body
ondata(conn, buf) ondata(connection, buf)
-- buffer no longer needed -- buffer no longer needed
buf = nil buf = nil
-- NB: we explicitly reassign receive handler so that -- NB: we explicitly reassign receive handler so that
-- next received chunks go directly to body handler -- next received chunks go directly to body handler
conn:on("receive", ondata) connection:on("receive", ondata)
-- parser done -- parser done
break break
end end
......
...@@ -24,7 +24,6 @@ local address = 0 ...@@ -24,7 +24,6 @@ local address = 0
local function read_reg(reg_addr, len) local function read_reg(reg_addr, len)
local ret={} local ret={}
local c local c
local x
i2c.start(id) i2c.start(id)
i2c.address(id, address ,i2c.TRANSMITTER) i2c.address(id, address ,i2c.TRANSMITTER)
i2c.write(id,reg_addr) i2c.write(id,reg_addr)
...@@ -32,9 +31,9 @@ local function read_reg(reg_addr, len) ...@@ -32,9 +31,9 @@ local function read_reg(reg_addr, len)
i2c.start(id) i2c.start(id)
i2c.address(id, address,i2c.RECEIVER) i2c.address(id, address,i2c.RECEIVER)
c=i2c.read(id,len) c=i2c.read(id,len)
for x=1,len,1 do for x = 1, len, 1 do
tc=string.byte(c,x) local tc = string.byte(c, x)
table.insert(ret,tc) table.insert(ret, tc)
end end
i2c.stop(id) i2c.stop(id)
return ret return ret
...@@ -64,7 +63,7 @@ function M.setup(a) ...@@ -64,7 +63,7 @@ function M.setup(a)
if (a ~= nil) and (a >= 0x48) and (a <= 0x4b ) then if (a ~= nil) and (a >= 0x48) and (a <= 0x4b ) then
address = a address = a
i2c.start(id) i2c.start(id)
res = i2c.address(id, address, i2c.TRANSMITTER) --verify that the address is valid local res = i2c.address(id, address, i2c.TRANSMITTER) --verify that the address is valid
i2c.stop(id) i2c.stop(id)
if (res == false) then if (res == false) then
print("device not found") print("device not found")
......
...@@ -17,6 +17,7 @@ _G[moduleName] = M ...@@ -17,6 +17,7 @@ _G[moduleName] = M
local MCP23008_ADDRESS = 0x20 local MCP23008_ADDRESS = 0x20
-- Registers' address as defined in the MCP23008's datashseet -- Registers' address as defined in the MCP23008's datashseet
-- luacheck: push no unused
local MCP23008_IODIR = 0x00 local MCP23008_IODIR = 0x00
local MCP23008_IPOL = 0x01 local MCP23008_IPOL = 0x01
local MCP23008_GPINTEN = 0x02 local MCP23008_GPINTEN = 0x02
...@@ -28,7 +29,7 @@ local MCP23008_INTF = 0x07 ...@@ -28,7 +29,7 @@ local MCP23008_INTF = 0x07
local MCP23008_INTCAP = 0x08 local MCP23008_INTCAP = 0x08
local MCP23008_GPIO = 0x09 local MCP23008_GPIO = 0x09
local MCP23008_OLAT = 0x0A local MCP23008_OLAT = 0x0A
-- luacheck: pop
-- Default value for i2c communication -- Default value for i2c communication
local id = 0 local id = 0
...@@ -75,8 +76,7 @@ local function read(registerAddress) ...@@ -75,8 +76,7 @@ local function read(registerAddress)
i2c.start(id) i2c.start(id)
-- Read the data form the register -- Read the data form the register
i2c.address(id,MCP23008_ADDRESS,i2c.RECEIVER) -- send the MCP's address and read bit i2c.address(id,MCP23008_ADDRESS,i2c.RECEIVER) -- send the MCP's address and read bit
local data = 0x00 local data = i2c.read(id,1) -- we expect only one byte of data
data = i2c.read(id,1) -- we expect only one byte of data
i2c.stop(id) i2c.stop(id)
return string.byte(data) -- i2c.read returns a string so we convert to it's int value return string.byte(data) -- i2c.read returns a string so we convert to it's int value
......
...@@ -55,7 +55,7 @@ do ...@@ -55,7 +55,7 @@ do
-- FIXME: this suddenly occurs. timeout? -- FIXME: this suddenly occurs. timeout?
--print("-FD") --print("-FD")
end) end)
_fd:on("receive", function(fd, s) _fd:on("receive", function(fd, s) --luacheck: no unused
--print("IN", s) --print("IN", s)
-- TODO: subscription to all channels -- TODO: subscription to all channels
-- lookup message pattern to determine channel and payload -- lookup message pattern to determine channel and payload
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment