Skip to content

Instantly share code, notes, and snippets.

@nfriedly nfriedly/mainIoTF.lua
Last active Oct 28, 2016

Embed
What would you like to do?
Connect ESP8266 to IBM IoT Foundation and publish data via MQTT (NodeMCU Firmware)
-- see https://developer.ibm.com/recipes/tutorials/connect-espressif-esp8266-to-ibm-iot-foundation/ for more information
orgID = "quickstart" -- IoT Foundation organization ID replace this with your own after creating an IoT service in bluemix
broker = "quickstart.messaging.internetofthings.ibmcloud.com" -- IP or hostname of Quickstart IoTF service
mqttPort = 1883 -- MQTT port (default 1883)
userID = "" -- optional. Set to "use-token-auth" for token auth
userPWD = "" -- optional. Put token here for token auth
macID= wifi.sta.getmac():gsub('-','') -- set this manually if needed. Just hex digits, no collons/spaces/dashes/etc.
clientID = "d:quickstart:esp8266:"..macID -- Device ID
count = 0 -- Test number of mqtt_do cycles
mqttState = 0 -- State control
topic = "iot-2/evt/status/fmt/json"
t0 = tmr.time()
-- Wifi credentials
SSID = "<your wifi SSID>" -- <========== Modify this!
wifiPWD = "<your wifi password>" -- <========== Modify this!
function wifi_connect()
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID,wifiPWD)
wifi.sta.connect()
end
function mqtt_do()
count = count + 1 -- tmr.alarm counter
if mqttState < 5 then
mqttState = wifi.sta.status() -- State: Waiting for wifi
wifi_connect()
elseif mqttState == 5 then
print("Starting to connect...")
m = mqtt.Client(clientID, 120, userID, userPWD)
m:on("offline", function(conn)
print ("Checking IoTF server...")
mqttState = 0 -- Starting all over again
end)
m:connect(broker , mqttPort, 0,
function(conn)
print("Connected to " .. broker .. ":" .. mqttPort)
if orgID == "quickstart" then
print("Visit https://quickstart.internetofthings.ibmcloud.com/#/device/" .. macID .. "/sensor/ to see data")
else
print("MAC address is " .. macID);
end
mqttState = 20 -- Go to publish state
end)
elseif mqttState == 20 then
mqttState = 25 -- Publishing…
t1 = tmr.time() - t0
if t1 > 100 then
t1 = 0
t0 = tmr.time()
end
m:publish(topic ,'{"d": {"data":'..t1..'}}', 0, 0, -- or use cjson module for more complex json
function(conn)
-- Print confirmation of data published
print("Sent message #"..count.." data:"..t1)
mqttState = 20 -- Finished publishing -- go back to publish state.
end)
else print("Waiting…"..mqttState)
mqttState = mqttState - 1 -- takes us gradually back to publish state to retry
end
end
tmr.alarm(2, 10000, 1, function() mqtt_do() end) -- send data every 10s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.