def put(self, request): service_ip = socket.gethostbyname(socket.gethostname()) client_ip = self.get_client_ip(request) client_id = request.data.get('client_id', 'Unknown') # Figure out how the color is specified c = Converter() if 'rgb' in request.data: r, g, b = request.data['rgb'] xy = c.rgb_to_xy(r, g, b) elif 'hex' in request.data: xy = c.hex_to_xy(request.data['hex']) hex_color = c.xy_to_hex(*xy) # Log the request if a database is present if settings.DATABASE_FOUND: ce = ChangeEvent(service_ip=service_ip, client_ip=client_ip, client_id=client_id, color=hex_color) ce.save() # There should probably be a throttle in place, but I can control # that elsewhere in the demo if not settings.BRIDGE_MOCK: self.bridge().set_light(settings.BRIDGE_LIGHT, 'xy', xy) return Response()
def sync(self): try: # Instantiate DominantColor dc = DominantColor(self.fullscreen, self.ignore_white, self.ignore_black) # Get the dominant color on the primary display rgb_color = dc.get_dominant_color() # Instantiate the rgb to xy color Converter class color_converter = Converter(GamutC) # Convert the dominant color from rgb to xy xy_color = color_converter.rgb_to_xy(rgb_color[0], rgb_color[1], rgb_color[2]) # Be verbose about what we're doing if self.verbose is True: print(f'RGB{rgb_color} -- XY{xy_color}') print( f'Fullscreen: {self.fullscreen}\nInterval: {self.interval}\nTransition: {self.transition}\n' f'Ignore White Pixels: {self.ignore_white}\nIgnore Black Pixels: {self.ignore_black}\n' ) # Change the color of the light(s) for light in self.lights_list: self.bridge.lights[light].state(xy=[xy_color[0], xy_color[1]], transitiontime=int( self.transition * 0.001)) except TypeError: # Not enough non-black or non-white pixels to update pass
def create_palette(self): gradient_steps = 100 gradient = list(Color("red").range_to(Color("green"), gradient_steps)) converter = Converter(GamutC) return [ converter.rgb_to_xy(color.red, color.green, color.blue) for color in gradient ]
def hex(self, hexStr): red = int(hexStr[1:3], 16) green = int(hexStr[3:5], 16) blue = int(hexStr[5:], 16) converter = Converter(GamutC) xy = converter.rgb_to_xy(red, green, blue) print(xy) self.b.lights(self.lightId, 'state', xy=xy)
def change_group_color(bridge, group, color): hue_group = get_group_name(bridge, group) if hue_group.islight = 0: LOGGER.debug("This is the hue group: {}".format(hue_group[0])) color_rgb = webcolors.html5_parse_legacy_color(unicode(color)) converterc = Converter(GamutC) color_xy = converterc.rgb_to_xy(*color_rgb) bridge.set_group(hue_group[0], 'xy', *color_xy) LOGGER.debug("Setting group {} to color {}".format(hue_group[0], *color_rgb)) return hue_group[0]
def convert(rgb_values): if type(rgb_values) != str: (r, g, b) = rgb_values.decode("utf-8").split(',') else: (r, g, b) = rgb_values.split(',') r = int(r) g = int(g) b = int(b) converter = Converter() print(r, " ", g, " ", b) if r == 255 and b == 255 and g == 255: saturation_val = 0 [x, y] = converter.rgb_to_xy(r, g, b) else: saturation_val = 255 [x, y] = converter.rgb_to_xy(r, g, b) return x, y, saturation_val
def set_color(self, color_name): try: self.connect() except PhueException: logging.info("Server unable to connect to the Hue Light") return "I'm sorry, but I cannot connect to the Hue Light." \ "Please try again later." rgb_values = getColor(color_name) if rgb_values is None: logging.info("Color " + color_name + " was not recognized") return "I'm sorry, but I don't recognize " \ "the color \"{}\".".format(color_name) (r, g, b) = rgb_values.decode("utf-8").split(',') r = int(r) g = int(g) b = int(b) converter = Converter() print(r, " ", g, " ", b) if r == 255 and b == 255 and g == 255: saturation_val = 0 [x, y] = converter.rgb_to_xy(r, g, b) else: saturation_val = 255 correction_value = 1.3 r = ((r / 255) ** (1 / correction_value)) g = ((g / 255) ** (1 / correction_value)) b = ((b / 255) ** (1 / correction_value)) [x, y] = converter.rgb_to_xy(r, g, b) try: self.light.xy = (x, y) self.light.saturation = saturation_val logging.info("The light was changed to the color " + color_name) return "The light was changed to the color \"{}\"."\ .format(clean_name(color_name)) except PhueException: logging.info("Server unable to connect to the Hue Light") return "I'm sorry, but I cannot connect to the Hue Light." \ "Please try again later."
def process(self, inport, msg): hueUser = "******" bridge = Bridge("10.0.0.159", hueUser) converter = Converter() # Convert farbgeber to Hue xy v1xy = converter.rgb_to_xy(msg.data['v1'][0], msg.data['v1'][1], msg.data['v1'][2]) cxy = converter.rgb_to_xy(msg.data['c'][0], msg.data['c'][1], msg.data['c'][2]) contrasted = True # Send to all lights. First light found gets contrast color for lightId in bridge.lights(): if contrasted: bridge.lights[lightId].state(xy=v1xy) contrasted = False else: contrasted = True bridge.lights[lightId].state(xy=cxy) # Send light status out self.send('out', bridge.lights()) self.ack(msg)
def set_hue(self, value): logging.info("Bulb hue value: %s", value) if self.accessory_state == 1: self.hue = value converter = Converter() rgb_tuple = self.hsv_to_rgb( self.hue, self.saturation, self.brightness) if len(rgb_tuple) == 3: xy = converter.rgb_to_xy(rgb_tuple[0], rgb_tuple[1], rgb_tuple[2]) httpx.put(f"http://127.0.0.1:8000/things/{self.thing_id}/properties/color", json={"color": {"x": xy[0], "y": xy[1]}}) else: self.hue = value
class LightController: def __init__(self, bridgeAddress): self.bridge = Bridge(bridgeAddress) self.lights = self.bridge.get_light_objects('name') self.converter = Converter() def setLight(self, light, r, g, b): try: xy = self.converter.rgb_to_xy(r, g, b) except ZeroDivisionError: xy = [1 / 3, 1 / 3] finally: self.lights[light].xy = xy
def set_bulbs_to_color(self, colortuple, bri, transition_time=100, gamut="gamutB"): converter = Converter(HueColor.gamuts[gamut]) self._connect() lights = self.huebridge.get_light_objects('name') for bulb in self.bulbs: logging.debug(f"Now setting {bulb} to {colortuple}") target = lights[bulb] color = converter.rgb_to_xy(*colortuple) target.transitiontime = transition_time target.xy = color target.brightness = bri # Sleep a little bit to prevent flooding the bridge time.sleep(0.3) logging.info("Done setting colors")
def set_color(self, color_name): try: self.connect() except PhueException: return "I'm sorry, but I cannot connect to the Hue Light." \ "Please try again later." rgb_values = self.name_to_color.convert(color_name) if rgb_values is None: return "I'm sorry, but I don't recognize " \ "the color {}".format(color_name) (r, g, b) = rgb_values converter = Converter() [x, y] = converter.rgb_to_xy(r, g, b) try: self.light.xy = (x, y) return "The light was changed to the color {}."\ .format(clean_name(color_name)) except PhueException: return "I'm sorry, but I cannot connect to the Hue Light." \ "Please try again later."
frame = stream.read() print(frame.shape) # crop image area for TV screen print(img_x, img_y, img_w, img_h) crop_img = frame[img_y:img_y + img_h, img_x:img_x + img_w] #find mean pixel value mean, stddev = cv2.meanStdDev(crop_img) b = int(mean[0]) g = int(mean[1]) r = int(mean[2]) print("BGR: ", b, g, r) #convert to hue xy colorspace x, y = converter.rgb_to_xy(r, g, b) print(x, y) print(abs(prevx - x), abs(prevy - y)) if ((abs(prevx - x) > 0.03) or (abs(prevy - y) > 0.03)): print("setting hue") prevx = x prevy = y #set hue light to mean hsv for light_name in light_names: hue_brige.set_light(light_name, 'xy', [x, y]) #hue_brige.set_light(light_name,'bri',30)
class Lamp(object): """A wrapper for the Philips Hue BLE protocol""" def __init__(self, address): self.address = address self.client = None @property def is_connected(self): return self.client and self.client.is_connected async def connect(self): # reinitialize BleakClient for every connection to avoid errors self.client = BleakClient(self.address) await self.client.connect() model = await self.get_model() try: self.converter = Converter(get_light_gamut(model)) except ValueError: self.converter = Converter(GamutC) async def disconnect(self): await self.client.disconnect() self.client = None async def get_model(self): """Returns the model string""" model = await self.client.read_gatt_char(CHAR_MODEL) return model.decode('ascii') async def get_power(self): """Gets the current power state""" power = await self.client.read_gatt_char(CHAR_POWER) return bool(power[0]) async def set_power(self, on): """Sets the power state""" await self.client.write_gatt_char(CHAR_POWER, bytes([1 if on else 0]), response=True) async def get_brightness(self): """Gets the current brightness as a float between 0.0 and 1.0""" brightness = await self.client.read_gatt_char(CHAR_BRIGHTNESS) return brightness[0] / 255 async def set_brightness(self, brightness): """Sets the brightness from a float between 0.0 and 1.0""" await self.client.write_gatt_char( CHAR_BRIGHTNESS, bytes([max(min(int(brightness * 255), 254), 1)]), response=True) async def get_color_xy(self): """Gets the current XY color coordinates as floats between 0.0 and 1.0""" buf = await self.client.read_gatt_char(CHAR_COLOR) x, y = unpack('<HH', buf) return x / 0xFFFF, y / 0xFFFF async def set_color_xy(self, x, y): """Sets the XY color coordinates from floats between 0.0 and 1.0""" buf = pack('<HH', int(x * 0xFFFF), int(y * 0xFFFF)) await self.client.write_gatt_char(CHAR_COLOR, buf, response=True) async def get_color_rgb(self): """Gets the RGB color as floats between 0.0 and 1.0""" x, y = await self.get_color_xy() return self.converter.xy_to_rgb(x, y) async def set_color_rgb(self, r, g, b): """Sets the RGB color from floats between 0.0 and 1.0""" x, y = self.converter.rgb_to_xy(r, g, b) await self.set_color_xy(x, y)
logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) app = Bottle() converter = Converter(GamutC) red_xy = converter.rgb_to_xy(255, 0, 0) red = {'transitiontime': 0, 'xy': red_xy} green = {'transitiontime': 0, 'xy': converter.rgb_to_xy(0, 255, 0)} blue = {'transitiontime': 0, 'xy': converter.rgb_to_xy(0, 0, 255)} orange = {'transitiontime': 0, 'xy': converter.rgb_to_xy(255, 165, 0)} yellow = {'transitiontime': 0, 'xy': converter.rgb_to_xy(255, 255, 0)} bridge = Bridge('192.168.178.38') bomb_planted = False def set_bomb_alarm_on(): global bomb_planted if not bomb_planted: bridge.set_light('Portable', red)
def change_group_color(bridge, group, color): hue_group = get_group_name(bridge, group) if hue_group.islight = 0: LOGGER.debug("This is the hue group: {}".format(hue_group[0])) color_rgb = webcolors.html5_parse_legacy_color(unicode(color)) converterc = Converter(GamutC) color_xy = converterc.rgb_to_xy(*color_rgb) bridge.set_group(hue_group[0], 'xy', *color_xy) LOGGER.debug("Setting group {} to color {}".format(hue_group[0], *color_rgb)) return hue_group[0] else: LOGGER.debug("This is the light: {}".format(hue_group[0])) color_rgb = webcolors.html5_parse_legacy_color(unicode(color)) converterc = Converter(GamutC) color_xy = converterc.rgb_to_xy(*color_rgb) bridge.set_light(hue_group[0], 'xy', *color_xy) LOGGER.debug("Setting group {} to color {}".format(hue_group[0], *color_rgb)) return hue_group[0] # The logic of each skill is contained within its own class, which inherits # base methods from the MycroftSkill class with the syntax you can see below: # "class ____Skill(MycroftSkill)" class GeekHueSkill(MycroftSkill): def __init__(self): super(GeekHueSkill, self).__init__(name='GeekHueSkill') self.ip = self.config.get('bridge_ip') self.bridge = Bridge(self.ip) @intent_handler(IntentBuilder('GroupColorIntent').require("GroupColorKeyword").require('Group').require('Color').build())
print('Estimated tempo: {:0.2f} beats per minute'.format(tempo)) # save output # 'beats' will contain the frame numbers of beat events. beat_times = librosa.frames_to_time(beats, sr=sr, hop_length=hop_length) print("Beat table generated:") print(beat_times) return (beat_times, tempo) def initialize_lights(): left.brightness = right.brightness = back.brightness = 255 left.colortemp = right.colortemp = back.colortemp = temp converter = Converter() converter.rgb_to_xy(255, 0, 0) b = Bridge(bridge_ip) lights = b.get_light_objects() for light in lights: light.on = True light.xy = converter.rgb_to_xy(255, 0, 0) time.sleep(.5) light.xy = converter.rgb_to_xy(0, 255, 0) time.sleep(.5) light.xy = converter.rgb_to_xy(0, 0, 255) time.sleep(.5) light.on = False # left = lights[0] # right = lights[1] # back = lights[2]
from PIL import ImageGrab, Image import requests, json from rgbxy import Converter import time converter = Converter() bridge_ip = "" key = "" room_id = "" grab_xy = [78, 1404] while 1: im = ImageGrab.grab() pix = im.load() pixrgb = pix[grab_xy[0], grab_xy[1]] try: converter.rgb_to_xy(pixrgb[0], pixrgb[1], pixrgb[2])[0] data = { 'xy': [ converter.rgb_to_xy(pixrgb[0], pixrgb[1], pixrgb[2])[0], converter.rgb_to_xy(pixrgb[0], pixrgb[1], pixrgb[2])[1] ] } r = requests.put( "http://" + bridge_ip + "/api/" + key + "/groups/" + room_id + "/action", json.dumps(data)) except ZeroDivisionError: pass time.sleep(5)