HA南京水费插件 | 宁静致远

HA南京水费插件

正在加载一言...


0.插件准备

a) 登录南京水务的官网

b) 按住F12进入开发者模式

c) 拿到cookie和客户号

结果如图:

结果截图

1.配置HA

将自定义插件上传到对应的目录下

custom_components
└─nanjing_water
sensor.py
__init__.py

接着在 configuration.yaml 中添加

sensor:

- platform: nanjing_water
name: ‘水费’
custno: ‘XXXXX’
cookies: ‘XXXXXXXXXXXXXX’

2.重启HA

3.结果展示

结果截图

4.代码展示


"""
Support for nanjing water
# Author: freefitter
# Created: 2019-08-21
"""
import logging
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 = 'nanjing_water'
COOKIES = 'cookies'
CUSTNO = 'custno'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(COOKIES): cv.string,
    vol.Required(CUSTNO): 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',
    'Referer': 'http://www.jlwater.com/waterFee/waterWx',
    'Accept-Language': 'zh-cn',
    'Accept-Encoding': 'gzip, deflate'
}
API_URL = "http://www.jlwater.com/waterFee/detail"
def setup_platform(hass, config, add_devices, discovery_info=None):
    cookies = config.get(COOKIES)
    custno = config.get(CUSTNO)
    sensor_name = config.get(CONF_NAME)
    query_dict = {
        'consNo': custno,
    }
    HEADERS["Cookie"] = cookies
    add_devices([NanjingWater(sensor_name,query_dict,cookies)])

class NanjingWater(Entity):
    """Representation of a Nanjing water """
    def __init__(self,sensor_name,query_dict,cookies):
        self.attributes = {}
        self._state = None
        self._query_dict = query_dict
        self._name = sensor_name
        self._cookies = cookies
    @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:cup-water'
    @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.get(API_URL,params=self._query_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')
        soup = BeautifulSoup(response.text,'html.parser')
        waterFee = soup.select_one("#searchFrom > div:nth-child(2) > div:nth-child(1)").get_text().split('¥')[1]
        lajiFee = soup.select_one("#searchFrom > div:nth-child(2) > div:nth-child(2)").get_text().split('¥')[1]
        weiyueFee = soup.select_one("#searchFrom > div:nth-child(2) > div:nth-child(3)").get_text().split('¥')[1]
        shangqijieyuFee = soup.select_one("#searchFrom > div:nth-child(2) > div:nth-child(4)").get_text().split('¥')[1]
        qianfeiFee = soup.select_one("#searchFrom > div:nth-child(2) > div:nth-child(2)").get_text().split('¥')[1]
        #_Log.info("waterFee=" + waterFee)
        self._state = waterFee
        self.attributes['lajiFee'] = lajiFee
        self.attributes['weiyueFee'] = weiyueFee
        self.attributes['shangqijieyuFee'] = shangqijieyuFee
        self.attributes['qianfeiFee'] = qianfeiFee

5. 附件下载

附件可以去论坛上下载 南京水费插件


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