首页 > 解决方案 > Hue api id 识别

问题描述

我正在通过javascript制作我自己的飞利浦色调控制器。我正在尝试识别组和轻 ID。但我不知道如何获得组或灯光的 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);
                        }
                    }

                }
            };
        }
    }

标签: javascriptjsonapi

解决方案


您在 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.
}

推荐阅读