al-one / hass-xiaomi-miot

Automatic integrate all Xiaomi devices to HomeAssistant via miot-spec, support Wi-Fi, BLE, ZigBee devices. 小米米家智能家居设备接入Hass集成
https://miot-spec.com
Apache License 2.0
4.65k stars 664 forks source link

service_token过期没有成功刷新 #1947

Open AnneYang720 opened 1 week ago

AnneYang720 commented 1 week ago

在请求业务接口返回httpcode=401 或 code=3 后,有调用_logout https://github.com/al-one/hass-xiaomi-miot/blob/master/custom_components/xiaomi_miot/core/xiaomi_cloud.py#L235

if code == 3:
    self._logout()

https://github.com/al-one/hass-xiaomi-miot/blob/master/custom_components/xiaomi_miot/core/xiaomi_cloud.py#L783

if response.status_code == 401:
    self._logout()

_logout会将内存里的service_token置为None,在下次请求业务接口时判断为空调用登录函数获取新service_token

但新的service_token没有生效,因为 https://github.com/al-one/hass-xiaomi-miot/blob/master/custom_components/xiaomi_miot/core/xiaomi_cloud.py#L664

def api_session(self, **kwargs):
        if not self.service_token or not self.user_id:
            raise MiCloudException('Cannot execute request. service token or userId missing. Make sure to login.')

        if kwargs.get('async'):
            if not (session := self.async_session):
                session = async_create_clientsession(
                    self.hass,
                    headers=self.api_headers(),
                    cookies=self.api_cookies(),
                )
                self.async_session = session
        else:
            session = requests.Session()
            session.headers.update(self.api_headers())
            session.cookies.update(self.api_cookies())
        return session

if not (session := self.async_session) 这里不会满足,因此还在用旧的session继续请求,而旧的session里存着旧的service_token

al-one commented 1 week ago

感谢!已优化