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