D. Schramm
D. Schramm

Reputation: 3

NodeMCU 0.9.6-dev on ESP 8266 (devkit v2): while dofile() script is not connecting to TCP-server

As mentioned I wrote a script that is connecting to a weather API and printing out the result.

Everything works fine when I run it line by line through the interpreter (ESPlorer "Send to ESP- and run "line by line""), but when I execute it via dofile() it cannot connect to the site and fails.

I am confused and hope some of you would find the mistake I am ignoring.

Here is the code:

data= ""
s= net.createConnection(net.TCP, 0)
s:on("receive", function(so, da) data= da end)
s:connect(80, "api.openweathermap.org")
s:send("GET /data/2.5/weather?q=berlin,de&appid=9a3719c191ce0e1e70673f892013647e&units=metric HTTP/1.1\r\nHost: www.api.openweathermap.org\r\n\r\n")
for x in string.gmatch(data, "([^\n]+)") do
    if string.find(x, '"coord"') ~= nil then
        for k,v in pairs(cjson.decode(x)) do
            if k == "main" or k == "weather" then 
            print("++++++"..k.."++++++")
            if type(v) == "table" then
                for kz, vz in pairs(v) do
                    if kz == 1 or kz == 2 then
                        for kd,vd in pairs(vz) do
                            print(kd,vd)
                        end 
                    else print(kz,vz) end
                    end end end
end end end
s:close()

Upvotes: 0

Views: 346

Answers (1)

Marcel Stör
Marcel Stör

Reputation: 23535

Do not use those old 0.9.x pre-built binaries as they're outdated, no longer supported and contain lots of bugs.

Build your own NodeMCU firmware ideally from the dev branch (Espressif SDK 1.5.1).

Then you need to get accustomed to the asynchronous event-driven nature of the NodeMCU firmware. It was a bug in the old SDKs that net.socket:send() was ever blocking (i.e. non-asynchronous).

Hence, you need to process the incoming data in the s:on('receive') callback and you need to wait with sending the request in s:on('connection'). Here's the template:

conn = net.createConnection()
conn:on("receive", function(conn, payload)
    -- processing data
end)
conn:on("connection", function(conn, payload)
    -- conn:send
end)
conn:connect(80, "api.openweathermap.org")

Have a look at the API docs at https://nodemcu.readthedocs.io/en/dev/en/modules/net/.

Side note: there's an HTTP (client) module in the dev branch that simplifies access to remote resources over HTTP.

Upvotes: 1

Related Questions