def allSwitchesOff(): dehumid = SmartPlug(plugs['Fan']) dehumid.turn_off() fan = SmartPlug(plugs['Dehumidifier']) fan.turn_off() return 'Hi!'
class Fan: FAN_OFF_DELAY = 500.0 def __init__(self, fan_ip, logger): self.logger = logger self.state = False self.changing = False self.fan_ip = fan_ip self.plug = SmartPlug(self.fan_ip) def fan_off(self): try: self.plug.turn_off() self.logger.info("Turned fan off") except Exception: self.logger.warning("Outlet is down") self.changing = False def should_be(self, heat): if heat == HEAT_ON: try: if self.plug.is_off: self.plug.turn_on() self.logger.info("Turned fan on") except Exception: self.logger.warning("Outlet is down") self.state = True try: if heat == HEAT_OFF and self.plug.is_on and self.changing is False: self.logger.info("Turning fan off") self.changing = True Timer(self.FAN_OFF_DELAY, self.fan_off).start() except Exception: self.logger.warning("Outlet is down")
def cancel_temp(): auth = request.args.get('auth') if auth == "cabin": time_now = datetime.now(gmt) string_time = time_now.strftime("%d/%m/%y %H:%M:%S") plug_log = open("/d1/cabin_log.txt", "a") plug = SmartPlug("192.168.1.144") temp = read_temp() plug_status_file = open("/d1/webserver/reaching_optimum.txt", "r") cabin_plug_status = plug_status_file.read() plug_status_file.close() if cabin_plug_status == "1": GPIO.output(17, GPIO.LOW) GPIO.output(27, GPIO.LOW) plug_log.write( string_time + " /cancel-temp heating cancelled, current temperature is: " + str(temp) + "\n") plug_log.close() plug_status_file = open("/d1/webserver/reaching_optimum.txt", "w") plug.turn_off() plug_status_file.write("0") plug_status_file.close() return jsonify({"message": "Heating cancelled.", "status": "ok"}) else: plug_log.write(string_time + " /cancel-temp plug not on, temperature is: " + str(temp) + "\n") plug_log.close() return jsonify({ "message": "Plug is not on so unable to cancel heating.", "status": "error" }) else: return jsonify({"message": "unauthorised", "status": "error"})
class PlugHandler(object): def __init__(self): self.plug = SmartPlug(plug_devices['living_room']) def switch_on(self): try: if self.plug.state == 'OFF': self.plug.turn_on() return 'switched on.' else: return 'already Switched on.' except Exception as e: print e return 'Try Again.' def switch_off(self): try: if self.plug.state == 'ON': self.plug.turn_off() return 'switched off.' else: return 'already Switched off.' except Exception as e: print e return 'Try Again.'
class HS100(): def __init__(self, name, ip): self.name = name self.ip = ip print(name, ip, type(ip), len(ip)) self.plug = SmartPlug(ip) self.logger = GetLogger('hs100') self.logger.info("Link to an HS100 at {0} with name {1}.".format( ip, name)) def state(self): return self.plug.state def turn_on(self): self.plug.turn_on() self.logger.info("Turn on {0} (HS100).".format(self.name)) def turn_off(self): self.plug.turn_off() self.logger.info("Turn off {0} (HS100).".format(self.name)) def switch(self): if self.state() == SmartPlug.SWITCH_STATE_OFF: self.plug.turn_on() else: self.plug.turn_off() self.logger.info("Switch {0} (HS100) to {1}.".format( self.name, self.state()))
def camerac1(): plug = SmartPlug("Insert IP Address here") print("Current state: %s" % plug.state) if (plug.state == 'ON'): plug.turn_off() else: plug.turn_on() return jsonify(data)
def setDeviceStatus(self, postmsg): setDeviceStatusResult = True ip = self.get_variable("ip") port = self.get_variable("port") p = SmartPlug(ip) if postmsg['status'] == 'ON': p.turn_on() if postmsg['status'] == 'OFF': p.turn_off()
class DigitalDevice(RaspberiumDevice): def __init__(self, address): super().__init__() self.digitalOutputDevice = SmartPlug(address) def on(self): self.digitalOutputDevice.turn_on() self.digitalOutputDevice.led = True def off(self): self.digitalOutputDevice.turn_off() self.digitalOutputDevice.led = False
class TplinkPlug(Plug): def __init__(self, id: str, alias: str, host: str) -> None: Plug.__init__(self, id, alias, host, DeviceBrand.tp_link) self.native_api = SmartPlug(host) _LOGGER.debug( "Initializing tp-link smartplug: %s", self.host, ) # self.initialize() def get_sysinfo(self) -> Dict: """Retrieve system information. :return: sysinfo :rtype dict :raises SmartDeviceException: on error """ return self.native_api.sys_info @property def is_off(self) -> bool: """Return True if device is off. :return: True if device is off, False otherwise. :rtype: bool """ return self.native_api.is_off def turn_on(self) -> None: """Turn device on.""" return self.native_api.turn_on() def turn_off(self) -> None: """Turn device off.""" return self.native_api.turn_off() @property def is_on(self) -> bool: """Return if the device is on. :return: True if the device is on, False otherwise. :rtype: bool :return: """ try: return self.native_api.is_on except: return None @property def state_information(self) -> Dict[str, Any]: """Return device-type specific, end-user friendly state information. :return: dict with state information. :rtype: dict """ return self.native_api.state_information
def main(): """ Print the water level and temperature every second :return: """ # create the spi bus spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) # create the cs (chip select) cs = digitalio.DigitalInOut(board.D22) # create the mcp object mcp = MCP.MCP3008(spi, cs) # create an analog input channel on pin 0 water_level_sensor = AnalogIn(mcp, MCP.P0) # create temperature sensor temp_sensor = W1ThermSensor() pump = SmartPlug(PUMP_IP) heater = SmartPlug(HEATER_IP) while True: temperature = temp_sensor.get_temperature() print( f"The temperature is {temperature} C, {celsius_to_fahrenheit(temperature)} F" ) print(f"ADC Voltage: {round(water_level_sensor.voltage, 2)}V") water_level = get_water_level_inches(water_level_sensor.voltage) print(f"Water Level: {water_level} inches") print("\n") if temperature < HEATER_CUTOFF_CELSIUS: print("Turning heater on") heater.turn_on() else: print("Turning heater off") heater.turn_off() if water_level < PUMP_CUTOFF_INCHES: print("Turning pump on") pump.turn_on() else: print("Turning pump off") pump.turn_off() time.sleep(1)
class TPLinkDevice(): def __init__(self): self.light_Plug = SmartPlug("192.168.43.236") time.sleep(1.2) self.fan_Plug = SmartPlug("192.168.43.37") self.logger = None self.log_manager = None def set_log_manager(self, log_manager, logger): self.log_manager = log_manager self.logger = logger def turn_on_off(self, device): if device == 'Lights': # Change gesture sequence to default value if self.light_Plug.state == "OFF": self.light_Plug.turn_on() else: self.light_Plug.turn_off() self.log_manager.set_gesture_sequence_link( "Lights", True, self.light_Plug.state.lower(), datetime.utcnow()) self.logger.log_device_state_change("Lights", True, self.light_Plug.state.lower(), datetime.utcnow()) elif device == 'Smart Plug': # Change gesture sequence to default value if self.fan_Plug.state == "OFF": self.fan_Plug.turn_on() else: self.fan_Plug.turn_off() self.log_manager.set_gesture_sequence_link( "Smart Plug", True, self.light_Plug.state.lower(), datetime.utcnow()) self.logger.log_device_state_change("Smart Plug", True, self.light_Plug.state.lower(), datetime.utcnow()) else: self.log_manager.set_gesture_sequence_link(device, False, "off", datetime.utcnow()) self.logger.log_device_state_change(device, False, "off", datetime.utcnow()) @staticmethod def check_status(smart_plug): return smart_plug.state
def restart_plug(ip_addr, delay): """ Restarts a smart plug: powers it OFF and, then, ON Args: ip_addr: IP address of the smart plug delay: the time to wait before powering plug ON after it was powered OFF """ try: plug = SmartPlug(ip_addr) if plug.state == "ON": plug.turn_off() threading.Timer(delay, plug.turn_on).start() else: threading.Timer(delay, plug.turn_on).start() logger.info("Restart successful!") except SmartDeviceException: #TODO: add retrying to communicate again after timeout, if after multiple retry attempts it still failes, send email or Telegram logger.error("Failed to communicate with plug at IP address %s!", ip_addr)
def set_plug(plug_ip, value): """ Sets the plug at the given ip to the given value. Returns true iff the plug had a state change. """ plug = SmartPlug(plug_ip) print("found plug on ip %s: %s" % (plug_ip, plug.alias)) state = plug.state print("current plug state: " + str(state)) if value and not plug.is_on: print("turning on fan") plug.turn_on() return True elif not value and plug.is_on: print("turning off fan") plug.turn_off() return True else: print("plug is already in correct state") return False
def update(self, request, pk=None): plug = self.get_object() serializer = PlugsSerializer(plug, data=request.data, partial=True) if serializer.is_valid(): try: smplug = SmartPlug(request.data['ip']) if (request.data['state'] == '1' or request.data['state'] == True): print("test") smplug.turn_on() else: print("test2") smplug.turn_off() print(serializer.save()) except: return Response({'error': 'Une erreur s\'est produite'}) return Response({'status': 'state set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Main(App): def __init__(self, name, device, context): App.__init__(self, name, device, context) self.plug = SmartPlug(self.device_fields['ip']) @action def get_state(self): return self.plug.state @action def turn_on(self): self.plug.turn_on() @action def turn_off(self): self.plug.turn_off() @action def on_since(self): return self.plug.on_since def shutdown(self): return
class Main(App): def __init__(self, name=None, device=None): App.__init__(self, name, device) self.plug = SmartPlug(self.get_device().ip) @action def get_state(self): return self.plug.state @action def turn_on(self): self.plug.turn_on() @action def turn_off(self): self.plug.turn_off() @action def on_since(self): return self.plug.on_since def shutdown(self): print("SmartPlug Shutting Down") return
def fanSwitchOff(): plug = SmartPlug(plugs['Fan']) plug.turn_off() return 'Hi!'
import ephem, datetime, time, os from pyHS100 import SmartPlug on = False i = 0 f = open("log.txt", "w") plug = SmartPlug("192.168.1.27") plug.turn_off() while True: #Make an observer ced = ephem.Observer() #PyEphem takes and returns only UTC times #ced.date = "2013-09-04 15:00:00" #Location of Cedar Rapids, IA ced.lon = str(-91.6369485) #Note that lon should be in string format ced.lat = str(42.0101096) #Note that lat should be in string format #Elevation of Cedar Rapids, IA, in metres ced.elev = 252.799 #To get U.S. Naval Astronomical Almanac values, use these settings ced.pressure = 0 ced.horizon = '-0:34'
# create erosion and dilation kernels eKernel = np.ones(tuple(conf["erode"]["kernel"]), "uint8") dKernel = np.ones(tuple(conf["dilate"]["kernel"]), "uint8") frame_count = 0 # initialize the ImageSender object with the socket address of the # server sender = imagezmq.ImageSender(connect_to = 'tcp://*:5566', REQ_REP = False) #sender = imagezmq.ImageSender(connect_to = 'tcp://{}:5555'.format(conf['server_ip'])) rpiName = socket.gethostname() send_time = None try: light_plug = SmartPlug(conf["ip_of_plug"]) light_plug.turn_off() except Exception: pass # begin capturing "ctrl + c" signals signal.signal(signal.SIGINT, signal_handler) print("[INFO] detecting motion and sending those frames to another RPi.") # loop through the frames while True: # grab a frame from the video stream frame = vs.read() timenow = datetime.datetime.now() # check to see if should send the frame
def dehumidSwitchOff(): plug = SmartPlug(plugs['Dehumidifier']) plug.turn_off() return 'Hi!'
class Fan: """Turn on my fan!""" def __init__(self, bot): self.bot = bot self.plug = SmartPlug( "192.168.0.175") #Change to the IP of your fan's Smart Plug. self.fan_enabled = True def toggle_plug(self): if self.plug.is_off: self.plug.turn_on() else: self.plug.turn_off() @commands.group(pass_context=True) async def fan(self, ctx): """Manage your fan""" if ctx.invoked_subcommand is None: await send_cmd_help(ctx) @fan.command(pass_context=True) async def on(self, ctx): """Turn it on!""" if not self.fan_enabled and not checks.is_owner_check(ctx): await self.bot.say("The fan's state currently cannot be changed.") return if self.plug.is_on: await self.bot.say("The fan is already on!") else: self.toggle_plug() await self.bot.say("The fan is now on!") @fan.command(pass_context=True) async def off(self, ctx): """Turn it off!""" if not self.fan_enabled and not checks.is_owner_check(ctx): await self.bot.say("The fan's state currently cannot be changed.") return if self.plug.is_off: await self.bot.say("The fan is already off!") else: self.toggle_plug() await self.bot.say("The fan is now off!") @fan.command(pass_context=True) async def toggle(self, ctx): """Toggle its state!""" if not self.fan_enabled and not checks.is_owner_check(ctx): await self.bot.say("The fan's state currently cannot be changed.") return self.toggle_plug() await self.bot.say("The fan is now {}!".format(self.plug.state.lower()) ) @fan.command(pass_context=True) async def status(self, ctx): """Check the fan's state.""" await self.bot.say("The fan is currently {}.".format( self.plug.state.lower())) @fan.command() @checks.is_owner() async def enable(self): """Enable use of the fan by anyone.""" self.fan_enabled = True await self.bot.say("Fan powers enabled!") @fan.command() @checks.is_owner() async def disable(self): """Disable use of the fan by anyone but yourself.""" self.fan_enabled = False await self.bot.say("Fan powers disabled!")
def cyclePower(rigName): if rigName in POWER_SWITCH_IP_DICT: plug = SmartPlug(POWER_SWITCH_IP_DICT[rigName]) plug.turn_off() sleep(2) plug.turn_on()
def tpPlugOff(self, ip): plug = SmartPlug(ip) plug.turn_off()
def main(): if __name__ == '__main__': args = docopt(""" cog_test. A python test program for Cognitive System interview. The program requires Openwrt, Wireless adapter(Configured as AP), and TP-Link Smartplug. The program use Openwrt's tool "iw" to detect wireless device connection and parse its MAC address. If the MAC address matches the program input argument, the program will turn on the SmartPlug. If the target MAC address left the AP, the program will turn off the SmartPlug. Limitation: Script will only run on OpenWrt with only one smartPlug being connected to the AP. This script also only beent tested with one HS105. Caveat: "iw event -f" displays multiple message when STA is disconnected Therefore, the output of this program reflects the behavior from "iw event -f" Usage: cog_test.py [options] <mac_address> Options: -h --help Show this screen. """) # Register signal signal.signal(signal.SIGINT, sig_term_handler) usr_mac = args['<mac_address>'].lower() # Check input argument if check_mac(usr_mac): raise ValueError("Input Error (MAC Address)") # Check OS & Distro if bool(is_os_valid()): pass else: raise RunTimeError("Script must be run on OpenWrt") # Get Wireless Dev dev_name = get_wireless_dev() if dev_name is None: raise RuntimeError(r"Wireless not up or not configured" r" as AP") # Initialize plug object plug_ip = get_plug_ip() if plug_ip is None: raise RuntimeError("Smartplug is not detected") else: plug = SmartPlug(plug_ip) # Using "iw" pipe result if STA is being added or deleted GLOBAL_PROC = subprocess.Popen(["iw", "event", "-f"],\ stdin = subprocess.PIPE,\ stdout =subprocess.PIPE) # Regex for iw output and for MAC address iwRegx = re.compile(r'(\bnew\b)|(\bdel\b)|' r'((([a-fA-F\d]){2}:){5}' r'(([a-fA-F\d]){2}))') # Check if the desired MAC has already been connected if bool(is_mac_exist(usr_mac, dev_name)): plug.turn_on() else: plug.turn_off() print("Script is ready! Waiting for", usr_mac, "action!") # Main running loop while True: output = GLOBAL_PROC.stdout.readline() m = iwRegx.findall(output.decode('utf-8')) if m: for i in m[0]: if i: act = i mac = m[1][2] if mac == usr_mac: if act == "new": print(usr_mac, "has connected") plug.turn_on() elif act == "del": print(usr_mac, "has disconnected") plug.turn_off() else: pass
def plugTurnOff(name): plug = SmartPlug(deviceList[name]) plug.turn_off()
class TestSmartPlug(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, 'dev_name': basestring, 'deviceId': basestring, 'feature': basestring, 'fwId': basestring, 'hwId': basestring, 'hw_ver': basestring, 'icon_hash': basestring, 'latitude': All(float, Range(min=-90, max=90)), 'led_off': check_int_bool, 'longitude': All(float, Range(min=-180, max=180)), 'mac': check_mac, 'model': basestring, 'oemId': basestring, 'on_time': int, 'relay_state': int, 'rssi': All(int, Range(max=0)), 'sw_ver': basestring, 'type': basestring, 'updating': check_int_bool, }) current_consumption_schema = Schema({ 'voltage': All(float, Range(min=0, max=300)), 'power': All(float, Range(min=0)), 'total': All(float, Range(min=0)), 'current': All(float, Range(min=0)), }) tz_schema = Schema({ 'zone_str': basestring, 'dst_offset': int, 'index': All(int, Range(min=0)), 'tz_str': basestring, }) def setUp(self): self.plug = SmartPlug(PLUG_IP, protocol=FakeTransportProtocol(sysinfo_hs110)) def tearDown(self): self.plug = None def test_initialize(self): self.assertIsNotNone(self.plug.sys_info) self.sysinfo_schema(self.plug.sys_info) def test_initialize_invalid_connection(self): plug = SmartPlug('127.0.0.1', protocol=FakeTransportProtocol(sysinfo_hs110, invalid=True)) with self.assertRaises(SmartPlugException): plug.sys_info['model'] def test_query_helper(self): with self.assertRaises(SmartPlugException): self.plug._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.plug.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.plug.state if orig_state == SmartPlug.SWITCH_STATE_OFF: self.plug.state = "ON" self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_ON) self.plug.state = "OFF" self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_OFF) elif orig_state == SmartPlug.SWITCH_STATE_ON: self.plug.state = "OFF" self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_OFF) self.plug.state = "ON" self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_ON) elif orig_state == SmartPlug.SWITCH_STATE_UNKNOWN: self.fail("can't test for unknown state") def test_get_sysinfo(self): # initialize checks for this already, but just to be sure self.sysinfo_schema(self.plug.get_sysinfo()) @skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping") def test_turns_and_isses(self): orig_state = self.plug.is_on if orig_state: self.plug.turn_off() self.assertFalse(self.plug.is_on) self.assertTrue(self.plug.is_off) self.plug.turn_on() self.assertTrue(self.plug.is_on) else: self.plug.turn_on() self.assertFalse(self.plug.is_off) self.assertTrue(self.plug.is_on) self.plug.turn_off() self.assertTrue(self.plug.is_off) def test_has_emeter(self): # a not so nice way for checking for emeter availability.. if "110" in self.plug.sys_info["model"]: self.assertTrue(self.plug.has_emeter) else: self.assertFalse(self.plug.has_emeter) def test_get_emeter_realtime(self): self.current_consumption_schema((self.plug.get_emeter_realtime())) def test_get_emeter_daily(self): self.assertEqual(self.plug.get_emeter_daily(year=1900, month=1), {}) k, v = self.plug.get_emeter_daily().popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, float)) def test_get_emeter_monthly(self): self.assertEqual(self.plug.get_emeter_monthly(year=1900), {}) d = self.plug.get_emeter_monthly() k, v = d.popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, float)) @skip("not clearing your stats..") def test_erase_emeter_stats(self): self.fail() def test_current_consumption(self): x = self.plug.current_consumption() self.assertTrue(isinstance(x, float)) self.assertTrue(x >= 0.0) def test_identify(self): ident = self.plug.identify() self.assertTrue(isinstance(ident, tuple)) self.assertTrue(len(ident) == 3) def test_alias(self): test_alias = "TEST1234" original = self.plug.alias self.assertTrue(isinstance(original, basestring)) self.plug.alias = test_alias self.assertEqual(self.plug.alias, test_alias) self.plug.alias = original self.assertEqual(self.plug.alias, original) def test_led(self): original = self.plug.led self.plug.led = False self.assertFalse(self.plug.led) self.plug.led = True self.assertTrue(self.plug.led) self.plug.led = original def test_icon(self): self.assertEqual(set(self.plug.icon.keys()), {'icon', 'hash'}) def test_time(self): self.assertTrue(isinstance(self.plug.time, datetime.datetime)) # TODO check setting? def test_timezone(self): self.tz_schema(self.plug.timezone) def test_hw_info(self): self.sysinfo_schema(self.plug.hw_info) def test_on_since(self): self.assertTrue(isinstance(self.plug.on_since, datetime.datetime)) def test_location(self): self.sysinfo_schema(self.plug.location) def test_rssi(self): self.sysinfo_schema({'rssi': self.plug.rssi}) # wrapping for vol def test_mac(self): self.sysinfo_schema({'mac': self.plug.mac}) # wrapping for val
def get(self, request, format=None): sensors = {} plugs = {} response = {} response['sensors'] = {} for sensor in Sensors.objects.all(): if env("DEBUG") == True: sensors[sensor.name] = {"Temperature": "21", "Humidity": "56"} else: sensors[sensor.name] = requests.get('http://' + sensor.ip + '/data').json() logsSensors = LogsSensors() logsSensors.temperature = sensors[sensor.name].get('Temperature') logsSensors.humidity = sensors[sensor.name].get('Humidity') logsSensors.sensor = sensor logsSensors.save() logsPlugs = LogsPlugs() plugs = Plugs.objects.all().filter(room_id=sensor.room.id) BoolInterval = False for ti in TimeInterval.objects.all().filter( room_id=sensor.room.id): if (isInTimeInterval(ti.startingTime, ti.endingTime)): BoolInterval = True presenceBool = True if sensors[sensor.name].get( 'Presence' ) == "1" else False #isPresent('iphone-de-sebastien.local') logPresence = LogsPresence() if presenceBool: logPresence.presence = 1 logPresence.save() print("Presence:" + str(presenceBool)) condition = ( isSetupTrue("ForceStop") != True and presenceBool and BoolInterval == False ) or (((not presenceBool) or BoolInterval) and int(sensors[sensor.name]['Temperature']) < int( Setup.objects.get(name__iexact="MinTemperature").value)) print("condition1: " + str((isSetupTrue("ForceStop") != True and presenceBool and BoolInterval == False))) print("__") print("condition2 : " + str(( (not presenceBool) or BoolInterval ) and int(sensors[sensor.name]['Temperature']) < int( Setup.objects.get(name__iexact="MinTemperature").value))) if condition: if presenceBool and (BoolInterval == False): askedTemperature = Setup.objects.get( name__iexact="Temperature").value else: askedTemperature = Setup.objects.get( name__iexact="MinTemperature").value print(askedTemperature) #print(sensors[sensor.name]['Temperature']) if int(sensors[sensor.name] ['Temperature']) < int(askedTemperature) + 1: response['success'] = True response['sensors'][sensor.name] = {'state': "on"} logsPlugs.value = 1 for plug in plugs: if (condition == True): print("ON " + plug.ip) plug.state = True smplug = SmartPlug(plug.ip) smplug.turn_on() elif int(sensors[sensor.name] ['Temperature']) >= int(askedTemperature) - 1: response['success'] = True response['sensors'][sensor.name] = {'state': "off"} logsPlugs.value = 0 for plug in plugs: print("Off " + plug.ip) plug.state = False smplug = SmartPlug(plug.ip) smplug.turn_off() else: logsPlugs.value = 0 else: logsPlugs.value = 0 for plug in plugs: smplug = SmartPlug(plug.ip) plug.state = False smplug.turn_off() logsPlugs.save() plug.save() return JsonResponse(response)