node-red-contrib-switchbot-devices
Version:
Simple node to get list of Switchbot devices and their status with Node-RED
54 lines (51 loc) • 1.84 kB
JavaScript
const axios = require('axios')
const HOST = "https://api.switch-bot.com/v1.0/devices/"
const METHOD_GET = "get"
module.exports = function (RED) {
function GetStatus(config) {
RED.nodes.createNode(this, config)
var node = this
node.status({})
this.acc = RED.nodes.getNode(config.acc)
var token = this.acc.credentials.token
node.on("input", function (msg) {
// check msg.deviceid
if (!msg.deviceid) {
node.status({ fill: "yellow", shape: "dot", text: "Empty Device ID!" })
node.error("Input a specific device ID in inject node with a string type msg.deviceid!",{})
return
}
// check token input
if (!token) {
node.status({ fill: "yellow", shape: "dot", text: "Empty Token!" })
node.error("Token can't be empty!", {})
return
}
node.status({ fill: "green", shape: "ring", text: "Requesting!" })
var requestConfig = {
method: METHOD_GET,
url: HOST + `${msg.deviceid}/status`,
headers: { Authorization: token }
}
axios(requestConfig).then(res => {
if(res.data.statusCode == 100){
// Check empty object
if(!Object.keys(res.data.body).length){
node.status({ fill: "yellow", shape: "dot", text: "Empty!" })
} else {
node.status({ fill: "green", shape: "dot", text: "Requested!" })
}
msg.payload = res.data.body
}
}).catch(err => {
node.status({ fill: "red", shape: "dot", text: "Wrong token!" })
msg.payload = 'Request failed with status code 401(wrong token)'
}).then(() => {
if(msg.payload){
node.send(msg)
}
})
})
}
RED.nodes.registerType("switchbot-status", GetStatus)
}