Beispiel #1
0
class YeetBulb:
    def __init__(self, name, ip):
        self.name = name
        self.ip = ip
        self.bulb = Bulb(self.ip, effect="smooth", duration=750, auto_on=True)
        self.properties = self.bulb.get_properties()

    def __getitem__(self, key):
        return getattr(self, key)

    def turnoff(self):
        self.bulb.turn_off()

    def turnon(self):
        self.bulb.turn_on()

    def toggle(self):
        self.bulb.toggle()

    def loadPreset(self, preset):
        if os.path.isfile(preset):
            with open(preset, 'r') as f:
                config = json.load(f)

            if 'preset' in config:
                preset = config['preset']
                if ('rgb' in preset):
                    try:
                        self.bulb.set_rgb(preset['rgb'][0], preset['rgb'][1],
                                          preset['rgb'][2])
                    except:
                        print('not supported by bulb')
                if ('hsv' in preset):
                    try:
                        self.bulb.set_hsv(preset['hsv'][0], preset['hsv'][1],
                                          preset['hsv'][2])
                    except:
                        print('not supported by bulb')
                if ('color_temp' in preset):
                    try:
                        self.bulb.set_color_temp(preset['color_temp'])
                    except:
                        print('not supported by bulb')
                if ('brightness' in preset):
                    try:
                        self.bulb.set_brightness(preset['brightness'])
                    except:
                        print('not supported by bulb')
                if ('color_temp' in preset):
                    try:
                        self.bulb.set_color_temp(preset['color_temp'])
                    except:
                        print('not supported by bulb')
        else:
            print('File not found: ' + preset)

    def updateProperties(self):
        self.properties = self.bulb.get_properties()
Beispiel #2
0
class WhiteBulb:
    def __init__(self, ip):
        self.bulb = Bulb(ip)

    def power_on(self):
        self.bulb.turn_on()
        print("Turning the light on...")

    def power_off(self):
        self.bulb.turn_off()
        print("Turning the light off...")

    def power_toggle(self):
        self.bulb.toggle()
        print("Toggling the light...")

    def set_brightness(self, bright):
        self.bulb.set_brightness(bright)
        print("Setting the brightness to ", bright, "%...")

    def set_temperature(self, temp):
        self.bulb.set_color_temp(temp)
        print("Setting the temperature to ", temp, "K...")

    def get_status(self):
        status = self.bulb.get_properties()
        power = status['power']
        bright = status['bright']
        temp = status['ct']
        rgb = status['rgb']
        r, g, b = [rgb[i:i + 3] for i in range(0, len(rgb), 3)]
        rgb = "(" + r + ", " + g + ", " + b + ")"
        print("Power: {}\nBrighness: {}%\nTemperature: {}K\nRGB: {}".format(
            power, bright, temp, rgb))
Beispiel #3
0
def main():
    print "Started..."
    time.sleep(1)
    #pygame.mixer.init()
    #pygame.mixer.music.load("/home/pi/Yeelight/tma.mp3")
    #pygame.mixer.music.set_volume(1.0)
    #pygame.mixer.music.play()
    #pygame.mixer.music.pause()

    bulb = Bulb("10.0.0.1", auto_on=True)
    bulb.turn_on()
    time.sleep(1)
    bulb.turn_off()
    #bulb.start_music(666, "10.0.0.2")
    #bulb.start_music()
    print(bulb.get_properties())
    ser = serial.Serial(
        "/dev/ttyACM0",
        9600)  #change ACM number as found from ls /dev/tty/ACM*
    ser.baudrate = 9600

    window = []
    while True:
        percentage = ser.readline()
        sanitized = re.sub("[^0-9]", "", percentage)
        if sanitized:
            window = avg_brightness(bulb, int(sanitized), window, 5)
            time.sleep(0.200)
Beispiel #4
0
 def test_ip(i):
     try:
         ip = f'192.168.1.{i}'
         b = Bulb(ip)
         print(b.get_properties())
         return ip
     except BulbException as e:
         return None
