HA中燃插件 | 宁静致远

HA中燃插件

正在加载一言...


这是中燃的燃气插件,抓包后的api还是比较友好的

0.抓包


按照国际惯例,首先抓包。从小程序入手,微信搜索 中燃慧生活 。然后打开抓包工具,开始抓包即可

1.分析抓包数据


中燃的接口还是挺友好的,都是json格式的。查看抓包的数据,找到这么一个地址 https://zrds.zrhsh.com/controller/payfee/getcustomerMoneyListForMp.do ,这个地址里面有咱想要的数据。数据咱就不贴了,都是看的到的。

2.开发插件


分析数据,插件代码如下:

"""
Support for zhongran gas
# Author:
    freefitter
# Created:
    2020/9/2
"""
import logging
import json
import datetime
from dateutil.relativedelta import relativedelta 
from homeassistant.const import (
    CONF_API_KEY, CONF_NAME, ATTR_ATTRIBUTION, CONF_ID
    )
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
import requests
from bs4 import BeautifulSoup
_Log=logging.getLogger(__name__)

DEFAULT_NAME = 'zrgas'
CUSTCODE = 'custCode'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CUSTCODE): cv.string,
    vol.Optional(CONF_NAME, default= DEFAULT_NAME): cv.string,
})

HEADERS = {
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.5(0x17000523) NetType/WIFI Language/zh_CN'
}
API_URL = "https://zrds.zrhsh.com/controller/payfee/getcustomerMoneyListForMp.do"
def setup_platform(hass, config, add_devices, discovery_info=None):
    custCode = config.get(CUSTCODE)
    sensor_name = config.get(CONF_NAME)
    today = datetime.date.today()
    current_month = datetime.datetime.strftime(today, "%Y%m")
    
    
    last_2_month = today + relativedelta(months=-2)
    last_two_month = datetime.datetime.strftime(last_2_month, "%Y%m")
    
    data_dict = {
        'custCode': custCode,
        'envir':'2',
        'startTime':last_two_month,
        'endTime':current_month,
    }
    add_devices([ZRGas(sensor_name,data_dict)])

class ZRGas(Entity):
    """Representation of a Nanjing water """
    def __init__(self,sensor_name,data_dict):
        self.attributes = {}
        self._state = None
        self._data_dict = data_dict
        self._name = sensor_name

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def icon(self):
        """返回mdi图标."""
        return 'mdi:fire'

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return self.attributes

    @property
    def unit_of_measurement(self):
        """Return the unit this state is expressed in."""
        return "元"

    def update(self):
        try:
            response = requests.post(API_URL,params=self._data_dict,headers = HEADERS)
        except ReadTimeout:
            _Log.error("Connection timeout....")
        except ConnectionError:
            _Log.error("Connection Error....")
        except RequestException:
            _Log.error("Unknown Error")
        res = response.content.decode('utf-8')
        ret = json.loads(res)
        self._state = ret["data"]["payGasCheckList"][0]["receivable"]
        self.attributes['recordMonth'] = ret["data"]["payGasCheckList"][0]["recordMonth"]
        self.attributes['curRecord'] = ret["data"]["payGasCheckList"][0]["curRecord"]
        self.attributes['curQty'] = ret["data"]["payGasCheckList"][0]["curQty"]
        self.attributes['balance'] = ret["data"]["balance"] 
        self.attributes['received'] = ret["data"]["payGasCheckList"][0]["received"]
        self.attributes['laterFee'] = ret["data"]["payGasCheckList"][0]["laterFee"]
        self.attributes['lastRecord'] = ret["data"]["payGasCheckList"][0]["lastRecord"]
        self.attributes['timeCurRecord'] = ret["data"]["payGasCheckList"][0]["timeCurRecord"]

4.配置HA


插件需要客户号,上面抓包的请求就有,拿就完事了。接着照着下面配置就行。配置完成后,重启HA就行了

- platform: zrgas
    name: '燃气费'
    custCode: 'XXXXXXX'

5.成果展示

插件展示

至此,家里的水电燃气已经接入完毕,后面再把其他的整理整理,分享出来。


文章作者: 彤爸比
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 彤爸比 !
评论
  目录