<commit_before>import requests
import socket
import json
import datetime
import logging
from time import sleep
import hashlib
from colorpy import colormodels

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('hue')


AUTH_FAILURE_RETRIES = 6
AUTH_FAILURE_SLEEP = 10


class Hue:
    station_ip = "192.168.1.130"

    # Hue appears to expect your username to be a 32 character hash
    client_identifier = hashlib.md5("ph-%s" % socket.getfqdn()).hexdigest()

    devicetype = "python-hue"
    last_update_state = None
    is_allowed = True
    state = {}
    lights = {}
    groups = {}
    schedules = {}
    config = {}

    def request(self, *args, **kwargs):
        path = "http://%s/api/%s%s" % (
            self.station_ip,
            self.client_identifier,
            kwargs.get("path", ""),
        )
        method = kwargs.get("method", "GET")
        data = kwargs.get("data", None)

        ## Needs more error checking, currently assumes connection will work
        ## and that returns proper json.
        resp = requests.request(method, path, data=data)

        logger.debug(resp)
        logger.debug(resp.content)

        resp = json.loads(resp.content)

        logger.debug(resp)

        if isinstance(resp, list) and resp[0].get("error", None):
            error = resp[0]["error"]
            if error["type"] == 1:
                ## Try to authenticate
                if self.authenticate():
                    return self.request(*args, **kwargs)
                else:
                    raise CouldNotAuthenticate()
        else:
            self.is_authenticated = True
            return resp

    def authenticate(self, tries=AUTH_FAILURE_RETRIES):
        path = "http://%s/api" % (
            self.station_ip
        )

        ## Needs more error checking, currently assumes connection will work
        ## and that returns proper json.
        auth = {
            "devicetype": self.devicetype,
            "username": self.client_identifier
        }

        resp = requests.post(path, data=json.dumps(auth))
        logger.debug(resp)
        logger.debug(resp.content)


        resp = json.loads(resp.content)

        logger.debug(resp)

        logger.warn("Time to go press your button!")

        if isinstance(resp, list) and resp[0].get("error", None):
            logger.debug(resp[0]["error"])
            if tries:
                sleep(AUTH_FAILURE_SLEEP)
                self.authenticate()
            else:
                raise TooManyFailures()

        return True

    def get_state(self):
        self.last_resp = self.request()
        state = self.last_resp
        logger.debug(state)

        self.state = state
        self.config = state['config']
        self.schedules = state['schedules']
        self.groups = state['groups']

        for l in state['lights']:
            light = self.lights.get("l%s" % l, None)
            if not light:
                light = ExtendedColorLight(self, l)
                self.lights["l%s" % l] = light
            light.update_state_cache(state['lights'][l])

        self.last_update_state = datetime.datetime.now()



class ExtendedColorLight:
    last_status_time = None
    light_id = None
    state = {}
    hue = None

    def __init__(self, hue, light_id):
        self.hue = hue
        self.light_id = light_id

    def update_state_cache(self, values=None):
        if not values:
            values = self.hue.request(path = "/lights/%s" % self.light_id)

        self.state.update(values)
        self.last_status_time = datetime.datetime.now()

    def set_state(self, state):
        self.hue.request(path="/lights/%s/state" % self.light_id, method="PUT", data=json.dumps(state))
        self.update_state_cache()
        return self

    def on(self):
        return self.set_state({"on": True})

    def off(self):
        return self.set_state({"on": False})
        
    def ct(self, ct):
        # set color temp in mired scale
        return self.set_state({"ct": ct})

    def cct(self, cct):
        # set color temp in degrees kelvin
        return self.ct(1000000 / cct)

    def bri(self, level):
        # level between 0 and 255
        return self.set_state({"bri": level})

    def toggle(self):
        self.update_state_cache()
        if self.state["on"]:
            self.off()
        else:
            self.on()

    def alert(self, type="select"):
        return self.set_state({"alert": type})

    def xy(self, x, y):<commit_msg>Fix Toggle. Closes #3.  Thanks @ocelma<commit_after>import requests
import socket
import json
import datetime
import logging
from time import sleep
import hashlib
from colorpy import colormodels

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('hue')


