Commencé mes tests de lecture de capteurs de température one-wire DS18b20 avec ThingSpeak

This commit is contained in:
Christian Zufferey
2019-06-16 11:37:30 +02:00
parent 551da1736f
commit 58bad9d31f
35 changed files with 1201 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
# tst_ds18b20
## Petit test pour mesurer la température avec des capteurs one-wire DS18B20 et les afficher sur ThingSpeak
dofile("a1.lua")
zf190616.1114

View File

@@ -0,0 +1,23 @@
-- programme pour faire un test depuis de le webide
-- source: https://nodemcu.readthedocs.io/en/master/modules/ds18b20/
function a1()
print("\n a1.lua zf190601.1627 \n")
end
a1()
local ow_pin = 3
ds18b20.setup(ow_pin)
print("toto182538")
-- read all sensors and print all measurement results
ds18b20.read(
function(ind,rom,res,temp,tdec,par)
print(ind,string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",string.match(rom,"(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)")),res,temp,tdec,par)
end,{})
print("tutu152603")

View File

@@ -0,0 +1,10 @@
-- programme pour faire un test depuis de le webide
function a2()
print("\n a2.lua zf190601.1304 \n")
end

View File

@@ -0,0 +1,10 @@
-- programme pour faire un test depuis de le webide
function a3()
print("\n a3.lua zf190601.1304 \n")
end

View File

@@ -0,0 +1,10 @@
-- programme pour faire un test depuis de le webide
function a4()
print("\n a4.lua zf190601.1304 \n")
end

View File

@@ -0,0 +1,34 @@
-- Scripts à charger après le boot pour démarrer son appli
print("\n boot.lua zf190601.1615 \n")
function heartbeat()
f= "flash_led_xfois.lua" if file.exists(f) then dofile(f) end
flash_led_xfois()
boottimer1=tmr.create()
-- tmr.alarm(boottimer1, 1*1000, tmr.ALARM_AUTO, function()
boottimer1:alarm(1*1000, tmr.ALARM_AUTO, function()
xfois =2
blink_LED ()
end)
end
--f= "led_rgb.lua" if file.exists(f) then dofile(f) end
--f= "wifi_ap_start.lua" if file.exists(f) then dofile(f) end
f= "wifi_ap_stop.lua" if file.exists(f) then dofile(f) end
f= "wifi_cli_conf.lua" if file.exists(f) then dofile(f) end
f= "wifi_cli_start.lua" if file.exists(f) then dofile(f) end
f= "telnet_srv2.lua" if file.exists(f) then dofile(f) end
f= "web_ide2.lua" if file.exists(f) then dofile(f) end
f= "web_srv2.lua" if file.exists(f) then dofile(f) end
--f= "set_time.lua" if file.exists(f) then dofile(f) end
--f= "dsleep.lua" if file.exists(f) then dofile(f) end
--f= "a_no_linear.lua" if file.exists(f) then dofile(f) end
f=nil
--heartbeat=nil
heartbeat()

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

View File

@@ -0,0 +1,39 @@
-- programme pour faire clignoter x fois une LED avec un rapport on/off
function flash_led_xfois()
print("\n flash_led_xfois.lua zf190601.1618 \n")
--zLED=0 --NodeMCU
zLED=4 --EPS-M3
zTm_On_LED = 50 --> en ms
zTm_Off_LED = 100 --> en ms
nbfois = 0
gpio.write(zLED, gpio.HIGH)
gpio.mode(zLED, gpio.OUTPUT)
ztmr_Flash_LED = tmr.create()
function blink_LED ()
if nbfois >= xfois then
-- print(nbfois)
nbfois = 0
else
if gpio.read(zLED)==gpio.HIGH then
gpio.write(zLED, gpio.LOW)
-- tmr.alarm(ztmr_Flash_LED, zTm_Off_LED, tmr.ALARM_SINGLE, blink_LED)
ztmr_Flash_LED:alarm(zTm_Off_LED, tmr.ALARM_SINGLE, blink_LED)
else
gpio.write(zLED, gpio.HIGH)
nbfois = nbfois+1
-- tmr.alarm(ztmr_Flash_LED, zTm_On_LED, tmr.ALARM_SINGLE, blink_LED)
ztmr_Flash_LED:alarm(zTm_On_LED, tmr.ALARM_SINGLE, blink_LED)
end
end
end
-- xfois =2
-- blink_LED ()
end

View File

@@ -0,0 +1,6 @@
-- Scripts pour afficher toutes les variables et fonctions en cours dans le système
print("\n a_tst_variable.lua zf190310.1525 \n")
for n in pairs (_G) do print(n) end

View File

@@ -0,0 +1,37 @@
-- Scripts juste pour allumer ou éteindre une LED sur un ruban RGB
-- tout sur la couleur: https://www.w3schools.com/colors/default.asp
-- roue des couleurs: https://iro.js.org/?ref=oldsite
print("\n led_rgb.lua zf190303.1436 \n")
nbleds=3
ws2812.init()
myLedStrip = ws2812.newBuffer(nbleds, 3)
function RGB_clear()
myLedStrip:fill(0, 0, 0) ws2812.write(myLedStrip)
end
function RGB_reform(R1, G1, B1) --conversion de RGB à BRG
rR1=B1 rG1=R1 rB1=G1
end
function zled_rgb(num_led, R1, G1, B1, zpower)
RGB_reform(R1, G1, B1)
myLedStrip:set(num_led, rR1*zpower, rG1*zpower, rB1*zpower)
ws2812.write(myLedStrip)
end
function zled_write()
ws2812.write(myLedStrip)
end
RGB_clear()
--[[
zled_rgb(1,255,0,0,1)
zled_rgb(2,0,255,0,1)
zled_rgb(2,0,255,0,0.05)
zled_rgb(3,0,0,255,1)
]]

View File

@@ -0,0 +1,12 @@
-- pour effacer TOUS les fichiers qui se trouve dans la flash du NodeMCU
print("\n rm_files.lua zf180907.1511 \n")
l=file.list() i=0
for k,v in pairs(l) do
i=i+v
file.remove(k)
end
print("-------------------------------")
print("\nC'est tout effaced :-) \n")

View File

@@ -0,0 +1,27 @@
ohm,%
33,100
36,96.77419355
41,92.74193548
45,88.70967742
52,84.67741935
56,80.64516129
61,76.61290323
67,72.58064516
72,68.5483871
79,64.51612903
83,60.48387097
91,56.4516129
97,52.41935484
104,48.38709677
112,44.35483871
117,40.32258065
121,36.29032258
128,32.25806452
132,28.22580645
139,24.19354839
150,20.16129032
166,16.12903226
191,12.09677419
207,8.064516129
224,4.032258065
240,0
1 ohm %
2 33 100
3 36 96.77419355
4 41 92.74193548
5 45 88.70967742
6 52 84.67741935
7 56 80.64516129
8 61 76.61290323
9 67 72.58064516
10 72 68.5483871
11 79 64.51612903
12 83 60.48387097
13 91 56.4516129
14 97 52.41935484
15 104 48.38709677
16 112 44.35483871
17 117 40.32258065
18 121 36.29032258
19 128 32.25806452
20 132 28.22580645
21 139 24.19354839
22 150 20.16129032
23 166 16.12903226
24 191 12.09677419
25 207 8.064516129
26 224 4.032258065
27 240 0

View File

@@ -0,0 +1,19 @@
-- Démarre le WIFI en mode AP
function wifi_ap_start()
print("\n wifi_ap_start.lua zf190310.1511 \n")
local zmodewifi=wifi.getmode()
if zmodewifi == wifi.NULLMODE then
print("WIFI mode AP only")
wifi.setmode(wifi.SOFTAP)
elseif zmodewifi == wifi.STATION then
print("WIFI mode AP+CLI")
wifi.setmode(wifi.STATIONAP)
end
wifi.ap.config({ ssid = "NodeMCU "..wifi.ap.getmac(), pwd = "12345678" })
--f= "wifi_info.lua" if file.exists(f) then dofile(f) end
end
wifi_ap_start()
wifi_ap_start=nil

View File

@@ -0,0 +1,9 @@
-- Déconnecte le WIFI
print("\n wifi_off.lua zf180822.0959 \n")
wifi.setmode(wifi.NULLMODE)
--[[
print(wifi.NULLMODE, wifi.STATION, wifi.SOFTAP, wifi.STATIONAP)
print(wifi.getmode())
]]

View File

@@ -0,0 +1,53 @@
--Script de bootstrap, test au moment du boot qui a été la cause de boot.
-- Si la cause est un power on ou une connexion depuis l'IDE, alors
-- le script repair.lua pendant xx secondes avant de continuer
--Source: https://nodemcu.readthedocs.io/en/master/en/modules/node/#nodebootreason
print("\n init.lua zf190601.1620 \n")
zswitch=3 --switch flash
gpio.mode(zswitch, gpio.INT, gpio.PULLUP)
function hvbouton()
-- gpio.trig(zswitch, "none")
tmr.unregister(initalarme)
f= "boot.lua" if file.exists(f) then dofile(f) end
end
gpio.trig(zswitch, "both", hvbouton)
function second_chance()
print("seconde chance...")
f= "repair.lua" if file.exists(f) then dofile(f) end
initalarme=tmr.create()
-- tmr.alarm(initalarme, 4*1000, tmr.ALARM_SINGLE, function()
initalarme:alarm(4*1000, tmr.ALARM_SINGLE, function()
f= "boot.lua" if file.exists(f) then dofile(f) end
end)
end
_, reset_reason = node.bootreason()
print("reset_reason:",reset_reason)
if reset_reason == 0 then
print("power on")
second_chance()
elseif reset_reason == 4 then
print("node.restart")
gpio.trig(zswitch)
hvbouton=nil
second_chance=nil
zswitch=nil
reset_reason=nil
f= "boot.lua" if file.exists(f) then dofile(f) end
elseif reset_reason == 5 then
print("dsleep wake up")
f= "boot.lua" if file.exists(f) then dofile(f) end
elseif reset_reason == 6 then
print("external reset")
second_chance()
-- f= "boot.lua" if file.exists(f) then dofile(f) end
else
print("autre raison")
second_chance()
end

View File

@@ -0,0 +1,52 @@
t = require("ds18b20")
pin = 3 -- gpio0 = 3, gpio2 = 4
local function readout(temp)
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 ""))
end
end
for addr, temp in pairs(temp) do
print(string.format("Sensor %s: %s °C", ('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(addr:byte(1,8)), temp))
end
-- Module can be released when it is no longer needed
--t = nil
--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)
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)

View File

@@ -0,0 +1,35 @@
t = require('ds18b20')
port = 80
pin = 3 -- gpio0 = 3, gpio2 = 4
gconn = {} -- global variable for connection
function readout(temp)
local resp = "HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" ..
"<!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)
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>"
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
)

View File

@@ -0,0 +1,223 @@
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- 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 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 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 DS18B20FAMILY = 0x28
local DS1920FAMILY = 0x10 -- and DS18S20 series
local CONVERT_T = 0x44
local READ_SCRATCHPAD = 0xBE
local READ_POWERSUPPLY= 0xB4
local MODE = 1
local pin, cb, unit = 3
local status = {}
local debugPrint = function() return end
--------------------------------------------------------------------------------
-- Implementation
--------------------------------------------------------------------------------
local function enable_debug()
debugPrint = function (...) print(now(),' ', ...) end
end
local function to_string(addr, esc)
if type(addr) == 'string' and #addr == 8 then
return ( esc == true and
'"\\%u\\%u\\%u\\%u\\%u\\%u\\%u\\%u"' or
'%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X '):format(addr:byte(1,8))
else
return tostring(addr)
end
end
local function readout(self)
local next = false
local sens = self.sens
local temp = self.temp
for i, s in ipairs(sens) do
if status[i] == 1 then
ow_reset(pin)
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 t=(data:byte(1)+data:byte(2)*256)
-- t is actually signed so process the sign bit and adjust for fractional bits
-- the DS18B20 family has 4 fractional bits and the DS18S20s, 1 fractional bit
t = ((t <= 32767) and t or t - 65536) *
((addr:byte(1) == DS18B20FAMILY) and 625 or 5000)
if 1/2 == 0 then
-- integer version
if unit == 'F' then
t = (t * 18)/10 + 320000
elseif unit == 'K' then
t = t + 2731500
end
local sgn = t<0 and -1 or 1
local tA = sgn*t
local tH=tA/10000
local tL=(tA%10000)/1000 + ((tA%1000)/100 >= 5 and 1 or 0)
if tH and (t~=850000) then
temp[addr]=(sgn<0 and "-" or "")..tH.."."..tL
debugPrint(to_string(addr),(sgn<0 and "-" or "")..tH.."."..tL)
status[i] = 2
end
-- end integer version
else
-- float version
if t and (math_floor(t/10000)~=85) then
t = t / 10000
if unit == 'F' then
t = t * 18/10 + 32
elseif unit == 'K' then
t = t + 27315/100
end
self.temp[addr]=t
debugPrint(to_string(addr), t)
status[i] = 2
end
-- end float version
end
end
next = next or status[i] == 0
end
if next then
node_task_post(node_task_LOW_PRIORITY, function() return conversion(self) end)
else
--sens = {}
if cb then
node_task_post(node_task_LOW_PRIORITY, function() return cb(temp) end)
end
end
end
local function conversion(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
if powered_only then
debugPrint("starting conversion: all sensors")
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
else
for i, s in ipairs(sens) do
if status[i] == 0 then
local addr, parasite = s:sub(1,8), s:byte(9)
debugPrint("starting conversion:", to_string(addr), parasite == 1 and "parasite" or " ")
ow_reset(pin)
ow_select(pin, addr) -- select the sensor
ow_write(pin, CONVERT_T, MODE) -- and start conversion
status[i] = 1
if parasite == 1 then break end -- parasite sensor blocks bus during conversion
end
end
end
tmr_create():alarm(750, tmr_ALARM_SINGLE, function() return readout(self) 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
local addr
if not search and #sens == 0 then
-- load addreses if available
debugPrint ("geting addreses from flash")
local s,check,a = pcall(dofile, "ds18b20_save.lc")
if s and check == "ds18b20" then
for i = 1, #a do sens[i] = a[i] end
end
debugPrint (#sens, "addreses found")
end
ow_setup(pin)
if search or #sens == 0 then
ow_reset_search(pin)
-- ow_target_search(pin,0x28)
-- search the first device
addr = ow_search(pin)
else
for i, s in ipairs(sens) do status[i] = 0 end
end
local function cycle()
debugPrint("cycle")
if addr then
local crc=ow_crc8(addr:sub(1,7))
if (crc==addr:byte(8)) and ((addr:byte(1)==DS1920FAMILY) or (addr:byte(1)==DS18B20FAMILY)) then
ow_reset(pin)
ow_select(pin, addr)
ow_write(pin, READ_POWERSUPPLY, MODE)
local parasite = (ow_read(pin)==0 and 1 or 0)
sens[#sens+1]= addr..string_char(parasite) -- {addr=addr, parasite=parasite, status=0}
debugPrint("contact: ", to_string(addr), parasite == 1 and "parasite" or " ")
end
addr = ow_search(pin)
node_task_post(node_task_LOW_PRIORITY, cycle)
else
ow_depower(pin)
-- place powered sensors first
table_sort(sens, function(a, b) return a:byte(9)<b:byte(9) end) -- parasite
-- save sensor addreses
if save then
debugPrint ("saving addreses to flash")
local addr_list = {}
for i =1, #sens do
local s = sens[i]
addr_list[i] = to_string(s:sub(1,8), true)..('.."\\%u"'):format(s:byte(9))
end
local save_statement = 'return "ds18b20", {' .. table_concat(addr_list, ',') .. '}'
debugPrint (save_statement)
local save_file = file_open("ds18b20_save.lc","w")
save_file:write(string_dump(loadstring(save_statement)))
save_file:close()
end
-- end save sensor addreses
if lcb then node_task_post(node_task_LOW_PRIORITY, lcb) end
end
end
cycle()
end
local function read_temp(self, lcb, lpin, lunit, force_search, save_search)
cb, unit = lcb, lunit or unit
_search(self, function() return conversion(self) end, lpin, force_search, save_search)
end
-- Set module name as parameter of require and return module table
local M = {
sens = {},
temp = {},
C = 'C', F = 'F', K = 'K',
read_temp = read_temp, enable_debug = enable_debug
}
_G[modname or 'ds18b20'] = M
return M

View File

@@ -0,0 +1,29 @@
-- Scripts pour régler l'horloge quand on est connecté en WIFI
-- Permet aussi de 'compresser' le unix time afin de prendre moins de place dans les strings
print("\n set_time.lua zf190217.1426 \n")
--source: https://www.freeformatter.com/epoch-timestamp-to-date-converter.html
ztime2019 = 1546300800 -- Unix time pour le 1.1.2019
function set_time()
sntp.sync(nil, nil, nil, 1)
end
function ztime_compress(ztime_long)
return ztime_long - ztime2019
end
function ztime_uncompress(ztime_short)
return ztime_short + ztime2019
end
function ztime_format(ztime)
tm = rtctime.epoch2cal(ztime + 3600)
return(string.format("%04d/%02d/%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"]))
end
set_time()
print(ztime_format(rtctime.get()))

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@@ -0,0 +1,87 @@
-- Serveur telnet pour connexion en remote WIFI, NOUVELLE VERSION !
-- source: https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/telnet/telnet.lua
print("\n telnet_srv2.lua zf181215.1326 \n")
local node, table, tmr, wifi, uwrite, tostring =
node, table, tmr, wifi, uart.write, tostring
local function telnet_listener(socket)
local insert, remove, concat, heap, gc =
table.insert, table.remove, table.concat, node.heap, collectgarbage
local fifo1, fifo1l, fifo2, fifo2l = {}, 0, {}, 0
local s -- s is a copy of the TCP socket if and only if sending is in progress
local wdclr, cnt = tmr.wdclr, 0
local function debug(fmt, ...)
if (...) then fmt = fmt:format(...) end
uwrite(0, "\r\nDBG: ",fmt,"\r\n" )
cnt = cnt + 1
if cnt % 10 then wdclr() end
end
local function flushGarbage()
if heap() < 13440 then gc() end
end
local function sendLine()
if not s then return end
if fifo2l + fifo1l == 0 then -- both FIFOs empty, so clear down s
s = nil
return
end
flushGarbage()
if #fifo2 < 4 then -- Flush FIFO1 into FIFO2
insert(fifo2,concat(fifo1))
fifo2l, fifo1, fifo1l = fifo2l + fifo1l, {}, 0
end
local rec = remove(fifo2,1) .. (remove(fifo2,1) or '') ..
(remove(fifo2,1) or '') .. (remove(fifo2,1) or '')
fifo2l = fifo2l - #rec
flushGarbage()
s:send(rec)
end
local F1_SIZE = 256
local function queueLine(str)
while #str > 0 do -- this is because str might be longer than the packet size!
local k, l = F1_SIZE - fifo1l, #str
local chunk
if #fifo1 >= 32 or (k < l and k < 16) then
insert(fifo2, concat(fifo1))
fifo2l, fifo1, fifo1l, k = fifo2l + fifo1l, {}, 0, F1_SIZE
end
if l > k+16 then -- also tolerate a size overrun of 16 bytes to avoid a split
chunk, str = str:sub(1,k), str:sub(k+1)
else
chunk, str = str, ''
end
insert(fifo1, chunk)
fifo1l = fifo1l + #chunk
end
if not s and socket then
s = socket
sendLine()
else
flushGarbage()
end
end
local function receiveLine(s, line)
node.input(line)
end
local function disconnect(s)
fifo1, fifo1l, fifo2, fifo2l, s = {}, 0, {}, 0, nil
node.output(nil)
end
socket:on("receive", receiveLine)
socket:on("disconnection", disconnect)
socket:on("sent", sendLine)
node.output(queueLine, 0)
end
net.createServer(net.TCP, 180):listen(23, telnet_listener)
print("Telnet server running...\nUsage: telnet -rN ip\n")

View File

@@ -0,0 +1,159 @@
-- Petit WEB IDE tout simple autonome
-- ATTENTION: tourne sur le port 88 !
print("\n _web_ide2.lua zf181210.1516 \n")
--[[
XChip's NodeMCU IDE
Create, Edit and run NodeMCU files using your webbrowser.
Examples:
http://<mcu_ip>/ will list all the files in the MCU
http://<mcu_ip>/newfile.lua displays the file on your browser
http://<mcu_ip>/newfile.lua?edit allows to creates or edits the specified script in your browser
http://<mcu_ip>/newfile.lua?run it will run the specified script and will show the returned value
]]--
srv=net.createServer(net.TCP)
srv:listen(88,function(conn)
local rnrn=0
local Status = 0
local DataToGet = 0
local method=""
local url=""
local vars=""
conn:on("receive",function(conn,payload)
if Status==0 then
_, _, method, url, vars = string.find(payload, "([A-Z]+) /([^?]*)%??(.*) HTTP")
print(method, url, vars)
end
if method=="POST" then
if Status==0 then
--print("status", Status)
_,_,DataToGet, payload = string.find(payload, "Content%-Length: (%d+)(.+)")
if DataToGet~=nil then
DataToGet = tonumber(DataToGet)
--print(DataToGet)
rnrn=1
Status = 1
else
print("bad length")
end
end
-- find /r/n/r/n
if Status==1 then
--print("status", Status)
local payloadlen = string.len(payload)
local mark = "\r\n\r\n"
local i
for i=1, payloadlen do
if string.byte(mark, rnrn) == string.byte(payload, i) then
rnrn=rnrn+1
if rnrn==5 then
payload = string.sub(payload, i+1,payloadlen)
file.open(url, "w")
file.close()
Status=2
break
end
else
rnrn=1
end
end
if Status==1 then
return
end
end
if Status==2 then
--print("status", Status)
if payload~=nil then
DataToGet=DataToGet-string.len(payload)
--print("DataToGet:", DataToGet, "payload len:", string.len(payload))
file.open(url, "a+")
file.write(payload)
file.close()
else
conn:send("HTTP/1.1 200 OK\r\n\r\nERROR")
Status=0
end
if DataToGet==0 then
conn:send("HTTP/1.1 200 OK\r\n\r\nOK")
Status=0
end
end
return
end
DataToGet = -1
if url == "favicon.ico" then
conn:send("HTTP/1.1 404 file not found")
return
end
conn:send("HTTP/1.1 200 OK\r\n\r\n")
-- it wants a file in particular
if url~="" and vars=="" then
DataToGet = 0
return
end
conn:send("<html><body><h1>NodeMCU IDE</h1>")
if vars=="edit" then
conn:send("<script>function tag(c){document.getElementsByTagName('w')[0].innerHTML=c};\n")
conn:send("var x=new XMLHttpRequest()\nx.onreadystatechange=function(){if(x.readyState==4) document.getElementsByName('t')[0].value = x.responseText; };\nx.open('GET',location.pathname,true)\nx.send()</script>")
conn:send("<h2><a href='/'>Back to file list</a>\n")
conn:send("<br><br><button onclick=\"tag('Saving');x.open('POST',location.pathname,true);\nx.onreadystatechange=function(){if(x.readyState==4) tag(x.responseText);};\nx.send(new Blob([document.getElementsByName('t')[0].value],{type:'text/plain'}));\">Save</button><a href='?run'>run</a><w></w>")
conn:send("</h2><br><textarea name=t cols=110 rows=50></textarea></br>")
end
if vars=="run" then
conn:send("<verbatim>")
local st, result=pcall(dofile, url)
conn:send(tostring(result))
conn:send("</verbatim>")
end
if url=="" then
local l = file.list();
for k,v in pairs(l) do
conn:send("<a href='"..k.."?edit'>"..k.."</a>, size:"..v.."<br>")
end
end
conn:send("</body></html>")
end)
conn:on("sent",function(conn)
if DataToGet>=0 and method=="GET" then
if file.open(url, "r") then
file.seek("set", DataToGet)
local line=file.read(512)
file.close()
if line then
conn:send(line)
DataToGet = DataToGet + 512
if (string.len(line)==512) then
return
end
end
end
end
conn:close()
end)
end)
print("listening, free:", node.heap())

View File

@@ -0,0 +1,77 @@
-- petit script de serveur WEB avec Active Server Page ZYX
print("\n web_srv2.lua zf190422.1135 \n")
ztemp=12
-- envoie sur le port ouvert mais depuis l'environnement global !
function zout(zstring)
zzclient:send(zstring) -- envoie le résultat du code lua inline
end
-- envoie un fichier HTML sur le port. ATTENTION: longueur de la ligne maximale de 1'024 bytes !
function send_file(zclient, zfilename)
print("start send html...")
zclient:send("HTTP/1.1 200 OK\n")
zclient:send("Content-Type: text/html\n\n")
zzclient = zclient -- export le port sur l'environnement global !
if zfilename == "" then zfilename = "z_index.html" end
file_web = file.open(zfilename, "r")
if file_web then
repeat
local line = file_web:read('\n')
if line then
if string.find(line, "<%%") then
-- print("start lua...")
flag_lua_code = true -- bascule sur le code lua inline
lua_code = ""
elseif string.find(line, "%%>") then
-- print("stop lua...")
flag_lua_code = false -- revient sur le code HTML
-- print("Et voici le code lua inline:\n"..lua_code)
loadstring(lua_code)() --on exécute ici le code lua inline !
elseif flag_lua_code then
-- print(line)
lua_code = lua_code..line -- récupère le code lua inline
else
zclient:send(line) -- envoie le code HTML
end
end
until not line
file_web:close() file_web = nil
else
zclient:send("<html><h1>"..zfilename.." not found - 404 error</h1><a href='/'>Home</a><br></html>")
end
end
srv = net.createServer()
srv:listen(80, function(conn)
conn:on("receive", function(client, request)
_, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
print("request: \n---\n"..request.."---")
-- print("method: ", method) print("path: ", path) print("vars: ", vars)
if not string.find(request, "/favicon.ico") then
print("coucou")
if (method == nil) then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP")
end
print("method: ", method) print("path: ", path) print("vars: ", vars)
_GET = {}
if (vars ~= nil) then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v
print(k..": "..v)
end
end
file_html=string.gsub(path, "/", "")
-- print("file_html: ",file_html)
send_file(client, file_html)
end
end)
conn:on("sent", function(c) c:close() end)
end)

View File

@@ -0,0 +1,10 @@
-- Démarre le WIFI en mode AP
print("\n wifi_ap_stop.lua zf180824.2000 \n")
local zmodewifi=wifi.getmode()
if zmodewifi == wifi.SOFTAP then
wifi.setmode(wifi.NULLMODE)
elseif zmodewifi == wifi.STATIONAP then
wifi.setmode(wifi.STATION)
end
print("WIFI AP arrêté")

View File

@@ -0,0 +1,20 @@
-- Petit script pour configurer le client WIFI du NodeMCU
function wifi_cli_conf()
print("\n wifi_cli_conf.lua zf190601.1328 \n")
--credentials par défaut
--cli_ssid="3g-s7"
cli_ssid="3G-zf"
cli_pwd="12234567"
--ses propre credentials
f= "credentials_solar.lua" if file.exists(f) then dofile(f) end
wifi.sta.config{ssid=cli_ssid, pwd=cli_pwd, save=true}
end
wifi_cli_conf()
wifi_cli_conf=nil
cli_ssid=nil
cli_pwd=nil

View File

@@ -0,0 +1,20 @@
-- Petit script pour connecter le NodeMCU sur un AP Wifi avec l'accompte sauvé en EEPROM
function wifi_cli_start()
print("\n wifi_cli_start.lua zf190310.1519 \n")
local zmodewifi=wifi.getmode()
if zmodewifi == wifi.NULLMODE then
print("WIFI mode CLI only")
wifi.setmode(wifi.STATION)
elseif zmodewifi == wifi.SOFTAP then
print("WIFI mode AP+CLI")
wifi.setmode(wifi.STATIONAP)
end
wifi.sta.autoconnect(1)
wifi.sta.connect()
--f= "wifi_get_ip.lua" if file.exists(f) then dofile(f) end
end
wifi_cli_start()
wifi_cli_start=nil

View File

@@ -0,0 +1,12 @@
-- Petit script pour obtenir l'adresse IP du NodeMCU connecté sur un AP Wifi
print("\n wifi_get_ip.lua zf181119.2318 \n")
wifitimer1=tmr.create()
tmr.alarm(wifitimer1, 1000, tmr.ALARM_AUTO , function()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
tmr.stop(wifitimer1)
f= "wifi_info.lua" if file.exists(f) then dofile(f) end
end
end)

View File

@@ -0,0 +1,31 @@
-- Petit script pour afficher les infos actuel du WIFI
print("\n wifi_info.lua zf181119.0014 \n")
local zmodewifi=wifi.getmode()
--wifi.NULLMODE, wifi.STATION, wifi.SOFTAP, wifi.STATIONAP
if zmodewifi == wifi.NULLMODE then
print("WIFI OFF")
elseif zmodewifi == wifi.STATION then
print("WIFI mode CLI")
print("Connected IP:\n",wifi.sta.getip())
do
local sta_config=wifi.sta.getconfig(true)
print(string.format("Current client config:\n\tssid:\"%s\"\tpassword:\"%s\"\n\tbssid:\"%s\"\tbssid_set:%s", sta_config.ssid, sta_config.pwd, sta_config.bssid, (sta_config.bssid_set and "true" or "false")))
end
elseif zmodewifi == wifi.SOFTAP then
print("WIFI mode AP")
print("AP MAC:\n",wifi.ap.getmac())
print("AP IP:\n",wifi.ap.getip())
print("AP Connect:\n",wifi.ap.getconfig())
elseif zmodewifi == wifi.STATIONAP then
print("WIFI mode CLI+AP")
print("Connected IP:\n",wifi.sta.getip())
do
local sta_config=wifi.sta.getconfig(true)
print(string.format("Current client config:\n\tssid:\"%s\"\tpassword:\"%s\"\n\tbssid:\"%s\"\tbssid_set:%s", sta_config.ssid, sta_config.pwd, sta_config.bssid, (sta_config.bssid_set and "true" or "false")))
end
print("AP MAC: "..wifi.ap.getmac())
print("AP IP: "..wifi.ap.getip())
end

View File

@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
<meta charset='utf-8' name='viewport' content='width=device-width, initial-scale=1.0'>
<title>ESP8266 home page</title>
</head>
<body>
<h1>ESP8266 home page 190422.1052</h1>
<h2>Différentes pages HTML:</h2>
<h3>
<a href="z_page1.html">Page 1, affichage de la température dynamique en code Lua inline.</a><br>
<a href="z_page2.html">Page 2, tableau dynamique écrit en Lua inline.</a><br>
<a href="z_page3.html">Page 3, affichage du capteur non linéaire corrigé.</a><br>
<a href="page_qui_existe_pag.html">Page qui n'existe pas !</a><br>
</h3>
</body>
</html>

View File

@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
<meta charset='utf-8' name='viewport' content='width=device-width, initial-scale=1.0'>
<title>ESP8266 page 1</title>
</head>
<body>
<h1>ESP8266 page 1 190127.1445</h1>
<br>
Coucou c'est la page 1 !<br>
<a href="/">Retour à la home page...</a><br><br><br>
La température est:
<%
ztemp=ztemp+1
zout(ztemp.."°C")
%>
<br>Mais il fait encore trop froid !<br>
</body>
</html>

View File

@@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
<meta charset='utf-8' name='viewport' content='width=device-width, initial-scale=1.0'>
<title>ESP8266 page 2</title>
</head>
<body>
<h1>ESP8266 page 2 190127.1449</h1>
<br>
Coucou c'est la page 2 !<br>
<a href="/">Retour à la home page...</a><br><br><br>
Voici un tableau dynamique écrit en Lua inline.<br><br>
Le code Lua pour créer ce tableau se trouve dans le code HTML de cette page et est exécuté sur le NodeMCU.<br>
Les données du tableau viennent du NodeMCU !<br><br>
<%
-- création du tableau sur le NodeMCUjuste juste pour la démo ici !
zmac_adrs={}
zmac_adrs["b8:d7:af:a6:bd:86"]={["zname"]="S7 zf", ["zrssi"]=45, ["ztime"]="12:03:36"}
zmac_adrs["cc:c0:79:7d:f5:d5"]={["zname"]="S7 Mélanie", ["zrssi"]=50, ["ztime"]="14:23:46"}
zmac_adrs["5c:f9:38:a1:f7:f0"]={["zname"]="MAC zf", ["zrssi"]=40, ["ztime"]="11:53:16"}
zmac_adrs["d8:30:62:5a:d6:3a"]={["zname"]="IMAC Maman", ["zrssi"]=55, ["ztime"]="17:07:23"}
%>
<table border='1'>
<tr>
<th>MAC</th><th>Name</th><th>RSSI</th><th>Time</th>
</tr>
<%
for k, v in pairs(zmac_adrs) do
zout("<tr>\n")
zout("\t<td>" .. k .. "</td>\n")
zout("\t<td>" .. tostring(zmac_adrs[k]["zname"]) .. "</td>\n")
zout("\t<td>" .. tostring(zmac_adrs[k]["zrssi"]) .. "</td>\n")
zout("\t<td>" .. tostring(zmac_adrs[k]["ztime"]) .. "</td>\n")
zout("</tr>\n")
end
%>
</table>
<%
-- libère la mémoire du tableau sur le NodeMCU qui avait été créé pour la démo ici !
zmac_adrs=nil
%>
</body>
</html>

View File

@@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
<meta charset='utf-8' name='viewport' content='width=device-width, initial-scale=1.0'>
<title>ESP8266 page 3</title>
</head>
<body>
<h1>ESP8266 page 3 190505.1156</h1>
<br>
Coucou c'est la page 3 !<br>
<a href="/">Retour à la home page...</a><br><br><br>
Voici le résultat du capteur non linéaire corrigé avec une table
d'interpolation dans un fichier .csv sur la flash.<br><br>
Le code Lua pour afficher ce résultat se trouve dans le code HTML de cette page et est exécuté sur le NodeMCU.<br>
Les données viennent du NodeMCU !<br><br>
<%
zout("Il reste: "..node.heap().." de RAM !<br><br>\n")
%>
<%
zx0=83
get_correction(zx0)
zout("la valeur corrigée de "..zx0.." est "..zy0.."<br>")
%>
<%
zx0=91
get_correction(zx0)
zout("la valeur corrigée de "..zx0.." est "..zy0.."<br>")
%>
<%
zx0=100
get_correction(zx0)
zout("la valeur corrigée de "..zx0.." est "..zy0.."<br>")
%>
<br>Yeah... cela fonctionne vachement bien !<br><br>
<%
zout("Il reste: "..node.heap().." de RAM !<br><br>\n")
%>
</body>
</html>