Exemplo n.º 1
0
    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
Exemplo n.º 2
0
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'])
Exemplo n.º 3
0
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])
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
    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()
Exemplo n.º 6
0
 def GetGamut(self, gamut):
     if (gamut.lower() == 'a'):
         conv = Converter(GamutA)
     elif (gamut.lower() == 'c'):
         conv = Converter(GamutC)
     else:
         conv = Converter(GamutB)
     return conv
Exemplo n.º 7
0
 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
     ]
Exemplo n.º 8
0
 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
Exemplo n.º 9
0
    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)
Exemplo n.º 10
0
 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
Exemplo n.º 11
0
    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
Exemplo n.º 12
0
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]
Exemplo n.º 13
0
    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)
Exemplo n.º 14
0
 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
Exemplo n.º 15
0
 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")
Exemplo n.º 16
0
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()
Exemplo n.º 17
0
    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)
Exemplo n.º 18
0
class ChangeLightColor(object):

    """Change a Philips Hue bulb color."""

    def __init__(self, say, bridge_address, bulb_name, hex_color):
        self.converter = Converter()
        self.say = say
        self.hex_color = hex_color
        self.bulb_name = bulb_name
        self.bridge_address = bridge_address

    def run(self):
        bridge = self.find_bridge()
        if bridge:
            light = bridge.get_light_objects("name")[self.bulb_name]
            light.on = True
            light.xy = self.converter.hex_to_xy(self.hex_color)
            self.say(_("Ok"))

    def find_bridge(self):
        try:
            bridge = phue.Bridge(self.bridge_address)
            bridge.connect()
            return bridge
        except phue.PhueRegistrationException:
            logging.info("hue: No bridge registered, press button on bridge and try again")
            self.say(_("No bridge registered, press button on bridge and try again"))
Exemplo n.º 19
0
class ChangeLightColor(object):

    """Change a Philips Hue bulb color."""

    def __init__(self, say, bridge_address, bulb_name, hex_color):
        self.converter = Converter()
        self.say = say
        self.hex_color = hex_color
        self.bulb_name = bulb_name
        self.bridge_address = bridge_address

    def run(self):
        bridge = self.find_bridge()
        if bridge:
            light = bridge.get_light_objects("name")[self.bulb_name]
            light.on = True
            light.xy = self.converter.hex_to_xy(self.hex_color)
            self.say(_("Ok"))

    def find_bridge(self):
        try:
            bridge = phue.Bridge(self.bridge_address)
            bridge.connect()
            return bridge
        except phue.PhueRegistrationException:
            logging.info("hue: No bridge registered, press button on bridge and try again")
            self.say(_("No bridge registered, press button on bridge and try again"))
Exemplo n.º 20
0
Arquivo: hue.py Projeto: KinGin/huehue
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
Exemplo n.º 21
0
 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)
Exemplo n.º 22
0
 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))
         })
Exemplo n.º 23
0
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']
Exemplo n.º 24
0
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)
Exemplo n.º 25
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
Exemplo n.º 26
0
    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."
Exemplo n.º 27
0
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)
Exemplo n.º 28
0
 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)
Exemplo n.º 29
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
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
Exemplo n.º 31
0
    def get(self, request):

        hex_color = None
        result = {
            'hex': None,
            'on': None,
            'hue': None,
            'brightness': None,
            'saturation': None,
        }

        # See if we can get the current hue from the light itself
        if not settings.BRIDGE_MOCK:
            try:
                light = self.bridge().get_light(settings.BRIDGE_LIGHT)
                c = Converter()
                state = light['state']
                hex_color = c.xy_to_hex(*state['xy'])

                result['on'] = state['on']
                result['hue'] = state['hue']
                result['brightness'] = state['bri']
                result['saturation'] = state['sat']
            except phue.PhueRequestTimeout:
                print('Could not connect to bridge at %s' % settings.BRIDGE_IP)

        # If we can't, check the database
        if hex_color is None:
            qs = ChangeEvent.objects.order_by('-timestamp')[:1]
            if len(qs) > 0:
                hex_color = qs[0].color

        # Worst case, default to white
        if hex_color is None:
            hex_color = 'ffffff'

        result['hex'] = hex_color
        return Response(data=result)
Exemplo n.º 32
0
 def __init__(self, say, bridge_address, bulb_name, hex_color):
     self.converter = Converter()
     self.say = say
     self.hex_color = hex_color
     self.bulb_name = bulb_name
     self.bridge_address = bridge_address