Beispiel #5
0
 def discover(self, command=None):
     if self.devlist:
         LOGGER.info("Using manually specified device list")
         for bulb_info in self.devlist:
             LOGGER.debug(bulb_info)
             address = bulb_info['address'][:14]
             try:
                 bulb = Bulb(bulb_info['ip'])
                 bulb_properties = bulb.get_properties()
             except Exception as ex:
                 LOGGER.error(
                     'Failed to connect to the bulb at {} {}'.format(
                         bulb_info['ip'], ex))
                 continue
             name = bulb_info['name']
             if name is None:
                 name = 'YeeLight ' + address[10:14]
             if not address in self.nodes:
                 LOGGER.info('Adding YeeLight bulb id: {}, name: {}'.format(
                     address, name))
                 self.addNode(
                     YeeColorBulb(self, self.address, address, name, bulb))
     else:
         for bulb_info in discover_bulbs():
             LOGGER.debug(bulb_info)
             address = str(bulb_info['capabilities']['id'])[-14:]
             try:
                 bulb = Bulb(bulb_info['ip'])
                 bulb_properties = bulb.get_properties()
             except Exception as ex:
                 LOGGER.error(
                     'Failed to connect to the bulb at {} {}'.format(
                         bulb_info['ip'], ex))
                 continue
             name = bulb_properties['name']
             if name is None:
                 name = 'YeeLight ' + address[10:14]
             if not address in self.nodes:
                 LOGGER.info('Adding YeeLight bulb id: {}, name: {}'.format(
                     bulb_info['capabilities']['id'], name))
                 self.addNode(
                     YeeColorBulb(self, self.address, address, name, bulb))
Beispiel #6
0
def control_yeelight(status):
    # 当前局域网存在灯设备
    if len(discover_bulbs()):
        # 连接到yeelight
        bulb = Bulb(bulb_ip)
        dic = bulb.get_properties()
        # {'sat': '100', 'color_mode': '2', 'ct': '6500', 'delayoff': '0', 'power': 'on', 'rgb': '16711680', 'hue': '359', 'music_on': '0', 'bright': '82', 'name': None, 'flowing': '0'}
        if dic.has_key('power'):
			power = dic.get('power')
			if bulb and status == True and power == 'off':
            	bulb.turn_on()
	    	else:
        		print("未找到灯")
Beispiel #7
0
def bulb_finder():
    global bulb_data, b_ip, b_port, b_bulb
    while True:
        try:
            bulb_data = discover_bulbs()
            if bulb_data:
                b_ip = bulb_data[-1]['ip']
                b_port = bulb_data[-1]['port']
                b_bulb = Bulb(b_ip, effect="smooth", duration=1000)
                if b_bulb:
                    print('Connected')
                    print(b_bulb.get_properties())
                    break
            print('cannot find')
            time.sleep(5)
        except Exception as e:
            print('Error discovering bulbs', e)
def blend_hsv(h: int, s: int, v: int, this_bulb: yeelight.Bulb):
    """Doesn't work, get_properties always returns the same hsv"""

    old_hsv = this_bulb.get_properties(
        requested_properties=['hue', 'sat', 'bright', 'rgb'])
    old_h: int = int(old_hsv['hue'])
    old_s: int = int(old_hsv['sat'])
    old_v: int = int(old_hsv['bright'])
    logging.info(f'Old hsv: {old_h}, {old_s}, {old_v}')

    if old_h > 128:
        blended_h: int = int((h + old_h) / 2)
    else:
        blended_h = h  # new/old value has probably rolled over to 0, don't bother calculating average
    blended_s: int = int((s + old_s) / 2)
    blended_v: int = int((v + old_v) / 2)
    logging.info(f'Blended hsv: {blended_h}, {blended_s}, {blended_v}')
    return int(blended_h), int(blended_s), int(blended_v)
