From 6926c66b1666974f52be9b8e42a8a067fcd7fd19 Mon Sep 17 00:00:00 2001 From: galjonsfigur <44552519+galjonsfigur@users.noreply.github.com> Date: Tue, 31 Dec 2019 00:53:54 +0100 Subject: [PATCH] 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 --- .travis.yml | 4 +- lua_examples/adc_rgb.lua | 64 +++++++------ lua_examples/dcc/dcc.lua | 25 ++--- lua_examples/email/read_email_imap.lua | 55 ++++++----- lua_examples/email/send_email_smtp.lua | 58 ++++++------ lua_examples/irsend.lua | 2 + lua_examples/lfs/HTTP_OTA.lua | 2 +- lua_examples/lfs/_init.lua | 2 +- lua_examples/lfs/dummy_strings.lua | 4 +- lua_examples/lfs/lfs_fragments.lua | 8 +- lua_examples/luaOTA/_doTick.lua | 1 + lua_examples/luaOTA/_provision.lua | 35 +++---- lua_examples/luaOTA/check.lua | 15 ++- lua_examples/luaOTA/default.lua | 3 +- lua_examples/luaOTA/luaOTAserver.lua | 9 +- lua_examples/make_phone_call.lua | 18 ++-- lua_examples/mcp23008/mcp23008_buttons.lua | 20 ++-- lua_examples/mcp23008/mcp23008_leds.lua | 29 +++--- lua_examples/mqtt/mqtt2cloud.lua | 62 +++++++------ lua_examples/mqtt/mqtt_file.lua | 50 +++++----- lua_examples/pcm/play_file.lua | 28 +++--- lua_examples/send_text_message.lua | 18 ++-- lua_examples/sjson-streaming.lua | 23 +++-- lua_examples/somfy.lua | 56 +++++++----- lua_examples/tcp2uart.lua | 32 ++++--- lua_examples/timezone/tz.lua | 5 +- lua_examples/u8g2/graphics_test.lua | 75 +++++++-------- lua_examples/ucglib/GT_box.lua | 1 + lua_examples/ucglib/GT_clip.lua | 1 + lua_examples/ucglib/GT_color_test.lua | 4 +- lua_examples/ucglib/GT_cross.lua | 1 + lua_examples/ucglib/GT_fonts.lua | 1 + lua_examples/ucglib/GT_gradient.lua | 1 + lua_examples/ucglib/GT_graphics_test.lua | 1 + lua_examples/ucglib/GT_pixel_and_lines.lua | 1 + lua_examples/ucglib/GT_text.lua | 1 + lua_examples/ucglib/GT_triangle.lua | 1 + lua_examples/ucglib/GraphicsTest.lua | 62 ++++++------- lua_examples/ucglib/HelloWorld.lua | 28 +++--- lua_examples/ucglib/UcgLogo.lua | 26 +++--- lua_examples/webap_toggle_pin.lua | 12 ++- lua_modules/bh1750/bh1750.lua | 6 +- lua_modules/bh1750/bh1750_Example1.lua | 24 +++-- lua_modules/bh1750/bh1750_Example2.lua | 66 +++++++------- lua_modules/ds18b20/ds18b20-example.lua | 68 +++++++------- lua_modules/ds18b20/ds18b20-web.lua | 48 +++++----- lua_modules/ds18b20/ds18b20.lua | 29 +++--- lua_modules/ds3231/ds3231-example.lua | 20 ++-- lua_modules/ds3231/ds3231-web.lua | 91 +++++++++---------- lua_modules/ds3231/ds3231.lua | 2 +- lua_modules/email/imap.lua | 24 +++-- lua_modules/fifo/fifosocktest.lua | 72 ++++++++------- lua_modules/ftp/ftpserver.lua | 47 +++++----- lua_modules/hdc1000/HDC1000-example.lua | 23 +++-- lua_modules/hdc1000/HDC1000.lua | 4 +- lua_modules/http/http-example.lua | 4 +- lua_modules/http/httpserver.lua | 24 ++--- lua_modules/lm92/lm92.lua | 9 +- lua_modules/mcp23008/mcp23008.lua | 6 +- lua_modules/redis/redis.lua | 2 +- .../yeelink/Example_for_Yeelink_Lib.lua | 6 +- lua_modules/yeelink/yeelink_lib.lua | 34 ++++--- tools/luacheck_config.lua | 46 +++++++++- tools/luacheck_config_helper.lua | 6 ++ tools/travis/run-luacheck-linux.sh | 72 +++++++++++++++ tools/travis/run-luacheck-windows.sh | 13 +++ tools/travis/run-luacheck.sh | 17 ---- 67 files changed, 897 insertions(+), 710 deletions(-) create mode 100755 tools/travis/run-luacheck-linux.sh create mode 100644 tools/travis/run-luacheck-windows.sh delete mode 100644 tools/travis/run-luacheck.sh diff --git a/.travis.yml b/.travis.yml index 7994a097..6a4f2ae7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,7 @@ addons: packages: - python-serial - srecord + - luarocks cache: - directories: - cache @@ -33,4 +34,5 @@ script: - echo "checking:" - find lua_modules lua_examples -iname "*.lua" -print0 | xargs -0 echo - find lua_modules lua_examples -iname "*.lua" -print0 | xargs -0 $LUACC -p -# - if [ "$OS" = "linux" ]; then bash "$TRAVIS_BUILD_DIR"/tools/travis/run-luacheck.sh || true ; fi +- if [ "$OS" = "linux" ]; then bash "$TRAVIS_BUILD_DIR"/tools/travis/run-luacheck-linux.sh; fi +- if [ "$OS" = "windows" ]; then bash "$TRAVIS_BUILD_DIR"/tools/travis/run-luacheck-windows.sh; fi diff --git a/lua_examples/adc_rgb.lua b/lua_examples/adc_rgb.lua index 6b094ced..9da9d805 100644 --- a/lua_examples/adc_rgb.lua +++ b/lua_examples/adc_rgb.lua @@ -1,43 +1,47 @@ -- --- Light sensor on ADC(0), RGB LED connected to gpio12(6) Green, gpio13(7) Blue & gpio15(8) Red. +-- Light sensor on adc0(A0), RGB LED connected to gpio12(D6) Green, gpio13(D7) Blue & gpio15(D8) Red. -- This works out of the box on the typical ESP8266 evaluation boards with Battery Holder -- -- It uses the input from the sensor to drive a "rainbow" effect on the RGB LED -- Includes a very "pseudoSin" function -- +-- Required C Modules: adc, tmr, pwm -function led(r,Sg,b) - pwm.setduty(8,r) - pwm.setduty(6,g) - pwm.setduty(7,b) +local redLed, greenLed, blueLed = 8, 6, 7 + +local function setRGB(r,g,b) + pwm.setduty(redLed, r) + pwm.setduty(greenLed, g) + pwm.setduty(blueLed, b) end --- this is perhaps the lightest weight sin function in existance --- Given an integer from 0..128, 0..512 appximating 256 + 256 * sin(idx*Pi/256) +-- this is perhaps the lightest weight sin function in existence +-- Given an integer from 0..128, 0..512 approximating 256 + 256 * sin(idx*Pi/256) -- This is first order square approximation of sin, it's accurate around 0 and any multiple of 128 (Pi/2), --- 92% accurate at 64 (Pi/4). -function pseudoSin (idx) - idx = idx % 128 - lookUp = 32 - idx % 64 - val = 256 - (lookUp * lookUp) / 4 - if (idx > 64) then - val = - val; - end - return 256+val +-- 92% accurate at 64 (Pi/4). +local function pseudoSin(idx) + idx = idx % 128 + local lookUp = 32 - idx % 64 + local val = 256 - (lookUp * lookUp) / 4 + if (idx > 64) then + val = - val; + end + return 256+val end -pwm.setup(6,500,512) -pwm.setup(7,500,512) -pwm.setup(8,500,512) -pwm.start(6) -pwm.start(7) -pwm.start(8) +do + pwm.setup(redLed, 500, 512) + pwm.setup(greenLed,500, 512) + pwm.setup(blueLed, 500, 512) + pwm.start(redLed) + pwm.start(greenLed) + pwm.start(blueLed) -tmr.alarm(1,20,1,function() - idx = 3 * adc.read(0) / 2 - r = pseudoSin(idx) - g = pseudoSin(idx + 43) - b = pseudoSin(idx + 85) - led(r,g,b) - idx = (idx + 1) % 128 - end) + tmr.create():alarm(20, tmr.ALARM_AUTO, function() + local idx = 3 * adc.read(0) / 2 + local r = pseudoSin(idx) + local g = pseudoSin(idx + 43) -- ~1/3rd of 128 + local b = pseudoSin(idx + 85) -- ~2/3rd of 128 + setRGB(r,g,b) + end) +end diff --git a/lua_examples/dcc/dcc.lua b/lua_examples/dcc/dcc.lua index 922b89d3..33cf1d17 100644 --- a/lua_examples/dcc/dcc.lua +++ b/lua_examples/dcc/dcc.lua @@ -4,7 +4,7 @@ local PIN = 2 -- GPIO4 local addr = 0x12a -CV = {[29]=0, +local CV = {[29]=0, [1]=bit.band(addr, 0x3f), --CV_ACCESSORY_DECODER_ADDRESS_LSB (6 bits) [9]=bit.band(bit.rshift(addr,6), 0x7) --CV_ACCESSORY_DECODER_ADDRESS_MSB (3 bits) } @@ -37,18 +37,18 @@ end local function DCC_command(cmd, params) if not is_new(cmd, params) then return end - if cmd == dcc.DCC_IDLE then + if cmd == dcc.DCC_IDLE then return elseif cmd == dcc.DCC_TURNOUT then - print("Turnout command") + print("Turnout command") elseif cmd == dcc.DCC_SPEED then - print("Speed command") + print("Speed command") elseif cmd == dcc.DCC_FUNC then - print("Function command") + print("Function command") else print("Other command", cmd) end - + for i,j in pairs(params) do print(i, j) end @@ -69,18 +69,21 @@ local function CV_callback(operation, param) elseif operation == dcc.CV_VALID then oper = "Valid" result = 1 - elseif operation == CV_RESET then + elseif operation == dcc.CV_RESET then oper = "Reset" CV = {} end - print(("[CV_callback] %s CV %d%s"):format(oper, param.CV, param.Value and "\tValue: "..param.Value or "\tValue: nil")) + print(("[CV_callback] %s CV %d%s") + :format(oper, param.CV, param.Value and "\tValue: "..param.Value or "\tValue: nil")) return result end dcc.setup(PIN, DCC_command, - dcc.MAN_ID_DIY, 1, - --bit.bor(dcc.FLAGS_AUTO_FACTORY_DEFAULT, dcc.FLAGS_DCC_ACCESSORY_DECODER, dcc.FLAGS_MY_ADDRESS_ONLY), -- Accessories (turnouts) decoder - bit.bor(dcc.FLAGS_AUTO_FACTORY_DEFAULT), -- Cab (train) decoder + dcc.MAN_ID_DIY, 1, + -- Accessories (turnouts) decoder: + --bit.bor(dcc.FLAGS_AUTO_FACTORY_DEFAULT, dcc.FLAGS_DCC_ACCESSORY_DECODER, dcc.FLAGS_MY_ADDRESS_ONLY), + -- Cab (train) decoder + bit.bor(dcc.FLAGS_AUTO_FACTORY_DEFAULT), 0, -- ??? CV_callback) diff --git a/lua_examples/email/read_email_imap.lua b/lua_examples/email/read_email_imap.lua index 0729b66f..97fa7b77 100644 --- a/lua_examples/email/read_email_imap.lua +++ b/lua_examples/email/read_email_imap.lua @@ -6,7 +6,7 @@ -- was tested with an AOL and Time Warner cable email accounts (GMail and other services who do -- not support no SSL access will not work). -require("imap") +local imap = require("imap") local IMAP_USERNAME = "email@domain.com" local IMAP_PASSWORD = "password" @@ -25,21 +25,13 @@ local SSID_PASSWORD = "password" local count = 0 -- we will send several IMAP commands/requests, this variable helps keep track of which one to send - --- configure the ESP8266 as a station -wifi.setmode(wifi.STATION) -wifi.sta.config(SSID,SSID_PASSWORD) -wifi.sta.autoconnect(1) - --- create an unencrypted connection -local imap_socket = net.createConnection(net.TCP,0) - +local imap_socket, timer --- -- @name setup -- @description A call back function used to begin reading email -- upon sucessfull connection to the IMAP server -function setup(sck) +local function setup(sck) -- Set the email user name and password, IMAP tag, and if debugging output is needed imap.config(IMAP_USERNAME, IMAP_PASSWORD, @@ -49,19 +41,16 @@ function setup(sck) imap.login(sck) end -imap_socket:on("connection",setup) -- call setup() upon connection -imap_socket:connect(IMAP_PORT,IMAP_SERVER) -- connect to the IMAP server - local subject = "" local from = "" -local message = "" +local body = "" --- -- @name do_next -- @description A call back function for a timer alarm used to check if the previous -- IMAP command reply has been processed. If the IMAP reply has been processed -- this function will call the next IMAP command function necessary to read the email -function do_next() +local function do_next() -- Check if the IMAP reply was processed if(imap.response_processed() == true) then @@ -75,15 +64,18 @@ function do_next() count = count + 1 elseif (count == 1) then -- After examining/selecting the INBOX folder we can begin to retrieve emails. - imap.fetch_header(imap_socket,imap.get_most_recent_num(),"SUBJECT") -- Retrieve the SUBJECT of the first/newest email + -- Retrieve the SUBJECT of the first/newest email + imap.fetch_header(imap_socket,imap.get_most_recent_num(),"SUBJECT") count = count + 1 elseif (count == 2) then subject = imap.get_header() -- store the SUBJECT response in subject - imap.fetch_header(imap_socket,imap.get_most_recent_num(),"FROM") -- Retrieve the FROM of the first/newest email + -- Retrieve the FROM of the first/newest email + imap.fetch_header(imap_socket,imap.get_most_recent_num(),"FROM") count = count + 1 elseif (count == 3) then from = imap.get_header() -- store the FROM response in from - imap.fetch_body_plain_text(imap_socket,imap.get_most_recent_num()) -- Retrieve the BODY of the first/newest email + -- Retrieve the BODY of the first/newest email + imap.fetch_body_plain_text(imap_socket,imap.get_most_recent_num()) count = count + 1 elseif (count == 4) then body = imap.get_body() -- store the BODY response in body @@ -92,9 +84,9 @@ function do_next() else -- display the email contents - -- create patterns to strip away IMAP protocl text from actual message - pattern1 = "(\*.+\}\r\n)" -- to remove "* n command (BODY[n] {n}" - pattern2 = "(%)\r\n.+)" -- to remove ") t1 OK command completed" + -- create patterns to strip away IMAP protocol text from actual message + local pattern1 = "%*.*}\n" -- to remove "* n command (BODY[n] {n}" + local pattern2 = "%)\n.+" -- to remove ") t1 OK command completed" from = string.gsub(from,pattern1,"") from = string.gsub(from,pattern2,"") @@ -108,7 +100,7 @@ function do_next() body = string.gsub(body,pattern2,"") print("Message: " .. body) - tmr.stop(0) -- Stop the timer alarm + timer:stop() -- Stop the timer alarm imap_socket:close() -- close the IMAP socket collectgarbage() -- clean up end @@ -116,5 +108,18 @@ function do_next() end --- A timer alarm is sued to check if an IMAP reply has been processed -tmr.alarm(0,1000,1, do_next) +do + -- configure the ESP8266 as a station + wifi.setmode(wifi.STATION) + wifi.sta.config(SSID,SSID_PASSWORD) + wifi.sta.autoconnect(1) + + -- create an unencrypted connection + imap_socket = net.createConnection(net.TCP,0) + imap_socket:on("connection",setup) -- call setup() upon connection + imap_socket:connect(IMAP_PORT,IMAP_SERVER) -- connect to the IMAP server + + -- A timer alarm is sued to check if an IMAP reply has been processed + timer = tmr.create() + timer:alarm(1000, tmr.ALARM_AUTO, do_next) +end diff --git a/lua_examples/email/send_email_smtp.lua b/lua_examples/email/send_email_smtp.lua index 4ba6585e..b11e1928 100644 --- a/lua_examples/email/send_email_smtp.lua +++ b/lua_examples/email/send_email_smtp.lua @@ -1,16 +1,17 @@ --- -- Working Example: https://www.youtube.com/watch?v=CcRbFIJ8aeU --- @description a basic SMTP email example. You must use an account which can provide unencrypted authenticated access. --- This example was tested with an AOL and Time Warner email accounts. GMail does not offer unecrypted authenticated access. +-- @description a basic SMTP email example. You must use an account which can +-- provide unencrypted authenticated access. +-- This example was tested with an AOL and Time Warner email accounts. +-- GMail does not offer unencrypted authenticated access. -- To obtain your email's SMTP server and port simply Google it e.g. [my email domain] SMTP settings --- For example for timewarner you'll get to this page http://www.timewarnercable.com/en/support/faqs/faqs-internet/e-mailacco/incoming-outgoing-server-addresses.html +-- For example for timewarner you'll get to this page +-- http://www.timewarnercable.com/en/support/faqs/faqs-internet/e-mailacco/incoming-outgoing-server-addresses.html -- To Learn more about SMTP email visit: -- SMTP Commands Reference - http://www.samlogic.net/articles/smtp-commands-reference.htm -- See "SMTP transport example" in this page http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol -- @author Miguel -require("base64") - -- The email and password from the account you want to send emails from local MY_EMAIL = "esp8266@domain.com" local EMAIL_PASSWORD = "123456" @@ -37,18 +38,18 @@ wifi.sta.autoconnect(1) local email_subject = "" local email_body = "" local count = 0 - +local timer local smtp_socket = nil -- will be used as socket to email server -- The display() function will be used to print the SMTP server's response -function display(sck,response) +local function display(sck, response) -- luacheck: no unused print(response) end -- The do_next() function is used to send the SMTP commands to the SMTP server in the required sequence. -- I was going to use socket callbacks but the code would not run callbacks after the first 3. -function do_next() +local function do_next() if(count == 0)then count = count+1 local IP_ADDRESS = wifi.sta.getip() @@ -58,10 +59,10 @@ function do_next() smtp_socket:send("AUTH LOGIN\r\n") elseif(count == 2) then count = count + 1 - smtp_socket:send(base64.enc(MY_EMAIL).."\r\n") + smtp_socket:send(encoder.toBase64(MY_EMAIL).."\r\n") elseif(count == 3) then count = count + 1 - smtp_socket:send(base64.enc(EMAIL_PASSWORD).."\r\n") + smtp_socket:send(encoder.toBase64(EMAIL_PASSWORD).."\r\n") elseif(count==4) then count = count+1 smtp_socket:send("MAIL FROM:<" .. MY_EMAIL .. ">\r\n") @@ -82,26 +83,27 @@ function do_next() smtp_socket:send(message.."\r\n.\r\n") elseif(count==8) then count = count+1 - tmr.stop(0) + timer:stop() smtp_socket:send("QUIT\r\n") else smtp_socket:close() end end --- The connectted() function is executed when the SMTP socket is connected to the SMTP server. +-- The connected() function is executed when the SMTP socket is connected to the SMTP server. -- This function will create a timer to call the do_next function which will send the SMTP commands -- in sequence, one by one, every 5000 seconds. -- You can change the time to be smaller if that works for you, I used 5000ms just because. -function connected(sck) - tmr.alarm(0,5000,1,do_next) +local function connected() + timer = tmr.create() + timer:alarm(5000, tmr.ALARM_AUTO, do_next) end -- @name send_email -- @description Will initiated a socket connection to the SMTP server and trigger the connected() function -- @param subject The email's subject -- @param body The email's body -function send_email(subject,body) +local function send_email(subject,body) count = 0 email_subject = subject email_body = body @@ -111,19 +113,13 @@ function send_email(subject,body) smtp_socket:connect(SMTP_PORT,SMTP_SERVER) end --- Send an email -send_email( - "ESP8266", -[[Hi, -How are your IoT projects coming along? -Best Wishes, -ESP8266]]) - - - - - - - - - +do + -- Send an email + send_email( + "ESP8266", + [[Hi, + How are your IoT projects coming along? + Best Wishes, + ESP8266]] + ) +end diff --git a/lua_examples/irsend.lua b/lua_examples/irsend.lua index ed1cb98b..dd3aec40 100644 --- a/lua_examples/irsend.lua +++ b/lua_examples/irsend.lua @@ -10,6 +10,7 @@ local M do -- const + -- luacheck: push no unused local NEC_PULSE_US = 1000000 / 38000 local NEC_HDR_MARK = 9000 local NEC_HDR_SPACE = 4500 @@ -17,6 +18,7 @@ do local NEC_ONE_SPACE = 1600 local NEC_ZERO_SPACE = 560 local NEC_RPT_SPACE = 2250 + -- luacheck: pop -- cache local gpio, bit = gpio, bit local mode, write = gpio.mode, gpio.write diff --git a/lua_examples/lfs/HTTP_OTA.lua b/lua_examples/lfs/HTTP_OTA.lua index 42472de5..513771b3 100644 --- a/lua_examples/lfs/HTTP_OTA.lua +++ b/lua_examples/lfs/HTTP_OTA.lua @@ -10,7 +10,7 @@ local host, dir, image = ... local doRequest, firstRec, subsRec, finalise local n, total, size = 0, 0 -doRequest = function(sk,hostIP) +doRequest = function(socket, hostIP) -- luacheck: no unused if hostIP then local con = net.createConnection(net.TCP,0) con:connect(80,hostIP) diff --git a/lua_examples/lfs/_init.lua b/lua_examples/lfs/_init.lua index 0060811e..d3ad4fa5 100644 --- a/lua_examples/lfs/_init.lua +++ b/lua_examples/lfs/_init.lua @@ -46,7 +46,7 @@ local lfs_t = { end end, - __newindex = function(_, name, value) + __newindex = function(_, name, value) -- luacheck: no unused error("LFS is readonly. Invalid write to LFS." .. name, 2) end, diff --git a/lua_examples/lfs/dummy_strings.lua b/lua_examples/lfs/dummy_strings.lua index cee2eaaf..f644d734 100644 --- a/lua_examples/lfs/dummy_strings.lua +++ b/lua_examples/lfs/dummy_strings.lua @@ -24,8 +24,10 @@ end This will exclude any strings already in the ROM table, so the output is the list of putative strings that you should consider adding to LFS ROM table. ----------------------------------------------------------------------------------]] +--------------------------------------------------------------------------------- +]]-- +-- luacheck: ignore local preload = "?.lc;?.lua", "/\n;\n?\n!\n-", "@init.lua", "_G", "_LOADED", "_LOADLIB", "__add", "__call", "__concat", "__div", "__eq", "__gc", "__index", "__le", "__len", "__lt", "__mod", "__mode", "__mul", "__newindex", "__pow", diff --git a/lua_examples/lfs/lfs_fragments.lua b/lua_examples/lfs/lfs_fragments.lua index c5e53e06..47ccb834 100644 --- a/lua_examples/lfs/lfs_fragments.lua +++ b/lua_examples/lfs/lfs_fragments.lua @@ -5,8 +5,8 @@ -- then enter the following commands interactively through the UART: -- do - local _,ma,fa=node.flashindex() - for n,v in pairs{LFS_MAPPED=ma, LFS_BASE=fa, SPIFFS_BASE=sa} do + local sa, ma, fa = node.flashindex() + for n,v in pairs{LFS_MAPPED = ma, LFS_BASE = fa, SPIFFS_BASE = sa} do print(('export %s=""0x%x"'):format(n, v)) end end @@ -60,7 +60,5 @@ local initTimer = tmr.create() initTimer:register(1000, tmr.ALARM_SINGLE, function() local fi=node.flashindex; return pcall(fi and fi'_init') - end - ) + end) initTimer:start() - diff --git a/lua_examples/luaOTA/_doTick.lua b/lua_examples/luaOTA/_doTick.lua index e8a7238f..979cb003 100644 --- a/lua_examples/luaOTA/_doTick.lua +++ b/lua_examples/luaOTA/_doTick.lua @@ -1,3 +1,4 @@ +-- luacheck: globals self if (self.timer) then self.timer:stop() end--SAFETRIM -- function _doTick(self) diff --git a/lua_examples/luaOTA/_provision.lua b/lua_examples/luaOTA/_provision.lua index 3b69fcae..7eaceb27 100644 --- a/lua_examples/luaOTA/_provision.lua +++ b/lua_examples/luaOTA/_provision.lua @@ -2,7 +2,7 @@ -- function _provision(self,socket,first_rec) local self, socket, first_rec = ... -local crypto, file, json, node, table = crypto, file, sjson, node, table +local crypto, file, json, node, table = crypto, file, sjson, node, table local stripdebug, gc = node.stripdebug, collectgarbage local buf = {} @@ -13,11 +13,10 @@ local function getbuf() -- upval: buf, table end -- Process a provisioning request record -local function receiveRec(socket, rec) -- upval: self, buf, crypto - -- Note that for 2nd and subsequent responses, we assme that the service has - -- "authenticated" itself, so any protocol errors are fatal and lkely to +local function receiveRec(sck, rec) -- upval: self, buf, crypto + -- Note that for 2nd and subsequent responses, we assume that the service has + -- "authenticated" itself, so any protocol errors are fatal and likely to -- cause a repeating boot, throw any protocol errors are thrown. - local config, file, log = self.config, file, self.log local cmdlen = (rec:find('\n',1, true) or 0) - 1 local cmd,hash = rec:sub(1,cmdlen-6), rec:sub(cmdlen-5,cmdlen) if cmdlen < 16 or @@ -25,7 +24,9 @@ local function receiveRec(socket, rec) -- upval: self, buf, crypto return error("Invalid command signature") end - local s; s, cmd = pcall(json.decode, cmd) + local s + s, cmd = pcall(json.decode, cmd) + if not s then error("JSON decode error") end local action,resp = cmd.a, {s = "OK"} local chunk @@ -59,15 +60,15 @@ local function receiveRec(socket, rec) -- upval: self, buf, crypto if not msg then gc(); gc() local code, name = string.dump(lcf), cmd.name:sub(1,-5) .. ".lc" - local s = file.open(name, "w+") - if s then + local f = file.open(name, "w+") + if f then for i = 1, #code, 1024 do - s = s and file.write(code:sub(i, ((i+1023)>#code) and i+1023 or #code)) + f = f and file.write(code:sub(i, ((i+1023)>#code) and i+1023 or #code)) end file.close() - if not s then file.remove(name) end + if not f then file.remove(name) end end - if s then + if f then resp.lcsize=#code print("Updated ".. name) else @@ -80,15 +81,15 @@ local function receiveRec(socket, rec) -- upval: self, buf, crypto buf = {} elseif action == "dl" then - local s = file.open(cmd.name, "w+") - if s then + local dlFile = file.open(cmd.name, "w+") + if dlFile then for i = 1, #buf do - s = s and file.write(buf[i]) + dlFile = dlFile and file.write(buf[i]) end file.close() end - if s then + if dlFile then print("Updated ".. cmd.name) else file.remove(cmd.name) @@ -109,13 +110,13 @@ local function receiveRec(socket, rec) -- upval: self, buf, crypto file.open(self.prefix.."config.json", "w+") file.writeline(json.encode(cmd)) file.close() - socket:close() + sck:close() print("Restarting to load new application") node.restart() -- reboot just schedules a restart return end end - self.socket_send(socket, resp, chunk) + self.socket_send(sck, resp, chunk) gc() end diff --git a/lua_examples/luaOTA/check.lua b/lua_examples/luaOTA/check.lua index 46dcd273..e869adf3 100644 --- a/lua_examples/luaOTA/check.lua +++ b/lua_examples/luaOTA/check.lua @@ -9,14 +9,13 @@ -------------------------------------------------------------------------------- -- upvals -local crypto, file, json, net, node, table, wifi = - crypto, file, sjson, net, node, table, wifi -local error, pcall = error, pcall +local crypto, json, node, wifi = + crypto, sjson, node, wifi +local error = error local loadfile, gc = loadfile, collectgarbage -local concat, unpack = table.concat, unpack or table.unpack local self = {post = node.task.post, prefix = "luaOTA/", conf = {}} - +-- luacheck: globals DEBUG self.log = (DEBUG == true) and print or function() end self.modname = ... self.timer = tmr.create() @@ -27,15 +26,15 @@ end -------------------------------------------------------------------------------------- -- Utility Functions -setmetatable( self, {__index=function(self, func) --upval: loadfile +setmetatable( self, {__index=function(obj, func) --upval: loadfile -- The only __index calls in in LuaOTA are dynamically loaded functions. -- The convention is that functions starting with "_" are treated as -- call-once / ephemeral; the rest are registered in self - func = self.prefix .. func + func = obj.prefix .. func local f,msg = loadfile( func..".lc") if msg then f, msg = loadfile(func..".lua") end if msg then error (msg,2) end - if func:sub(8,8) ~= "_" then self[func] = f end + if func:sub(8,8) ~= "_" then obj[func] = f end return f end} ) diff --git a/lua_examples/luaOTA/default.lua b/lua_examples/luaOTA/default.lua index bfbaad79..fa059e98 100644 --- a/lua_examples/luaOTA/default.lua +++ b/lua_examples/luaOTA/default.lua @@ -1,5 +1,4 @@ --- -local function enum(t,log) for k,v in pairs(t)do log(k,v) end end +-- luacheck: globals DEBUG return {entry = function(msg) package.loaded["luaOTA.default"]=nil local gc=collectgarbage; gc(); gc() diff --git a/lua_examples/luaOTA/luaOTAserver.lua b/lua_examples/luaOTA/luaOTAserver.lua index b1e07a9f..5356e295 100644 --- a/lua_examples/luaOTA/luaOTAserver.lua +++ b/lua_examples/luaOTA/luaOTAserver.lua @@ -17,6 +17,8 @@ ]] +-- luacheck: std max + local socket = require "socket" local lfs = require "lfs" local md5 = require "md5" @@ -31,7 +33,6 @@ local receive_and_parse -- function(esp) local provision -- function(esp, config, files, inventory, fingerprint) local read_file -- function(fname) local save_file -- function(fname, data) -local compress_lua -- function(lua_file) local hmac -- function(data) -- Function-wide locals (can be upvalues) @@ -164,6 +165,7 @@ receive_and_parse = function(esp) local packed_cmd, sig = line:sub(1,#line-6),line:sub(-6) -- print("reply:", packed_cmd, sig) local status, cmd = pcall(json.decode, packed_cmd) + if not status then error("JSON decode error") end if not hmac or hmac(packed_cmd):sub(-6) == sig then if cmd and cmd.data == "number" then local data = esp:receive(cmd.data) @@ -183,7 +185,7 @@ provision = function(esp, config, inventory, fingerprint) local name, size, mtime, content = f.name, f.size, f.mtime, f.content if not cf[name] or cf[name] ~= mtime then -- Send the file - local func, action, cmd, buf + local action, cmd, buf if f.name:sub(-4) == ".lua" then assert(load(content, f.name)) -- check that the contents can compile if content:find("--SAFETRIM\n",1,true) then @@ -241,12 +243,11 @@ end -- Save contents to the given file ---------------------------------- -save_file = function(fname, data) +save_file = function(fname, data) -- luacheck: ignore local file = io.open(fname, "wb") file:write(data) file:close() end - -------------------------------------------------------------------------------------- main() -- now that all functions have been bound to locals, we can start the show :-) diff --git a/lua_examples/make_phone_call.lua b/lua_examples/make_phone_call.lua index 27058b6b..d5501a0e 100644 --- a/lua_examples/make_phone_call.lua +++ b/lua_examples/make_phone_call.lua @@ -29,10 +29,12 @@ local TWILIO_ACCOUNT_SID = "xxxxxx" local TWILIO_TOKEN = "xxxxxx" local HOST = "iot-https-relay.appspot.com" -- visit http://iot-https-relay.appspot.com/ to learn more about this service - -- Please be sure to understand the security issues of using this relay app and use at your own risk. +-- Please be sure to understand the security issues of using this relay app and use at your own risk. local URI = "/twilio/Calls.json" -function build_post_request(host, uri, data_table) +local wifiTimer = tmr.create() + +local function build_post_request(host, uri, data_table) local data = "" @@ -40,7 +42,7 @@ function build_post_request(host, uri, data_table) data = data .. param.."="..value.."&" end - request = "POST "..uri.." HTTP/1.1\r\n".. + local request = "POST "..uri.." HTTP/1.1\r\n".. "Host: "..host.."\r\n".. "Connection: close\r\n".. "Content-Type: application/x-www-form-urlencoded\r\n".. @@ -53,7 +55,7 @@ function build_post_request(host, uri, data_table) return request end -local function display(sck,response) +local function display(socket, response) -- luacheck: no unused print(response) end @@ -69,7 +71,7 @@ local function make_call(from,to,body) To = to } - socket = net.createConnection(net.TCP,0) + local socket = net.createConnection(net.TCP,0) socket:on("receive",display) socket:connect(80,HOST) @@ -80,13 +82,13 @@ local function make_call(from,to,body) end) end -function check_wifi() +local function check_wifi() local ip = wifi.sta.getip() if(ip==nil) then print("Connecting...") else - tmr.stop(0) + wifiTimer:stop() print("Connected to AP!") print(ip) -- make a call with a voice message "your house is on fire" @@ -95,4 +97,4 @@ function check_wifi() end -tmr.alarm(0,2000,1,check_wifi) +wifiTimer:alarm(2000, tmr.ALARM_AUTO, check_wifi) diff --git a/lua_examples/mcp23008/mcp23008_buttons.lua b/lua_examples/mcp23008/mcp23008_buttons.lua index 1a71c155..585a4fa6 100644 --- a/lua_examples/mcp23008/mcp23008_buttons.lua +++ b/lua_examples/mcp23008/mcp23008_buttons.lua @@ -14,23 +14,17 @@ -- Website: http://AllAboutEE.com --------------------------------------------------------------------------------------------- -require ("mcp23008") +local mcp23008 = require ("mcp23008") -- ESP-01 GPIO Mapping as per GPIO Table in https://github.com/nodemcu/nodemcu-firmware -gpio0, gpio2 = 3, 4 - --- Setup the MCP23008 -mcp23008.begin(0x0,gpio2,gpio0,i2c.SLOW) - -mcp23008.writeIODIR(0xff) -mcp23008.writeGPPU(0xff) +local gpio0, gpio2 = 3, 4 --- -- @name showButtons -- @description Shows the state of each GPIO pin -- @return void --------------------------------------------------------- -function showButtons() +local function showButtons() local gpio = mcp23008.readGPIO() -- read the GPIO/buttons states @@ -51,7 +45,13 @@ function showButtons() print("\r\n") end -tmr.alarm(0,2000,1,showButtons) -- run showButtons() every 2 seconds +do + -- Setup the MCP23008 + mcp23008.begin(0x0,gpio2,gpio0,i2c.SLOW) + mcp23008.writeIODIR(0xff) + mcp23008.writeGPPU(0xff) + tmr.create():alarm(2000, tmr.ALARM_AUTO, showButtons) -- run showButtons() every 2 seconds +end diff --git a/lua_examples/mcp23008/mcp23008_leds.lua b/lua_examples/mcp23008/mcp23008_leds.lua index 4f9b6463..e1e06331 100644 --- a/lua_examples/mcp23008/mcp23008_leds.lua +++ b/lua_examples/mcp23008/mcp23008_leds.lua @@ -13,26 +13,17 @@ -- Website: http://AllAboutEE.com --------------------------------------------------------------------------------------------- -require ("mcp23008") +local mcp23008 = require ("mcp23008") -- ESP-01 GPIO Mapping as per GPIO Table in https://github.com/nodemcu/nodemcu-firmware -gpio0, gpio2 = 3, 4 - --- Setup MCP23008 -mcp23008.begin(0x0,gpio2,gpio0,i2c.SLOW) - -mcp23008.writeIODIR(0x00) -- make all GPIO pins as outputs -mcp23008.writeGPIO(0x00) -- make all GIPO pins off/low +local gpio0, gpio2 = 3, 4 --- -- @name count() -- @description Reads the value from the GPIO register, increases the read value by 1 -- and writes it back so the LEDs will display a binary count up to 255 or 0xFF in hex. local function count() - - local gpio = 0x00 - - gpio = mcp23008.readGPIO() + local gpio = mcp23008.readGPIO() if(gpio<0xff) then mcp23008.writeGPIO(gpio+1) @@ -41,5 +32,15 @@ local function count() end end --- Run count() every 100ms -tmr.alarm(0,100,1,count) + +do + -- Setup MCP23008 + mcp23008.begin(0x0,gpio2,gpio0,i2c.SLOW) + + mcp23008.writeIODIR(0x00) -- make all GPIO pins as outputs + mcp23008.writeGPIO(0x00) -- make all GIPO pins off/low + + -- Run count() every 100ms + tmr.create():alarm(100, tmr.ALARM_AUTO, count) +end + diff --git a/lua_examples/mqtt/mqtt2cloud.lua b/lua_examples/mqtt/mqtt2cloud.lua index a64e970a..753601d3 100644 --- a/lua_examples/mqtt/mqtt2cloud.lua +++ b/lua_examples/mqtt/mqtt2cloud.lua @@ -1,33 +1,41 @@ -- test with cloudmqtt.com -m_dis={} -function dispatch(m,t,pl) - if pl~=nil and m_dis[t] then - m_dis[t](m,pl) - end +local m_dis = {} + +local function dispatch(m,t,pl) + if pl~=nil and m_dis[t] then + m_dis[t](m,pl) + end end -function topic1func(m,pl) - print("get1: "..pl) + +local function topic1func(_,pl) + print("get1: "..pl) end -function topic2func(m,pl) - print("get2: "..pl) + +local function topic2func(_,pl) + print("get2: "..pl) end -m_dis["/topic1"]=topic1func -m_dis["/topic2"]=topic2func --- Lua: mqtt.Client(clientid, keepalive, user, pass) -m=mqtt.Client("nodemcu1",60,"test","test123") -m:on("connect",function(m) - print("connection "..node.heap()) - m:subscribe("/topic1",0,function(m) print("sub done") end) - m:subscribe("/topic2",0,function(m) print("sub done") end) - m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0) - end ) -m:on("offline", function(conn) + +do + m_dis["/topic1"] = topic1func + m_dis["/topic2"] = topic2func + -- Lua: mqtt.Client(clientid, keepalive, user, pass) + local m = mqtt.Client("nodemcu1", 60, "test", "test123") + m:on("connect",function(client) + print("connection "..node.heap()) + client:subscribe("/topic1",0,function() print("sub done") end) + client:subscribe("/topic2",0,function() print("sub done") end) + client:publish("/topic1","hello",0,0) + client:publish("/topic2","world",0,0) + end) + m:on("offline", function() print("disconnect to broker...") print(node.heap()) -end) -m:on("message",dispatch ) --- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) ) -m:connect("m11.cloudmqtt.com",11214,0,1) -tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time() - m:publish("/topic1",pl,0,0) - end) + end) + m:on("message",dispatch ) + -- Lua: mqtt:connect( host, port, secure, function(client) ) + m:connect("m11.cloudmqtt.com",11214,0) + tmr.create():alarm(10000, tmr.ALARM_AUTO, function() + local pl = "time: "..tmr.time() + m:publish("/topic1",pl,0,0) + end) +end \ No newline at end of file diff --git a/lua_examples/mqtt/mqtt_file.lua b/lua_examples/mqtt/mqtt_file.lua index d5285850..ed5d71d9 100644 --- a/lua_examples/mqtt/mqtt_file.lua +++ b/lua_examples/mqtt/mqtt_file.lua @@ -1,22 +1,23 @@ -- test transfer files over mqtt. -m_dis={} -function dispatch(m,t,pl) - if pl~=nil and m_dis[t] then +local m_dis = {} + +local function dispatch(m, t, pl) + if pl ~= nil and m_dis[t] then m_dis[t](m,pl) end end -function pubfile(m,filename) +local function pubfile(m,filename) file.close() file.open(filename) repeat - local pl=file.read(1024) - if pl then m:publish("/topic2",pl,0,0) end - until not pl - file.close() + local pl = file.read(1024) + if pl then m:publish("/topic2", pl, 0, 0) end + until not pl + file.close() end -- payload(json): {"cmd":xxx,"content":xxx} -function topic1func(m,pl) +local function topic1func(m,pl) print("get1: "..pl) local pack = sjson.decode(pl) if pack.content then @@ -30,21 +31,22 @@ function topic1func(m,pl) end end -m_dis["/topic1"]=topic1func --- Lua: mqtt.Client(clientid, keepalive, user, pass) -m=mqtt.Client() -m:on("connect",function(m) - print("connection "..node.heap()) - m:subscribe("/topic1",0,function(m) print("sub done") end) - end ) -m:on("offline", function(conn) - print("disconnect to broker...") - print(node.heap()) -end) -m:on("message",dispatch ) --- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) ) -m:connect("192.168.18.88",1883,0,1) - +do + m_dis["/topic1"]=topic1func + -- Lua: mqtt.Client(clientid, keepalive, user, pass) + local m = mqtt.Client() + m:on("connect",function(client) + print("connection "..node.heap()) + client:subscribe("/topic1", 0, function() print("sub done") end) + end) + m:on("offline", function() + print("disconnect to broker...") + print(node.heap()) + end) + m:on("message",dispatch ) + -- Lua: mqtt:connect( host, port, secure, function(client) ) + m:connect("192.168.18.88",1883,0) +end -- usage: -- another client(pc) subscribe to /topic2, will receive the test.lua content. -- and publish below message to /topic1 diff --git a/lua_examples/pcm/play_file.lua b/lua_examples/pcm/play_file.lua index d3ceefdc..3a5f8594 100644 --- a/lua_examples/pcm/play_file.lua +++ b/lua_examples/pcm/play_file.lua @@ -6,7 +6,7 @@ -- **************************************************************************** -function cb_drained(d) +local function cb_drained() print("drained "..node.heap()) file.seek("set", 0) @@ -14,27 +14,29 @@ function cb_drained(d) --d:play(pcm.RATE_8K) end -function cb_stopped(d) +local function cb_stopped() print("playback stopped") file.seek("set", 0) end -function cb_paused(d) +local function cb_paused() print("playback paused") end -file.open("jump_8k.u8", "r") +do + file.open("jump_8k.u8", "r") -drv = pcm.new(pcm.SD, 1) + local drv = pcm.new(pcm.SD, 1) --- fetch data in chunks of FILE_READ_CHUNK (1024) from file -drv:on("data", function(drv) return file.read() end) + -- fetch data in chunks of FILE_READ_CHUNK (1024) from file + drv:on("data", function(driver) return file.read() end) -- luacheck: no unused --- get called back when all samples were read from the file -drv:on("drained", cb_drained) + -- get called back when all samples were read from the file + drv:on("drained", cb_drained) -drv:on("stopped", cb_stopped) -drv:on("paused", cb_paused) + drv:on("stopped", cb_stopped) + drv:on("paused", cb_paused) --- start playback -drv:play(pcm.RATE_8K) + -- start playback + drv:play(pcm.RATE_8K) +end diff --git a/lua_examples/send_text_message.lua b/lua_examples/send_text_message.lua index c454e0ca..45d8b8d5 100644 --- a/lua_examples/send_text_message.lua +++ b/lua_examples/send_text_message.lua @@ -29,10 +29,12 @@ local TWILIO_ACCOUNT_SID = "xxxxxx" local TWILIO_TOKEN = "xxxxxx" local HOST = "iot-https-relay.appspot.com" -- visit http://iot-https-relay.appspot.com/ to learn more about this service - -- Please be sure to understand the security issues of using this relay app and use at your own risk. +-- Please be sure to understand the security issues of using this relay app and use at your own risk. local URI = "/twilio/Messages.json" -function build_post_request(host, uri, data_table) +local wifiTimer = tmr.create() + +local function build_post_request(host, uri, data_table) local data = "" @@ -40,7 +42,7 @@ function build_post_request(host, uri, data_table) data = data .. param.."="..value.."&" end - request = "POST "..uri.." HTTP/1.1\r\n".. + local request = "POST "..uri.." HTTP/1.1\r\n".. "Host: "..host.."\r\n".. "Connection: close\r\n".. "Content-Type: application/x-www-form-urlencoded\r\n".. @@ -53,7 +55,7 @@ function build_post_request(host, uri, data_table) return request end -local function display(sck,response) +local function display(socket, response) -- luacheck: no unused print(response) end @@ -69,7 +71,7 @@ local function send_sms(from,to,body) To = to } - socket = net.createConnection(net.TCP,0) + local socket = net.createConnection(net.TCP,0) socket:on("receive",display) socket:connect(80,HOST) @@ -80,13 +82,13 @@ local function send_sms(from,to,body) end) end -function check_wifi() +local function check_wifi() local ip = wifi.sta.getip() if(ip==nil) then print("Connecting...") else - tmr.stop(0) + wifiTimer.stop() print("Connected to AP!") print(ip) -- send a text message with the text "Hello from your esp8266" @@ -95,4 +97,4 @@ function check_wifi() end -tmr.alarm(0,7000,1,check_wifi) +wifiTimer.alarm(7000, tmr.ALARM_AUTO, check_wifi) diff --git a/lua_examples/sjson-streaming.lua b/lua_examples/sjson-streaming.lua index d7981c5f..c92d2a73 100644 --- a/lua_examples/sjson-streaming.lua +++ b/lua_examples/sjson-streaming.lua @@ -1,11 +1,18 @@ -- Test sjson and GitHub API local s = tls.createConnection() -s:on("connection", function(sck, c) - sck:send("GET /repos/nodemcu/nodemcu-firmware/git/trees/master HTTP/1.0\r\nUser-agent: nodemcu/0.1\r\nHost: api.github.com\r\nConnection: close\r\nAccept: application/json\r\n\r\n") +s:on("connection", function(sck) + sck:send( +[[GET /repos/nodemcu/nodemcu-firmware/git/trees/master HTTP/1.0 +User-agent: nodemcu/0.1 +Host: api.github.com +Connection: close +Accept: application/json + +]]) end) -function startswith(String, Start) +local function startswith(String, Start) return string.sub(String, 1, string.len(Start)) == Start end @@ -23,13 +30,13 @@ local decoder = sjson.decoder({ end } }) -local function handledata(s) - decoder:write(s) +local function handledata(sck) + decoder:write(sck) end -- The receive callback is somewhat gnarly as it has to deal with find the end of the header -- and having the newline sequence split across packets -s:on("receive", function(sck, c) +s:on("receive", function(socket, c) -- luacheck: no unused if partial then c = partial .. c partial = nil @@ -45,8 +52,8 @@ s:on("receive", function(sck, c) handledata(c) return end - local s, e = c:find("\r\n") - if s then + local str, e = c:find("\r\n") + if str then -- Throw away line c = c:sub(e + 1) else diff --git a/lua_examples/somfy.lua b/lua_examples/somfy.lua index a6755306..8f594235 100644 --- a/lua_examples/somfy.lua +++ b/lua_examples/somfy.lua @@ -1,17 +1,20 @@ -- Somfy module example (beside somfy module requires also SJSON module) --- The rolling code number is stored in the file somfy.cfg. A cached write of the somfy.cfg file is implemented in order to reduce the number of write to the EEPROM memory. Together with the logic of the file module it should allow long lasting operation. +-- The rolling code number is stored in the file somfy.cfg. +-- A cached write of the somfy.cfg file is implemented in order to reduce +-- the number of write to the EEPROM memory. Together with the logic of the +-- file module it should allow long lasting operation. -config_file = "somfy." +local config_file = "somfy." +local config, config_saved -- somfy.cfg looks like -- {"window1":{"rc":1,"address":123},"window2":{"rc":1,"address":124}} local tmr_cache = tmr.create() local tmr_delay = tmr.create() -pin = 4 -gpio.mode(pin, gpio.OUTPUT, gpio.PULLUP) +local pin = 4 -function deepcopy(orig) +local function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then @@ -26,8 +29,8 @@ function deepcopy(orig) return copy end -function readconfig() - local cfg, ok, ln +local function readconfig() + local ln if file.exists(config_file.."cfg") then print("Reading config from "..config_file.."cfg") file.open(config_file.."cfg", "r+") @@ -47,7 +50,7 @@ function readconfig() config_saved = deepcopy(config) end -function writeconfighard() +local function writeconfighard() print("Saving config") file.remove(config_file.."bak") file.rename(config_file.."cfg", config_file.."bak") @@ -63,8 +66,8 @@ function writeconfighard() config_saved = deepcopy(config) end -function writeconfig() - tmr.stop(tmr_cache) +local function writeconfig() + tmr_cache:stop() local savenow = false local savelater = false @@ -87,12 +90,18 @@ function writeconfig() end if savelater then print("Saving config later") - tmr.alarm(tmr_cache, 65000, tmr.ALARM_SINGLE, writeconfighard) + tmr_cache:alarm(65000, tmr.ALARM_SINGLE, writeconfighard) end end --======================================================================================================-- -function down(remote, cb, par) +local function wait(ms, cb, par) + par = par or {} + print("wait: ".. ms) + if cb then tmr_delay:alarm(ms, tmr.ALARM_SINGLE, function () cb(unpack(par)) end) end +end + +local function down(remote, cb, par) par = par or {} print("down: ".. remote) config[remote].rc=config[remote].rc+1 @@ -100,7 +109,7 @@ function down(remote, cb, par) writeconfig() end -function up(remote, cb, par) +local function up(remote, cb, par) par = par or {} print("up: ".. remote) config[remote].rc=config[remote].rc+1 @@ -108,7 +117,7 @@ function up(remote, cb, par) writeconfig() end -function downStep(remote, cb, par) +local function downStep(remote, cb, par) par = par or {} print("downStep: ".. remote) config[remote].rc=config[remote].rc+1 @@ -116,7 +125,7 @@ function downStep(remote, cb, par) writeconfig() end -function upStep(remote, cb, par) +local function upStep(remote, cb, par) -- luacheck: ignore par = par or {} print("upStep: ".. remote) config[remote].rc=config[remote].rc+1 @@ -124,14 +133,9 @@ function upStep(remote, cb, par) writeconfig() end -function wait(ms, cb, par) - par = par or {} - print("wait: ".. ms) - if cb then tmr.alarm(tmr_delay, ms, tmr.ALARM_SINGLE, function () cb(unpack(par)) end) end -end - - --======================================================================================================-- +gpio.mode(pin, gpio.OUTPUT, gpio.PULLUP) + if not config then readconfig() end if #config == 0 then -- somfy.cfg does not exist config = sjson.decode([[{"window1":{"rc":1,"address":123},"window2":{"rc":1,"address":124}}]]) @@ -141,5 +145,11 @@ down('window1', wait, {60000, up, {'window1', wait, {9000, - downStep, {'window1', downStep, {'window1', downStep, {'window1', downStep, {'window1', downStep, {'window1', downStep, {'window1', downStep, {'window1' + downStep, {'window1', + downStep, {'window1', + downStep, {'window1', + downStep, {'window1', + downStep, {'window1', + downStep, {'window1', + downStep, {'window1' }}}}}}}}}}) diff --git a/lua_examples/tcp2uart.lua b/lua_examples/tcp2uart.lua index 638a2d77..db38371e 100644 --- a/lua_examples/tcp2uart.lua +++ b/lua_examples/tcp2uart.lua @@ -1,16 +1,18 @@ -uart.setup(0,9600,8,0,1,0) -sv=net.createServer(net.TCP, 60) -global_c = nil -sv:listen(9999, function(c) - if global_c~=nil then - global_c:close() - end - global_c=c - c:on("receive",function(sck,pl) uart.write(0,pl) end) -end) +do + uart.setup(0, 9600, 8, 0, 1, 0) + local sv = net.createServer(net.TCP, 60) + local global_c = nil + sv:listen(9999, function(c) + if global_c~=nil then + global_c:close() + end + global_c = c + c:on("receive",function(_, pl) uart.write(0, pl) end) + end) -uart.on("data",4, function(data) - if global_c~=nil then - global_c:send(data) - end -end, 0) + uart.on("data", 4, function(data) + if global_c ~= nil then + global_c:send(data) + end + end, 0) +end diff --git a/lua_examples/timezone/tz.lua b/lua_examples/timezone/tz.lua index 8cc6cc5e..05d4641d 100644 --- a/lua_examples/timezone/tz.lua +++ b/lua_examples/timezone/tz.lua @@ -27,7 +27,7 @@ function M.getzones() return result end -function load(t) +local function load(t) local z = file.open(thezone .. ".zone", "r") local hdr = z:read(20) @@ -35,7 +35,8 @@ function load(t) if magic == "TZif" then local lens = z:read(24) - local ttisgmt_count, ttisdstcnt, leapcnt, timecnt, typecnt, charcnt = struct.unpack("> LLLLLL", lens) + local ttisgmt_count, ttisdstcnt, leapcnt, timecnt, typecnt, charcnt -- luacheck: no unused + = struct.unpack("> LLLLLL", lens) local times = z:read(4 * timecnt) local typeindex = z:read(timecnt) diff --git a/lua_examples/u8g2/graphics_test.lua b/lua_examples/u8g2/graphics_test.lua index 7287c0ed..42145306 100644 --- a/lua_examples/u8g2/graphics_test.lua +++ b/lua_examples/u8g2/graphics_test.lua @@ -9,8 +9,13 @@ -- -- *************************************************************************** +-- display object +local disp + +local draw_state, loop_tmr = 0, tmr.create() + -- setup I2c and connect display -function init_i2c_display() +local function init_i2c_display() -- SDA and SCL can be assigned freely to available GPIOs local sda = 5 -- GPIO14 local scl = 6 -- GPIO12 @@ -18,9 +23,8 @@ function init_i2c_display() i2c.setup(0, sda, scl, i2c.SLOW) disp = u8g2.ssd1306_i2c_128x64_noname(0, sla) end - -- setup SPI and connect display -function init_spi_display() +local function init_spi_display() -- luacheck: no unused -- Hardware SPI CLK = GPIO14 -- Hardware SPI MOSI = GPIO13 -- Hardware SPI MISO = GPIO12 (not used) @@ -37,8 +41,7 @@ function init_spi_display() disp = u8g2.ssd1306_128x64_noname(1, cs, dc, res) end - -function u8g2_prepare() +local function u8g2_prepare() disp:setFont(u8g2.font_6x10_tf) disp:setFontRefHeightExtendedText() disp:setDrawColor(1) @@ -47,7 +50,7 @@ function u8g2_prepare() end -function u8g2_box_frame(a) +local function u8g2_box_frame(a) disp:drawStr( 0, 0, "drawBox") disp:drawBox(5,10,20,10) disp:drawBox(10+a,15,30,7) @@ -56,7 +59,7 @@ function u8g2_box_frame(a) disp:drawFrame(10+a,15+30,30,7) end -function u8g2_disc_circle(a) +local function u8g2_disc_circle(a) disp:drawStr( 0, 0, "drawDisc") disp:drawDisc(10,18,9) disp:drawDisc(24+a,16,7) @@ -65,13 +68,13 @@ function u8g2_disc_circle(a) disp:drawCircle(24+a,16+30,7) end -function u8g2_r_frame(a) +local function u8g2_r_frame(a) disp:drawStr( 0, 0, "drawRFrame/Box") disp:drawRFrame(5, 10,40,30, a+1) disp:drawRBox(50, 10,25,40, a+1) end -function u8g2_string(a) +local function u8g2_string(a) disp:setFontDirection(0) disp:drawStr(30+a,31, " 0") disp:setFontDirection(1) @@ -82,7 +85,7 @@ function u8g2_string(a) disp:drawStr(30,31-a, " 270") end -function u8g2_line(a) +local function u8g2_line(a) disp:drawStr( 0, 0, "drawLine") disp:drawLine(7+a, 10, 40, 55) disp:drawLine(7+a*2, 10, 60, 55) @@ -90,7 +93,7 @@ function u8g2_line(a) disp:drawLine(7+a*4, 10, 100, 55) end -function u8g2_triangle(a) +local function u8g2_triangle(a) local offset = a disp:drawStr( 0, 0, "drawTriangle") disp:drawTriangle(14,7, 45,30, 10,40) @@ -99,7 +102,7 @@ function u8g2_triangle(a) disp:drawTriangle(10+offset,40+offset, 45+offset,30+offset, 86+offset,53+offset) end -function u8g2_ascii_1() +local function u8g2_ascii_1() disp:drawStr( 0, 0, "ASCII page 1") for y = 0, 5 do for x = 0, 15 do @@ -108,7 +111,7 @@ function u8g2_ascii_1() end end -function u8g2_ascii_2() +local function u8g2_ascii_2() disp:drawStr( 0, 0, "ASCII page 2") for y = 0, 5 do for x = 0, 15 do @@ -117,7 +120,7 @@ function u8g2_ascii_2() end end -function u8g2_extra_page(a) +local function u8g2_extra_page(a) disp:drawStr( 0, 0, "Unicode") disp:setFont(u8g2.font_unifont_t_symbols) disp:setFontPosTop() @@ -129,9 +132,9 @@ function u8g2_extra_page(a) end end -cross_width = 24 -cross_height = 24 -cross_bits = string.char( +local cross_width = 24 +local cross_height = 24 +local cross_bits = string.char( 0x00, 0x18, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x81, 0x00, 0x00, 0x81, 0x00, 0xC0, 0x00, 0x03, 0x38, 0x3C, 0x1C, 0x06, 0x42, 0x60, 0x01, 0x42, 0x80, @@ -139,24 +142,25 @@ cross_bits = string.char( 0x00, 0x81, 0x00, 0x00, 0x81, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x18, 0x00) -cross_fill_width = 24 -cross_fill_height = 24 -cross_fill_bits = string.char( +-- luacheck: push no unused +local cross_fill_width = 24 +local cross_fill_height = 24 +local cross_fill_bits = string.char( 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x64, 0x00, 0x26, 0x84, 0x00, 0x21, 0x08, 0x81, 0x10, 0x08, 0x42, 0x10, 0x10, 0x3C, 0x08, 0x20, 0x00, 0x04, 0x40, 0x00, 0x02, 0x80, 0x00, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x80, 0x00, 0x01, 0x40, 0x00, 0x02, 0x20, 0x00, 0x04, 0x10, 0x3C, 0x08, 0x08, 0x42, 0x10, 0x08, 0x81, 0x10, 0x84, 0x00, 0x21, 0x64, 0x00, 0x26, 0x18, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) - -cross_block_width = 14 -cross_block_height = 14 -cross_block_bits = string.char( +-- luacheck: pop +local cross_block_width = 14 +local cross_block_height = 14 +local cross_block_bits = string.char( 0xFF, 0x3F, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0xC1, 0x20, 0xC1, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0xFF, 0x3F) -function u8g2_bitmap_overlay(a) +local function u8g2_bitmap_overlay(a) local frame_size = 28 disp:drawStr(0, 0, "Bitmap overlay") @@ -177,7 +181,7 @@ function u8g2_bitmap_overlay(a) end end -function u8g2_bitmap_modes(transparent) +local function u8g2_bitmap_modes(transparent) local frame_size = 24 disp:drawBox(0, frame_size * 0.5, frame_size * 5, frame_size) @@ -201,7 +205,7 @@ function u8g2_bitmap_modes(transparent) end -function draw() +local function draw() u8g2_prepare() local d3 = bit.rshift(draw_state, 3) @@ -235,7 +239,7 @@ function draw() end -function loop() +local function loop() -- picture loop disp:clearBuffer() draw() @@ -251,13 +255,12 @@ function loop() loop_tmr:start() end +do + loop_tmr:register(100, tmr.ALARM_SEMI, loop) -draw_state = 0 -loop_tmr = tmr.create() -loop_tmr:register(100, tmr.ALARM_SEMI, loop) + init_i2c_display() + --init_spi_display() -init_i2c_display() ---init_spi_display() - -print("--- Starting Graphics Test ---") -loop_tmr:start() + print("--- Starting Graphics Test ---") + loop_tmr:start() +end diff --git a/lua_examples/ucglib/GT_box.lua b/lua_examples/ucglib/GT_box.lua index b21323f8..4b68c394 100644 --- a/lua_examples/ucglib/GT_box.lua +++ b/lua_examples/ucglib/GT_box.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GT_clip.lua b/lua_examples/ucglib/GT_clip.lua index bf3d9b4d..8348177d 100644 --- a/lua_examples/ucglib/GT_clip.lua +++ b/lua_examples/ucglib/GT_clip.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GT_color_test.lua b/lua_examples/ucglib/GT_color_test.lua index 0b619498..e8cd84d7 100644 --- a/lua_examples/ucglib/GT_color_test.lua +++ b/lua_examples/ucglib/GT_color_test.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M @@ -7,10 +8,7 @@ function M.run() print("Running component color_test...") - local mx local c, x - mx = disp:getWidth() / 2 - --my = disp:getHeight() / 2 disp:setColor(0, 0, 0, 0) disp:drawBox(0, 0, disp:getWidth(), disp:getHeight()) diff --git a/lua_examples/ucglib/GT_cross.lua b/lua_examples/ucglib/GT_cross.lua index e4cc3e2d..502d1d12 100644 --- a/lua_examples/ucglib/GT_cross.lua +++ b/lua_examples/ucglib/GT_cross.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GT_fonts.lua b/lua_examples/ucglib/GT_fonts.lua index 3990f317..b885806f 100644 --- a/lua_examples/ucglib/GT_fonts.lua +++ b/lua_examples/ucglib/GT_fonts.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GT_gradient.lua b/lua_examples/ucglib/GT_gradient.lua index e432cba6..33b6f8ab 100644 --- a/lua_examples/ucglib/GT_gradient.lua +++ b/lua_examples/ucglib/GT_gradient.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GT_graphics_test.lua b/lua_examples/ucglib/GT_graphics_test.lua index 4db6800b..ba840cf3 100644 --- a/lua_examples/ucglib/GT_graphics_test.lua +++ b/lua_examples/ucglib/GT_graphics_test.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GT_pixel_and_lines.lua b/lua_examples/ucglib/GT_pixel_and_lines.lua index 03d65c17..5b4b7a25 100644 --- a/lua_examples/ucglib/GT_pixel_and_lines.lua +++ b/lua_examples/ucglib/GT_pixel_and_lines.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GT_text.lua b/lua_examples/ucglib/GT_text.lua index 8a99d8df..60aed1b8 100644 --- a/lua_examples/ucglib/GT_text.lua +++ b/lua_examples/ucglib/GT_text.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GT_triangle.lua b/lua_examples/ucglib/GT_triangle.lua index d2e8ab88..0ed188e9 100644 --- a/lua_examples/ucglib/GT_triangle.lua +++ b/lua_examples/ucglib/GT_triangle.lua @@ -1,3 +1,4 @@ +-- luacheck: globals T r disp millis lcg_rnd local M, module = {}, ... _G[module] = M diff --git a/lua_examples/ucglib/GraphicsTest.lua b/lua_examples/ucglib/GraphicsTest.lua index b5bcf153..8cc3879f 100644 --- a/lua_examples/ucglib/GraphicsTest.lua +++ b/lua_examples/ucglib/GraphicsTest.lua @@ -1,5 +1,23 @@ +-- luacheck: new globals z T r disp lcg_rnd millis +z = 127 -- start value +T = 1000 +r = 0 +disp = nil + +local loop_idx = 0 + +function lcg_rnd() + z = bit.band(65 * z + 17, 255) + return z +end + +function millis() + local usec = tmr.now() + return usec/1000 +end + -- setup SPI and connect display -function init_spi_display() +local function init_spi_display() -- Hardware SPI CLK = GPIO14 -- Hardware SPI MOSI = GPIO13 -- Hardware SPI MISO = GPIO12 (not used) @@ -20,11 +38,8 @@ function init_spi_display() disp = ucg.st7735_18x128x160_hw_spi(bus, cs, dc, res) end - - - -- switch statement http://lua-users.org/wiki/SwitchStatement -function switch(c) +local function switch(c) local swtbl = { casevar = c, caseof = function (self, code) @@ -46,20 +61,7 @@ function switch(c) return swtbl end - -z = 127 -- start value -function lcg_rnd() - z = bit.band(65 * z + 17, 255) - return z -end - - -function millis() - local usec = tmr.now() - return usec/1000 -end - -function set_clip_range() +local function set_clip_range() local x, y, w, h w = bit.band(lcg_rnd(), 31) h = bit.band(lcg_rnd(), 31) @@ -71,7 +73,7 @@ function set_clip_range() disp:setClipRange(x, y, w, h) end -function loop() +local function loop() if (loop_idx == 0) then switch(bit.band(r, 3)) : caseof { @@ -112,18 +114,12 @@ function loop() print("Heap: " .. node.heap()) end +do + init_spi_display() -T = 1000 + disp:begin(ucg.FONT_MODE_TRANSPARENT) + disp:setFont(ucg.font_ncenR14_hr) + disp:clearScreen() -r = 0 -loop_idx = 0 - -init_spi_display() - -disp:begin(ucg.FONT_MODE_TRANSPARENT) -disp:setFont(ucg.font_ncenR14_hr) -disp:clearScreen() - - -tmr.register(0, 3000, tmr.ALARM_AUTO, function() loop() end) -tmr.start(0) + tmr.create():alarm(3000, tmr.ALARM_AUTO, function() loop() end) +end diff --git a/lua_examples/ucglib/HelloWorld.lua b/lua_examples/ucglib/HelloWorld.lua index 6c7c8731..d5b6215e 100644 --- a/lua_examples/ucglib/HelloWorld.lua +++ b/lua_examples/ucglib/HelloWorld.lua @@ -1,5 +1,7 @@ +local disp + -- setup SPI and connect display -function init_spi_display() +local function init_spi_display() -- Hardware SPI CLK = GPIO14 -- Hardware SPI MOSI = GPIO13 -- Hardware SPI MISO = GPIO12 (not used) @@ -20,17 +22,17 @@ function init_spi_display() disp = ucg.st7735_18x128x160_hw_spi(bus, cs, dc, res) end +do + init_spi_display() + + disp:begin(ucg.FONT_MODE_TRANSPARENT) + disp:clearScreen() + + disp:setFont(ucg.font_ncenR12_tr); + disp:setColor(255, 255, 255); + disp:setColor(1, 255, 0,0); -init_spi_display() - -disp:begin(ucg.FONT_MODE_TRANSPARENT) -disp:clearScreen() - -disp:setFont(ucg.font_ncenR12_tr); -disp:setColor(255, 255, 255); -disp:setColor(1, 255, 0,0); - - -disp:setPrintPos(0, 25) -disp:print("Hello World!") + disp:setPrintPos(0, 25) + disp:print("Hello World!") +end diff --git a/lua_examples/ucglib/UcgLogo.lua b/lua_examples/ucglib/UcgLogo.lua index 760fd0bd..644b90a5 100644 --- a/lua_examples/ucglib/UcgLogo.lua +++ b/lua_examples/ucglib/UcgLogo.lua @@ -1,5 +1,7 @@ +local disp + -- setup SPI and connect display -function init_spi_display() +local function init_spi_display() -- Hardware SPI CLK = GPIO14 -- Hardware SPI MOSI = GPIO13 -- Hardware SPI MISO = GPIO12 (not used) @@ -21,7 +23,7 @@ function init_spi_display() end -function upper_pin(x, y) +local function upper_pin(x, y) local w = 7 local h = 6 disp:setColor(0, 212, 212, 212) @@ -36,7 +38,7 @@ function upper_pin(x, y) disp:drawGradientLine(x+w, y, h, 1) end -function lower_pin(x, y) +local function lower_pin(x, y) local w = 7 local h = 5 disp:setColor(0, 212, 212, 212) @@ -56,7 +58,7 @@ function lower_pin(x, y) disp:drawPixel(x+w, y+h) end -function ic_body(x, y) +local function ic_body(x, y) local w = 4*14+4 local h = 31 disp:setColor(0, 60, 60, 60) @@ -77,7 +79,7 @@ function ic_body(x, y) disp:drawDisc(x+w-1, y+h/2+1, 7, bit.bor(ucg.DRAW_UPPER_LEFT, ucg.DRAW_LOWER_LEFT)) end -function draw_ucg_logo() +local function draw_ucg_logo() local a, b --ucg_Init(ucg, ucg_sdl_dev_cb, ucg_ext_none, (ucg_com_fnptr)0) @@ -156,12 +158,12 @@ function draw_ucg_logo() --disp:drawString(1, 61, 0, "code.google.com/p/ucglib/") end +do + init_spi_display() -init_spi_display() + disp:begin(ucg.FONT_MODE_TRANSPARENT) + disp:clearScreen() -disp:begin(ucg.FONT_MODE_TRANSPARENT) -disp:clearScreen() - - -disp:setRotate180() -draw_ucg_logo() + disp:setRotate180() + draw_ucg_logo() +end diff --git a/lua_examples/webap_toggle_pin.lua b/lua_examples/webap_toggle_pin.lua index 60de70a6..bacb3def 100644 --- a/lua_examples/webap_toggle_pin.lua +++ b/lua_examples/webap_toggle_pin.lua @@ -1,21 +1,24 @@ +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 .. "