Hue api id identification



我正在通过javascript制作我自己的philips色调控制器。我正在努力识别群体和轻身份证。但我不知道如何获得组或灯光的JSON id。

我得到了一个JSON格式的http答案,如下所示:

{
"1": {
"name": "Woonkamer",
"lights": [
"2",
"1",
"4"
],
"sensors": [],
"type": "Room",
"state": {
"all_on": true,
"any_on": true
},
"recycle": false,
"class": "Living room",
"action": {
"on": true,
"bri": 144,
"hue": 12057,
"sat": 143,
"effect": "none",
"xy": [
0.502,
0.4204
],
"ct": 447,
"alert": "select",
"colormode": "xy"
}
},
"2": {
"name": "keuken",
"lights": [
"3"
],
"sensors": [],
"type": "Room",
"state": {
"all_on": true,
"any_on": true
},
"recycle": false,
"class": "Kitchen",
"action": {
"on": true,
"bri": 254,
"ct": 366,
"alert": "select",
"colormode": "ct"
}
},

例如,我对访问类型和名称没有问题,但我不知道如何访问每个部分开头写的id。我不能只得到第一个索引,因为然后我只得到其他对象,比如名称等。

我当前的功能是这样的,我可以访问房间名称,但我也需要房间id。请记住,这段代码看起来很糟糕,因为我对JS 还很陌生

function getGroups()
{
var url = "https://"+ipadress+"/api/"+username+"/groups";
request.open("GET", url);
request.setRequestHeader("Content-Type", "application/json");
request.send();
request.onreadystatechange = () => {
if (request.readyState === XMLHttpRequest.DONE) {
const res = JSON.parse(request.responseText);
for(var i = 1; i < Object.keys(res).length; i++)
{
if(res[i] != null)
{
if(res[i].type == "Room")
{
var name = res[i].name;
document.getElementById("light_container").style.display = "block";
var onoff = document.createElement('input');
onoff.setAttribute('type', 'button');
onoff.setAttribute('id', name);
onoff.setAttribute('value', name); //need to change this to dynamic function that reads the hue
onoff.setAttribute('onclick', 'changeState("/groups/'+name+'/action")') //need to make change state function
document.body.appendChild(onoff);
}
}
}
};
}
}

API响应中包含的是一个对象。现在你只访问它的值,还没有访问它的键。您可以更改for循环的工作方式,改为使用对象键作为索引。那么i将是您要查找的房间id。

for (var i in res) {
....  // everything inside the for loop can stay the same
// but now "i" is the room id you are looking for.
}

相关内容

  • 没有找到相关文章

最新更新