Beispiel #9
0
def main():
    print('Welcome to fluxee by davidramiro')
    print('Reading config...')
    config = configparser.ConfigParser()
    config.read('config.ini')
    global static_brightness
    bulb_count = int(config.get('general', 'LampCount'))
    check_state = config.getboolean('general', 'CheckLampState')
    static_brightness = config.getboolean('general', 'StaticBrightness')
    default_brightness = int(config.get('general', 'BrightnessValue'))
    for n in range(1, (bulb_count + 1)):
        bulbs.append(config.get(str(n), 'ip'))
        if config.get(str(n), 'MaxColorTemperature') == '':
            maxtemps.append(6500)
        else:
            maxtemps.append(config.get(str(n), 'MaxColorTemperature'))
        if config.get(str(n), 'MinColorTemperature') == '':
            mintemps.append(1700)
        else:
            mintemps.append(config.get(str(n), 'MinColorTemperature'))
    print('Initializing...')
    for init_bulb in bulbs:
        if init_bulb != '':
            print('Initializing Yeelight at %s' % init_bulb)
            bulb = Bulb(init_bulb)
            if check_state is True:
                state = bulb.get_properties(requested_properties=['power'])
                if 'off' in state['power']:
                    print('Powered off. Ignoring Yeelight at %s' % init_bulb)
                elif static_brightness is True:
                    print('Changing brightness of', init_bulb)
                    bulb.set_brightness(default_brightness)
            else:
                print('Turning on Yeelight at %s' % init_bulb)
                bulb.turn_on()
                if static_brightness is True:
                    bulb.set_brightness(default_brightness)
                else:
                    bulb.set_brightness(100)

    run(host='127.0.0.1', port=8080)
    print('Thank you for using fluxee. Have a good one!')
Beispiel #10
0
collection = db["collection"]

arp_packet = scapy.ARP(pdst='192.168.0.1/24')
broadcast_packet = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_broadcast_packet = broadcast_packet / arp_packet
answered_list = scapy.srp(arp_broadcast_packet, timeout=30, verbose=False)[0]

for element in answered_list:
    client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
    client_list.append(client_dict)

