Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
86 lines (65 sloc) 2.22 KB
var log = require("log"); log.setLevel("info");
var http = require("http");
var document = require("document");
const APIKEY = "YOUR_WEATHER_API_APIKEY"; // replace with you API key from https://openweathermap.org
const WEATHER_API = "http://api.openweathermap.org/data/2.5/weather";
var data = request.body ? request.body : request.parameters.data;
// if no data received, log it and return an empty object
if (!data){
log.warn("/blog/queues/processor: received empty request body");
return {};
}
//if the incoming data structure is of type string (mqtt message), transform it
var dataObj = {};
if (typeof(data) == "string") {
dataObj = transformData(data);
}else{
dataObj = data;
}
// get the outside temperate from the weather API
var outsideTemperature = getOutideTemperature(dataObj.coordinates);
if (outsideTemperature) {
dataObj.outsideTemperature = outsideTemperature;
}
// persist the data object into scriptr.io's persistent storage
saveToDataStore(dataObj);
// return the data object
return dataObj;
function transformData(data) {
var values = data.split(",");
var dataObj = {};
dataObj.temperature = values[0];
dataObj.pressure = values[1];
dataObj.coordinates = values[2];
dataObj.timestamp = values[3];
return dataObj;
}
function getOutideTemperature(coordinates) {
var latlon = coordinates.split(":");
var requestParams = {
url: WEATHER_API,
params: {
lat: latlon[0],
lon: latlon[1],
appid: APIKEY
}
};
// invoke weather API
var resp = http.request(requestParams);
if (resp.status == "200") {
var body = JSON.parse(resp.body);
return body.main.temp / 10;
}
return undefined;
}
function saveToDataStore(dataObj) {
var dataToPersist = JSON.parse(JSON.stringify(dataObj)); // lazy cloning
dataToPersist["meta.types"] = { // add some metadata about the field types
temperature: "numeric",
pressure: "numeric"
}
var resp = document.save(dataToPersist);
if (resp.metadata.status == "failure") {
log.error("/blog/queues/processor: could not persist data\n" + JSON.stringifyresp.metadata());
}
}