Skip to content

Instantly share code, notes, and snippets.

@hyhilman
Created May 7, 2018 13:46
Show Gist options
  • Save hyhilman/e78d04fa47f03373e19d02f7e5d784a3 to your computer and use it in GitHub Desktop.
Save hyhilman/e78d04fa47f03373e19d02f7e5d784a3 to your computer and use it in GitHub Desktop.
simple coap handling when server is down(timeout)
var sensorLib = require("node-dht-sensor");
var temp = {
read: function() {
var a = sensorLib.read(11,4);
return a.temperature.toFixed(1);
}
};
var hum = {
read: function() {
var b = sensorLib.read(11,4);
return b.humidity.toFixed(1);
}
};
var coapp = function () {
const coap = require('coap')
const cron = require('node-cron');
var payload = {
protocol: "coap",
timestamp: new Date().toISOString(),
topic: "dht/pi2A",
sensor: {
tipe: "esp8266",
index: "cocoap",
ip: "192.168.42.42",
module: "dht11"
},
humidity: {
value: hum.read(),
unit: "%"
},
temperature: {
value: temp.read(),
unit: "celcius"
}
}
var req = coap.request({host: '192.168.42.101', port: '5683', pathname: '/r/dht/pi2A', method: 'post', retrySend: 0})
req.write(JSON.stringify(payload))
req.on("response", (res) => {console.log(res)})
// err has two attribtues, name and message, this CoaP library based on HTTP connection
// using following answer to catch the error
// error catch : https://stackoverflow.com/questions/4328540/how-to-catch-http-client-request-exceptions-in-node-js
// error prototype : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype
req.on("error", (err) => {
console.log(err.message);
console.log("Sending data to backup server")
var reqOnBackupServer = coap.
request({
host: '192.168.42.100',
port: '5683',
pathname: '/r/backup/dht/pi2A/',
method: 'post'
})
reqOnBackupServer.on("response", (res) => {
console.log("Success sending to backup server")
process.exit(0)
})
reqOnBackupServer.write(JSON.stringify(payload))
reqOnBackupServer.end()
})
req.end()
}
module.exports = coapp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment