Skip to content

Commit

Permalink
Extract common device node logic (#34)
Browse files Browse the repository at this point in the history
* Cleanup code

* Cleanup code

* Extract common device node logic
  • Loading branch information
ottoszika authored Dec 10, 2019
1 parent 5dc6e04 commit 03c56aa
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 22 deletions.
25 changes: 3 additions & 22 deletions src/generic-device/generic-device.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var eWeLinkConnect = require('../utils/ewelink-connect');
const eWeLinkConnect = require('../utils/ewelink-connect');

/**
* Generic device node.
Expand All @@ -13,27 +13,8 @@ module.exports = (RED) => {
// Create the node
RED.nodes.createNode(this, config);

// Clean up device ID
const deviceId = config.deviceId ? config.deviceId.trim() : '';

// Log in to eWeLink
eWeLinkConnect.login(RED, this, config).then(connection => {
// Once logged in we can listen to inputs
this.on('input', (msg) => {
let { method, params } = msg.payload;

// Set params to empty array if not set
params = params || [];

// First parameter should be always the device ID
params.unshift(deviceId);

// Call dynamically the method
connection[method].apply(connection, params).then(result => {
this.send({ payload: result });
}).catch(error => this.error(error));
})
}).catch(error => this.error(error));
// Initialize device node
eWeLinkConnect.initializeDeviceNode(RED, this, config);
}

// Register node
Expand Down
31 changes: 31 additions & 0 deletions src/utils/ewelink-connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,37 @@ module.exports = {
});
},

/**
* Initialize device node.
*
* @param {object} RED The NodeRED instance.
* @param {object} node The current node.
* @param {object} config The node configuration.
* @param {string} method The method to call on the device.
* @param {array} params The parameters of the method.
*/
initializeDeviceNode(RED, node, config, method, params) {
// Clean up device ID
const deviceId = config.deviceId ? config.deviceId.trim() : '';

// Log in to eWeLink
this.login(RED, node, config).then(connection => {
// Once logged in we can listen to inputs
node.on('input', (msg) => {
method = method || msg.payload.method;
params = params || msg.payload.params || [];

// First parameter should be always the device ID
params.unshift(deviceId);

// Call dynamically the method
connection[method].apply(connection, params).then(result => {
node.send({ payload: result });
}).catch(error => node.error(error));
})
}).catch(error => node.error(error));
},

/**
* Set node status to 'connecting'.
*
Expand Down

0 comments on commit 03c56aa

Please sign in to comment.