As the title says... Chat on...

User avatar
By Kenneth
#10621 I'm trying to post data to the thingspeak API. When running below code, everything just works fine.

Code: Select allvalue = 0
conn = net.createConnection(net.TCP, false)
conn:connect(80, "api.thingspeak.com")
conn:send("GET /update?key=REDACTED&field1="..value.." HTTP/1.1\r\nHOST: api.thingspeak.com\r\nConnection: close\r\nAccept: */*\r\n\r\n")
conn:close()
conn = nil


However, I'm trying to wrap this in a function, for easier re-use. Below code doesn't work

Code: Select allfunction send (value)
    conn = net.createConnection(net.TCP, false)
    conn:connect(80, "api.thingspeak.com")
    conn:send("GET /update?key=REDACTED&field1="..value.." HTTP/1.1\r\nHOST: api.thingspeak.com\r\nConnection: close\r\nAccept: */*\r\n\r\n")
    conn:close()
    conn = nil
end
send(0)


And I don't get why. Any thoughts?
User avatar
By Kenneth
#10666 That didn't help, but it came to my mind that I was indeed thinking too procedural. If executed in a function, the connection wasn't yet established when I tried to send data. If I was just executing the statements, I was actually copy'ing them over, so it took enough time for me to copy-paste the send command for the connection to be established.

The working code

Code: Select allfunction send (value)
  conn = net.createConnection(net.TCP, false)
  conn:connect(80, "api.thingspeak.com")
  conn:on("connection", function()
    conn:send("GET /update?key=REDACTED&field1="..value.." HTTP/1.1\r\nHOST: api.thingspeak.com\r\nConnection: close\r\nAccept: */*\r\n\r\n")
  end)
  conn:on("sent",function()
    conn:close()
    conn = nil
  end)
end
send(0)


Thanks, Bydpwhittaker