Beispiel #1
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the VeSync switch platform."""
    from pyvesync_v2.vesync import VeSync

    switches = []

    manager = VeSync(config.get(CONF_USERNAME), config.get(CONF_PASSWORD))

    if not manager.login():
        _LOGGER.error("Unable to login to VeSync")
        return

    manager.update()

    if manager.devices is not None and manager.devices:
        if len(manager.devices) == 1:
            count_string = 'switch'
        else:
            count_string = 'switches'

        _LOGGER.info("Discovered %d VeSync %s",
                     len(manager.devices), count_string)

        for switch in manager.devices:
            switches.append(VeSyncSwitchHA(switch))
            _LOGGER.info("Added a VeSync switch named '%s'",
                         switch.device_name)
    else:
        _LOGGER.info("No VeSync devices found")

    add_entities(switches)
Beispiel #2
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the VeSync switch platform."""
    from pyvesync_v2.vesync import VeSync

    switches = []

    manager = VeSync(config.get(CONF_USERNAME), config.get(CONF_PASSWORD))

    if not manager.login():
        _LOGGER.error("Unable to login to VeSync")
        return

    manager.update()

    if manager.devices is not None and manager.devices:
        if len(manager.devices) == 1:
            count_string = 'switch'
        else:
            count_string = 'switches'

        _LOGGER.info("Discovered %d VeSync %s",
                     len(manager.devices), count_string)

        for switch in manager.devices:
            switches.append(VeSyncSwitchHA(switch))
            _LOGGER.info("Added a VeSync switch named '%s'",
                         switch.device_name)
    else:
        _LOGGER.info("No VeSync devices found")

    add_entities(switches)
	def connect_vesync_cloud(self):
		# check to see if VeSync manager is already connected - if so, don't try to connect again
		if not self._manager:
			# try connecting to the VeSync using the provided configuration data
			self._manager = VeSync(self._settings.get(["username"]), self._settings.get(["password"]))

			if self._manager.login():
				self._logger.info("Successfully connected to VeSync cloud service!")
				return True
			else:
				self._logger.info("Could not connect to VeSync cloud service.  Verify username/password and try again")
				self._manager = None
				return False
 def test_bad_login(self, api_mock, email, password, testid):
     """Test failed login."""
     full_return = ({'code': 455}, 200)
     self.mock_api.return_value = full_return
     vesync_obj = VeSync(email, password)
     assert vesync_obj.login() is False
     if testid == 'correct':
         jd = helpers.req_body(vesync_obj, 'login')
         self.mock_api.assert_called_with('/cloud/v1/user/login',
                                          'post',
                                          json=jd)
     else:
         assert not self.mock_api.called
def test_login(mock_api, email, password, testid):
    """Test multiple failed login calls."""
    return_tuple = {'code': 455, 'msg': 'sdasd'}
    mock_api.return_value.ok = True
    mock_api.return_value.json.return_value = return_tuple
    vesync_obj = VeSync(email, password)
    vesync_login = vesync_obj.login()
    assert vesync_login is False
    if testid == 'correct':
        jd = helpers.req_body(vesync_obj, 'login')
        mock_api.assert_called_with(
            'https://smartapi.vesync.com/cloud/v1/user/login',
            headers=None,
            json=jd,
            timeout=5)
    else:
        assert not mock_api.called
 def test_good_login(self, api_mock):
     """Test successful login."""
     full_return = ({
         'code': 0,
         'result': {
             'accountID': 'sam_actid',
             'token': 'sam_token'
         }
     }, 200)
     self.mock_api.return_value = full_return
     vesync_obj = VeSync('*****@*****.**', 'pass')
     assert vesync_obj.login() is True
     jd = helpers.req_body(vesync_obj, 'login')
     self.mock_api.assert_called_with('/cloud/v1/user/login',
                                      'post',
                                      json=jd)
     assert vesync_obj.token == 'sam_token'
     assert vesync_obj.account_id == 'sam_actid'
