1 Commits
Author SHA1 Message Date
HassBox 4e86f2f3b6 deploy 2024-06-14 09:39:21 +08:00
6 changed files with 306 additions and 368 deletions
+29 -1
View File
@@ -1 +1,29 @@
# State Grid # 国家电网
集成国家电网每日用电等数据,支持多户号,阶梯用电。
## 安装/更新
#### 方法 1: 通过`Samba`或`SFTP`手动安装
下载并复制`custom_components/state_gird`文件夹到 Home Assistant 根目录下的`custom_components`文件夹
#### 方法 2: 通过`SSH`或`Terminal & SSH`加载项执行一键安装命令
```shell
curl -fsSL get.hassbox.cn/state_grid | bash
```
#### 方法 3: 通过`shell_command`服务
1. 复制下面的代码到 Home Assistant 配置文件`configuration.yaml`
```yaml
shell_command:
install_state_grid: |-
curl -fsSL get.hassbox.cn/state_grid | bash
```
2. 重启 Home Assistant
3. 在 Home Assistant 开发者工具中调用此服务[`service: shell_command.install_state_grid`](https://my.home-assistant.io/redirect/developer_call_service/?service=shell_command.install_state_grid)
+2 -2
View File
@@ -202,12 +202,13 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
async def async_step_check_qr_code(self, user_input=None): async def async_step_check_qr_code(self, user_input=None):
result = await self.data_client.check_qr_code() result = await self.data_client.check_qr_code()
if result['errcode'] != 0: if result['errcode'] != 0:
return self.async_abort( return self.async_abort(
reason="check_qr_code_error", reason="check_qr_code_error",
description_placeholders={'errmsg': result["errmsg"]} description_placeholders={'errmsg': result["errmsg"]}
) )
await self.data_client.refresh_data(force_refresh=True)
return self.async_create_entry( return self.async_create_entry(
title="国家电网", title="国家电网",
data={} data={}
@@ -247,7 +248,6 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
code = user_input['code'] code = user_input['code']
result = await self.data_client.verfiy_phone_code(code) result = await self.data_client.verfiy_phone_code(code)
if result['errcode'] == 0: if result['errcode'] == 0:
await self.data_client.refresh_data(force_refresh=True)
return self.async_create_entry( return self.async_create_entry(
title="国家电网", title="国家电网",
data={} data={}
+1 -1
View File
@@ -1,4 +1,4 @@
DOMAIN = "state_grid" DOMAIN = "state_grid"
PACKAGE_NAME = "custom_components.state_grid" PACKAGE_NAME = "custom_components.state_grid"
VERSION = "0.1.3" VERSION = "0.1.1"
VERSION_STORAGE = 1 VERSION_STORAGE = 1
+239 -281
View File
@@ -1,129 +1,108 @@
_B4='get_door_daily_bill_api' _Al='constType'
_B3='startTime' _Ak='queryYear'
_B2='constType' _Aj='provinceCode'
_B1='provinceCode' _Ai='access_token'
_B0='access_token' _Ah='businessType'
_A_='businessType' _Ag='qrCodeSerial'
_Az='qrCodeSerial' _Af='redirect_url'
_Ay='redirect_url' _Ae='_access_token'
_Ax='_access_token' _Ad='refresh_interval'
_Aw='dataVersion' _Ac='doorAccountDict'
_Av='refresh_interval' _Ab='refreshToken'
_Au='doorAccountDict' _Aa='accessToken'
_At='refreshToken' _AZ='/osg-web0004/member/c24/f01'
_As='accessToken' _AY='BCP_00026'
_Ar='/osg-web0004/member/c24/f01' _AX='serviceCode_smt'
_Aq='BCP_00026' _AW='WEBA10070900'
_Ap='serviceCode_smt' _AV='serviceType'
_Ao='WEBA10070900' _AU='jM_custType'
_An='serviceType' _AT='jM_busiTypeCode'
_Am='jM_custType' _AS='doorNumberManeger'
_Al='jM_busiTypeCode' _AR='month'
_Ak='doorNumberManeger' _AQ='consType'
_Aj='month_t_ele_num' _AP='userAccountId'
_Ai='month_n_ele_num' _AO='powerUserList'
_Ah='month_v_ele_num' _AN='publicKey'
_Ag='month_p_ele_num' _AM='WEBA10070800'
_Af='month_ele_num' _AL='timeDay'
_Ae='thisTPq' _AK='WEBA10070700'
_Ad='thisNPq' _AJ='channelNo'
_Ac='thisVPq' _AI='monthBillList'
_Ab='thisPPq' _AH='yearTotalCost'
_Aa='%Y%m%d' _AG='provinceId'
_AZ='params4' _AF='proCode'
_AY='params3' _AE='loginAccount'
_AX='params1' _AD='0000'
_AW='queryYear' _AC='refresh_token'
_AV='userAccountId' _AB='skey'
_AU='powerUserList' _AA='userInfo'
_AT='publicKey' _A9='0101046'
_AS='WEBA10070800' _A8='account_balance'
_AR='timeDay' _A7='list'
_AQ='WEBA10070700' _A6='userName'
_AP='channelNo' _A5='acctId'
_AO='dayElePq' _A4='keyCode'
_AN='sevenEleList' _A3='querytypeCode'
_AM='month' _A2='01010049'
_AL='yearTotalCost' _A1='account'
_AK='consType' _A0='resultCode'
_AJ='0000' _z='quInfo'
_AI='refresh_token' _y=True
_AH='skey' _x='BCP_000026'
_AG='userInfo' _w='app'
_AF='0101046' _v='WEBALIPAY_01'
_AE='billYear' _u='order'
_AD='proCode' _t='state_grid'
_AC='loginAccount' _s='latestBillMonth'
_AB='list' _r='consNo_dst'
_AA='keyCode' _q='consNo'
_A9='querytypeCode' _p='authFlag'
_A8='01010049' _o='09'
_A7='account' _n='0101183'
_A6='daily_bill_list' _m='stepelect'
_A5='account_balance' _l='daily_bill_list'
_A4='provinceId'
_A3='userName'
_A2='acctId'
_A1='resultCode'
_A0='BCP_000026'
_z='app'
_y='WEBALIPAY_01'
_x='order'
_w='state_grid'
_v='latestBillMonth'
_u='quInfo'
_t='authFlag'
_s='09'
_r='0101183'
_q='stepelect'
_p='consNo'
_o=True
_n='0101154'
_m='monthBillList'
_l='bizrt'
_k='token' _k='token'
_j='timestamp' _j=False
_i=False _i='0101154'
_h='month_ele' _h='getday'
_g='errmsg' _g='bizrt'
_f='clearCache' _f='clearCache'
_e='SGAPP' _e='orgNo'
_d='orgNo' _d='timestamp'
_c='consNo_dst' _c='promotCode'
_b='promotCode' _b='errmsg'
_a='01' _a='01'
_Z='devciceId' _Z='SGAPP'
_Y='devciceIp' _Y='devciceId'
_X='proNo' _X='devciceIp'
_W='tenant' _W='proNo'
_V='member' _V='tenant'
_U='promotType' _U='member'
_T='getday' _T='promotType'
_S='srvrt' _S='userId'
_R='userId' _R='target'
_Q='subBusiTypeCode' _Q='srvrt'
_P='target' _P='subBusiTypeCode'
_O='serCat' _O='serialNo'
_N='serialNo' _N='serCat'
_M='0902' _M='srvCode'
_L='srvCode' _L='0902'
_K='busiTypeCode' _K='uscInfo'
_J='uscInfo' _J='busiTypeCode'
_I='channelCode' _I='channelCode'
_H='code' _H='code'
_G='1' _G=None
_F=None _F='1'
_E='source' _E='source'
_D='funcCode' _D='funcCode'
_C='errcode' _C='serviceCode'
_B='serviceCode' _B='errcode'
_A='data' _A='data'
import json,time,aiohttp,urllib.parse,datetime import json,time,aiohttp,urllib.parse,datetime
from.const import VERSION
from.utils.logger import LOGGER from.utils.logger import LOGGER
from.utils.store import async_save_to_store from.utils.store import async_save_to_store
from.utils.crypt import a,b,c,d,e from.utils.crypt import a,b,c,d,e
configuration={_J:{_V:_M,_Y:'',_Z:'',_W:_w},_E:_e,_P:'32101',_I:_M,_AP:_M,'toPublish':_a,'siteId':'2012000000033700',_L:'',_N:'',_D:'',_B:{_x:_n,'uploadPic':'0101296','pauseSCode':'0101250','pauseTCode':'0101251','listconsumers':'0101093','messageList':'0101343','submit':'0101003','sbcMsg':'0101210','powercut':'0104514','BkAuth01':'f15','BkAuth02':'f18','BkAuth03':'f02','BkAuth04':'f17','BkAuth05':'f05','BkAuth06':'f16','BkAuth07':'f01','BkAuth08':'f03'},'electricityArchives':{'servicecode':'0104505',_E:_M},'subscriptionList':{_L:'APP_SGPMS_05_030',_N:'22',_I:_M,_D:'22',_P:'-1'},'userInformation':{_B:'01008183',_E:_e},'userInform':{_B:_r,_E:_e},'elesum':{_I:_M,_D:_y,_b:_G,_U:_G,_B:'0101143',_E:_z},_A7:{_I:_M,_D:'WEBA1007200'},_Ak:{_E:_M,_P:'-1',_I:_s,_AP:_s,_B:_A8,_D:'WEBA40050000',_J:{_V:_M,_Y:'',_Z:'',_W:_w}},'doorAuth':{_E:_e,_B:'f04'},'xinZ':{_O:'101',_Al:'101','fJ_busiTypeCode':'102',_Am:'03','fJ_custType':'02',_An:_a,_Q:'',_D:_AQ,_x:_n,_E:_e,_A9:_G},'onedo':{_B:_AF,_E:_e,_D:_AQ,'queryType':'03'},'xinHuTongDian':{_O:'110',_K:'211',_Q:'21102',_D:'WEBA10071200',_I:_M,_E:_s,_B:_r},'company':{_O:'104',_D:_AQ,_An:'02',_A9:_G,_t:_G,_E:_e,_x:_n},'charge':{_I:_s,_D:'WEBA10071300',_AP:'0901',_O:'102',_Am:_a,_Al:'102'},'other':{_I:_s,_D:'WEBA10079700',_O:'129',_K:'999',_Q:'21501',_B:_A0,_L:'',_N:''},'vatchange':{'submit':'0101003',_K:'320',_Q:'',_O:'115',_D:'WEBA10074000',_t:_G},'bill':{_f:_G,_D:_y,_U:_G,_B:_A0},_q:{_I:_M,_D:_y,_U:_G,_f:_s,_B:_A0,_E:_z},_T:{_I:_M,_f:'11',_D:_y,_b:_G,_U:_G,_B:_A0,_E:_z},'mouthOut':{_I:_M,_f:'11',_D:_y,_b:_G,_U:_G,_B:_A0,_E:_z},'meter':{_O:'114',_K:'304',_D:'WEBA10071000',_Q:'',_B:_AF,_N:''},'complaint':{_K:'005','srvMode':_M,'anonymousFlag':'0','replyMode':_a,'retvisitFlag':_a},'report':{_K:'006'},'tradewinds':{_K:'019'},'somesay':{_K:'091'},'faultrepair':{_D:_Ao,_B:_r,_O:'111',_K:'001',_Q:'21505'},'electronicInvoice':{_O:'105',_K:'0'},'rename':{_B:_AF,_D:'WEBA10076100',_K:'210',_O:'109',_t:_G,'gh_busiTypeCode':'211','gh_subusi':'21101',_N:'',_L:''},'pause':{_Q:'',_B:_A8,_D:'WEBA10073600',_O:'107',_K:'203','jr_busi':'201',_N:'',_L:''},'capacityRecovery':{_B:_A8,_E:_e,_L:'',_N:'',_D:'WEBA10073700','busiTypeCode_stop':'204','busiTypeCode_less':'202',_K:'202',_Q:'',_O:'108',_AR:'5',_t:_G},'electricityPriceChange':{_B:_r,_K:'215',_Q:'21502',_O:'113',_t:_G,_AR:'15',_D:'WEBA10073900WEB',_L:'',_N:''},'electricityPriceStrategyChange':{_B:'01008183',_K:'215',_Q:'21506',_O:'160',_D:'WEBV00000517WEB',_L:'',_N:''},'eemandValueAdjustment':{_B:_r,_L:'',_N:'',_O:'112',_D:'WEBA10073800',_K:'215',_Q:'21504',_t:_G,_AR:'5','getMonthServiceCode':_AF},'businessProgress':{_B:_r,_L:_a,_D:'WEB01'},'increase':{_E:_e,_N:'',_L:'',_Ap:_A8,_B:_n,_x:_n,_D:_AS,_A9:_G,_O:'106',_K:'111',_Q:''},'fjincrea':{_O:'105',_K:'110',_Q:'',_E:_e,_D:_AS,_N:'',_L:'',_Ap:_A8,_B:_n,_x:_n,_A9:_G},'persIncrea':{_O:'105',_K:'109',_x:_n,_Q:'',_E:_e,_D:_AS,_A9:_G},'fgdChange':{_B:_r,_L:_a,_I:_s,_D:_Ao,_K:'215',_Q:'21505',_O:'111',_t:_G},'createOrder':{_I:_M,_D:_y,_L:'BCP_000001','chargeMode':'02','conType':_a,'bizTypeId':'BT_ELEC'},'largePopulation':{_K:'383',_D:'WEBA10076800',_Q:'',_L:'',_U:'',_b:'',_I:'0901',_O:'383',_B:'',_N:''},'biaoJiCode':{_B:'0104507',_E:'1704',_I:'1704'},'twoGuar':{_K:'402',_Q:'40201',_D:'web_twoGuar'},'electTrend':{_B:_Aq,_I:_M},'emergency':{_B:_Aq,_D:'A10000000',_I:_M},'infoPublic':{_B:'2545454',_E:_z}} configuration={_K:{_U:_L,_X:'',_Y:'',_V:_t},_E:_Z,_R:'32101',_I:_L,_AJ:_L,'toPublish':_a,'siteId':'2012000000033700',_M:'',_O:'',_D:'',_C:{_u:_i,'uploadPic':'0101296','pauseSCode':'0101250','pauseTCode':'0101251','listconsumers':'0101093','messageList':'0101343','submit':'0101003','sbcMsg':'0101210','powercut':'0104514','BkAuth01':'f15','BkAuth02':'f18','BkAuth03':'f02','BkAuth04':'f17','BkAuth05':'f05','BkAuth06':'f16','BkAuth07':'f01','BkAuth08':'f03'},'electricityArchives':{'servicecode':'0104505',_E:_L},'subscriptionList':{_M:'APP_SGPMS_05_030',_O:'22',_I:_L,_D:'22',_R:'-1'},'userInformation':{_C:'01008183',_E:_Z},'userInform':{_C:_n,_E:_Z},'elesum':{_I:_L,_D:_v,_c:_F,_T:_F,_C:'0101143',_E:_w},_A1:{_I:_L,_D:'WEBA1007200'},_AS:{_E:_L,_R:'-1',_I:_o,_AJ:_o,_C:_A2,_D:'WEBA40050000',_K:{_U:_L,_X:'',_Y:'',_V:_t}},'doorAuth':{_E:_Z,_C:'f04'},'xinZ':{_N:'101',_AT:'101','fJ_busiTypeCode':'102',_AU:'03','fJ_custType':'02',_AV:_a,_P:'',_D:_AK,_u:_i,_E:_Z,_A3:_F},'onedo':{_C:_A9,_E:_Z,_D:_AK,'queryType':'03'},'xinHuTongDian':{_N:'110',_J:'211',_P:'21102',_D:'WEBA10071200',_I:_L,_E:_o,_C:_n},'company':{_N:'104',_D:_AK,_AV:'02',_A3:_F,_p:_F,_E:_Z,_u:_i},'charge':{_I:_o,_D:'WEBA10071300',_AJ:'0901',_N:'102',_AU:_a,_AT:'102'},'other':{_I:_o,_D:'WEBA10079700',_N:'129',_J:'999',_P:'21501',_C:_x,_M:'',_O:''},'vatchange':{'submit':'0101003',_J:'320',_P:'',_N:'115',_D:'WEBA10074000',_p:_F},'bill':{_f:_F,_D:_v,_T:_F,_C:_x},_m:{_I:_L,_D:_v,_T:_F,_f:_o,_C:_x,_E:_w},_h:{_I:_L,_f:'11',_D:_v,_c:_F,_T:_F,_C:_x,_E:_w},'mouthOut':{_I:_L,_f:'11',_D:_v,_c:_F,_T:_F,_C:_x,_E:_w},'meter':{_N:'114',_J:'304',_D:'WEBA10071000',_P:'',_C:_A9,_O:''},'complaint':{_J:'005','srvMode':_L,'anonymousFlag':'0','replyMode':_a,'retvisitFlag':_a},'report':{_J:'006'},'tradewinds':{_J:'019'},'somesay':{_J:'091'},'faultrepair':{_D:_AW,_C:_n,_N:'111',_J:'001',_P:'21505'},'electronicInvoice':{_N:'105',_J:'0'},'rename':{_C:_A9,_D:'WEBA10076100',_J:'210',_N:'109',_p:_F,'gh_busiTypeCode':'211','gh_subusi':'21101',_O:'',_M:''},'pause':{_P:'',_C:_A2,_D:'WEBA10073600',_N:'107',_J:'203','jr_busi':'201',_O:'',_M:''},'capacityRecovery':{_C:_A2,_E:_Z,_M:'',_O:'',_D:'WEBA10073700','busiTypeCode_stop':'204','busiTypeCode_less':'202',_J:'202',_P:'',_N:'108',_AL:'5',_p:_F},'electricityPriceChange':{_C:_n,_J:'215',_P:'21502',_N:'113',_p:_F,_AL:'15',_D:'WEBA10073900WEB',_M:'',_O:''},'electricityPriceStrategyChange':{_C:'01008183',_J:'215',_P:'21506',_N:'160',_D:'WEBV00000517WEB',_M:'',_O:''},'eemandValueAdjustment':{_C:_n,_M:'',_O:'',_N:'112',_D:'WEBA10073800',_J:'215',_P:'21504',_p:_F,_AL:'5','getMonthServiceCode':_A9},'businessProgress':{_C:_n,_M:_a,_D:'WEB01'},'increase':{_E:_Z,_O:'',_M:'',_AX:_A2,_C:_i,_u:_i,_D:_AM,_A3:_F,_N:'106',_J:'111',_P:''},'fjincrea':{_N:'105',_J:'110',_P:'',_E:_Z,_D:_AM,_O:'',_M:'',_AX:_A2,_C:_i,_u:_i,_A3:_F},'persIncrea':{_N:'105',_J:'109',_u:_i,_P:'',_E:_Z,_D:_AM,_A3:_F},'fgdChange':{_C:_n,_M:_a,_I:_o,_D:_AW,_J:'215',_P:'21505',_N:'111',_p:_F},'createOrder':{_I:_L,_D:_v,_M:'BCP_000001','chargeMode':'02','conType':_a,'bizTypeId':'BT_ELEC'},'largePopulation':{_J:'383',_D:'WEBA10076800',_P:'',_M:'',_T:'',_c:'',_I:'0901',_N:'383',_C:'',_O:''},'biaoJiCode':{_C:'0104507',_E:'1704',_I:'1704'},'twoGuar':{_J:'402',_P:'40201',_D:'web_twoGuar'},'electTrend':{_C:_AY,_I:_L},'emergency':{_C:_AY,_D:'A10000000',_I:_L},'infoPublic':{_C:'2545454',_E:_w}}
appKey='3def6c365d284881bf1a9b2b502ee68c' appKey='3def6c365d284881bf1a9b2b502ee68c'
appSecret='ab7357dae64944a197ace37398897f64' appSecret='ab7357dae64944a197ace37398897f64'
baseApi='https://www.95598.cn/api' baseApi='https://www.95598.cn/api'
@@ -141,13 +120,13 @@ get_door_number_api='/osg-open-uc0001/member/c9/f02'
get_door_balance_api='/osg-open-bc0001/member/c05/f01' get_door_balance_api='/osg-open-bc0001/member/c05/f01'
get_door_bill_api='/osg-open-bc0001/member/c01/f02' get_door_bill_api='/osg-open-bc0001/member/c01/f02'
get_door_ladder_api='/osg-open-bc0001/member/c04/f03' get_door_ladder_api='/osg-open-bc0001/member/c04/f03'
getJiaoFeiRecordApi=_Ar getJiaoFeiRecordApi=_AZ
get_door_daily_bill_api=_Ar get_door_daily_bill_api=_AZ
sessionIdControlApiList=[get_qr_code_api,get_qr_code_status_api,get_qr_code_token_api,send_code_api,code_login_api] sessionIdControlApiList=[get_qr_code_api,get_qr_code_status_api,get_qr_code_token_api,send_code_api,code_login_api]
keyCodeControlApiList=[get_qr_code_status_api,get_qr_code_token_api,send_code_api,code_login_api,getCertificationApi,get_request_authorize_api,get_web_token_api,refresh_web_token_api,get_door_number_api,get_door_balance_api,get_door_bill_api,get_door_ladder_api,getJiaoFeiRecordApi,get_door_daily_bill_api] keyCodeControlApiList=[get_qr_code_status_api,get_qr_code_token_api,send_code_api,code_login_api,getCertificationApi,get_request_authorize_api,get_web_token_api,refresh_web_token_api,get_door_number_api,get_door_balance_api,get_door_bill_api,get_door_ladder_api,getJiaoFeiRecordApi,get_door_daily_bill_api]
authControlApiList=[get_door_number_api,get_door_balance_api,get_door_bill_api,get_door_ladder_api,getJiaoFeiRecordApi,get_door_daily_bill_api] authControlApiList=[get_door_number_api,get_door_balance_api,get_door_bill_api,get_door_ladder_api,getJiaoFeiRecordApi,get_door_daily_bill_api]
tControlApiList=[getCertificationApi,get_door_balance_api,get_door_bill_api,get_door_ladder_api,getJiaoFeiRecordApi,get_door_daily_bill_api] tControlApiList=[getCertificationApi,get_door_balance_api,get_door_bill_api,get_door_ladder_api,getJiaoFeiRecordApi,get_door_daily_bill_api]
def json_dumps(data):return json.dumps(data,separators=(',',':'),ensure_ascii=_i) def json_dumps(data):return json.dumps(data,separators=(',',':'),ensure_ascii=_j)
def normal_round(num,ndigits=0): def normal_round(num,ndigits=0):
A=ndigits A=ndigits
if A==0:return int(num+.5) if A==0:return int(num+.5)
@@ -158,19 +137,19 @@ def catchFloat(data,key):
except:return 0 except:return 0
else:return 0 else:return 0
class StateGridDataClient: class StateGridDataClient:
hass=_F;session=_F;dataVersion=_F;keyCode=_F;publicKey=_F;need_login=_i;retry_times=0;phone=_F;codeKey=_F;serialNo=_F;qrCodeSerial=_F;userInfo=_F;accountInfo=_F;powerUserList=_F;doorAccountDict={};cookie=[];timestamp=int(time.time()*1000);accessToken=_F;refreshToken=_F;token=_F;expirationDate=_F;refresh_interval=6;is_debug=_i hass=_G;session=_G;keyCode=_G;publicKey=_G;need_login=_j;phone=_G;codeKey=_G;serialNo=_G;qrCodeSerial=_G;userInfo=_G;accountInfo=_G;powerUserList=_G;doorAccountDict={};cookie=[];timestamp=int(time.time()*1000);accessToken=_G;refreshToken=_G;token=_G;expirationDate=_G;refresh_interval=6;is_debug=_j
def __init__(A,hass,config=_F): def __init__(A,hass,config=_G):
B=config;A.hass=hass;C=aiohttp.TCPConnector(ssl=_i);D=aiohttp.CookieJar(quote_cookie=_o);A.session=aiohttp.ClientSession(cookie_jar=D,connector=C) B=config;A.hass=hass;C=aiohttp.TCPConnector(ssl=_j);D=aiohttp.CookieJar(quote_cookie=_y);A.session=aiohttp.ClientSession(cookie_jar=D,connector=C)
if B is not _F: if B is not _G:
try:A.keyCode=B[_AA];A.publicKey=B[_AT];A.accessToken=B[_As];A.refreshToken=B[_At];A.token=B[_k];A.userInfo=B[_AG];A.powerUserList=B[_AU];A.doorAccountDict=B[_Au];A.refresh_interval=B[_Av];A.is_debug=B['is_debug'];A.dataVersion=B[_Aw] try:A.keyCode=B[_A4];A.publicKey=B[_AN];A.accessToken=B[_Aa];A.refreshToken=B[_Ab];A.token=B[_k];A.userInfo=B[_AA];A.powerUserList=B[_AO];A.doorAccountDict=B[_Ac];A.refresh_interval=B[_Ad];A.is_debug=B['is_debug']
except Exception as E:LOGGER.error(E) except Exception as E:LOGGER.error(E)
async def save_data(B):A={};A[_AA]=B.keyCode;A[_AT]=B.publicKey;A[_As]=B.accessToken;A[_At]=B.refreshToken;A[_k]=B.token;A[_AG]=B.userInfo;A[_AU]=B.powerUserList;A[_Au]=B.doorAccountDict;A[_Av]=B.refresh_interval;A['is_debug']=B.is_debug;A[_Aw]=VERSION;await async_save_to_store(B.hass,'state_grid.config',A) async def save_data(A):B={};B[_A4]=A.keyCode;B[_AN]=A.publicKey;B[_Aa]=A.accessToken;B[_Ab]=A.refreshToken;B[_k]=A.token;B[_AA]=A.userInfo;B[_AO]=A.powerUserList;B[_Ac]=A.doorAccountDict;B[_Ad]=A.refresh_interval;B['is_debug']=A.is_debug;await async_save_to_store(A.hass,'state_grid.config',B)
def encrypt_post_data(A,data):B={_Ax:A.accessToken[len(A.accessToken)//2:]if A.accessToken else'','_t':A.token[len(A.token)//2:]if A.token else'','_data':data,_j:A.timestamp};return A.encrypt_wapper_data(B) def encrypt_post_data(A,data):B={_Ae:A.accessToken[len(A.accessToken)//2:]if A.accessToken else'','_t':A.token[len(A.token)//2:]if A.token else'','_data':data,_d:A.timestamp};return A.encrypt_wapper_data(B)
def encrypt_wapper_data(A,data):B=a(json_dumps(data),A.keyCode);return{_A:B+c(B+str(A.timestamp)),_AH:d(A.keyCode,A.publicKey),_j:str(A.timestamp)} def encrypt_wapper_data(A,data):B=a(json_dumps(data),A.keyCode);return{_A:B+c(B+str(A.timestamp)),_AB:d(A.keyCode,A.publicKey),_d:str(A.timestamp)}
def handle_request_result_message(E,api,result): def handle_request_result_message(E,api,result):
D='message';C='resultMessage';A=result;B=_F D='message';C='resultMessage';A=result;B=_G
if _A in A and _S in A[_A]and C in A[_A][_S]:B=A[_A][_S][C] if _A in A and _Q in A[_A]and C in A[_A][_Q]:B=A[_A][_Q][C]
elif _S in A and C in A[_S]:B=A[_S][C] elif _Q in A and C in A[_Q]:B=A[_Q][C]
elif D in A:B=A[D] elif D in A:B=A[D]
else:B=json_dumps(A) else:B=json_dumps(A)
if E.is_debug:LOGGER.error(api+': '+B);LOGGER.error(json_dumps(A)) if E.is_debug:LOGGER.error(api+': '+B);LOGGER.error(json_dumps(A))
@@ -181,24 +160,24 @@ class StateGridDataClient:
A=B[_H] A=B[_H]
if 10015==A or 10108==A or 10009==A or 10207==A or 10005==A or 10010==A or 30010==A or 10002==A: if 10015==A or 10108==A or 10009==A or 10207==A or 10005==A or 10010==A or 30010==A or 10002==A:
await C.__refresh_token() await C.__refresh_token()
if C.need_login is _o:return B if C.need_login is _y:return B
else:return await C.__fetch(api,data) else:return await C.__fetch(api,data)
else:return B else:return B
async def __fetch(B,api,data,header=_F): async def __fetch(B,api,data,header=_G):
T='encryptData';S='464606a4-184c-4beb-b442-2ab7761d0796';R='key_code';Q='state';P='sign';O='grant_type';N='application/json;charset=UTF-8';M='Content-Type';L=header;K='client_secret';I='client_id';E=api;B.timestamp=int(time.time()*1000);D=B.timestamp T='encryptData';S='464606a4-184c-4beb-b442-2ab7761d0796';R='key_code';Q='state';P='sign';O='grant_type';N='application/json;charset=UTF-8';M='Content-Type';L=header;K='client_secret';I='client_id';E=api;B.timestamp=int(time.time()*1000);D=B.timestamp
if B.keyCode is _F:B.keyCode=e(32,16,2) if B.keyCode is _G:B.keyCode=e(32,16,2)
F=B.keyCode;G={'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36','Accept':N,M:N,'version':'1.0',_E:'0901',_j:str(D),'wsgwType':'web','appKey':appKey};A=data F=B.keyCode;G={'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36','Accept':N,M:N,'version':'1.0',_E:'0901',_d:str(D),'wsgwType':'web','appKey':appKey};A=data
if E==get_request_key_api:A={I:appKey,K:appSecret};H=a(json_dumps(A),F);A={_A:H+c(H+str(D)),_AH:d(F,'042BC7AD510BF9793B7744C8854C56A8C95DD1027EE619247A332EC6ED5B279F435A23D62441FE861F4B0C963347ECD5792F380B64CA084BE8BE41151F8B8D19C8'),I:appKey,_j:str(D)} if E==get_request_key_api:A={I:appKey,K:appSecret};H=a(json_dumps(A),F);A={_A:H+c(H+str(D)),_AB:d(F,'042BC7AD510BF9793B7744C8854C56A8C95DD1027EE619247A332EC6ED5B279F435A23D62441FE861F4B0C963347ECD5792F380B64CA084BE8BE41151F8B8D19C8'),I:appKey,_d:str(D)}
elif E==get_qr_code_api:A={_Ax:'','_t':'','_data':A,_j:D} elif E==get_qr_code_api:A={_Ae:'','_t':'','_data':A,_d:D}
elif E==get_request_authorize_api: elif E==get_request_authorize_api:
A={I:appKey,'response_type':_H,_Ay:'/test',_j:D,'rsi':B.token};A=urllib.parse.urlencode(A);G[M]='application/x-www-form-urlencoded; charset=UTF-8';G[_AA]=F A={I:appKey,'response_type':_H,_Af:'/test',_d:D,'rsi':B.token};A=urllib.parse.urlencode(A);G[M]='application/x-www-form-urlencoded; charset=UTF-8';G[_A4]=F
async with B.session.post(baseApi+E,data=A,headers=G)as J:B.session.cookie_jar.update_cookies(J.cookies);C=await J.json();C=b(C[_A],B.token);C=json.loads(C);return C async with B.session.post(baseApi+E,data=A,headers=G)as J:B.session.cookie_jar.update_cookies(J.cookies);C=await J.json();C=b(C[_A],B.token);C=json.loads(C);return C
elif E==get_web_token_api:A={O:'authorization_code',P:c(appKey+str(D)),K:appSecret,Q:S,R:F,I:appKey,_j:D,_H:A[_H]};H=a(json_dumps(A),F);A={_A:H+c(H+str(D)),_AH:d(F,B.publicKey),_j:str(D)} elif E==get_web_token_api:A={O:'authorization_code',P:c(appKey+str(D)),K:appSecret,Q:S,R:F,I:appKey,_d:D,_H:A[_H]};H=a(json_dumps(A),F);A={_A:H+c(H+str(D)),_AB:d(F,B.publicKey),_d:str(D)}
elif E==refresh_web_token_api:A={O:_AI,P:c(appKey+str(D)),K:appSecret,Q:S,R:F,I:appKey,_j:D,_AI:B.refreshToken};H=a(json_dumps(A),F);A={_A:H+c(H+str(D)),_AH:d(F,B.publicKey),_j:str(D)};E=get_web_token_api elif E==refresh_web_token_api:A={O:_AC,P:c(appKey+str(D)),K:appSecret,Q:S,R:F,I:appKey,_d:D,_AC:B.refreshToken};H=a(json_dumps(A),F);A={_A:H+c(H+str(D)),_AB:d(F,B.publicKey),_d:str(D)};E=get_web_token_api
else:A=B.encrypt_post_data(A) else:A=B.encrypt_post_data(A)
if L is not _F:G.update(L) if L is not _G:G.update(L)
if E in sessionIdControlApiList:G['sessionId']='web'+str(D) if E in sessionIdControlApiList:G['sessionId']='web'+str(D)
if E in keyCodeControlApiList:G[_AA]=F if E in keyCodeControlApiList:G[_A4]=F
if E in authControlApiList:G['Authorization']='Bearer '+B.accessToken[:len(B.accessToken)//2] if E in authControlApiList:G['Authorization']='Bearer '+B.accessToken[:len(B.accessToken)//2]
if E in tControlApiList:G['t']=B.token[:len(B.token)//2] if E in tControlApiList:G['t']=B.token[:len(B.token)//2]
async with B.session.post(baseApi+E,json=A,headers=G)as J: async with B.session.post(baseApi+E,json=A,headers=G)as J:
@@ -208,185 +187,164 @@ class StateGridDataClient:
if T in C:C=b(C[T],F);C=json.loads(C) if T in C:C=b(C[T],F);C=json.loads(C)
return C return C
async def __get_request_key(A): async def __get_request_key(A):
A.keyCode=_F;B=await A.__fetch(get_request_key_api,{});C=A.handle_request_result_message('get_request_key_api',B) A.keyCode=_G;B=await A.__fetch(get_request_key_api,{});C=A.handle_request_result_message('get_request_key_api',B)
if B[_H]==_G:A.keyCode=B[_A][_AA];A.publicKey=B[_A][_AT];return{_C:0} if B[_H]==_F:A.keyCode=B[_A][_A4];A.publicKey=B[_A][_AN];return{_B:0}
return{_C:1,_g:C} return{_B:1,_b:C}
async def __get_qr_code(B): async def __get_qr_code(B):
C={_J:{_Y:'',_W:_w,_V:_M,_Z:''},_u:{'optType':_a,_N:e(28,10,1)}};A=await B.__fetch(get_qr_code_api,C);D=B.handle_request_result_message('get_qr_code_api',A) C={_K:{_X:'',_V:_t,_U:_L,_Y:''},_z:{'optType':_a,_O:e(28,10,1)}};A=await B.__fetch(get_qr_code_api,C);D=B.handle_request_result_message('get_qr_code_api',A)
if A[_H]==1: if A[_H]==1:
if A[_A]and A[_A][_S]and A[_A][_S][_A1]==_AJ:B.qrCodeSerial=A[_A][_l][_Az];E=A[_A][_l]['qrCode'];return{_C:0,_A:E} if A[_A]and A[_A][_Q]and A[_A][_Q][_A0]==_AD:B.qrCodeSerial=A[_A][_g][_Ag];E=A[_A][_g]['qrCode'];return{_B:0,_A:E}
return{_C:1,_g:D} return{_B:1,_b:D}
async def __get_qr_code_status(B): async def __get_qr_code_status(B):
C={_l:{_Az:B.qrCodeSerial}};D={_k:'98'+e(10,10,1)};A=await B.__fetch(get_qr_code_status_api,C,D);E=B.handle_request_result_message('get_qr_code_status_api',A) C={_g:{_Ag:B.qrCodeSerial}};D={_k:'98'+e(10,10,1)};A=await B.__fetch(get_qr_code_status_api,C,D);E=B.handle_request_result_message('get_qr_code_status_api',A)
if _H in A and A[_H]==1: if _H in A and A[_H]==1:
if _A in A and A[_A]!='null':B.token=A[_A];return{_C:0} if _A in A and A[_A]!='null':B.token=A[_A];return{_B:0}
else:return{_C:1,_g:'未使用网上国网 App 扫码或确认登录'} else:return{_B:1,_b:'未使用网上国网 App 扫码或确认登录'}
return{_C:1,_g:E} return{_B:1,_b:E}
async def __get_qr_code_token(B): async def __get_qr_code_token(B):
C={_J:{_W:_w,_V:_M,'isEncrypt':_o},_k:B.token};A=await B.__fetch(get_qr_code_token_api,C);D=B.handle_request_result_message('get_qr_code_token_api',A) C={_K:{_V:_t,_U:_L,'isEncrypt':_y},_k:B.token};A=await B.__fetch(get_qr_code_token_api,C);D=B.handle_request_result_message('get_qr_code_token_api',A)
if _S in A and _A1 in A[_S]and A[_S][_A1]==_AJ:B.userInfo=A[_l][_AG];return{_C:0} if _Q in A and _A0 in A[_Q]and A[_Q][_A0]==_AD:B.userInfo=A[_g][_AA];return{_B:0}
return{_C:1,_g:D} return{_B:1,_b:D}
async def __send_code(B,phone): async def __send_code(B,phone):
C=phone;B.phone=C;D={_J:{_Y:'',_W:_w,_V:_M,_Z:''},_u:{'sendType':'0',_A7:C,_A_:'login','accountType':''},'Channels':'web'};A=await B.__fetch(send_code_api,D);E=B.handle_request_result_message('send_code_api',A) C=phone;B.phone=C;D={_K:{_X:'',_V:_t,_U:_L,_Y:''},_z:{'sendType':'0',_A1:C,_Ah:'login','accountType':''},'Channels':'web'};A=await B.__fetch(send_code_api,D);E=B.handle_request_result_message('send_code_api',A)
if A[_H]==1: if A[_H]==1:
if A[_A]and A[_A][_S]and A[_A][_S][_A1]==_AJ:B.codeKey=A[_A][_l]['codeKey'];return{_C:0} if A[_A]and A[_A][_Q]and A[_A][_Q][_A0]==_AD:B.codeKey=A[_A][_g]['codeKey'];return{_B:0}
return{_C:1,_g:E} return{_B:1,_b:E}
async def __verfiy_code(A,code): async def __verfiy_code(A,code):
C={_J:{_Y:'',_W:_w,_V:_M,_Z:''},_u:{_A7:A.phone,_A_:'login',_H:code,'optSys':'ios','pushId':'00000','codeKey':A.codeKey},'Channels':'web'};B=await A.__fetch(code_login_api,C);D=A.handle_request_result_message('code_login_api',B) C={_K:{_X:'',_V:_t,_U:_L,_Y:''},_z:{_A1:A.phone,_Ah:'login',_H:code,'optSys':'ios','pushId':'00000','codeKey':A.codeKey},'Channels':'web'};B=await A.__fetch(code_login_api,C);D=A.handle_request_result_message('code_login_api',B)
if _S in B and _A1 in B[_S]and B[_S][_A1]==_AJ:A.token=B[_l][_k];A.userInfo=B[_l][_AG][0];return{_C:0} if _Q in B and _A0 in B[_Q]and B[_Q][_A0]==_AD:A.token=B[_g][_k];A.userInfo=B[_g][_AA][0];return{_B:0}
return{_C:1,_g:D} return{_B:1,_b:D}
async def __get_request_authorize(B): async def __get_request_authorize(B):
A=await B.__fetch(get_request_authorize_api,{});E=B.handle_request_result_message('get_request_authorize_api',A) A=await B.__fetch(get_request_authorize_api,{});E=B.handle_request_result_message('get_request_authorize_api',A)
if _H in A and A[_H]==_G:C=A[_A][_Ay];D=C.rfind('code=');B.authorizeCode=C[D+5:D+5+32];return{_C:0} if _H in A and A[_H]==_F:C=A[_A][_Af];D=C.rfind('code=');B.authorizeCode=C[D+5:D+5+32];return{_B:0}
return{_C:1,_g:E} return{_B:1,_b:E}
async def __get_web_token(A): async def __get_web_token(A):
C={_H:A.authorizeCode};B=await A.__fetch(get_web_token_api,C);D=A.handle_request_result_message('get_web_token_api',B) C={_H:A.authorizeCode};B=await A.__fetch(get_web_token_api,C);D=A.handle_request_result_message('get_web_token_api',B)
if _H in B and B[_H]==_G:A.accessToken=B[_A][_B0];A.refreshToken=B[_A][_AI];return{_C:0} if _H in B and B[_H]==_F:A.accessToken=B[_A][_Ai];A.refreshToken=B[_A][_AC];return{_B:0}
return{_C:1,_g:D} return{_B:1,_b:D}
async def __refresh_web_token(B): async def __refresh_web_token(B):
A=await B.__fetch(refresh_web_token_api,{});C=B.handle_request_result_message('refresh_web_token_api',A) A=await B.__fetch(refresh_web_token_api,{});C=B.handle_request_result_message('refresh_web_token_api',A)
if _H in A and A[_H]==_G:B.accessToken=A[_A][_B0];B.refreshToken=A[_A][_AI];return{_C:0} if _H in A and A[_H]==_F:B.accessToken=A[_A][_Ai];B.refreshToken=A[_A][_AC];return{_B:0}
return{_C:1,_g:C} return{_B:1,_b:C}
async def __get_door_number(A): async def __get_door_number(C):
B=configuration[_Ak];G={_B:B[_B],_E:B[_E],_P:B[_P],_J:{_V:B[_J][_V],_Y:B[_J][_Y],_Z:B[_J][_Z],_W:B[_J][_W]},_u:{_R:A.userInfo[_R]},_k:A.token};C=await A.__fetch_safe(get_door_number_api,G);H=A.handle_request_result_message('get_door_number_api',C) A=configuration[_AS];D={_C:A[_C],_E:A[_E],_R:A[_R],_K:{_U:A[_K][_U],_X:A[_K][_X],_Y:A[_K][_Y],_V:A[_K][_V]},_z:{_S:C.userInfo[_S]},_k:C.token};B=await C.__fetch_safe(get_door_number_api,D);E=C.handle_request_result_message('get_door_number_api',B)
if _H in C and C[_H]==1 and _A in C and _l in C[_A]: if _H in B and B[_H]==1 and _A in B and _g in B[_A]:C.powerUserList=B[_A][_g][_AO];return{_B:0}
D={} return{_B:1,_b:E}
if A.powerUserList is not _F:D={A[_c]:A for A in A.powerUserList}
E=[]
for F in C[_A][_l][_AU]:
if F[_c]in D:E.append(D[F[_c]])
else:E.append(F)
A.powerUserList=E;return{_C:0}
return{_C:1,_g:H}
async def __get_door_balance(B,door_account): async def __get_door_balance(B,door_account):
A=door_account;E={_A:{_L:'',_N:'',_I:configuration[_A7][_I],_D:configuration[_A7][_D],_A2:B.userInfo[_R],_A3:B.userInfo.get(_AC,B.userInfo.get('nickname',_F)),_U:_G,_b:_G,_AV:B.userInfo[_R],_AB:[{'consNoSrc':A[_c],_AD:A.get(_X,A.get(_A4,_F)),'sceneType':A.get('consSortCode',A.get('elecTypeCode',_F)),_p:A[_p],_d:A[_d]}]},_B:'0101143',_E:configuration[_E],_P:A.get(_X,A.get(_A4,_F))};C=await B.__fetch_safe(get_door_balance_api,E);B.handle_request_result_message('get_door_balance_api',C) A=door_account;E={_A:{_M:'',_O:'',_I:configuration[_A1][_I],_D:configuration[_A1][_D],_A5:B.userInfo[_S],_A6:B.userInfo.get(_AE,B.userInfo.get('nickname',_G)),_T:_F,_c:_F,_AP:B.userInfo[_S],_A7:[{'consNoSrc':A[_r],_AF:A.get(_W,A.get(_AG,_G)),'sceneType':A.get('consSortCode',A.get('elecTypeCode',_G)),_q:A[_q],_e:A[_e]}]},_C:'0101143',_E:configuration[_E],_R:A.get(_W,A.get(_AG,_G))};C=await B.__fetch_safe(get_door_balance_api,E);B.handle_request_result_message('get_door_balance_api',C)
if _H in C and C[_H]==1 and _A in C and _AB in C[_A]: if _H in C and C[_H]==1 and _A in C and _A7 in C[_A]:
D=C[_A][_AB] D=C[_A][_A7]
if len(D)!=0:A[_A5]=D[0] if len(D)!=0:A[_A8]=D[0]
async def __get_door_bill(C,door_account,monthDate): async def __get_door_bill(C,door_account,year):
I='dataInfo';G='mothEleList';E=monthDate;A=door_account;J={_A:{_A2:C.userInfo[_R],_I:configuration[_I],_f:'11',_AK:A[_B2],_D:'ALIPAY_01',_d:A[_d],_AD:A[_X],_b:_G,_U:_G,_N:'',_L:'',_A3:'',_B1:A[_X],_AV:C.userInfo[_R],_p:A[_p],_AW:E.year},_B:_A0,_E:_z,_P:A[_X]};B=await C.__fetch_safe(get_door_bill_api,J);C.handle_request_result_message('get_door_bill_api',B) E='dataInfo';D='mothEleList';B=door_account;F={_A:{_A5:C.userInfo[_S],_I:configuration[_I],_f:'11',_AQ:B[_Al],_D:'ALIPAY_01',_e:B[_e],_AF:B[_W],_c:_F,_T:_F,_O:'',_M:'',_A6:'',_Aj:B[_W],_AP:C.userInfo[_S],_q:B[_q],_Ak:year},_C:_x,_E:_w,_R:B[_W]};A=await C.__fetch_safe(get_door_bill_api,F);C.handle_request_result_message('get_door_bill_api',A)
if _H in B and B[_H]==1 and _A in B: if _H in A and A[_H]==1 and _A in A:
if I in B[_A]:A[_AL]=B[_A][I] if E in A[_A]:B[_AH]=A[_A][E]
if G in B[_A]: if D in A[_A]:
if _AE not in A or A[_AE]!=E.year:A[_m]=B[_A][G];A[_AE]=E.year B[_AI]=A[_A][D]
else: if len(A[_A][D])!=0:B[_s]=A[_A][D][-1]
F={A.month:A for A in A[_m]};H=B[_A][G] async def __get_door_ladder(B,door_account,month):
for D in H: F='ladder_flag';E=month;A=door_account;G=A[_r];H={_A:{_I:configuration[_m][_I],_D:configuration[_m][_D],_T:configuration[_m][_T],_f:configuration[_m][_f],_q:A[_r],_c:A[_W],_e:A[_e],'queryDate':E,_Aj:A[_W],_AQ:A[_Al],_AP:B.userInfo[_S],_O:'',_M:'',_A6:B.userInfo[_AE],_A5:B.userInfo[_S]},_C:configuration[_m][_C],_E:configuration[_m][_E],_R:A[_W]};C=await B.__fetch(get_door_ladder_api,H);I=B.handle_request_result_message('get_door_ladder_api',C)
if D.month in F and _h in F[D.month]:D[_h]=F[D.month][_h] if _H in C and C[_H]==1 and _A in C and _A7 in C[_A]:
A[_m]=H D=C[_A][_A7]
if len(A[_m])>0:A[_v]=A[_m][-1] if len(D)!=0:
async def __get_door_ladder(C,door_account,monthBill): D=D[0];D[_AR]=E
E=monthBill;A=door_account;I=A[_c];F=datetime.datetime.strptime(E[_AM],'%Y%m');G=f"{F.year}-{F.month:02d}";H={_A:{_I:configuration[_q][_I],_D:configuration[_q][_D],_U:configuration[_q][_U],_f:configuration[_q][_f],_p:A[_c],_b:A[_X],_d:A[_d],'queryDate':G,_B1:A[_X],_AK:A[_B2],_AV:C.userInfo[_R],_N:'',_L:'',_A3:C.userInfo[_AC],_A2:C.userInfo[_R]},_B:configuration[_q][_B],_E:configuration[_q][_E],_P:A[_X]};B=await C.__fetch(get_door_ladder_api,H);J=C.handle_request_result_message('get_door_ladder_api',B) if D['electricParticulars']['levelFlag']=='2':A[F]=1
if _H in B and B[_H]==1 and _A in B and _AB in B[_A]: else:A[F]=0
D=B[_A][_AB] B.doorAccountDict[G]['ladder']=D
if len(D)!=0:D=D[0];E['ladder']=D
async def __get_door_mouth_daily_bill(B,door_account,monthBill):
F=monthBill;A=door_account;N=A[_c];L=datetime.datetime.strptime(F[_AM],'%Y%m');M={_AX:{_B:configuration[_B],_E:configuration[_E],_P:configuration[_P],_J:{_V:configuration[_J][_V],_Y:configuration[_J][_Y],_Z:configuration[_J][_Z],_W:configuration[_J][_W]},_u:{_R:B.userInfo[_R]},_k:B.token},_AY:{_A:{_A2:B.userInfo[_R],_p:A[_c],_AK:_a,'endTime':F['endDate'],_d:A[_d],_AW:str(L.year),_AD:A.get(_X,A.get(_A4,_F)),_N:'',_L:'',_B3:F['begDate'],_A3:B.userInfo[_AC],_D:configuration[_T][_D],_I:configuration[_T][_I],_f:configuration[_T][_f],_b:configuration[_T][_b],_U:configuration[_T][_U]},_B:configuration[_T][_B],_E:configuration[_T][_E],_P:A.get(_X,A.get(_A4,_F))},_AZ:'010103'};C=await B.__fetch_safe(get_door_daily_bill_api,M);O=B.handle_request_result_message(_B4,C)
if _H in C and C[_H]==1 and _A in C and _AN in C[_A]:
G=0;H=0;I=0;J=0;K=0
for D in C[_A][_AN]:P=datetime.datetime.strptime(D['day'],_Aa);G+=catchFloat(D,_AO);H+=catchFloat(D,_Ab);I+=catchFloat(D,_Ac);J+=catchFloat(D,_Ad);K+=catchFloat(D,_Ae)
E={};E[_Af]=normal_round(G,2);E[_Ag]=normal_round(H,2);E[_Ah]=normal_round(I,2);E[_Ai]=normal_round(J,2);E[_Aj]=normal_round(K,2);F[_h]=E
async def __get_door_daily_bill(B,door_account,year,start_date,end_date): async def __get_door_daily_bill(B,door_account,year,start_date,end_date):
A=door_account;D={_AX:{_B:configuration[_B],_E:configuration[_E],_P:configuration[_P],_J:{_V:configuration[_J][_V],_Y:configuration[_J][_Y],_Z:configuration[_J][_Z],_W:configuration[_J][_W]},_u:{_R:B.userInfo[_R]},_k:B.token},_AY:{_A:{_A2:B.userInfo[_R],_p:A[_c],_AK:_a,'endTime':end_date,_d:A[_d],_AW:year,_AD:A.get(_X,A.get(_A4,_F)),_N:'',_L:'',_B3:start_date,_A3:B.userInfo[_AC],_D:configuration[_T][_D],_I:configuration[_T][_I],_f:configuration[_T][_f],_b:configuration[_T][_b],_U:configuration[_T][_U]},_B:configuration[_T][_B],_E:configuration[_T][_E],_P:A.get(_X,A.get(_A4,_F))},_AZ:'010103'};C=await B.__fetch_safe(get_door_daily_bill_api,D);E=B.handle_request_result_message(_B4,C) D='sevenEleList';A=door_account;E={'params1':{_C:configuration[_C],_E:configuration[_E],_R:configuration[_R],_K:{_U:configuration[_K][_U],_X:configuration[_K][_X],_Y:configuration[_K][_Y],_V:configuration[_K][_V]},_z:{_S:B.userInfo[_S]},_k:B.token},'params3':{_A:{_A5:B.userInfo[_S],_q:A[_r],_AQ:_a,'endTime':end_date,_e:A[_e],_Ak:year,_AF:A.get(_W,A.get(_AG,_G)),_O:'',_M:'','startTime':start_date,_A6:B.userInfo[_AE],_D:configuration[_h][_D],_I:configuration[_h][_I],_f:configuration[_h][_f],_c:configuration[_h][_c],_T:configuration[_h][_T]},_C:configuration[_h][_C],_E:configuration[_h][_E],_R:A.get(_W,A.get(_AG,_G))},'params4':'010103'};C=await B.__fetch_safe(get_door_daily_bill_api,E);F=B.handle_request_result_message('get_door_daily_bill_api',C)
if _H in C and C[_H]==1 and _A in C and _AN in C[_A]:A[_A6]=C[_A][_AN] if _H in C and C[_H]==1 and _A in C and D in C[_A]:A[_l]=C[_A][D]
async def __get_door_pay_record(A,door_account):B=door_account;D=B[_c];C={_AX:{_B:configuration[_B],_E:configuration[_E],_P:configuration[_P],_J:{_V:configuration[_J][_V],_Y:configuration[_J][_Y],_Z:configuration[_J][_Z],_W:configuration[_J][_W]},_u:{_R:A.userInfo[_R]},_k:A.token},_AY:{_A:{_A2:A.userInfo[_R],'bgnPayDate':'2023-04-24',_I:configuration[_I],_p:B[_c],'endPayDate':'2024-04-24',_D:'webALIPAY_01','number':100,_d:B[_d],'page':_G,_AD:B[_X],_b:_G,_U:_G,_N:'',_L:'',_A3:A.userInfo[_AC]},_B:'0101051',_E:_a,_P:B[_X]},_AZ:'010104'};E=await A.__fetch(getJiaoFeiRecordApi,C) async def __get_door_pay_record(A,door_account):B=door_account;D=B[_r];C={'params1':{_C:configuration[_C],_E:configuration[_E],_R:configuration[_R],_K:{_U:configuration[_K][_U],_X:configuration[_K][_X],_Y:configuration[_K][_Y],_V:configuration[_K][_V]},_z:{_S:A.userInfo[_S]},_k:A.token},'params3':{_A:{_A5:A.userInfo[_S],'bgnPayDate':'2023-04-24',_I:configuration[_I],_q:B[_r],'endPayDate':'2024-04-24',_D:'webALIPAY_01','number':100,_e:B[_e],'page':_F,_AF:B[_W],_c:_F,_T:_F,_O:'',_M:'',_A6:A.userInfo[_AE]},_C:'0101051',_E:_a,_R:B[_W]},'params4':'010104'};E=await A.__fetch(getJiaoFeiRecordApi,C)
async def get_qr_code(B): async def get_qr_code(B):
A=await B.__get_request_key() A=await B.__get_request_key()
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
return await B.__get_qr_code() return await B.__get_qr_code()
async def check_qr_code(B): async def check_qr_code(B):
A=await B.__get_qr_code_status() A=await B.__get_qr_code_status()
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
A=await B.__get_qr_code_token() A=await B.__get_qr_code_token()
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
return await B.__get_token() return await B.__get_token()
async def send_phone_code(B,phone): async def send_phone_code(B,phone):
A=await B.__get_request_key() A=await B.__get_request_key()
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
return await B.__send_code(phone) return await B.__send_code(phone)
async def verfiy_phone_code(B,code): async def verfiy_phone_code(B,code):
A=await B.__verfiy_code(code) A=await B.__verfiy_code(code)
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
return await B.__get_token() return await B.__get_token()
async def __get_token(B): async def __get_token(B):
A=await B.__get_request_key() A=await B.__get_request_key()
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
A=await B.__get_request_authorize() A=await B.__get_request_authorize()
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
A=await B.__get_web_token() A=await B.__get_web_token()
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
A=await B.__get_door_number() A=await B.__get_door_number()
if _C in A and A[_C]!=0:return A if _B in A and A[_B]!=0:return A
B.need_login=_i;await B.save_data();return{_C:0,_A:B.powerUserList} B.need_login=_j;await B.save_data();return{_B:0,_A:B.powerUserList}
async def __refresh_token(A): async def __refresh_token(A):
B=await A.__get_request_key() B=await A.__get_request_key()
if _C in B and B[_C]!=0:return if _B in B and B[_B]!=0:return
B=await A.__refresh_web_token() B=await A.__refresh_web_token()
if _C in B and B[_C]==0:A.need_login=_i;A.retry_times=0;await A.save_data() if _B in B and B[_B]==0:A.need_login=_j;await A.save_data()
elif A.retry_times>=3:A.need_login=_o else:A.need_login=_y;LOGGER.error('国家电网刷新 Token 失败')
else:A.retry_times=A.retry_times+1 async def refresh_data(C,setup=_j):
async def refresh_data(B,setup=_i,force_refresh=_i): k='last_month_ele_cost';j='monthEleNum';i='year_ele_cost';h='thisTPq';g='thisNPq';f='thisVPq';e='thisPPq';d='refresh_time';U=setup;T='ladder_level_num';S='ladder_level';R='last_month_ele_num';Q='year_ele_num';L='%Y%m%d';K='day';I='dayElePq';H='balance'
p='last_month_ele_cost';o='year_ele_cost';n='%Y-%m-%d %H:%M:%S';b=setup;a='last_month_ele_num';Z='daily_lasted_date';Y='refresh_time';U='year_ele_num';G='balance' if U is _y:await C.__get_door_number()
if b is _o: if C.need_login is _y:A[d]='刷新 Token 失败,需重新登录!';LOGGER.error('国家电网需要重新登录!');return
if B.dataVersion!=VERSION:B.powerUserList=_F l=U or int(time.time()*1000)-C.timestamp>C.refresh_interval*3600*1000
c=await B.__get_door_number() if l is _j:return
if _C in c and c[_C]!=0:B.need_login=_o M=datetime.datetime.now();J=M-datetime.timedelta(days=1);m=f"{J.year}-{J.month:02d}-{J.day:02d}";N=J-datetime.timedelta(days=40);n=f"{N.year}-{N.month:02d}-{N.day:02d}"
if B.need_login is _o: for A in C.powerUserList:
if B.powerUserList is not _F: o=A[_r];C.doorAccountDict[o]=A;await C.__get_door_balance(A)
for A in B.get_door_account_list():A[Y]='Token刷新失败,请重新登录' if _A8 in A:
LOGGER.error('国家电网 - Token刷新失败,请重新登录!');return V=catchFloat(A[_A8],'prepayBal');p=catchFloat(A[_A8],'sumMoney')
q=b or force_refresh or int(time.time()*1000)-B.timestamp>B.refresh_interval*3600*1000 if V==0:A[H]=p
if q is _i:return else:A[H]=V
H=datetime.datetime.now();F=H-datetime.timedelta(days=1);d=f"{F.year}-{F.month:02d}-{F.day:02d}";V=F-datetime.timedelta(days=40);r=f"{V.year}-{V.month:02d}-{V.day:02d}" W=catchFloat(A[_A8],'historyOwe')
for A in B.powerUserList: if W>0:A[H]=-W
s=A[_c];B.doorAccountDict[s]=A
if Z in A and A[Z]==d:A[Y]=datetime.datetime.strftime(H,n);continue
await B.__get_door_balance(A)
if B.retry_times!=0:return
if _A5 in A:
t=catchFloat(A[_A5],'estiAmt');W=catchFloat(A[_A5],'prepayBal');e=catchFloat(A[_A5],'sumMoney')
if W==0 or W==e:A[G]=e
else:A[G]=W-t
f=catchFloat(A[_A5],'historyOwe')
if f>0:A[G]=-f
else:LOGGER.error('国家电网账户余额获取失败!') else:LOGGER.error('国家电网账户余额获取失败!')
if G not in A:A[G]=0 if H not in A:A[H]=0
await B.__get_door_daily_bill(A,H.year,r,d) await C.__get_door_daily_bill(A,M.year,n,m)
if _A6 not in A:LOGGER.error('国家电网无法获取日用电数据!');return if _l not in A:LOGGER.error('国家电网无法获取日用电数据!');return
X=0;I=_i O=0
for g in range(10): for X in range(10):
D=A[_A6][g] D=A[_l][X]
try:float(D[_AO]);I=_o;break try:float(D[I]);break
except:X=X+1 except:O=O+1
h=0;i=0;j=0;k=0;l=0 for X in range(O):A[_l].pop(0)
if I: D=A[_l][0];E=datetime.datetime.strptime(D[K],L);A['daily_ele_num']=catchFloat(D,I);A['daily_p_ele_num']=catchFloat(D,e);A['daily_v_ele_num']=catchFloat(D,f);A['daily_n_ele_num']=catchFloat(D,g);A['daily_t_ele_num']=catchFloat(D,h);Y=0;Z=0;a=0;b=0;c=0
for g in range(X):A[_A6].pop(0) for B in A[_l]:
D=A[_A6][0];E=datetime.datetime.strptime(D['day'],_Aa);A[Z]=f"{E.year}-{E.month:02d}-{E.day:02d}";h=catchFloat(D,_AO);i=catchFloat(D,_Ab);j=catchFloat(D,_Ac);k=catchFloat(D,_Ad);l=catchFloat(D,_Ae) G=datetime.datetime.strptime(B[K],L)
A['daily_ele_num']=normal_round(h,2);A['daily_p_ele_num']=normal_round(i,2);A['daily_v_ele_num']=normal_round(j,2);A['daily_n_ele_num']=normal_round(k,2);A['daily_t_ele_num']=normal_round(l,2);J=0;K=0;L=0;M=0;N=0 if G.month!=E.month:break
if I: Y+=catchFloat(B,I);Z+=catchFloat(B,e);a+=catchFloat(B,f);b+=catchFloat(B,g);c+=catchFloat(B,h)
for C in A[_A6]: A['month_ele_num']=normal_round(Y,2);A['month_p_ele_num']=normal_round(Z,2);A['month_v_ele_num']=normal_round(a,2);A['month_n_ele_num']=normal_round(b,2);A['month_t_ele_num']=normal_round(c,2);P=E-datetime.timedelta(days=E.day);q=f"{P.year}-{P.month:02d}"
u=datetime.datetime.strptime(C['day'],_Aa) if _s not in A or A[_s][_AR]!=q:await C.__get_door_bill(A,P.year)
if u.month!=E.month:break if _s not in A:LOGGER.error('国家电网无法获取年度用电数据!');return
J+=catchFloat(C,_AO);K+=catchFloat(C,_Ab);L+=catchFloat(C,_Ac);M+=catchFloat(C,_Ad);N+=catchFloat(C,_Ae) if _AH in A:A[Q]=catchFloat(A[_AH],'totalEleNum');A[i]=catchFloat(A[_AH],'totalEleCost')
A[_Af]=normal_round(J,2);A[_Ag]=normal_round(K,2);A[_Ah]=normal_round(L,2);A[_Ai]=normal_round(M,2);A[_Aj]=normal_round(N,2) if Q not in A:A[Q]=0;A[i]=0
if I: if _AI in A:A[R]=catchFloat(A[_s],j);A[k]=catchFloat(A[_s],'monthEleCost')
O=E-datetime.timedelta(days=E.day);v=f"{O.year}{O.month:02d}" if R not in A:A[R]=0;A[k]=0
if _AE not in A or A[_AE]!=O.year or _v not in A or A[_v][_AM]!=v:await B.__get_door_bill(A,O) r=datetime.datetime.strptime(A[_s][_AR],'%Y%m')
if _m in A: if r.month==12:
for C in A[_m]: F=0
if _h not in C:await B.__get_door_mouth_daily_bill(A,C) for B in A[_l]:
if _AL in A:A[U]=catchFloat(A[_AL],'totalEleNum');A[o]=catchFloat(A[_AL],'totalEleCost') G=datetime.datetime.strptime(B[K],L)
if U not in A:A[U]=0;A[o]=0 if G.month!=12:break
if _v in A:A[a]=catchFloat(A[_v],'monthEleNum');A[p]=catchFloat(A[_v],'monthEleCost');m=datetime.datetime.strptime(A[_v][_AM],'%Y%m') F+=catchFloat(B,I)
if a not in A:A[a]=0;A[p]=0;m=F.month
P=0;Q=0;R=0;S=0;T=0
if m.month==12:P=J;Q=K;R=L;S=M;T=N
else: else:
if _m in A: F=0
for C in A[_m]: for B in A[_AI]:F+=catchFloat(B,j)
if _h in C:P+=C[_h][_Af];Q+=C[_h][_Ag];R+=C[_h][_Ah];S+=C[_h][_Ai];T+=C[_h][_Aj] s=len(A[_AI])
P+=J;Q+=K;R+=L;S+=M;T+=N for B in A[_l]:
A[U]=normal_round(P,2);A['year_p_ele_num']=normal_round(Q,2);A['year_v_ele_num']=normal_round(R,2);A['year_n_ele_num']=normal_round(S,2);A['year_t_ele_num']=normal_round(T,2);A[Y]=datetime.datetime.strftime(H,n) G=datetime.datetime.strptime(B[K],L)
await B.save_data() if G.month<=s:break
def get_door_account_list(A):return list(A.doorAccountDict.values()) F+=catchFloat(B,I)
if F<=2760:A[S]='第一阶梯';A[T]=1
elif F<=4800:A[S]='第二阶梯';A[T]=2
else:A[S]='第三阶梯';A[T]=3
A['daily_lasted_date']=f"{E.year}-{E.month:02d}-{E.day:02d}";A[d]=datetime.datetime.strftime(M,'%Y-%m-%d %H:%M:%S')
await C.save_data()
async def get_door_account_list(A):return list(A.doorAccountDict.values())
def get_door_account(A):return A.doorAccountDict def get_door_account(A):return A.doorAccountDict
+1 -1
View File
@@ -5,5 +5,5 @@
"config_flow": true, "config_flow": true,
"documentation": "https://hassbox.cn/", "documentation": "https://hassbox.cn/",
"iot_class": "cloud_polling", "iot_class": "cloud_polling",
"version": "0.1.3" "version": "0.1.1"
} }
+33 -81
View File
@@ -16,6 +16,7 @@ from .const import DOMAIN, VERSION
from .data_client import StateGridDataClient from .data_client import StateGridDataClient
from .coordinator import StateGridCoordinator from .coordinator import StateGridCoordinator
UNIT_DU = ""
UNIT_YUAN = "" UNIT_YUAN = ""
ENTITY_ID_SENSOR_FORMAT = SENSOR_DOMAIN + ".state_grid_" ENTITY_ID_SENSOR_FORMAT = SENSOR_DOMAIN + ".state_grid_"
@@ -24,139 +25,96 @@ SENSOR_TYPES = [
{ {
"key":"balance", "key":"balance",
"name": "账户余额", "name": "账户余额",
"native_unit_of_measurement": UNIT_YUAN, "unit_of_measurement": UNIT_YUAN,
"device_class": SensorDeviceClass.MONETARY, "native_unit_of_measurement": UNIT_YUAN
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "year_ele_num", "key": "year_ele_num",
"name": "年度累计用电", "name": "年度累计用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
},
{
"key": "year_p_ele_num",
"name": "年度累计峰用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL
},
{
"key": "year_v_ele_num",
"name": "年度累计谷用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL
},
{
"key": "year_n_ele_num",
"name": "年度累计平用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL
},
{
"key": "year_t_ele_num",
"name": "年度累计尖用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "year_ele_cost", "key": "year_ele_cost",
"name": "年度累计电费", "name": "年度累计电费",
"native_unit_of_measurement": UNIT_YUAN, "unit_of_measurement": UNIT_YUAN,
"device_class": SensorDeviceClass.MONETARY, "native_unit_of_measurement": UNIT_YUAN
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "last_month_ele_num", "key": "last_month_ele_num",
"name": "上个月用电", "name": "上个月用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "last_month_ele_cost", "key": "last_month_ele_cost",
"name": "上个月电费", "name": "上个月电费",
"native_unit_of_measurement": UNIT_YUAN, "unit_of_measurement": UNIT_YUAN,
"device_class": SensorDeviceClass.MONETARY, "native_unit_of_measurement": UNIT_YUAN
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "month_ele_num", "key": "month_ele_num",
"name": "当月累计用电", "name": "当月累计用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "month_p_ele_num", "key": "month_p_ele_num",
"name": "当月累计峰用电", "name": "当月累计峰用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "month_v_ele_num", "key": "month_v_ele_num",
"name": "当月累计谷用电", "name": "当月累计谷用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "month_n_ele_num", "key": "month_n_ele_num",
"name": "当月累计平用电", "name": "当月累计平用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "month_t_ele_num", "key": "month_t_ele_num",
"name": "当月累计尖用电", "name": "当月累计尖用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "daily_ele_num", "key": "daily_ele_num",
"name": "日总用电", "name": "日总用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "daily_p_ele_num", "key": "daily_p_ele_num",
"name": "日峰用电", "name": "日峰用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "daily_v_ele_num", "key": "daily_v_ele_num",
"name": "日谷用电", "name": "日谷用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "daily_n_ele_num", "key": "daily_n_ele_num",
"name": "日平用电", "name": "日平用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "daily_t_ele_num", "key": "daily_t_ele_num",
"name": "日尖用电", "name": "日尖用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, "unit_of_measurement": UNIT_DU,
"device_class": SensorDeviceClass.ENERGY, "native_unit_of_measurement": UNIT_DU
"state_class": SensorStateClass.TOTAL
}, },
{ {
"key": "daily_lasted_date", "key": "daily_lasted_date",
"name": "最新用电日期" "name": "最新用电日期"
}, },
{ {
"key": "refresh_time", "key": "refresh_time",
@@ -177,7 +135,7 @@ async def async_setup_entry(
coordinator = StateGridCoordinator(hass) coordinator = StateGridCoordinator(hass)
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
data_client: StateGridDataClient = hass.data[DOMAIN] data_client: StateGridDataClient = hass.data[DOMAIN]
door_account_list = data_client.get_door_account_list() door_account_list = await data_client.get_door_account_list()
for door_account in door_account_list: for door_account in door_account_list:
async_add_entities( async_add_entities(
[StateGridSensor(door_account, sensor_type, entry.entry_id, coordinator) for sensor_type in SENSOR_TYPES] [StateGridSensor(door_account, sensor_type, entry.entry_id, coordinator) for sensor_type in SENSOR_TYPES]
@@ -203,12 +161,6 @@ class StateGridSensor(CoordinatorEntity[StateGridCoordinator], SensorEntity):
self._attr_unique_id = entry_id + "-" + door_account["consNo_dst"] + "-" + sensor_type["key"] self._attr_unique_id = entry_id + "-" + door_account["consNo_dst"] + "-" + sensor_type["key"]
if "device_class" in sensor_type:
self._attr_device_class = sensor_type["device_class"]
if "state_class" in sensor_type:
self._attr_state_class = sensor_type["state_class"]
if "native_unit_of_measurement" in sensor_type: if "native_unit_of_measurement" in sensor_type:
self._attr_native_unit_of_measurement = sensor_type["native_unit_of_measurement"] self._attr_native_unit_of_measurement = sensor_type["native_unit_of_measurement"]