Skip to content

Access your bulbs through their names instead of ID# in examples

Patrik edited this page Nov 30, 2017 · 1 revision

This is an example provided by @Lakitna on how to access the bulbs through their names rather than device ID#.

# Like we know en love from the examples
lampList = [dev for dev in devices if dev.has_light_control]

# Define the different group names
groupNameList = ['Alpha', 'Beta']

# Make an empty dict to store our groups
groups = {}

# Iterate all group names
for groupName in groupNameList:
    groups[groupName] = []
    
    # Iterate all lamps on the network
    for lamp in lampList:
        # Check if the group name is a partial of the lamp name. By forcing both to be lowercase the check is case insensitive.
        if groupName.lower() in lamp.name.lower():
            groups[groupName].append(lamp)

# Output the group hierarchy
print(groups)

This code will output:

{
    'Alpha': [
            <65545 - Alpha 1 (TRADFRI bulb E27 WS opal 980lm)>,
            <65537 - Alpha 2 (TRADFRI bulb E27 WS opal 980lm)>
        ],
    'Beta': [
            <65539 - Beta 1 (TRADFRI bulb E27 WS opal 980lm)>
        ]
}

After this point, you can use the new hierarchy in your program. For example like this:

for lamp in groups['Alpha']:
    dim_command = lamp.light_control.set_dimmer(254)
    api(dim_command)