Commit 9cab7513 authored by Vowstar's avatar Vowstar
Browse files

Merge pull request #1 from MarsTechHAN/master

Update to MarsTechHAN's nodemcu-firmware
parents a2d1e5ff ad1ec8fb
--------------------------------------------------------------------------------
-- DS3231 I2C module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Tobie Booth <tbooth@hindbra.in>
--------------------------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
-- Default value for i2c communication
local id = 0
--device address
local dev_addr = 0x68
local function decToBcd(val)
return((val/10*16) + (val%10))
end
local function bcdToDec(val)
return((val/16*10) + (val%16))
end
-- initialize i2c
--parameters:
--d: sda
--l: scl
function M.init(d, l)
if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then
sda = d
scl = l
else
print("iic config failed!") return nil
end
print("init done")
i2c.setup(id, sda, scl, i2c.SLOW)
end
--get time from DS3231
function M.getTime()
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local c=i2c.read(id, 7)
i2c.stop(id)
return bcdToDec(tonumber(string.byte(c, 1))),
bcdToDec(tonumber(string.byte(c, 2))),
bcdToDec(tonumber(string.byte(c, 3))),
bcdToDec(tonumber(string.byte(c, 4))),
bcdToDec(tonumber(string.byte(c, 5))),
bcdToDec(tonumber(string.byte(c, 6))),
bcdToDec(tonumber(string.byte(c, 7)))
end
--set time for DS3231
function M.setTime(second, minute, hour, day, date, month, year)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.write(id, decToBcd(second))
i2c.write(id, decToBcd(minute))
i2c.write(id, decToBcd(hour))
i2c.write(id, decToBcd(day))
i2c.write(id, decToBcd(date))
i2c.write(id, decToBcd(month))
i2c.write(id, decToBcd(year))
i2c.stop(id)
end
return M
------------------------------------------------------------------------------
-- HTTP server Hello world example
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
------------------------------------------------------------------------------
require("http").createServer(80, function(req, res)
-- analyse method and url
print("+R", req.method, req.url, node.heap())
-- setup handler of headers, if any
req.onheader = function(self, name, value)
-- print("+H", name, value)
-- E.g. look for "content-type" header,
-- setup body parser to particular format
-- if name == "content-type" then
-- if value == "application/json" then
-- req.ondata = function(self, chunk) ... end
-- elseif value == "application/x-www-form-urlencoded" then
-- req.ondata = function(self, chunk) ... end
-- end
-- end
end
-- setup handler of body, if any
req.ondata = function(self, chunk)
print("+B", chunk and #chunk, node.heap())
-- request ended?
if not chunk then
-- reply
--res:finish("")
res:send(nil, 200)
res:send_header("Connection", "close")
res:send("Hello, world!")
res:finish()
end
end
-- or just do something not waiting till body (if any) comes
--res:finish("Hello, world!")
--res:finish("Salut, monde!")
end)
------------------------------------------------------------------------------
-- HTTP server module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
------------------------------------------------------------------------------
local collectgarbage, tonumber, tostring = collectgarbage, tonumber, tostring
local http
do
------------------------------------------------------------------------------
-- request methods
------------------------------------------------------------------------------
local make_req = function(conn, method, url)
local req = {
conn = conn,
method = method,
url = url,
}
-- return setmetatable(req, {
-- })
return req
end
------------------------------------------------------------------------------
-- response methods
------------------------------------------------------------------------------
local send = function(self, data, status)
local c = self.conn
-- TODO: req.send should take care of response headers!
if self.send_header then
c:send("HTTP/1.1 ")
c:send(tostring(status or 200))
-- TODO: real HTTP status code/name table
c:send(" OK\r\n")
-- we use chunked transfer encoding, to not deal with Content-Length:
-- response header
self:send_header("Transfer-Encoding", "chunked")
-- TODO: send standard response headers, such as Server:, Date:
end
if data then
-- NB: no headers allowed after response body started
if self.send_header then
self.send_header = nil
-- end response headers
c:send("\r\n")
end
-- chunked transfer encoding
c:send(("%X\r\n"):format(#data))
c:send(data)
c:send("\r\n")
end
end
local send_header = function(self, name, value)
local c = self.conn
-- NB: quite a naive implementation
c:send(name)
c:send(": ")
c:send(value)
c:send("\r\n")
end
-- finalize request, optionally sending data
local finish = function(self, data, status)
local c = self.conn
-- NB: req.send takes care of response headers
if data then
self:send(data, status)
end
-- finalize chunked transfer encoding
c:send("0\r\n\r\n")
-- close connection
c:close()
end
--
local make_res = function(conn)
local res = {
conn = conn,
}
-- return setmetatable(res, {
-- send_header = send_header,
-- send = send,
-- finish = finish,
-- })
res.send_header = send_header
res.send = send
res.finish = finish
return res
end
------------------------------------------------------------------------------
-- HTTP parser
------------------------------------------------------------------------------
local http_handler = function(handler)
return function(conn)
local req, res
local buf = ""
local method, url
local ondisconnect = function(conn)
collectgarbage("collect")
end
-- header parser
local cnt_len = 0
local onheader = function(conn, k, v)
-- TODO: look for Content-Type: header
-- to help parse body
-- parse content length to know body length
if k == "content-length" then
cnt_len = tonumber(v)
end
if k == "expect" and v == "100-continue" then
conn:send("HTTP/1.1 100 Continue\r\n")
end
-- delegate to request object
if req and req.onheader then
req:onheader(k, v)
end
end
-- body data handler
local body_len = 0
local ondata = function(conn, chunk)
-- NB: do not reset node in case of lengthy requests
tmr.wdclr()
-- feed request data to request handler
if not req or not req.ondata then return end
req:ondata(chunk)
-- NB: once length of seen chunks equals Content-Length:
-- onend(conn) is called
body_len = body_len + #chunk
-- print("-B", #chunk, body_len, cnt_len, node.heap())
if body_len >= cnt_len then
req:ondata()
end
end
local onreceive = function(conn, chunk)
-- merge chunks in buffer
if buf then
buf = buf .. chunk
else
buf = chunk
end
-- consume buffer line by line
while #buf > 0 do
-- extract line
local e = buf:find("\r\n", 1, true)
if not e then break end
local line = buf:sub(1, e - 1)
buf = buf:sub(e + 2)
-- method, url?
if not method then
local i
-- NB: just version 1.1 assumed
_, i, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$")
if method then
-- make request and response objects
req = make_req(conn, method, url)
res = make_res(conn)
end
-- header line?
elseif #line > 0 then
-- parse header
local _, _, k, v = line:find("^([%w-]+):%s*(.+)")
-- header seems ok?
if k then
k = k:lower()
onheader(conn, k, v)
end
-- headers end
else
-- spawn request handler
-- NB: do not reset in case of lengthy requests
tmr.wdclr()
handler(req, res)
tmr.wdclr()
-- NB: we feed the rest of the buffer as starting chunk of body
ondata(conn, buf)
-- buffer no longer needed
buf = nil
-- NB: we explicitly reassign receive handler so that
-- next received chunks go directly to body handler
conn:on("receive", ondata)
-- parser done
break
end
end
end
conn:on("receive", onreceive)
conn:on("disconnection", ondisconnect)
end
end
------------------------------------------------------------------------------
-- HTTP server
------------------------------------------------------------------------------
local srv
local createServer = function(port, handler)
-- NB: only one server at a time
if srv then srv:close() end
srv = net.createServer(net.TCP, 15)
-- listen
srv:listen(port, http_handler(handler))
return srv
end
------------------------------------------------------------------------------
-- HTTP server methods
------------------------------------------------------------------------------
http = {
createServer = createServer,
}
end
return http
tmr.alarm(0, 60000, 1, function()
SDA_PIN = 6 -- sda pin, GPIO12
SCL_PIN = 5 -- scl pin, GPIO14
si7021 = require("si7021")
si7021.init(SDA_PIN, SCL_PIN)
si7021.read(OSS)
h = si7021.getHumidity()
t = si7021.getTemperature()
-- pressure in differents units
print("Humidity: "..(h / 100).."."..(h % 100).." %")
-- temperature in degrees Celsius and Farenheit
print("Temperature: "..(t/100).."."..(t%100).." deg C")
print("Temperature: "..(9 * t / 500 + 32).."."..(9 * t / 50 % 10).." deg F")
-- release module
si7021 = nil
package.loaded["si7021"]=nil
end)
--创建一个定时器
tmr.alarm(0, 60000, 1, function()
SDA_PIN = 6 -- sda pin, GPIO12
SCL_PIN = 5 -- scl pin, GPIO14
si7021 = require("si7021")
si7021.init(SDA_PIN, SCL_PIN)
si7021.read(OSS)
Hum = si7021.getHumidity()
Temp = si7021.getTemperature()
--定义数据变量格式
PostData = "[{\"Name\":\"T\",\"Value\":\"" .. (Temp/100).."."..(Temp%100) .. "\"},{\"Name\":\"H\",\"Value\":\"" .. (Hum/100).."."..(Hum%100) .. "\"}]"
--创建一个TCP连接
socket=net.createConnection(net.TCP, 0)
--域名解析IP地址并赋值
socket:dns("www.lewei50.com", function(conn, ip)
ServerIP = ip
print("Connection IP:" .. ServerIP)
end)
--开始连接服务器
socket:connect(80, ServerIP)
socket:on("connection", function(sck) end)
--HTTP请求头定义
socket:send("POST /api/V1/gateway/UpdateSensors/yourID HTTP/1.1\r\n" ..
"Host: www.lewei50.com\r\n" ..
"Content-Length: " .. string.len(PostData) .. "\r\n" ..
"userkey: yourKEY\r\n\r\n" ..
PostData .. "\r\n")
--HTTP响应内容
socket:on("receive", function(sck, response)
print(response)
end)
-- release module
si7021 = nil
package.loaded["si7021"]=nil
end)
# si7021 module
##Require
```lua
si7021 = require("si7021")
```
## Release
```lua
si7021 = nil
package.loaded["si7021"]=nil
```
<a id="si7021_init"></a>
##init()
####Description
Setting the i2c pin of si7021.<br />
####Syntax
init(sda, scl)
####Parameters
sda: 1~12, IO index.<br />
scl: 1~12, IO index.<br />
####Returns
nil
####Example
```lua
si7021 = require("si7021")
gpio5 = 1
gpio4 = 2
sda = gpio5
scl = gpio4
si7021.init(sda, scl)
-- Don't forget to release it after use
si7021 = nil
package.loaded["si7021"]=nil
```
####See also
**-** []()
<a id="si7021_read"></a>
##read()
####Description
Read temperature and humidity from si7021.<br />
####Syntax
read()
####Parameters
nil.<br />
####Returns
nil(Why?).<br />
####Example
```lua
si7021 = require("si7021")
sda = 1
scl = 2
si7021.init(sda, scl)
r = si7021.read()
print(r)
-- Don't forget to release it after use
si7021 = nil
package.loaded["si7021"]=nil
```
####See also
**-** []()
<a id="si7021_getHumidity"></a>
##getHumidity()
####Description
Get humidity from si7021.<br />
####Syntax
getHumidity()
####Parameters
nil.<br />
####Returns
h: Integer, humidity from si7021.
####Example
```lua
si7021 = require("si7021")
sda = 1
scl = 2
si7021.init(sda, scl)
h = si7021.getHumidity()
print(h)
-- Don't forget to release it after use
si7021 = nil
package.loaded["si7021"]=nil
```
####See also
**-** []()
<a id="si7021_getTemperature"></a>
##getTemperature()
####Description
Get temperature from si7021.<br />
####Syntax
getTemperature()
####Parameters
nil.<br />
####Returns
t: Integer, temperature from si7021.
####Example
```lua
si7021 = require("si7021")
sda = 1
scl = 2
si7021.init(sda, scl)
t = si7021.getTemperature()
print(t)
-- Don't forget to release it after use
si7021 = nil
package.loaded["si7021"]=nil
```
####See also
**-** []()
-- ***************************************************************************
-- SI7021 module for ESP8266 with nodeMCU
-- Si7021 compatible tested 2015-1-22
--
-- Written by VIP6
--
-- MIT license, http://opensource.org/licenses/MIT
-- ***************************************************************************
local moduleName = ...
local M = {}
_G[moduleName] = M
--I2C slave address of Si70xx
local Si7021_ADDR = 0x40
--Commands
local CMD_MEASURE_HUMIDITY_HOLD = 0xE5
local CMD_MEASURE_HUMIDITY_NO_HOLD = 0xF5
local CMD_MEASURE_TEMPERATURE_HOLD = 0xE3
local CMD_MEASURE_TEMPERATURE_NO_HOLD = 0xF3
-- temperature and pressure
local t,h
local init = false
-- i2c interface ID
local id = 0
-- 16-bit two's complement
-- value: 16-bit integer
local function twoCompl(value)
if value > 32767 then value = -(65535 - value + 1)
end
return value
end
-- read data from si7021
-- ADDR: slave address
-- commands: Commands of si7021
-- length: bytes to read
local function read_data(ADDR, commands, length)
i2c.start(id)
i2c.address(id, ADDR, i2c.TRANSMITTER)
i2c.write(id, commands)
i2c.stop(id)
i2c.start(id)
i2c.address(id, ADDR,i2c.RECEIVER)
tmr.delay(20000)
c = i2c.read(id, length)
i2c.stop(id)
return c
end
-- initialize module
-- sda: SDA pin
-- scl SCL pin
function M.init(sda, scl)
i2c.setup(id, sda, scl, i2c.SLOW)
--print("i2c ok..")
init = true
end
-- read humidity from si7021
local function read_humi()
dataH = read_data(Si7021_ADDR, CMD_MEASURE_HUMIDITY_HOLD, 2)
UH = string.byte(dataH, 1) * 256 + string.byte(dataH, 2)
h = ((UH*12500+65536/2)/65536 - 600)
return(h)
end
-- read temperature from si7021
local function read_temp()
dataT = read_data(Si7021_ADDR, CMD_MEASURE_TEMPERATURE_HOLD, 2)
UT = string.byte(dataT, 1) * 256 + string.byte(dataT, 2)
t = ((UT*17572+65536/2)/65536 - 4685)
return(t)
end
-- read temperature and humidity from si7021
function M.read()
if (not init) then
print("init() must be called before read.")
else
read_humi()
read_temp()
end
end;
-- get humidity
function M.getHumidity()
return h
end
-- get temperature
function M.getTemperature()
return t
end
return M
# Enforce Unix newlines
*.css text eol=lf
*.html text eol=lf
*.js text eol=lf
*.json text eol=lf
*.less text eol=lf
*.md text eol=lf
*.svg text eol=lf
*.yml text eol=lf
*.py text eol=lf
*.sh text eol=lf
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment