├── .devcontainer ├── Dockerfile ├── README.md ├── configuration.yaml ├── custom_component_helper ├── devcontainer.json └── images │ └── reopen.png ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── issue.md └── settings.yml ├── .vscode └── tasks.json ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── custom_components └── templatesensor │ ├── __init__.py │ ├── config_flow.py │ ├── const.py │ ├── manifest.json │ ├── sensor.py │ └── translations │ └── en.json ├── example.png ├── hacs.json └── info.md /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.7 2 | 3 | RUN apt-get update \ 4 | && apt-get install -y --no-install-recommends \ 5 | git \ 6 | && apt-get clean \ 7 | && rm -rf /var/lib/apt/lists/* 8 | 9 | RUN python -m pip install --upgrade colorlog black pylint 10 | RUN python -m pip install --upgrade git+git://github.com/home-assistant/home-assistant.git@dev 11 | RUN cd && mkdir -p /config/custom_components 12 | 13 | 14 | WORKDIR /workspace 15 | 16 | # Set the default shell to bash instead of sh 17 | ENV SHELL /bin/bash -------------------------------------------------------------------------------- /.devcontainer/README.md: -------------------------------------------------------------------------------- 1 | # Devcontainer 2 | 3 | _The easiest way to contribute to and/or test this repository._ 4 | 5 | ## Requirements 6 | 7 | - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 8 | - [docker](https://docs.docker.com/install/) 9 | - [VS Code](https://code.visualstudio.com/) 10 | - [Remote - Containers (VSC Extention)](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) 11 | 12 | [More info about requirements and devcontainer in general](https://code.visualstudio.com/docs/remote/containers#_getting-started) 13 | 14 | ## How to use Devcontainer for development/test 15 | 16 | 1. Make sure your computer meets the requirements. 17 | 1. Fork this repository. 18 | 1. Clone the repository to your computer. 19 | 1. Open the repository using VS Code. 20 | 21 | When you open this repository with VSCode and your computer meets the requirements you are asked to "Reopen in Container", do that. 22 | 23 | ![reopen](images/reopen.png) 24 | 25 | If you don't see this notification, open the command pallet (ctrl+shift+p) and select `Remote-Containers: Reopen Folder in Container`. 26 | 27 | _It will now build the devcontainer._ 28 | 29 | The container have some "tasks" to help you testing your changes. 30 | 31 | ## Custom Tasks in this repository 32 | 33 | _Start "tasks" by opening the the command pallet (ctrl+shift+p) and select `Tasks: Run Task`_ 34 | 35 | Running tasks like `Start Home Assistant on port 8124` can be restarted by opening the the command pallet (ctrl+shift+p) and select `Tasks: Restart Running Task`, then select the task you want to restart. 36 | 37 | ### Start Home Assistant on port 8124 38 | 39 | This will copy the configuration and the integration files to the expected location in the container. 40 | 41 | And start up Home Assistant on [port 8124.](http://localhost:8124) 42 | 43 | ### Upgrade Home Assistant to latest dev 44 | 45 | This will upgrade Home Assistant to the latest dev version. 46 | 47 | ### Set Home Assistant Version 48 | 49 | This allows you to specify a version of Home Assistant to install inside the devcontainer. 50 | 51 | ### Home Assistant Config Check 52 | 53 | This runs a config check to make sure your config is valid. 54 | -------------------------------------------------------------------------------- /.devcontainer/configuration.yaml: -------------------------------------------------------------------------------- 1 | default_config: 2 | logger: 3 | default: error 4 | logs: 5 | custom_components.templatesensor: debug 6 | -------------------------------------------------------------------------------- /.devcontainer/custom_component_helper: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | function StartHomeAssistant { 4 | echo "Copy configuration.yaml" 5 | cp -f .devcontainer/configuration.yaml /config || echo ".devcontainer/configuration.yaml are missing!" exit 1 6 | 7 | echo "Copy the custom component" 8 | rm -R /config/custom_components/ || echo "" 9 | cp -r custom_components /config/custom_components/ || echo "Could not copy the custom_component" exit 1 10 | 11 | echo "Start Home Assistant" 12 | hass -c /config 13 | } 14 | 15 | function UpdgradeHomeAssistantDev { 16 | python -m pip install --upgrade git+git://github.com/home-assistant/home-assistant.git@dev 17 | } 18 | 19 | function SetHomeAssistantVersion { 20 | read -p 'Version: ' version 21 | python -m pip install --upgrade homeassistant==$version 22 | } 23 | 24 | function HomeAssistantConfigCheck { 25 | hass -c /config --script check_config 26 | } -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // See https://aka.ms/vscode-remote/devcontainer.json for format details. 2 | { 3 | "context": "..", 4 | "dockerFile": "Dockerfile", 5 | "appPort": "8124:8123", 6 | "runArgs": [ 7 | "-e", 8 | "GIT_EDTIOR='code --wait'" 9 | ], 10 | "extensions": [ 11 | "ms-python.python", 12 | "github.vscode-pull-request-github", 13 | "tabnine.tabnine-vscode" 14 | ], 15 | "settings": { 16 | "editor.tabSize": 4, 17 | "python.pythonPath": "/usr/local/bin/python", 18 | "python.linting.pylintEnabled": true, 19 | "python.linting.enabled": true, 20 | "python.formatting.provider": "black", 21 | "editor.formatOnPaste": false, 22 | "editor.formatOnSave": true, 23 | "editor.formatOnType": true, 24 | "files.trimTrailingWhitespace": true 25 | } 26 | } -------------------------------------------------------------------------------- /.devcontainer/images/reopen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/custom-components/templatesensor/16f15f73b003d8228dfbb5f91bf28f76cc8aa35f/.devcontainer/images/reopen.png -------------------------------------------------------------------------------- /.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/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 logs 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 | ``` -------------------------------------------------------------------------------- /.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" -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Start Home Assistant on port 8124", 6 | "type": "shell", 7 | "command": "source .devcontainer/custom_component_helper && StartHomeAssistant", 8 | "group": { 9 | "kind": "test", 10 | "isDefault": true, 11 | }, 12 | "presentation": { 13 | "reveal": "always", 14 | "panel": "new" 15 | }, 16 | "problemMatcher": [] 17 | }, 18 | { 19 | "label": "Upgrade Home Assistant to latest dev", 20 | "type": "shell", 21 | "command": "source .devcontainer/custom_component_helper && UpdgradeHomeAssistantDev", 22 | "group": { 23 | "kind": "test", 24 | "isDefault": true, 25 | }, 26 | "presentation": { 27 | "reveal": "always", 28 | "panel": "new" 29 | }, 30 | "problemMatcher": [] 31 | }, 32 | { 33 | "label": "Set Home Assistant Version", 34 | "type": "shell", 35 | "command": "source .devcontainer/custom_component_helper && SetHomeAssistantVersion", 36 | "group": { 37 | "kind": "test", 38 | "isDefault": true, 39 | }, 40 | "presentation": { 41 | "reveal": "always", 42 | "panel": "new" 43 | }, 44 | "problemMatcher": [] 45 | }, 46 | { 47 | "label": "Home Assistant Config Check", 48 | "type": "shell", 49 | "command": "source .devcontainer/custom_component_helper && HomeAssistantConfigCheck", 50 | "group": { 51 | "kind": "test", 52 | "isDefault": true, 53 | }, 54 | "presentation": { 55 | "reveal": "always", 56 | "panel": "new" 57 | }, 58 | "problemMatcher": [] 59 | } 60 | ] 61 | } -------------------------------------------------------------------------------- /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 | ## Github is used for everything 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. Make sure your code lints (using black). 19 | 4. Issue that pull request! 20 | 21 | ## Any contributions you make will be under the MIT Software License 22 | 23 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern. 24 | 25 | ## Report bugs using Github's [issues](../../issues) 26 | 27 | GitHub issues are used to track public bugs. 28 | Report a bug by [opening a new issue](../../issues/new/choose); it's that easy! 29 | 30 | ## Write bug reports with detail, background, and sample code 31 | 32 | **Great Bug Reports** tend to have: 33 | 34 | - A quick summary and/or background 35 | - Steps to reproduce 36 | - Be specific! 37 | - Give sample code if you can. 38 | - What you expected would happen 39 | - What actually happens 40 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 41 | 42 | People *love* thorough bug reports. I'm not even kidding. 43 | 44 | ## Use a Consistent Coding Style 45 | 46 | Use [black](https://github.com/ambv/black) to make sure the code follows the style. 47 | 48 | ## License 49 | 50 | By contributing, you agree that your contributions will be licensed under its MIT License. 51 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Joakim Sørensen @ludeeus 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # templatesensor 2 | 3 | Please do not use this, use https://www.home-assistant.io/integrations/template/ instead. 4 | 5 |
6 | Old instructions 7 | 8 | 9 | ## Installation 10 | 11 | 1. Using the tool of choice open the directory (folder) for your HA configuration (where you find `configuration.yaml`). 12 | 2. If you do not have a `custom_components` directory (folder) there, you need to create it. 13 | 3. In the `custom_components` directory (folder) create a new folder called `templatesensor`. 14 | 4. Download _all_ the files from the `custom_components/templatesensor/` directory (folder) in this repository. 15 | 5. Place the files you downloaded in the new directory (folder) you created. 16 | 6. Restart Home Assistant 17 | 7. In the HA UI go to "Configuration" -> "Integrations" click "+" and search for "Custom Template Sensor" 18 | 19 | Using your HA configuration directory (folder) as a starting point you should now also have this: 20 | 21 | ```text 22 | custom_components/templatesensor/.translations/en.json 23 | custom_components/templatesensor/__init__.py 24 | custom_components/templatesensor/config_flow.py 25 | custom_components/templatesensor/const.py 26 | custom_components/templatesensor/manifest.json 27 | custom_components/templatesensor/sensor.py 28 | ``` 29 | 30 | ## Configuration 31 | 32 | Configuration are done through the UI. 33 | 34 | "Configuration" --> "Integrations" --> "+" --> "Custom Template Sensor" 35 | 36 | ![example][exampleimg] 37 | 38 | ## Contributions are welcome! 39 | 40 | If you want to contribute to this please read the [Contribution guidelines](CONTRIBUTING.md) 41 | 42 | *** 43 | 44 | [templatesensor]: https://github.com/custom-components/templatesensor 45 | [buymecoffee]: https://www.buymeacoffee.com/ludeeus 46 | [buymecoffeebadge]: https://img.shields.io/badge/buy%20me%20a%20coffee-donate-yellow.svg?style=for-the-badge 47 | [commits-shield]: https://img.shields.io/github/commit-activity/y/custom-components/templatesensor.svg?style=for-the-badge 48 | [commits]: https://github.com/custom-components/templatesensor/commits/master 49 | [hacs]: https://github.com/custom-components/hacs 50 | [hacsbadge]: https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge 51 | [discord]: https://discord.gg/Qa5fW2R 52 | [discord-shield]: https://img.shields.io/discord/330944238910963714.svg?style=for-the-badge 53 | [exampleimg]: https://raw.githubusercontent.com/custom-components/templatesensor/master/example.png 54 | [forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg?style=for-the-badge 55 | [forum]: https://community.home-assistant.io/ 56 | [license-shield]: https://img.shields.io/github/license/custom-components/templatesensor.svg?style=for-the-badge 57 | [maintenance-shield]: https://img.shields.io/badge/maintainer-Joakim%20Sørensen%20%40ludeeus-blue.svg?style=for-the-badge 58 | [releases-shield]: https://img.shields.io/github/release/custom-components/templatesensor.svg?style=for-the-badge 59 | [releases]: https://github.com/custom-components/templatesensor/releases 60 | 61 |
62 | -------------------------------------------------------------------------------- /custom_components/templatesensor/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Component to integrate with blueprint. 3 | 4 | For more details about this component, please refer to 5 | https://github.com/custom-components/blueprint 6 | """ 7 | import os 8 | from datetime import timedelta 9 | import logging 10 | import voluptuous as vol 11 | from homeassistant import config_entries 12 | import homeassistant.helpers.config_validation as cv 13 | from homeassistant.helpers import discovery 14 | from homeassistant.util import Throttle 15 | 16 | from .const import DOMAIN_DATA, DOMAIN, ISSUE_URL, PLATFORMS, REQUIRED_FILES, VERSION 17 | 18 | MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30) 19 | 20 | _LOGGER = logging.getLogger(__name__) 21 | 22 | 23 | async def async_setup(hass, config): 24 | """Set up this component using YAML is not supported.""" 25 | return True 26 | 27 | 28 | async def async_setup_entry(hass, config_entry): 29 | """Set up this integration using UI.""" 30 | # Check that all required files are present 31 | config_entry.add_update_listener(update_listener) 32 | file_check = await check_files(hass) 33 | if not file_check: 34 | return False 35 | 36 | config_entry.options = config_entry.data 37 | 38 | # Add sensor 39 | hass.async_add_job( 40 | hass.config_entries.async_forward_entry_setup(config_entry, "sensor") 41 | ) 42 | return True 43 | 44 | 45 | async def check_files(hass): 46 | """Return bool that indicates if all files are present.""" 47 | # Verify that the user downloaded all files. 48 | base = f"{hass.config.path()}/custom_components/{DOMAIN}/" 49 | missing = [] 50 | for file in REQUIRED_FILES: 51 | fullpath = "{}{}".format(base, file) 52 | if not os.path.exists(fullpath): 53 | missing.append(file) 54 | 55 | if missing: 56 | _LOGGER.critical("The following files are missing: %s", str(missing)) 57 | returnvalue = False 58 | else: 59 | returnvalue = True 60 | 61 | return returnvalue 62 | 63 | 64 | async def async_remove_entry(hass, config_entry): 65 | """Handle removal of an entry.""" 66 | try: 67 | await hass.config_entries.async_forward_entry_unload(config_entry, "sensor") 68 | _LOGGER.info("Successfully removed sensor") 69 | except ValueError: 70 | pass 71 | 72 | 73 | async def update_listener(hass, entry): 74 | """Update listener.""" 75 | entry.data = entry.options 76 | await hass.config_entries.async_forward_entry_unload(entry, "sensor") 77 | hass.async_add_job(hass.config_entries.async_forward_entry_setup(entry, "sensor")) 78 | -------------------------------------------------------------------------------- /custom_components/templatesensor/config_flow.py: -------------------------------------------------------------------------------- 1 | """Adds config flow for templatesensor.""" 2 | from collections import OrderedDict 3 | import logging 4 | import voluptuous as vol 5 | 6 | from homeassistant import config_entries 7 | from homeassistant.core import callback 8 | from homeassistant.helpers import template as templater 9 | 10 | from .const import DOMAIN 11 | 12 | _LOGGER = logging.getLogger(__name__) 13 | 14 | 15 | class TemplateSensorFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): 16 | """Config flow for templatesensor.""" 17 | 18 | VERSION = 1 19 | CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL 20 | 21 | def __init__(self): 22 | """Initialize.""" 23 | self._errors = {} 24 | 25 | async def async_step_user(self, user_input={}): 26 | """Handle a flow initialized by the user.""" 27 | self._errors = {} 28 | if user_input is not None: 29 | valid = await self._validate_template(user_input["template"]) 30 | if valid: 31 | return self.async_create_entry(title=user_input["name"], data=user_input) 32 | else: 33 | self._errors["base"] = "template" 34 | 35 | return await self._show_config_form(user_input) 36 | 37 | return await self._show_config_form(user_input) 38 | 39 | async def _show_config_form(self, user_input): 40 | """Show the configuration form to edit location data.""" 41 | 42 | # Defaults 43 | name = "" 44 | template = "" 45 | icon = "" 46 | unit = "" 47 | 48 | if user_input is not None: 49 | if "name" in user_input: 50 | name = user_input["name"] 51 | if "template" in user_input: 52 | template = user_input["template"] 53 | if "icon" in user_input: 54 | icon = user_input["icon"] 55 | if "unit" in user_input: 56 | unit = user_input["unit"] 57 | 58 | data_schema = OrderedDict() 59 | data_schema[vol.Required("name", default=name)] = str 60 | data_schema[vol.Required("template", default=template)] = str 61 | data_schema[vol.Optional("icon", default=icon)] = str 62 | data_schema[vol.Optional("unit", default=unit)] = str 63 | return self.async_show_form( 64 | step_id="user", data_schema=vol.Schema(data_schema), errors=self._errors 65 | ) 66 | 67 | @staticmethod 68 | @callback 69 | def async_get_options_flow(config_entry): 70 | return OptionsFlowHandler(config_entry) 71 | 72 | async def _validate_template(self, template): 73 | """Return true if template is valid.""" 74 | try: 75 | templater.Template(template, self.hass).async_render() 76 | return True 77 | except Exception as exception: # pylint: disable=broad-except 78 | _LOGGER.error(exception) 79 | pass 80 | return False 81 | 82 | 83 | class OptionsFlowHandler(config_entries.OptionsFlow): 84 | def __init__(self, config_entry): 85 | """Initialize UniFi options flow.""" 86 | self.config_entry = config_entry 87 | 88 | async def async_step_init(self, user_input=None): 89 | """Manage the options.""" 90 | return await self.async_step_user() 91 | 92 | async def async_step_user(self, user_input=None): 93 | """Handle a flow initialized by the user.""" 94 | if user_input is not None: 95 | return self.async_create_entry(title="", data=user_input) 96 | 97 | data_schema = { 98 | vol.Required("name", default=self.config_entry.options.get("name")): str, 99 | vol.Required("template", default=self.config_entry.options.get("template")): str, 100 | vol.Optional( 101 | "icon", description={"suggested_value": self.config_entry.options.get("icon")} 102 | ): str, 103 | vol.Optional( 104 | "unit", description={"suggested_value": self.config_entry.options.get("unit")} 105 | ): str, 106 | } 107 | 108 | return self.async_show_form(step_id="user", data_schema=vol.Schema(data_schema)) 109 | -------------------------------------------------------------------------------- /custom_components/templatesensor/const.py: -------------------------------------------------------------------------------- 1 | """Constants for templatesensor.""" 2 | # Base component constants 3 | DOMAIN = "templatesensor" 4 | DOMAIN_DATA = f"{DOMAIN}_data" 5 | VERSION = "0.1.3" 6 | PLATFORMS = ["sensor"] 7 | REQUIRED_FILES = [ 8 | "translations/en.json", 9 | "const.py", 10 | "config_flow.py", 11 | "manifest.json", 12 | "sensor.py", 13 | ] 14 | ISSUE_URL = "https://github.com/custom-components/templatesensor/issues" 15 | -------------------------------------------------------------------------------- /custom_components/templatesensor/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.1.3", 3 | "domain": "templatesensor", 4 | "name": "UI Template sensor configuration", 5 | "documentation": "https://github.com/custom-components/templatesensor", 6 | "dependencies": [], 7 | "config_flow": true, 8 | "codeowners": [ 9 | "@ludeeus" 10 | ], 11 | "requirements": [] 12 | } 13 | -------------------------------------------------------------------------------- /custom_components/templatesensor/sensor.py: -------------------------------------------------------------------------------- 1 | """Sensor platform for templatesensor.""" 2 | from homeassistant.helpers.entity import Entity 3 | from homeassistant.helpers import template as templater 4 | 5 | 6 | async def async_setup_entry(hass, config_entry, async_add_devices): 7 | """Setup sensor platform.""" 8 | async_add_devices([CustomTemplateSensor(hass, config_entry)], True) 9 | 10 | 11 | class CustomTemplateSensor(Entity): 12 | """CustomTemplateSensor class.""" 13 | 14 | def __init__(self, hass, config): 15 | self.hass = hass 16 | self.config = config 17 | self._state = None 18 | 19 | async def async_update(self): 20 | """Update the sensor.""" 21 | try: 22 | self._state = templater.Template( 23 | self.config.options.get("template"), self.hass 24 | ).async_render() 25 | except Exception as exception: 26 | self._state = self._state 27 | 28 | @property 29 | def unique_id(self): 30 | """Return a unique ID to use for this sensor.""" 31 | return self.config.entry_id 32 | 33 | @property 34 | def name(self): 35 | """Return the name of the sensor.""" 36 | return self.config.data.get("name") 37 | 38 | @property 39 | def state(self): 40 | """Return the state of the sensor.""" 41 | return self._state 42 | 43 | @property 44 | def unit_of_measurement(self): 45 | """Return the unit_of_measurement of the sensor.""" 46 | return self.config.options.get("unit") 47 | 48 | @property 49 | def icon(self): 50 | """Return the icon of the sensor.""" 51 | return self.config.options.get("icon") 52 | -------------------------------------------------------------------------------- /custom_components/templatesensor/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "title": "Custom Template Sensor", 4 | "step": { 5 | "user": { 6 | "title": "Custom Template Sensor", 7 | "description": "If you need help with the configuration have a look here: https://github.com/custom-components/templatesensor", 8 | "data": { 9 | "name": "Name*", 10 | "template": "Template*", 11 | "icon": "Icon", 12 | "unit": "Unit of measurement" 13 | } 14 | } 15 | }, 16 | "error": { 17 | "template": "There was an issue rendering the template." 18 | } 19 | }, 20 | "options": { 21 | "step": { 22 | "init": { 23 | "data": {} 24 | }, 25 | "user": { 26 | "data": { 27 | "name": "Name*", 28 | "template": "Template*", 29 | "icon": "Icon", 30 | "unit": "Unit of measurement" 31 | } 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/custom-components/templatesensor/16f15f73b003d8228dfbb5f91bf28f76cc8aa35f/example.png -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "UI Template sensor configuration", 3 | "domains": ["sensor"], 4 | "homeassistant": "0.109.0" 5 | } -------------------------------------------------------------------------------- /info.md: -------------------------------------------------------------------------------- 1 | [![GitHub Release][releases-shield]][releases] 2 | [![GitHub Activity][commits-shield]][commits] 3 | [![License][license-shield]](LICENSE.md) 4 | 5 | [![hacs][hacsbadge]](hacs) 6 | ![Project Maintenance][maintenance-shield] 7 | [![BuyMeCoffee][buymecoffeebadge]][buymecoffee] 8 | 9 | [![Discord][discord-shield]][discord] 10 | [![Community Forum][forum-shield]][forum] 11 | 12 | ## Configuration 13 | 14 | Configuration are done through the UI. 15 | 16 | "Configuration" --> "Integrations" --> "+" --> "Custom Template Sensor" 17 | 18 | ![example][exampleimg] 19 | 20 | *** 21 | 22 | [templatesensor]: https://github.com/custom-components/templatesensor 23 | [buymecoffee]: https://www.buymeacoffee.com/ludeeus 24 | [buymecoffeebadge]: https://img.shields.io/badge/buy%20me%20a%20coffee-donate-yellow.svg?style=for-the-badge 25 | [commits-shield]: https://img.shields.io/github/commit-activity/y/custom-components/templatesensor.svg?style=for-the-badge 26 | [commits]: https://github.com/custom-components/templatesensor/commits/master 27 | [hacs]: https://github.com/custom-components/hacs 28 | [hacsbadge]: https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge 29 | [discord]: https://discord.gg/Qa5fW2R 30 | [discord-shield]: https://img.shields.io/discord/330944238910963714.svg?style=for-the-badge 31 | [exampleimg]: https://raw.githubusercontent.com/custom-components/templatesensor/master/example.png 32 | [forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg?style=for-the-badge 33 | [forum]: https://community.home-assistant.io/ 34 | [license-shield]: https://img.shields.io/github/license/custom-components/templatesensor.svg?style=for-the-badge 35 | [maintenance-shield]: https://img.shields.io/badge/maintainer-Joakim%20Sørensen%20%40ludeeus-blue.svg?style=for-the-badge 36 | [releases-shield]: https://img.shields.io/github/release/custom-components/templatesensor.svg?style=for-the-badge 37 | [releases]: https://github.com/custom-components/templatesensor/releases --------------------------------------------------------------------------------