我才刚刚开始学习Javascript,并且无法向TP Link HS300智能电源板上的各个插头发送ON / OFF命令。 tplink-smarthome-api文档说,此模型将具有children属性,如果用childId实例化了插件,它将控制与该childId关联的插座。如何向带有childid的开关发出命令?
API文档-https://www.npmjs.com/package/tplink-smarthome-api
这是我的代码,无需指定子代即可开启设备。
const { Client } = require('tplink-smarthome-api');
const fs = require('fs');
const client = new Client();
const name = "Lights"
function getDateTime() {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var day = date.getDate();
day = (day < 10 ? "0" : "") + day;
return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}
function log(message){
date = getDateTime()
msg = `${date} ${name} ${message}\n`
fs.appendFile("/var/www/html/project/lights/log/log.txt",msg, function(err) {
if(err) {
return console.log(err);
}
});
}
// Look for devices, log to console, and turn them on
//client.startDiscovery().on('device-new', (device) => {
// device.getSysInfo().then(console.log);
// device.setPowerState(true);
//});
const plug = client.getDevice({host: '192.168.1.21'}).then((device)=>{
//device.getSysInfo().then(console.log);
});
function turnOn(){
client.getDevice({host: '192.168.1.21'}).then((device)=>{
device.setPowerState(true)
log("turned on.")
});
}
function turnOff(){
client.getDevice({host: '192.168.1.21'}).then((device)=>{
device.setPowerState(false)
log("turned off.")
});
}
function displayStats(stats) {
if(stats.relay_state == 0){
//Turn on
turnOn()
}
}
function toggle(callback){
client.getDevice({host: '192.168.1.21'}).then((device) => {
device.getSysInfo().then(displayStats);
});
}
toggle()
在此先感谢您能提供的任何帮助,
编辑:明白了。
const { Client } = require('tplink-smarthome-api');
const client = new Client();
const plug = client.getDevice({host: '192.168.1.101'}).then((device)=>{
device.setPowerState(true, {childId: 'CHILD_ID'}).then(console.log);
});