Last active
July 2, 2019 08:01
-
-
Save kikermo/bef7821cc1a611c82c6ecaa60acd5037 to your computer and use it in GitHub Desktop.
Simple node js rest service that periodically reads battery and humidity
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
#!/usr/bin/env | |
var express = require('express'); | |
const http = require('http'); | |
var app = express(); | |
var exec = require('exec'); | |
const sensorMac = "<YOUR-DEVICE-MAC>"; | |
const batteryChar = "00002a19-0000-1000-8000-00805f9b34fb"; | |
const batteryHandler = "0x001b"; | |
const humiditySensorHandler = "0x001f"; | |
const humiditySensorChar = "00002a6f-0000-1000-8000-00805f9b34fb"; | |
var sensorOutput = { | |
battery: {}, | |
humidity: {} | |
}; | |
app.get('/readmoisture', function (req, res) { | |
res.json({ | |
humidity: humidityValue, | |
lastRead: lastRead, | |
battery: battery | |
}); | |
}) | |
function readMoistureSensor() { | |
readBleCharacteristic(humiditySensorChar, humiditySensorHandler, function (humidityVal) { | |
if (humidityVal) { | |
sensorOutput.humidity.lastRead = new Date(); | |
sensorOutput.humidity.value = Math.round(parseInt("0x" + humidityVal) * 100 / 256); | |
} | |
}); | |
} | |
function readBattery() { | |
readBleCharacteristic(batteryChar, batteryHandler, function (batteryVal) { | |
if (batteryVal) { | |
sensorOutput.battery.level = Math.round(parseInt("0x" + batteryVal)); | |
sensorOutput.battery.lastRead = new Date(); | |
} | |
}); | |
} | |
function readBleCharacteristic(characteristicUuid, handler, callback) { | |
exec("gatttool -b " + sensorMac + " --char-read " + characteristicUuid + " -t random --handle=" + handler, function (err, out, code) { | |
if (err instanceof Error) | |
throw err; | |
process.stderr.write(err); | |
process.stdout.write(out); | |
console.log(out); | |
let output = out.replace('Characteristic value\/descriptor: ', '').trim(); | |
callback(output); | |
}); | |
} | |
setInterval(readMoistureSensor, 10000); | |
setInterval(readBattery, 5000); | |
var server = app.listen(80, function () { | |
var host = server.address().address | |
var port = server.address().port | |
console.log("Simple rest service for iot listening at http://%s:%s", host, port) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment