/ BLE_Colorific / colorific.py
colorific.py
1 # SPDX-FileCopyrightText: 2019 Tony DiCola for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 # Smart Bulb Colorific! Control With Bluez 6 # Author: Tony DiCola 7 # 8 # This script will cycle a Smart Bulb Colorific! Bluetooth Low Energy light bulb 9 # through a rainbow of different hues. 10 # 11 # Dependencies: 12 # - You must install the pexpect library, typically with 'sudo pip install pexpect'. 13 # - You must have bluez installed and gatttool in your path (copy it from the 14 # attrib directory after building bluez into the /usr/bin/ location). 15 # 16 # License: Released under an MIT license: http://opensource.org/licenses/MIT 17 import colorsys 18 import math 19 import sys 20 import time 21 22 import pexpect 23 24 25 # Configuration values. 26 HUE_RANGE = (0.0, 1.0) # Tuple with the minimum and maximum hue values for a 27 # cycle. Stick with 0 to 1 to cover all hues. 28 SATURATION = 1.0 # Color saturation for hues (1 is full color). 29 VALUE = 1.0 # Color value for hues (1 is full value). 30 CYCLE_SEC = 5.0 # Amount of time for a full cycle of hues to complete. 31 SLEEP_SEC = 0.05 # Amount of time to sleep between loop iterations. 32 33 34 # Get bulb address from command parameters. 35 if len(sys.argv) != 2: 36 print ('Error must specify bulb address as parameter!') 37 print ('Usage: sudo python colorific.py <bulb address>') 38 print ('Example: sudo python colorific.py 5C:31:3E:F2:16:13') 39 sys.exit(1) 40 bulb = sys.argv[1] 41 42 # Run gatttool interactively. 43 gatt = pexpect.spawn('gatttool -I') 44 45 # Connect to the device. 46 gatt.sendline('connect {0}'.format(bulb)) 47 gatt.expect('Connection successful') 48 49 # Setup range of hue value and start at minimum hue. 50 hue_min, hue_max = HUE_RANGE 51 hue = hue_min 52 53 # Enter main loop. 54 print ('Press Ctrl-C to quit.') 55 last = time.time() 56 while True: 57 # Get amount of time elapsed since last update, then compute hue delta. 58 now = time.time() 59 hue_delta = (now-last)/CYCLE_SEC*(hue_max-hue_min) 60 hue += hue_delta 61 # If hue exceeds the maximum wrap back around to start from the minimum. 62 if hue > hue_max: 63 hue = hue_min+math.modf(hue)[0] 64 # Compute 24-bit RGB color based on HSV values. 65 r, g, b = map(lambda x: int(x*255.0), colorsys.hsv_to_rgb(hue, SATURATION, 66 VALUE)) 67 # Set light color by sending color change packet over BLE. 68 gatt.sendline('char-write-cmd 0x0028 58010301ff00{0:02X}{1:02X}{2:02X}'.format(r, g, b)) 69 # Wait a short period of time and setup for the next loop iteration. 70 time.sleep(SLEEP_SEC) 71 last = now