UNPKG

node-red-contrib-switchbot-devices

Version:

Simple node to get list of Switchbot devices and their status with Node-RED

51 lines (46 loc) 1.82 kB
const axios = require("axios") const HOST = "https://api.switch-bot.com/v1.0/devices" const METHOD_GET = "get" module.exports = function (RED) { function GetDevicesNode(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 token input if (!token) { node.error("Token can't be empty!", {}) node.status({ fill: "yellow", shape: "dot", text: "Empty Token!" }) return } node.status({ fill: "green", shape: "ring", text: "Requesting!" }) var requestConfig = { method: METHOD_GET, url: HOST, headers: { Authorization: token } } // Get list devices axios(requestConfig).then((res) => { if (res.data.statusCode == 100) { var listDevices = res.data.body if (listDevices.deviceList === undefined && listDevices.infraredRemoteList === undefined) { node.status({ fill: "yellow", shape: "dot", text: "Undefined response!" }) } else if (listDevices.deviceList.length == 0 && listDevices.infraredRemoteList.length == 0) { node.status({fill: "grey", shape: "dot", text: "Empty list"}) } else { node.status({fill: "green", shape: "dot", text: "Requested!"}) } msg.payload = listDevices } }).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-list", GetDevicesNode) }