Examples

Basic Example

Simple blinky light example demonstrating making a connection to a light from its MAC address and making it turn off then on again.

Note

Do not forget to put the light in pairing mode before first connection!

 1import asyncio
 2from bleak import BleakScanner
 3import HueBLE
 4
 5
 6async def main():
 7
 8    # Address of light to connect to
 9    address = "F6:9B:48:A4:D2:D8"
10
11    # Obtain the BLEDevice from bleak
12    device = await BleakScanner.find_device_by_address(address)
13
14    # Initialize the light object
15    light = HueBLE.HueBleLight(device)
16
17    # Optionally we could call connect but it will be called automatically
18    # on the first request to the light. You might want to call this if
19    # you want to subscribe to state changes without changing the lights state.
20    # await light.connect()
21
22    # Will automatically connect to the light and turn it off
23    await light.set_power(False)
24
25    # Wait
26    await asyncio.sleep(5)
27
28    # Turn the light back on again
29    await light.set_power(True)
30
31if __name__ == "__main__":
32    asyncio.run(main())

Complex Example

Demonstration program which implements the majority of the features of the module using a push based approach.

  • ✔️ Scanning and detection of Hue lights

  • ✔️ Connecting to the light

  • ✔️ Reading values from the light

  • ✔️ Setting parameters of the light
    • 💡 Power

    • 🌗 Brightness

    • 🌡️ Colour Temp

    • 🌈 XY Colour

    • 🌟 Effects

  • ✔️ Notifications of state changes to the light via push approach

Note

Do not forget to put the light in pairing mode before first connection!

  1import asyncio
  2import bleak
  3import logging
  4import sys
  5
  6# Allows for reading and writing to the console at the same time
  7# pip3 install aioconsole
  8from aioconsole import ainput
  9from HueBLE import HueBleLight, discover_lights, EffectType
 10
 11
 12# Ask if debug log is wanted
 13while True:
 14
 15    print("Show debug info? [Y/N]")
 16    response = input().lower()
 17
 18    if response == "y":
 19        logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
 20        break
 21
 22    elif response == "n":
 23        break
 24
 25# Global variable for the light
 26light = None
 27
 28
 29def light_state_callback():
 30    """Callback which is run when the light notified us of a state change."""
 31    global light
 32
 33    print("==== REMOTE STATE CHANGE DETECTED ====")
 34    print(f"Light power state: {light.power_state}")
 35    print(f"Light brightness: {light.brightness}")
 36    print(f"Is colour temp mode active: {light.colour_temp_mode}")
 37    print(f"Light colour temperature: {light.colour_temp}")
 38    print(f"Light XY colour: {light.colour_xy}")
 39    print(f"Light Effect/Speed: {light.effect}")
 40    print("==== END OF STATE CHANGE REPORT ====")
 41
 42
 43async def main():
 44    """Main program loop."""
 45    global light
 46
 47    print("Looking for lights...")
 48    # scanner = BleakScanner()
 49    lights = await discover_lights()
 50
 51    # If we have found any lights
 52    if (len(lights)) != 0:
 53
 54        # Ask the user to select a light
 55        print("Which light would you like to connect to?")
 56        for i in range(1, len(lights) + 1):
 57            light = lights[i - 1]
 58            print(f"""{i}. "{light.name}" with MAC "{light.address}""")
 59
 60        # Connect to the selected light
 61        ble_device = lights[int(await ainput("> ")) - 1]
 62        light = HueBleLight(ble_device)
 63        await light.connect()
 64
 65        # Subscribe to state changes
 66        light.add_callback_on_state_changed(light_state_callback)
 67
 68        # Prompt user for action
 69        while True:
 70            print("What action would you like to perform?")
 71            print(
 72                "1. Turn On\n"
 73                "2. Turn Off\n"
 74                "3. Set brightness\n"
 75                "4. Set colour temp\n"
 76                "5. Set XY colour\n"
 77                "6. Set Colour Effect\n"
 78                "7. Set Temperature Effect\n"
 79                "8. View info\n"
 80                "9. Exit"
 81            )
 82
 83            action = int(await ainput("> ")) - 1
 84
 85            # Perform requested action
 86            try:
 87                match action:
 88
 89                    # Turn on
 90                    case 0:
 91                        await light.set_power(True)
 92
 93                    # Turn off
 94                    case 1:
 95                        await light.set_power(False)
 96
 97                    # Set brightness
 98                    case 2:
 99                        print("Enter brightness value (0-255)")
100                        await light.set_brightness(int(await ainput()))
101
102                    # Set colour temp
103                    case 3:
104                        print("Enter colour temp (153-500)")
105                        await light.set_colour_temp(int(await ainput()))
106
107                    # Set XY colour
108                    case 4:
109                        print("Enter X value of colour (0.0-1.0)")
110                        x = float(await ainput())
111                        print("Enter Y value of colour (0.0-1.0)")
112                        y = float(await ainput())
113                        await light.set_colour_xy(x, y)
114                    # Set Colour Effect
115                    case 5:
116                        print("Enter X value of colour (0.0-1.0)")
117                        x = float(await ainput())
118                        print("Enter Y value of colour (0.0-1.0)")
119                        y = float(await ainput())
120                        print("Possible Effects:")
121                        for effect in EffectType:
122                            print(f"({effect.name}: {effect.value})")
123                        print("Enter id of effect")
124                        effect_id = int(await ainput())
125                        print("Enter speed of effect (0 - 255)")
126                        effect_speed = int(await ainput())
127                        print("Enter brightness (0 - 255)")
128                        brightness = int(await ainput())
129                        await light.set_colour_effect(x, y, brightness, EffectType(effect_id), effect_speed)
130                    # Set Temperature Effect
131                    case 6:
132                        print("Enter colour temp (153-500)")
133                        temperature = float(await ainput())
134                        print("Possible Effects:")
135                        for effect in EffectType:
136                            print(f"({effect.name}: {effect.value})")
137                        print("Enter id of effect")
138                        effect_id = int(await ainput())
139                        print("Enter speed of effect (0 - 255)")
140                        effect_speed = int(await ainput())
141                        print("Enter brightness (0 - 255)")
142                        brightness = int(await ainput())
143                        await light.set_temperature_effect(temperature, brightness, EffectType(effect_id), effect_speed)
144                    # Print all light metadata
145                    case 7:
146                        # Poll all values from the light
147                        await light.poll_state()
148                        print(f"Light name: {light.name}")
149                        print(f"Light address: {light.address}")
150                        print(f"Light manufacturer: {light.manufacturer}")
151                        print(f"Light model: {light.model}")
152                        print(f"Supports on/off: {light.supports_on_off}")
153                        print(f"Supports brightness:" f" {light.supports_brightness}")
154                        print(f"Supports colour temp:" f" {light.supports_colour_temp}")
155                        print(f"Supports XY colour: {light.supports_colour_xy}")
156                        print(f"Supports Effects: {light.supports_effects}")
157                        print(f"Light firmware: {light.firmware}")
158                        print(f"Light Zigbee address: {light.zigbee_address}")
159                        print(f"Light power state: {light.power_state}")
160                        print(f"Light brightness: {light.brightness}")
161                        print(
162                            f"Is colour temp mode active:" f" {light.colour_temp_mode}"
163                        )
164                        print(f"Light colour temperature: {light.colour_temp}")
165                        print(f"Light minimum mireds: {light.minimum_mireds}")
166                        print(f"Light maximum mireds: {light.maximum_mireds}")
167                        print(f"Light colour XY: {light.colour_xy}")
168                        print(f"Light effects: {light.effect}")
169
170                    case 8:
171                        break
172
173            # Warn about pairing errors.
174            except bleak.BleakError as bleak_error:
175                if "Insufficient Authentication" in str(bleak_error):
176                    print(
177                        "Failed to pair to light. Make sure light is"
178                        " in pairing mode!\n"
179                        "If this does not resolve the issue try pairing"
180                        " using your OS."
181                    )
182
183    else:
184        print("No lights found!")
185
186    print("Goodbye :)")
187
188
189if __name__ == "__main__":
190    asyncio.run(main())