Skip to content

Instantly share code, notes, and snippets.

@wybiral
Created August 16, 2019 00:21
Show Gist options
  • Save wybiral/5388efc0d832da2fdee1828aeffc1204 to your computer and use it in GitHub Desktop.
Save wybiral/5388efc0d832da2fdee1828aeffc1204 to your computer and use it in GitHub Desktop.
Testing the WebThings API with Espruino
const i2c = new I2C();
i2c.setup({sda:B9,scl:B8});
const bme = require("BME680").connectI2C(i2c);
const wifi = require("Wifi");
const thing = {
temperature: 0,
humidity: 0,
gas: 0,
pressure: 0,
description: {
"@context": "https://iot.mozilla.org/schemas/",
"@type": ["TemperatureSensor"],
"id": url,
"title": "Environment",
"description": "Sense the weather",
"properties": {
"temperature": {
"@type": "TemperatureProperty",
"type": "integer",
"unit": "degree fahrenheit",
"title": "Temperature",
"description": "Current temperature",
"links": [{"href": "/things/weather/properties/temperature"}]
},
"humidity": {
"@type": "LevelProperty",
"type": "integer",
"unit": "percent",
"readOnly": true,
"title": "Humidity",
"description": "Current humidity",
"links": [{"href": "/things/weather/properties/humidity"}]
},
"gas": {
"type": "integer",
"readOnly": true,
"title": "Gas (ohms)",
"description": "Current gas resistance",
"links": [{"href": "/things/weather/properties/gas"}]
},
"pressure": {
"type": "integer",
"readOnly": true,
"title": "Pressure (hPa)",
"description": "Current pressure",
"links": [{"href": "/things/weather/properties/pressure"}]
}
}
}
};
function success(res, obj) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(obj));
}
function router(req, res) {
if (req.url === '/things/weather') {
return success(res, thing.description);
}
if (req.url === '/things/weather/properties/temperature') {
return success(res, {temperature: thing.temperature});
}
if (req.url === '/things/weather/properties/humidity') {
return success(res, {humidity: thing.humidity});
}
if (req.url === '/things/weather/properties/gas') {
return success(res, {gas: thing.gas});
}
if (req.url === '/things/weather/properties/pressure') {
return success(res, {pressure: thing.pressure});
}
}
function createServer(ip){
thing.id = 'http://' + ip + '/things/weather';
require("http").createServer(router).listen(80);
console.log('Serving at ' + thing.id);
}
setInterval(() => {
const x = bme.get_sensor_data();
thing.temperature = ((x.temperature * (9.0 / 5.0)) + 32.0) | 0;
thing.humidity = (x.humidity) | 0;
thing.gas = (x.gas_resistance) | 0;
thing.pressure = (x.pressure) | 0;
bme.perform_measurement();
}, 1000);
console.log('Connecting...');
wifi.stopAP();
wifi.connect('ssid', {'password':'password'}, () => {
wifi.getIP((err, x) => {
if (err !== null) {
console.log(err);
} else {
createServer(x.ip);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment