Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Webseiten/URLs abfragen mit Fehlerbehandlung, siehe:
// http://forum.iobroker.net/viewtopic.php?f=21&t=4259&p=40890&hilit=request#p40880
var logOn = true; // Skript Logausgabe ein- (true) / ausschalten (false). Fehler werden immer ausgegeben.
var http = require('http'); // Node Module http verwenden
var deviceParams = ["level.color.hue", "level.color.saturation", "level.dimmer", "switch"];
var objectId = 'rest.0.room0.rgb';
deviceParams.forEach(function(param) {
var internalDeviceId = objectId + '.' + param;
var deviceUrl = '/api/v1/state';
on({id: internalDeviceId, change: 'any'}, function (obj) {
if(obj.newState.val) {
doRequest(deviceUrl, "on");
} else {
doRequest(deviceUrl, "off");
}
});
});
// URL, die abgefragt, bzw. gesendet werden soll:
var options = {
host: '192.168.178.80',
port: '80',
path: '/api/v1/state', // will be overriden on call
method: 'POST' // in der Regel: "GET"
};
// Funktionen:
function doRequest(baseUrl, state) {
log('REST HTTP call');
var bodyData = {'state':"OFF",'brightness':0,'color':{'mode': 'hsv', 'h':0,'s':0,'v':0},'mode':"SOLID"};
if(getState("rest.0.room0.rgb.switch").val > 0) {
var h = getState("rest.0.room0.rgb.level.color.hue").val;
var s = getState("rest.0.room0.rgb.level.color.saturation").val;
var v = getState("rest.0.room0.rgb.level.dimmer").val;
bodyData = {'state':"ON",'brightness':100,'color':{'mode': 'hsv', 'h':h,'s':s,'v':v},'mode':"SOLID"};
}
if(logOn) log(bodyData); // Statuscode
if(logOn) log(JSON.stringify(bodyData)); // Statuscode
options.headers = {
'content-type': 'application/json',
'content-length': JSON.stringify(bodyData).length
}
if(logOn) log('OPTIONS: ' + JSON.stringify(options));
var req = http.request(options, function(res) {
if(logOn) log('STATUS: ' + res.statusCode); // Statuscode
if(logOn) log('HEADERS: ' + JSON.stringify(res.headers)); // Header (Rückmeldung vom Webserver)
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
var chunkLine = 0;
res.on('data', function(chunk) {
chunkLine = chunkLine + 1;
if(logOn) log("Zeilennummer: " + chunkLine+ " ,Inhalt: " + chunk);
// Hier können die einzelnen Zeilen verarbeitet werden...
bodyChunks.push(chunk);
}).on('end', function() {
if(logOn) log("ARRAY mit den einzelnen Zeilen: " + bodyChunks);
if(logOn) log("ARRAY Länge: " + bodyChunks.length);
var body = Buffer.concat(bodyChunks);
if(logOn) log('BODY: ' + body);
// ...und/oder das Gesamtergebnis.
var jsonObject = JSON.parse(body);
});
});
req.on('error', function(e) { // Fehler abfangen
log('ERROR: ' + e.message,"warn");
});
req.write(JSON.stringify(bodyData));
req.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.