def alarm(self, tr_time, blink_count, hex_color=RED): anim_in = { 'transitiontime': tr_time, 'on': True, 'bri': 254, # 'bri': self.light.brightness, 'sat': 254, # 'sat': self.light.saturation, 'xy': list(Converter().hex_to_xy(hex_color)) } anim_out = { 'transitiontime': tr_time, 'on': True, 'bri': 5, 'sat': 70, 'xy': list(Converter().hex_to_xy(hex_color)) } sleep_time = float(tr_time + 1) / 10.0 for i in range(0, blink_count): self.bridge.set_light(self.lights, anim_in) time.sleep(sleep_time) self.bridge.set_light(self.lights, anim_out) time.sleep(sleep_time)
def initialize_server(): global converter, lights_url, all_the_lights, \ host, port, pi_host, pi_port # Read configurations config = configparser.ConfigParser() config.read('config.ini') # Initialize Hue Bridge information and RGB_to_XY converter if config['LIGHT BRIDGE']['converter'] == "GamutA": converter = Converter(GamutA) elif config['LIGHT BRIDGE']['converter'] == "GamutB": converter = Converter(GamutB) elif config['LIGHT BRIDGE']['converter'] == "GamutC": converter = Converter(GamutC) base_url = config['LIGHT BRIDGE']['base_url'] username = config['LIGHT BRIDGE']['username'] lights_url = base_url + '/api/' + username + '/lights/' all_the_lights = rest.send(url=lights_url) # Initialize Server information host = config['SERVER']['host'] port = int(config['SERVER']['port']) # Initialize raspberry IP and PORT pi_host = config['SERVER']['pi_host'] pi_port = int(config['SERVER']['pi_port'])
def GetGamut(self, gamut): if (gamut.lower() == 'a'): conv = Converter(GamutA) elif (gamut.lower() == 'c'): conv = Converter(GamutC) else: conv = Converter(GamutB) return conv
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)
def __init__(self): super(PhillipsHueSkill, self).__init__(name="PhillipsHueSkill") self.brightness_step = int(self.settings.get('brightness_step', DEFAULT_BRIGHTNESS_STEP)) self.color_temperature_step = \ int(self.settings.get('color_temperature_step', DEFAULT_COLOR_TEMPERATURE_STEP)) verbose = self.settings.get('verbose', False) if type(verbose) == str: verbose = verbose.lower() verbose = True if verbose == 'true' else False self.verbose = verbose converter = Converter() self.colors = { "red": (65160, 254), "green": (27975, 254), "blue": (45908, 254), "pink": (52673, 254), "violet": (48156, 254), "yellow": (10821, 254), "orange": ( 6308, 254), "white": (41439, 81), } self.username = self.settings.get('username') if self.username == '': self.username = None self.ip = None # set in _connect_to_bridge self.bridge = None self.default_group = None self.groups_to_ids_map = dict() self.scenes_to_ids_map = defaultdict(dict)
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 activate_goal_light(woohue_config, team): team_colors = [] team_colors.append(team['primary-color']) # Team primary color team_colors.append(team['secondary-color']) # Team secondary color existingState = [] for light in woohue_config.goal_lights: existingState.append( config.Bridge(woohue_config.ip).get_light(light, 'xy')) converter = Converter() for i, item in enumerate(team_colors): xy_color = converter.hex_to_xy(item) team_colors[i] = xy_color c = cycle(team_colors) for i in range(9): team_color = next(c) try: config.Bridge(woohue_config.ip).set_light( woohue_config.goal_lights, 'xy', team_color, transitiontime=0) except Exception as e: print(e) time.sleep(.5) #Restore previous color values for i in range(2): config.Bridge(woohue_config.ip).set_light(woohue_config.goal_lights[i], 'xy', existingState[i])
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 __init__(self, bridge, light_id): self.color_converter = Converter(GamutA) self.speed = 0 self.userid = bridge.userid self.ipaddress = bridge.ipaddress self.light_id = light_id self.bridge = bridge self.strobe = False
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 init(bridge_ip = '192.168.1.2', gamut = GamutC): # print(bridge_ip) global converter, b, group, go converter = Converter(gamut) b = Bridge(bridge_ip) # print(b) group = Group(b, 1) # go = Group(b, 2) go = b['portable']
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 convert_xy_to_rgb(self, color): converter = Converter(GamutC) x = color[0] y = color[1] _rgb = [0, 0, 0, 255] rgb = converter.xy_to_rgb(x, y) for i in range(len(rgb)): _rgb[i] = rgb[i] / 255 return _rgb
def set_color(device, hex_value): value = { 'transitiontime': 1, 'on': True, 'bri': 254, 'sat': 254, 'xy': list(Converter().hex_to_xy(hex_value)) } PHue.send(device, value)
async def run(self): """Called when the Accessory should start doing its thing. Called when HAP server is running, advertising is set, etc. Can be overridden with a normal or async method. """ uri = f"ws://127.0.0.1:8000/things/{self.thing_id}" print(f"{self.category}:{self.thing_id}") self.sleep_time = 5 while True: # outer loop restarted every time the connection fails print(f"Creating new connection to {uri}") try: async with websockets.connect(uri) as ws: while True: try: rep = await ws.recv() except websockets.exceptions.ConnectionClosed: print(f"Ping error - retrying connection in {self.sleep_time} sec (Ctrl-C to quit)") await asyncio.sleep(self.sleep_time) break recv_data = json.loads(rep) if recv_data.get("messageType") == "propertyStatus": value = recv_data.get("data") if value.get('contact') is not None and hasattr(self, 'char_contact'): self.char_contact.set_value(value.get('contact')) if value.get('temperature') and hasattr(self, 'char_temp'): self.char_temp.set_value(value.get('temperature')) if value.get('state') is not None and hasattr(self, 'char_on'): self.char_on.set_value(True if value.get('state') == 1 else False) if value.get('brightness') and hasattr(self, 'char_brightness'): self.char_brightness.set_value(int((value.get('brightness') / 254) * 100)) if value.get('color') and hasattr(self, 'char_brightness') and hasattr(self, 'char_saturation'): x = value.get('color').get('x') y = value.get('color').get('y') converter = Converter() print(value) rgb = converter.xy_to_rgb(x, y, value.get('brightness')) import colorsys hsv = colorsys.rgb_to_hsv(rgb[0], rgb[1], rgb[2]) self.char_on.set_value(hsv[0]*60) self.char_saturation.set_value(hsv[1]*100) self.char_brightness.set_value(hsv[2]*100) print(f"data push from ws:{value}") except socket.gaierror: print( f"Socket error - retrying connection in {self.sleep_time} sec (Ctrl-C to quit)") await asyncio.sleep(self.sleep_time) continue except (websockets.exceptions.InvalidStatusCode, ConnectionRefusedError): print('Nobody seems to listen to this endpoint. Please check the URL.') print(f"Retrying connection in {self.sleep_time} sec (Ctrl-C to quit)") await asyncio.sleep(self.sleep_time) continue
def set_color(self, hex_value): self.bridge.set_light( self.lights, { 'transitiontime': 1, 'on': True, 'bri': 254, 'sat': 254, 'xy': list(Converter().hex_to_xy(hex_value)) })
def get_hex_color_payload(hex_color: str, transitiontime: int = 400): try: return { 'xy': Converter().hex_to_xy(hex_color.strip('#')), 'transitiontime': transitiontime } except ValueError: print('invalidValue') return None
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 __init__(self, bridge_ip="192.168.1.238", connect=False): '''Creates GcpDot object and optionally connects to Phillips Hue''' # Internals self._rgb_conv = Converter() self._BASE_GRADIENT_COLOR = (239, 239, 255) self.stats = [] self.connected = False if connect: self.API_BASE_IP = bridge_ip self.light = self._connect() self.connected = True
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
def alarm(device, tr_time, blink_count, hex_color=RED): anim_in = { 'transitiontime': tr_time, 'on': True, 'bri': 254, 'sat': 254, 'xy': list(Converter().hex_to_xy(hex_color)) } anim_out = { 'transitiontime': tr_time, 'on': True, 'bri': 5, 'sat': 70, 'xy': list(Converter().hex_to_xy(hex_color)) } sleep_time = float(tr_time + 1) / 10.0 for i in range(0, blink_count): PHue.send(device, anim_in) sleep(sleep_time) PHue.send(device, anim_out) sleep(sleep_time)
def __init__(self, **kwargs): self.__lights = None self.__lastUpdate = 0 # Get variables self.__api = { apiManager.KWARG_ADDR: kwargs.get(apiManager.KWARG_ADDR, None), apiManager.KWARG_KEY: kwargs.get(apiManager.KWARG_KEY, None) } self.__verbose = kwargs.get(apiManager.KWARG_VERBOSE, False) self.__froceBri = kwargs.get(apiManager.KWARG_BRI, None) self.__converter = Converter() if not self.isReady(): if self.__verbose: print("No API address or key given - Run configAPI()")
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 get_result_for_lights(seat): converter = Converter() xy_old = converter.hex_to_xy(colors[seat['old_party']]) xy_new = converter.hex_to_xy(colors[seat['new_party']]) comm = {'bri':127, 'transitiontime':20, 'xy':xy_old} b.set_light(LIGHTS, comm) time.sleep(5) comm = {'bri':254, 'transitiontime':20, 'xy':xy_new} b.set_light(LIGHTS, comm) time.sleep(20) state_of_the_parties()
def state_of_the_parties(): global b while(True): page = requests.get(url=home_url,headers=USER_AGENT_HEADER) tree = html.fromstring(page.text) parties = [] parties_tree = tree.xpath(party_order_xpath) #for party in parties_tree: print parties_tree party_seats = tree.xpath(party_seats_xpath) print party_seats results = {} con_idx = parties_tree.index('CON') results['CON'] = float(party_seats[con_idx]) lab_idx = parties_tree.index('LAB') results['LAB'] = float(party_seats[lab_idx]) snp_idx = parties_tree.index('SNP') results['SNP'] = float(party_seats[snp_idx]) total_seats = float(results['CON'] + results['LAB'] + results['SNP']) brightness = {} brightness['CON'] = results['CON']/total_seats brightness['LAB'] = results['LAB']/total_seats brightness['SNP'] = results['SNP']/total_seats converter = Converter() light_count = 0 for party in results: bri = int(brightness[party]*254) xy = converter.hex_to_xy(colors[party.lower()]) comm = {'bri':bri, 'transitiontime':20, 'xy':xy} b.set_light(LIGHTS[light_count], comm) light_count += 1 time.sleep(10)
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 rainbow(): converter = Converter() r0, g0, b0 = (0, 0, 0) while True: for i in np.arange(start=0, stop=1010, step=1): h = i / 100.0 r1, g1, b1 = [ round(c * 255) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0) ] #r1, g1, b1 = HSV.hsv_to_rgb(h, 1.0, 1.0) if (r1 != r0): pi.set_PWM_dutycycle(LED_RED, r1) if (g1 != g0): pi.set_PWM_dutycycle(LED_GREEN, g1) if (b1 != b0): pi.set_PWM_dutycycle(LED_BLUE, b1) r0, g0, b0 = (r1, g1, b1) time.sleep(0.2)
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 sin_rainbow(radius=1): converter = Converter() r0, g0, b0 = (0, 0, 0) while (1): for rad in np.arange(0, math.pi * 2, 0.01): time.sleep(0.05) #rad = (math.sin(counter * math.pi * 1.5) / 2) x = radius * math.cos(rad) y = radius * math.sin(rad) r1, g1, b1 = converter.xy_to_rgb(x, y) if (r1 != r0): pi.set_PWM_dutycycle(LED_RED, r1) if (g1 != g0): pi.set_PWM_dutycycle(LED_GREEN, g1) if (b1 != b0): pi.set_PWM_dutycycle(LED_BLUE, b1) r0, g0, b0 = (r1, g1, b1)