Skip to content

Instantly share code, notes, and snippets.

@aderbas
Created April 8, 2019 14:58
Show Gist options
  • Save aderbas/0684c27026435d5c6af2cf7c5e8d3989 to your computer and use it in GitHub Desktop.
Save aderbas/0684c27026435d5c6af2cf7c5e8d3989 to your computer and use it in GitHub Desktop.
Thingsboard Telemetry MQTT for Wemos D1 Mini
-- send temperature telemetry (Thingsboard.io)
-- require module DS18B20 for temp
local DS18B20 = require "ds18b20"
-- ESP8266 pin
local TEMP_PIN = 2
-- setup DS18B20
DS18B20.setup(TEMP_PIN)
-- flag connected
local connected = false
--MQTT params
local mqtt_settings = {
module = "ESP8266_"..node.chipid(),
ip = "host",
port = 1883,
token = "<device token>"
}
-- loop to send telemetry
local function send_telemetry()
if connected == true then
tmr.alarm(2, 10000, tmr.ALARM_AUTO, function()
temp = DS18B20.read(nil, 'C')
--print("Actual temp: "..temp)
m:publish("v1/devices/me/telemetry", string.format("{\"temperature\":%d}", math.floor(temp)), 0, 0)
end)
end
end
-- client mqtt
m = mqtt.Client(mqtt_settings.module, 41, mqtt_settings.token, "password")
-- handler error, try to reconnect
function handler_mqtt_error(client, reason)
print("Connection fail reason: "..reason)
connected = false
tmr.create():alarm(10 * 1000, tmr.ALARM_SINGLE, do_mqtt_connect)
end
-- handler connected
function handler_mqtt_connect(client)
print("MQTT Connected!")
connected = true
send_telemetry()
end
-- try connect broker
function do_mqtt_connect()
print("Connecting "..node.chipid().." to MQTT broker...")
m:connect(mqtt_settings.ip, mqtt_settings.port, handler_mqtt_connect, handler_mqtt_error)
end
-- call connect
do_mqtt_connect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment