NODEMCU XIVELY GET AND PARSE DATA

Post date: Jul 12, 2016 10:50:8 AM

function split(text, delim)

    -- returns an array of fields based on text and delimiter (one character only)

    local result = {}

    local magic = "().%+-*?[]^$"

    if delim == nil then

        delim = "%s"

    elseif string.find(delim, magic, 1, true) then

        -- escape magic

        delim = "%"..delim

    end

    local pattern = "[^"..delim.."]+"

    for w in string.gmatch(text, pattern) do

        table.insert(result, w)

    end

    return result

end

tmr.alarm(1,25000,tmr.ALARM_AUTO, function()

sk=net.createConnection(net.TCP,0) 

sk:on("receive", function(sck, payload)

local str=string.sub(payload,string.find(payload,'CH01'),-1)

local tab=split(str,'\n')

print("Time:"..string.sub(tab[1],6,33))

print("Va="..string.sub(tab[1],34,-1), "Vb="..string.sub(tab[2],34,-1),

"Vc="..string.sub(tab[3],34,-1))

print("Ia="..string.sub(tab[4],34,-1), "Ib="..string.sub(tab[5],34,-1),

"Ic="..string.sub(tab[6],34,-1))

print("P="..string.sub(tab[7],34,-1), "Q="..string.sub(tab[8],34,-1),

"PF="..string.sub(tab[9],34,-1), "Freq="..string.sub(tab[10],34,-1))

--print(payload) 

--tab=cjson.decode(string.sub(payload,string.find(payload,"{"),-1))

--print("Va="..tab.current_value.."V")

sk:close()

end)

sk:on("disconnection", function(sck,c) print("Disconnect") end)

sk:connect(80,"api.xively.com")

sk:on("connection", function(sck, c) print("Connect Ok")

sck:send("GET /v2/feeds/104704.csv HTTP/1.1\r\nHOST: api.xively.com\r\nX-Apikey: YOUR_API_XIVELY_KEY\r\n\r\n")

--sck:send("GET /v2/feeds/104704/datastreams/CH01.json HTTP/1.1\r\nHOST: api.xively.com\r\nX-Apikey: YOUR_API_XIVELY_KEY\r\n\r\n")

end)

end)