def get_light_state(address, light): logging.debug("tasmota: <get_light_state> invoked!") data = sendRequest("http://" + address["ip"] + "/cm?cmnd=Status%2011") #logging.debug(data) light_data = json.loads(data)["StatusSTS"] #logging.debug(light_data) state = {} if 'POWER' in light_data: state['on'] = True if light_data["POWER"] == "ON" else False #logging.debug('POWER') elif 'POWER1' in light_data: state['on'] = True if light_data["POWER1"] == "ON" else False #logging.debug('POWER1') if 'Color' not in light_data: #logging.debug('not Color') if state['on'] == True: state["xy"] = convert_rgb_xy(255, 255, 255) state["bri"] = int(255) state["colormode"] = "xy" else: #logging.debug('Color') hex = light_data["Color"] rgb = hex_to_rgb(hex) logging.debug(rgb) #rgb = light_data["Color"].split(",") logging.debug("tasmota: <get_light_state>: red " + str(rgb[0]) + " green " + str(rgb[1]) + " blue " + str(rgb[2])) # state["xy"] = convert_rgb_xy(int(rgb[0],16), int(rgb[1],16), int(rgb[2],16)) state["xy"] = convert_rgb_xy(rgb[0], rgb[1], rgb[2]) state["bri"] = (int(light_data["Dimmer"]) / 100.0) * 254.0 state["colormode"] = "xy" return state
def get_light_state(light): c = connect(light) state = {} light_data = c.get_properties() prefix = '' if light.protocol_cfg["backlight"]: prefix = "bg_" if light_data[prefix + "power"] == "on": #powerstate state['on'] = True else: state['on'] = False state["bri"] = int(int(light_data[prefix + "bright"]) * 2.54) if light_data["color_mode"] == "1": #rgb mode hex_rgb = "%06x" % int(light_data[prefix + "rgb"]) rgb=hex_to_rgb(hex_rgb) state["xy"] = convert_rgb_xy(rgb[0],rgb[1],rgb[2]) state["colormode"] = "xy" elif light_data["color_mode"] == "2": #ct mode state["ct"] = calculate_color_temp(light_data[prefix + "ct"]) state["colormode"] = "ct" elif light_data["color_mode"] == "3": #hs mode state["hue"] = int(light_data[prefix + "hue"] * 182) state["sat"] = int(light_data[prefix + "sat"] * 2.54) state["colormode"] = "hs" return state
def get_light_state(address, light): ip = address["ip"] if ip in Connections: c = Connections[ip] else: c = HyperionConnection(ip, address["jss_port"]) Connections[ip] = c state = {"on": False} c.command({"command": "serverinfo"}) try: response = c.recv(1024 * 1024).decode('utf-8').split("\r\n") for data in response: info = json.loads(data) if "success" in info and info["success"] == True and len( info["info"]["priorities"]) >= 0: activeColor = info["info"]["priorities"][0] if activeColor["priority"] == PRIORITY: rgb = activeColor["value"]["RGB"] state["on"] = True state["xy"] = convert_rgb_xy(rgb[0], rgb[1], rgb[2]) state["bri"] = max(rgb[0], rgb[1], rgb[2]) state["colormode"] = "xy" except Exception as e: logging.warning(e) return {'reachable': False} return state
def set_light(light, data): payload = {} url = "coaps://" + light.protocol_cfg["ip"] + ":5684/15001/" + str( light.protocol_cfg["id"]) for key, value in data.items(): if key == "on": payload["5850"] = int(value) elif key == "transitiontime": payload["5712"] = value elif key == "bri": if value > 254: value = 254 payload["5851"] = value elif key == "ct": if value < 270: payload["5706"] = "f5faf6" elif value < 385: payload["5706"] = "f1e0b5" else: payload["5706"] = "efd275" elif key == "xy": payload["5709"] = int(value[0] * 65535) payload["5710"] = int(value[1] * 65535) if "hue" in data or "sat" in data: if ("hue" in data): hue = data["hue"] else: hue = lights[light]["state"]["hue"] if ("sat" in data): sat = data["sat"] else: sat = lights[light]["state"]["sat"] if ("bri" in data): bri = data["bri"] else: bri = lights[light]["state"]["bri"] rgbValue = hsv_to_rgb(hue, sat, bri) xyValue = convert_rgb_xy(rgbValue[0], rgbValue[1], rgbValue[2]) payload["5709"] = int(xyValue[0] * 65535) payload["5710"] = int(xyValue[1] * 65535) if "5850" in payload and payload["5850"] == 0: payload.clear( ) #setting brightnes will turn on the ligh even if there was a request to power off payload["5850"] = 0 elif "5850" in payload and "5851" in payload: #when setting brightness don't send also power on command del payload["5850"] if "5712" not in payload: payload[ "5712"] = 4 #If no transition add one, might also add check to prevent large transitiontimes check_output("./coap-client-linux -B 2 -m put -u \"" + light.protocol_cfg["identity"] + "\" -k \"" + light.protocol_cfg["psk"] + "\" -e '{ \"3311\": [" + json.dumps(payload) + "] }' \"" + url + "\"", shell=True)
def get_light_state(address, light): #logging.info("name is: " + light["name"]) #if light["name"].find("desklamp") > 0: logging.info("is desk lamp") state = {} tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.settimeout(5) tcp_socket.connect((address["ip"], int(55443))) msg=json.dumps({"id": 1, "method": "get_prop", "params":["power","bright"]}) + "\r\n" tcp_socket.send(msg.encode()) data = tcp_socket.recv(16 * 1024) light_data = json.loads(data[:-2].decode("utf8"))["result"] if light_data[0] == "on": #powerstate state['on'] = True else: state['on'] = False state["bri"] = int(int(light_data[1]) * 2.54) #if ip[:-3] == "201" or ip[:-3] == "202": if light["name"].find("desklamp") > 0: msg_ct=json.dumps({"id": 1, "method": "get_prop", "params":["ct"]}) + "\r\n" tcp_socket.send(msg_ct.encode()) data = tcp_socket.recv(16 * 1024) tempval = int(-(347/4800) * int(json.loads(data[:-2].decode("utf8"))["result"][0]) +(2989900/4800)) if tempval > 369: tempval = 369 state["ct"] = tempval # int(-(347/4800) * int(json.loads(data[:-2].decode("utf8"))["result"][0]) +(2989900/4800)) state["colormode"] = "ct" else: msg_mode=json.dumps({"id": 1, "method": "get_prop", "params":["color_mode"]}) + "\r\n" tcp_socket.send(msg_mode.encode()) data = tcp_socket.recv(16 * 1024) if json.loads(data[:-2].decode("utf8"))["result"][0] == "1": #rgb mode msg_rgb=json.dumps({"id": 1, "method": "get_prop", "params":["rgb"]}) + "\r\n" tcp_socket.send(msg_rgb.encode()) data = tcp_socket.recv(16 * 1024) hue_data = json.loads(data[:-2].decode("utf8"))["result"] hex_rgb = "%6x" % int(json.loads(data[:-2].decode("utf8"))["result"][0]) rgb=hex_to_rgb(hex_rgb) state["xy"] = convert_rgb_xy(rgb[0],rgb[1],rgb[2]) state["colormode"] = "xy" elif json.loads(data[:-2].decode("utf8"))["result"][0] == "2": #ct mode msg_ct=json.dumps({"id": 1, "method": "get_prop", "params":["ct"]}) + "\r\n" tcp_socket.send(msg_ct.encode()) data = tcp_socket.recv(16 * 1024) state["ct"] = int(-(347/4800) * int(json.loads(data[:-2].decode("utf8"))["result"][0]) +(2989900/4800)) state["colormode"] = "ct" elif json.loads(data[:-2].decode("utf8"))["result"][0] == "3": #hs mode msg_hsv=json.dumps({"id": 1, "method": "get_prop", "params":["hue","sat"]}) + "\r\n" tcp_socket.send(msg_hsv.encode()) data = tcp_socket.recv(16 * 1024) hue_data = json.loads(data[:-2].decode("utf8"))["result"] state["hue"] = int(int(hue_data[0]) * 182) state["sat"] = int(int(hue_data[1]) * 2.54) state["colormode"] = "hs" tcp_socket.close() return state
def get_light_state(ip, light): logging.debug("tasmota: <get_light_state> invoked!") data = sendRequest ("http://" + ip + "/cm?cmnd=Status%2011") light_data = json.loads(data)["StatusSTS"] rgb = light_data["Color"].split(",") logging.debug("tasmota: <get_light_state>: red " + str(rgb[0]) + " green " + str(rgb[1]) + " blue " + str(rgb[2]) ) state = {} state['on'] = True if light_data["POWER"] == "ON" else False state["xy"] = convert_rgb_xy(int(rgb[0],16), int(rgb[1],16), int(rgb[2],16)) state["colormode"] = "xy" return state
def getSegState(self, seg): state = {} data = self.getLightState()['state'] seg = data['seg'][seg] state['bri'] = seg['bri'] state['on'] = data['on'] # Get on/off at light level state['bri'] = seg['bri'] # Weird division by zero when a color is 0 r = int(seg['col'][0][0]) + 1 g = int(seg['col'][0][1]) + 1 b = int(seg['col'][0][2]) + 1 state['xy'] = convert_rgb_xy(r, g, b) state["colormode"] = "xy" return state
def get_light_state(address, light): state = {} tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.settimeout(5) tcp_socket.connect((address["ip"], int(55443))) data = get_prop_data(tcp_socket, ["power", "bright"]) light_data = data_to_result(data) if light_data[0] == "on": #powerstate state['on'] = True else: state['on'] = False state["bri"] = int(int(light_data[1]) * 2.54) #if ip[:-3] == "201" or ip[:-3] == "202": if light["name"].find("desklamp") > 0: data = get_prop_data(tcp_socket, ["ct"]) tempval = calculate_color_temp(data_to_result(data)[0]) state["ct"] = min(tempval, 369) state["colormode"] = "ct" else: data = get_prop_data(tcp_socket, ["color_mode"]) light_mode = data_to_result(data)[0] if light_mode == "1": #rgb mode data = get_prop_data(tcp_socket, ["rgb"]) hue_data = data_to_result(data) hex_rgb = "%06x" % int(data_to_result(data)[0]) rgb = hex_to_rgb(hex_rgb) state["xy"] = convert_rgb_xy(rgb[0], rgb[1], rgb[2]) state["colormode"] = "xy" elif light_mode == "2": #ct mode data = get_prop_data(tcp_socket, ["ct"]) state["ct"] = calculate_color_temp(data_to_result(data)[0]) state["colormode"] = "ct" elif light_mode == "3": #hs mode data = get_prop_data(tcp_socket, ["hue", "sat"]) hue_data = data_to_result(data) state["hue"] = int(int(hue_data[0]) * 182) state["sat"] = int(int(hue_data[1]) * 2.54) state["colormode"] = "hs" tcp_socket.close() return state
def entertainmentService(group, user): logging.debug("User: "******"Key: " + user.client_key) lights_v2 = [] lights_v1 = {} hueGroup = -1 hueGroupLights = {} for light in group.lights: lights_v1[int(light().id_v1)] = light() if light().protocol == "hue" and get_hue_entertainment_group(light(), group.name) != -1: # If the lights' Hue bridge has an entertainment group with the same name as this current group, we use it to sync the lights. hueGroup = get_hue_entertainment_group(light(), group.name) hueGroupLights[int(light().protocol_cfg["id"])] = [] # Add light id to list bridgeConfig["lights"][light().id_v1].state["mode"] = "streaming" v2LightNr = {} for channel in group.getV2Api()["channels"]: lightObj = getObject(channel["members"][0]["service"]["rid"]) if lightObj.id_v1 not in v2LightNr: v2LightNr[lightObj.id_v1] = 0 else: v2LightNr[lightObj.id_v1] += 1 lights_v2.append({"light": lightObj, "lightNr": v2LightNr[lightObj.id_v1]}) logging.debug(lights_v1) logging.debug(lights_v2) opensslCmd = ['openssl', 's_server', '-dtls', '-psk', user.client_key, '-psk_identity', user.username, '-nocert', '-accept', '2100', '-quiet'] p = Popen(opensslCmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) if hueGroup != -1: # If we have found a hue Brige containing a suitable entertainment group for at least one Lamp, we connect to it h = HueConnection(bridgeConfig["config"]["hue"]["ip"]) h.connect(hueGroup, hueGroupLights) if h._connected == False: hueGroupLights = {} # on a failed connection, empty the list init = False frameBites = 10 frameID = 1 initMatchBytes = 0 host_ip = bridgeConfig["config"]["ipaddress"] p.stdout.read(1) # read one byte so the init function will correctly detect the frameBites try: while bridgeConfig["groups"][group.id_v1].stream["active"]: if not init: readByte = p.stdout.read(1) logging.debug(readByte) if readByte in b'\x48\x75\x65\x53\x74\x72\x65\x61\x6d': initMatchBytes += 1 else: initMatchBytes = 0 if initMatchBytes == 9: frameBites = frameID - 8 logging.debug("frameBites: " + str(frameBites)) p.stdout.read(frameBites - 9) # sync streaming bytes init = True frameID += 1 else: data = p.stdout.read(frameBites) logging.debug(",".join('{:02x}'.format(x) for x in data)) nativeLights = {} esphomeLights = {} mqttLights = [] wledLights = {} if data[:9].decode('utf-8') == "HueStream": i = 0 apiVersion = 0 counter = 0 if data[9] == 1: #api version 1 i = 16 apiVersion = 1 counter = len(data) elif data[9] == 2: #api version 1 i = 52 apiVersion = 2 counter = len(group.getV2Api()["channels"]) * 7 + 52 channels = {} while (i < counter): light = None r,g,b = 0,0,0 if apiVersion == 1: if (data[i+1] * 256 + data[i+2]) in channels: channels[data[i+1] * 256 + data[i+2]] += 1 else: channels[data[i+1] * 256 + data[i+2]] = 0 if data[i] == 0: # Type of device 0x00 = Light if data[i+1] * 256 + data[i+2] == 0: break light = lights_v1[data[i+1] * 256 + data[i+2]] elif data[i] == 1: # Type of device Gradient Strip light = findGradientStrip(group) if data[14] == 0: #rgb colorspace r = int((data[i+3] * 256 + data[i+4]) / 256) g = int((data[i+5] * 256 + data[i+6]) / 256) b = int((data[i+7] * 256 + data[i+8]) / 256) elif data[14] == 1: #cie colorspace x = (data[i+3] * 256 + data[i+4]) / 65535 y = (data[i+5] * 256 + data[i+6]) / 65535 bri = int((data[i+7] * 256 + data[i+8]) / 256) r, g, b = convert_xy(x, y, bri) elif apiVersion == 2: light = lights_v2[data[i]]["light"] if data[14] == 0: #rgb colorspace r = int((data[i+1] * 256 + data[i+2]) / 256) g = int((data[i+3] * 256 + data[i+4]) / 256) b = int((data[i+5] * 256 + data[i+6]) / 256) elif data[14] == 1: #cie colorspace x = (data[i+1] * 256 + data[i+2]) / 65535 y = (data[i+3] * 256 + data[i+4]) / 65535 bri = int((data[i+5] * 256 + data[i+6]) / 256) r, g, b = convert_xy(x, y, bri) if light == None: logging.info("error in light identification") break logging.debug("Light:" + str(light.name) + " RED: " + str(r) + ", GREEN: " + str(g) + ", BLUE: " + str(b) ) proto = light.protocol if r == 0 and g == 0 and b == 0: light.state["on"] = False else: light.state.update({"on": True, "bri": int((r + g + b) / 3), "xy": convert_rgb_xy(r, g, b), "colormode": "xy"}) if proto in ["native", "native_multi", "native_single"]: if light.protocol_cfg["ip"] not in nativeLights: nativeLights[light.protocol_cfg["ip"]] = {} if apiVersion == 1: if light.modelid in ["LCX001", "LCX002", "LCX003", "915005987201", "LCX004"]: if data[i] == 1: # individual strip address nativeLights[light.protocol_cfg["ip"]][data[i+1] * 256 + data[i+2]] = [r, g, b] elif data[i] == 0: # individual strip address for x in range(7): nativeLights[light.protocol_cfg["ip"]][x] = [r, g, b] else: nativeLights[light.protocol_cfg["ip"]][light.protocol_cfg["light_nr"] - 1] = [r, g, b] elif apiVersion == 2: if light.modelid in ["LCX001", "LCX002", "LCX003", "915005987201", "LCX004"]: nativeLights[light.protocol_cfg["ip"]][lights_v2[data[i]]["lightNr"]] = [r, g, b] else: nativeLights[light.protocol_cfg["ip"]][light.protocol_cfg["light_nr"] - 1] = [r, g, b] elif proto == "esphome": if light.protocol_cfg["ip"] not in esphomeLights: esphomeLights[light.protocol_cfg["ip"]] = {} bri = int(max(r,g,b)) esphomeLights[light.protocol_cfg["ip"]]["color"] = [r, g, b, bri] elif proto == "mqtt": operation = skipSimilarFrames(light.id_v1, light.state["xy"], light.state["bri"]) if operation == 1: mqttLights.append({"topic": light.protocol_cfg["command_topic"], "payload": json.dumps({"brightness": light.state["bri"], "transition": 0.2})}) elif operation == 2: mqttLights.append({"topic": light.protocol_cfg["command_topic"], "payload": json.dumps({"color": {"x": light.state["xy"][0], "y": light.state["xy"][1]}, "transition": 0.15})}) elif proto == "yeelight": enableMusic(light.protocol_cfg["ip"], host_ip) c = YeelightConnections[light.protocol_cfg["ip"]] operation = skipSimilarFrames(light.id_v1, light.state["xy"], light.state["bri"]) if operation == 1: c.command("set_bright", [int(light.state["bri"] / 2.55), "smooth", 200]) #c.command("set_bright", [int(bridgeConfig["lights"][str(lightId)]["state"]["bri"] / 2.55), "sudden", 0]) elif operation == 2: c.command("set_rgb", [(r * 65536) + (g * 256) + b, "smooth", 200]) #c.command("set_rgb", [(r * 65536) + (g * 256) + b, "sudden", 0]) elif proto == "wled": if light.protocol_cfg["ip"] not in wledLights: wledLights[light.protocol_cfg["ip"]] = {} wledLights[light.protocol_cfg["ip"] ]["ledCount"] = light.protocol_cfg["ledCount"] wledLights[light.protocol_cfg["ip"] ]["color"] = [r, g, b] elif proto == "hue" and int(light.protocol_cfg["id"]) in hueGroupLights: hueGroupLights[int(light.protocol_cfg["id"])] = [r,g,b] else: if frameID % 4 == 0: # can use 2, 4, 6, 8, 12 => increase in case the destination device is overloaded operation = skipSimilarFrames(light.id_v1, light.state["xy"], light.state["bri"]) if operation == 1: light.setV1State({"bri": light.state["bri"], "transitiontime": 3}) elif operation == 2: light.setV1State({"xy": light.state["xy"], "transitiontime": 3}) frameID += 1 if frameID == 25: frameID = 1 if apiVersion == 1: i = i + 9 elif apiVersion == 2: i = i + 7 if len(nativeLights) != 0: for ip in nativeLights.keys(): udpmsg = bytearray() for light in nativeLights[ip].keys(): udpmsg += bytes([light]) + bytes([nativeLights[ip][light][0]]) + bytes([nativeLights[ip][light][1]]) + bytes([nativeLights[ip][light][2]]) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(udpmsg, (ip.split(":")[0], 2100)) if len(esphomeLights) != 0: for ip in esphomeLights.keys(): udpmsg = bytearray() udpmsg += bytes([0]) + bytes([esphomeLights[ip]["color"][0]]) + bytes([esphomeLights[ip]["color"][1]]) + bytes([esphomeLights[ip]["color"][2]]) + bytes([esphomeLights[ip]["color"][3]]) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(udpmsg, (ip.split(":")[0], 2100)) if len(mqttLights) != 0: auth = None if bridgeConfig["config"]["mqtt"]["mqttUser"] != "" and bridgeConfig["config"]["mqtt"]["mqttPassword"] != "": auth = {'username':bridgeConfig["config"]["mqtt"]["mqttUser"], 'password':bridgeConfig["config"]["mqtt"]["mqttPassword"]} publish.multiple(mqttLights, hostname=bridgeConfig["config"]["mqtt"]["mqttServer"], port=bridgeConfig["config"]["mqtt"]["mqttPort"], auth=auth) if len(wledLights) != 0: wled_udpmode = 2 wled_secstowait = 2 for ip in wledLights.keys(): udphead = [wled_udpmode, wled_secstowait] color = wledLights[ip]["color"] * int(wledLights[ip]["ledCount"]) udpdata = bytes(udphead+color) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(udpdata, (ip.split(":")[0], 21324)) if len(hueGroupLights) != 0: h.send(hueGroupLights, hueGroup) else: logging.info("HueStream was missing in the frame") p.kill() try: h.disconnect() except UnboundLocalError: pass except Exception as e: #Assuming the only exception is a network timeout, please don't scream at me logging.info("Entertainment Service was syncing and has timed out, stopping server and clearing state" + str(e)) p.kill() try: h.disconnect() except UnboundLocalError: pass bridgeConfig["groups"][group.id_v1].stream["active"] = False for light in group.lights: bridgeConfig["lights"][light().id_v1].state["mode"] = "homeautomation" logging.info("Entertainment service stopped")
def entertainmentService(lights, addresses, groups, host_ip): serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) serverSocket.settimeout(3) #Set a packet timeout that we catch later serverSocket.bind(('127.0.0.1', 2101)) frameID = 0 lightStatus = {} syncing = False #Flag to check whether or not we had been syncing when a timeout occurs while True: try: data = serverSocket.recvfrom(106)[0] nativeLights = {} esphomeLights = {} if data[:9].decode('utf-8') == "HueStream": syncing = True #Set sync flag when receiving valid data if data[14] == 0: #rgb colorspace i = 16 while i < len(data): if data[i] == 0: #Type of device 0x00 = Light lightId = data[i+1] * 256 + data[i+2] if lightId != 0: r = int((data[i+3] * 256 + data[i+4]) / 256) g = int((data[i+5] * 256 + data[i+6]) / 256) b = int((data[i+7] * 256 + data[i+8]) / 256) proto = addresses[str(lightId)]["protocol"] if lightId not in lightStatus: lightStatus[lightId] = {"on": False, "bri": 1} if r == 0 and g == 0 and b == 0: lights[str(lightId)]["state"]["on"] = False else: lights[str(lightId)]["state"].update({"on": True, "bri": int((r + g + b) / 3), "xy": convert_rgb_xy(r, g, b), "colormode": "xy"}) if proto in ["native", "native_multi", "native_single"]: if addresses[str(lightId)]["ip"] not in nativeLights: nativeLights[addresses[str(lightId)]["ip"]] = {} nativeLights[addresses[str(lightId)]["ip"]][addresses[str(lightId)]["light_nr"] - 1] = [r, g, b] elif proto == "esphome": if addresses[str(lightId)]["ip"] not in esphomeLights: esphomeLights[addresses[str(lightId)]["ip"]] = {} bri = int(max(r,g,b)) esphomeLights[addresses[str(lightId)]["ip"]]["color"] = [r, g, b, bri] else: if frameID == 24: # => every seconds, increase in case the destination device is overloaded gottaSend = False yee = proto == "yeelight" brABS = abs(int((r + b + g) / 3) - lightStatus[lightId]["bri"]) if r == 0 and g == 0 and b == 0: #Turn off if color is black if lightStatus[lightId]["on"]: sendLightRequest(str(lightId), {"on": False, "transitiontime": 3}, lights, addresses, None, host_ip) lightStatus[lightId]["on"] = False else: if lightStatus[lightId]["on"] == False: #Turn on if color is not black sendLightRequest(str(lightId), {"on": True, "transitiontime": 3}, lights, addresses, None, host_ip) lightStatus[lightId]["on"] = True elif brABS > 50: # to optimize, send brightness only if difference is bigger than this value sendLightRequest(str(lightId), {"bri": int((r + b + g) / 3), "transitiontime": 150 / brABS}, lights, addresses, None, host_ip) lightStatus[lightId]["bri"] = int((r + b + g) / 3) else: gottaSend = True if gottaSend or yee: sendLightRequest(str(lightId), {"xy": convert_rgb_xy(r, g, b), "transitiontime": 3}, lights, addresses, [r, g, b], host_ip) frameID += 1 if frameID == 25: frameID = 0 i = i + 9 elif data[14] == 1: #cie colorspace i = 16 while i < len(data): if data[i] == 0: #Type of device 0x00 = Light lightId = data[i+1] * 256 + data[i+2] if lightId != 0: x = (data[i+3] * 256 + data[i+4]) / 65535 y = (data[i+5] * 256 + data[i+6]) / 65535 bri = int((data[i+7] * 256 + data[i+8]) / 256) if bri == 0: lights[str(lightId)]["state"]["on"] = False else: lights[str(lightId)]["state"].update({"on": True, "bri": bri, "xy": [x,y], "colormode": "xy"}) if addresses[str(lightId)]["protocol"] in ["native", "native_multi", "native_single"]: if addresses[str(lightId)]["ip"] not in nativeLights: nativeLights[addresses[str(lightId)]["ip"]] = {} nativeLights[addresses[str(lightId)]["ip"]][addresses[str(lightId)]["light_nr"] - 1] = convert_xy(x, y, bri) elif addresses[str(lightId)]["protocol"] == "esphome": if addresses[str(lightId)]["ip"] not in esphomeLights: esphomeLights[addresses[str(lightId)]["ip"]] = {} r, g, b = convert_xy(x, y, bri) esphomeLights[addresses[str(lightId)]["ip"]]["color"] = [r, g, b, bri] else: frameID += 1 if frameID == 24 : #24 = every seconds, increase in case the destination device is overloaded sendLightRequest(str(lightId), {"xy": [x,y]}, lights, addresses, None, host_ip) frameID = 0 i = i + 9 if len(nativeLights) != 0: for ip in nativeLights.keys(): udpmsg = bytearray() for light in nativeLights[ip].keys(): udpmsg += bytes([light]) + bytes([nativeLights[ip][light][0]]) + bytes([nativeLights[ip][light][1]]) + bytes([nativeLights[ip][light][2]]) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(udpmsg, (ip.split(":")[0], 2100)) if len(esphomeLights) != 0: for ip in esphomeLights.keys(): udpmsg = bytearray() udpmsg += bytes([0]) + bytes([esphomeLights[ip]["color"][0]]) + bytes([esphomeLights[ip]["color"][1]]) + bytes([esphomeLights[ip]["color"][2]]) + bytes([esphomeLights[ip]["color"][3]]) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(udpmsg, (ip.split(":")[0], 2100)) except Exception: #Assuming the only exception is a network timeout, please don't scream at me if syncing: #Reset sync status and kill relay service logging.info("Entertainment Service was syncing and has timed out, stopping server and clearing state") Popen(["killall", "entertain-srv"]) for group in groups.keys(): if "type" in groups[group] and groups[group]["type"] == "Entertainment": groups[group]["stream"].update({"active": False, "owner": None}) syncing = False
def sendLightRequest(light, data, lights, addresses): payload = {} if light in addresses: protocol_name = addresses[light]["protocol"] for protocol in protocols: if "protocols." + protocol_name == protocol.__name__: try: light_state = protocol.set_light(addresses[light], lights[light], data) except Exception as e: lights[light]["state"]["reachable"] = False logging.warning(lights[light]["name"] + " light not reachable: %s", e) return if addresses[light]["protocol"] == "native": #ESP8266 light or strip url = "http://" + addresses[light]["ip"] + "/set?light=" + str(addresses[light]["light_nr"]) method = 'GET' for key, value in data.items(): if key == "xy": url += "&x=" + str(value[0]) + "&y=" + str(value[1]) else: url += "&" + key + "=" + str(value) elif addresses[light]["protocol"] in ["hue","deconz"]: #Original Hue light or Deconz light url = "http://" + addresses[light]["ip"] + "/api/" + addresses[light]["username"] + "/lights/" + addresses[light]["light_id"] + "/state" method = 'PUT' payload.update(data) elif addresses[light]["protocol"] == "domoticz": #Domoticz protocol url = "http://" + addresses[light]["ip"] + "/json.htm?type=command&idx=" + addresses[light]["light_id"] method = 'GET' if "on" in data and not "bri" in data and not "ct" in data and not "xy" in data: for key, value in data.items(): url += "¶m=switchlight" if key == "on": if value: url += "&switchcmd=On" else: url += "&switchcmd=Off" else: url += "¶m=setcolbrightnessvalue" color_data = {} old_light_state = lights[light]["state"] colormode = old_light_state["colormode"] ct = old_light_state["ct"] bri = old_light_state["bri"] xy = old_light_state["xy"] if "bri" in data: bri = data["bri"] if "ct" in data: ct = data["ct"] if "xy" in data: xy = data["xy"] bri = int(bri) color_data["m"] = 1 #0: invalid, 1: white, 2: color temp, 3: rgb, 4: custom if colormode == "ct": color_data["m"] = 2 ct01 = (ct - 153) / (500 - 153) #map color temperature from 153-500 to 0-1 ct255 = ct01 * 255 #map color temperature from 0-1 to 0-255 color_data["t"] = ct255 elif colormode == "xy": color_data["m"] = 3 (color_data["r"], color_data["g"], color_data["b"]) = convert_xy(xy[0], xy[1], 255) url += "&color="+json.dumps(color_data) url += "&brightness=" + str(round(float(bri)/255*100)) urlObj = {} urlObj["url"] = url elif addresses[light]["protocol"] == "jeedom": #Jeedom protocol url = "http://" + addresses[light]["ip"] + "/core/api/jeeApi.php?apikey=" + addresses[light]["light_api"] + "&type=cmd&id=" method = 'GET' for key, value in data.items(): if key == "on": if value: url += addresses[light]["light_on"] else: url += addresses[light]["light_off"] elif key == "bri": url += addresses[light]["light_slider"] + "&slider=" + str(round(float(value)/255*100)) # jeedom range from 0 to 100 (for zwave devices) instead of 0-255 of bridge elif addresses[light]["protocol"] == "milight": #MiLight bulb url = "http://" + addresses[light]["ip"] + "/gateways/" + addresses[light]["device_id"] + "/" + addresses[light]["mode"] + "/" + str(addresses[light]["group"]) method = 'PUT' for key, value in data.items(): if key == "on": payload["status"] = value elif key == "bri": payload["brightness"] = value elif key == "ct": payload["color_temp"] = int(value / 1.6 + 153) elif key == "hue": payload["hue"] = value / 180 elif key == "sat": payload["saturation"] = value * 100 / 255 elif key == "xy": payload["color"] = {} (payload["color"]["r"], payload["color"]["g"], payload["color"]["b"]) = convert_xy(value[0], value[1], lights[light]["state"]["bri"]) logging.info(json.dumps(payload)) elif addresses[light]["protocol"] == "ikea_tradfri": #IKEA Tradfri bulb url = "coaps://" + addresses[light]["ip"] + ":5684/15001/" + str(addresses[light]["device_id"]) for key, value in data.items(): if key == "on": payload["5850"] = int(value) elif key == "transitiontime": payload["5712"] = value elif key == "bri": payload["5851"] = value elif key == "ct": if value < 270: payload["5706"] = "f5faf6" elif value < 385: payload["5706"] = "f1e0b5" else: payload["5706"] = "efd275" elif key == "xy": payload["5709"] = int(value[0] * 65535) payload["5710"] = int(value[1] * 65535) if "hue" in data or "sat" in data: if("hue" in data): hue = data["hue"] else: hue = lights[light]["state"]["hue"] if("sat" in data): sat = data["sat"] else: sat = lights[light]["state"]["sat"] if("bri" in data): bri = data["bri"] else: bri = lights[light]["state"]["bri"] rgbValue = hsv_to_rgb(hue, sat, bri) xyValue = convert_rgb_xy(rgbValue[0], rgbValue[1], rgbValue[2]) payload["5709"] = int(xyValue[0] * 65535) payload["5710"] = int(xyValue[1] * 65535) if "5850" in payload and payload["5850"] == 0: payload.clear() #setting brightnes will turn on the ligh even if there was a request to power off payload["5850"] = 0 elif "5850" in payload and "5851" in payload: #when setting brightness don't send also power on command del payload["5850"] elif addresses[light]["protocol"] == "flex": msg = bytearray() if "on" in data: if data["on"]: msg = bytearray([0x71, 0x23, 0x8a, 0x0f]) else: msg = bytearray([0x71, 0x24, 0x8a, 0x0f]) checksum = sum(msg) & 0xFF msg.append(checksum) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(msg, (addresses[light]["ip"], 48899)) if ("bri" in data and lights[light]["state"]["colormode"] == "xy") or "xy" in data: logging.info(pretty_json(data)) bri = data["bri"] if "bri" in data else lights[light]["state"]["bri"] xy = data["xy"] if "xy" in data else lights[light]["state"]["xy"] rgb = convert_xy(xy[0], xy[1], bri) msg = bytearray([0x41, rgb[0], rgb[1], rgb[2], 0x00, 0xf0, 0x0f]) checksum = sum(msg) & 0xFF msg.append(checksum) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(msg, (addresses[light]["ip"], 48899)) elif ("bri" in data and lights[light]["state"]["colormode"] == "ct") or "ct" in data: bri = data["bri"] if "bri" in data else lights[light]["state"]["bri"] msg = bytearray([0x41, 0x00, 0x00, 0x00, bri, 0x0f, 0x0f]) checksum = sum(msg) & 0xFF msg.append(checksum) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(msg, (addresses[light]["ip"], 48899)) try: if addresses[light]["protocol"] == "ikea_tradfri": if "5712" not in payload: payload["5712"] = 4 #If no transition add one, might also add check to prevent large transitiontimes check_output("./coap-client-linux -m put -u \"" + addresses[light]["identity"] + "\" -k \"" + addresses[light]["preshared_key"] + "\" -e '{ \"3311\": [" + json.dumps(payload) + "] }' \"" + url + "\"", shell=True) elif addresses[light]["protocol"] in ["hue", "deconz"]: color = {} if "xy" in payload: color["xy"] = payload["xy"] del(payload["xy"]) elif "ct" in payload: color["ct"] = payload["ct"] del(payload["ct"]) elif "hue" in payload: color["hue"] = payload["hue"] del(payload["hue"]) elif "sat" in payload: color["sat"] = payload["sat"] del(payload["sat"]) if len(payload) != 0: sendRequest(url, method, json.dumps(payload)) if addresses[light]["protocol"] == "deconz": sleep(0.7) if len(color) != 0: sendRequest(url, method, json.dumps(color)) else: sendRequest(url, method, json.dumps(payload)) except: lights[light]["state"]["reachable"] = False logging.info("request error") else: lights[light]["state"]["reachable"] = True logging.info("LightRequest: " + url)
def get_light_state(address, light): logging.debug("ESPHome: <get_light_state> invoked!") state = {} if address["esphome_model"] == "ESPHome-RGBW": white_response = requests.get("http://" + address["ip"] + "/light/white_led", timeout=3) color_response = requests.get("http://" + address["ip"] + "/light/color_led", timeout=3) white_device = json.loads(white_response.text) # get white device data color_device = json.loads(color_response.text) # get color device data if white_device['state'] == 'OFF' and color_device['state'] == 'OFF': state['on'] = False elif white_device['state'] == 'ON': state['on'] = True state['ct'] = int(white_device['color_temp']) state['bri'] = int(white_device['brightness']) state['colormode'] = "ct" elif color_device['state'] == 'ON': state['on'] = True state['xy'] = convert_rgb_xy(int(color_device['color']['r']), int(color_device['color']['g']), int(color_device['color']['b'])) state['bri'] = int(color_device['brightness']) state['colormode'] = "xy" elif address["esphome_model"] == "ESPHome-CT": white_response = requests.get("http://" + address["ip"] + "/light/white_led", timeout=3) white_device = json.loads(white_response.text) # get white device data if white_device['state'] == 'OFF': state['on'] = False elif white_device['state'] == 'ON': state['on'] = True state['ct'] = int(white_device['color_temp']) state['bri'] = int(white_device['brightness']) state['colormode'] = "ct" elif address["esphome_model"] == "ESPHome-RGB": color_response = requests.get("http://" + address["ip"] + "/light/color_led", timeout=3) color_device = json.loads(color_response.text) if color_device['state'] == 'OFF': state['on'] = False elif color_device['state'] == 'ON': state['on'] = True state['xy'] = convert_rgb_xy(int(color_device['color']['r']), int(color_device['color']['g']), int(color_device['color']['b'])) state['bri'] = int(color_device['brightness']) state['colormode'] = "xy" elif address["esphome_model"] == "ESPHome-Dimmable": dimmable_response = requests.get("http://" + address["ip"] + "/light/dimmable_led", timeout=3) dimmable_device = json.loads(dimmable_response.text) if dimmable_device['state'] == 'OFF': state['on'] = False elif dimmable_device['state'] == 'ON': state['on'] = True state['bri'] = int(dimmable_device['brightness']) elif address["esphome_model"] == "ESPHome-Toggle": toggle_response = requests.get("http://" + address["ip"] + "/light/toggle_led", timeout=3) toggle_device = json.loads(toggle_response.text) if toggle_device['state'] == 'OFF': state['on'] = False elif toggle_device['state'] == 'ON': state['on'] = True return state
def get_light_state(ip, light): state = {} tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.settimeout(5) tcp_socket.connect((ip, int(55443))) msg = json.dumps({ "id": 1, "method": "get_prop", "params": ["power", "bright"] }) + "\r\n" tcp_socket.send(msg.encode()) data = tcp_socket.recv(16 * 1024) light_data = json.loads(data[:-2].decode("utf8"))["result"] if light_data[0] == "on": #powerstate state['on'] = True else: state['on'] = False state["bri"] = int(int(light_data[1]) * 2.54) msg_mode = json.dumps({ "id": 1, "method": "get_prop", "params": ["color_mode"] }) + "\r\n" tcp_socket.send(msg_mode.encode()) data = tcp_socket.recv(16 * 1024) if json.loads(data[:-2].decode("utf8"))["result"][0] == "1": #rgb mode msg_rgb = json.dumps({ "id": 1, "method": "get_prop", "params": ["rgb"] }) + "\r\n" tcp_socket.send(msg_rgb.encode()) data = tcp_socket.recv(16 * 1024) hue_data = json.loads(data[:-2].decode("utf8"))["result"] hex_rgb = "%6x" % int( json.loads(data[:-2].decode("utf8"))["result"][0]) r = hex_rgb[:2] if r == " ": r = "00" g = hex_rgb[3:4] if g == " ": g = "00" b = hex_rgb[-2:] if b == " ": b = "00" state["xy"] = convert_rgb_xy(int(r, 16), int(g, 16), int(b, 16)) state["colormode"] = "xy" elif json.loads(data[:-2].decode("utf8"))["result"][0] == "2": #ct mode msg_ct = json.dumps({ "id": 1, "method": "get_prop", "params": ["ct"] }) + "\r\n" tcp_socket.send(msg_ct.encode()) data = tcp_socket.recv(16 * 1024) state["ct"] = int( 1000000 / int(json.loads(data[:-2].decode("utf8"))["result"][0])) state["colormode"] = "ct" elif json.loads(data[:-2].decode("utf8"))["result"][0] == "3": #ct mode msg_hsv = json.dumps({ "id": 1, "method": "get_prop", "params": ["hue", "sat"] }) + "\r\n" tcp_socket.send(msg_hsv.encode()) data = tcp_socket.recv(16 * 1024) hue_data = json.loads(data[:-2].decode("utf8"))["result"] state["hue"] = int(hue_data[0] * 182) state["sat"] = int(int(hue_data[1]) * 2.54) state["colormode"] = "hs" tcp_socket.close() return state
0.673179 ] }, "swversion": "1.46.13_r26312", "type": "Extended color light", "uniqueid": "1a2b3c447" } } """ lights = json.loads(lightsjson) lights["9"]["state"].update({ "on": True, "bri": int((255 + 0 + 0) / 3), "xy": convert_rgb_xy(255, 0, 0), "colormode": "xy" }) def setColor(data, sleepTime): r, g, b = data sendLightRequest("9", {"xy": lights["9"]["state"]["xy"]}, lights, addresses, [r, g, b]) sleep(sleepTime) for i in range(1, 20): setColor([255, 0, 0], 0.05) setColor([0, 255, 0], 0.05)