Esempio n. 1
0
def power_get(host, port, index):
    assert port is None
    index = int(index)
    strip = SmartStrip(host)
    asyncio.run(strip.update())
    assert (len(strip.children) >
            index), "Trying to access non-existant plug socket on strip"
    return strip.children[index].is_on
class TpLinkHandlerSmartStrip(SmartDeviceException):
	def __init__(self, address):
		self.worker = ThreadedWorker()
		self.device = SmartStrip(address)

	def update(self):
		asyncio.run(self.device.update())

	def update_two(self):
		asyncio.create_task(self.device.update())

	def update_three(self):
		future = asyncio.run_coroutine_threadsafe(self.device.update(), self.worker.loop)
		result = future.result()

	def shutdown_btn(self, settings):
		if settings.get(["navButton", "deviceOne"]):
			asyncio.create_task(self.device.children[0].turn_off())
		if settings.get(["navButton", "deviceTwo"]):
			asyncio.create_task(self.device.children[1].turn_off())
		if settings.get(["navButton", "deviceThree"]):
			asyncio.create_task(self.device.children[2].turn_off())
		return "shutdown"

	def turnOn_btn(self, settings):
		if settings.get(["navButton", "deviceOne"]):
			asyncio.create_task(self.device.children[0].turn_on())
		if settings.get(["navButton", "deviceTwo"]):
			asyncio.create_task(self.device.children[1].turn_on())
		if settings.get(["navButton", "deviceThree"]):
			asyncio.create_task(self.device.children[2].turn_on())
		return "Turning on"

	def turn_on(self, plugNumber):
		asyncio.run(self.device.children[plugNumber].turn_on())

	def shutdown(self, plugNumber):
		asyncio.run(self.device.children[plugNumber].turn_off())

	def get_plug_information(self):
		return self.device.hw_info

	def __repr__(self):
		pass
Esempio n. 3
0
class OutputModule(AbstractOutput):
    """An output support class that operates an output."""
    def __init__(self, output, testing=False):
        super().__init__(output, testing=testing, name=__name__)

        self.strip = None
        self.outlet_switching = False
        self.status_thread = None
        self.outlet_status_checking = False
        self.timer_status_check = time.time()
        self.first_connect = True

        self.plug_address = None
        self.status_update_period = None

        self.setup_custom_options(OUTPUT_INFORMATION['custom_options'], output)

        output_channels = db_retrieve_table_daemon(OutputChannel).filter(
            OutputChannel.output_id == self.output.unique_id).all()
        self.options_channels = self.setup_custom_channel_options_json(
            OUTPUT_INFORMATION['custom_channel_options'], output_channels)

    def initialize(self):
        self.setup_output_variables(OUTPUT_INFORMATION)

        if not self.plug_address:
            self.logger.error("Plug address must be set")
            return

        try:
            self.try_connect()

            self.status_thread = threading.Thread(target=self.status_update)
            self.status_thread.start()

            if self.output_setup:
                self.logger.debug('Strip setup: {}'.format(self.strip.hw_info))
                for channel in channels_dict:
                    if self.options_channels['state_startup'][channel] == 1:
                        self.output_switch("on", output_channel=channel)
                    elif self.options_channels['state_startup'][channel] == 0:
                        self.output_switch("off", output_channel=channel)
                    self.logger.debug('Strip children: {}'.format(
                        self.strip.children[channel]))
        except Exception as e:
            self.logger.error("initialize() Error: {err}".format(err=e))

    def try_connect(self):
        try:
            from kasa import SmartStrip

            self.strip = SmartStrip(self.plug_address)
            asyncio.run(self.strip.update())
            self.output_setup = True
        except Exception as e:
            if self.first_connect:
                self.first_connect = False
                self.logger.error(
                    "Output was unable to be setup: {err}".format(err=e))
            else:
                self.logger.debug(
                    "Output was unable to be setup: {err}".format(err=e))

    def output_switch(self,
                      state,
                      output_type=None,
                      amount=None,
                      output_channel=None):
        if not self.is_setup():
            msg = "Error 101: Device not set up. See https://kizniche.github.io/Mycodo/Error-Codes#error-101 for more info."
            self.logger.error(msg)
            return msg

        while self.outlet_status_checking and self.running:
            time.sleep(0.1)

        try:
            self.outlet_switching = True
            if state == 'on':
                asyncio.run(self.strip.children[output_channel].turn_on())
                self.output_states[output_channel] = True
            elif state == 'off':
                asyncio.run(self.strip.children[output_channel].turn_off())
                self.output_states[output_channel] = False
            msg = 'success'
        except Exception as e:
            msg = "State change error: {}".format(e)
            self.logger.error(msg)
            self.output_setup = False
        finally:
            self.outlet_switching = False
        return msg

    def is_on(self, output_channel=None):
        if self.is_setup():
            if output_channel is not None and output_channel in self.output_states:
                return self.output_states[output_channel]
            else:
                return self.output_states

    def is_setup(self):
        return self.output_setup

    def stop_output(self):
        """Called when Output is stopped."""
        if self.is_setup():
            for channel in channels_dict:
                if self.options_channels['state_shutdown'][channel] == 1:
                    self.output_switch('on', output_channel=channel)
                elif self.options_channels['state_shutdown'][channel] == 0:
                    self.output_switch('off', output_channel=channel)
        self.running = False

    def status_update(self):
        while self.running:
            if self.timer_status_check < time.time():

                while self.timer_status_check < time.time():
                    self.timer_status_check += self.status_update_period

                while self.outlet_switching and self.running:
                    time.sleep(0.1)
                self.outlet_status_checking = True
                self.logger.debug("Checking state of outlets")

                if not self.output_setup:
                    self.try_connect()
                    if not self.output_setup:
                        self.logger.debug("Could not connect to power strip")

                try:
                    if self.output_setup:
                        asyncio.run(self.strip.update())
                        for channel in channels_dict:
                            if self.strip.children[channel].is_on:
                                self.output_states[channel] = True
                            else:
                                self.output_states[channel] = False
                except Exception as e:
                    self.logger.debug(
                        "Could not query power strip status: {}".format(e))
                    self.output_setup = False
                finally:
                    self.outlet_status_checking = False

            time.sleep(1)