예제 #1
0
파일: Test.py 프로젝트: natn/lifxlan
def main():
    num_lights = None
    if len(sys.argv) != 2:
        print(
            "\nDiscovery will go much faster if you provide the number of lights on your LAN:"
        )
        print("  python {} <number of lights on LAN>\n".format(sys.argv[0]))
    else:
        num_lights = int(sys.argv[1])

    # instantiate LifxLAN client, num_lights may be None (unknown).
    # In fact, you don't need to provide LifxLAN with the number of bulbs at all.
    # lifx = LifxLAN() works just as well. Knowing the number of bulbs in advance
    # simply makes initial bulb discovery faster.
    print("Discovering lights...")
    lifx = LifxLAN(num_lights)

    # get devices
    devices = lifx.get_devices()
    lights = lifx.get_lights()
    print("Found {} devices(s).".format(len(devices)))
    print("Found {} light(s):\n".format(len(lights)))

    cpulight = lifx.get_device_by_name("CPU")
    print(cpulight)
    workbenchlight = lifx.get_device_by_name("Workbench")
    print(workbenchlight)

    cpulight.set_color(RED, rapid=True)
    workbenchlight.set_color(RED, rapid=True)
    sleep(5)
    cpulight.set_waveform(is_transient=0,
                          color=BLUE,
                          period=55000,
                          cycles=10000,
                          duty_cycle=0.5,
                          waveform=1,
                          rapid=False)
    workbenchlight.set_waveform(is_transient=0,
                                color=BLUE,
                                period=60000,
                                cycles=10000,
                                duty_cycle=0.5,
                                waveform=1,
                                rapid=False)
예제 #2
0
    def start_pairing(self, timeout):
        """
        Start the pairing process.

        timeout -- Timeout in seconds at which to quit pairing
        """
        self.pairing = True

        lan = LifxLAN()
        lan_devices = lan.get_devices()

        for dev in lan_devices:
            if not self.pairing:
                break

            _id = 'lifx-' + dev.get_mac_addr().replace(':', '-')
            if _id not in self.devices:
                device = LifxBulb(self, _id, dev)
                self.handle_device_added(device)
예제 #3
0
class LifxController:
    def __init__(self, bulb_mac=None, bulb_ip=None):
        logging.debug("Initialising LifxController.")
        self.lan = LifxLAN()
        self.bulbs = None
        self.groups = None
        self.bulb_labels: list = []
        self.group_labels: list = []
        self.bulb = None
        self.group = None
        self.bulb_mac = bulb_mac
        self.bulb_ip = bulb_ip

        # Logger config
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        self.ch = logging.StreamHandler()
        self.ch.setLevel(logging.DEBUG)
        self.formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.ch.setFormatter(self.formatter)
        self.logger.addHandler(self.ch)

        # When loading config, we don't need to discover the bulb
        if self.bulb_mac and self.bulb_ip:
            from lifxlan import Light
            self.bulb = Light(self.bulb_mac, self.bulb_ip)

    def discover_bulbs(self):
        """
        Discovers individual bulbs, then groups
        """
        logging.debug("discover_bulbs: Discovering individual bulbs.")
        # Discover bulbs on the LAN
        self.bulbs = self.lan.get_devices()
        logging.debug(
            f"discover_bulbs: Discovery complete. {len(self.lan.devices)} bulbs found."
        )

        for bulb in self.bulbs:
            # Build a list of bulb names
            bulb_name = bulb.get_label()
            if bulb_name not in self.bulb_labels:
                self.bulb_labels.append(bulb_name)
            # Figure out what groups exist from their group_labels
            # There is no way to simply discover what groups are available
            group = bulb.get_group_label()
            if group:
                if group not in self.group_labels:
                    self.group_labels.append(group)

    def select_target(self):
        """
        Creates menu to select target bulb or group.
        """

        title = "Would you like to target a single bulb, or groups of bulbs?"
        options = ["Single", "Group"]

        _, selection = pick(options, title)
        print(type(selection), selection)
        if selection == 0:
            logging.debug("User is going to target a single bulb.")
            title = "Select the bulb to target"
            _, selection = pick(self.bulb_labels, title)
            self.bulb = self.bulbs[selection]
        elif selection == 1:
            logging.debug("User is going to target a group of bulbs.")
            title = "Select the target group"
            _, selection = pick(self.group_labels, title)
            self.group = self.groups[selection]

    def get_colour(self):
        """
        Obtains the current colour of the bulb.
        """
        if self.bulb:
            return self.bulb.get_color()
        elif self.group:
            return self.group.get_color()

    def set_colour(self, colour):
        """
        Sets colour of selected bulb to input.
        Input is HSBK format, which seems to be specific to LifX and really poorly documented
        at the time of this comment.
        https://api.developer.lifx.com/docs/colors
        input: list
        """
        if self.bulb:
            return self.bulb.set_color(colour)
        if self.group:
            return self.group.set_color(colour)

    def get_config(self):
        """
        Returns bulb config, to save for later.
        return: dict
        """
        if self.bulb:
            bulb_config: dict = {
                "mac_addr": self.bulb.get_mac_addr(),
                "ip_addr": self.bulb.get_ip_addr(),
                "label": self.bulb.get_label()
            }
            return bulb_config
        else:
            logging.debug("get_config: Returning group config")
예제 #4
0
from lifxlan import LifxLAN

from flask import Flask, request, render_template
app = Flask(__name__)

lifx = LifxLAN()
lifx.get_devices() # fetch and cache all devices

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/switch', methods=['POST'])
def switch():
    params = request.get_json()
    device_name = params.get('device')
    devices = [lifx.get_device_by_name(device_name)] if device_name else lifx.get_devices()
    power = params.get('power')
    color = params.get('color')
    for device in devices:
        if power: device.set_power(power, 200, True)
        if color: device.set_color([int(n) for n in color.split(',')], 200, True)
    return ''