5 Commits
Author SHA1 Message Date
HassBox c12e77d4e6 . 2024-05-08 08:01:34 +08:00
HassBox ba103f293c . 2024-05-06 23:15:45 +08:00
HassBox b116ef701f . 2024-05-06 23:14:13 +08:00
HassBox ebcfbb0935 . 2024-05-06 10:02:29 +08:00
HassBox 806c44e174 . 2024-05-06 09:37:57 +08:00
15 changed files with 689 additions and 620 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)
+3 -1
View File
@@ -11,5 +11,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
"""Set up this integration using UI.""" """Set up this integration using UI."""
config = await async_load_from_store(hass, "state_grid.config") or None config = await async_load_from_store(hass, "state_grid.config") or None
hass.data[DOMAIN] = StateGridDataClient(hass = hass, config = config) hass.data[DOMAIN] = StateGridDataClient(hass = hass, config = config)
await hass.config_entries.async_forward_entry_setups(config_entry, [Platform.SENSOR]) hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, Platform.SENSOR)
)
return True return True
+2 -4
View File
@@ -202,13 +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)
await self.data_client.coordinator.async_request_refresh()
return self.async_create_entry( return self.async_create_entry(
title="国家电网", title="国家电网",
data={} data={}
@@ -248,8 +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)
await self.data_client.coordinator.async_request_refresh()
return self.async_create_entry( return self.async_create_entry(
title="国家电网", title="国家电网",
data={} data={}
+2 -2
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.6" VERSION = "0.0.4"
VERSION_STORAGE = 1 VERSION_STORAGE = 1
+321 -361
View File
@@ -1,385 +1,345 @@
_Aw='get_door_ladder_api' BZ='params4'
_Av='queryDate' BY='params3'
_Au='queryYear' BX='params1'
_At='access_token' BW='queryYear'
_As='businessType' BV='provinceCode'
_Ar='qrCodeSerial' BU='sceneType'
_Aq='redirect_url' BT='consNoSrc'
_Ap='_access_token' BS='access_token'
_Ao='dataVersion' BR='codeKey'
_An='refresh_interval' BQ='businessType'
_Am='doorAccountDict' BP='Channels'
_Al='refreshToken' BO='qrCodeSerial'
_Ak='accessToken' BN='redirect_url'
_Aj='/osg-web0004/member/c24/f01' BM='_access_token'
_Ai='BCP_00026' BL='is_debug'
_Ah='serviceCode_smt' BK='refresh_interval'
_Ag='WEBA10070900' BJ='doorAccountDict'
_Af='serviceType' BI='refreshToken'
_Ae='jM_custType' BH='accessToken'
_Ad='jM_busiTypeCode' BG='/osg-web0004/member/c24/f01'
_Ac='doorNumberManeger' BF='BCP_00026'
_Ab='month_t_ele_num' BE='serviceCode_smt'
_Aa='month_n_ele_num' BD='WEBA10070900'
_AZ='month_v_ele_num' BC='serviceType'
_AY='month_p_ele_num' BB='jM_custType'
_AX='month_ele_num' BA='jM_busiTypeCode'
_AW='constType' B9='01008183'
_AV='provinceCode' B8='0101003'
_AU='elecTypeCode' B7='submit'
_AT='powerUserList' B2='consType'
_AS='publicKey' B1='constType'
_AR='WEBA10070800' B0='powerUserList'
_AQ='timeDay' A_='publicKey'
_AP='WEBA10070700' Az='WEBA10070800'
_AO='channelNo' Ay='timeDay'
_AN='month' Ax='105'
_AM='yearTotalCost' Aw='111'
_AL='consType' Av='0901'
_AK='provinceId' Au='WEBA10070700'
_AJ='proCode' At='102'
_AI='userAccountId' As='0101143'
_AH='0000' Ar='channelNo'
_AG='refresh_token' Ae='latestBillMonth'
_AF='skey' Ad='yearTotalCost'
_AE='userInfo' Ac='userAccountId'
_AD='0101046' Ab='0000'
_AC='billYear' Aa='refresh_token'
_AB='loginAccount' AZ='web'
_AA='keyCode' AY='skey'
_A9='querytypeCode' AX='userInfo'
_A8='01010049' AW=True
_A7='account' AV='215'
_A6='daily_bill_list' AU='0101046'
_A5='account_balance' AK='accountBalance'
_A4='userName' AJ='proCode'
_A3='acctId' AI='loginAccount'
_A2='resultCode' AH='keyCode'
_A1='quInfo' AG='querytypeCode'
_A0='BCP_000026' AF='01010049'
_z='app' AE='doorNumberManeger'
_y='WEBALIPAY_01' AD='monthBillList'
_x='order' AC='list'
_w='state_grid' AB='userName'
_v='latestBillMonth' AA='acctId'
_u='list' A9='resultCode'
_t='authFlag' A8='quInfo'
_s='09' A7='BCP_000026'
_r='0101183' A6='app'
_q='consNo' A5='WEBALIPAY_01'
_p='token' A4='order'
_o=True A3='state_grid'
_n='0101154' z=False
_m='getday' y='authFlag'
_l='monthBillList' x='09'
_k='bizrt' w='0101183'
_j='timestamp' v='stepelect'
_i=False u='account'
_h='month_ele' t=len
_g='consNo_dst' s='consNo_dst'
_f='errmsg' r='token'
_e='clearCache' q='0101154'
_d='promotCode' p='getday'
_c='01' n='consNo'
_b='SGAPP' m='bizrt'
_a='devciceId' l='clearCache'
_Z='devciceIp' k='timestamp'
_Y='orgNo' i='errmsg'
_X='tenant' h='promotCode'
_W='member' g='01'
_V='stepelect' f='SGAPP'
_U='proNo' e='devciceId'
_T='promotType' d='devciceIp'
_S='target' c='orgNo'
_R='userId' b='tenant'
_Q='srvrt' a='member'
_P='subBusiTypeCode' Z=str
_O='serCat' Y='daily_bill_list'
_N='serialNo' X='proNo'
_M='0902' W='promotType'
_L='srvCode' V='target'
_K='uscInfo' U='userId'
_J='busiTypeCode' T='srvrt'
_I='channelCode' S='subBusiTypeCode'
_H='code' R='serCat'
_G='1' Q='serialNo'
_F=None O='0902'
_E='source' N='srvCode'
_D='funcCode' M='uscInfo'
_C='serviceCode' L=None
_B='errcode' K='busiTypeCode'
_A='data' J='code'
import json,time,aiohttp,urllib.parse,datetime I='channelCode'
from.const import VERSION H='1'
from.utils.logger import LOGGER G='source'
from.utils.store import async_save_to_store E='funcCode'
from.utils.crypt import a,b,c,d,e D='serviceCode'
configuration={_K:{_W:_M,_Z:'',_a:'',_X:_w},_E:_b,_S:'32101',_I:_M,_AO:_M,'toPublish':_c,'siteId':'2012000000033700',_L:'',_N:'',_D:'',_C:{_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',_S:'-1'},'userInformation':{_C:'01008183',_E:_b},'userInform':{_C:_r,_E:_b},'elesum':{_I:_M,_D:_y,_d:_G,_T:_G,_C:'0101143',_E:_z},_A7:{_I:_M,_D:'WEBA1007200'},_Ac:{_E:_M,_S:'-1',_I:_s,_AO:_s,_C:_A8,_D:'WEBA40050000',_K:{_W:_M,_Z:'',_a:'',_X:_w}},'doorAuth':{_E:_b,_C:'f04'},'xinZ':{_O:'101',_Ad:'101','fJ_busiTypeCode':'102',_Ae:'03','fJ_custType':'02',_Af:_c,_P:'',_D:_AP,_x:_n,_E:_b,_A9:_G},'onedo':{_C:_AD,_E:_b,_D:_AP,'queryType':'03'},'xinHuTongDian':{_O:'110',_J:'211',_P:'21102',_D:'WEBA10071200',_I:_M,_E:_s,_C:_r},'company':{_O:'104',_D:_AP,_Af:'02',_A9:_G,_t:_G,_E:_b,_x:_n},'charge':{_I:_s,_D:'WEBA10071300',_AO:'0901',_O:'102',_Ae:_c,_Ad:'102'},'other':{_I:_s,_D:'WEBA10079700',_O:'129',_J:'999',_P:'21501',_C:_A0,_L:'',_N:''},'vatchange':{'submit':'0101003',_J:'320',_P:'',_O:'115',_D:'WEBA10074000',_t:_G},'bill':{_e:_G,_D:_y,_T:_G,_C:_A0},_V:{_I:_M,_D:_y,_T:_G,_e:_s,_C:_A0,_E:_z},_m:{_I:_M,_e:'11',_D:_y,_d:_G,_T:_G,_C:_A0,_E:_z},'mouthOut':{_I:_M,_e:'11',_D:_y,_d:_G,_T:_G,_C:_A0,_E:_z},'meter':{_O:'114',_J:'304',_D:'WEBA10071000',_P:'',_C:_AD,_N:''},'complaint':{_J:'005','srvMode':_M,'anonymousFlag':'0','replyMode':_c,'retvisitFlag':_c},'report':{_J:'006'},'tradewinds':{_J:'019'},'somesay':{_J:'091'},'faultrepair':{_D:_Ag,_C:_r,_O:'111',_J:'001',_P:'21505'},'electronicInvoice':{_O:'105',_J:'0'},'rename':{_C:_AD,_D:'WEBA10076100',_J:'210',_O:'109',_t:_G,'gh_busiTypeCode':'211','gh_subusi':'21101',_N:'',_L:''},'pause':{_P:'',_C:_A8,_D:'WEBA10073600',_O:'107',_J:'203','jr_busi':'201',_N:'',_L:''},'capacityRecovery':{_C:_A8,_E:_b,_L:'',_N:'',_D:'WEBA10073700','busiTypeCode_stop':'204','busiTypeCode_less':'202',_J:'202',_P:'',_O:'108',_AQ:'5',_t:_G},'electricityPriceChange':{_C:_r,_J:'215',_P:'21502',_O:'113',_t:_G,_AQ:'15',_D:'WEBA10073900WEB',_L:'',_N:''},'electricityPriceStrategyChange':{_C:'01008183',_J:'215',_P:'21506',_O:'160',_D:'WEBV00000517WEB',_L:'',_N:''},'eemandValueAdjustment':{_C:_r,_L:'',_N:'',_O:'112',_D:'WEBA10073800',_J:'215',_P:'21504',_t:_G,_AQ:'5','getMonthServiceCode':_AD},'businessProgress':{_C:_r,_L:_c,_D:'WEB01'},'increase':{_E:_b,_N:'',_L:'',_Ah:_A8,_C:_n,_x:_n,_D:_AR,_A9:_G,_O:'106',_J:'111',_P:''},'fjincrea':{_O:'105',_J:'110',_P:'',_E:_b,_D:_AR,_N:'',_L:'',_Ah:_A8,_C:_n,_x:_n,_A9:_G},'persIncrea':{_O:'105',_J:'109',_x:_n,_P:'',_E:_b,_D:_AR,_A9:_G},'fgdChange':{_C:_r,_L:_c,_I:_s,_D:_Ag,_J:'215',_P:'21505',_O:'111',_t:_G},'createOrder':{_I:_M,_D:_y,_L:'BCP_000001','chargeMode':'02','conType':_c,'bizTypeId':'BT_ELEC'},'largePopulation':{_J:'383',_D:'WEBA10076800',_P:'',_L:'',_T:'',_d:'',_I:'0901',_O:'383',_C:'',_N:''},'biaoJiCode':{_C:'0104507',_E:'1704',_I:'1704'},'twoGuar':{_J:'402',_P:'40201',_D:'web_twoGuar'},'electTrend':{_C:_Ai,_I:_M},'emergency':{_C:_Ai,_D:'A10000000',_I:_M},'infoPublic':{_C:'2545454',_E:_z}} C='errcode'
appKey='3def6c365d284881bf1a9b2b502ee68c' B='data'
appSecret='ab7357dae64944a197ace37398897f64' A=''
baseApi='https://www.95598.cn/api' import json as AL,time as Af,aiohttp as Ag,urllib.parse,datetime as j
get_request_key_api='/oauth2/outer/c02/f02' from.utils.logger import LOGGER as A0
get_qr_code_api='/osg-open-uc0001/member/c8/f24' from.utils.store import async_save_to_store as Ba
get_qr_code_status_api='/osg-web0004/open/c50/f02' from.utils.crypt import a as AM,b as B3,c as A1,d as AN,e as Ah
get_qr_code_token_api='/osg-uc0013/member/c4/f04' o='3def6c365d284881bf1a9b2b502ee68c'
send_code_api='/osg-open-uc0001/member/c8/f04' Ai='ab7357dae64944a197ace37398897f64'
code_login_api='/osg-uc0013/member/c4/f02' F={M:{a:O,d:A,e:A,b:A3},G:f,V:'32101',I:O,Ar:O,'toPublish':g,'siteId':'2012000000033700',N:A,Q:A,E:A,D:{A4:q,'uploadPic':'0101296','pauseSCode':'0101250','pauseTCode':'0101251','listconsumers':'0101093','messageList':'0101343',B7:B8,'sbcMsg':'0101210','powercut':'0104514','BkAuth01':'f15','BkAuth02':'f18','BkAuth03':'f02','BkAuth04':'f17','BkAuth05':'f05','BkAuth06':'f16','BkAuth07':'f01','BkAuth08':'f03'},'electricityArchives':{'servicecode':'0104505',G:O},'subscriptionList':{N:'APP_SGPMS_05_030',Q:'22',I:O,E:'22',V:'-1'},'userInformation':{D:B9,G:f},'userInform':{D:w,G:f},'elesum':{I:O,E:A5,h:H,W:H,D:As,G:A6},u:{I:O,E:'WEBA1007200'},AE:{G:O,V:'-1',I:x,Ar:x,D:AF,E:'WEBA40050000',M:{a:O,d:A,e:A,b:A3}},'doorAuth':{G:f,D:'f04'},'xinZ':{R:'101',BA:'101','fJ_busiTypeCode':At,BB:'03','fJ_custType':'02',BC:g,S:A,E:Au,A4:q,G:f,AG:H},'onedo':{D:AU,G:f,E:Au,'queryType':'03'},'xinHuTongDian':{R:'110',K:'211',S:'21102',E:'WEBA10071200',I:O,G:x,D:w},'company':{R:'104',E:Au,BC:'02',AG:H,y:H,G:f,A4:q},'charge':{I:x,E:'WEBA10071300',Ar:Av,R:At,BB:g,BA:At},'other':{I:x,E:'WEBA10079700',R:'129',K:'999',S:'21501',D:A7,N:A,Q:A},'vatchange':{B7:B8,K:'320',S:A,R:'115',E:'WEBA10074000',y:H},'bill':{l:H,E:A5,W:H,D:A7},v:{I:O,E:A5,W:H,l:x,D:A7,G:A6},p:{I:O,l:'11',E:A5,h:H,W:H,D:A7,G:A6},'mouthOut':{I:O,l:'11',E:A5,h:H,W:H,D:A7,G:A6},'meter':{R:'114',K:'304',E:'WEBA10071000',S:A,D:AU,Q:A},'complaint':{K:'005','srvMode':O,'anonymousFlag':'0','replyMode':g,'retvisitFlag':g},'report':{K:'006'},'tradewinds':{K:'019'},'somesay':{K:'091'},'faultrepair':{E:BD,D:w,R:Aw,K:'001',S:'21505'},'electronicInvoice':{R:Ax,K:'0'},'rename':{D:AU,E:'WEBA10076100',K:'210',R:'109',y:H,'gh_busiTypeCode':'211','gh_subusi':'21101',Q:A,N:A},'pause':{S:A,D:AF,E:'WEBA10073600',R:'107',K:'203','jr_busi':'201',Q:A,N:A},'capacityRecovery':{D:AF,G:f,N:A,Q:A,E:'WEBA10073700','busiTypeCode_stop':'204','busiTypeCode_less':'202',K:'202',S:A,R:'108',Ay:'5',y:H},'electricityPriceChange':{D:w,K:AV,S:'21502',R:'113',y:H,Ay:'15',E:'WEBA10073900WEB',N:A,Q:A},'electricityPriceStrategyChange':{D:B9,K:AV,S:'21506',R:'160',E:'WEBV00000517WEB',N:A,Q:A},'eemandValueAdjustment':{D:w,N:A,Q:A,R:'112',E:'WEBA10073800',K:AV,S:'21504',y:H,Ay:'5','getMonthServiceCode':AU},'businessProgress':{D:w,N:g,E:'WEB01'},'increase':{G:f,Q:A,N:A,BE:AF,D:q,A4:q,E:Az,AG:H,R:'106',K:Aw,S:A},'fjincrea':{R:Ax,K:'110',S:A,G:f,E:Az,Q:A,N:A,BE:AF,D:q,A4:q,AG:H},'persIncrea':{R:Ax,K:'109',A4:q,S:A,G:f,E:Az,AG:H},'fgdChange':{D:w,N:g,I:x,E:BD,K:AV,S:'21505',R:Aw,y:H},'createOrder':{I:O,E:A5,N:'BCP_000001','chargeMode':'02','conType':g,'bizTypeId':'BT_ELEC'},'largePopulation':{K:'383',E:'WEBA10076800',S:A,N:A,W:A,h:A,I:Av,R:'383',D:A,Q:A},'biaoJiCode':{D:'0104507',G:'1704',I:'1704'},'twoGuar':{K:'402',S:'40201',E:'web_twoGuar'},'electTrend':{D:BF,I:O},'emergency':{D:BF,E:'A10000000',I:O},'infoPublic':{D:'2545454',G:A6}}
getCertificationApi='/osg-open-uc0001/member/c8/f11' B4='https://www.95598.cn/api'
get_request_authorize_api='/oauth2/oauth/authorize' B5='/oauth2/outer/c02/f02'
get_web_token_api='/oauth2/outer/getWebToken' Aj='/osg-open-uc0001/member/c8/f24'
refresh_web_token_api='/oauth2/outer/refresh_web_token' Ak='/osg-web0004/open/c50/f02'
get_door_number_api='/osg-open-uc0001/member/c9/f02' Al='/osg-uc0013/member/c4/f04'
get_door_balance_api='/osg-open-bc0001/member/c05/f01' Am='/osg-open-uc0001/member/c8/f04'
get_door_bill_api='/osg-open-bc0001/member/c01/f02' An='/osg-uc0013/member/c4/f02'
get_door_ladder_api='/osg-open-bc0001/member/c04/f03' B6='/osg-open-uc0001/member/c8/f11'
getJiaoFeiRecordApi=_Aj Ao='/oauth2/oauth/authorize'
get_door_daily_bill_api=_Aj AO='/oauth2/outer/getWebToken'
sessionIdControlApiList=[get_qr_code_api,get_qr_code_status_api,get_qr_code_token_api,send_code_api,code_login_api] Ap='/oauth2/outer/refresh_web_token'
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] Aq='/osg-open-uc0001/member/c9/f02'
authControlApiList=[get_door_number_api,get_door_balance_api,get_door_bill_api,get_door_ladder_api,getJiaoFeiRecordApi,get_door_daily_bill_api] AP='/osg-open-bc0001/member/c05/f01'
tControlApiList=[getCertificationApi,get_door_balance_api,get_door_bill_api,get_door_ladder_api,getJiaoFeiRecordApi,get_door_daily_bill_api] AQ='/osg-open-bc0001/member/c01/f02'
def json_dumps(data):return json.dumps(data,separators=(',',':'),ensure_ascii=_i) AR='/osg-open-bc0001/member/c04/f03'
def normal_round(num,ndigits=0): AS=BG
A=ndigits AT=BG
if A==0:return int(num+.5) Bb=[Aj,Ak,Al,Am,An]
else:B=10**A;return int(num*B+.5)/B Bc=[Ak,Al,Am,An,B6,Ao,AO,Ap,Aq,AP,AQ,AR,AS,AT]
def catchFloat(data,key): Bd=[Aq,AP,AQ,AR,AS,AT]
Be=[B6,AP,AQ,AR,AS,AT]
def A2(data):return AL.dumps(data,separators=(',',':'),ensure_ascii=z)
def P(data,key):
if key in data: if key in data:
try:return normal_round(float(data[key]),2) try:return float(data[key])
except:return 0 except:return 0
else:return 0 else:return 0
class StateGridDataClient: class StateGridDataClient:
hass=_F;coordinator=_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=L;session=L;keyCode=L;publicKey=L;need_login=z;phone=L;codeKey=L;serialNo=L;qrCodeSerial=L;userInfo=L;accountInfo=L;powerUserList=L;doorAccountDict={};cookie=[];timestamp=int(Af.time()*1000);accessToken=L;refreshToken=L;token=L;expirationDate=L;refresh_interval=12;is_debug=z
def __init__(A,hass,config=_F): def __init__(A,hass,config=L):
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=Ag.TCPConnector(ssl=z);D=Ag.CookieJar(quote_cookie=AW);A.session=Ag.ClientSession(cookie_jar=D,connector=C)
if B is not _F: if B is not L:
try:A.keyCode=B[_AA];A.publicKey=B[_AS];A.accessToken=B[_Ak];A.refreshToken=B[_Al];A.token=B[_p];A.userInfo=B[_AE];A.powerUserList=B[_AT];A.doorAccountDict=B[_Am];A.refresh_interval=B[_An];A.is_debug=B['is_debug'];A.dataVersion=B[_Ao] try:A.keyCode=B[AH];A.publicKey=B[A_];A.accessToken=B[BH];A.refreshToken=B[BI];A.token=B[r];A.userInfo=B[AX];A.powerUserList=B[B0];A.doorAccountDict=B[BJ];A.refresh_interval=B[BK];A.is_debug=B[BL]
except Exception as E:LOGGER.error(E) except Exception as E:A0.error(E)
async def save_data(B):A={};A[_AA]=B.keyCode;A[_AS]=B.publicKey;A[_Ak]=B.accessToken;A[_Al]=B.refreshToken;A[_p]=B.token;A[_AE]=B.userInfo;A[_AT]=B.powerUserList;A[_Am]=B.doorAccountDict;A[_An]=B.refresh_interval;A['is_debug']=B.is_debug;A[_Ao]=VERSION;await async_save_to_store(B.hass,'state_grid.config',A) async def save_data(A):B={};B[AH]=A.keyCode;B[A_]=A.publicKey;B[BH]=A.accessToken;B[BI]=A.refreshToken;B[r]=A.token;B[AX]=A.userInfo;B[B0]=A.powerUserList;B[BJ]=A.doorAccountDict;B[BK]=A.refresh_interval;B[BL]=A.is_debug;await Ba(A.hass,'state_grid.config',B)
def encrypt_post_data(A,data):B={_Ap: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(B,data):C={BM:B.accessToken[t(B.accessToken)//2:]if B.accessToken else A,'_t':B.token[t(B.token)//2:]if B.token else A,'_data':data,k:B.timestamp};return B.encrypt_wapper_data(C)
def encrypt_wapper_data(A,data):B=a(json_dumps(data),A.keyCode);return{_A:B+c(B+str(A.timestamp)),_AF:d(A.keyCode,A.publicKey),_j:str(A.timestamp)} def encrypt_wapper_data(A,data):C=AM(A2(data),A.keyCode);return{B:C+A1(C+Z(A.timestamp)),AY:AN(A.keyCode,A.publicKey),k:Z(A.timestamp)}
def handle_request_result_message(E,api,result): def handle_request_result_message(F,api,result):
D='message';C='resultMessage';A=result;B=_F E='message';D='resultMessage';A=result;C=L
if _A in A and _Q in A[_A]and C in A[_A][_Q]:B=A[_A][_Q][C] if B in A and T in A[B]and D in A[B][T]:C=A[B][T][D]
elif _Q in A and C in A[_Q]:B=A[_Q][C] elif T in A and D in A[T]:C=A[T][D]
elif D in A:B=A[D] elif E in A:C=A[E]
else:B=json_dumps(A) else:C=A2(A)
if E.is_debug:LOGGER.error(api+': '+B);LOGGER.error(json_dumps(A)) if F.is_debug:A0.error(api+': '+C);A0.error(A2(A))
return B return C
async def __fetch_safe(C,api,data): async def fetch(D,api,data,header=L):
B=await C.__fetch(api,data) Y='encryptData';X='464606a4-184c-4beb-b442-2ab7761d0796';W='key_code';V='state';U='sign';T='grant_type';S='application/json;charset=UTF-8';R='Content-Type';Q=header;P='client_secret';N='client_id';H=api;D.timestamp=int(Af.time()*1000);F=D.timestamp
if _H not in B:return B if D.keyCode is L:D.keyCode=Ah(32,16,2)
A=B[_H] I=D.keyCode;K={'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':S,R:S,'version':'1.0',G:Av,k:Z(F),'wsgwType':AZ,'appKey':o};C=data
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 H==B5:C={N:o,P:Ai};M=AM(A2(C),I);C={B:M+A1(M+Z(F)),AY:AN(I,'042BC7AD510BF9793B7744C8854C56A8C95DD1027EE619247A332EC6ED5B279F435A23D62441FE861F4B0C963347ECD5792F380B64CA084BE8BE41151F8B8D19C8'),N:o,k:Z(F)}
await C.__refresh_token() elif H==Aj:C={BM:A,'_t':A,'_data':C,k:F}
if C.need_login is _o:return B elif H==Ao:
else:return await C.__fetch(api,data) C={N:o,'response_type':J,BN:'/test',k:F,'rsi':D.token};C=urllib.parse.urlencode(C);K[R]='application/x-www-form-urlencoded; charset=UTF-8';K[AH]=I
else:return B async with D.session.post(B4+H,data=C,headers=K)as O:D.session.cookie_jar.update_cookies(O.cookies);E=await O.json();E=B3(E[B],D.token);E=AL.loads(E);return E
async def __fetch(B,api,data,header=_F): elif H==AO:C={T:'authorization_code',U:A1(o+Z(F)),P:Ai,V:X,W:I,N:o,k:F,J:C[J]};M=AM(A2(C),I);C={B:M+A1(M+Z(F)),AY:AN(I,D.publicKey),k:Z(F)}
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 elif H==Ap:C={T:Aa,U:A1(o+Z(F)),P:Ai,V:X,W:I,N:o,k:F,Aa:D.refreshToken};M=AM(A2(C),I);C={B:M+A1(M+Z(F)),AY:AN(I,D.publicKey),k:Z(F)};H=AO
if B.keyCode is _F:B.keyCode=e(32,16,2) else:C=D.encrypt_post_data(C)
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 if Q is not L:K.update(Q)
if E==get_request_key_api:A={I:appKey,K:appSecret};H=a(json_dumps(A),F);A={_A:H+c(H+str(D)),_AF:d(F,'042BC7AD510BF9793B7744C8854C56A8C95DD1027EE619247A332EC6ED5B279F435A23D62441FE861F4B0C963347ECD5792F380B64CA084BE8BE41151F8B8D19C8'),I:appKey,_j:str(D)} if H in Bb:K['sessionId']=AZ+Z(F)
elif E==get_qr_code_api:A={_Ap:'','_t':'','_data':A,_j:D} if H in Bc:K[AH]=I
elif E==get_request_authorize_api: if H in Bd:K['Authorization']='Bearer '+D.accessToken[:t(D.accessToken)//2]
A={I:appKey,'response_type':_H,_Aq:'/test',_j:D,'rsi':B.token};A=urllib.parse.urlencode(A);G[M]='application/x-www-form-urlencoded; charset=UTF-8';G[_AA]=F if H in Be:K['t']=D.token[:t(D.token)//2]
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 D.session.post(B4+H,json=C,headers=K)as O:
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)),_AF:d(F,B.publicKey),_j:str(D)} E=await O.text()
elif E==refresh_web_token_api:A={O:_AG,P:c(appKey+str(D)),K:appSecret,Q:S,R:F,I:appKey,_j:D,_AG:B.refreshToken};H=a(json_dumps(A),F);A={_A:H+c(H+str(D)),_AF:d(F,B.publicKey),_j:str(D)};E=get_web_token_api if E.startswith('{'):
else:A=B.encrypt_post_data(A) E=AL.loads(E)
if L is not _F:G.update(L) if Y in E:E=B3(E[Y],I);E=AL.loads(E)
if E in sessionIdControlApiList:G['sessionId']='web'+str(D) return E
if E in keyCodeControlApiList:G[_AA]=F
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]
async with B.session.post(baseApi+E,json=A,headers=G)as J:
C=await J.text()
if C.startswith('{'):
C=json.loads(C)
if T in C:C=b(C[T],F);C=json.loads(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=L;D=await A.fetch(B5,{});E=A.handle_request_result_message('get_request_key_api',D)
if B[_H]==_G:A.keyCode=B[_A][_AA];A.publicKey=B[_A][_AS];return{_B:0} if D[J]==H:A.keyCode=D[B][AH];A.publicKey=D[B][A_];return{C:0}
return{_B:1,_f:C} return{C:1,i:E}
async def __get_qr_code(B): async def __get_qr_code(E):
C={_K:{_Z:'',_X:_w,_W:_M,_a:''},_A1:{'optType':_c,_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) F={M:{d:A,b:A3,a:O,e:A},A8:{'optType':g,Q:Ah(28,10,1)}};D=await E.fetch(Aj,F);G=E.handle_request_result_message('get_qr_code_api',D)
if A[_H]==1: if D[J]==1:
if A[_A]and A[_A][_Q]and A[_A][_Q][_A2]==_AH:B.qrCodeSerial=A[_A][_k][_Ar];E=A[_A][_k]['qrCode'];return{_B:0,_A:E} if D[B]and D[B][T]and D[B][T][A9]==Ab:E.qrCodeSerial=D[B][m][BO];H=D[B][m]['qrCode'];return{C:0,B:H}
return{_B:1,_f:D} return{C:1,i:G}
async def __get_qr_code_status(B): async def __get_qr_code_status(D):
C={_k:{_Ar:B.qrCodeSerial}};D={_p:'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) E={m:{BO:D.qrCodeSerial}};F={r:'98'+Ah(10,10,1)};A=await D.fetch(Ak,E,F);G=D.handle_request_result_message('get_qr_code_status_api',A)
if _H in A and A[_H]==1: if J in A and A[J]==1:
if _A in A and A[_A]!='null':B.token=A[_A];return{_B:0} if B in A and A[B]!='null':D.token=A[B];return{C:0}
else:return{_B:1,_f:'未使用网上国网 App 扫码或确认登录'} else:return{C:1,i:'未使用网上国网 App 扫码或确认登录'}
return{_B:1,_f:E} return{C:1,i:G}
async def __get_qr_code_token(B): async def __get_qr_code_token(B):
C={_K:{_X:_w,_W:_M,'isEncrypt':_o},_p:B.token};A=await B.__fetch(get_qr_code_token_api,C);D=B.handle_request_result_message('get_qr_code_token_api',A) D={M:{b:A3,a:O,'isEncrypt':AW},r:B.token};A=await B.fetch(Al,D);E=B.handle_request_result_message('get_qr_code_token_api',A)
if _Q in A and _A2 in A[_Q]and A[_Q][_A2]==_AH:B.userInfo=A[_k][_AE];return{_B:0} if T in A and A9 in A[T]and A[T][A9]==Ab:B.userInfo=A[m][AX];return{C:0}
return{_B:1,_f:D} return{C:1,i:E}
async def __send_code(B,phone): async def __send_code(E,phone):
C=phone;B.phone=C;D={_K:{_Z:'',_X:_w,_W:_M,_a:''},_A1:{'sendType':'0',_A7:C,_As:'login','accountType':''},'Channels':'web'};A=await B.__fetch(send_code_api,D);E=B.handle_request_result_message('send_code_api',A) F=phone;E.phone=F;G={M:{d:A,b:A3,a:O,e:A},A8:{'sendType':'0',u:F,BQ:'login','accountType':A},BP:AZ};D=await E.fetch(Am,G);H=E.handle_request_result_message('send_code_api',D)
if A[_H]==1: if D[J]==1:
if A[_A]and A[_A][_Q]and A[_A][_Q][_A2]==_AH:B.codeKey=A[_A][_k]['codeKey'];return{_B:0} if D[B]and D[B][T]and D[B][T][A9]==Ab:E.codeKey=D[B][m][BR];return{C:0}
return{_B:1,_f:E} return{C:1,i:H}
async def __verfiy_code(A,code): async def __verfiy_code(B,code):
C={_K:{_Z:'',_X:_w,_W:_M,_a:''},_A1:{_A7:A.phone,_As:'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) E={M:{d:A,b:A3,a:O,e:A},A8:{u:B.phone,BQ:'login',J:code,'optSys':'ios','pushId':'00000',BR:B.codeKey},BP:AZ};D=await B.fetch(An,E);F=B.handle_request_result_message('code_login_api',D)
if _Q in B and _A2 in B[_Q]and B[_Q][_A2]==_AH:A.token=B[_k][_p];A.userInfo=B[_k][_AE][0];return{_B:0} if T in D and A9 in D[T]and D[T][A9]==Ab:B.token=D[m][r];B.userInfo=D[m][AX][0];return{C:0}
return{_B:1,_f:D} return{C:1,i:F}
async def __get_request_authorize(B): async def __get_request_authorize(D):
A=await B.__fetch(get_request_authorize_api,{});E=B.handle_request_result_message('get_request_authorize_api',A) A=await D.fetch(Ao,{});G=D.handle_request_result_message('get_request_authorize_api',A)
if _H in A and A[_H]==_G:C=A[_A][_Aq];D=C.rfind('code=');B.authorizeCode=C[D+5:D+5+32];return{_B:0} if J in A and A[J]==H:E=A[B][BN];F=E.rfind('code=');D.authorizeCode=E[F+5:F+5+32];return{C:0}
return{_B:1,_f:E} return{C:1,i:G}
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) E={J:A.authorizeCode};D=await A.fetch(AO,E);F=A.handle_request_result_message('get_web_token_api',D)
if _H in B and B[_H]==_G:A.accessToken=B[_A][_At];A.refreshToken=B[_A][_AG];return{_B:0} if J in D and D[J]==H:A.accessToken=D[B][BS];A.refreshToken=D[B][Aa];return{C:0}
return{_B:1,_f:D} return{C:1,i:F}
async def __refresh_web_token(B): async def __refresh_web_token(D):
A=await B.__fetch(refresh_web_token_api,{});C=B.handle_request_result_message('refresh_web_token_api',A) A=await D.fetch(Ap,{});E=D.handle_request_result_message('refresh_web_token_api',A)
if _H in A and A[_H]==_G:B.accessToken=A[_A][_At];B.refreshToken=A[_A][_AG];return{_B:0} if J in A and A[J]==H:D.accessToken=A[B][BS];D.refreshToken=A[B][Aa];return{C:0}
return{_B:1,_f:C} return{C:1,i:E}
async def __get_door_number(A): async def __get_door_number(E):
B=configuration[_Ac];G={_C:B[_C],_E:B[_E],_S:B[_S],_K:{_W:B[_K][_W],_Z:B[_K][_Z],_a:B[_K][_a],_X:B[_K][_X]},_A1:{_R:A.userInfo[_R]},_p:A.token};C=await A.__fetch_safe(get_door_number_api,G);H=A.handle_request_result_message('get_door_number_api',C) H={D:F[D],G:F[G],V:F[V],M:{a:F[AE][M][a],d:F[AE][M][d],e:F[AE][M][e],b:F[AE][M][b]},A8:{U:E.userInfo[U]},r:E.token};A=await E.fetch(Aq,H);I=E.handle_request_result_message('get_door_number_api',A)
if _H in C and C[_H]==1 and _A in C and _k in C[_A]: if J in A and A[J]==1 and B in A and m in A[B]:E.powerUserList=A[B][m][B0];return{C:0}
E={} return{C:1,i:I}
if A.powerUserList is not _F:E={A[_g]:A for A in A.powerUserList} async def __get_door_balance(L,door_account):
F=[] C=door_account;O={B:{N:A,Q:A,I:F[u][I],E:F[u][E],AA:L.userInfo[U],AB:L.userInfo[AI],W:H,h:H,Ac:L.userInfo[U],AC:[{BT:C[s],AJ:C[X],BU:C[B1],n:C[n],c:C[c]}]},D:As,G:F[G],V:C[X]};K=await L.fetch(AP,O);L.handle_request_result_message('get_door_balance_api',K)
for D in C[_A][_k][_AT]: if J in K and K[J]==1 and B in K and AC in K[B]:
if D[_g]in E:F.append(E[D[_g]]) M=K[B][AC]
elif _AU in D and D[_AU]!='05':F.append(D) if t(M)!=0:C[AK]=M[0]
A.powerUserList=F;return{_B:0} async def __get_door_bill(L,door_account,year):
return{_B:1,_f:H} P='dataInfo';M='mothEleList';C=door_account;O={B:{N:A,Q:A,I:F[u][I],E:F[u][E],AA:L.userInfo[U],AB:L.userInfo[AI],W:H,h:H,Ac:L.userInfo[U],AC:[{BT:C[s],AJ:C[X],BU:C['consSortCode'],n:C[n],c:C[c]}]},D:As,G:F[G],V:C[X]};O={B:{AA:L.userInfo[U],I:F[I],l:'11',B2:C[B1],E:'ALIPAY_01',c:C[c],AJ:C[X],h:H,W:H,Q:A,N:A,AB:A,BV:C[X],Ac:L.userInfo[U],n:C[n],BW:year},D:A7,G:A6,V:C[X]};K=await L.fetch(AQ,O);L.handle_request_result_message('get_door_bill_api',K)
async def __get_door_balance(B,door_account): if J in K and K[J]==1 and B in K:
A=door_account;E={_A:{_L:'',_N:'',_I:configuration[_A7][_I],_D:configuration[_A7][_D],_A3:B.userInfo[_R],_A4:B.userInfo.get(_AB,B.userInfo.get('nickname',_F)),_T:_G,_d:_G,_AI:B.userInfo[_R],_u:[{'consNoSrc':A[_g],_AJ:A.get(_U,A.get(_AK,_F)),'sceneType':A.get('consSortCode',A.get(_AU,_F)),_q:A[_q],_Y:A[_Y]}]},_C:'0101143',_E:configuration[_E],_S:A.get(_U,A.get(_AK,_F))};C=await B.__fetch_safe(get_door_balance_api,E);B.handle_request_result_message('get_door_balance_api',C) if P in K[B]:C[Ad]=K[B][P]
if _H in C and C[_H]==1 and _A in C and _u in C[_A]: if M in K[B]:C[AD]=K[B][M];C[Ae]=K[B][M][-1]['month']
D=C[_A][_u] async def __get_door_ladder(H,door_account,month):
if len(D)!=0:A[_A5]=D[0] O='ladder_flag';M=month;C=door_account;P=C[s];R={B:{I:F[v][I],E:F[v][E],W:F[v][W],l:F[v][l],n:C[s],h:C[X],c:C[c],'queryDate':M,BV:C[X],B2:C[B1],Ac:H.userInfo[U],Q:A,N:A,AB:H.userInfo[AI],AA:H.userInfo[U]},D:F[v][D],G:F[v][G],V:C[X]};K=await H.fetch(AR,R);S=H.handle_request_result_message('get_door_ladder_api',K)
async def __get_door_bill(C,door_account,monthDate): if J in K and K[J]==1 and B in K and AC in K[B]:
I='dataInfo';G='mothEleList';E=monthDate;A=door_account;J={_A:{_A3:C.userInfo[_R],_I:configuration[_I],_e:'11',_AL:A[_AW],_D:'ALIPAY_01',_Y:A[_Y],_AJ:A[_U],_d:_G,_T:_G,_N:'',_L:'',_A4:'',_AV:A[_U],_AI:C.userInfo[_R],_q:A[_q],_Au:E.year},_C:_A0,_E:_z,_S:A[_U]};B=await C.__fetch_safe(get_door_bill_api,J);C.handle_request_result_message('get_door_bill_api',B) L=K[B][AC]
if _H in B and B[_H]==1 and _A in B: if t(L)!=0:
if I in B[_A]:A[_AM]=B[_A][I] L=L[0];L['month']=M
if G in B[_A]: if L['electricParticulars']['levelFlag']=='2':C[O]=1
if _AC not in A or A[_AC]!=E.year:A[_l]=B[_A][G];A[_AC]=E.year else:C[O]=0
else: H.doorAccountDict[P]['ladder']=L
F={A.month:A for A in A[_l]};H=B[_A][G] async def __get_door_daily_bill(C,door_account,year,start_date,end_date):
for D in H: L='sevenEleList';K=door_account;O={BX:{D:F[D],G:F[G],V:F[V],M:{a:F[M][a],d:F[M][d],e:F[M][e],b:F[M][b]},A8:{U:C.userInfo[U]},r:C.token},BY:{B:{AA:C.userInfo[U],n:K[s],B2:g,'endTime':end_date,c:K[c],BW:year,AJ:K[X],Q:A,N:A,'startTime':start_date,AB:C.userInfo[AI],E:F[p][E],I:F[p][I],l:F[p][l],h:F[p][h],W:F[p][W]},D:F[p][D],G:F[p][G],V:K[X]},BZ:'010103'};H=await C.fetch(AT,O);P=C.handle_request_result_message('get_door_daily_bill_api',H)
if D.month in F and _h in F[D.month]:D[_h]=F[D.month][_h] if J in H and H[J]==1 and B in H and L in H[B]:K[Y]=H[B][L]
A[_l]=H async def __get_door_pay_record(C,door_account):J=door_account;L=J[s];K={BX:{D:F[D],G:F[G],V:F[V],M:{a:F[M][a],d:F[M][d],e:F[M][e],b:F[M][b]},A8:{U:C.userInfo[U]},r:C.token},BY:{B:{AA:C.userInfo[U],'bgnPayDate':'2023-04-24',I:F[I],n:J[s],'endPayDate':'2024-04-24',E:'webALIPAY_01','number':100,c:J[c],'page':H,AJ:J[X],h:H,W:H,Q:A,N:A,AB:C.userInfo[AI]},D:'0101051',G:g,V:J[X]},BZ:'010104'};O=await C.fetch(AS,K)
if len(A[_l])>0:A[_v]=A[_l][-1]
async def __get_door_ladder(C,door_account,monthBill):
E=monthBill;A=door_account;I=A[_g];F=datetime.datetime.strptime(E[_AN],'%Y%m');G=f"{F.year}-{F.month:02d}";H={_A:{_I:configuration[_V][_I],_D:configuration[_V][_D],_T:configuration[_V][_T],_e:configuration[_V][_e],_q:A[_g],_d:A[_U],_Y:A[_Y],_Av:G,_AV:A[_U],_AL:A[_AW],_AI:C.userInfo[_R],_N:'',_L:'',_A4:C.userInfo[_AB],_A3:C.userInfo[_R]},_C:configuration[_V][_C],_E:configuration[_V][_E],_S:A[_U]};B=await C.__fetch(get_door_ladder_api,H);J=C.handle_request_result_message(_Aw,B)
if _H in B and B[_H]==1 and _A in B and _u in B[_A]:
D=B[_A][_u]
if len(D)!=0:D=D[0];E['ladder']=D
async def __get_door_mouth_bill(E,door_account,monthBill):
O='pointList';H=monthBill;G='quantity';F='priceName';B=door_account;I=datetime.datetime.strptime(H[_AN],'%Y%m');P=f"{I.year}-{I.month:02d}";Q={_A:{_I:configuration[_V][_I],_D:configuration[_V][_D],_T:configuration[_V][_T],_e:configuration[_V][_e],_q:B[_g],_d:B[_U],_Y:B[_Y],_Av:P,_AV:B[_U],_AL:B[_AW],_AI:E.userInfo[_R],_N:'',_L:'',_A4:E.userInfo[_AB],_A3:E.userInfo[_R]},_C:configuration[_V][_C],_E:configuration[_V][_E],_S:B[_U]};C=await E.__fetch(get_door_ladder_api,Q);S=E.handle_request_result_message(_Aw,C)
if _H in C and C[_H]==1 and _A in C and _u in C[_A]:
J=C[_A][_u][0];R=catchFloat(J[O][0]['readList'][0],'activeCount');K=0;L=0;M=0;N=0
for A in J[O][0]['amtGroupList'][0]['amtList']:
if A[F]=='':K=catchFloat(A,G)
elif A[F]=='':L=catchFloat(A,G)
elif A[F]=='':M=catchFloat(A,G)
elif A[F]=='':N=catchFloat(A,G)
D={};D[_AX]=normal_round(R,2);D[_AY]=normal_round(K,2);D[_AZ]=normal_round(L,2);D[_Aa]=normal_round(M,2);D[_Ab]=normal_round(N,2);H[_h]=D
async def __get_door_daily_bill(B,door_account,year,start_date,end_date):
D='sevenEleList';A=door_account;E={'params1':{_C:configuration[_C],_E:configuration[_E],_S:configuration[_S],_K:{_W:configuration[_K][_W],_Z:configuration[_K][_Z],_a:configuration[_K][_a],_X:configuration[_K][_X]},_A1:{_R:B.userInfo[_R]},_p:B.token},'params3':{_A:{_A3:B.userInfo[_R],_q:A[_g],_AL:_c,'endTime':end_date,_Y:A[_Y],_Au:year,_AJ:A.get(_U,A.get(_AK,_F)),_N:'',_L:'','startTime':start_date,_A4:B.userInfo[_AB],_D:configuration[_m][_D],_I:configuration[_m][_I],_e:configuration[_m][_e],_d:configuration[_m][_d],_T:configuration[_m][_T]},_C:configuration[_m][_C],_E:configuration[_m][_E],_S:A.get(_U,A.get(_AK,_F))},'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 D in C[_A]:A[_A6]=C[_A][D]
async def __get_door_pay_record(A,door_account):B=door_account;D=B[_g];C={'params1':{_C:configuration[_C],_E:configuration[_E],_S:configuration[_S],_K:{_W:configuration[_K][_W],_Z:configuration[_K][_Z],_a:configuration[_K][_a],_X:configuration[_K][_X]},_A1:{_R:A.userInfo[_R]},_p:A.token},'params3':{_A:{_A3:A.userInfo[_R],'bgnPayDate':'2023-04-24',_I:configuration[_I],_q:B[_g],'endPayDate':'2024-04-24',_D:'webALIPAY_01','number':100,_Y:B[_Y],'page':_G,_AJ:B[_U],_d:_G,_T:_G,_N:'',_L:'',_A4:A.userInfo[_AB]},_C:'0101051',_E:_c,_S:B[_U]},'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 _B in A and A[_B]!=0:return A if C in A and A[C]!=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 _B in A and A[_B]!=0:return A if C in A and A[C]!=0:return A
A=await B.__get_qr_code_token() A=await B.__get_qr_code_token()
if _B in A and A[_B]!=0:return A if C in A and A[C]!=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 _B in A and A[_B]!=0:return A if C in A and A[C]!=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 _B in A and A[_B]!=0:return A if C in A and A[C]!=0:return A
return await B.__get_token() return await B.__get_token()
async def __get_token(B): async def __get_token(D):
A=await B.__get_request_key() A=await D.__get_request_key()
if _B in A and A[_B]!=0:return A if C in A and A[C]!=0:return A
A=await B.__get_request_authorize() A=await D.__get_request_authorize()
if _B in A and A[_B]!=0:return A if C in A and A[C]!=0:return A
A=await B.__get_web_token() A=await D.__get_web_token()
if _B in A and A[_B]!=0:return A if C in A and A[C]!=0:return A
A=await B.__get_door_number() A=await D.__get_door_number()
if _B in A and A[_B]!=0:return A if C in A and A[C]!=0:return A
B.need_login=_i;await B.save_data();return{_B:0,_A:B.powerUserList} D.need_login=z;await D.save_data();return{C:0,B:D.powerUserList}
async def __refresh_token(A): async def refresh_data(B,setup=z):
B=await A.__get_request_key() q='daily_t_ele_num';p='daily_n_ele_num';o='daily_v_ele_num';n='daily_p_ele_num';m='daily_ele_num';l='last_month_ele_cost';k='last_month_ele_num';i='year_ele_cost';h='year_ele_num';g='monthEleNum';f='thisTPq';e='thisNPq';d='thisVPq';c='thisPPq';T='balance';S='ladder_level_num';R='ladder_level';L='%Y%m%d';K='day';I='dayElePq';r=setup or int(Af.time()*1000)-B.timestamp>B.refresh_interval*3600*1000
if _B in B and B[_B]!=0:return if r is z:return
B=await A.__refresh_web_token() E=await B.__get_door_number()
if _B in B and B[_B]==0:A.need_login=_i;A.retry_times=0;await A.save_data() if C in E and E[C]!=0:
elif A.retry_times>=3:A.need_login=_o A0.warning('刷新 Token');E=await B.__get_request_key()
else:A.retry_times=A.retry_times+1 if C in E and E[C]!=0:return
async def refresh_data(B,setup=_i,force_refresh=_i): E=await B.__refresh_web_token()
t='last_month_ele_cost';s='year_ele_cost';r='thisTPq';q='thisNPq';p='thisVPq';o='thisPPq';n='%Y%m%d';m='day';l='refresh_time';a=setup;Z='last_month_ele_num';Y='dayElePq';T='year_ele_num';G='balance' if C in E and E[C]==0:await B.save_data()
if a is _o: else:B.need_login=AW;A0.error('刷新 Token 失败');return
if B.dataVersion!=VERSION:B.powerUserList=_F E=await B.__get_door_number()
b=await B.__get_door_number() if C in E and E[C]!=0:B.need_login=AW;A0.error('重新请求失败');return
if _B in b and b[_B]!=0:B.need_login=_o M=j.datetime.now();J=M-j.timedelta(days=1);u=f"{J.year}-{J.month:02d}-{J.day:02d}";N=J-j.timedelta(days=40);v=f"{N.year}-{N.month:02d}-{N.day:02d}"
if B.need_login is _o:
if B.powerUserList is not _F:
for A in B.get_door_account_list():A[l]='Token刷新失败,请重新登录'
LOGGER.error('国家电网 - Token刷新失败,请重新登录!');return
u=a or force_refresh or int(time.time()*1000)-B.timestamp>B.refresh_interval*3600*1000
if u is _i:return
U=datetime.datetime.now();F=U-datetime.timedelta(days=1);v=f"{F.year}-{F.month:02d}-{F.day:02d}";V=F-datetime.timedelta(days=40);w=f"{V.year}-{V.month:02d}-{V.day:02d}"
for A in B.powerUserList: for A in B.powerUserList:
x=A[_g];B.doorAccountDict[x]=A;await B.__get_door_balance(A) w=A[s];B.doorAccountDict[w]=A;await B.__get_door_balance(A);await B.__get_door_daily_bill(A,M.year,v,u);O=A[Y][0]
if B.retry_times!=0:return try:float(O[I])
if _A5 in A: except:A[Y].pop(0)
y=catchFloat(A[_A5],'estiAmt');W=catchFloat(A[_A5],'prepayBal');c=catchFloat(A[_A5],'sumMoney') O=A[Y][0];F=j.datetime.strptime(O[K],L);U=0;V=0;W=0;X=0;Z=0
if W==0 or W==c:A[G]=c for D in A[Y]:
else:A[G]=W-y H=j.datetime.strptime(D[K],L)
d=catchFloat(A[_A5],'historyOwe') if H.month!=F.month:break
if d>0:A[G]=-d U+=P(D,I);V+=P(D,c);W+=P(D,d);X+=P(D,e);Z+=P(D,f)
else:LOGGER.error('国家电网账户余额获取失败!') Q=F-j.timedelta(days=F.day);a=f"{Q.year}-{Q.month:02d}"
if G not in A:A[G]=0 if Ae not in A or A[Ae]!=a:await B.__get_door_bill(A,Q.year);await B.__get_door_ladder(A,a)
await B.__get_door_daily_bill(A,U.year,w,v) x=j.datetime.strptime(A[Ae],'%Y%m')
if _A6 not in A:LOGGER.error('国家电网无法获取日用电数据!');continue if x.month==12:
X=0;H=_i G=0
for e in range(10): for D in A[Y]:
D=A[_A6][e] H=j.datetime.strptime(D[K],L)
try:float(D[Y]);H=_o;break if H.month!=12:break
except:X=X+1 G+=P(D,I)
f=0;g=0;h=0;i=0;j=0
if H:
for e in range(X):A[_A6].pop(0)
D=A[_A6][0];E=datetime.datetime.strptime(D[m],n);A['daily_lasted_date']=f"{E.year}-{E.month:02d}-{E.day:02d}";f=catchFloat(D,Y);g=catchFloat(D,o);h=catchFloat(D,p);i=catchFloat(D,q);j=catchFloat(D,r)
A['daily_ele_num']=normal_round(f,2);A['daily_p_ele_num']=normal_round(g,2);A['daily_v_ele_num']=normal_round(h,2);A['daily_n_ele_num']=normal_round(i,2);A['daily_t_ele_num']=normal_round(j,2);I=0;J=0;K=0;L=0;M=0
if H:
for C in A[_A6]:
z=datetime.datetime.strptime(C[m],n)
if z.month!=E.month:break
I+=catchFloat(C,Y);J+=catchFloat(C,o);K+=catchFloat(C,p);L+=catchFloat(C,q);M+=catchFloat(C,r)
A[_AX]=normal_round(I,2);A[_AY]=normal_round(J,2);A[_AZ]=normal_round(K,2);A[_Aa]=normal_round(L,2);A[_Ab]=normal_round(M,2)
if H:
N=E-datetime.timedelta(days=E.day);A0=f"{N.year}{N.month:02d}"
if _AC not in A or A[_AC]!=N.year or _v not in A or A[_v][_AN]!=A0:await B.__get_door_bill(A,N)
if _l in A:
for C in A[_l]:
if _h not in C:await B.__get_door_mouth_bill(A,C)
if _AM in A:A[T]=catchFloat(A[_AM],'totalEleNum');A[s]=catchFloat(A[_AM],'totalEleCost')
if T not in A:A[T]=0;A[s]=0
if _v in A:A[Z]=catchFloat(A[_v],'monthEleNum');A[t]=catchFloat(A[_v],'monthEleCost');k=datetime.datetime.strptime(A[_v][_AN],'%Y%m')
if Z not in A:A[Z]=0;A[t]=0;k=F.month
O=0;P=0;Q=0;R=0;S=0
if k.month==12:O=I;P=J;Q=K;R=L;S=M
else: else:
if _l in A: G=0
for C in A[_l]: for D in A[AD]:G+=P(D,g)
if _h in C:O+=C[_h][_AX];P+=C[_h][_AY];Q+=C[_h][_AZ];R+=C[_h][_Aa];S+=C[_h][_Ab] y=t(A[AD])
O+=I;P+=J;Q+=K;R+=L;S+=M for D in A[Y]:
A[T]=normal_round(O,2);A['year_p_ele_num']=normal_round(P,2);A['year_v_ele_num']=normal_round(Q,2);A['year_n_ele_num']=normal_round(R,2);A['year_t_ele_num']=normal_round(S,2);A[l]=datetime.datetime.strftime(U,'%Y-%m-%d %H:%M:%S') H=j.datetime.strptime(D[K],L)
if H.month<=y:break
G+=P(D,I)
if G<=2760:A[R]='第一阶梯';A[S]=1
elif G<=4800:A[R]='第二阶梯';A[S]=2
else:A[R]='第三阶梯';A[S]=3
if AK in A:
A1=P(A[AK],'estiAmt');A2=P(A[AK],'prepayBal');A[T]=A2-A1;b=P(A[AK],'historyOwe')
if b>0:A[T]=-b
else:A[T]=0
if Ad in A:A[h]=P(A[Ad],'totalEleNum');A[i]=P(A[Ad],'totalEleCost')
else:A[h]=0;A[i]=0
if AD in A:A[k]=P(A[AD][-1],g);A[l]=P(A[AD][-1],'monthEleCost')
else:A[k]=0;A[l]=0
if Y in A:A[m]=P(A[Y][0],I);A[n]=P(A[Y][0],c);A[o]=P(A[Y][0],d);A[p]=P(A[Y][0],e);A[q]=P(A[Y][0],f)
else:A[m]=0;A[n]=0;A[o]=0;A[p]=0;A[q]=0
A['month_ele_num']=U;A['month_p_ele_num']=V;A['month_v_ele_num']=W;A['month_n_ele_num']=X;A['month_t_ele_num']=Z;A['daily_lasted_date']=f"{F.year}-{F.month:02d}-{F.day:02d}";A['refresh_time']=j.datetime.strftime(M,'%Y-%m-%d %H:%M:%S')
await B.save_data() await B.save_data()
def get_door_account_list(A):return list(A.doorAccountDict.values()) 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
+2 -2
View File
@@ -3,7 +3,7 @@
"name": "国家电网", "name": "国家电网",
"codeowners": ["@hassbox"], "codeowners": ["@hassbox"],
"config_flow": true, "config_flow": true,
"documentation": "https://hassbox.cn/", "documentation": "https://github.com/hass-box/state-grid",
"iot_class": "cloud_polling", "iot_class": "cloud_polling",
"version": "0.1.6" "version": "0.0.4"
} }
+138 -174
View File
@@ -2,11 +2,13 @@ from homeassistant.components.sensor import (
DOMAIN as SENSOR_DOMAIN, DOMAIN as SENSOR_DOMAIN,
SensorDeviceClass, SensorDeviceClass,
SensorEntity, SensorEntity,
SensorEntityDescription,
SensorStateClass, SensorStateClass,
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import UnitOfEnergy from homeassistant.const import UnitOfEnergy
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity
@@ -16,213 +18,175 @@ from .const import DOMAIN, VERSION
from .data_client import StateGridDataClient from .data_client import StateGridDataClient
from .coordinator import StateGridCoordinator from .coordinator import StateGridCoordinator
UNIT_YUAN = "" CURRENCY_YUAN = ""
ENTITY_ID_SENSOR_FORMAT = SENSOR_DOMAIN + ".state_grid_" ENTITY_ID_SENSOR_FORMAT = SENSOR_DOMAIN + ".state_grid_"
SENSOR_TYPES = [ SENSOR_TYPES = (
{ SensorEntityDescription(
"key":"balance", key="balance",
"name": "账户余额", translation_key="balance",
"native_unit_of_measurement": UNIT_YUAN, native_unit_of_measurement=CURRENCY_YUAN,
"device_class": SensorDeviceClass.MONETARY, device_class=SensorDeviceClass.MONETARY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "year_ele_num", key="year_ele_num",
"name": "年度累计用电", translation_key="year_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "year_p_ele_num", key="year_ele_cost",
"name": "年度累计峰用电", translation_key="year_ele_cost",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=CURRENCY_YUAN,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.MONETARY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "year_v_ele_num", key="last_month_ele_num",
"name": "年度累计谷用电", translation_key="last_month_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "year_n_ele_num", key="last_month_ele_cost",
"name": "年度累计平用电", translation_key="last_month_ele_cost",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=CURRENCY_YUAN,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.MONETARY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "year_t_ele_num", key="month_ele_num",
"name": "年度累计尖用电", translation_key="month_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "year_ele_cost", key="month_p_ele_num",
"name": "年度累计电费", translation_key="month_p_ele_num",
"native_unit_of_measurement": UNIT_YUAN, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.MONETARY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "last_month_ele_num", key="month_v_ele_num",
"name": "上个月用电", translation_key="month_v_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "last_month_ele_cost", key="month_n_ele_num",
"name": "上个月电费", translation_key="month_n_ele_num",
"native_unit_of_measurement": UNIT_YUAN, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.MONETARY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "month_ele_num", key="month_t_ele_num",
"name": "当月累计用电", translation_key="month_t_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "month_p_ele_num", key="daily_ele_num",
"name": "当月累计峰用电", translation_key="daily_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "month_v_ele_num", key="daily_p_ele_num",
"name": "当月累计谷用电", translation_key="daily_p_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "month_n_ele_num", key="daily_v_ele_num",
"name": "当月累计平用电", translation_key="daily_v_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "month_t_ele_num", key="daily_n_ele_num",
"name": "当月累计尖用电", translation_key="daily_n_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "daily_ele_num", key="daily_t_ele_num",
"name": "日总用电", translation_key="daily_t_ele_num",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY, device_class=SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL state_class=SensorStateClass.TOTAL
}, ),
{ SensorEntityDescription(
"key": "daily_p_ele_num", key="daily_lasted_date",
"name": "日峰用电", translation_key="daily_lasted_date"
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR, ),
"device_class": SensorDeviceClass.ENERGY, SensorEntityDescription(
"state_class": SensorStateClass.TOTAL key="refresh_time",
}, translation_key="refresh_time"
{ )
"key": "daily_v_ele_num", )
"name": "日谷用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL
},
{
"key": "daily_n_ele_num",
"name": "日平用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL
},
{
"key": "daily_t_ele_num",
"name": "日尖用电",
"native_unit_of_measurement": UnitOfEnergy.KILO_WATT_HOUR,
"device_class": SensorDeviceClass.ENERGY,
"state_class": SensorStateClass.TOTAL
},
{
"key": "daily_lasted_date",
"name": "最新日用电日期"
},
{
"key": "refresh_time",
"name": "最近刷新时间"
}
]
SENSOR_TYPES_FOR_LADDER = [ SENSOR_TYPES_FOR_LADDER = (
{ SensorEntityDescription(
"key": "ladder_level", key="ladder_level",
"name": "当前阶梯" translation_key="ladder_level"
}, ),
] )
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None: ) -> None:
data_client: StateGridDataClient = hass.data[DOMAIN]
coordinator = StateGridCoordinator(hass) coordinator = StateGridCoordinator(hass)
data_client.coordinator = coordinator
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
door_account_list = data_client.get_door_account_list() data_client: StateGridDataClient = hass.data[DOMAIN]
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, description, entry.entry_id, coordinator) for description in SENSOR_TYPES]
) )
# if door_account["ladder_flag"] == 1: # if door_account["ladder_flag"] == 1:
# async_add_entities( # async_add_entities(
# StateGridSensor(door_account, sensor_type, entry.entry_id) # StateGridSensor(door_account, description, entry.entry_id)
# for sensor_type in SENSOR_TYPES_FOR_LADDER # for description in SENSOR_TYPES_FOR_LADDER
# ) # )
class StateGridSensor(CoordinatorEntity[StateGridCoordinator], SensorEntity): class StateGridSensor(CoordinatorEntity[StateGridCoordinator], SensorEntity):
_attr_has_entity_name = True _attr_has_entity_name = True
entity_description: SensorEntityDescription
def __init__( def __init__(
self, door_account, sensor_type, entry_id: str, coordinator: StateGridCoordinator, self, door_account, entity_description: SensorEntityDescription, entry_id: str, coordinator: StateGridCoordinator,
) -> None: ) -> None:
super().__init__(coordinator) super().__init__(coordinator)
self.entity_description = entity_description
self.door_account = door_account self.door_account = door_account
self.sensor_type = sensor_type self.entity_id = SENSOR_DOMAIN + ".state_grid" + "_" + door_account["consNo_dst"] + "_" + entity_description.key
self.entity_id = SENSOR_DOMAIN + ".state_grid" + "_" + door_account["consNo_dst"] + "_" + sensor_type["key"] self._attr_translation_key = entity_description.key
self._attr_name = sensor_type["name"] self._attr_unique_id = entry_id + "-" + door_account["consNo_dst"] + "-" + entity_description.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:
self._attr_native_unit_of_measurement = sensor_type["native_unit_of_measurement"]
self._attr_device_info = { self._attr_device_info = {
"name": door_account["elecAddr_dst"], "name": door_account["elecAddr_dst"],
"identifiers": {(DOMAIN, door_account["consNo_dst"])}, "identifiers": {(DOMAIN, door_account["consNo_dst"])},
"sw_version": VERSION, "sw_version": VERSION,
"manufacturer": "HassBox", "manufacturer": "HassBox",
"model": "户号:" + door_account["consName_dst"] + " - " + door_account["consNo_dst"] "model": "户号:" + door_account["consName_dst"] + " - " + door_account["consNo_dst"],
"entry_type": DeviceEntryType.SERVICE,
} }
@property @property
def native_value(self): def native_value(self):
data = self.coordinator.data[self.door_account["consNo_dst"]] data = self.coordinator.data[self.door_account["consNo_dst"]]
return data[self.sensor_type["key"]] return data[self.entity_description.key]
+58
View File
@@ -70,5 +70,63 @@
"get_qr_code_error": "{errmsg}", "get_qr_code_error": "{errmsg}",
"check_qr_code_error": "{errmsg}" "check_qr_code_error": "{errmsg}"
} }
},
"entity": {
"sensor": {
"balance": {
"name": "账户余额"
},
"year_ele_num": {
"name": "年度累计用电"
},
"year_ele_cost": {
"name": "年度累计电费"
},
"last_month_ele_num": {
"name": "上个月用电"
},
"last_month_ele_cost": {
"name": "上个月电费"
},
"month_ele_num": {
"name": "当月累计用电"
},
"month_p_ele_num": {
"name": "当月累计峰用电"
},
"month_v_ele_num": {
"name": "当月累计谷用电"
},
"month_n_ele_num": {
"name": "当月累计平用电"
},
"month_t_ele_num": {
"name": "当月累计尖用电"
},
"daily_ele_num": {
"name": "日总用电"
},
"daily_p_ele_num": {
"name": "日峰用电"
},
"daily_v_ele_num": {
"name": "日谷用电"
},
"daily_n_ele_num": {
"name": "日平用电"
},
"daily_t_ele_num": {
"name": "日尖用电"
},
"daily_lasted_date": {
"name": "最新日用电日期"
},
"ladder_level": {
"name": "当前阶梯"
},
"refresh_time": {
"name": "最近刷新时间"
}
}
} }
} }
@@ -1,74 +0,0 @@
{
"config": {
"flow_title": "国家电网",
"step": {
"user": {
"title": "国家电网",
"description": "集成国家电网可以选择网上国网 App 扫码登录或短信验证码登录。如登录异常,可至 **HassBox全屋智能** 微信公众号联系客服。"
},
"code_login": {
"title": "短信验证码登录",
"description": "手机号需先在网上电网 App 注册并绑定户号",
"data": {
"phone": "请输入手机号"
}
},
"verfiy_code": {
"title": "短信验证码登录",
"data": {
"code": "请输入验证码"
}
},
"check_qr_code": {
"title": "网上国网 App 扫码登录",
"description": "\n {qr_image} \n\n\n 请使用 网上国网 App 扫码登录,确认登录后再点击提交。"
}
},
"abort": {
"single_instance_allowed": "该集成已经配置过了,且只能配置一次。若要重新配置,请先删除旧集成。",
"get_qr_code_error": "{errmsg}",
"check_qr_code_error": "{errmsg}"
}
},
"options": {
"step": {
"debug": {
"title": "国家电网",
"description": "国家电网当日用电等数据一般隔天才会刷新,且各地区时间不一,可根据情况适当调整接口轮询间隔。",
"data": {
"refresh_interval": "轮询间隔",
"is_debug": "调试模式"
},
"data_description": {
"is_debug": "打开调试开关后,将会打印所有请求日志。可在[配置]-[系统]-[日志]中查看。\n如需反馈异常,可至 **HassBox全屋智能** 微信公众号联系客服。"
}
},
"user": {
"title": "重新登录国家电网",
"description": "刷新 Token 异常,需重新登录。\n如需反馈异常,可至 **HassBox全屋智能** 微信公众号联系客服。"
},
"code_login": {
"title": "短信验证码登录",
"description": "手机号需先在网上电网 App 注册并绑定户号",
"data": {
"phone": "请输入手机号"
}
},
"verfiy_code": {
"title": "短信验证码登录",
"data": {
"code": "请输入验证码"
}
},
"check_qr_code": {
"title": "网上国网 App 扫码登录",
"description": "\n {qr_image} \n\n\n 请使用 网上国网 App 扫码登录,确认登录后再点击提交。"
}
},
"abort": {
"single_instance_allowed": "该集成已经配置过了,且只能配置一次。若要重新配置,请先删除旧集成。",
"get_qr_code_error": "{errmsg}",
"check_qr_code_error": "{errmsg}"
}
}
}
@@ -70,5 +70,63 @@
"get_qr_code_error": "{errmsg}", "get_qr_code_error": "{errmsg}",
"check_qr_code_error": "{errmsg}" "check_qr_code_error": "{errmsg}"
} }
},
"entity": {
"sensor": {
"balance": {
"name": "账户余额"
},
"year_ele_num": {
"name": "年度累计用电"
},
"year_ele_cost": {
"name": "年度累计电费"
},
"last_month_ele_num": {
"name": "上个月用电"
},
"last_month_ele_cost": {
"name": "上个月电费"
},
"month_ele_num": {
"name": "当月累计用电"
},
"month_p_ele_num": {
"name": "当月累计峰用电"
},
"month_v_ele_num": {
"name": "当月累计谷用电"
},
"month_n_ele_num": {
"name": "当月累计平用电"
},
"month_t_ele_num": {
"name": "当月累计尖用电"
},
"daily_ele_num": {
"name": "日总用电"
},
"daily_p_ele_num": {
"name": "日峰用电"
},
"daily_v_ele_num": {
"name": "日谷用电"
},
"daily_n_ele_num": {
"name": "日平用电"
},
"daily_t_ele_num": {
"name": "日尖用电"
},
"daily_lasted_date": {
"name": "最新日用电日期"
},
"ladder_level": {
"name": "当前阶梯"
},
"refresh_time": {
"name": "最近刷新时间"
}
}
} }
} }
+75
View File
@@ -0,0 +1,75 @@
#!/bin/bash
# curl -fsSL get.hassbox.cn/state_grid | bash
set -e
export LC_ALL=en_US.UTF-8
RED_COLOR='\033[0;31m'
GREEN_COLOR='\033[0;32m'
GREEN_YELLOW='\033[1;33m'
NO_COLOR='\033[0m'
declare haPath
declare -a paths=(
"$PWD"
"$PWD/config"
"/config"
"$HOME/.homeassistant"
"/usr/share/hassio/homeassistant"
)
function info () { echo -e "${GREEN_COLOR}INFO: $1${NO_COLOR}";}
function warn () { echo -e "${GREEN_YELLOW}WARN: $1${NO_COLOR}";}
function error () { echo -e "${RED_COLOR}ERROR: $1${NO_COLOR}";}
function checkRequirement () {
if [ -z "$(command -v "$1")" ]; then
warn "'$1' 未安装,准备安装..."
apt install $1
fi
}
info "检查依赖项"
checkRequirement "wget"
checkRequirement "unzip"
for path in "${paths[@]}"; do
if [ -n "$haPath" ]; then
break
fi
if [ -f "$path/.HA_VERSION" ]; then
haPath="$path"
fi
done
if [ -z "$haPath" ]; then
echo
error "找不到 Home Assistant 根目录"
exit 1
fi
cd "$haPath"
if [ ! -d "$haPath/custom_components" ]; then
mkdir "$haPath/custom_components"
fi
cd "$haPath/custom_components"
info "检查依赖项 ok"
info "下载 state_grid 集成包"
wget "https://get.hasss.cn/state_grid.zip" >/dev/null 2>&1
info "下载 HassBox 集成包 ok"
info "state_grid 集成包解压"
if [ -d "$haPath/custom_components/state_grid" ]; then
rm -R "$haPath/custom_components/state_grid"
fi
mkdir "$haPath/custom_components/state_grid"
unzip "$haPath/custom_components/state_grid.zip" -d "$haPath/custom_components/state_grid" >/dev/null 2>&1
rm "$haPath/custom_components/state_grid.zip"
info "HassBox 集成包解压 ok"
info "安装成功!请重启 Home Assistant!如需其他帮助,可至 HassBox全屋智能 微信公众号联系客服"
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 180 KiB