├── .gitignore ├── docs ├── lovelace.jpg └── water_meter.jpg ├── hacs.json ├── METERS.md ├── custom_components └── read_your_meter │ ├── manifest.json │ ├── utils.py │ ├── const.py │ ├── __init__.py │ ├── sensor.py │ └── client.py ├── CHANGELOG.md ├── .github ├── workflows │ └── validate.yaml ├── settings.yml ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── issue.md └── stale.yml ├── info.md ├── CONTRIBUTING.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ -------------------------------------------------------------------------------- /docs/lovelace.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyalcha/read_your_meter/HEAD/docs/lovelace.jpg -------------------------------------------------------------------------------- /docs/water_meter.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyalcha/read_your_meter/HEAD/docs/water_meter.jpg -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Read Your Meter", 3 | "domains": ["sensor"], 4 | "country": "IL", 5 | "homeassistant": "0.106.0" 6 | } -------------------------------------------------------------------------------- /METERS.md: -------------------------------------------------------------------------------- 1 | # Meters 2 | 3 | List of known corporations that known to work with this integration: 4 | 5 | - https://www.yuvalim-sh.co.il/ 6 | - https://www.mayanot-h.co.il/ 7 | - http://www.mayanot-hadarom.co.il/ 8 | - http://www.meniv-rishon.co.il/ -------------------------------------------------------------------------------- /custom_components/read_your_meter/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "read_your_meter", 3 | "name": "Read Your Meter", 4 | "version": "1.0.12", 5 | "documentation": "", 6 | "dependencies": [], 7 | "codeowners": ["@eyalcha"], 8 | "requirements": ["selenium", "beautifulsoup4"] 9 | } 10 | -------------------------------------------------------------------------------- /custom_components/read_your_meter/utils.py: -------------------------------------------------------------------------------- 1 | """Utils""" 2 | 3 | def truncate(f, n=2): 4 | '''Truncates/pads a float f to n decimal places without rounding''' 5 | s = '{}'.format(f) 6 | if 'e' in s or 'E' in s: 7 | return '{0:.{1}f}'.format(f, n) 8 | i, p, d = s.partition('.') 9 | return '.'.join([i, (d+'0'*n)[:n]]) -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | ## 1.0.10 5 | - Change unit of measurements 6 | - Add config option: unit of measurement 7 | 8 | ## 1.0.3 9 | - Change to multiple sensors (See documentation) 10 | - Use data coordinator for data fetching 11 | 12 | ## 1.0.0 13 | - **Initial Release** -------------------------------------------------------------------------------- /custom_components/read_your_meter/const.py: -------------------------------------------------------------------------------- 1 | """Constant""" 2 | 3 | DOMAIN = "read_your_meter" 4 | DOMAIN_DATA = "{}_data".format(DOMAIN) 5 | 6 | CONF_DAILY="daily" 7 | CONF_MONTHLY="monthly" 8 | 9 | DEFAULT_HOST = "http://localhost:4444" 10 | DEFAULT_SCAN_INTERVAL = 1800 11 | DEFAULT_DAILY=[0] 12 | DEFAULT_MONTHLY=[0] 13 | DEFAULT_NAME = "Read your meter" 14 | DEFAULT_ICON = "mdi:speedometer-medium" 15 | DEFAULT_UNIT_OF_MEASUREMENT = "m³" 16 | 17 | DATA = "data" 18 | DATA_CLIENT = "client" -------------------------------------------------------------------------------- /.github/workflows/validate.yaml: -------------------------------------------------------------------------------- 1 | name: Validate 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: "0 0 * * *" 8 | 9 | jobs: 10 | validate: 11 | runs-on: "ubuntu-latest" 12 | steps: 13 | - uses: "actions/checkout@v2" 14 | - name: HACS validation 15 | uses: "hacs/integration/action@master" 16 | with: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | CATEGORY: "integration" 19 | 20 | env: 21 | SKIP_BRANDS_CHECK: "True" -------------------------------------------------------------------------------- /.github/settings.yml: -------------------------------------------------------------------------------- 1 | repository: 2 | private: false 3 | has_issues: true 4 | has_projects: false 5 | has_wiki: false 6 | has_downloads: false 7 | default_branch: master 8 | allow_squash_merge: true 9 | allow_merge_commit: false 10 | allow_rebase_merge: false 11 | labels: 12 | - name: "Feature Request" 13 | color: "fbca04" 14 | - name: "Bug" 15 | color: "b60205" 16 | - name: "Wont Fix" 17 | color: "ffffff" 18 | - name: "Enhancement" 19 | color: a2eeef 20 | - name: "Documentation" 21 | color: "008672" 22 | - name: "Stale" 23 | color: "930191" -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 14 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 7 5 | # Issues with these labels will never be considered stale 6 | #exemptLabels: 7 | # - pinned 8 | # - security 9 | # Label to use when marking an issue as stale 10 | staleLabel: Stale 11 | # Comment to post when marking an issue as stale. Set to `false` to disable 12 | markComment: >- 13 | This issue has been automatically marked as stale because it has not had 14 | recent activity. It will be closed if no further activity occurs. Thank you 15 | for your contributions. 16 | # Comment to post when closing a stale issue. Set to `false` to disable 17 | closeComment: false -------------------------------------------------------------------------------- /info.md: -------------------------------------------------------------------------------- 1 | # Read Your Meter 2 | 3 | ![Water Meter](https://github.com/eyalcha/read_your_meter/raw/master/docs/water_meter.jpg) 4 | 5 | ## Features: 6 | 7 | - Read daily water consumption 8 | - Monthly consumption 9 | 10 | ## Links 11 | 12 | - [Documentation](https://github.com/eyalcha/read_your_meter) 13 | - [Configuration](https://github.com/eyalcha/read_your_meter#configuration) 14 | - [Report a Bug](https://github.com/eyalcha/read_your_meter/issues/new?template=issue.md) 15 | - [Suggest an idea](https://github.com/eyalcha/read_your_meter/issues/new?template=feature_request.md) 16 | 17 | --- 18 | 19 |

* * *

20 | I put a lot of work into making this repo and component available and updated to inspire and help others! I will be glad to receive thanks from you — it will give me new strength and add enthusiasm: 21 |


22 | PayPal 23 |

-------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Issue 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | 16 | 17 | ## Version of the custom_component 18 | 21 | 22 | ## Configuration 23 | 24 | ```yaml 25 | 26 | Add your configs here. 27 | 28 | ``` 29 | 30 | ## Describe the bug 31 | A clear and concise description of what the bug is. 32 | 33 | 34 | ## Debug log 35 | 36 | 37 | 38 | ```text 39 | 40 | Add your logs here. 41 | 42 | ``` -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution guidelines 2 | 3 | Contributing to this project should be as easy and transparent as possible, whether it's: 4 | 5 | - Reporting a bug 6 | - Discussing the current state of the code 7 | - Submitting a fix 8 | - Proposing new features 9 | 10 | ## Contributing Code 11 | 12 | Github is used to host code, to track issues and feature requests, as well as accept pull requests. 13 | 14 | Pull requests are the best way to propose changes to the codebase. 15 | 16 | 1. Fork the repo and create your branch from `master`. 17 | 2. If you've changed something, update the documentation. 18 | 3. Issue a pull request 19 | 20 | By contributing, you agree that your contributions will be licensed under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. 21 | Feel free to contact the maintainers if that's a concern. 22 | 23 | ## Coding Style 24 | 25 | This project uses [black](https://github.com/ambv/black) to ensure the code follows a consistent style. 26 | 27 | ## Report bugs using Github's issues 28 | 29 | GitHub issues are used to track public bugs. Report a bug by [opening a new issue](../../issues/new/choose) 30 | 31 | ## Write bug reports with details 32 | 33 | **Great Bug Reports** tend to have: 34 | 35 | - A quick summary and/or background 36 | - Steps to reproduce 37 | - What you expected would happen 38 | - What actually happens 39 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) -------------------------------------------------------------------------------- /custom_components/read_your_meter/__init__.py: -------------------------------------------------------------------------------- 1 | """Thermal integration""" 2 | 3 | import logging 4 | 5 | import voluptuous as vol 6 | 7 | import homeassistant.helpers.config_validation as cv 8 | 9 | from homeassistant.const import ( 10 | CONF_HOST, 11 | CONF_NAME, 12 | CONF_USERNAME, 13 | CONF_PASSWORD, 14 | CONF_SCAN_INTERVAL, 15 | CONF_UNIT_OF_MEASUREMENT 16 | ) 17 | 18 | from .client import Client 19 | 20 | from .const import ( 21 | DOMAIN, 22 | DOMAIN_DATA, 23 | CONF_DAILY, 24 | CONF_MONTHLY, 25 | DEFAULT_HOST, 26 | DEFAULT_NAME, 27 | DEFAULT_DAILY, 28 | DEFAULT_MONTHLY, 29 | DEFAULT_UNIT_OF_MEASUREMENT, 30 | DATA, DATA_CLIENT 31 | ) 32 | 33 | _LOGGER = logging.getLogger(__name__) 34 | 35 | CONFIG_SCHEMA = vol.Schema({ 36 | DOMAIN: vol.Schema({ 37 | vol.Required(CONF_USERNAME): cv.string, 38 | vol.Required(CONF_PASSWORD): cv.string, 39 | vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.url, 40 | vol.Optional(CONF_NAME, DEFAULT_NAME): cv.string, 41 | vol.Optional(CONF_SCAN_INTERVAL): cv.time_period, 42 | vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=DEFAULT_UNIT_OF_MEASUREMENT): cv.string, 43 | vol.Optional(CONF_DAILY, default=DEFAULT_DAILY): vol.All( 44 | cv.ensure_list, [vol.Range(min=0, max=3)] 45 | ), 46 | vol.Optional(CONF_MONTHLY, default=DEFAULT_MONTHLY): vol.All( 47 | cv.ensure_list, [vol.Range(min=0, max=3)] 48 | ), 49 | }) 50 | }, extra=vol.ALLOW_EXTRA) 51 | 52 | 53 | async def async_setup(hass, config): 54 | 55 | # Check configuration exists 56 | conf = config.get(DOMAIN) 57 | if conf is None: 58 | return True 59 | 60 | host = conf.get(CONF_HOST) 61 | username = conf.get(CONF_USERNAME) 62 | password = conf.get(CONF_PASSWORD) 63 | 64 | client = Client(host, 'https://cp.city-mind.com', username, password) 65 | if client is None: 66 | return True 67 | 68 | hass.data[DOMAIN_DATA] = { 69 | DATA_CLIENT: client 70 | } 71 | 72 | # Add sensors 73 | hass.async_create_task( 74 | hass.helpers.discovery.async_load_platform('sensor', DOMAIN, conf, config) 75 | ) 76 | 77 | # Initialization was successful. 78 | return True -------------------------------------------------------------------------------- /custom_components/read_your_meter/sensor.py: -------------------------------------------------------------------------------- 1 | """Read youe meter sensor.""" 2 | 3 | import logging 4 | 5 | from datetime import datetime, timedelta 6 | 7 | from homeassistant.helpers.entity import Entity 8 | from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed 9 | 10 | from homeassistant.const import ( 11 | CONF_NAME, CONF_UNIT_OF_MEASUREMENT 12 | ) 13 | 14 | from .const import ( 15 | DOMAIN_DATA, DATA, DATA_CLIENT, 16 | CONF_DAILY, CONF_MONTHLY, 17 | DEFAULT_SCAN_INTERVAL, DEFAULT_NAME, DEFAULT_ICON 18 | ) 19 | 20 | _LOGGER = logging.getLogger(__name__) 21 | 22 | 23 | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): 24 | """Setup sensor platform""" 25 | 26 | async def async_update_data(): 27 | try: 28 | client = hass.data[DOMAIN_DATA][DATA_CLIENT] 29 | await hass.async_add_executor_job(client.update_data) 30 | except Exception as e: 31 | raise UpdateFailed(f"Error communicating with server: {e}") 32 | 33 | coordinator = DataUpdateCoordinator( 34 | hass, 35 | _LOGGER, 36 | name="sensor", 37 | update_method=async_update_data, 38 | update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL), 39 | ) 40 | 41 | # Immediate refresh 42 | await coordinator.async_request_refresh() 43 | 44 | entities = [ReadYourMeterSensor(hass, discovery_info, coordinator)] 45 | for d in discovery_info.get(CONF_DAILY): 46 | entities.append(ReadYourMeterSensor(hass, discovery_info, coordinator, 'daily', d)) 47 | for m in discovery_info.get(CONF_MONTHLY): 48 | entities.append(ReadYourMeterSensor(hass, discovery_info, coordinator, 'monthly', m)) 49 | async_add_entities(entities) 50 | 51 | 52 | class ReadYourMeterSensor(Entity): 53 | """Read your meter sensor""" 54 | 55 | def __init__(self, hass, config, coordinator, period=None, index=None) -> None: 56 | """Init sensor""" 57 | self._hass = hass 58 | self._name = config.get(CONF_NAME, DEFAULT_NAME) 59 | self._coordinator = coordinator 60 | self._period = period 61 | self._index = index 62 | self._icon = DEFAULT_ICON 63 | self._client = hass.data[DOMAIN_DATA][DATA_CLIENT] 64 | self._unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) 65 | _LOGGER.debug(f"Add sensor name:{self._name} period:{self._period} index:{self._index} icon:{self._icon}") 66 | 67 | @property 68 | def name(self): 69 | """Return the name of the sensor.""" 70 | if not self._period: 71 | return self._name 72 | elif self._index == 0: 73 | return '{} {}'.format(self._name, self._period) 74 | return '{} {} {}'.format(self._name, self._period, self._index) 75 | 76 | @property 77 | def state(self): 78 | """Return the state of the sensor.""" 79 | if self._period: 80 | return self._client.consumption(self._period, self._index) 81 | else: 82 | return self._client.last_read 83 | 84 | @property 85 | def device_state_attributes(self): 86 | """Return the attributes of the sensor.""" 87 | if self._period: 88 | statistics = self._client.statistics(self._period) 89 | if self._index == 0: 90 | attributes = { 91 | "date": self._client.date(self._period, self._index), 92 | "avg": statistics['avg'] if 'avg' in statistics else 0, 93 | "min": statistics['min'] if 'min' in statistics else 0, 94 | "max": statistics['max'] if 'max' in statistics else 0, 95 | "reading_state": self._client.state(self._period, self._index) 96 | } 97 | else: 98 | attributes = { 99 | "date": self._client.date(self._period, self._index), 100 | "reading_state": self._client.state(self._period, self._index) 101 | } 102 | else: 103 | attributes = { 104 | "meter_number": self._client.meter_number, 105 | "forecast": self._client.forecast, 106 | "low_consumption": self._client.low_consumption, 107 | "house_hold_avg": self._client.house_hold_avg, 108 | "messages": self._client.messages_count 109 | } 110 | return attributes 111 | 112 | @property 113 | def icon(self): 114 | """Return the icon of the sensor.""" 115 | return self._icon 116 | 117 | @property 118 | def should_poll(self): 119 | """No need to poll. Coordinator notifies entity of updates.""" 120 | return False 121 | 122 | @property 123 | def available(self): 124 | """Return if entity is available.""" 125 | return self._coordinator.last_update_success 126 | 127 | @property 128 | def unit_of_measurement(self): 129 | """Return the unit of measurement.""" 130 | return self._unit_of_measurement 131 | 132 | async def async_update(self): 133 | """Update the entity. Only used by the generic entity update service.""" 134 | await self._coordinator.async_request_refresh() 135 | 136 | async def async_added_to_hass(self): 137 | """When entity is added to hass.""" 138 | self.async_on_remove( 139 | self._coordinator.async_add_listener( 140 | self.async_write_ha_state 141 | ) 142 | ) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg)](https://github.com/hacs/integration) 2 | 3 | *Please :star: this repo if you find it useful* 4 | 5 |


6 | PayPal 7 |

8 | 9 | # Read Your Meter 10 | 11 | The read your meter integration can be used to read your house water consumption and hopefully will enable you to save water and to early detect water leaks. 12 | 13 | ![Heat Map](./docs/water_meter.jpg) 14 | 15 | There is currently support for the following device types within Home Assistant: 16 | 17 | - [Sensor](#sensor) 18 | 19 | ## Requirements 20 | 21 | For the integration to work, you need the following: 22 | 23 | - Account in read your meter 24 | - Selenuim standalone chrome running on same device as Home Assistant. 25 | 26 | ### Install Selenuim 27 | 28 | For installing [Sellenuim](https://www.selenium.dev/) please refer to the [offical documentation](https://www.selenium.dev/documentation/en/selenium_installation). 29 | 30 | #### Raspberry PI 31 | 32 | If you want to run the Sellenuim on Raspbery Pi, you can use the following command to download and start container with the following command: 33 | 34 | ``` 35 | docker run -d -p 4444:4444 --name selenium chadbutz/rpi-selenium-standalone-chrome 36 | ``` 37 | 38 | or with docker-compose 39 | 40 | ``` 41 | version: '2.1' 42 | 43 | services: 44 | 45 | selenuim: 46 | image: chadbutz/rpi-selenium-standalone-chrome 47 | container_name: selenuim 48 | ports: 49 | - 4444:4444 50 | restart: unless-stopped 51 | ``` 52 | 53 | #### Ubuntu 54 | 55 | For unbuntu, the offical image of selenuim can be used: 56 | 57 | 58 | ``` 59 | docker run -d -p 4444:4444 --name selenium selenium/standalone-chrome 60 | ``` 61 | 62 | ### MANUAL INSTALLATION 63 | 64 | 1. Download the `read_your_meter.zip` file from the 65 | [latest release](https://github.com/eyalcha/read_your_meter/releases/latest). 66 | 2. Unpack the release and copy the `custom_components/read_your_meter` directory 67 | into the `custom_components` directory of your Home Assistant 68 | installation. 69 | 3. Configure the `read_your_meter` integration. 70 | 4. Restart Home Assistant. 71 | 72 | ### INSTALLATION VIA HACS 73 | 74 | 1. Ensure that [HACS](https://custom-components.github.io/hacs/) is installed. 75 | 2. Search for and install the `read_your_meter` integration. 76 | 3. Configure the `read_your_meter` integration. 77 | 4. Restart Home Assistant. 78 | 79 | ## Configuration 80 | 81 | To enable this integration with the default configuration, add the following lines to your configuration.yaml file: 82 | 83 | ```yaml 84 | read_your_meter: 85 | host: Selenuim host url 86 | username: Account user name 87 | password: Account password 88 | ``` 89 | 90 | |Parameter |Required|Description 91 | |:---|---|--- 92 | | `username` | Yes | Account username 93 | | `password` | Yes | Account password 94 | | `host` | No | Selenuim url (path & port) **Default** http://localhost:4444 95 | | `name` | No | Sensor prefix name **Default** Read your meter 96 | | `scan_interval` | No | NOT SUPPORTED YET **Default**: 1800 sec 97 | | `unit_of_measurement` | No | Consumption unit of measurement **Default**: m³ 98 | | `daily` | No | List of days information, starting 0 as today and up to 3 (three days ago). **Default** 0 99 | | `monthly` | No | List of month information, starting 0 as this month and up to 3 (three month ago). **Default** 0 100 | Here is an example for a minimal configuration: 101 | 102 | ```yaml 103 | # Example configuration.yaml entry 104 | 105 | read_your_meter: 106 | username: john.brinston@gmail.com 107 | password: verycomplicatedpassword 108 | ``` 109 | 110 | Advance configuration: 111 | 112 | ```yaml 113 | # Example configuration.yaml entry 114 | 115 | read_your_meter: 116 | host: http://localhost:4444 117 | username: john.brinston@gmail.com 118 | password: verycomplicatedpassword 119 | daily: 120 | - 0 121 | - 1 122 | monthly: 123 | - 0 124 | - 1 125 | - 2 126 | - 3 127 | ``` 128 | 129 | ## Sensors 130 | 131 | ### `sensor.read_your_meter` 132 | 133 | ``` 134 | state: Total water consumption 135 | 136 | attributes: 137 | meter_number: Meter number 138 | forecast: This month forecast consumption 139 | low_consumption: Max low price consumption 140 | house_hold_avg: House holde monthly average 141 | messages: Number of messages 142 | ``` 143 | 144 | ### `sensor.read_your_meter_daily` 145 | 146 | ``` 147 | state: Total water consumption daily 148 | 149 | attributes: 150 | date: Rading day date 151 | avg: Last 30 days average consumption 152 | min: Last 30 days min value 153 | max: Last 30 days max value 154 | reading_state: E.g., approximate etc. 155 | ``` 156 | 157 | ### `sensor.read_your_meter_daily_` 158 | 159 | ``` 160 | state: Total water consumption daily (x days ago) 161 | 162 | attributes: 163 | date: Rading day date 164 | reading_state: E.g., approximate etc. 165 | ``` 166 | 167 | ### `sensor.read_your_meter_monthly` 168 | 169 | ``` 170 | state: Total water consumption monthly 171 | 172 | attributes: 173 | date: Reading month date 174 | avg: Last 12 month average consumption 175 | min: Last 12 month min value 176 | max: Last 12 month max value 177 | reading_state: E.g., approximate etc. 178 | ``` 179 | 180 | ### `sensor.read_your_meter_monthly_` 181 | 182 | ``` 183 | state: Total water consumption monthly (x month ago) 184 | 185 | attributes: 186 | date: Reading month date 187 | reading_state: E.g., approximate etc. 188 | ``` 189 | 190 | # Services 191 | 192 | TBI 193 | 194 | # Lovelace 195 | 196 | An example view of Meter data. It includes: 197 | 198 | - Meter data 199 | - Daily graph (Grafana IFrame) 200 | - Threshold for exceeded notifications 201 | 202 | ![Heat Map](./docs/lovelace.jpg) 203 | 204 | ### Information Cards 205 | 206 | ``` 207 | - type: entities 208 | show_header_toggle: false 209 | entities: 210 | - type: attribute 211 | entity: sensor.read_your_meter 212 | attribute: meter_number 213 | name: Meter Number 214 | - entity: sensor.read_your_meter 215 | name: Total 216 | - entity: sensor.read_your_meter_daily 217 | type: custom:multiple-entity-row 218 | name: Daily 219 | show_state: false 220 | secondary_info: last-changed 221 | icon: mdi:calendar-today 222 | entities: 223 | - attribute: min 224 | name: Min 225 | - entity: sensor.read_your_meter_daily 226 | name: Current 227 | unit: ' ' 228 | - attribute: max 229 | name: Max 230 | - entity: sensor.read_your_meter_monthly 231 | type: custom:multiple-entity-row 232 | name: Monthly 233 | show_state: false 234 | secondary_info: last-changed 235 | icon: mdi:calendar-month 236 | entities: 237 | - attribute: min 238 | name: Min 239 | - entity: sensor.read_your_meter_monthly 240 | name: Current 241 | unit: ' ' 242 | - attribute: max 243 | name: Max 244 | ``` 245 | 246 | ### Threshold Cards 247 | 248 | ``` 249 | - type: entities 250 | show_header_toggle: false 251 | entities: 252 | - type: custom:slider-entity-row 253 | entity: input_number.water_meter_daily_threshold 254 | - type: custom:slider-entity-row 255 | entity: input_number.water_meter_monthly_threshold 256 | ``` 257 | 258 | # Automations 259 | 260 | The following example shows how to be notified when unusual daily usage has exceeded some threshold. 261 | 262 | Threshold input: 263 | 264 | ``` 265 | input_number: 266 | water_meter_daily_threshold: 267 | name: Daily Max Threshold 268 | icon: mdi:speedometer 269 | unit_of_measurement: "m³" 270 | min: 0 271 | max: 2 272 | step: 0.1 273 | ``` 274 | 275 | Notification Automation: 276 | 277 | ``` 278 | automation: 279 | - alias: Notify daily water usage exceed threshold 280 | trigger: 281 | - platform: state 282 | entity_id: sensor.read_your_meter_daily 283 | condition: 284 | - condition: template 285 | value_template: "{{ states('sensor.read_your_meter_daily') | float >= states('input_number.water_meter_daily_threshold') | float }}" 286 | action: 287 | - service: notify.Telegram 288 | data_template: 289 | message: > 290 | Daily water usage {{ states('sensor.read_your_meter_daily') }} has exceeded daily threshold, please check for leaks. 291 | 292 | ``` 293 | 294 | --- 295 | 296 | I put a lot of work into making this repo and component available and updated to inspire and help others! I will be glad to receive thanks from you — it will give me new strength and add enthusiasm: 297 |


298 | PayPal 299 |

300 | -------------------------------------------------------------------------------- /custom_components/read_your_meter/client.py: -------------------------------------------------------------------------------- 1 | """Meter client""" 2 | 3 | import logging 4 | import time 5 | import requests 6 | 7 | from datetime import datetime 8 | from urllib.parse import urljoin 9 | 10 | from selenium import webdriver 11 | from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 12 | from selenium.webdriver.support.ui import WebDriverWait 13 | from selenium.webdriver.support import expected_conditions as EC 14 | from selenium.webdriver.common.by import By 15 | from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException 16 | 17 | from bs4 import BeautifulSoup 18 | 19 | from .utils import truncate 20 | 21 | _LOGGER = logging.getLogger(__name__) 22 | 23 | 24 | class Client: 25 | 26 | def __init__(self, selenium, host, username, password): 27 | """Initialize the class.""" 28 | self._selenium = selenium 29 | self._host = host 30 | self._username = username 31 | self._password = password 32 | self._meter_number = None 33 | self._last_read = None 34 | self._forecast = None 35 | self._low_consumption = None 36 | self._house_hold_avg = None 37 | self._messages_count = None 38 | self._daily_table = [] 39 | self._monthly_table = [] 40 | 41 | def update_data(self, start_date=None, end_date=None): 42 | """Update consumption data""" 43 | daily_table = [] 44 | monthly_table = [] 45 | 46 | chrome_options = webdriver.ChromeOptions() 47 | chrome_options.add_argument('whitelisted-ips') 48 | chrome_options.add_argument('headless') 49 | chrome_options.add_argument('no-sandbox') 50 | 51 | try: 52 | # Check selenuim connection 53 | r = requests.get(urljoin(self._selenium, 'wd/hub/status')) 54 | r.raise_for_status() 55 | 56 | with webdriver.Remote(command_executor=urljoin(self._selenium, 'wd/hub'), 57 | desired_capabilities=DesiredCapabilities.CHROME, 58 | options=chrome_options) as driver: 59 | # Login 60 | # _LOGGER.debug('Login') 61 | driver.implicitly_wait(5) 62 | driver.get(self._host) 63 | driver.find_element_by_id('txtEmail').send_keys(self._username) 64 | driver.find_element_by_id('txtPassword').send_keys(self._password) 65 | driver.find_element_by_id('btnLogin').click() 66 | # Extract some general data 67 | try: 68 | element = driver.find_element_by_id('cphMain_lblMeterSN') 69 | self._meter_number = element.text 70 | except NoSuchElementException: 71 | pass 72 | try: 73 | element = driver.find_element_by_id('spn_current_read') 74 | self._last_read = element.text 75 | except NoSuchElementException: 76 | pass 77 | try: 78 | element = driver.find_element_by_id('spn_forecast') 79 | self._forecast = element.text 80 | except NoSuchElementException: 81 | pass 82 | try: 83 | element = driver.find_element_by_id('spn_low_consumption') 84 | self._low_consumption = element.text 85 | except NoSuchElementException: 86 | pass 87 | try: 88 | element = driver.find_element_by_id('spn_house_hold_avg') 89 | self._house_hold_avg = element.text 90 | except NoSuchElementException: 91 | pass 92 | try: 93 | element = driver.find_element_by_id('cphMain_spn_messages_count') 94 | self._messages_count = element.text 95 | except NoSuchElementException: 96 | pass 97 | # Navigate to my consumption age 98 | driver.get(urljoin(self._host, 'Consumption.aspx#0')) 99 | try: 100 | WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID, 'Consumption'))) 101 | except TimeoutException: 102 | _LOGGER.error('Loading of my consumption page took too much time') 103 | driver.close() 104 | return False 105 | # _LOGGER.debug(f"{driver.current_url}") 106 | # Switch to daily table view 107 | element = driver.find_element_by_id('btn_table') 108 | webdriver.ActionChains(driver).move_to_element(element).click(element).perform() 109 | try: 110 | WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'AlertsTable'))) 111 | except TimeoutException: 112 | _LOGGER.error('Loading of table took too much time') 113 | driver.close() 114 | return False 115 | # _LOGGER.debug(f"{driver.current_url}") 116 | html = driver.page_source 117 | # Extract daily table 118 | if html: 119 | soup = BeautifulSoup(html, features="html.parser") 120 | table = soup.find('table', attrs={'class':'AlertsTable'}) 121 | if table: 122 | for row in table.find('tbody').find_all('tr'): 123 | cols = row.find_all('td') 124 | cols = [ele.text.strip() for ele in cols] 125 | if len(cols): 126 | daily_table.append([ele for ele in cols if ele]) 127 | # Remove table summary 128 | if len(daily_table): 129 | daily_table.pop() 130 | # Switch to monthly 131 | element = driver.find_element_by_id('btn_period_type_0') 132 | webdriver.ActionChains(driver).move_to_element(element).click(element).perform() 133 | time.sleep(1) 134 | # _LOGGER.debug(f"{driver.current_url}") 135 | html = driver.page_source 136 | # Extract daily table 137 | if html: 138 | soup = BeautifulSoup(html, features="html.parser") 139 | table = soup.find('table', attrs={'class':'AlertsTable'}) 140 | if table: 141 | for row in table.find('tbody').find_all('tr'): 142 | cols = row.find_all('td') 143 | cols = [ele.text.strip() for ele in cols] 144 | if len(cols): 145 | monthly_table.append([ele for ele in cols if ele]) 146 | # Remove table summary 147 | if len(monthly_table): 148 | monthly_table.pop() 149 | # Update new values 150 | self._daily_table = daily_table 151 | self._monthly_table = monthly_table 152 | driver.close() 153 | except WebDriverException: 154 | _LOGGER.error('Webdriver error') 155 | except requests.exceptions.HTTPError as errh: 156 | _LOGGER.error('Sellenuim http error: %s', errh) 157 | except requests.exceptions.ConnectionError as errc: 158 | _LOGGER.error('Sellenuim error connecting: %s', errc) 159 | except requests.exceptions.Timeout as errt: 160 | _LOGGER.error("Sellenuim timeout error: %s", errt) 161 | except requests.exceptions.RequestException as err: 162 | _LOGGER.error("OOps: error: %s", err) 163 | 164 | return True 165 | 166 | def consumption(self, period, index=0): 167 | """Return consumption""" 168 | try: 169 | table = self._monthly_table if period == 'monthly' else self._daily_table 170 | return float(table[-1 - index][1]) 171 | except IndexError: 172 | return None 173 | 174 | def state(self, period, index=0): 175 | """Return consumption state""" 176 | try: 177 | table = self._monthly_table if period == 'monthly' else self._daily_table 178 | return table[-1 - index][4] 179 | except IndexError: 180 | return None 181 | 182 | def date(self, period, index=0): 183 | """Return consumption date""" 184 | try: 185 | table = self._monthly_table if period == 'monthly' else self._daily_table 186 | return table[-1 - index][0] 187 | except IndexError: 188 | return None 189 | 190 | def statistics(self, period): 191 | """Return consumption statistics""" 192 | table = self._monthly_table if period == 'monthly' else self._daily_table 193 | values = [float(row[1]) for row in table[:-1]] 194 | if len(values): 195 | return { 196 | 'avg': truncate(sum(values) / len(values), 2), 197 | 'min': min(values), 198 | 'max': max(values) 199 | } 200 | else: 201 | _LOGGER.debug(f"Failed to calculate {period} statistics") 202 | return {} 203 | 204 | @property 205 | def meter_number(self): 206 | return self._meter_number 207 | 208 | @property 209 | def last_read(self): 210 | return self._last_read 211 | 212 | @property 213 | def forecast(self): 214 | return self._forecast 215 | 216 | @property 217 | def low_consumption(self): 218 | return self._low_consumption 219 | 220 | @property 221 | def house_hold_avg(self): 222 | return self._house_hold_avg 223 | 224 | @property 225 | def messages_count(self): 226 | message_count = 0 227 | if self._messages_count: 228 | message_count = [int(s) for s in self._messages_count.split() if s.isdigit()][0] 229 | return message_count -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "{}" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright {yyyy} {name of copyright owner} 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. --------------------------------------------------------------------------------