Created
August 5, 2018 13:23
-
-
Save riston/0fa8eb67b7e590ebd4fad19a99014b92 to your computer and use it in GitHub Desktop.
Mongoose OS DHT11 MQTT temperature and humidity reporter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
load('api_config.js'); | |
load('api_events.js'); | |
load('api_gpio.js'); | |
load('api_mqtt.js'); | |
load('api_net.js'); | |
load('api_sys.js'); | |
load('api_esp8266.js'); | |
load('api_dht.js'); | |
load('api_timer.js'); | |
let millisToTurnOff = 30e3; | |
let sleepFor = 60e6; // microseconds | |
let pin = 2; | |
let dht = DHT.create(pin, DHT.DHT11); | |
let tempTopic = Cfg.get('mqtt.user') + '/feeds/home.temperature'; | |
let humTopic = Cfg.get('mqtt.user') + '/feeds/home.humidity'; | |
let getInfo = function() { | |
return JSON.stringify({ | |
total_ram: Sys.total_ram(), | |
free_ram: Sys.free_ram() | |
}); | |
}; | |
let getHumidity = function() { | |
let h = dht.getHumidity(); | |
if (isNaN(h)) { | |
print('Failed to get humidity'); | |
return; | |
} | |
let ok = MQTT.pub(humTopic, JSON.stringify(h), 1); | |
if(ok) { | |
print('sent humidity mqtt'); | |
} else { | |
print('failed humidity mqtt'); | |
} | |
}; | |
let getTemperature = function() { | |
let t = dht.getTemp(); | |
if (isNaN(t)) { | |
print('Failed to get temperature'); | |
return; | |
} | |
let ok = MQTT.pub(tempTopic, JSON.stringify(t), 1); | |
if(ok) { | |
print('sent temperature mqtt'); | |
} else { | |
print('failed temperature mqtt'); | |
} | |
}; | |
MQTT.setEventHandler(function(conn, ev, edata) | |
{ | |
if (ev === MQTT.EV_CONNACK) | |
{ | |
Timer.set(2000 /* milliseconds */, false, function() { | |
getTemperature(); | |
getHumidity(); | |
MQTT.setEventHandler(function() {}, null); | |
}, null); | |
} | |
}, null); | |
Timer.set(millisToTurnOff , false , function() { | |
print("deep sleep", getInfo()); | |
ESP8266.deepSleep(sleepFor); | |
}, millisToTurnOff); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment