本文整理汇总了Python中homeassistant.helpers.aiohttp_client.async_get_clientsession方法的典型用法代码示例。如果您正苦于以下问题:Python aiohttp_client.async_get_clientsession方法的具体用法?Python aiohttp_client.async_get_clientsession怎么用?Python aiohttp_client.async_get_clientsession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类homeassistant.helpers.aiohttp_client
的用法示例。
在下文中一共展示了aiohttp_client.async_get_clientsession方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: async_check_http_oauth
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def async_check_http_oauth(self, triggered=None):
_LOGGER.debug("[%s] check accessibility from local", LOGGER_NAME)
try:
if self._retry_remove is not None:
self._retry_remove()
self._retry_remove = None
session = async_get_clientsession(self._hass, verify_ssl=False)
with async_timeout.timeout(5, loop= self._hass.loop):
response = await session.get(self._ha_url + '/havcs/auth/authorize')
if response.status == 401:
_LOGGER.debug("[%s][check] access success: url = %s, status = %s", LOGGER_NAME, self._ha_url + '/havcs/auth/authorize', response.status)
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.debug("[%s][check] retry check after 15s", LOGGER_NAME)
self._retry_times -= 1
if(self._retry_times > 0):
self._retry_remove = async_track_time_interval(
self._hass, self.async_check_http_oauth, timedelta(seconds=15)
)
else:
_LOGGER.error("[%s][check] can not access http, check `ha_url` in configuration.yml", LOGGER_NAME)
except Exception:
_LOGGER.exception("[%s][check] unexpected error occur", LOGGER_NAME)
raise
示例2: async_bind_device
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def async_bind_device(self):
for uuid in self._hass.data[INTEGRATION][DATA_HAVCS_BIND_MANAGER].discovery:
p_user_id = uuid.split('@')[0]
platform = uuid.split('@')[1]
if platform in self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER] and getattr(self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER].get(platform), 'should_report_when_starup', False) and hasattr(self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER].get(platform), 'bind_device'):
err_result, devices, entity_ids = self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER][platform].process_discovery_command()
if err_result:
return
bind_entity_ids, unbind_entity_ids = await self._hass.data[INTEGRATION][DATA_HAVCS_BIND_MANAGER].async_save_changed_devices(entity_ids,platform, p_user_id,True)
payload = await self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER][platform].bind_device(p_user_id, entity_ids , unbind_entity_ids, devices)
_LOGGER.debug("[skill] bind device to %s:\nbind_entity_ids = %s, unbind_entity_ids = %s", platform, bind_entity_ids, unbind_entity_ids)
if payload:
url = HAVCS_SERVICE_URL + '/skill/smarthome.php?v=update&AppKey='+self._sync_manager.get('app_key')
data = havcs_util.AESCipher(self._sync_manager.get('decrypt_key')).encrypt(json.dumps(payload, ensure_ascii = False).encode('utf8'))
try:
session = async_get_clientsession(self._hass, verify_ssl=False)
with async_timeout.timeout(5, loop=self._hass.loop):
response = await session.post(url, data=data)
_LOGGER.debug("[skill] get bind device result from %s: %s", platform, await response.text())
except(asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("[skill] fail to access %s, bind device fail: timeout", url)
except:
_LOGGER.error("[skill] fail to access %s, bind device fail: %s", url, traceback.format_exc())
示例3: init_connection
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def init_connection(self):
session = async_get_clientsession(self.hass)
self.connection = AudiConnectAccount(
session=session,
username=self.config_entry.data.get(CONF_USERNAME),
password=self.config_entry.data.get(CONF_PASSWORD),
country=self.config_entry.data.get(CONF_REGION),
spin=self.config_entry.data.get(CONF_SPIN),
)
self.hass.services.async_register(
DOMAIN,
SERVICE_REFRESH_VEHICLE_DATA,
self.refresh_vehicle_data,
schema=SERVICE_REFRESH_VEHICLE_DATA_SCHEMA,
)
self.hass.services.async_register(
DOMAIN,
SERVICE_EXECUTE_VEHICLE_ACTION,
self.execute_vehicle_action,
schema=SERVICE_EXECUTE_VEHICLE_ACTION_SCHEMA,
)
self.connection.add_observer(self)
示例4: async_setup_platform
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
using_wu = CONF_API_KEY in config
session = None
if using_wu:
session = async_get_clientsession(hass)
if not await _async_get_wu_data(
hass, session, config[CONF_API_KEY], [], config[CONF_QUERY]):
return False
async_add_entities([IlluminanceSensor(using_wu, config, session)], True)
示例5: _test_token
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def _test_token(self, token):
"""Return true if token is valid."""
try:
session = aiohttp_client.async_get_clientsession(self.hass)
await get_repository(session, token, "hacs/org")
return True
except (
AIOGitHubAPIException,
AIOGitHubAPIAuthenticationException,
) as exception:
_LOGGER.error(exception)
return False
示例6: async_get_longitude_latitude
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def async_get_longitude_latitude(self, address_dict):
if address_dict.get(CONF_LONGITUDE_LATITUDE) is not None:
return address_dict.get(CONF_LONGITUDE_LATITUDE)
if (address_dict.get(CONF_ADDRESS) is None) or (address_dict.get(CONF_CITY) is None):
return
url = ("http://restapi.amap.com/v3/geocode/geo?key="
+ self._api_key
+ '&address=' + address_dict.get(CONF_ADDRESS)
+ '&city=' + address_dict.get(CONF_CITY)
)
try:
session = async_get_clientsession(self._hass)
with async_timeout.timeout(15, loop=self._hass.loop):
response = yield from session.get( url )
except(asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while accessing: %s", url)
return
if response.status != 200:
_LOGGER.error("Error while accessing: %s, status=%d", url, response.status)
return
data = yield from response.json()
if data is None:
_LOGGER.error("Request api Error: %s", url)
return
elif (data['status'] != '1'):
_LOGGER.error("Error Api return, state=%s, errmsg=%s",
data['status'],
data['info']
)
return
return data['geocodes'][0]['location']
示例7: async_connect
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def async_connect(self):
"""Connect to remote home-assistant websocket..."""
url = self._get_url()
session = async_get_clientsession(self._hass, self._verify_ssl)
self._hass.states.async_set(self._connection_state_entity, STATE_CONNECTING, self._instance_attrs)
while True:
try:
_LOGGER.info('Connecting to %s', url)
self._connection = await session.ws_connect(url)
except aiohttp.client_exceptions.ClientError as err:
_LOGGER.error(
'Could not connect to %s, retry in 10 seconds...', url)
self._hass.states.async_set(self._connection_state_entity, STATE_RECONNECTING, self._instance_attrs)
await asyncio.sleep(10)
else:
_LOGGER.info(
'Connected to home-assistant websocket at %s', url)
self._hass.states.async_set(self._connection_state_entity, STATE_CONNECTED, self._instance_attrs)
break
async def stop():
"""Close connection."""
if self._connection is not None:
await self._connection.close()
self._hass.states.async_set(self._connection_state_entity, STATE_DISCONNECTED)
self._hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop)
asyncio.ensure_future(self._recv())
示例8: __init__
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def __init__(self, hass, name, stop_id, direction):
"""Initialize the sensor."""
self.hass = hass
self.websession = async_get_clientsession(hass)
self._name = name
self.stop_id = stop_id
self.direction = direction
self.data = {
'stopName': '...',
'actual': []
}
示例9: setup_platform
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def setup_platform(hass, config, add_devices, discovery_info=None):
_LOGGER.error('Setup of the soundbar')
ip = config.get(CONF_HOST)
port = config.get(CONF_PORT)
name = config.get(CONF_NAME)
max_volume = int(config.get(CONF_MAX_VOLUME))
session = async_get_clientsession(hass)
api = MultiRoomApi(ip, port, session, hass)
add_devices([MultiRoomDevice(name, max_volume, api)], True)
示例10: setup_platform
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def setup_platform(hass, config, add_devices, discovery_info=None):
account_id = config.get(CONF_ACCOUNT_ID)
token = config.get(CONF_TOKEN)
name = config.get(CONF_NAME)
websession = async_get_clientsession(hass)
add_devices([HarvestSensor(hass, websession, account_id, token, name)])
示例11: setup_platform
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def setup_platform(hass, config, add_devices, discovery_info=None):
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
name = config.get(CONF_NAME)
websession = async_get_clientsession(hass)
add_devices([LunchingSensor(hass, websession, name, username, password)])
示例12: __init__
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def __init__(self, hass, city_card_id, identity_id, name):
"""Initialize the sensor."""
self.hass = hass
self.websession = async_get_clientsession(hass)
self.city_card_id = city_card_id
self.identity_id = identity_id
self._lines = []
self._name = name
self._expire_at = None
self._state = STATE_OFF
示例13: sync_device
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def sync_device(self):
remove_listener = self._sync_manager.get('remove_listener')
if remove_listener:
remove_listener()
@callback
def report_device(event):
# _LOGGER.debug("[skill] %s changed, try to report", event.data[ATTR_ENTITY_ID])
self._hass.add_job(async_report_device(event))
async def async_report_device(event):
"""report device state when changed. """
entity = self._hass.states.get(event.data[ATTR_ENTITY_ID])
if entity is None:
return
for platform, handler in self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER].items():
if hasattr(handler, 'report_device'):
device_ids = handler.vcdm.get_entity_related_device_ids(self._hass, entity.entity_id)
for device_id in device_ids:
payload = handler.report_device(device_id)
_LOGGER.debug("[skill] report device to %s: platform = %s, device_id = %s (entity_id = %s), data = %s", platform, device_id, event.data[ATTR_ENTITY_ID], platform, payload)
if payload:
url = HAVCS_SERVICE_URL + '/skill/'+platform+'.php?v=report&AppKey=' + self._sync_manager.get('app_key')
data = havcs_util.AESCipher(self._sync_manager.get('decrypt_key')).encrypt(json.dumps(payload, ensure_ascii = False).encode('utf8'))
try:
session = async_get_clientsession(self._hass, verify_ssl=False)
with async_timeout.timeout(5, loop=self._hass.loop):
response = await session.post(url, data=data)
_LOGGER.debug("[skill] get report device result from %s: %s", platform, await response.text())
except(asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("[skill] fail to access %s, report device fail: timeout", url)
except:
_LOGGER.error("[skill] fail to access %s, report device fail: %s", url, traceback.format_exc())
self._sync_manager['remove_listener'] = self._hass.bus.async_listen(EVENT_STATE_CHANGED, report_device)
示例14: async_update
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def async_update(self, now):
"""从远程更新信息."""
_LOGGER.info("Update from JingdongWangxiang's OpenAPI...")
"""
# 异步模式的测试代码
import time
_LOGGER.info("before time.sleep")
time.sleep(40)
_LOGGER.info("after time.sleep and before asyncio.sleep")
asyncio.sleep(40)
_LOGGER.info("after asyncio.sleep and before yield from asyncio.sleep")
yield from asyncio.sleep(40)
_LOGGER.info("after yield from asyncio.sleep")
"""
# 通过HTTP访问,获取需要的信息
# 此处使用了基于aiohttp库的async_get_clientsession
try:
session = async_get_clientsession(self._hass)
with async_timeout.timeout(15, loop=self._hass.loop):
response = yield from session.post(
self._url, data=self._params)
except(asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while accessing: %s", self._url)
return
if response.status != 200:
_LOGGER.error("Error while accessing: %s, status=%d",
self._url,
response.status)
return
try:
result = yield from response.json()
except(aiohttp.client_exceptions.ContentTypeError):
_LOGGER.error("Error return type: %s", str(response))
return
if result is None:
_LOGGER.error("Request api Error")
return
elif result["code"] != "10000":
_LOGGER.error("Error API return, code=%s, msg=%s",
result["code"],
result["msg"])
return
# 根据http返回的结果,更新数据
all_result = result["result"]["HeWeather5"][0]
self._temprature = all_result["now"]["tmp"]
self._humidity = all_result["now"]["hum"]
self._pm25 = all_result["aqi"]["city"]["pm25"]
self._updatetime = all_result["basic"]["update"]["loc"]
示例15: async_update
# 需要导入模块: from homeassistant.helpers import aiohttp_client [as 别名]
# 或者: from homeassistant.helpers.aiohttp_client import async_get_clientsession [as 别名]
def async_update(self, now):
"""Get the latest data and updates the states."""
date = now.strftime("%Y-%m-%d")
params = {
"key": self.key,
"date": date,
}
try:
session = async_get_clientsession(self.hass)
with async_timeout.timeout(15, loop=self.hass.loop):
response = yield from session.post( self.url, data=params )
except(asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while accessing: %s", self.url)
return
if response.status != 200:
_LOGGER.error("Error while accessing: %s, status=%d", url, response.status)
return
result = yield from response.json()
if result is None:
_LOGGER.error("Request api Error: %s", url)
return
elif (result["error_code"] != 0):
_LOGGER.error("Error API return, errorcode=%s, reson=%s",
result["error_code"],
result["reason"],
)
return
self.yangli = result["result"]["yangli"]
self.yinli = result["result"]["yinli"]
self.wuxing = result["result"]["wuxing"].replace(" ","、")
self.chongsha = result["result"]["chongsha"]
self.baiji = result["result"]["baiji"].replace(" ","、")
self.jishen = result["result"]["jishen"].replace(" ","、")
self.yi = result["result"]["yi"].replace(" ","、")
self.xiongshen = result["result"]["xiongshen"].replace(" ","、")
self.ji = result["result"]["ji"].replace(" ","、")