def test_vesync_init(email, password, timezone, testid):
    """Testing only input validation."""
    v_inst = VeSync(email, password, timezone)
    assert isinstance(v_inst, VeSync)
    assert v_inst.username == email
    assert v_inst.password == password

    if testid == 'full correct':
        assert v_inst.time_zone == timezone
    elif testid in ('invalid tz', 'none tz', 'non tz pass', 'empty tz'):
        assert v_inst.time_zone == pyvesync_v2.helpers.DEFAULT_TZ
class VeSyncPowerMonitorPlugin(octoprint.plugin.StartupPlugin,
							   octoprint.plugin.TemplatePlugin,
							   octoprint.plugin.AssetPlugin,
							   octoprint.plugin.SettingsPlugin):

	def __init__(self):
		self._vesync_data_engine_timer = None
		self._manager = None

	def on_after_startup(self):
		# check to verify connection was successful - if it was, launch the VeSync data engine
		if self.connect_vesync_cloud():
			self.start_vesync_data_engine()

	def connect_vesync_cloud(self):
		# check to see if VeSync manager is already connected - if so, don't try to connect again
		if not self._manager:
			# try connecting to the VeSync using the provided configuration data
			self._manager = VeSync(self._settings.get(["username"]), self._settings.get(["password"]))

			if self._manager.login():
				self._logger.info("Successfully connected to VeSync cloud service!")
				return True
			else:
				self._logger.info("Could not connect to VeSync cloud service.  Verify username/password and try again")
				self._manager = None
				return False

	def disconnect_vesync_cloud(self):
		self._manager = None

	def start_vesync_data_engine(self):
		# check to see if VeSync data engine is already running - if so, don't try to launch it again
		if not self._vesync_data_engine_timer:
			self._logger.info("Launching the VeSync data engine...")
			self._vesync_data_engine_timer = RepeatedTimer(float(self._settings.get(["update_interval"])),
														   self.get_vesync_data,
														   None, None, True)
			self._vesync_data_engine_timer.start()

	def stop_vesync_data_engine(self):
		# check to see if VeSync data engine is running - if not, it is already stopped
		if self._vesync_data_engine_timer:
			self._logger.info("Stopping the VeSync data engine...")
			self._vesync_data_engine_timer.cancel()
			self._vesync_data_engine_timer = None

	def get_vesync_data(self):
		# only run this code if the VeSync cloud service manager is connected
		if self._manager:
			displayed_statistic = self._settings.get(["displayed_statistic"])
			device_name = self._settings.get(["device_name"])
			statistic_value = None
			statistic_name = None

			self._manager.update()
			for device in self._manager.get_devices():
				if device.device_name == device_name:
					if displayed_statistic == "kWh_now":
						statistic_value = (device.get_power() / 1000)
						statistic_name = "kWh"
					elif displayed_statistic == "kWh_today":
						statistic_value = device.get_kwh_today()
						statistic_name = "kWh Today"
					elif displayed_statistic == "voltage":
						statistic_value = device.get_voltage()
						statistic_name = "Voltage"
					self._logger.debug(statistic_value)
					self._plugin_manager.send_plugin_message(self._identifier, dict(name=statistic_name,
																					value=statistic_value))

	def get_settings_defaults(self):
		return dict(username="******",
					password="",
					device_name="",
					displayed_statistic="kWh",
					update_interval=5)

	def on_settings_save(self, data):
		octoprint.plugin.SettingsPlugin.on_settings_save(self, data)

		self._logger.info("New configuration received - restarting services...")
		self.stop_vesync_data_engine()
		self.disconnect_vesync_cloud()
		if self.connect_vesync_cloud():
			self.start_vesync_data_engine()

	def get_template_configs(self):
		return [
			dict(type="navbar", custom_bindings=False),
			dict(type="settings", custom_bindings=False)
		]

	def get_assets(self):
		return {
			"js": ["js/vesync-power-monitor.js"]
		}

	def get_update_information(self):
		return dict(
			vesync_power_monitor_plugin=dict(
				displayName="VeSync Power Monitor Plugin",
				displayVersion=self._plugin_version,
				type="github_release",
				user="******",
				repo="OctoPrint-VeSync-Power-Monitor",
				current=self._plugin_version,
				pip="https://github.com/bjones14/OctoPrint-VeSync-Power-Monitor/archive/{target_version}.zip"
			)
		)