def add_entity(device: SmartBulb, async_add_entities): """Check if device is online and add the entity.""" # Attempt to get the sysinfo. If it fails, it will raise an # exception that is caught by async_add_entities_retry which # will try again later. device.get_sysinfo() async_add_entities([TPLinkSmartBulb(device)], update_before_add=True)
def log_consumption(): for bulb in Bulb.objects.all(): smartBulb = SmartBulb(bulb.ipAddr) consumption = smartBulb.get_emeter_realtime()['power_mw'] logBulb = LogBulb() logBulb.bulb = bulb logBulb.consumption = consumption logBulb.save() print(bulb)
def temperature(dev: SmartBulb, temperature): """Get or set color temperature.""" if temperature is None: click.echo("Color temperature: %s" % dev.color_temp) if dev.valid_temperature_range != (0, 0): click.echo("(min: %s, max: %s)" % dev.valid_temperature_range) else: click.echo("Temperature range unknown, please open a github issue" " or a pull request for model '%s'" % dev.model) else: click.echo("Setting color temperature to %s" % temperature) dev.set_color_temp(temperature)
def get_consumption(): consumption = 0 maxPerBulb = 8000 numberOfBulbs = len(Bulb.objects.all()) max = maxPerBulb * numberOfBulbs print("# bulbs: %s" % numberOfBulbs) bulbs = Bulb.objects.all() for bulb in bulbs: smartBulb = SmartBulb(bulb.ipAddr) print(str(smartBulb.get_emeter_realtime())) consumption = consumption + smartBulb.get_emeter_realtime()['power_mw'] percent = int((consumption / max) * 100) print(percent) return percent
def cli(ctx, ip, debug, bulb, plug): """A cli tool for controlling TP-Link smart home plugs.""" if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) if ctx.invoked_subcommand == "discover": return if ip is None: click.echo("No IP given, trying discovery..") ctx.invoke(discover) return elif ip is not None: if not bulb and not plug: click.echo("No --bulb nor --plug given, discovering..") devs = ctx.invoke(discover, discover_only=True) for discovered_ip, discovered_dev in devs: if discovered_ip == ip: dev = discovered_dev break elif bulb: dev = SmartBulb(ip) elif plug: dev = SmartPlug(ip) else: click.echo("Unable to detect type, use --bulb or --plug!") return ctx.obj = dev if ctx.invoked_subcommand is None: ctx.invoke(state)
def dev(request): file = request.param ip = request.config.getoption("--ip") if ip: d = Discover.discover_single(ip) print(d.model) if d.model in file: return d return with open(file) as f: sysinfo = json.load(f) model = basename(file) params = { "host": "123.123.123.123", "protocol": FakeTransportProtocol(sysinfo), "cache_ttl": 0, } if "LB" in model or "KL" in model: p = SmartBulb(**params) elif "HS300" in model: p = SmartStrip(**params) elif "HS" in model: p = SmartPlug(**params) else: raise Exception("No tests for %s" % model) yield p
def cli(ctx, ip, host, debug, bulb, plug): """A cli tool for controlling TP-Link smart home plugs.""" if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) if ctx.invoked_subcommand == "discover": return if ip is not None and host is None: host = ip if host is None: click.echo("No host name given, trying discovery..") ctx.invoke(discover) return else: if not bulb and not plug: click.echo("No --bulb nor --plug given, discovering..") dev = Discover.discover_single(host) elif bulb: dev = SmartBulb(host) elif plug: dev = SmartPlug(host) else: click.echo("Unable to detect type, use --bulb or --plug!") return ctx.obj = dev if ctx.invoked_subcommand is None: ctx.invoke(state)
def status(self): try: settings.plugins.lights[self.room] except Exception: return try: self.isOpen(9999) except Exception: return type = settings.plugins.lights[self.room]['type'] if type == 'plug': emoji = ':electric_plug:' tplinklight = SmartPlug( settings.plugins.lights[self.room]['ipaddr']) else: emoji = ':bulb:' type = 'light' tplinklight = SmartBulb( settings.plugins.lights[self.room]['ipaddr']) if eval(os.environ['DEBUG']): debug = "[{}] ".format(device_name) else: debug = "" room_name = self.room.capitalize() if room_name.endswith('s'): room_name = room_name[:-1] + "'" + room_name[-1:] if tplinklight.state == "OFF": chat.post("{} {}{} {} is off.".format(emoji, debug, room_name, type)) else: chat.post("{} {}{} {} is on.".format(emoji, debug, room_name, type))
def get_static_devices(config_data) -> SmartDevices: """Get statically defined devices in the config.""" _LOGGER.debug("Getting static devices") lights = [] switches = [] for type_ in (CONF_LIGHT, CONF_SWITCH, CONF_STRIP, CONF_DIMMER): for entry in config_data[type_]: host = entry["host"] try: if type_ == CONF_LIGHT: lights.append(SmartBulb(host)) elif type_ == CONF_SWITCH: switches.append(SmartPlug(host)) elif type_ == CONF_STRIP: for plug in SmartStrip(host).plugs.values(): switches.append(plug) # Dimmers need to be defined as smart plugs to work correctly. elif type_ == CONF_DIMMER: lights.append(SmartPlug(host)) except SmartDeviceException as sde: _LOGGER.error( "Failed to setup device %s due to %s; not retrying", host, sde ) return SmartDevices(lights, switches)
def _device_for_type(host, type_): dev = None if type_ == CONF_LIGHT: dev = SmartBulb(host) elif type_ == CONF_SWITCH: dev = SmartPlug(host) return dev
async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock( side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{ CONF_HOST: "123.123.123.1" }], CONF_SWITCH: [{ CONF_HOST: "123.123.123.2" }], CONF_DIMMER: [{ CONF_HOST: "123.123.123.22" }], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2
def update_bulb(bulb): smartBulb = SmartBulb(bulb.ipAddr) if bulb.onOff: smartBulb.turn_on() else: smartBulb.turn_off() if smartBulb.is_color: hsv = rgb2hsv(int(bulb.rgbColor[0:2], 16), int(bulb.rgbColor[2:4], 16), int(bulb.rgbColor[4:6], 16)) smartBulb.hsv = hsv smartBulb.brightness = bulb.brightness
def setup_platform(hass, config, add_entities, discovery_info=None): """Initialise pyLB100 SmartBulb.""" from pyHS100 import SmartBulb from pyHS100 import SmartPlug host = config.get(CONF_HOST) name = config.get(CONF_NAME) device_type = config.get(CONF_DEVICE_TYPE) if device_type == "dimmer": add_entities([TPLinkSmartDimmer(SmartPlug(host), name)], True) else: add_entities([TPLinkSmartBulb(SmartBulb(host), name)], True)
def __init__(self, ip=None): bulb = None if not ip: d = Discover() devices = d.discover() for ip, device in devices.items(): if isinstance(device, SmartBulb): bulb = device else: bulb = SmartBulb(ip) if bulb: self._bulb = bulb else: raise NoBulbException
def cli(ctx, ip, host, alias, debug, bulb, plug, strip): """A cli tool for controlling TP-Link smart home plugs.""" if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) if ctx.invoked_subcommand == "discover": return if ip is not None and host is None: host = ip if alias is not None and host is None: click.echo("Alias is given, using discovery to find host %s" % alias) host = find_host_from_alias(alias=alias) if host: click.echo("Found hostname is {}".format(host)) else: click.echo("No device with name {} found".format(alias)) return if host is None: click.echo("No host name given, trying discovery..") ctx.invoke(discover) return else: if not bulb and not plug and not strip: click.echo("No --strip nor --bulb nor --plug given, discovering..") dev = Discover.discover_single(host) elif bulb: dev = SmartBulb(host) elif plug: dev = SmartPlug(host) elif strip: dev = SmartStrip(host) else: click.echo( "Unable to detect type, use --strip or --bulb or --plug!") return ctx.obj = dev if ctx.invoked_subcommand is None: ctx.invoke(state)
def get_static_devices(config_data) -> SmartDevices: """Get statically defined devices in the config.""" _LOGGER.debug("Getting static devices") lights = [] switches = [] for type_ in [CONF_LIGHT, CONF_SWITCH, CONF_DIMMER]: for entry in config_data[type_]: host = entry["host"] if type_ == CONF_LIGHT: lights.append(SmartBulb(host)) elif type_ == CONF_SWITCH: switches.append(SmartPlug(host)) # Dimmers need to be defined as smart plugs to work correctly. elif type_ == CONF_DIMMER: lights.append(SmartPlug(host)) return SmartDevices(lights, switches)
async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.get_static_devices" ) as get_static_devices, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as async_setup_entry: config = { tplink.DOMAIN: { platform: [{ CONF_HOST: "123.123.123.123" }], CONF_DISCOVERY: False, } } light = SmartBulb("123.123.123.123") switch = SmartPlug("321.321.321.321") switch.get_sysinfo = MagicMock( return_value=SMARTPLUG_HS110_DATA["sysinfo"]) switch.get_emeter_realtime = MagicMock( return_value=EmeterStatus(SMARTPLUG_HS110_DATA["realtime"])) if platform == "light": get_static_devices.return_value = SmartDevices([light], []) elif platform == "switch": get_static_devices.return_value = SmartDevices([], [switch]) assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(async_setup_entry.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
def cli(ctx, ip, debug, bulb): """A cli tool for controlling TP-Link smart home plugs.""" if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) if ctx.invoked_subcommand == "discover": return if ip is None: click.echo("You must specify the IP!") sys.exit(-1) if bulb: dev = SmartBulb(ip) else: dev = SmartPlug(ip) ctx.obj = dev if ctx.invoked_subcommand is None: ctx.invoke(state)
def action(self, action, timeout=None): action = action.upper() try: settings.plugins.lights[self.room] except Exception: return try: self.isOpen(9999) except Exception: return if not self.post.ack(): return type = settings.plugins.lights[self.room]['type'] if type == 'plug': emoji = ':electric_plug:' tplinklight = SmartPlug( settings.plugins.lights[self.room]['ipaddr']) else: type = 'light' emoji = ':bulb:' tplinklight = SmartBulb( settings.plugins.lights[self.room]['ipaddr']) if eval(os.environ['DEBUG']): debug = "[{}] ".format(device_name) else: debug = "" room_name = self.room.capitalize() if room_name.endswith('s'): room_name = room_name[:-1] + "'" + room_name[-1:] chat.post("{} {}Switching {} {} {}.".format(emoji, debug, room_name, type, action.lower())) tplinklight.state = action if timeout is not None: sleep(float(timeout) * 60) tplinklight.state = 'OFF' self.post.unack()
def toggle(self): try: settings.plugins.lights[self.room] except Exception: return try: self.isOpen(9999) except Exception: return if not self.post.ack(): return type = settings.plugins.lights[self.room]['type'] if type == 'plug': emoji = ':electric_plug:' tplinklight = SmartPlug( settings.plugins.lights[self.room]['ipaddr']) else: emoji = ':bulb:' type = 'light' tplinklight = SmartBulb( settings.plugins.lights[self.room]['ipaddr']) if eval(os.environ['DEBUG']): debug = "[{}] ".format(device_name) else: debug = "" if tplinklight.state == "OFF": action = "ON" else: action = "OFF" room_name = self.room.capitalize() if room_name.endswith('s'): room_name = room_name[:-1] + "'" + room_name[-1:] chat.post("{} {}Switching {} {} {}.".format(emoji, debug, room_name, type, action.lower())) tplinklight.state = action self.post.unack()
def setUp(self): self.bulb = SmartBulb(BULB_IP, protocol=FakeTransportProtocol(sysinfo_lb130))
def test_initialize_invalid_connection(self): bulb = SmartBulb('127.0.0.1', protocol=FakeTransportProtocol(sysinfo_lb130, invalid=True)) with self.assertRaises(SmartPlugException): bulb.sys_info['model']
from pyHS100 import SmartPlug, SmartBulb from pprint import pformat as pf # plug = SmartPlug("192.168.31.99") # print("Hardware: %s" % pf(plug.hw_info)) # print("Full sysinfo: %s" % pf(plug.get_sysinfo())) # this prints lots of information about the device # # # print("Current state: %s" % plug.state) # plug.turn_on() # # print("Current time: %s" % plug.time) # # # print("Current LED state: %s" % plug.led) # plug.led = False # turn off led # print("New LED state: %s" % plug.led) bulb = SmartBulb("192.168.31.100") print(bulb.brightness) if bulb.is_dimmable: bulb.brightness = 100 bulb.turn_on() #print("Hardware: %s" % pf(bulb.hw_info)) #print("Full sysinfo: %s" % pf(bulb.get_sysinfo())) # this prints lots of information about the device print(bulb.is_on)
def setup_platform(hass, config, add_devices, discovery_info=None): """Initialise pyLB100 SmartBulb.""" from pyHS100 import SmartBulb host = config.get(CONF_HOST) name = config.get(CONF_NAME) add_devices([TPLinkSmartBulb(SmartBulb(host), name)], True)
### Change the ip addresss accordingly print('loading smartplug <--- HS100') plug = SmartPlug("192.168.1.x") def plug_turn_on(): plug.turn_on() def plug_turn_off(): plug.turn_off() ### TPLINK KASA KL130 ### Change the ip addresss accordingly print('Loading smartbulb <--- KL130') bulb = SmartBulb("192.168.1.24") def red_alert_mode(): bulb.turn_on() bulb.hsv = (0, 75, 100) time.sleep (0.7) bulb.turn_off() time.sleep (0.7) bulb.turn_on() time.sleep (0.7) bulb.turn_off() time.sleep (0.7) bulb.turn_on() time.sleep (0.7) bulb.turn_off()
def bulb_turn_off(bulb): smartBulb = SmartBulb(bulb.ipAddr) smartBulb.turn_off() bulb.onOff = False bulb.save()
def bulb_turn_on(bulb): smartBulb = SmartBulb(bulb.ipAddr) smartBulb.turn_on() bulb.onOff = True bulb.save()
if(os == "windows"): #replace arguments for number of packets and packet size for windows args[1]='-n' args[3]='-l' output = subprocess.Popen(args ,stdout = subprocess.PIPE).communicate()[0].decode() #returns true if can ping phone if(os == "windows"): return 'unreachable' not in output else: return 'Unreachable' not in output if (__name__ == "__main__"): plug = SmartPlug(PLUG_IP) bulb = SmartBulb(BULB_IP) amHome = ping(PHONE_IP) # v = sunset() if(amHome and lampTime()): #if the bulb is currently on and it's night time then turn off the bulb and turn on lamp#transition to 50% then turn on lamp then transition to 0 if(bulb.is_on): bulb.set_light_state({'on_off': 0, 'transition_period': 3000}) plug.turn_on() #print('ping: ' + str(ping(PHONE_IP))) elif(amHome and bulbTime()): #bulb.set_light_state({'on_off': 1, 'transition_period': 3000}) """ #for easier testing comment out for implementation elif(plug.is_on): #if daytime and the lamp is still on, turn it off
h = r.random() * 270 h = int(h) #h = 100 s = r.random() * 100 s = int(s) s = 100 for y in range(1,4): for x in range(17,25): #for x in range(1,35): addr = "10.66."+str(y)+"."+str(x) print(addr) if ( ( x == 24 ) & (y == 1 ) ): pass else: try: b = SmartBulb(addr) b.turn_on() # b.turn_off() # b.turn_off() # b.turn_off() # b.turn_off() #s = 100 b.hsv = (h,s, 100) except: pass print(i) i += 1 t.sleep(1.0)
class TestSmartBulb(TestCase): # these schemas should go to the mainlib as # they can be useful when adding support for new features/devices # as well as to check that faked devices are operating properly. sysinfo_schema = Schema({ 'active_mode': check_mode, 'alias': basestring, 'ctrl_protocols': { 'name': basestring, 'version': basestring, }, 'description': basestring, 'dev_state': basestring, 'deviceId': basestring, 'disco_ver': basestring, 'heapsize': int, 'hwId': basestring, 'hw_ver': basestring, 'is_color': check_int_bool, 'is_dimmable': check_int_bool, 'is_factory': bool, 'is_variable_color_temp': check_int_bool, 'light_state': { 'brightness': All(int, Range(min=0, max=100)), 'color_temp': int, 'hue': All(int, Range(min=0, max=255)), 'mode': basestring, 'on_off': check_int_bool, 'saturation': All(int, Range(min=0, max=255)), }, 'mic_mac': basestring, 'mic_type': basestring, 'model': basestring, 'oemId': basestring, 'preferred_state': [{ 'brightness': All(int, Range(min=0, max=100)), 'color_temp': int, 'hue': All(int, Range(min=0, max=255)), 'index': int, 'saturation': All(int, Range(min=0, max=255)), }], 'rssi': All(int, Range(max=0)), 'sw_ver': basestring, }) current_consumption_schema = Schema({ 'power_mw': int, }) tz_schema = Schema({ 'zone_str': basestring, 'dst_offset': int, 'index': All(int, Range(min=0)), 'tz_str': basestring, }) def setUp(self): self.bulb = SmartBulb(BULB_IP, protocol=FakeTransportProtocol(sysinfo_lb130)) def tearDown(self): self.bulb = None def test_initialize(self): self.assertIsNotNone(self.bulb.sys_info) self.sysinfo_schema(self.bulb.sys_info) def test_initialize_invalid_connection(self): bulb = SmartBulb('127.0.0.1', protocol=FakeTransportProtocol(sysinfo_lb130, invalid=True)) with self.assertRaises(SmartPlugException): bulb.sys_info['model'] def test_query_helper(self): with self.assertRaises(SmartPlugException): self.bulb._query_helper("test", "testcmd", {}) # TODO check for unwrapping? @skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping") def test_state(self): def set_invalid(x): self.bulb.state = x set_invalid_int = partial(set_invalid, 1234) self.assertRaises(ValueError, set_invalid_int) set_invalid_str = partial(set_invalid, "1234") self.assertRaises(ValueError, set_invalid_str) set_invalid_bool = partial(set_invalid, True) self.assertRaises(ValueError, set_invalid_bool) orig_state = self.bulb.state if orig_state == SmartBulb.BULB_STATE_OFF: self.bulb.state = SmartBulb.BULB_STATE_ON self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON) self.bulb.state = SmartBulb.BULB_STATE_OFF self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF) elif orig_state == SmartBulb.BULB_STATE_ON: self.bulb.state = SmartBulb.BULB_STATE_OFF self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF) self.bulb.state = SmartBulb.BULB_STATE_ON self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON) def test_get_sysinfo(self): # initialize checks for this already, but just to be sure self.sysinfo_schema(self.bulb.get_sysinfo()) @skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping") def test_turns_and_isses(self): orig_state = self.bulb.state if orig_state == SmartBulb.BULB_STATE_ON: self.bulb.state = SmartBulb.BULB_STATE_OFF self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF) self.bulb.state = SmartBulb.BULB_STATE_ON self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON) else: self.bulb.state = SmartBulb.BULB_STATE_ON self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON) self.bulb.state = SmartBulb.BULB_STATE_OFF self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF) def test_get_emeter_realtime(self): self.current_consumption_schema((self.bulb.get_emeter_realtime())) def test_get_emeter_daily(self): self.assertEqual(self.bulb.get_emeter_daily(year=1900, month=1), {}) k, v = self.bulb.get_emeter_daily().popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, int)) def test_get_emeter_monthly(self): self.assertEqual(self.bulb.get_emeter_monthly(year=1900), {}) d = self.bulb.get_emeter_monthly() k, v = d.popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, int)) @skip("not clearing your stats..") def test_erase_emeter_stats(self): self.fail() def test_current_consumption(self): x = self.bulb.current_consumption() self.assertTrue(isinstance(x, int)) self.assertTrue(x >= 0.0) def test_alias(self): test_alias = "TEST1234" original = self.bulb.alias self.assertTrue(isinstance(original, basestring)) self.bulb.alias = test_alias self.assertEqual(self.bulb.alias, test_alias) self.bulb.alias = original self.assertEqual(self.bulb.alias, original) def test_icon(self): self.assertEqual(set(self.bulb.icon.keys()), {'icon', 'hash'}) def test_rssi(self): self.sysinfo_schema({'rssi': self.bulb.rssi}) # wrapping for vol