AUTH_FAILURE_RETRIES = 6
AUTH_FAILURE_SLEEP = 10


class Hue:
    station_ip = "192.168.1.130"

    # Hue appears to expect your username to be a 32 character hash
    client_identifier = hashlib.md5("ph-%s" % socket.getfqdn()).hexdigest()

    devicetype = "python-hue"
    last_update_state = None
    is_allowed = True
    state = {}
    lights = {}
    groups = {}
    schedules = {}
    config = {}

    def request(self, *args, **kwargs):
        path = "http://%s/api/%s%s" % (
            self.station_ip,
            self.client_identifier,
            kwargs.get("path", ""),
        )
        method = kwargs.get("method", "GET")
        data = kwargs.get("data", None)

        ## Needs more error checking, currently assumes connection will work
        ## and that returns proper json.
        resp = requests.request(method, path, data=data)

        logger.debug(resp)
        logger.debug(resp.content)

        resp = json.loads(resp.content)

        logger.debug(resp)

        if isinstance(resp, list) and resp[0].get("error", None):
            error = resp[0]["error"]
            if error["type"] == 1:
                ## Try to authenticate
                if self.authenticate():
                    return self.request(*args, **kwargs)
                else:
                    raise CouldNotAuthenticate()
        else:
            self.is_authenticated = True
            return resp

    def authenticate(self, tries=AUTH_FAILURE_RETRIES):
        path = "http://%s/api" % (
            self.station_ip
        )

        ## Needs more error checking, currently assumes connection will work
        ## and that returns proper json.
        auth = {
            "devicetype": self.devicetype,
            "username": self.client_identifier
        }

        resp = requests.post(path, data=json.dumps(auth))
        logger.debug(resp)
        logger.debug(resp.content)


        resp = json.loads(resp.content)

        logger.debug(resp)

        logger.warn("Time to go press your button!")

        if isinstance(resp, list) and resp[0].get("error", None):
            logger.debug(resp[0]["error"])
            if tries:
                sleep(AUTH_FAILURE_SLEEP)
                self.authenticate()
            else:
                raise TooManyFailures()

        return True

    def get_state(self):
        self.last_resp = self.request()
        state = self.last_resp
        logger.debug(state)

        self.state = state
        self.config = state['config']
        self.schedules = state['schedules']
        self.groups = state['groups']

        for l in state['lights']:
            light = self.lights.get("l%s" % l, None)
            if not light:
                light = ExtendedColorLight(self, l)
                self.lights["l%s" % l] = light
            light.update_state_cache(state['lights'][l])

        self.last_update_state = datetime.datetime.now()



class ExtendedColorLight:
    last_status_time = None
    light_id = None
    state = {}
    hue = None

    def __init__(self, hue, light_id):
        self.hue = hue
        self.light_id = light_id

    def update_state_cache(self, values=None):
        if not values:
            values = self.hue.request(path = "/lights/%s" % self.light_id)

        self.state.update(values)
        self.last_status_time = datetime.datetime.now()

    def set_state(self, state):
        self.hue.request(path="/lights/%s/state" % self.light_id, method="PUT", data=json.dumps(state))
        self.update_state_cache()
        return self

    def on(self):
        return self.set_state({"on": True})

    def off(self):
        return self.set_state({"on": False})

    def ct(self, ct):
        # set color temp in mired scale
        return self.set_state({"ct": ct})

    def cct(self, cct):
        # set color temp in degrees kelvin
        return self.ct(1000000 / cct)

    def bri(self, level):
        # level between 0 and 255
        return self.set_state({"bri": level})

    def toggle(self):
        self.update_state_cache()
        if self.state and self.state.get('state', None) and self.state["state"].get("on", None):
            self.off()
        else:
            self.on()

    def alert(self, type="select"):
        return self.set_state({"alert": type})

    def xy(self, x, y):
{'fraction_non_alphanumeric': 0.1175305381313965, 'fraction_numerical': 0.00715307582260372, 'mean_word_length': 2.030343447815939, 'pattern_counts': {'":': 14, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3963678', 'n_tokens_mistral': 2802, 'n_tokens_neox': 2652, 'n_words': 640}