for client in client_list:
    if (client["mac"][0:8] == '5c:e5:0c'):

        check_status = Bulb(client["ip"])
        power_status = check_status.get_properties()['power']

        if power_status == 'on':
            status = True
        elif power_status == 'off':
            status = False

        bulbInDatabase = collection.find({"_id": client["ip"]})
        publishOnce = bulbInDatabase.count() > 0
        level = random.randint(1, 2)

        if (publishOnce == False):
            identified_bulbs = {
                "_id": client["ip"],
                "mac_address": client["mac"],
                "status": status,
Beispiel #11
0
class Device(BaseDevice):

    typesDevice = ["light"]
    name = DEVICE_NAME
    addConfig = AddDevice(
        fields=False,
        description=
        "1. Through the original application, you must enable device management over the local network.\n2. Enter the ip-address of the device (it can be viewed in the same application)."
    )
    editConfig = EditDevice(address=True, fields=EditField(icon=True))

    def __init__(self, *args, **kwargs):
        super().__init__(**kwargs)
        self.device = Bulb(self.coreAddress)
        try:
            values = self.device.get_properties()
            self.minmaxValue = self.device.get_model_specs()
            if (not look_for_param(self.values, "state")
                    and "power" in values):
                val = "0"
                if (values["power"] == "on"):
                    val = "1"
                self.values.append(
                    DeviceElement(name="state",
                                  systemName=self.systemName,
                                  control=True,
                                  high=1,
                                  low=0,
                                  type="binary",
                                  icon="fas fa-power-off",
                                  value=val))
            if (not look_for_param(self.values, "brightness")
                    and "current_brightness" in values):
                self.values.append(
                    DeviceElement(name="brightness",
                                  systemName=self.systemName,
                                  control=True,
                                  high=100,
                                  low=0,
                                  type="number",
                                  icon="far fa-sun",
                                  value=values["current_brightness"]))
            if (not look_for_param(self.values, "night_light")
                    and self.minmaxValue["night_light"] != False):
                self.values.append(
                    DeviceElement(name="night_light",
                                  systemName=self.systemName,
                                  control=True,
                                  high="1",
                                  low=0,
                                  type="binary",
                                  icon="fab fa-moon",
                                  value=values["active_mode"]))
            if (not look_for_param(self.values, "color")
                    and values["hue"] != None):
                self.values.append(
                    DeviceElement(name="color",
                                  systemName=self.systemName,
                                  control=True,
                                  high=360,
                                  low=0,
                                  type="number",
                                  icon="fab fa-medium-m",
                                  value=values["hue"]))
            if (not look_for_param(self.values, "saturation")
                    and values["sat"] != None):
                self.values.append(
                    DeviceElement(name="saturation",
                                  systemName=self.systemName,
                                  control=True,
                                  high=100,
                                  low=0,
                                  type="number",
                                  icon="fab fa-medium-m",
                                  value=values["sat"]))
            if (not look_for_param(self.values, "temp") and "ct" in values):
                self.values.append(
                    DeviceElement(name="temp",
                                  systemName=self.systemName,
                                  control=True,
                                  high=self.minmaxValue["color_temp"]["max"],
                                  low=self.minmaxValue["color_temp"]["min"],
                                  type="number",
                                  icon="fas fa-adjust",
                                  value=values["ct"]))
            super().save()
        except Exception as e:
            logger.warning(f"yeelight initialize error. {e}")
            self.device = None

    def update_value(self, *args, **kwargs):
        values = self.device.get_properties()
        state = look_for_param(self.values, "state")
        if (state and "power" in values):
            val = "0"
            if (values["power"] == "on"):
                val = "1"
            saveNewDate(state, val)
        brightness = look_for_param(self.values, "brightness")
        if (brightness and "current_brightness" in values):
            saveNewDate(brightness, values["current_brightness"])
        mode = look_for_param(self.values, "night_light")
        if (mode and "active_mode" in values):
            saveNewDate(mode, values["active_mode"])
        temp = look_for_param(self.values, "temp")
        if (temp and "ct" in values):
            saveNewDate(temp, values["ct"])
        color = look_for_param(self.values, "color")
        if (color and "hue" in values):
            saveNewDate(color, values["hue"])
        saturation = look_for_param(self.values, "saturation")
        if (saturation and "sat" in values):
            saveNewDate(saturation, values["sat"])

    def get_value(self, name):
        self.update_value()
        return super().get_value(name)

    def get_values(self):
        self.update_value()
        return super().get_values()

    def set_value(self, name, status):
        status = super().set_value(name, status)
        if (name == "state"):
            if (int(status) == 1):
                self.device.turn_on()
            else:
                self.device.turn_off()
        if (name == "brightness"):
            self.device.set_brightness(int(status))
        if (name == "temp"):
            self.device.set_power_mode(PowerMode.NORMAL)
            self.device.set_color_temp(int(status))
        if (name == "night_light"):
            if (int(status) == 1):
                self.device.set_power_mode(PowerMode.MOONLIGHT)
            if (int(status) == 0):
                self.device.set_power_mode(PowerMode.NORMAL)
        if (name == "color"):
            self.device.set_power_mode(PowerMode.HSV)
            saturation = look_for_param(self.values, "saturation")
            self.device.set_hsv(int(status), int(saturation.get()))
        if (name == "saturation"):
            self.device.set_power_mode(PowerMode.HSV)
            color = look_for_param(self.values, "color")
            self.device.set_hsv(int(color.get()), int(status))

    def get_All_Info(self):
        self.update_value()
        return super().get_All_Info()
Beispiel #12
0
import paho.mqtt.client as mqtt
from yeelight import Bulb
from pynput import keyboard
import time
import ssl

### Setting the lamps
lamp_1 = Bulb("192.168.1.16")
lamp_2 = Bulb("192.168.1.17")

lamp_1.set_name("Lamp 1")
lamp_2.set_name("Lamp 2")

lamp_1_properties = lamp_1.get_properties(
    requested_properties=["power", "bright", "rgb", "name"])
lamp_2_properties = lamp_2.get_properties(
    requested_properties=["power", "bright", "rgb", "name"])


### Logging function
def on_log(client, userdata, level, buf):
    print("log : " + buf)


### Information about connection
### ==> OK or KO with returned code
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected OK")
    else:
        print("Bad connection, returned code : " + str(rc))
Beispiel #13
0
 async def getLightStatus(self, light):
     bulb = Bulb(self.lights[0]['ip'])
     bulbProps = bulb.get_properties()
     return bulbProps
Beispiel #14
0
class Yeelight(AbstractLight):
    def __init__(self, ip: str, supports: List[str]) -> None:
        """
        @type ip: The ip of the light bulb
        @type supports: A list of all methods this light bulb supports
        """
        super().__init__(1)

        self.bulb = Bulb(ip)
        self.bulb.effect = "smooth"
        self.bulb.duration = 1000
        self.bulb.turn_on()

        self.supports = supports

        properties = self.bulb.get_properties()

        # We could also parse rgb from properties, however the encoding does not seem trivial.
        self.previous_rgb = [0, 0, 0]
        self.previous_brightness = float(properties["current_brightness"]) / 100  # Scale from [0, 100] to [0, 1]
        self.previous_power = properties["power"]

        self.next_message = 0  # Tracks the last time we send a message, used for rate limiting

    def write(self):
        # Check if we should back off
        if time.time() < self.next_message:
            return

        [red, green, blue, brightness] = self.leds[0]  # Get the desired light state values.
        send_messages_count = 0  # Track the amount of messages we send during this write.

        try:
            # Only update the brightness if the difference is more than one percent
            if abs(self.previous_brightness - brightness) > 0.01:
                # Turn the light off when brightness approaches zero and it is turned on
                if brightness < 0.01:
                    if self.previous_power == "on":
                        self.bulb.turn_off()
                        self.previous_power = "off"
                        send_messages_count += 1
                else:
                    # Turn the light on in case it was previously turned off
                    if self.previous_power == "off":
                        self.bulb.turn_on()
                        self.previous_power = "on"
                        send_messages_count += 1

                    # Update the brightness
                    self.bulb.set_brightness(brightness * 100)  # Scale from [0, 1] to [0, 100]
                    send_messages_count += 1

                # Always update the brightness, even in case we turned it off, as the light will
                # do this internally.
                self.previous_brightness = brightness

            rgb = [int(255 * c) for c in [red, green, blue]]
            # Prevent updating the color if it either didn't change or we're backing off
            if self.previous_rgb != rgb and "set_rgb" in self.supports:
                self.previous_rgb = rgb
                self.bulb.set_rgb(*rgb)
                send_messages_count += 1
        except BulbException as e:
            print(e)
        finally:
            # Make sure we back off for #send_messages seconds to prevent hitting the rate limiting cap.
            if send_messages_count > 0:
                self.next_message = time.time() + send_messages_count

    @staticmethod
    def from_discover_bulbs_dict(dict: dict):
        return Yeelight(dict["ip"], dict["capabilities"]["support"])
from yeelight import Bulb
import sys
ip = sys.argv[1]
bulb = Bulb(ip)
result = bulb.get_properties()
print(result)
Beispiel #16
0
            if blink_red < 0:
                blink_red = 0

            if blink_green < 0:
                blink_green = 0

            for x in range(7):
                stick.set_color(channel=0, red=blink_red, green=blink_green, blue=blink_blue, index=x)
    except:
        pass


if __name__ == '__main__':
    yeelight = Bulb('10.70.2.8', duration=300)
    properties = yeelight.get_properties()

    if properties['music_on'] == '0':
        yeelight.start_music()

    while True:
        try:
            color = get_color()
            darkness_ratio = color['dark_ratio']
            color = color['rgb']

            # hue
            _thread.start_new_thread(update_hue, (color, darkness_ratio))

            # Yeelight
            _thread.start_new_thread(update_yeelight, (yeelight, color, darkness_ratio))
Beispiel #17
0
 def status(self, address):
     ip = self.getIP(address)
     bulb = Bulb(ip)
     prp = bulb.get_properties()
     return prp['power']
    def do_REQUEST(self):
        parsed = urlparse(self.path)
        qs = parse_qs(parsed.query)
        try:
            action = qs['action']
            if (action[0] == "set"):
                state = qs['state']
                pin = qs['pin']
                delay = qs['delay']
            elif (action[0] == "get"):
                pin = qs['pin']
            elif (action[0] == "get_bulb_state"):
                id = qs['id']
            elif (action[0] == "set_bulb_state"):
                id = qs['id']
                state = qs['state']
            elif (action[0] == "bulb_color"):
                id = qs['id']
                red = qs['r']
                green = qs['g']
                blue = qs['b']
            elif (action[0] == 'set_rel_state'):
                id = qs['id']
                pin = qs['pin']
                state = qs['state']
                dat = qs['dat']
        except KeyError:
            message = "<p>No commands processed</p>"

        else:
            message = "."
            if (action[0] == "set" and state in (["1"], ["0"])
                    and int(pin[0]) in (GPIO_OUT_LIST) and int(delay[0]) == 0):
                GPIO.output(int(pin[0]), state == ["1"])
                message = "OK|SET|%d|%d" % (int(pin[0]), int(state[0]))
            elif (action[0] == "set" and state in (["1"], ["0"])
                  and int(pin[0]) in (GPIO_OUT_LIST) and int(delay[0]) > 0):
                message = "OK|SETDELAY|%d|%d|%d" % (int(pin[0]), int(
                    state[0]), int(delay[0]))
                GPIO.output(int(pin[0]), state == ["1"])
                time.sleep(int(delay[0]))
                GPIO.output(int(pin[0]), state == ["0"])
                message = "OK|SETDELAY|%d|%d" % (int(pin[0]), int(state[0]))
            elif (action[0] == "get" and int(pin[0]) in (GPIO_OUT_LIST)):
                message = "OK|GET|%d|%s" % (int(pin[0]), GPIO.input(int(
                    pin[0])))
            elif (action[0] == "bulb" and state[0] == "1"
                  and id[0] in (BULB_DICT)):
                bulb = Bulb(BULB_DICT[id[0]])
                bulb.turn_on()
                message = "OK|BULB_ON|%s" % (id[0])
            elif (action[0] == "get_bulb_state" and id[0] in (BULB_DICT)):
                bulb = Bulb(BULB_DICT[id[0]])
                status = bulb.get_properties()
                message = "OK|%s|%s" % (id[0], status.get('power'))
            elif (action[0] == "set_bulb_state" and state[0] == "0"
                  and id[0] in (BULB_DICT)):
                bulb = Bulb(BULB_DICT[id[0]])
                bulb.turn_off()
                message = "OK|BULB_OFF|%s" % (id[0])
            elif (action[0] == "bulb_color" and id[0] in (BULB_DICT)):
                bulb = Bulb(BULB_DICT[id[0]])
                bulb.set_rgb(int(red[0]), int(green[0]), int(blue[0]))
            elif (action[0] == "get_rel"):
                message = sel_tab(SQL_GET_REL)
            elif (action[0] == "get_temp"):
                message = sel_tab(SQL_GET_TEMP)
            elif (action[0] == "set_rel_state"):
                message = upd_rel_state(state, dat, id, pin)
            else:
                message = "ERR|NO_ACTION|NO_PIN"

        self.send_response(200)
        # Custom headers, if need be
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        # Custom body
        self.wfile.write(bytes(message, "utf8"))
        return
Beispiel #19
0
parser.add_argument('-b', '--brightness', help='set the brightness', type=int)
onoff = parser.add_mutually_exclusive_group()
onoff.add_argument('--on', help='turn on the light', action="store_true")
onoff.add_argument('--off', help='turn off the light', action="store_true")
colors = parser.add_mutually_exclusive_group()
colors.add_argument('-t', '--temp', help='set the white color temp', type=int)
colors.add_argument('-c',
                    '--color',
                    help='set the rgb color',
                    type=valid_color)
args = parser.parse_args()

for bulbaddr in args.bulbs:
    bulb = Bulb(bulbaddr)
    if args.switch:
        status = bulb.get_properties()
        if status['power'] == "off":
            bulb.turn_on()
        else:
            bulb.turn_off()
    if args.on:
        bulb.turn_on()
    elif args.off:
        bulb.turn_off()
    if args.brightness is not None:
        bulb.set_brightness(args.brightness)
    if args.temp is not None:
        bulb.set_color_temp(args.temp)
    elif args.color is not None:
        bulb.set_rgb(args.color[0], args.color[1], args.color[2])
Beispiel #20
0
Version: 0.0.1
https://github.com/Blahnacles
"""
# Setup
# Imports
from tkinter import *
# Hardcoding IP for now, as discover_bulbs() does not work
bedroom_ip = "192.168.1.122"
update_rate = 2000  # UI refresh rate in ms
# TODO set static ip
import yeelight
from yeelight import Bulb
global bedroom
bedroom = Bulb(bedroom_ip)
bedroom.start_music(port=5555)
bedroom_data = bedroom.get_properties()

# setup window
window = Tk()
window.title("PySwitch")
#window.geometry('800x480')

# setup buttons & labels
switch_text = "+"
switch_bg = "black"
switch_fg = "orange"
if bedroom_data['power'] == 'on':
    switch_text = "-"
    switch_bg = "orange"
    switch_fg = "black"
class LedLightYeeLight(LedLight):
    def __init__(self, name, ipAddrOrName=None):
        if ipAddrOrName is None:
            ipAddrOrName = name

        self.bulb = Bulb(ipAddrOrName)
        self.name = name
        try:
            self.bulb.set_name(name)
        except Exception as exc:
            print "Caught exception socket.error : %s" % exc

    # Send an RGB message
    def sendRGB(self, red, green, blue):
        try:
            self.bulb.set_rgb(red, green, blue)
        except Exception as exc:
            print "Caught exception socket.error : %s" % exc

    # Send a white message
    def sendWhite(self, white):
        try:
            self.bulb.set_color_temp(5000)
            self.bulb.set_brightness(white)
        except Exception as exc:
            print "Caught exception socket.error : %s" % exc

    def turnOff(self):
        try:
            return self.bulb.turn_off()
        except Exception as exc:
            print "Caught exception socket.error : %s" % exc

    def turnOn(self):
        try:
            self.bulb.turn_on()
        except Exception as exc:
            print "Caught exception socket.error : %s" % exc

    def isOn(self):
        try:
            return self.bulb.get_properties()['power'] == 'on'
        except Exception as exc:
            print "Caught exception socket.error : %s" % exc

    def getWhite(self):
        try:
            properties = self.bulb.get_properties()
            if (properties['color_mode'] == '2'):
                return int(properties['bright'])
            else:
                return -1
        except Exception as exc:
            print "Caught exception socket.error : %s" % exc


# comment

    def getRGB(self):
        try:
            properties = self.bulb.get_properties()
            if (properties['color_mode'] == '1'):
                rgb = int(properties['rgb'])
                return [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255]
            else:
                return -1
        except Exception as exc:
            print "Caught exception socket.error : %s" % exc
Beispiel #22
0
class YeelightDevice(Device):
    """Yeelight device type."""
    def __init__(self, adapter, _id, dev_dict):
        """
        Initialize the object.

        adapter -- the Adapter managing this device
        _id -- ID of this device
        dev_dict -- the device object to initialize from
        """
        Device.__init__(self, adapter, _id)
        self._type = ['OnOffSwitch', 'Light']

        self.bulb = Bulb(dev_dict['ip'])
        self.description = dev_dict['capabilities']['model']
        self.name = dev_dict['capabilities']['name']
        if not self.name:
            self.name = self.description

        self.support = dev_dict['capabilities']['support'].split(' ')

        self.update_properties()

        if self.is_color():
            self._type.append('ColorControl')

            self.properties['color'] = YeelightProperty(
                self, 'color', {
                    '@type': 'ColorProperty',
                    'label': 'Color',
                    'type': 'string',
                }, self.color())
        elif self.is_variable_color_temp():
            self._type.append('ColorControl')

            self.properties['colorTemperature'] = YeelightProperty(
                self, 'colorTemperature', {
                    '@type': 'ColorTemperatureProperty',
                    'label': 'Color Temperature',
                    'type': 'integer',
                    'unit': 'kelvin',
                    'minimum': 1700,
                    'maximum': 6500,
                }, self.color_temp())

        if self.is_dimmable() and not self.is_color():
            self.properties['level'] = YeelightProperty(
                self, 'level', {
                    '@type': 'BrightnessProperty',
                    'label': 'Brightness',
                    'type': 'integer',
                    'unit': 'percent',
                    'minimum': 0,
                    'maximum': 100,
                }, self.brightness())

        self.properties['on'] = YeelightProperty(self, 'on', {
            '@type': 'OnOffProperty',
            'label': 'On/Off',
            'type': 'boolean',
        }, self.is_on())

        if self.is_color():
            self.type = 'onOffColorLight'
        elif self.is_variable_color_temp():
            if self.is_dimmable():
                self.type = 'dimmableColorLight'
            else:
                self.type = 'onOffColorLight'
        elif self.is_dimmable():
            self.type = 'dimmableLight'
        else:
            self.type = 'onOffLight'

        t = threading.Thread(target=self.poll)
        t.daemon = True
        t.start()

    def poll(self):
        """Poll the device for changes."""
        while True:
            time.sleep(_POLL_INTERVAL)
            self.update_properties()

            for prop in self.properties.values():
                prop.update()

    def update_properties(self):
        """Update the cached properties."""
        try:
            self.bulb_properties = self.bulb.get_properties()
        except socket.error:
            pass

    def is_dimmable(self):
        """Determine whether or not the light is dimmable."""
        return 'set_bright' in self.support

    def is_color(self):
        """Determine whether or not the light is color-changing."""
        return 'set_rgb' in self.support and 'set_hsv' in self.support

    def is_variable_color_temp(self):
        """Determine whether or not the light is color-temp-changing."""
        return 'set_ct_abx' in self.support

    def is_on(self):
        """Determine whether or not the light is on."""
        return self.bulb_properties['power'] == 'on'

    def color_temp(self):
        """Determine the current color temperature."""
        return int(self.bulb_properties['ct'])

    def color(self):
        """Determine the current color of the light."""
        mode = int(self.bulb_properties['color_mode'])

        if mode == 1:
            # RGB mode
            return '#{:06X}'.format(int(self.bulb_properties['rgb']))
        elif mode == 3:
            # HSV mode
            return hsv_to_rgb(int(self.bulb_properties['hue']),
                              int(self.bulb_properties['sat']),
                              int(self.bulb_properties['bright']))
        else:
            # Color temperature mode
            return '#000000'

    def brightness(self):
        """Determine the current brightness of the light."""
        return int(self.bulb_properties['bright'])
Beispiel #23
0
Updated: 12/02/2020
Version: 0.0.1
https://github.com/Blahnacles

To access on local machine: http://192.168.1.106:5000/api
"""
# imports
from flask import Flask, jsonify, request, escape
import yeelight, json
from yeelight import Bulb

# setup
# Hardcoding IP for now, as discover_bulbs() does not work
bedroom_ip = "192.168.1.122"
bedroom = Bulb(bedroom_ip)
if bedroom.get_properties()['music_on']== '0':
    try:
        bedroom.start_music(port=5555)
    except yeelight.BulbException:
        pass


app = Flask(__name__)
@app.route("/api", methods=['GET','POST','PUT','DELETE'])
def handle():
    responseBool = False
    if request.method == 'GET':
        return json.dumps(Bulb(bedroom_ip).get_properties())
    elif request.method == 'POST':
        try:
            bright = int(request.form['brightness'])