Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
EsphomeCover.async_close_cover
(self, **kwargs)
Close cover.
Close cover.
async def async_close_cover(self, **kwargs) -> None: """Close cover.""" await self._client.cover_command(key=self._static_info.key, position=0.0)
[ "async", "def", "async_close_cover", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_client", ".", "cover_command", "(", "key", "=", "self", ".", "_static_info", ".", "key", ",", "position", "=", "0.0", ")" ]
[ 106, 4 ]
[ 108, 81 ]
python
en
['en', 'la', 'en']
False
EsphomeCover.async_stop_cover
(self, **kwargs)
Stop the cover.
Stop the cover.
async def async_stop_cover(self, **kwargs) -> None: """Stop the cover.""" await self._client.cover_command(key=self._static_info.key, stop=True)
[ "async", "def", "async_stop_cover", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_client", ".", "cover_command", "(", "key", "=", "self", ".", "_static_info", ".", "key", ",", "stop", "=", "True", ")" ]
[ 110, 4 ]
[ 112, 78 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.async_set_cover_position
(self, **kwargs)
Move the cover to a specific position.
Move the cover to a specific position.
async def async_set_cover_position(self, **kwargs) -> None: """Move the cover to a specific position.""" await self._client.cover_command( key=self._static_info.key, position=kwargs[ATTR_POSITION] / 100 )
[ "async", "def", "async_set_cover_position", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_client", ".", "cover_command", "(", "key", "=", "self", ".", "_static_info", ".", "key", ",", "position", "=", "kwargs", "[", "ATTR_POSITION", "]", "/", "100", ")" ]
[ 114, 4 ]
[ 118, 9 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.async_open_cover_tilt
(self, **kwargs)
Open the cover tilt.
Open the cover tilt.
async def async_open_cover_tilt(self, **kwargs) -> None: """Open the cover tilt.""" await self._client.cover_command(key=self._static_info.key, tilt=1.0)
[ "async", "def", "async_open_cover_tilt", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_client", ".", "cover_command", "(", "key", "=", "self", ".", "_static_info", ".", "key", ",", "tilt", "=", "1.0", ")" ]
[ 120, 4 ]
[ 122, 77 ]
python
en
['en', 'no', 'en']
True
EsphomeCover.async_close_cover_tilt
(self, **kwargs)
Close the cover tilt.
Close the cover tilt.
async def async_close_cover_tilt(self, **kwargs) -> None: """Close the cover tilt.""" await self._client.cover_command(key=self._static_info.key, tilt=0.0)
[ "async", "def", "async_close_cover_tilt", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_client", ".", "cover_command", "(", "key", "=", "self", ".", "_static_info", ".", "key", ",", "tilt", "=", "0.0", ")" ]
[ 124, 4 ]
[ 126, 77 ]
python
en
['en', 'fr', 'en']
True
EsphomeCover.async_set_cover_tilt_position
(self, **kwargs)
Move the cover tilt to a specific position.
Move the cover tilt to a specific position.
async def async_set_cover_tilt_position(self, **kwargs) -> None: """Move the cover tilt to a specific position.""" await self._client.cover_command( key=self._static_info.key, tilt=kwargs[ATTR_TILT_POSITION] / 100 )
[ "async", "def", "async_set_cover_tilt_position", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_client", ".", "cover_command", "(", "key", "=", "self", ".", "_static_info", ".", "key", ",", "tilt", "=", "kwargs", "[", "ATTR_TILT_POSITION", "]", "/", "100", ")" ]
[ 128, 4 ]
[ 132, 9 ]
python
en
['en', 'en', 'en']
True
DynaliteFlowHandler.__init__
(self)
Initialize the Dynalite flow.
Initialize the Dynalite flow.
def __init__(self) -> None: """Initialize the Dynalite flow.""" self.host = None
[ "def", "__init__", "(", "self", ")", "->", "None", ":", "self", ".", "host", "=", "None" ]
[ 16, 4 ]
[ 18, 24 ]
python
en
['en', 'pl', 'en']
True
DynaliteFlowHandler.async_step_import
(self, import_info: Dict[str, Any])
Import a new bridge as a config entry.
Import a new bridge as a config entry.
async def async_step_import(self, import_info: Dict[str, Any]) -> Any: """Import a new bridge as a config entry.""" LOGGER.debug("Starting async_step_import - %s", import_info) host = import_info[CONF_HOST] for entry in self.hass.config_entries.async_entries(DOMAIN): if entry.data[CONF_HOST] == host: if entry.data != import_info: self.hass.config_entries.async_update_entry(entry, data=import_info) return self.async_abort(reason="already_configured") # New entry bridge = DynaliteBridge(self.hass, import_info) if not await bridge.async_setup(): LOGGER.error("Unable to setup bridge - import info=%s", import_info) return self.async_abort(reason="no_connection") LOGGER.debug("Creating entry for the bridge - %s", import_info) return self.async_create_entry(title=host, data=import_info)
[ "async", "def", "async_step_import", "(", "self", ",", "import_info", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Any", ":", "LOGGER", ".", "debug", "(", "\"Starting async_step_import - %s\"", ",", "import_info", ")", "host", "=", "import_info", "[", "CONF_HOST", "]", "for", "entry", "in", "self", ".", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", ":", "if", "entry", ".", "data", "[", "CONF_HOST", "]", "==", "host", ":", "if", "entry", ".", "data", "!=", "import_info", ":", "self", ".", "hass", ".", "config_entries", ".", "async_update_entry", "(", "entry", ",", "data", "=", "import_info", ")", "return", "self", ".", "async_abort", "(", "reason", "=", "\"already_configured\"", ")", "# New entry", "bridge", "=", "DynaliteBridge", "(", "self", ".", "hass", ",", "import_info", ")", "if", "not", "await", "bridge", ".", "async_setup", "(", ")", ":", "LOGGER", ".", "error", "(", "\"Unable to setup bridge - import info=%s\"", ",", "import_info", ")", "return", "self", ".", "async_abort", "(", "reason", "=", "\"no_connection\"", ")", "LOGGER", ".", "debug", "(", "\"Creating entry for the bridge - %s\"", ",", "import_info", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "host", ",", "data", "=", "import_info", ")" ]
[ 20, 4 ]
[ 35, 68 ]
python
en
['en', 'gl', 'en']
True
Transaction.generate_reference_code
(self)
Generates a unique transaction reference code
Generates a unique transaction reference code
def generate_reference_code(self): ''' Generates a unique transaction reference code ''' return uuid.uuid4()
[ "def", "generate_reference_code", "(", "self", ")", ":", "return", "uuid", ".", "uuid4", "(", ")" ]
[ 37, 4 ]
[ 41, 27 ]
python
en
['en', 'error', 'th']
False
Transaction.full_transaction_cost
(self, locale, local_cost, intl_cost)
Adds on paystack transaction charges and returns updated cost Arguments: locale : Card location (LOCAL or INTERNATIONAL)
Adds on paystack transaction charges and returns updated cost
def full_transaction_cost(self, locale, local_cost, intl_cost): ''' Adds on paystack transaction charges and returns updated cost Arguments: locale : Card location (LOCAL or INTERNATIONAL) ''' if self.amount: if locale not in ('LOCAL', 'INTERNATIONAL'): raise ValueError("Invalid locale, locale should be 'LOCAL' or 'INTERNATIONAL'") else: locale_cost = {'LOCAL' : local_cost, 'INTERNATIONAL' : intl_cost} cost = self.amount / (1 - locale_cost[locale]) if cost > 250000: cost = (self.amount + 100)/ (1 - locale_cost[locale]) paystack_charge = locale_cost[locale] * cost #Paystack_charge is capped at N2000 if paystack_charge > 200000: cost = self.amount + 200000 return math.ceil(cost) else: raise AttributeError("Amount not set")
[ "def", "full_transaction_cost", "(", "self", ",", "locale", ",", "local_cost", ",", "intl_cost", ")", ":", "if", "self", ".", "amount", ":", "if", "locale", "not", "in", "(", "'LOCAL'", ",", "'INTERNATIONAL'", ")", ":", "raise", "ValueError", "(", "\"Invalid locale, locale should be 'LOCAL' or 'INTERNATIONAL'\"", ")", "else", ":", "locale_cost", "=", "{", "'LOCAL'", ":", "local_cost", ",", "'INTERNATIONAL'", ":", "intl_cost", "}", "cost", "=", "self", ".", "amount", "/", "(", "1", "-", "locale_cost", "[", "locale", "]", ")", "if", "cost", ">", "250000", ":", "cost", "=", "(", "self", ".", "amount", "+", "100", ")", "/", "(", "1", "-", "locale_cost", "[", "locale", "]", ")", "paystack_charge", "=", "locale_cost", "[", "locale", "]", "*", "cost", "#Paystack_charge is capped at N2000", "if", "paystack_charge", ">", "200000", ":", "cost", "=", "self", ".", "amount", "+", "200000", "return", "math", ".", "ceil", "(", "cost", ")", "else", ":", "raise", "AttributeError", "(", "\"Amount not set\"", ")" ]
[ 43, 4 ]
[ 71, 50 ]
python
en
['en', 'error', 'th']
False
setup_climate
(hass, raw_traits=None, auth=None)
Load Nest climate devices.
Load Nest climate devices.
async def setup_climate(hass, raw_traits=None, auth=None): """Load Nest climate devices.""" devices = None if raw_traits: traits = raw_traits traits["sdm.devices.traits.Info"] = {"customName": "My Thermostat"} devices = { "some-device-id": Device.MakeDevice( { "name": "some-device-id", "type": "sdm.devices.types.Thermostat", "traits": traits, }, auth=auth, ), } return await async_setup_sdm_platform(hass, PLATFORM, devices)
[ "async", "def", "setup_climate", "(", "hass", ",", "raw_traits", "=", "None", ",", "auth", "=", "None", ")", ":", "devices", "=", "None", "if", "raw_traits", ":", "traits", "=", "raw_traits", "traits", "[", "\"sdm.devices.traits.Info\"", "]", "=", "{", "\"customName\"", ":", "\"My Thermostat\"", "}", "devices", "=", "{", "\"some-device-id\"", ":", "Device", ".", "MakeDevice", "(", "{", "\"name\"", ":", "\"some-device-id\"", ",", "\"type\"", ":", "\"sdm.devices.types.Thermostat\"", ",", "\"traits\"", ":", "traits", ",", "}", ",", "auth", "=", "auth", ",", ")", ",", "}", "return", "await", "async_setup_sdm_platform", "(", "hass", ",", "PLATFORM", ",", "devices", ")" ]
[ 41, 0 ]
[ 57, 66 ]
python
en
['fr', 'en', 'en']
True
test_no_devices
(hass)
Test no devices returned by the api.
Test no devices returned by the api.
async def test_no_devices(hass): """Test no devices returned by the api.""" await setup_climate(hass) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_no_devices", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 60, 0 ]
[ 63, 44 ]
python
en
['en', 'en', 'en']
True
test_climate_devices
(hass)
Test no eligible climate devices returned by the api.
Test no eligible climate devices returned by the api.
async def test_climate_devices(hass): """Test no eligible climate devices returned by the api.""" await setup_climate(hass, {"sdm.devices.traits.CameraImage": {}}) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_climate_devices", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.CameraImage\"", ":", "{", "}", "}", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 66, 0 ]
[ 69, 44 ]
python
en
['en', 'en', 'en']
True
test_thermostat_off
(hass)
Test a thermostat that is not running.
Test a thermostat that is not running.
async def test_thermostat_off(hass): """Test a thermostat that is not running.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": {"status": "OFF"}, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "OFF", }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 16.2, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 16.2 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_TEMPERATURE] is None assert thermostat.attributes[ATTR_TARGET_TEMP_LOW] is None assert thermostat.attributes[ATTR_TARGET_TEMP_HIGH] is None assert ATTR_PRESET_MODE not in thermostat.attributes assert ATTR_PRESET_MODES not in thermostat.attributes assert ATTR_FAN_MODE not in thermostat.attributes assert ATTR_FAN_MODES not in thermostat.attributes
[ "async", "def", "test_thermostat_off", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "16.2", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "16.2", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "is", "None", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_LOW", "]", "is", "None", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_HIGH", "]", "is", "None", "assert", "ATTR_PRESET_MODE", "not", "in", "thermostat", ".", "attributes", "assert", "ATTR_PRESET_MODES", "not", "in", "thermostat", ".", "attributes", "assert", "ATTR_FAN_MODE", "not", "in", "thermostat", ".", "attributes", "assert", "ATTR_FAN_MODES", "not", "in", "thermostat", ".", "attributes" ]
[ 72, 0 ]
[ 106, 54 ]
python
en
['en', 'en', 'en']
True
test_thermostat_heat
(hass)
Test a thermostat that is heating.
Test a thermostat that is heating.
async def test_thermostat_heat(hass): """Test a thermostat that is heating.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": { "status": "HEATING", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEAT", }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 16.2, }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "heatCelsius": 22.0, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_HEAT assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 16.2 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_TEMPERATURE] == 22.0 assert thermostat.attributes[ATTR_TARGET_TEMP_LOW] is None assert thermostat.attributes[ATTR_TARGET_TEMP_HIGH] is None assert ATTR_PRESET_MODE not in thermostat.attributes assert ATTR_PRESET_MODES not in thermostat.attributes
[ "async", "def", "test_thermostat_heat", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"HEATING\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEAT\"", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "16.2", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"heatCelsius\"", ":", "22.0", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_HEAT", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "16.2", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "==", "22.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_LOW", "]", "is", "None", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_HIGH", "]", "is", "None", "assert", "ATTR_PRESET_MODE", "not", "in", "thermostat", ".", "attributes", "assert", "ATTR_PRESET_MODES", "not", "in", "thermostat", ".", "attributes" ]
[ 109, 0 ]
[ 146, 57 ]
python
en
['en', 'en', 'en']
True
test_thermostat_cool
(hass)
Test a thermostat that is cooling.
Test a thermostat that is cooling.
async def test_thermostat_cool(hass): """Test a thermostat that is cooling.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": { "status": "COOLING", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "COOL", }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 29.9, }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "coolCelsius": 28.0, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_COOL assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_COOL assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 29.9 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_TEMPERATURE] == 28.0 assert thermostat.attributes[ATTR_TARGET_TEMP_LOW] is None assert thermostat.attributes[ATTR_TARGET_TEMP_HIGH] is None assert ATTR_PRESET_MODE not in thermostat.attributes assert ATTR_PRESET_MODES not in thermostat.attributes
[ "async", "def", "test_thermostat_cool", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"COOLING\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"COOL\"", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "29.9", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"coolCelsius\"", ":", "28.0", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "29.9", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "==", "28.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_LOW", "]", "is", "None", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_HIGH", "]", "is", "None", "assert", "ATTR_PRESET_MODE", "not", "in", "thermostat", ".", "attributes", "assert", "ATTR_PRESET_MODES", "not", "in", "thermostat", ".", "attributes" ]
[ 149, 0 ]
[ 186, 57 ]
python
en
['en', 'en', 'en']
True
test_thermostat_heatcool
(hass)
Test a thermostat that is cooling in heatcool mode.
Test a thermostat that is cooling in heatcool mode.
async def test_thermostat_heatcool(hass): """Test a thermostat that is cooling in heatcool mode.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": { "status": "COOLING", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEATCOOL", }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 29.9, }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "heatCelsius": 22.0, "coolCelsius": 28.0, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT_COOL assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_COOL assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 29.9 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_TARGET_TEMP_LOW] == 22.0 assert thermostat.attributes[ATTR_TARGET_TEMP_HIGH] == 28.0 assert thermostat.attributes[ATTR_TEMPERATURE] is None assert ATTR_PRESET_MODE not in thermostat.attributes assert ATTR_PRESET_MODES not in thermostat.attributes
[ "async", "def", "test_thermostat_heatcool", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"COOLING\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEATCOOL\"", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "29.9", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"heatCelsius\"", ":", "22.0", ",", "\"coolCelsius\"", ":", "28.0", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "29.9", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_LOW", "]", "==", "22.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_HIGH", "]", "==", "28.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "is", "None", "assert", "ATTR_PRESET_MODE", "not", "in", "thermostat", ".", "attributes", "assert", "ATTR_PRESET_MODES", "not", "in", "thermostat", ".", "attributes" ]
[ 189, 0 ]
[ 227, 57 ]
python
en
['en', 'en', 'en']
True
test_thermostat_eco_off
(hass)
Test a thermostat cooling with eco off.
Test a thermostat cooling with eco off.
async def test_thermostat_eco_off(hass): """Test a thermostat cooling with eco off.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": { "status": "COOLING", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEATCOOL", }, "sdm.devices.traits.ThermostatEco": { "availableModes": ["MANUAL_ECO", "OFF"], "mode": "OFF", "heatCelsius": 20.0, "coolCelsius": 22.0, }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 29.9, }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "heatCelsius": 22.0, "coolCelsius": 28.0, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT_COOL assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_COOL assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 29.9 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_TARGET_TEMP_LOW] == 22.0 assert thermostat.attributes[ATTR_TARGET_TEMP_HIGH] == 28.0 assert thermostat.attributes[ATTR_TEMPERATURE] is None assert thermostat.attributes[ATTR_PRESET_MODE] == PRESET_NONE assert thermostat.attributes[ATTR_PRESET_MODES] == [PRESET_ECO, PRESET_NONE]
[ "async", "def", "test_thermostat_eco_off", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"COOLING\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEATCOOL\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatEco\"", ":", "{", "\"availableModes\"", ":", "[", "\"MANUAL_ECO\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "\"heatCelsius\"", ":", "20.0", ",", "\"coolCelsius\"", ":", "22.0", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "29.9", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"heatCelsius\"", ":", "22.0", ",", "\"coolCelsius\"", ":", "28.0", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "29.9", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_LOW", "]", "==", "22.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_HIGH", "]", "==", "28.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "is", "None", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODE", "]", "==", "PRESET_NONE", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODES", "]", "==", "[", "PRESET_ECO", ",", "PRESET_NONE", "]" ]
[ 230, 0 ]
[ 274, 80 ]
python
en
['en', 'en', 'en']
True
test_thermostat_eco_on
(hass)
Test a thermostat in eco mode.
Test a thermostat in eco mode.
async def test_thermostat_eco_on(hass): """Test a thermostat in eco mode.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": { "status": "COOLING", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEATCOOL", }, "sdm.devices.traits.ThermostatEco": { "availableModes": ["MANUAL_ECO", "OFF"], "mode": "MANUAL_ECO", "heatCelsius": 21.0, "coolCelsius": 29.0, }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 29.9, }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "heatCelsius": 22.0, "coolCelsius": 28.0, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT_COOL assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_COOL assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 29.9 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_TARGET_TEMP_LOW] == 21.0 assert thermostat.attributes[ATTR_TARGET_TEMP_HIGH] == 29.0 assert thermostat.attributes[ATTR_TEMPERATURE] is None assert thermostat.attributes[ATTR_PRESET_MODE] == PRESET_ECO assert thermostat.attributes[ATTR_PRESET_MODES] == [PRESET_ECO, PRESET_NONE]
[ "async", "def", "test_thermostat_eco_on", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"COOLING\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEATCOOL\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatEco\"", ":", "{", "\"availableModes\"", ":", "[", "\"MANUAL_ECO\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"MANUAL_ECO\"", ",", "\"heatCelsius\"", ":", "21.0", ",", "\"coolCelsius\"", ":", "29.0", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "29.9", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"heatCelsius\"", ":", "22.0", ",", "\"coolCelsius\"", ":", "28.0", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "29.9", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_LOW", "]", "==", "21.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_HIGH", "]", "==", "29.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "is", "None", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODE", "]", "==", "PRESET_ECO", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODES", "]", "==", "[", "PRESET_ECO", ",", "PRESET_NONE", "]" ]
[ 277, 0 ]
[ 321, 80 ]
python
en
['en', 'en', 'it']
True
test_thermostat_eco_heat_only
(hass)
Test a thermostat in eco mode that only supports heat.
Test a thermostat in eco mode that only supports heat.
async def test_thermostat_eco_heat_only(hass): """Test a thermostat in eco mode that only supports heat.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": { "status": "OFF", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "OFF"], "mode": "HEAT", }, "sdm.devices.traits.ThermostatEco": { "availableModes": ["MANUAL_ECO", "OFF"], "mode": "MANUAL_ECO", "heatCelsius": 21.0, "coolCelsius": 29.0, }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 29.9, }, "sdm.devices.traits.ThermostatTemperatureSetpoint": {}, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 29.9 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_TEMPERATURE] == 21.0 assert ATTR_TARGET_TEMP_LOW not in thermostat.attributes assert ATTR_TARGET_TEMP_HIGH not in thermostat.attributes assert thermostat.attributes[ATTR_PRESET_MODE] == PRESET_ECO assert thermostat.attributes[ATTR_PRESET_MODES] == [PRESET_ECO, PRESET_NONE]
[ "async", "def", "test_thermostat_eco_heat_only", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEAT\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatEco\"", ":", "{", "\"availableModes\"", ":", "[", "\"MANUAL_ECO\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"MANUAL_ECO\"", ",", "\"heatCelsius\"", ":", "21.0", ",", "\"coolCelsius\"", ":", "29.0", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "29.9", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "29.9", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "==", "21.0", "assert", "ATTR_TARGET_TEMP_LOW", "not", "in", "thermostat", ".", "attributes", "assert", "ATTR_TARGET_TEMP_HIGH", "not", "in", "thermostat", ".", "attributes", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODE", "]", "==", "PRESET_ECO", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODES", "]", "==", "[", "PRESET_ECO", ",", "PRESET_NONE", "]" ]
[ 324, 0 ]
[ 363, 80 ]
python
en
['en', 'en', 'en']
True
test_thermostat_set_hvac_mode
(hass, auth)
Test a thermostat changing hvac modes.
Test a thermostat changing hvac modes.
async def test_thermostat_set_hvac_mode(hass, auth): """Test a thermostat changing hvac modes.""" subscriber = await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": {"status": "OFF"}, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "OFF", }, }, auth=auth, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF await common.async_set_hvac_mode(hass, HVAC_MODE_HEAT) await hass.async_block_till_done() assert auth.method == "post" assert auth.url == "some-device-id:executeCommand" assert auth.json == { "command": "sdm.devices.commands.ThermostatMode.SetMode", "params": {"mode": "HEAT"}, } # Local state does not reflect the update thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF # Simulate pubsub message when mode changes event = EventMessage( { "eventId": "some-event-id", "timestamp": "2019-01-01T00:00:01Z", "resourceUpdate": { "name": "some-device-id", "traits": { "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEAT", }, }, }, }, auth=None, ) subscriber.receive_event(event) await hass.async_block_till_done() # Process dispatch/update signal thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF # Simulate pubsub message when the thermostat starts heating event = EventMessage( { "eventId": "some-event-id", "timestamp": "2019-01-01T00:00:01Z", "resourceUpdate": { "name": "some-device-id", "traits": { "sdm.devices.traits.ThermostatHvac": { "status": "HEATING", }, }, }, }, auth=None, ) subscriber.receive_event(event) await hass.async_block_till_done() # Process dispatch/update signal thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_HEAT
[ "async", "def", "test_thermostat_set_hvac_mode", "(", "hass", ",", "auth", ")", ":", "subscriber", "=", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "}", ",", "}", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "await", "common", ".", "async_set_hvac_mode", "(", "hass", ",", "HVAC_MODE_HEAT", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "auth", ".", "method", "==", "\"post\"", "assert", "auth", ".", "url", "==", "\"some-device-id:executeCommand\"", "assert", "auth", ".", "json", "==", "{", "\"command\"", ":", "\"sdm.devices.commands.ThermostatMode.SetMode\"", ",", "\"params\"", ":", "{", "\"mode\"", ":", "\"HEAT\"", "}", ",", "}", "# Local state does not reflect the update", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "# Simulate pubsub message when mode changes", "event", "=", "EventMessage", "(", "{", "\"eventId\"", ":", "\"some-event-id\"", ",", "\"timestamp\"", ":", "\"2019-01-01T00:00:01Z\"", ",", "\"resourceUpdate\"", ":", "{", "\"name\"", ":", "\"some-device-id\"", ",", "\"traits\"", ":", "{", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEAT\"", ",", "}", ",", "}", ",", "}", ",", "}", ",", "auth", "=", "None", ",", ")", "subscriber", ".", "receive_event", "(", "event", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Process dispatch/update signal", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "# Simulate pubsub message when the thermostat starts heating", "event", "=", "EventMessage", "(", "{", "\"eventId\"", ":", "\"some-event-id\"", ",", "\"timestamp\"", ":", "\"2019-01-01T00:00:01Z\"", ",", "\"resourceUpdate\"", ":", "{", "\"name\"", ":", "\"some-device-id\"", ",", "\"traits\"", ":", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"HEATING\"", ",", "}", ",", "}", ",", "}", ",", "}", ",", "auth", "=", "None", ",", ")", "subscriber", ".", "receive_event", "(", "event", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Process dispatch/update signal", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_HEAT" ]
[ 366, 0 ]
[ 449, 71 ]
python
en
['en', 'en', 'en']
True
test_thermostat_set_eco_preset
(hass, auth)
Test a thermostat put into eco mode.
Test a thermostat put into eco mode.
async def test_thermostat_set_eco_preset(hass, auth): """Test a thermostat put into eco mode.""" subscriber = await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": {"status": "OFF"}, "sdm.devices.traits.ThermostatEco": { "availableModes": ["MANUAL_ECO", "OFF"], "mode": "OFF", "heatCelsius": 15.0, "coolCelsius": 28.0, }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "OFF", }, }, auth=auth, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF assert thermostat.attributes[ATTR_PRESET_MODE] == PRESET_NONE # Turn on eco mode await common.async_set_preset_mode(hass, PRESET_ECO) await hass.async_block_till_done() assert auth.method == "post" assert auth.url == "some-device-id:executeCommand" assert auth.json == { "command": "sdm.devices.commands.ThermostatEco.SetMode", "params": {"mode": "MANUAL_ECO"}, } # Local state does not reflect the update thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF assert thermostat.attributes[ATTR_PRESET_MODE] == PRESET_NONE # Simulate pubsub message when mode changes event = EventMessage( { "eventId": "some-event-id", "timestamp": "2019-01-01T00:00:01Z", "resourceUpdate": { "name": "some-device-id", "traits": { "sdm.devices.traits.ThermostatEco": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "MANUAL_ECO", "heatCelsius": 15.0, "coolCelsius": 28.0, }, }, }, }, auth=auth, ) subscriber.receive_event(event) await hass.async_block_till_done() # Process dispatch/update signal thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF assert thermostat.attributes[ATTR_PRESET_MODE] == PRESET_ECO # Turn off eco mode await common.async_set_preset_mode(hass, PRESET_NONE) await hass.async_block_till_done() assert auth.method == "post" assert auth.url == "some-device-id:executeCommand" assert auth.json == { "command": "sdm.devices.commands.ThermostatEco.SetMode", "params": {"mode": "OFF"}, }
[ "async", "def", "test_thermostat_set_eco_preset", "(", "hass", ",", "auth", ")", ":", "subscriber", "=", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", "}", ",", "\"sdm.devices.traits.ThermostatEco\"", ":", "{", "\"availableModes\"", ":", "[", "\"MANUAL_ECO\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "\"heatCelsius\"", ":", "15.0", ",", "\"coolCelsius\"", ":", "28.0", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "}", ",", "}", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODE", "]", "==", "PRESET_NONE", "# Turn on eco mode", "await", "common", ".", "async_set_preset_mode", "(", "hass", ",", "PRESET_ECO", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "auth", ".", "method", "==", "\"post\"", "assert", "auth", ".", "url", "==", "\"some-device-id:executeCommand\"", "assert", "auth", ".", "json", "==", "{", "\"command\"", ":", "\"sdm.devices.commands.ThermostatEco.SetMode\"", ",", "\"params\"", ":", "{", "\"mode\"", ":", "\"MANUAL_ECO\"", "}", ",", "}", "# Local state does not reflect the update", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODE", "]", "==", "PRESET_NONE", "# Simulate pubsub message when mode changes", "event", "=", "EventMessage", "(", "{", "\"eventId\"", ":", "\"some-event-id\"", ",", "\"timestamp\"", ":", "\"2019-01-01T00:00:01Z\"", ",", "\"resourceUpdate\"", ":", "{", "\"name\"", ":", "\"some-device-id\"", ",", "\"traits\"", ":", "{", "\"sdm.devices.traits.ThermostatEco\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"MANUAL_ECO\"", ",", "\"heatCelsius\"", ":", "15.0", ",", "\"coolCelsius\"", ":", "28.0", ",", "}", ",", "}", ",", "}", ",", "}", ",", "auth", "=", "auth", ",", ")", "subscriber", ".", "receive_event", "(", "event", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Process dispatch/update signal", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_PRESET_MODE", "]", "==", "PRESET_ECO", "# Turn off eco mode", "await", "common", ".", "async_set_preset_mode", "(", "hass", ",", "PRESET_NONE", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "auth", ".", "method", "==", "\"post\"", "assert", "auth", ".", "url", "==", "\"some-device-id:executeCommand\"", "assert", "auth", ".", "json", "==", "{", "\"command\"", ":", "\"sdm.devices.commands.ThermostatEco.SetMode\"", ",", "\"params\"", ":", "{", "\"mode\"", ":", "\"OFF\"", "}", ",", "}" ]
[ 452, 0 ]
[ 534, 5 ]
python
en
['en', 'en', 'en']
True
test_thermostat_set_cool
(hass, auth)
Test a thermostat in cool mode with a temperature change.
Test a thermostat in cool mode with a temperature change.
async def test_thermostat_set_cool(hass, auth): """Test a thermostat in cool mode with a temperature change.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": {"status": "OFF"}, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "COOL", }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "coolCelsius": 25.0, }, }, auth=auth, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_COOL await common.async_set_temperature(hass, temperature=24.0) await hass.async_block_till_done() assert auth.method == "post" assert auth.url == "some-device-id:executeCommand" assert auth.json == { "command": "sdm.devices.commands.ThermostatTemperatureSetpoint.SetCool", "params": {"coolCelsius": 24.0}, }
[ "async", "def", "test_thermostat_set_cool", "(", "hass", ",", "auth", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"COOL\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"coolCelsius\"", ":", "25.0", ",", "}", ",", "}", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_COOL", "await", "common", ".", "async_set_temperature", "(", "hass", ",", "temperature", "=", "24.0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "auth", ".", "method", "==", "\"post\"", "assert", "auth", ".", "url", "==", "\"some-device-id:executeCommand\"", "assert", "auth", ".", "json", "==", "{", "\"command\"", ":", "\"sdm.devices.commands.ThermostatTemperatureSetpoint.SetCool\"", ",", "\"params\"", ":", "{", "\"coolCelsius\"", ":", "24.0", "}", ",", "}" ]
[ 537, 0 ]
[ 567, 5 ]
python
en
['en', 'en', 'en']
True
test_thermostat_set_heat
(hass, auth)
Test a thermostat heating mode with a temperature change.
Test a thermostat heating mode with a temperature change.
async def test_thermostat_set_heat(hass, auth): """Test a thermostat heating mode with a temperature change.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": {"status": "OFF"}, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEAT", }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "heatCelsius": 19.0, }, }, auth=auth, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT await common.async_set_temperature(hass, temperature=20.0) await hass.async_block_till_done() assert auth.method == "post" assert auth.url == "some-device-id:executeCommand" assert auth.json == { "command": "sdm.devices.commands.ThermostatTemperatureSetpoint.SetHeat", "params": {"heatCelsius": 20.0}, }
[ "async", "def", "test_thermostat_set_heat", "(", "hass", ",", "auth", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEAT\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"heatCelsius\"", ":", "19.0", ",", "}", ",", "}", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT", "await", "common", ".", "async_set_temperature", "(", "hass", ",", "temperature", "=", "20.0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "auth", ".", "method", "==", "\"post\"", "assert", "auth", ".", "url", "==", "\"some-device-id:executeCommand\"", "assert", "auth", ".", "json", "==", "{", "\"command\"", ":", "\"sdm.devices.commands.ThermostatTemperatureSetpoint.SetHeat\"", ",", "\"params\"", ":", "{", "\"heatCelsius\"", ":", "20.0", "}", ",", "}" ]
[ 570, 0 ]
[ 600, 5 ]
python
en
['en', 'en', 'en']
True
test_thermostat_set_heat_cool
(hass, auth)
Test a thermostat in heatcool mode with a temperature change.
Test a thermostat in heatcool mode with a temperature change.
async def test_thermostat_set_heat_cool(hass, auth): """Test a thermostat in heatcool mode with a temperature change.""" await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": {"status": "OFF"}, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEATCOOL", }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "heatCelsius": 19.0, "coolCelsius": 25.0, }, }, auth=auth, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT_COOL await common.async_set_temperature( hass, target_temp_low=20.0, target_temp_high=24.0 ) await hass.async_block_till_done() assert auth.method == "post" assert auth.url == "some-device-id:executeCommand" assert auth.json == { "command": "sdm.devices.commands.ThermostatTemperatureSetpoint.SetRange", "params": {"heatCelsius": 20.0, "coolCelsius": 24.0}, }
[ "async", "def", "test_thermostat_set_heat_cool", "(", "hass", ",", "auth", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEATCOOL\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"heatCelsius\"", ":", "19.0", ",", "\"coolCelsius\"", ":", "25.0", ",", "}", ",", "}", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT_COOL", "await", "common", ".", "async_set_temperature", "(", "hass", ",", "target_temp_low", "=", "20.0", ",", "target_temp_high", "=", "24.0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "auth", ".", "method", "==", "\"post\"", "assert", "auth", ".", "url", "==", "\"some-device-id:executeCommand\"", "assert", "auth", ".", "json", "==", "{", "\"command\"", ":", "\"sdm.devices.commands.ThermostatTemperatureSetpoint.SetRange\"", ",", "\"params\"", ":", "{", "\"heatCelsius\"", ":", "20.0", ",", "\"coolCelsius\"", ":", "24.0", "}", ",", "}" ]
[ 603, 0 ]
[ 636, 5 ]
python
en
['en', 'en', 'en']
True
test_thermostat_fan_off
(hass)
Test a thermostat with the fan not running.
Test a thermostat with the fan not running.
async def test_thermostat_fan_off(hass): """Test a thermostat with the fan not running.""" await setup_climate( hass, { "sdm.devices.traits.Fan": { "timerMode": "OFF", "timerTimeout": "2019-05-10T03:22:54Z", }, "sdm.devices.traits.ThermostatHvac": {"status": "OFF"}, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "OFF", }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 16.2, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 16.2 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_FAN_MODE] == FAN_OFF assert thermostat.attributes[ATTR_FAN_MODES] == [FAN_ON, FAN_OFF]
[ "async", "def", "test_thermostat_fan_off", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.Fan\"", ":", "{", "\"timerMode\"", ":", "\"OFF\"", ",", "\"timerTimeout\"", ":", "\"2019-05-10T03:22:54Z\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "16.2", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "16.2", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_FAN_MODE", "]", "==", "FAN_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_FAN_MODES", "]", "==", "[", "FAN_ON", ",", "FAN_OFF", "]" ]
[ 639, 0 ]
[ 672, 69 ]
python
en
['en', 'en', 'en']
True
test_thermostat_fan_on
(hass)
Test a thermostat with the fan running.
Test a thermostat with the fan running.
async def test_thermostat_fan_on(hass): """Test a thermostat with the fan running.""" await setup_climate( hass, { "sdm.devices.traits.Fan": { "timerMode": "ON", "timerTimeout": "2019-05-10T03:22:54Z", }, "sdm.devices.traits.ThermostatHvac": { "status": "OFF", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "OFF", }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 16.2, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 16.2 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert thermostat.attributes[ATTR_FAN_MODE] == FAN_ON assert thermostat.attributes[ATTR_FAN_MODES] == [FAN_ON, FAN_OFF]
[ "async", "def", "test_thermostat_fan_on", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.Fan\"", ":", "{", "\"timerMode\"", ":", "\"ON\"", ",", "\"timerTimeout\"", ":", "\"2019-05-10T03:22:54Z\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "16.2", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "16.2", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "thermostat", ".", "attributes", "[", "ATTR_FAN_MODE", "]", "==", "FAN_ON", "assert", "thermostat", ".", "attributes", "[", "ATTR_FAN_MODES", "]", "==", "[", "FAN_ON", ",", "FAN_OFF", "]" ]
[ 675, 0 ]
[ 710, 69 ]
python
en
['en', 'en', 'en']
True
test_thermostat_set_fan
(hass, auth)
Test a thermostat enabling the fan.
Test a thermostat enabling the fan.
async def test_thermostat_set_fan(hass, auth): """Test a thermostat enabling the fan.""" await setup_climate( hass, { "sdm.devices.traits.Fan": { "timerMode": "ON", "timerTimeout": "2019-05-10T03:22:54Z", }, "sdm.devices.traits.ThermostatHvac": { "status": "OFF", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "OFF", }, }, auth=auth, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_FAN_MODE] == FAN_ON assert thermostat.attributes[ATTR_FAN_MODES] == [FAN_ON, FAN_OFF] # Turn off fan mode await common.async_set_fan_mode(hass, FAN_OFF) await hass.async_block_till_done() assert auth.method == "post" assert auth.url == "some-device-id:executeCommand" assert auth.json == { "command": "sdm.devices.commands.Fan.SetTimer", "params": {"timerMode": "OFF"}, }
[ "async", "def", "test_thermostat_set_fan", "(", "hass", ",", "auth", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.Fan\"", ":", "{", "\"timerMode\"", ":", "\"ON\"", ",", "\"timerTimeout\"", ":", "\"2019-05-10T03:22:54Z\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "}", ",", "}", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_FAN_MODE", "]", "==", "FAN_ON", "assert", "thermostat", ".", "attributes", "[", "ATTR_FAN_MODES", "]", "==", "[", "FAN_ON", ",", "FAN_OFF", "]", "# Turn off fan mode", "await", "common", ".", "async_set_fan_mode", "(", "hass", ",", "FAN_OFF", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "auth", ".", "method", "==", "\"post\"", "assert", "auth", ".", "url", "==", "\"some-device-id:executeCommand\"", "assert", "auth", ".", "json", "==", "{", "\"command\"", ":", "\"sdm.devices.commands.Fan.SetTimer\"", ",", "\"params\"", ":", "{", "\"timerMode\"", ":", "\"OFF\"", "}", ",", "}" ]
[ 713, 0 ]
[ 749, 5 ]
python
en
['en', 'en', 'en']
True
test_thermostat_fan_empty
(hass)
Test a fan trait with an empty response.
Test a fan trait with an empty response.
async def test_thermostat_fan_empty(hass): """Test a fan trait with an empty response.""" await setup_climate( hass, { "sdm.devices.traits.Fan": {}, "sdm.devices.traits.ThermostatHvac": {"status": "OFF"}, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "OFF", }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 16.2, }, }, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_OFF assert thermostat.attributes[ATTR_HVAC_ACTION] == CURRENT_HVAC_OFF assert thermostat.attributes[ATTR_CURRENT_TEMPERATURE] == 16.2 assert set(thermostat.attributes[ATTR_HVAC_MODES]) == { HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, } assert ATTR_FAN_MODE not in thermostat.attributes assert ATTR_FAN_MODES not in thermostat.attributes
[ "async", "def", "test_thermostat_fan_empty", "(", "hass", ")", ":", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.Fan\"", ":", "{", "}", ",", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"OFF\"", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"OFF\"", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "16.2", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_HVAC_ACTION", "]", "==", "CURRENT_HVAC_OFF", "assert", "thermostat", ".", "attributes", "[", "ATTR_CURRENT_TEMPERATURE", "]", "==", "16.2", "assert", "set", "(", "thermostat", ".", "attributes", "[", "ATTR_HVAC_MODES", "]", ")", "==", "{", "HVAC_MODE_HEAT", ",", "HVAC_MODE_COOL", ",", "HVAC_MODE_HEAT_COOL", ",", "HVAC_MODE_OFF", ",", "}", "assert", "ATTR_FAN_MODE", "not", "in", "thermostat", ".", "attributes", "assert", "ATTR_FAN_MODES", "not", "in", "thermostat", ".", "attributes" ]
[ 752, 0 ]
[ 782, 54 ]
python
en
['en', 'fy', 'en']
True
test_thermostat_target_temp
(hass, auth)
Test a thermostat changing hvac modes and affected on target temps.
Test a thermostat changing hvac modes and affected on target temps.
async def test_thermostat_target_temp(hass, auth): """Test a thermostat changing hvac modes and affected on target temps.""" subscriber = await setup_climate( hass, { "sdm.devices.traits.ThermostatHvac": { "status": "HEATING", }, "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEAT", }, "sdm.devices.traits.Temperature": { "ambientTemperatureCelsius": 20.1, }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "heatCelsius": 23.0, }, }, auth=auth, ) assert len(hass.states.async_all()) == 1 thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT assert thermostat.attributes[ATTR_TEMPERATURE] == 23.0 assert thermostat.attributes[ATTR_TARGET_TEMP_LOW] is None assert thermostat.attributes[ATTR_TARGET_TEMP_HIGH] is None # Simulate pubsub message changing modes event = EventMessage( { "eventId": "some-event-id", "timestamp": "2019-01-01T00:00:01Z", "resourceUpdate": { "name": "some-device-id", "traits": { "sdm.devices.traits.ThermostatMode": { "availableModes": ["HEAT", "COOL", "HEATCOOL", "OFF"], "mode": "HEATCOOL", }, "sdm.devices.traits.ThermostatTemperatureSetpoint": { "heatCelsius": 22.0, "coolCelsius": 28.0, }, }, }, }, auth=None, ) subscriber.receive_event(event) await hass.async_block_till_done() # Process dispatch/update signal thermostat = hass.states.get("climate.my_thermostat") assert thermostat is not None assert thermostat.state == HVAC_MODE_HEAT_COOL assert thermostat.attributes[ATTR_TARGET_TEMP_LOW] == 22.0 assert thermostat.attributes[ATTR_TARGET_TEMP_HIGH] == 28.0 assert thermostat.attributes[ATTR_TEMPERATURE] is None
[ "async", "def", "test_thermostat_target_temp", "(", "hass", ",", "auth", ")", ":", "subscriber", "=", "await", "setup_climate", "(", "hass", ",", "{", "\"sdm.devices.traits.ThermostatHvac\"", ":", "{", "\"status\"", ":", "\"HEATING\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEAT\"", ",", "}", ",", "\"sdm.devices.traits.Temperature\"", ":", "{", "\"ambientTemperatureCelsius\"", ":", "20.1", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"heatCelsius\"", ":", "23.0", ",", "}", ",", "}", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "==", "23.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_LOW", "]", "is", "None", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_HIGH", "]", "is", "None", "# Simulate pubsub message changing modes", "event", "=", "EventMessage", "(", "{", "\"eventId\"", ":", "\"some-event-id\"", ",", "\"timestamp\"", ":", "\"2019-01-01T00:00:01Z\"", ",", "\"resourceUpdate\"", ":", "{", "\"name\"", ":", "\"some-device-id\"", ",", "\"traits\"", ":", "{", "\"sdm.devices.traits.ThermostatMode\"", ":", "{", "\"availableModes\"", ":", "[", "\"HEAT\"", ",", "\"COOL\"", ",", "\"HEATCOOL\"", ",", "\"OFF\"", "]", ",", "\"mode\"", ":", "\"HEATCOOL\"", ",", "}", ",", "\"sdm.devices.traits.ThermostatTemperatureSetpoint\"", ":", "{", "\"heatCelsius\"", ":", "22.0", ",", "\"coolCelsius\"", ":", "28.0", ",", "}", ",", "}", ",", "}", ",", "}", ",", "auth", "=", "None", ",", ")", "subscriber", ".", "receive_event", "(", "event", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Process dispatch/update signal", "thermostat", "=", "hass", ".", "states", ".", "get", "(", "\"climate.my_thermostat\"", ")", "assert", "thermostat", "is", "not", "None", "assert", "thermostat", ".", "state", "==", "HVAC_MODE_HEAT_COOL", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_LOW", "]", "==", "22.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TARGET_TEMP_HIGH", "]", "==", "28.0", "assert", "thermostat", ".", "attributes", "[", "ATTR_TEMPERATURE", "]", "is", "None" ]
[ 785, 0 ]
[ 844, 58 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Tesla binary_sensors by config_entry.
Set up the Tesla binary_sensors by config_entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Tesla binary_sensors by config_entry.""" async_add_entities( [ TeslaThermostat( device, hass.data[TESLA_DOMAIN][config_entry.entry_id]["coordinator"], ) for device in hass.data[TESLA_DOMAIN][config_entry.entry_id]["devices"][ "climate" ] ], True, )
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "async_add_entities", "(", "[", "TeslaThermostat", "(", "device", ",", "hass", ".", "data", "[", "TESLA_DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "\"coordinator\"", "]", ",", ")", "for", "device", "in", "hass", ".", "data", "[", "TESLA_DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "\"devices\"", "]", "[", "\"climate\"", "]", "]", ",", "True", ",", ")" ]
[ 22, 0 ]
[ 35, 5 ]
python
en
['en', 'en', 'en']
True
TeslaThermostat.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self): """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_TARGET_TEMPERATURE", "|", "SUPPORT_PRESET_MODE" ]
[ 42, 4 ]
[ 44, 63 ]
python
en
['en', 'en', 'en']
True
TeslaThermostat.hvac_mode
(self)
Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*.
Return hvac operation ie. heat, cool mode.
def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self.tesla_device.is_hvac_enabled(): return HVAC_MODE_HEAT_COOL return HVAC_MODE_OFF
[ "def", "hvac_mode", "(", "self", ")", ":", "if", "self", ".", "tesla_device", ".", "is_hvac_enabled", "(", ")", ":", "return", "HVAC_MODE_HEAT_COOL", "return", "HVAC_MODE_OFF" ]
[ 47, 4 ]
[ 54, 28 ]
python
bg
['en', 'bg', 'bg']
True
TeslaThermostat.hvac_modes
(self)
Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES.
Return the list of available hvac operation modes.
def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return SUPPORT_HVAC
[ "def", "hvac_modes", "(", "self", ")", ":", "return", "SUPPORT_HVAC" ]
[ 57, 4 ]
[ 62, 27 ]
python
en
['en', 'en', 'en']
True
TeslaThermostat.temperature_unit
(self)
Return the unit of measurement.
Return the unit of measurement.
def temperature_unit(self): """Return the unit of measurement.""" if self.tesla_device.measurement == "F": return TEMP_FAHRENHEIT return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", ":", "if", "self", ".", "tesla_device", ".", "measurement", "==", "\"F\"", ":", "return", "TEMP_FAHRENHEIT", "return", "TEMP_CELSIUS" ]
[ 65, 4 ]
[ 69, 27 ]
python
en
['en', 'la', 'en']
True
TeslaThermostat.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self): """Return the current temperature.""" return self.tesla_device.get_current_temp()
[ "def", "current_temperature", "(", "self", ")", ":", "return", "self", ".", "tesla_device", ".", "get_current_temp", "(", ")" ]
[ 72, 4 ]
[ 74, 51 ]
python
en
['en', 'la', 'en']
True
TeslaThermostat.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self): """Return the temperature we try to reach.""" return self.tesla_device.get_goal_temp()
[ "def", "target_temperature", "(", "self", ")", ":", "return", "self", ".", "tesla_device", ".", "get_goal_temp", "(", ")" ]
[ 77, 4 ]
[ 79, 48 ]
python
en
['en', 'en', 'en']
True
TeslaThermostat.async_set_temperature
(self, **kwargs)
Set new target temperatures.
Set new target temperatures.
async def async_set_temperature(self, **kwargs): """Set new target temperatures.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature: _LOGGER.debug("%s: Setting temperature to %s", self.name, temperature) await self.tesla_device.set_temperature(temperature)
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "temperature", "=", "kwargs", ".", "get", "(", "ATTR_TEMPERATURE", ")", "if", "temperature", ":", "_LOGGER", ".", "debug", "(", "\"%s: Setting temperature to %s\"", ",", "self", ".", "name", ",", "temperature", ")", "await", "self", ".", "tesla_device", ".", "set_temperature", "(", "temperature", ")" ]
[ 81, 4 ]
[ 86, 64 ]
python
en
['en', 'ca', 'en']
True
TeslaThermostat.async_set_hvac_mode
(self, hvac_mode)
Set new target hvac mode.
Set new target hvac mode.
async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" _LOGGER.debug("%s: Setting hvac mode to %s", self.name, hvac_mode) if hvac_mode == HVAC_MODE_OFF: await self.tesla_device.set_status(False) elif hvac_mode == HVAC_MODE_HEAT_COOL: await self.tesla_device.set_status(True)
[ "async", "def", "async_set_hvac_mode", "(", "self", ",", "hvac_mode", ")", ":", "_LOGGER", ".", "debug", "(", "\"%s: Setting hvac mode to %s\"", ",", "self", ".", "name", ",", "hvac_mode", ")", "if", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "await", "self", ".", "tesla_device", ".", "set_status", "(", "False", ")", "elif", "hvac_mode", "==", "HVAC_MODE_HEAT_COOL", ":", "await", "self", ".", "tesla_device", ".", "set_status", "(", "True", ")" ]
[ 88, 4 ]
[ 94, 52 ]
python
da
['da', 'su', 'en']
False
TeslaThermostat.async_set_preset_mode
(self, preset_mode: str)
Set new preset mode.
Set new preset mode.
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" _LOGGER.debug("%s: Setting preset_mode to: %s", self.name, preset_mode) try: await self.tesla_device.set_preset_mode(preset_mode) except UnknownPresetMode as ex: _LOGGER.error("%s", ex.message)
[ "async", "def", "async_set_preset_mode", "(", "self", ",", "preset_mode", ":", "str", ")", "->", "None", ":", "_LOGGER", ".", "debug", "(", "\"%s: Setting preset_mode to: %s\"", ",", "self", ".", "name", ",", "preset_mode", ")", "try", ":", "await", "self", ".", "tesla_device", ".", "set_preset_mode", "(", "preset_mode", ")", "except", "UnknownPresetMode", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"%s\"", ",", "ex", ".", "message", ")" ]
[ 96, 4 ]
[ 102, 43 ]
python
en
['en', 'sr', 'en']
True
TeslaThermostat.preset_mode
(self)
Return the current preset mode, e.g., home, away, temp. Requires SUPPORT_PRESET_MODE.
Return the current preset mode, e.g., home, away, temp.
def preset_mode(self) -> Optional[str]: """Return the current preset mode, e.g., home, away, temp. Requires SUPPORT_PRESET_MODE. """ return self.tesla_device.preset_mode
[ "def", "preset_mode", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "tesla_device", ".", "preset_mode" ]
[ 105, 4 ]
[ 110, 44 ]
python
en
['en', 'pt', 'en']
True
TeslaThermostat.preset_modes
(self)
Return a list of available preset modes. Requires SUPPORT_PRESET_MODE.
Return a list of available preset modes.
def preset_modes(self) -> Optional[List[str]]: """Return a list of available preset modes. Requires SUPPORT_PRESET_MODE. """ return self.tesla_device.preset_modes
[ "def", "preset_modes", "(", "self", ")", "->", "Optional", "[", "List", "[", "str", "]", "]", ":", "return", "self", ".", "tesla_device", ".", "preset_modes" ]
[ 113, 4 ]
[ 118, 45 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass: HomeAssistant, config: dict)
Set up the Nightscout component.
Set up the Nightscout component.
async def async_setup(hass: HomeAssistant, config: dict): """Set up the Nightscout component.""" hass.data.setdefault(DOMAIN, {}) return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ")", ":", "hass", ".", "data", ".", "setdefault", "(", "DOMAIN", ",", "{", "}", ")", "return", "True" ]
[ 21, 0 ]
[ 24, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass: HomeAssistant, entry: ConfigEntry)
Set up Nightscout from a config entry.
Set up Nightscout from a config entry.
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Nightscout from a config entry.""" server_url = entry.data[CONF_URL] api_key = entry.data.get(CONF_API_KEY) session = async_get_clientsession(hass) api = NightscoutAPI(server_url, session=session, api_secret=api_key) try: status = await api.get_server_status() except (ClientError, AsyncIOTimeoutError, OSError) as error: raise ConfigEntryNotReady from error hass.data[DOMAIN][entry.entry_id] = api device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(DOMAIN, server_url)}, manufacturer="Nightscout Foundation", name=status.name, sw_version=status.version, entry_type="service", ) for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "server_url", "=", "entry", ".", "data", "[", "CONF_URL", "]", "api_key", "=", "entry", ".", "data", ".", "get", "(", "CONF_API_KEY", ")", "session", "=", "async_get_clientsession", "(", "hass", ")", "api", "=", "NightscoutAPI", "(", "server_url", ",", "session", "=", "session", ",", "api_secret", "=", "api_key", ")", "try", ":", "status", "=", "await", "api", ".", "get_server_status", "(", ")", "except", "(", "ClientError", ",", "AsyncIOTimeoutError", ",", "OSError", ")", "as", "error", ":", "raise", "ConfigEntryNotReady", "from", "error", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "=", "api", "device_registry", "=", "await", "dr", ".", "async_get_registry", "(", "hass", ")", "device_registry", ".", "async_get_or_create", "(", "config_entry_id", "=", "entry", ".", "entry_id", ",", "identifiers", "=", "{", "(", "DOMAIN", ",", "server_url", ")", "}", ",", "manufacturer", "=", "\"Nightscout Foundation\"", ",", "name", "=", "status", ".", "name", ",", "sw_version", "=", "status", ".", "version", ",", "entry_type", "=", "\"service\"", ",", ")", "for", "component", "in", "PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "component", ")", ")", "return", "True" ]
[ 27, 0 ]
[ 55, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass: HomeAssistant, entry: ConfigEntry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
[ "async", "def", "async_unload_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", "->", "bool", ":", "unload_ok", "=", "all", "(", "await", "asyncio", ".", "gather", "(", "*", "[", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "component", ")", "for", "component", "in", "PLATFORMS", "]", ")", ")", "if", "unload_ok", ":", "hass", ".", "data", "[", "DOMAIN", "]", ".", "pop", "(", "entry", ".", "entry_id", ")", "return", "unload_ok" ]
[ 58, 0 ]
[ 72, 20 ]
python
en
['en', 'es', 'en']
True
test_controlling_state_via_mqtt
(hass, mqtt_mock, setup_tasmota)
Test state update via MQTT.
Test state update via MQTT.
async def test_controlling_state_via_mqtt(hass, mqtt_mock, setup_tasmota): """Test state update via MQTT.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_dht11_temperature") assert state.state == "unavailable" assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("sensor.tasmota_dht11_temperature") assert state.state == STATE_UNKNOWN assert not state.attributes.get(ATTR_ASSUMED_STATE) # Test periodic state update async_fire_mqtt_message( hass, "tasmota_49A3BC/tele/SENSOR", '{"DHT11":{"Temperature":20.5}}' ) state = hass.states.get("sensor.tasmota_dht11_temperature") assert state.state == "20.5" # Test polled state update async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS10", '{"StatusSNS":{"DHT11":{"Temperature":20.0}}}', ) state = hass.states.get("sensor.tasmota_dht11_temperature") assert state.state == "20.0"
[ "async", "def", "test_controlling_state_via_mqtt", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_dht11_temperature\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_dht11_temperature\"", ")", "assert", "state", ".", "state", "==", "STATE_UNKNOWN", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "# Test periodic state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/SENSOR\"", ",", "'{\"DHT11\":{\"Temperature\":20.5}}'", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_dht11_temperature\"", ")", "assert", "state", ".", "state", "==", "\"20.5\"", "# Test polled state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS10\"", ",", "'{\"StatusSNS\":{\"DHT11\":{\"Temperature\":20.0}}}'", ",", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_dht11_temperature\"", ")", "assert", "state", ".", "state", "==", "\"20.0\"" ]
[ 90, 0 ]
[ 132, 32 ]
python
en
['en', 'co', 'en']
True
test_nested_sensor_state_via_mqtt
(hass, mqtt_mock, setup_tasmota)
Test state update via MQTT.
Test state update via MQTT.
async def test_nested_sensor_state_via_mqtt(hass, mqtt_mock, setup_tasmota): """Test state update via MQTT.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(NESTED_SENSOR_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_tx23_speed_act") assert state.state == "unavailable" assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("sensor.tasmota_tx23_speed_act") assert state.state == STATE_UNKNOWN assert not state.attributes.get(ATTR_ASSUMED_STATE) # Test periodic state update async_fire_mqtt_message( hass, "tasmota_49A3BC/tele/SENSOR", '{"TX23":{"Speed":{"Act":"12.3"}}}' ) state = hass.states.get("sensor.tasmota_tx23_speed_act") assert state.state == "12.3" # Test polled state update async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS10", '{"StatusSNS":{"TX23":{"Speed":{"Act":"23.4"}}}}', ) state = hass.states.get("sensor.tasmota_tx23_speed_act") assert state.state == "23.4"
[ "async", "def", "test_nested_sensor_state_via_mqtt", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "NESTED_SENSOR_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_tx23_speed_act\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_tx23_speed_act\"", ")", "assert", "state", ".", "state", "==", "STATE_UNKNOWN", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "# Test periodic state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/SENSOR\"", ",", "'{\"TX23\":{\"Speed\":{\"Act\":\"12.3\"}}}'", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_tx23_speed_act\"", ")", "assert", "state", ".", "state", "==", "\"12.3\"", "# Test polled state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS10\"", ",", "'{\"StatusSNS\":{\"TX23\":{\"Speed\":{\"Act\":\"23.4\"}}}}'", ",", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_tx23_speed_act\"", ")", "assert", "state", ".", "state", "==", "\"23.4\"" ]
[ 135, 0 ]
[ 177, 32 ]
python
en
['en', 'co', 'en']
True
test_indexed_sensor_state_via_mqtt
(hass, mqtt_mock, setup_tasmota)
Test state update via MQTT.
Test state update via MQTT.
async def test_indexed_sensor_state_via_mqtt(hass, mqtt_mock, setup_tasmota): """Test state update via MQTT.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(INDEXED_SENSOR_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_energy_totaltariff_1") assert state.state == "unavailable" assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("sensor.tasmota_energy_totaltariff_1") assert state.state == STATE_UNKNOWN assert not state.attributes.get(ATTR_ASSUMED_STATE) # Test periodic state update async_fire_mqtt_message( hass, "tasmota_49A3BC/tele/SENSOR", '{"ENERGY":{"TotalTariff":[1.2,3.4]}}' ) state = hass.states.get("sensor.tasmota_energy_totaltariff_1") assert state.state == "3.4" # Test polled state update async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS10", '{"StatusSNS":{"ENERGY":{"TotalTariff":[5.6,7.8]}}}', ) state = hass.states.get("sensor.tasmota_energy_totaltariff_1") assert state.state == "7.8"
[ "async", "def", "test_indexed_sensor_state_via_mqtt", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "INDEXED_SENSOR_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_energy_totaltariff_1\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_energy_totaltariff_1\"", ")", "assert", "state", ".", "state", "==", "STATE_UNKNOWN", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "# Test periodic state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/SENSOR\"", ",", "'{\"ENERGY\":{\"TotalTariff\":[1.2,3.4]}}'", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_energy_totaltariff_1\"", ")", "assert", "state", ".", "state", "==", "\"3.4\"", "# Test polled state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS10\"", ",", "'{\"StatusSNS\":{\"ENERGY\":{\"TotalTariff\":[5.6,7.8]}}}'", ",", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_energy_totaltariff_1\"", ")", "assert", "state", ".", "state", "==", "\"7.8\"" ]
[ 180, 0 ]
[ 222, 31 ]
python
en
['en', 'co', 'en']
True
test_status_sensor_state_via_mqtt
(hass, mqtt_mock, setup_tasmota)
Test state update via MQTT.
Test state update via MQTT.
async def test_status_sensor_state_via_mqtt(hass, mqtt_mock, setup_tasmota): """Test state update via MQTT.""" entity_reg = await hass.helpers.entity_registry.async_get_registry() # Pre-enable the status sensor entity_reg.async_get_or_create( sensor.DOMAIN, "tasmota", "00000049A3BC_status_sensor_status_sensor_status_signal", suggested_object_id="tasmota_status", disabled_by=None, ) config = copy.deepcopy(DEFAULT_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "unavailable" assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("sensor.tasmota_status") assert state.state == STATE_UNKNOWN assert not state.attributes.get(ATTR_ASSUMED_STATE) # Test pushed state update async_fire_mqtt_message( hass, "tasmota_49A3BC/tele/STATE", '{"Wifi":{"Signal":20.5}}' ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "20.5" # Test polled state update async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS11", '{"StatusSTS":{"Wifi":{"Signal":20.0}}}', ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "20.0"
[ "async", "def", "test_status_sensor_state_via_mqtt", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "entity_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "# Pre-enable the status sensor", "entity_reg", ".", "async_get_or_create", "(", "sensor", ".", "DOMAIN", ",", "\"tasmota\"", ",", "\"00000049A3BC_status_sensor_status_sensor_status_signal\"", ",", "suggested_object_id", "=", "\"tasmota_status\"", ",", "disabled_by", "=", "None", ",", ")", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "STATE_UNKNOWN", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "# Test pushed state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/STATE\"", ",", "'{\"Wifi\":{\"Signal\":20.5}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"20.5\"", "# Test polled state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS11\"", ",", "'{\"StatusSTS\":{\"Wifi\":{\"Signal\":20.0}}}'", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"20.0\"" ]
[ 226, 0 ]
[ 275, 32 ]
python
en
['en', 'co', 'en']
True
test_single_shot_status_sensor_state_via_mqtt
(hass, mqtt_mock, setup_tasmota)
Test state update via MQTT.
Test state update via MQTT.
async def test_single_shot_status_sensor_state_via_mqtt(hass, mqtt_mock, setup_tasmota): """Test state update via MQTT.""" entity_reg = await hass.helpers.entity_registry.async_get_registry() # Pre-enable the status sensor entity_reg.async_get_or_create( sensor.DOMAIN, "tasmota", "00000049A3BC_status_sensor_status_sensor_status_restart_reason", suggested_object_id="tasmota_status", disabled_by=None, ) config = copy.deepcopy(DEFAULT_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "unavailable" assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("sensor.tasmota_status") assert state.state == STATE_UNKNOWN assert not state.attributes.get(ATTR_ASSUMED_STATE) # Test polled state update async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS1", '{"StatusPRM":{"RestartReason":"Some reason"}}', ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "Some reason" # Test polled state update is ignored async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS1", '{"StatusPRM":{"RestartReason":"Another reason"}}', ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "Some reason" # Device signals online again async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "Some reason" # Test polled state update async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS1", '{"StatusPRM":{"RestartReason":"Another reason"}}', ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "Another reason" # Test polled state update is ignored async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS1", '{"StatusPRM":{"RestartReason":"Third reason"}}', ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "Another reason"
[ "async", "def", "test_single_shot_status_sensor_state_via_mqtt", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "entity_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "# Pre-enable the status sensor", "entity_reg", ".", "async_get_or_create", "(", "sensor", ".", "DOMAIN", ",", "\"tasmota\"", ",", "\"00000049A3BC_status_sensor_status_sensor_status_restart_reason\"", ",", "suggested_object_id", "=", "\"tasmota_status\"", ",", "disabled_by", "=", "None", ",", ")", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "STATE_UNKNOWN", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "# Test polled state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS1\"", ",", "'{\"StatusPRM\":{\"RestartReason\":\"Some reason\"}}'", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"Some reason\"", "# Test polled state update is ignored", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS1\"", ",", "'{\"StatusPRM\":{\"RestartReason\":\"Another reason\"}}'", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"Some reason\"", "# Device signals online again", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"Some reason\"", "# Test polled state update", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS1\"", ",", "'{\"StatusPRM\":{\"RestartReason\":\"Another reason\"}}'", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"Another reason\"", "# Test polled state update is ignored", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS1\"", ",", "'{\"StatusPRM\":{\"RestartReason\":\"Third reason\"}}'", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"Another reason\"" ]
[ 279, 0 ]
[ 356, 42 ]
python
en
['en', 'co', 'en']
True
test_restart_time_status_sensor_state_via_mqtt
( hass, mqtt_mock, setup_tasmota )
Test state update via MQTT.
Test state update via MQTT.
async def test_restart_time_status_sensor_state_via_mqtt( hass, mqtt_mock, setup_tasmota ): """Test state update via MQTT.""" entity_reg = await hass.helpers.entity_registry.async_get_registry() # Pre-enable the status sensor entity_reg.async_get_or_create( sensor.DOMAIN, "tasmota", "00000049A3BC_status_sensor_status_sensor_last_restart_time", suggested_object_id="tasmota_status", disabled_by=None, ) config = copy.deepcopy(DEFAULT_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "unavailable" assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("sensor.tasmota_status") assert state.state == STATE_UNKNOWN assert not state.attributes.get(ATTR_ASSUMED_STATE) # Test polled state update utc_now = datetime.datetime(2020, 11, 11, 8, 0, 0, tzinfo=dt.UTC) hatasmota.status_sensor.datetime.now.return_value = utc_now async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/STATUS11", '{"StatusSTS":{"UptimeSec":"3600"}}', ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_status") assert state.state == "2020-11-11T07:00:00+00:00"
[ "async", "def", "test_restart_time_status_sensor_state_via_mqtt", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "entity_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "# Pre-enable the status sensor", "entity_reg", ".", "async_get_or_create", "(", "sensor", ".", "DOMAIN", ",", "\"tasmota\"", ",", "\"00000049A3BC_status_sensor_status_sensor_last_restart_time\"", ",", "suggested_object_id", "=", "\"tasmota_status\"", ",", "disabled_by", "=", "None", ",", ")", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "STATE_UNKNOWN", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "# Test polled state update", "utc_now", "=", "datetime", ".", "datetime", "(", "2020", ",", "11", ",", "11", ",", "8", ",", "0", ",", "0", ",", "tzinfo", "=", "dt", ".", "UTC", ")", "hatasmota", ".", "status_sensor", ".", "datetime", ".", "now", ".", "return_value", "=", "utc_now", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/STATUS11\"", ",", "'{\"StatusSTS\":{\"UptimeSec\":\"3600\"}}'", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_status\"", ")", "assert", "state", ".", "state", "==", "\"2020-11-11T07:00:00+00:00\"" ]
[ 361, 0 ]
[ 406, 53 ]
python
en
['en', 'co', 'en']
True
test_attributes
(hass, mqtt_mock, setup_tasmota)
Test correct attributes for sensors.
Test correct attributes for sensors.
async def test_attributes(hass, mqtt_mock, setup_tasmota): """Test correct attributes for sensors.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = { "sn": { "DHT11": {"Temperature": None}, "Beer": {"CarbonDioxide": None}, "TempUnit": "C", } } mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_dht11_temperature") assert state.attributes.get("device_class") == "temperature" assert state.attributes.get("friendly_name") == "Tasmota DHT11 Temperature" assert state.attributes.get("icon") is None assert state.attributes.get("unit_of_measurement") == "°C" state = hass.states.get("sensor.tasmota_beer_CarbonDioxide") assert state.attributes.get("device_class") is None assert state.attributes.get("friendly_name") == "Tasmota Beer CarbonDioxide" assert state.attributes.get("icon") == "mdi:molecule-co2" assert state.attributes.get("unit_of_measurement") == "ppm"
[ "async", "def", "test_attributes", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "{", "\"sn\"", ":", "{", "\"DHT11\"", ":", "{", "\"Temperature\"", ":", "None", "}", ",", "\"Beer\"", ":", "{", "\"CarbonDioxide\"", ":", "None", "}", ",", "\"TempUnit\"", ":", "\"C\"", ",", "}", "}", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_dht11_temperature\"", ")", "assert", "state", ".", "attributes", ".", "get", "(", "\"device_class\"", ")", "==", "\"temperature\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"friendly_name\"", ")", "==", "\"Tasmota DHT11 Temperature\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"icon\"", ")", "is", "None", "assert", "state", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "\"°C\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_beer_CarbonDioxide\"", ")", "assert", "state", ".", "attributes", ".", "get", "(", "\"device_class\"", ")", "is", "None", "assert", "state", ".", "attributes", ".", "get", "(", "\"friendly_name\"", ")", "==", "\"Tasmota Beer CarbonDioxide\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"icon\"", ")", "==", "\"mdi:molecule-co2\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "\"ppm\"" ]
[ 409, 0 ]
[ 444, 63 ]
python
en
['en', 'en', 'en']
True
test_nested_sensor_attributes
(hass, mqtt_mock, setup_tasmota)
Test correct attributes for sensors.
Test correct attributes for sensors.
async def test_nested_sensor_attributes(hass, mqtt_mock, setup_tasmota): """Test correct attributes for sensors.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(NESTED_SENSOR_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_tx23_speed_act") assert state.attributes.get("device_class") is None assert state.attributes.get("friendly_name") == "Tasmota TX23 Speed Act" assert state.attributes.get("icon") is None assert state.attributes.get("unit_of_measurement") == "km/h" state = hass.states.get("sensor.tasmota_tx23_dir_avg") assert state.attributes.get("device_class") is None assert state.attributes.get("friendly_name") == "Tasmota TX23 Dir Avg" assert state.attributes.get("icon") is None assert state.attributes.get("unit_of_measurement") == " "
[ "async", "def", "test_nested_sensor_attributes", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "NESTED_SENSOR_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_tx23_speed_act\"", ")", "assert", "state", ".", "attributes", ".", "get", "(", "\"device_class\"", ")", "is", "None", "assert", "state", ".", "attributes", ".", "get", "(", "\"friendly_name\"", ")", "==", "\"Tasmota TX23 Speed Act\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"icon\"", ")", "is", "None", "assert", "state", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "\"km/h\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_tx23_dir_avg\"", ")", "assert", "state", ".", "attributes", ".", "get", "(", "\"device_class\"", ")", "is", "None", "assert", "state", ".", "attributes", ".", "get", "(", "\"friendly_name\"", ")", "==", "\"Tasmota TX23 Dir Avg\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"icon\"", ")", "is", "None", "assert", "state", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "\" \"" ]
[ 447, 0 ]
[ 476, 61 ]
python
en
['en', 'en', 'en']
True
test_indexed_sensor_attributes
(hass, mqtt_mock, setup_tasmota)
Test correct attributes for sensors.
Test correct attributes for sensors.
async def test_indexed_sensor_attributes(hass, mqtt_mock, setup_tasmota): """Test correct attributes for sensors.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = { "sn": { "Dummy1": {"Temperature": [None, None]}, "Dummy2": {"CarbonDioxide": [None, None]}, "TempUnit": "C", } } mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_dummy1_temperature_0") assert state.attributes.get("device_class") == "temperature" assert state.attributes.get("friendly_name") == "Tasmota Dummy1 Temperature 0" assert state.attributes.get("icon") is None assert state.attributes.get("unit_of_measurement") == "°C" state = hass.states.get("sensor.tasmota_dummy2_carbondioxide_1") assert state.attributes.get("device_class") is None assert state.attributes.get("friendly_name") == "Tasmota Dummy2 CarbonDioxide 1" assert state.attributes.get("icon") == "mdi:molecule-co2" assert state.attributes.get("unit_of_measurement") == "ppm"
[ "async", "def", "test_indexed_sensor_attributes", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "{", "\"sn\"", ":", "{", "\"Dummy1\"", ":", "{", "\"Temperature\"", ":", "[", "None", ",", "None", "]", "}", ",", "\"Dummy2\"", ":", "{", "\"CarbonDioxide\"", ":", "[", "None", ",", "None", "]", "}", ",", "\"TempUnit\"", ":", "\"C\"", ",", "}", "}", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_dummy1_temperature_0\"", ")", "assert", "state", ".", "attributes", ".", "get", "(", "\"device_class\"", ")", "==", "\"temperature\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"friendly_name\"", ")", "==", "\"Tasmota Dummy1 Temperature 0\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"icon\"", ")", "is", "None", "assert", "state", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "\"°C\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_dummy2_carbondioxide_1\"", ")", "assert", "state", ".", "attributes", ".", "get", "(", "\"device_class\"", ")", "is", "None", "assert", "state", ".", "attributes", ".", "get", "(", "\"friendly_name\"", ")", "==", "\"Tasmota Dummy2 CarbonDioxide 1\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"icon\"", ")", "==", "\"mdi:molecule-co2\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "\"ppm\"" ]
[ 479, 0 ]
[ 514, 63 ]
python
en
['en', 'en', 'en']
True
test_enable_status_sensor
(hass, mqtt_mock, setup_tasmota)
Test enabling status sensor.
Test enabling status sensor.
async def test_enable_status_sensor(hass, mqtt_mock, setup_tasmota): """Test enabling status sensor.""" entity_reg = await hass.helpers.entity_registry.async_get_registry() config = copy.deepcopy(DEFAULT_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_signal") assert state is None entry = entity_reg.async_get("sensor.tasmota_signal") assert entry.disabled assert entry.disabled_by == "integration" # Enable the status sensor updated_entry = entity_reg.async_update_entity( "sensor.tasmota_signal", disabled_by=None ) assert updated_entry != entry assert updated_entry.disabled is False await hass.async_block_till_done() async_fire_time_changed( hass, dt.utcnow() + timedelta(seconds=config_entries.RELOAD_AFTER_UPDATE_DELAY + 1), ) await hass.async_block_till_done() # Fake re-send of retained discovery message async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_signal") assert state.state == "unavailable" assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("sensor.tasmota_signal") assert state.state == STATE_UNKNOWN assert not state.attributes.get(ATTR_ASSUMED_STATE)
[ "async", "def", "test_enable_status_sensor", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "entity_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_signal\"", ")", "assert", "state", "is", "None", "entry", "=", "entity_reg", ".", "async_get", "(", "\"sensor.tasmota_signal\"", ")", "assert", "entry", ".", "disabled", "assert", "entry", ".", "disabled_by", "==", "\"integration\"", "# Enable the status sensor", "updated_entry", "=", "entity_reg", ".", "async_update_entity", "(", "\"sensor.tasmota_signal\"", ",", "disabled_by", "=", "None", ")", "assert", "updated_entry", "!=", "entry", "assert", "updated_entry", ".", "disabled", "is", "False", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_time_changed", "(", "hass", ",", "dt", ".", "utcnow", "(", ")", "+", "timedelta", "(", "seconds", "=", "config_entries", ".", "RELOAD_AFTER_UPDATE_DELAY", "+", "1", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Fake re-send of retained discovery message", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_signal\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.tasmota_signal\"", ")", "assert", "state", ".", "state", "==", "STATE_UNKNOWN", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")" ]
[ 518, 0 ]
[ 568, 55 ]
python
en
['fr', 'jv', 'en']
False
test_availability_when_connection_lost
( hass, mqtt_client_mock, mqtt_mock, setup_tasmota )
Test availability after MQTT disconnection.
Test availability after MQTT disconnection.
async def test_availability_when_connection_lost( hass, mqtt_client_mock, mqtt_mock, setup_tasmota ): """Test availability after MQTT disconnection.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) await help_test_availability_when_connection_lost( hass, mqtt_client_mock, mqtt_mock, sensor.DOMAIN, config, sensor_config, "tasmota_dht11_temperature", )
[ "async", "def", "test_availability_when_connection_lost", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "await", "help_test_availability_when_connection_lost", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "sensor", ".", "DOMAIN", ",", "config", ",", "sensor_config", ",", "\"tasmota_dht11_temperature\"", ",", ")" ]
[ 571, 0 ]
[ 585, 5 ]
python
en
['en', 'en', 'en']
True
test_availability
(hass, mqtt_mock, setup_tasmota)
Test availability.
Test availability.
async def test_availability(hass, mqtt_mock, setup_tasmota): """Test availability.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) await help_test_availability( hass, mqtt_mock, sensor.DOMAIN, config, sensor_config, "tasmota_dht11_temperature", )
[ "async", "def", "test_availability", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "await", "help_test_availability", "(", "hass", ",", "mqtt_mock", ",", "sensor", ".", "DOMAIN", ",", "config", ",", "sensor_config", ",", "\"tasmota_dht11_temperature\"", ",", ")" ]
[ 588, 0 ]
[ 599, 5 ]
python
en
['fr', 'ga', 'en']
False
test_availability_discovery_update
(hass, mqtt_mock, setup_tasmota)
Test availability discovery update.
Test availability discovery update.
async def test_availability_discovery_update(hass, mqtt_mock, setup_tasmota): """Test availability discovery update.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) await help_test_availability_discovery_update( hass, mqtt_mock, sensor.DOMAIN, config, sensor_config, "tasmota_dht11_temperature", )
[ "async", "def", "test_availability_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "await", "help_test_availability_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "sensor", ".", "DOMAIN", ",", "config", ",", "sensor_config", ",", "\"tasmota_dht11_temperature\"", ",", ")" ]
[ 602, 0 ]
[ 613, 5 ]
python
en
['en', 'en', 'en']
True
test_availability_poll_state
( hass, mqtt_client_mock, mqtt_mock, setup_tasmota )
Test polling after MQTT connection (re)established.
Test polling after MQTT connection (re)established.
async def test_availability_poll_state( hass, mqtt_client_mock, mqtt_mock, setup_tasmota ): """Test polling after MQTT connection (re)established.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) poll_topic = "tasmota_49A3BC/cmnd/STATUS" await help_test_availability_poll_state( hass, mqtt_client_mock, mqtt_mock, sensor.DOMAIN, config, poll_topic, "10", sensor_config, )
[ "async", "def", "test_availability_poll_state", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "poll_topic", "=", "\"tasmota_49A3BC/cmnd/STATUS\"", "await", "help_test_availability_poll_state", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "sensor", ".", "DOMAIN", ",", "config", ",", "poll_topic", ",", "\"10\"", ",", "sensor_config", ",", ")" ]
[ 616, 0 ]
[ 632, 5 ]
python
da
['da', 'da', 'en']
True
test_discovery_removal_sensor
(hass, mqtt_mock, caplog, setup_tasmota)
Test removal of discovered sensor.
Test removal of discovered sensor.
async def test_discovery_removal_sensor(hass, mqtt_mock, caplog, setup_tasmota): """Test removal of discovered sensor.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config1 = copy.deepcopy(DEFAULT_SENSOR_CONFIG) await help_test_discovery_removal( hass, mqtt_mock, caplog, sensor.DOMAIN, config, config, sensor_config1, {}, "tasmota_dht11_temperature", "Tasmota DHT11 Temperature", )
[ "async", "def", "test_discovery_removal_sensor", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "await", "help_test_discovery_removal", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "sensor", ".", "DOMAIN", ",", "config", ",", "config", ",", "sensor_config1", ",", "{", "}", ",", "\"tasmota_dht11_temperature\"", ",", "\"Tasmota DHT11 Temperature\"", ",", ")" ]
[ 635, 0 ]
[ 651, 5 ]
python
en
['en', 'en', 'en']
True
test_discovery_update_unchanged_sensor
( hass, mqtt_mock, caplog, setup_tasmota )
Test update of discovered sensor.
Test update of discovered sensor.
async def test_discovery_update_unchanged_sensor( hass, mqtt_mock, caplog, setup_tasmota ): """Test update of discovered sensor.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) with patch( "homeassistant.components.tasmota.sensor.TasmotaSensor.discovery_update" ) as discovery_update: await help_test_discovery_update_unchanged( hass, mqtt_mock, caplog, sensor.DOMAIN, config, discovery_update, sensor_config, "tasmota_dht11_temperature", "Tasmota DHT11 Temperature", )
[ "async", "def", "test_discovery_update_unchanged_sensor", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "with", "patch", "(", "\"homeassistant.components.tasmota.sensor.TasmotaSensor.discovery_update\"", ")", "as", "discovery_update", ":", "await", "help_test_discovery_update_unchanged", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "sensor", ".", "DOMAIN", ",", "config", ",", "discovery_update", ",", "sensor_config", ",", "\"tasmota_dht11_temperature\"", ",", "\"Tasmota DHT11 Temperature\"", ",", ")" ]
[ 654, 0 ]
[ 673, 9 ]
python
en
['en', 'da', 'en']
True
test_discovery_device_remove
(hass, mqtt_mock, setup_tasmota)
Test device registry remove.
Test device registry remove.
async def test_discovery_device_remove(hass, mqtt_mock, setup_tasmota): """Test device registry remove.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) unique_id = f"{DEFAULT_CONFIG['mac']}_sensor_sensor_DHT11_Temperature" await help_test_discovery_device_remove( hass, mqtt_mock, sensor.DOMAIN, unique_id, config, sensor_config )
[ "async", "def", "test_discovery_device_remove", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "unique_id", "=", "f\"{DEFAULT_CONFIG['mac']}_sensor_sensor_DHT11_Temperature\"", "await", "help_test_discovery_device_remove", "(", "hass", ",", "mqtt_mock", ",", "sensor", ".", "DOMAIN", ",", "unique_id", ",", "config", ",", "sensor_config", ")" ]
[ 676, 0 ]
[ 683, 5 ]
python
en
['fr', 'en', 'en']
True
test_entity_id_update_subscriptions
(hass, mqtt_mock, setup_tasmota)
Test MQTT subscriptions are managed when entity_id is updated.
Test MQTT subscriptions are managed when entity_id is updated.
async def test_entity_id_update_subscriptions(hass, mqtt_mock, setup_tasmota): """Test MQTT subscriptions are managed when entity_id is updated.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) topics = [ get_topic_tele_sensor(config), get_topic_stat_status(config, 10), get_topic_tele_will(config), ] await help_test_entity_id_update_subscriptions( hass, mqtt_mock, sensor.DOMAIN, config, topics, sensor_config, "tasmota_dht11_temperature", )
[ "async", "def", "test_entity_id_update_subscriptions", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "topics", "=", "[", "get_topic_tele_sensor", "(", "config", ")", ",", "get_topic_stat_status", "(", "config", ",", "10", ")", ",", "get_topic_tele_will", "(", "config", ")", ",", "]", "await", "help_test_entity_id_update_subscriptions", "(", "hass", ",", "mqtt_mock", ",", "sensor", ".", "DOMAIN", ",", "config", ",", "topics", ",", "sensor_config", ",", "\"tasmota_dht11_temperature\"", ",", ")" ]
[ 686, 0 ]
[ 703, 5 ]
python
en
['en', 'en', 'en']
True
test_entity_id_update_discovery_update
(hass, mqtt_mock, setup_tasmota)
Test MQTT discovery update when entity_id is updated.
Test MQTT discovery update when entity_id is updated.
async def test_entity_id_update_discovery_update(hass, mqtt_mock, setup_tasmota): """Test MQTT discovery update when entity_id is updated.""" config = copy.deepcopy(DEFAULT_CONFIG) sensor_config = copy.deepcopy(DEFAULT_SENSOR_CONFIG) await help_test_entity_id_update_discovery_update( hass, mqtt_mock, sensor.DOMAIN, config, sensor_config, "tasmota_dht11_temperature", )
[ "async", "def", "test_entity_id_update_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "sensor_config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_SENSOR_CONFIG", ")", "await", "help_test_entity_id_update_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "sensor", ".", "DOMAIN", ",", "config", ",", "sensor_config", ",", "\"tasmota_dht11_temperature\"", ",", ")" ]
[ 706, 0 ]
[ 717, 5 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Smappee binary sensor.
Set up the Smappee binary sensor.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Smappee binary sensor.""" smappee_base = hass.data[DOMAIN][config_entry.entry_id] entities = [] for service_location in smappee_base.smappee.service_locations.values(): for appliance_id, appliance in service_location.appliances.items(): if appliance.type != "Find me" and appliance.source_type == "NILM": entities.append( SmappeeAppliance( smappee_base=smappee_base, service_location=service_location, appliance_id=appliance_id, appliance_name=appliance.name, appliance_type=appliance.type, ) ) if not smappee_base.smappee.local_polling: # presence value only available in cloud env entities.append(SmappeePresence(smappee_base, service_location)) async_add_entities(entities, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "smappee_base", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "entities", "=", "[", "]", "for", "service_location", "in", "smappee_base", ".", "smappee", ".", "service_locations", ".", "values", "(", ")", ":", "for", "appliance_id", ",", "appliance", "in", "service_location", ".", "appliances", ".", "items", "(", ")", ":", "if", "appliance", ".", "type", "!=", "\"Find me\"", "and", "appliance", ".", "source_type", "==", "\"NILM\"", ":", "entities", ".", "append", "(", "SmappeeAppliance", "(", "smappee_base", "=", "smappee_base", ",", "service_location", "=", "service_location", ",", "appliance_id", "=", "appliance_id", ",", "appliance_name", "=", "appliance", ".", "name", ",", "appliance_type", "=", "appliance", ".", "type", ",", ")", ")", "if", "not", "smappee_base", ".", "smappee", ".", "local_polling", ":", "# presence value only available in cloud env", "entities", ".", "append", "(", "SmappeePresence", "(", "smappee_base", ",", "service_location", ")", ")", "async_add_entities", "(", "entities", ",", "True", ")" ]
[ 12, 0 ]
[ 34, 38 ]
python
en
['en', 'haw', 'en']
True
SmappeePresence.__init__
(self, smappee_base, service_location)
Initialize the Smappee sensor.
Initialize the Smappee sensor.
def __init__(self, smappee_base, service_location): """Initialize the Smappee sensor.""" self._smappee_base = smappee_base self._service_location = service_location self._state = self._service_location.is_present
[ "def", "__init__", "(", "self", ",", "smappee_base", ",", "service_location", ")", ":", "self", ".", "_smappee_base", "=", "smappee_base", "self", ".", "_service_location", "=", "service_location", "self", ".", "_state", "=", "self", ".", "_service_location", ".", "is_present" ]
[ 40, 4 ]
[ 44, 55 ]
python
en
['en', 'en', 'en']
True
SmappeePresence.name
(self)
Return the name of the binary sensor.
Return the name of the binary sensor.
def name(self): """Return the name of the binary sensor.""" return f"{self._service_location.service_location_name} - {PRESENCE_PREFIX}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self._service_location.service_location_name} - {PRESENCE_PREFIX}\"" ]
[ 47, 4 ]
[ 49, 84 ]
python
en
['en', 'mi', 'en']
True
SmappeePresence.is_on
(self)
Return if the binary sensor is turned on.
Return if the binary sensor is turned on.
def is_on(self): """Return if the binary sensor is turned on.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 52, 4 ]
[ 54, 26 ]
python
en
['en', 'et', 'en']
True
SmappeePresence.device_class
(self)
Return the class of this device, from component DEVICE_CLASSES.
Return the class of this device, from component DEVICE_CLASSES.
def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_PRESENCE
[ "def", "device_class", "(", "self", ")", ":", "return", "DEVICE_CLASS_PRESENCE" ]
[ 57, 4 ]
[ 59, 36 ]
python
en
['en', 'en', 'en']
True
SmappeePresence.unique_id
( self, )
Return the unique ID for this binary sensor.
Return the unique ID for this binary sensor.
def unique_id( self, ): """Return the unique ID for this binary sensor.""" return ( f"{self._service_location.device_serial_number}-" f"{self._service_location.service_location_id}-" f"{DEVICE_CLASS_PRESENCE}" )
[ "def", "unique_id", "(", "self", ",", ")", ":", "return", "(", "f\"{self._service_location.device_serial_number}-\"", "f\"{self._service_location.service_location_id}-\"", "f\"{DEVICE_CLASS_PRESENCE}\"", ")" ]
[ 62, 4 ]
[ 70, 9 ]
python
en
['en', 'en', 'en']
True
SmappeePresence.device_info
(self)
Return the device info for this binary sensor.
Return the device info for this binary sensor.
def device_info(self): """Return the device info for this binary sensor.""" return { "identifiers": {(DOMAIN, self._service_location.device_serial_number)}, "name": self._service_location.service_location_name, "manufacturer": "Smappee", "model": self._service_location.device_model, "sw_version": self._service_location.firmware_version, }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "_service_location", ".", "device_serial_number", ")", "}", ",", "\"name\"", ":", "self", ".", "_service_location", ".", "service_location_name", ",", "\"manufacturer\"", ":", "\"Smappee\"", ",", "\"model\"", ":", "self", ".", "_service_location", ".", "device_model", ",", "\"sw_version\"", ":", "self", ".", "_service_location", ".", "firmware_version", ",", "}" ]
[ 73, 4 ]
[ 81, 9 ]
python
en
['en', 'en', 'en']
True
SmappeePresence.async_update
(self)
Get the latest data from Smappee and update the state.
Get the latest data from Smappee and update the state.
async def async_update(self): """Get the latest data from Smappee and update the state.""" await self._smappee_base.async_update() self._state = self._service_location.is_present
[ "async", "def", "async_update", "(", "self", ")", ":", "await", "self", ".", "_smappee_base", ".", "async_update", "(", ")", "self", ".", "_state", "=", "self", ".", "_service_location", ".", "is_present" ]
[ 83, 4 ]
[ 87, 55 ]
python
en
['en', 'en', 'en']
True
SmappeeAppliance.__init__
( self, smappee_base, service_location, appliance_id, appliance_name, appliance_type, )
Initialize the Smappee sensor.
Initialize the Smappee sensor.
def __init__( self, smappee_base, service_location, appliance_id, appliance_name, appliance_type, ): """Initialize the Smappee sensor.""" self._smappee_base = smappee_base self._service_location = service_location self._appliance_id = appliance_id self._appliance_name = appliance_name self._appliance_type = appliance_type self._state = False
[ "def", "__init__", "(", "self", ",", "smappee_base", ",", "service_location", ",", "appliance_id", ",", "appliance_name", ",", "appliance_type", ",", ")", ":", "self", ".", "_smappee_base", "=", "smappee_base", "self", ".", "_service_location", "=", "service_location", "self", ".", "_appliance_id", "=", "appliance_id", "self", ".", "_appliance_name", "=", "appliance_name", "self", ".", "_appliance_type", "=", "appliance_type", "self", ".", "_state", "=", "False" ]
[ 93, 4 ]
[ 107, 27 ]
python
en
['en', 'en', 'en']
True
SmappeeAppliance.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return ( f"{self._service_location.service_location_name} - " f"{BINARY_SENSOR_PREFIX} - " f"{self._appliance_name if self._appliance_name != '' else self._appliance_type}" )
[ "def", "name", "(", "self", ")", ":", "return", "(", "f\"{self._service_location.service_location_name} - \"", "f\"{BINARY_SENSOR_PREFIX} - \"", "f\"{self._appliance_name if self._appliance_name != '' else self._appliance_type}\"", ")" ]
[ 110, 4 ]
[ 116, 9 ]
python
en
['en', 'mi', 'en']
True
SmappeeAppliance.is_on
(self)
Return if the binary sensor is turned on.
Return if the binary sensor is turned on.
def is_on(self): """Return if the binary sensor is turned on.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 119, 4 ]
[ 121, 26 ]
python
en
['en', 'et', 'en']
True
SmappeeAppliance.icon
(self)
Icon to use in the frontend.
Icon to use in the frontend.
def icon(self): """Icon to use in the frontend.""" icon_mapping = { "Car Charger": "mdi:car", "Coffeemaker": "mdi:coffee", "Clothes Dryer": "mdi:tumble-dryer", "Clothes Iron": "mdi:hanger", "Dishwasher": "mdi:dishwasher", "Lights": "mdi:lightbulb", "Fan": "mdi:fan", "Freezer": "mdi:fridge", "Microwave": "mdi:microwave", "Oven": "mdi:stove", "Refrigerator": "mdi:fridge", "Stove": "mdi:stove", "Washing Machine": "mdi:washing-machine", "Water Pump": "mdi:water-pump", } return icon_mapping.get(self._appliance_type)
[ "def", "icon", "(", "self", ")", ":", "icon_mapping", "=", "{", "\"Car Charger\"", ":", "\"mdi:car\"", ",", "\"Coffeemaker\"", ":", "\"mdi:coffee\"", ",", "\"Clothes Dryer\"", ":", "\"mdi:tumble-dryer\"", ",", "\"Clothes Iron\"", ":", "\"mdi:hanger\"", ",", "\"Dishwasher\"", ":", "\"mdi:dishwasher\"", ",", "\"Lights\"", ":", "\"mdi:lightbulb\"", ",", "\"Fan\"", ":", "\"mdi:fan\"", ",", "\"Freezer\"", ":", "\"mdi:fridge\"", ",", "\"Microwave\"", ":", "\"mdi:microwave\"", ",", "\"Oven\"", ":", "\"mdi:stove\"", ",", "\"Refrigerator\"", ":", "\"mdi:fridge\"", ",", "\"Stove\"", ":", "\"mdi:stove\"", ",", "\"Washing Machine\"", ":", "\"mdi:washing-machine\"", ",", "\"Water Pump\"", ":", "\"mdi:water-pump\"", ",", "}", "return", "icon_mapping", ".", "get", "(", "self", ".", "_appliance_type", ")" ]
[ 124, 4 ]
[ 142, 53 ]
python
en
['en', 'en', 'en']
True
SmappeeAppliance.unique_id
( self, )
Return the unique ID for this binary sensor.
Return the unique ID for this binary sensor.
def unique_id( self, ): """Return the unique ID for this binary sensor.""" return ( f"{self._service_location.device_serial_number}-" f"{self._service_location.service_location_id}-" f"appliance-{self._appliance_id}" )
[ "def", "unique_id", "(", "self", ",", ")", ":", "return", "(", "f\"{self._service_location.device_serial_number}-\"", "f\"{self._service_location.service_location_id}-\"", "f\"appliance-{self._appliance_id}\"", ")" ]
[ 145, 4 ]
[ 153, 9 ]
python
en
['en', 'en', 'en']
True
SmappeeAppliance.device_info
(self)
Return the device info for this binary sensor.
Return the device info for this binary sensor.
def device_info(self): """Return the device info for this binary sensor.""" return { "identifiers": {(DOMAIN, self._service_location.device_serial_number)}, "name": self._service_location.service_location_name, "manufacturer": "Smappee", "model": self._service_location.device_model, "sw_version": self._service_location.firmware_version, }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "_service_location", ".", "device_serial_number", ")", "}", ",", "\"name\"", ":", "self", ".", "_service_location", ".", "service_location_name", ",", "\"manufacturer\"", ":", "\"Smappee\"", ",", "\"model\"", ":", "self", ".", "_service_location", ".", "device_model", ",", "\"sw_version\"", ":", "self", ".", "_service_location", ".", "firmware_version", ",", "}" ]
[ 156, 4 ]
[ 164, 9 ]
python
en
['en', 'en', 'en']
True
SmappeeAppliance.async_update
(self)
Get the latest data from Smappee and update the state.
Get the latest data from Smappee and update the state.
async def async_update(self): """Get the latest data from Smappee and update the state.""" await self._smappee_base.async_update() appliance = self._service_location.appliances.get(self._appliance_id) self._state = bool(appliance.state)
[ "async", "def", "async_update", "(", "self", ")", ":", "await", "self", ".", "_smappee_base", ".", "async_update", "(", ")", "appliance", "=", "self", ".", "_service_location", ".", "appliances", ".", "get", "(", "self", ".", "_appliance_id", ")", "self", ".", "_state", "=", "bool", "(", "appliance", ".", "state", ")" ]
[ 166, 4 ]
[ 171, 43 ]
python
en
['en', 'en', 'en']
True
OpenAIAdam.step
(self, closure=None)
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
Performs a single optimization step.
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] beta1, beta2 = group['b1'], group['b2'] state['step'] += 1 # Add grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and second moment running average coefficient exp_avg.mul_(beta1).add_(1 - beta1, grad) exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) denom = exp_avg_sq.sqrt().add_(group['e']) bias_correction1 = 1 - beta1 ** state['step'] bias_correction2 = 1 - beta2 ** state['step'] if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 p.data.addcdiv_(-step_size, exp_avg, denom) # Add weight decay at the end (fixed version) if (len(p.size()) > 1 or group['vector_l2']) and group['weight_decay'] > 0: p.data.add_(-lr_scheduled * group['weight_decay'], p.data) return loss
[ "def", "step", "(", "self", ",", "closure", "=", "None", ")", ":", "loss", "=", "None", "if", "closure", "is", "not", "None", ":", "loss", "=", "closure", "(", ")", "for", "group", "in", "self", ".", "param_groups", ":", "for", "p", "in", "group", "[", "'params'", "]", ":", "if", "p", ".", "grad", "is", "None", ":", "continue", "grad", "=", "p", ".", "grad", ".", "data", "if", "grad", ".", "is_sparse", ":", "raise", "RuntimeError", "(", "'Adam does not support sparse gradients, please consider SparseAdam instead'", ")", "state", "=", "self", ".", "state", "[", "p", "]", "# State initialization", "if", "len", "(", "state", ")", "==", "0", ":", "state", "[", "'step'", "]", "=", "0", "# Exponential moving average of gradient values", "state", "[", "'exp_avg'", "]", "=", "torch", ".", "zeros_like", "(", "p", ".", "data", ")", "# Exponential moving average of squared gradient values", "state", "[", "'exp_avg_sq'", "]", "=", "torch", ".", "zeros_like", "(", "p", ".", "data", ")", "exp_avg", ",", "exp_avg_sq", "=", "state", "[", "'exp_avg'", "]", ",", "state", "[", "'exp_avg_sq'", "]", "beta1", ",", "beta2", "=", "group", "[", "'b1'", "]", ",", "group", "[", "'b2'", "]", "state", "[", "'step'", "]", "+=", "1", "# Add grad clipping", "if", "group", "[", "'max_grad_norm'", "]", ">", "0", ":", "clip_grad_norm_", "(", "p", ",", "group", "[", "'max_grad_norm'", "]", ")", "# Decay the first and second moment running average coefficient", "exp_avg", ".", "mul_", "(", "beta1", ")", ".", "add_", "(", "1", "-", "beta1", ",", "grad", ")", "exp_avg_sq", ".", "mul_", "(", "beta2", ")", ".", "addcmul_", "(", "1", "-", "beta2", ",", "grad", ",", "grad", ")", "denom", "=", "exp_avg_sq", ".", "sqrt", "(", ")", ".", "add_", "(", "group", "[", "'e'", "]", ")", "bias_correction1", "=", "1", "-", "beta1", "**", "state", "[", "'step'", "]", "bias_correction2", "=", "1", "-", "beta2", "**", "state", "[", "'step'", "]", "if", "group", "[", "'t_total'", "]", "!=", "-", "1", ":", "schedule_fct", "=", "SCHEDULES", "[", "group", "[", "'schedule'", "]", "]", "lr_scheduled", "=", "group", "[", "'lr'", "]", "*", "schedule_fct", "(", "state", "[", "'step'", "]", "/", "group", "[", "'t_total'", "]", ",", "group", "[", "'warmup'", "]", ")", "else", ":", "lr_scheduled", "=", "group", "[", "'lr'", "]", "step_size", "=", "lr_scheduled", "*", "math", ".", "sqrt", "(", "bias_correction2", ")", "/", "bias_correction1", "p", ".", "data", ".", "addcdiv_", "(", "-", "step_size", ",", "exp_avg", ",", "denom", ")", "# Add weight decay at the end (fixed version)", "if", "(", "len", "(", "p", ".", "size", "(", ")", ")", ">", "1", "or", "group", "[", "'vector_l2'", "]", ")", "and", "group", "[", "'weight_decay'", "]", ">", "0", ":", "p", ".", "data", ".", "add_", "(", "-", "lr_scheduled", "*", "group", "[", "'weight_decay'", "]", ",", "p", ".", "data", ")", "return", "loss" ]
[ 79, 4 ]
[ 139, 19 ]
python
en
['en', 'en', 'en']
True
main
()
you can change this to DoReFaQuantizer to implement it DoReFaQuantizer(configure_list).compress(model)
you can change this to DoReFaQuantizer to implement it DoReFaQuantizer(configure_list).compress(model)
def main(): torch.manual_seed(0) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) train_loader = torch.utils.data.DataLoader( datasets.MNIST('data', train=True, download=True, transform=trans), batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader( datasets.MNIST('data', train=False, transform=trans), batch_size=1000, shuffle=True) model = NaiveModel() '''you can change this to DoReFaQuantizer to implement it DoReFaQuantizer(configure_list).compress(model) ''' configure_list = [{ 'quant_types': ['weight'], 'quant_bits': { 'weight': 8, }, # you can just use `int` here because all `quan_types` share same bits length, see config for `ReLu6` below. 'op_types':['Conv2d', 'Linear'] }, { 'quant_types': ['output'], 'quant_bits': 8, 'quant_start_step': 1000, 'op_types':['ReLU6'] }] optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.5) quantizer = QAT_Quantizer(model, configure_list, optimizer) quantizer.compress() model.to(device) for epoch in range(40): print('# Epoch {} #'.format(epoch)) train(model, quantizer, device, train_loader, optimizer) test(model, device, test_loader) model_path = "mnist_model.pth" calibration_path = "mnist_calibration.pth" onnx_path = "mnist_model.onnx" input_shape = (1, 1, 28, 28) device = torch.device("cuda") calibration_config = quantizer.export_model(model_path, calibration_path, onnx_path, input_shape, device) print("Generated calibration config is: ", calibration_config)
[ "def", "main", "(", ")", ":", "torch", ".", "manual_seed", "(", "0", ")", "device", "=", "torch", ".", "device", "(", "\"cuda\"", "if", "torch", ".", "cuda", ".", "is_available", "(", ")", "else", "\"cpu\"", ")", "trans", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "(", "0.1307", ",", ")", ",", "(", "0.3081", ",", ")", ")", "]", ")", "train_loader", "=", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "datasets", ".", "MNIST", "(", "'data'", ",", "train", "=", "True", ",", "download", "=", "True", ",", "transform", "=", "trans", ")", ",", "batch_size", "=", "64", ",", "shuffle", "=", "True", ")", "test_loader", "=", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "datasets", ".", "MNIST", "(", "'data'", ",", "train", "=", "False", ",", "transform", "=", "trans", ")", ",", "batch_size", "=", "1000", ",", "shuffle", "=", "True", ")", "model", "=", "NaiveModel", "(", ")", "configure_list", "=", "[", "{", "'quant_types'", ":", "[", "'weight'", "]", ",", "'quant_bits'", ":", "{", "'weight'", ":", "8", ",", "}", ",", "# you can just use `int` here because all `quan_types` share same bits length, see config for `ReLu6` below.", "'op_types'", ":", "[", "'Conv2d'", ",", "'Linear'", "]", "}", ",", "{", "'quant_types'", ":", "[", "'output'", "]", ",", "'quant_bits'", ":", "8", ",", "'quant_start_step'", ":", "1000", ",", "'op_types'", ":", "[", "'ReLU6'", "]", "}", "]", "optimizer", "=", "torch", ".", "optim", ".", "SGD", "(", "model", ".", "parameters", "(", ")", ",", "lr", "=", "0.01", ",", "momentum", "=", "0.5", ")", "quantizer", "=", "QAT_Quantizer", "(", "model", ",", "configure_list", ",", "optimizer", ")", "quantizer", ".", "compress", "(", ")", "model", ".", "to", "(", "device", ")", "for", "epoch", "in", "range", "(", "40", ")", ":", "print", "(", "'# Epoch {} #'", ".", "format", "(", "epoch", ")", ")", "train", "(", "model", ",", "quantizer", ",", "device", ",", "train_loader", ",", "optimizer", ")", "test", "(", "model", ",", "device", ",", "test_loader", ")", "model_path", "=", "\"mnist_model.pth\"", "calibration_path", "=", "\"mnist_calibration.pth\"", "onnx_path", "=", "\"mnist_model.onnx\"", "input_shape", "=", "(", "1", ",", "1", ",", "28", ",", "28", ")", "device", "=", "torch", ".", "device", "(", "\"cuda\"", ")", "calibration_config", "=", "quantizer", ".", "export_model", "(", "model_path", ",", "calibration_path", ",", "onnx_path", ",", "input_shape", ",", "device", ")", "print", "(", "\"Generated calibration config is: \"", ",", "calibration_config", ")" ]
[ 37, 0 ]
[ 82, 66 ]
python
en
['en', 'en', 'en']
True
TestTCPBinarySensor.setup_method
(self, method)
Set up things to be run when tests are started.
Set up things to be run when tests are started.
def setup_method(self, method): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant()
[ "def", "setup_method", "(", "self", ",", "method", ")", ":", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")" ]
[ 15, 4 ]
[ 17, 45 ]
python
en
['en', 'en', 'en']
True
TestTCPBinarySensor.teardown_method
(self, method)
Stop down everything that was started.
Stop down everything that was started.
def teardown_method(self, method): """Stop down everything that was started.""" self.hass.stop()
[ "def", "teardown_method", "(", "self", ",", "method", ")", ":", "self", ".", "hass", ".", "stop", "(", ")" ]
[ 19, 4 ]
[ 21, 24 ]
python
en
['en', 'en', 'en']
True
TestTCPBinarySensor.test_setup_platform_valid_config
(self)
Check a valid configuration.
Check a valid configuration.
def test_setup_platform_valid_config(self): """Check a valid configuration.""" with assert_setup_component(0, "binary_sensor"): assert setup_component(self.hass, "binary_sensor", test_tcp.TEST_CONFIG)
[ "def", "test_setup_platform_valid_config", "(", "self", ")", ":", "with", "assert_setup_component", "(", "0", ",", "\"binary_sensor\"", ")", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "\"binary_sensor\"", ",", "test_tcp", ".", "TEST_CONFIG", ")" ]
[ 23, 4 ]
[ 26, 84 ]
python
en
['en', 'en', 'en']
True
TestTCPBinarySensor.test_setup_platform_invalid_config
(self)
Check the invalid configuration.
Check the invalid configuration.
def test_setup_platform_invalid_config(self): """Check the invalid configuration.""" with assert_setup_component(0): assert setup_component( self.hass, "binary_sensor", {"binary_sensor": {"platform": "tcp", "porrt": 1234}}, )
[ "def", "test_setup_platform_invalid_config", "(", "self", ")", ":", "with", "assert_setup_component", "(", "0", ")", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "\"binary_sensor\"", ",", "{", "\"binary_sensor\"", ":", "{", "\"platform\"", ":", "\"tcp\"", ",", "\"porrt\"", ":", "1234", "}", "}", ",", ")" ]
[ 28, 4 ]
[ 35, 13 ]
python
en
['en', 'it', 'en']
True
TestTCPBinarySensor.test_setup_platform_devices
(self, mock_update)
Check the supplied config and call add_entities with sensor.
Check the supplied config and call add_entities with sensor.
def test_setup_platform_devices(self, mock_update): """Check the supplied config and call add_entities with sensor.""" add_entities = Mock() ret = bin_tcp.setup_platform(None, test_tcp.TEST_CONFIG, add_entities) assert ret is None assert add_entities.called assert isinstance(add_entities.call_args[0][0][0], bin_tcp.TcpBinarySensor)
[ "def", "test_setup_platform_devices", "(", "self", ",", "mock_update", ")", ":", "add_entities", "=", "Mock", "(", ")", "ret", "=", "bin_tcp", ".", "setup_platform", "(", "None", ",", "test_tcp", ".", "TEST_CONFIG", ",", "add_entities", ")", "assert", "ret", "is", "None", "assert", "add_entities", ".", "called", "assert", "isinstance", "(", "add_entities", ".", "call_args", "[", "0", "]", "[", "0", "]", "[", "0", "]", ",", "bin_tcp", ".", "TcpBinarySensor", ")" ]
[ 38, 4 ]
[ 44, 83 ]
python
en
['en', 'en', 'en']
True
TestTCPBinarySensor.test_is_on_true
(self, mock_update)
Check the return that _state is value_on.
Check the return that _state is value_on.
def test_is_on_true(self, mock_update): """Check the return that _state is value_on.""" sensor = bin_tcp.TcpBinarySensor(self.hass, test_tcp.TEST_CONFIG["sensor"]) sensor._state = test_tcp.TEST_CONFIG["sensor"][tcp.CONF_VALUE_ON] print(sensor._state) assert sensor.is_on
[ "def", "test_is_on_true", "(", "self", ",", "mock_update", ")", ":", "sensor", "=", "bin_tcp", ".", "TcpBinarySensor", "(", "self", ".", "hass", ",", "test_tcp", ".", "TEST_CONFIG", "[", "\"sensor\"", "]", ")", "sensor", ".", "_state", "=", "test_tcp", ".", "TEST_CONFIG", "[", "\"sensor\"", "]", "[", "tcp", ".", "CONF_VALUE_ON", "]", "print", "(", "sensor", ".", "_state", ")", "assert", "sensor", ".", "is_on" ]
[ 47, 4 ]
[ 52, 27 ]
python
en
['en', 'en', 'en']
True
TestTCPBinarySensor.test_is_on_false
(self, mock_update)
Check the return that _state is not the same as value_on.
Check the return that _state is not the same as value_on.
def test_is_on_false(self, mock_update): """Check the return that _state is not the same as value_on.""" sensor = bin_tcp.TcpBinarySensor(self.hass, test_tcp.TEST_CONFIG["sensor"]) sensor._state = "{} abc".format( test_tcp.TEST_CONFIG["sensor"][tcp.CONF_VALUE_ON] ) assert not sensor.is_on
[ "def", "test_is_on_false", "(", "self", ",", "mock_update", ")", ":", "sensor", "=", "bin_tcp", ".", "TcpBinarySensor", "(", "self", ".", "hass", ",", "test_tcp", ".", "TEST_CONFIG", "[", "\"sensor\"", "]", ")", "sensor", ".", "_state", "=", "\"{} abc\"", ".", "format", "(", "test_tcp", ".", "TEST_CONFIG", "[", "\"sensor\"", "]", "[", "tcp", ".", "CONF_VALUE_ON", "]", ")", "assert", "not", "sensor", ".", "is_on" ]
[ 55, 4 ]
[ 61, 31 ]
python
en
['en', 'en', 'en']
True
make_divisible
(v, divisor, min_val=None)
This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
def make_divisible(v, divisor, min_val=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ if min_val is None: min_val = divisor new_v = max(min_val, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v
[ "def", "make_divisible", "(", "v", ",", "divisor", ",", "min_val", "=", "None", ")", ":", "if", "min_val", "is", "None", ":", "min_val", "=", "divisor", "new_v", "=", "max", "(", "min_val", ",", "int", "(", "v", "+", "divisor", "/", "2", ")", "//", "divisor", "*", "divisor", ")", "# Make sure that round down does not go down by more than 10%.", "if", "new_v", "<", "0.9", "*", "v", ":", "new_v", "+=", "divisor", "return", "new_v" ]
[ 56, 0 ]
[ 69, 16 ]
python
en
['en', 'error', 'th']
False
accuracy
(output, target, topk=(1,))
Computes the precision@k for the specified values of k
Computes the precision
def accuracy(output, target, topk=(1,)): """ Computes the precision@k for the specified values of k """ maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() # one-hot case if target.ndimension() > 1: target = target.max(1)[1] correct = pred.eq(target.view(1, -1).expand_as(pred)) res = dict() for k in topk: correct_k = correct[:k].reshape(-1).float().sum(0) res["acc{}".format(k)] = correct_k.mul_(1.0 / batch_size).item() return res
[ "def", "accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", ")", ")", ":", "maxk", "=", "max", "(", "topk", ")", "batch_size", "=", "target", ".", "size", "(", "0", ")", "_", ",", "pred", "=", "output", ".", "topk", "(", "maxk", ",", "1", ",", "True", ",", "True", ")", "pred", "=", "pred", ".", "t", "(", ")", "# one-hot case", "if", "target", ".", "ndimension", "(", ")", ">", "1", ":", "target", "=", "target", ".", "max", "(", "1", ")", "[", "1", "]", "correct", "=", "pred", ".", "eq", "(", "target", ".", "view", "(", "1", ",", "-", "1", ")", ".", "expand_as", "(", "pred", ")", ")", "res", "=", "dict", "(", ")", "for", "k", "in", "topk", ":", "correct_k", "=", "correct", "[", ":", "k", "]", ".", "reshape", "(", "-", "1", ")", ".", "float", "(", ")", ".", "sum", "(", "0", ")", "res", "[", "\"acc{}\"", ".", "format", "(", "k", ")", "]", "=", "correct_k", ".", "mul_", "(", "1.0", "/", "batch_size", ")", ".", "item", "(", ")", "return", "res" ]
[ 72, 0 ]
[ 89, 14 ]
python
en
['en', 'en', 'en']
True
get_scanner
(hass, config)
Validate the configuration and return an ubus scanner.
Validate the configuration and return an ubus scanner.
def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
[ "def", "get_scanner", "(", "hass", ",", "config", ")", ":", "dhcp_sw", "=", "config", "[", "DOMAIN", "]", "[", "CONF_DHCP_SOFTWARE", "]", "if", "dhcp_sw", "==", "\"dnsmasq\"", ":", "scanner", "=", "DnsmasqUbusDeviceScanner", "(", "config", "[", "DOMAIN", "]", ")", "elif", "dhcp_sw", "==", "\"odhcpd\"", ":", "scanner", "=", "OdhcpdUbusDeviceScanner", "(", "config", "[", "DOMAIN", "]", ")", "else", ":", "scanner", "=", "UbusDeviceScanner", "(", "config", "[", "DOMAIN", "]", ")", "return", "scanner", "if", "scanner", ".", "success_init", "else", "None" ]
[ 35, 0 ]
[ 45, 52 ]
python
en
['en', 'en', 'en']
True
_refresh_on_access_denied
(func)
If remove rebooted, it lost our session so rebuild one and try again.
If remove rebooted, it lost our session so rebuild one and try again.
def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.session_id = _get_session_id(self.url, self.username, self.password) return func(self, *args, **kwargs) return decorator
[ "def", "_refresh_on_access_denied", "(", "func", ")", ":", "def", "decorator", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrap the function to refresh session_id on PermissionError.\"\"\"", "try", ":", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "PermissionError", ":", "_LOGGER", ".", "warning", "(", "\"Invalid session detected.\"", "\" Trying to refresh session_id and re-run RPC\"", ")", "self", ".", "session_id", "=", "_get_session_id", "(", "self", ".", "url", ",", "self", ".", "username", ",", "self", ".", "password", ")", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "decorator" ]
[ 48, 0 ]
[ 64, 20 ]
python
en
['en', 'en', 'en']
True
_req_json_rpc
(url, session_id, rpcmethod, subsystem, method, **params)
Perform one JSON RPC operation.
Perform one JSON RPC operation.
def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): """Perform one JSON RPC operation.""" data = json.dumps( { "jsonrpc": "2.0", "id": 1, "method": rpcmethod, "params": [session_id, subsystem, method, params], } ) try: res = requests.post(url, data=data, timeout=5) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout): return if res.status_code == HTTP_OK: response = res.json() if "error" in response: if ( "message" in response["error"] and response["error"]["message"] == "Access denied" ): raise PermissionError(response["error"]["message"]) raise HomeAssistantError(response["error"]["message"]) if rpcmethod == "call": try: return response["result"][1] except IndexError: return else: return response["result"]
[ "def", "_req_json_rpc", "(", "url", ",", "session_id", ",", "rpcmethod", ",", "subsystem", ",", "method", ",", "*", "*", "params", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "\"jsonrpc\"", ":", "\"2.0\"", ",", "\"id\"", ":", "1", ",", "\"method\"", ":", "rpcmethod", ",", "\"params\"", ":", "[", "session_id", ",", "subsystem", ",", "method", ",", "params", "]", ",", "}", ")", "try", ":", "res", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "data", ",", "timeout", "=", "5", ")", "except", "(", "requests", ".", "exceptions", ".", "ConnectionError", ",", "requests", ".", "exceptions", ".", "Timeout", ")", ":", "return", "if", "res", ".", "status_code", "==", "HTTP_OK", ":", "response", "=", "res", ".", "json", "(", ")", "if", "\"error\"", "in", "response", ":", "if", "(", "\"message\"", "in", "response", "[", "\"error\"", "]", "and", "response", "[", "\"error\"", "]", "[", "\"message\"", "]", "==", "\"Access denied\"", ")", ":", "raise", "PermissionError", "(", "response", "[", "\"error\"", "]", "[", "\"message\"", "]", ")", "raise", "HomeAssistantError", "(", "response", "[", "\"error\"", "]", "[", "\"message\"", "]", ")", "if", "rpcmethod", "==", "\"call\"", ":", "try", ":", "return", "response", "[", "\"result\"", "]", "[", "1", "]", "except", "IndexError", ":", "return", "else", ":", "return", "response", "[", "\"result\"", "]" ]
[ 199, 0 ]
[ 232, 37 ]
python
en
['en', 'en', 'en']
True
_get_session_id
(url, username, password)
Get the authentication token for the given host+username+password.
Get the authentication token for the given host+username+password.
def _get_session_id(url, username, password): """Get the authentication token for the given host+username+password.""" res = _req_json_rpc( url, "00000000000000000000000000000000", "call", "session", "login", username=username, password=password, ) return res["ubus_rpc_session"]
[ "def", "_get_session_id", "(", "url", ",", "username", ",", "password", ")", ":", "res", "=", "_req_json_rpc", "(", "url", ",", "\"00000000000000000000000000000000\"", ",", "\"call\"", ",", "\"session\"", ",", "\"login\"", ",", "username", "=", "username", ",", "password", "=", "password", ",", ")", "return", "res", "[", "\"ubus_rpc_session\"", "]" ]
[ 235, 0 ]
[ 246, 34 ]
python
en
['en', 'en', 'en']
True
UbusDeviceScanner.__init__
(self, config)
Initialize the scanner.
Initialize the scanner.
def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.session_id = _get_session_id(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.session_id is not None
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "host", "=", "config", "[", "CONF_HOST", "]", "self", ".", "username", "=", "config", "[", "CONF_USERNAME", "]", "self", ".", "password", "=", "config", "[", "CONF_PASSWORD", "]", "self", ".", "parse_api_pattern", "=", "re", ".", "compile", "(", "r\"(?P<param>\\w*) = (?P<value>.*);\"", ")", "self", ".", "last_results", "=", "{", "}", "self", ".", "url", "=", "f\"http://{host}/ubus\"", "self", ".", "session_id", "=", "_get_session_id", "(", "self", ".", "url", ",", "self", ".", "username", ",", "self", ".", "password", ")", "self", ".", "hostapd", "=", "[", "]", "self", ".", "mac2name", "=", "None", "self", ".", "success_init", "=", "self", ".", "session_id", "is", "not", "None" ]
[ 74, 4 ]
[ 87, 55 ]
python
en
['en', 'en', 'en']
True
UbusDeviceScanner.scan_devices
(self)
Scan for new devices and return a list with found device IDs.
Scan for new devices and return a list with found device IDs.
def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results
[ "def", "scan_devices", "(", "self", ")", ":", "self", ".", "_update_info", "(", ")", "return", "self", ".", "last_results" ]
[ 89, 4 ]
[ 92, 32 ]
python
en
['en', 'en', 'en']
True
UbusDeviceScanner._generate_mac2name
(self)
Return empty MAC to name dict. Overridden if DHCP server is set.
Return empty MAC to name dict. Overridden if DHCP server is set.
def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {}
[ "def", "_generate_mac2name", "(", "self", ")", ":", "self", ".", "mac2name", "=", "{", "}" ]
[ 94, 4 ]
[ 96, 26 ]
python
en
['en', 'en', 'en']
True
UbusDeviceScanner.get_device_name
(self, device)
Return the name of the given device or None if we don't know.
Return the name of the given device or None if we don't know.
def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name
[ "def", "get_device_name", "(", "self", ",", "device", ")", ":", "if", "self", ".", "mac2name", "is", "None", ":", "self", ".", "_generate_mac2name", "(", ")", "if", "self", ".", "mac2name", "is", "None", ":", "# Generation of mac2name dictionary failed", "return", "None", "name", "=", "self", ".", "mac2name", ".", "get", "(", "device", ".", "upper", "(", ")", ",", "None", ")", "return", "name" ]
[ 99, 4 ]
[ 107, 19 ]
python
en
['en', 'en', 'en']
True
UbusDeviceScanner._update_info
(self)
Ensure the information from the router is up to date. Returns boolean if scanning successful.
Ensure the information from the router is up to date.
def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = _req_json_rpc(self.url, self.session_id, "list", "hostapd.*", "") self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: result = _req_json_rpc( self.url, self.session_id, "call", hostapd, "get_clients" ) if result: results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results)
[ "def", "_update_info", "(", "self", ")", ":", "if", "not", "self", ".", "success_init", ":", "return", "False", "_LOGGER", ".", "info", "(", "\"Checking hostapd\"", ")", "if", "not", "self", ".", "hostapd", ":", "hostapd", "=", "_req_json_rpc", "(", "self", ".", "url", ",", "self", ".", "session_id", ",", "\"list\"", ",", "\"hostapd.*\"", ",", "\"\"", ")", "self", ".", "hostapd", ".", "extend", "(", "hostapd", ".", "keys", "(", ")", ")", "self", ".", "last_results", "=", "[", "]", "results", "=", "0", "# for each access point", "for", "hostapd", "in", "self", ".", "hostapd", ":", "result", "=", "_req_json_rpc", "(", "self", ".", "url", ",", "self", ".", "session_id", ",", "\"call\"", ",", "hostapd", ",", "\"get_clients\"", ")", "if", "result", ":", "results", "=", "results", "+", "1", "# Check for each device is authorized (valid wpa key)", "for", "key", "in", "result", "[", "\"clients\"", "]", ".", "keys", "(", ")", ":", "device", "=", "result", "[", "\"clients\"", "]", "[", "key", "]", "if", "device", "[", "\"authorized\"", "]", ":", "self", ".", "last_results", ".", "append", "(", "key", ")", "return", "bool", "(", "results", ")" ]
[ 110, 4 ]
[ 140, 28 ]
python
en
['en', 'en', 'en']
True
DnsmasqUbusDeviceScanner.__init__
(self, config)
Initialize the scanner.
Initialize the scanner.
def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "super", "(", ")", ".", "__init__", "(", "config", ")", "self", ".", "leasefile", "=", "None" ]
[ 146, 4 ]
[ 149, 29 ]
python
en
['en', 'en', 'en']
True