Repository: twrecked/hass-virtual Branch: master Commit: a056ceaf73d4 Files: 30 Total size: 162.1 KB Directory structure: gitextract_p4gtqxj7/ ├── .github/ │ └── workflows/ │ ├── hacs.yaml │ ├── hass.yaml │ └── stale.yaml ├── .gitignore ├── LICENSE ├── README.md ├── changelog ├── custom_components/ │ └── virtual/ │ ├── __init__.py │ ├── binary_sensor.py │ ├── cfg.py │ ├── config_flow.py │ ├── const.py │ ├── cover.py │ ├── device_tracker.py │ ├── entity.py │ ├── fan.py │ ├── light.py │ ├── lock.py │ ├── manifest.json │ ├── number.py │ ├── sensor.py │ ├── services.yaml │ ├── switch.py │ ├── translations/ │ │ ├── cz.json │ │ ├── en.json │ │ └── sk.json │ └── valve.py ├── hacs.json ├── info.md └── install ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/hacs.yaml ================================================ name: HACS Validation on: workflow_dispatch: push: branches: - master pull_request: branches: - master jobs: hacs: name: HACS Validation runs-on: "ubuntu-latest" steps: - name: HACS Validation uses: "hacs/action@main" with: category: "integration" ================================================ FILE: .github/workflows/hass.yaml ================================================ name: hassfest Validation on: workflow_dispatch: push: branches: - master pull_request: branches: - master jobs: validate: name: hassfest Validation runs-on: "ubuntu-latest" steps: - uses: "actions/checkout@v2" - uses: "home-assistant/actions/hassfest@master" ================================================ FILE: .github/workflows/stale.yaml ================================================ name: Close inactive issues on: workflow_dispatch: schedule: - cron: "30 2 * * 0" jobs: close-issues: runs-on: ubuntu-latest permissions: issues: write pull-requests: write steps: - uses: actions/stale@v9 with: days-before-issue-stale: 365 days-before-issue-close: 28 stale-issue-label: "stale" stale-issue-message: "This issue is stale because it has been open for 365 days with no activity. This issue will be automatically closed within 28 days if there is no further activity." close-issue-message: "This issue was closed because it has been inactive for 28 days since being marked as stale." days-before-pr-stale: -1 days-before-pr-close: -1 repo-token: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # Me! *~ .*.sw? *.rej *.orig *.diff .idea ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # **Virtual devices for Home Assistant** _Virtual_ is a component that provides virtual entities for _Home Assistant_. ![icon](images/virtual-icon.png) # !!!BREAKING CHANGES!!! Version 0.9 supports adding virtual devices using _config flow_. By default it will move your existing devices into a single file `virtual.yaml`. If you **DO NOT** want this behaviour add this to your current `virtual` configuration. ```yaml virtual: yaml_config: True ``` # Table Of Contents - [**Virtual devices for Home Assistant**](#virtual-devices-for-home-assistant) - [!!!BREAKING CHANGES!!!](#breaking-changes) - [Table Of Contents](#table-of-contents) - [Introduction](#introduction) - [Notes](#notes) - [Version 0.8 Documentation](#version-08-documentation) - [New Features in 0.9.0](#new-features-in-090) - [Config Flow](#config-flow) - [What pieces are done](#what-pieces-are-done) - [What you need to be wary of](#what-you-need-to-be-wary-of) - [What if it goes wrong?](#what-if-it-goes-wrong) - [Thanks](#thanks) - [Installation](#installation) - [Getting the Software](#getting-the-software) - [HACS](#hacs) - [Adding the Integration](#adding-the-integration) - [After a Fresh Install](#after-a-fresh-install) - [After an Upgrade](#after-an-upgrade) - [I don't want the New Behaviour!!!](#i-dont-want-the-new-behaviour) - [Adding More Entries](#adding-more-entries) - [Component Configuration](#component-configuration) - [Entity Configuration](#entity-configuration) - [File Layout](#file-layout) - [Common Attributes](#common-attributes) - [Availability](#availability) - [Persistence](#persistence) - [Switches](#switches) - [Binary Sensors](#binary-sensors) - [Sensors](#sensors) - [Lights](#lights) - [Locks](#locks) - [Fans](#fans) - [Covers](#covers) - [Valves](#valves) - [Device Tracking](#device-tracking) - [Old Style Entity Configuration](#old-style-entity-configuration) - [Services](#services) # Introduction Virtual provides virtual components for testing Home Assistant systems. ## Notes Wherever you see `/config` in this README it refers to your home-assistant configuration directory. For me, for example, it's `/home/steve/ha` that is mapped to `/config` inside my docker container. ## Version 0.8 Documentation **This documentation is for the 0.9.x version, you can find the 0.8.x version** [here](https://github.com/twrecked/hass-virtual/tree/version-0.8.x#readme). ## New Features in 0.9.0 ### Config Flow Finally. After sitting on it for far too long I decided to do the work I needed to, this integration now acts much like every integration, splitting down by entity, device and integration. #### What pieces are done - _upgrade_; the code will upgrade a _0.8_ build to the _config flow_ system. Your current configuration will be moved into 1 file, `virtual.yaml`. This file contains all your virtual devices. Edit this file to add any type of device. - _services_; they follow the _Home Assistant_ standard - _multiple integrations_; the integration can be added several times and you can spread your devices across several files - _device groupings_; for example, a motion detector can have a motion detection entity and a battery entity, upgraded devices will have a one to one relationship. For example, the following will create a motion device with 2 entities. If you don't provide a name for an entity the system will provide a default. ```yaml Mezzanine Motion: - platform: binary_sensor initial_value: 'off' class: motion - platform: sensor initial_value: '98' class: battery ``` #### What you need to be wary of - _device trackers_; the upgrade process is a little more complicated if you have device trackers, because of the way _virtual_ created the old devices you will end up with duplicates entries, you can fix it by running the following steps 1. do the upgrade 2. comment out device virtual device trackers from `device_trackers.yaml` and `known_devices.yaml` 3. restart _Home Assistant_ 4. delete the virtual integration 5. add back the virtual integration in accepting the defaults #### What if it goes wrong? For now I recommend leaving your old configuration in place so you can revert back to a _0.8_ release if you encounter an issue. _Home Assistant_ will complain about the config but it's OK to ignore it. If you do encounter and issue if you can turn on debug an create an issue that would be great. ## Thanks Many thanks to: * Icon from [iconscout](https://iconscout.com) by [twitter-inc](https://iconscout.com/contributors/twitter-inc) # Installation ## Getting the Software ### HACS [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) Virtual is part of the default HACS store. If you're not interested in development branches this is the easiest way to install. ## Adding the Integration ### After a Fresh Install When you have created your initial configuration file do the following: - go to `Settings` -> `Devices and Integrations` -> `+ ADD INTEGRATION` - search for _virtual_ and choose the integration - give your configuration a name and point it at your newly created file Then you click OK **Warning:** Check your /config/ folder if a virtual.yml file has been added. If not, make this file yourself. ### After an Upgrade All your devices will be moved to a group called _import_ and put into `/config/virtual.yaml`. The system will create a single _virtual_ integration. ## I don't want the New Behaviour!!! If you want to keep your existing behaviour change your current `virtual` entry in `configuration.yaml` to this: ```yaml virtual: yaml_config: True ``` ## Adding More Entries You can add more than one integration by selecting `Add Entry` on the _virtual_ integration page. You will need to give this new entity group a name and point it to the new file. # Component Configuration You set this to enable backwards compatibility. - `yaml_config`; set to `True` to enable backwards compatibility, set to `False` to disable it. The default is `False`. For example, this enable backwards compatibility. ```yaml virtual: yaml_config: True ``` # Entity Configuration All component configuration is done through _yaml_ files. You can put all of your virtual devices into a single _yaml_ file or you can group devices together in multiple file. If this is a fresh install you will need to install a _virtual_ integration instance and tell it about your file. If you are upgrading from _0.8_ the system will create a single instance and copy all your current devices into a `/config/virtual.yaml`. ## File Layout An empty file looks like this: ```yaml version: 1 devices: {} ``` - _version_; this is currently 1 - _devices_; this is a list of devices and entities associated with that device These two entries are optional. If you remove them then remove the indentation from the following device entries. This is a small example of an imported file: ```yaml version: 1 devices: Living Room Sensor: - platform: binary_sensor name: Living Room Motion initial_value: 'off' class: motion Back Door Sensor: - platform: binary_sensor name: Back Door initial_value: 'off' class: door ``` This is an example of a file without the preamble. ```yaml Living Room Sensor: - platform: binary_sensor name: Living Room Motion initial_value: 'off' class: motion Back Door Sensor: - platform: binary_sensor name: Back Door initial_value: 'off' class: door ``` Note that these entities have explicit names, this is because these entities were imported and the integration will re-create the same entity and unique IDs as previous version. You do not need to assign a name on new entries, the system will provide a default suffix based on device class. But, you can also choose to provide names if you wish. This is the same file without the names: ```yaml version: 1 devices: Living Room Sensor: - platform: binary_sensor initial_value: 'off' class: motion Back Door Sensor: - platform: binary_sensor initial_value: 'off' class: door ``` In this case it will create 2 entities, one called `Living Room Sensor motion` and `Back Door Sensor door`. The default naming can get a little hairy but you can alter it from the _Integration_ settings. You can also define virtual multi sensors. In this example a multi sensor devices provides 2 entities. ```yaml Living Room Multi Sensor: - platform: binary_sensor initial_value: 'off' class: motion - platform: sensor initial_value: '20' class: temperature ``` ## Common Attributes ### Availability By default, all devices are market as available. As shown below in each domain, adding `initial_availability: false` to configuration can override default and set as unavailable on HA start. Availability can by set by using the `virtual.set_available` with value `true` or `false`. This is fully optional and `initial_availability` is not required to be set. ### Persistence By default, all device states are persistent. You can change this behaviour with the `persistent` configuration option. If you have set an `initial_value` it will only be used if the device state is not restored. The following switch will always start _on_. ```yaml Test Switch: - platform: virtual name: Switch 1 persistent: False initial_value: on ``` ## Switches To add a virtual switch use the following: ```yaml Test Switch: - platform: switch ``` ## Binary Sensors To add a virtual binary_sensor use the following. It supports all standard classes. ```yaml Test Binary Sensor: - platform: binary_sensor initial_value: 'on' class: presence ``` Use the `virtual.turn_on`, `virtual.turn_off` and `virtual.toggle` services to manipulate the binary sensors. ## Sensors To add a virtual sensor use the following: ```yaml Test Sensor: - platform: sensor class: temperature initial_value: 37 unit_of_measurement: 'F' ``` Use the `virtual.set` service to manipulate the sensor value. Setting `unit_of_measurement` can override default unit for selected sensor class. This is optional ans any string is accepted. List of standard units can be found here: [Sensor Entity](https://developers.home-assistant.io/docs/core/entity/sensor/) ## Lights To add a virtual light use the following: ```yaml Test Lights: - platform: light initial_value: 'on' support_brightness: true initial_brightness: 100 support_color: true initial_color: [0,255] support_color_temp: true initial_color_temp: 255 support_white_value: true initial_white_value: 240 ``` Only `name` is required. - `support_*`; this allows the light to have colour and temperature properties - `initial_*`; this is to set the initial values. `initial_color` is `[hue (0-360), saturation (0-100)]` _Note; *white_value is deprecated and will be removed in future releases._ ## Locks To add a virtual lock use the following: ```yaml Test Lock: - platform: lock name: Front Door Lock initial_value: locked locking_time: 5 jamming_test: 5 ``` - Persistent Configuration - `initial_value`: optional, default `locked`; any other value will result in the lock being unlocked at start up - Per Run Configuration - `locking_time`: optional, default `0` seconds; any positive value will result in a locking or unlocking phase that lasts `locking_time` seconds - `jamming_test`: optional, default `0` tries; any positive value will result in a jamming failure approximately once per `jamming_test` tries ## Fans To add a virtual fan use the following: ```yaml Test Fan: - platform: fan speed: True speed_count: 5 direction: True oscillate: True ``` You only need one of `speed` or `speed_count`. - `speed`; if `True` then fan can be set to low, medium and high speeds - `speed_count`; number of speeds to allow, these will be broken down into percentages. 4 speeds = 25, 50, 75 and 100%. - `direction`; if `True` then fan can run in 2 directions - `oscillate`; if `True` then fan can be set to oscillate ## Covers To add a virtual cover use the following: ```yaml Test Cover: - platform: cover initial_value: 'closed' open_close_duration: 10 open_close_tick: 1 ``` Supports `open`, `close`, `stop` and `set_position`. Opening and closing of the cover is emulated with timed events, and the timing can be controlled with - `open_close_duration`: The time it take to go from fully open to fully closed, or back - `open_close_tick`: The update interval when opening and closing ## Valves To add a virtual valve use the following: ```yaml Test Valve: - platform: valve initial_value: 'closed' open_close_duration: 10 open_close_tick: 1 ``` Supports `open_valve`, `close_valve`, `stop_valve` and `set_valve_position`. Opening and closing of the valve is emulated with timed events, and the timing can be controlled with - `open_close_duration`: The time it take to go from fully open to fully closed, or back - `open_close_tick`: The update interval when opening and closing ## Device Tracking To add a virtual device tracker use the following: ```yaml Test Device_Tracker: - platform: device_tracker initial_value: home ``` - `persistent`: default `True`; if `True` then entity location is remembered across restarts otherwise entity always starts at `location` - `location`: default `home`; this sets the device location when it is created or if the device is not `persistent` Use the `virtual.move` service to change device locations. # Old Style Entity Configuration For now; look at [the 0.8](https://github.com/twrecked/hass-virtual/tree/version-0.8.x?tab=readme-ov-file#component-configuration) documentation. # Services The component provides the following services: **Name: `virtual.set_availability`** *Parameters:* - `entity_id`; The entity id of the binary sensor to turn on. This will change the availability setting of any virtual device. --- **Name: `virtual.turn_on`** *Parameters:* - `entity_id`; The entity id of the binary sensor to turn on. This service will turn on a binary sensor. --- **Name: `virtual.turn_off`** *Parameters:* - `entity_id`; The entity id of the binary sensor to turn off. This service will turn off a binary sensor. --- **Name: `virtual.toggle`** *Parameters:* - `entity_id`; The entity id of the binary sensor to toggle. - This service will toggle a binary sensor. --- **Name: `virtual.move`** *Parameters:* - `location`; a named location - `gps`; GPS coordinates Move a device tracker. You use one of the parameters. ================================================ FILE: changelog ================================================ 0.9.4: Fix deprecation warnings. (Thanks @Tony763) 0.9.3: Fix some deprecation warnings. Tidy up cover and valve code. Many thanks to @mikz 0.9.2: Remove Python deprecated function. Remove Home Assistant deprecated contants. Fix reload issues. 0.9.1: (Finally!) Move out of beta. 0.9.0b18: The last beta... Added virtual numbers; thanks@olegtarasov Updated Slovakian translations, thanks @misa1515 0.9.0b17: Switch device tracker to GPS if needed Fix warning about POWER_VOLT_AMPERE_REACTIVE Fix restore state of lights Add GPS accuracy 0.9.0b16: Use async interfaces where possible. Add github stale action. 0.9.0b15: Fix threading issue with cover and valve. 0.9.0b14: Restore previous YAML config support. 0.9.0b13: Refactored cover to provide valve support. Made `version and device` optional in the yaml config 0.9.0b12: Fix fan support. Fix cover service calls. Add GPS to device tracker 0.9.0b11: Fix up light support. Fix race condition in meta data write Fix reload issue that just doubled up the devices 0.9.0b10: Fix IO in event loop issues 0.9.0a9: I forgot to bump the revision Fix set availability service 0.9.0a8: fix upgrade issue #2, use config functions not hard coded directory locations 0.9.0a7: remove deprecated constants fix upgrade issue 0.9.0a6: add an import notice added Czech translation, thanks @Tony763 0.9.0a5: fix availability service issue 0.9.0a4: fix time delta import issue 0.9.0a3: fix device tracker import issue Slovakian translations, thanks @misa1515 0.9.0a2: add extra import debug 0.9.0a1: move to config flow and proper integration support 0.8.0b1: move into beta... 0.8.0a3: save device tracker location 0.8.0a2: added locking/unlocking state to locks 0.8.0a1: Added state restore to all but device tracker. [thanks to SergeyPomelov for the push on this] 0.7.9: Added state restore to sensor [thanks to SergeyPomelov] 0.7.8: Added brightness support. 0.7.7: Remove deprecated white value code Added units of measurement [thanks Tony763] Added custome effects [thanks Digitalralf] Updated HACS url [thanks wrt54g] 0.7.6: Remove deprecated fan speeds 0.7.4: Fix attributes issue. 0.7.3: Add percentage support to fan Allow user to set availability of the device 0.7.2: Make virtual part of name optional 0.7.1: fixed Home Assistant breaking change 0.4: fixed missing exception 0.3: added locks 0.2: added device trackers 0.1: initial release ================================================ FILE: custom_components/virtual/__init__.py ================================================ """ This component provides support for virtual components. """ import logging import voluptuous as vol import asyncio import homeassistant.helpers.config_validation as cv import homeassistant.helpers.device_registry as dr from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.issue_registry import ( async_create_issue, IssueSeverity ) from homeassistant.helpers.service import verify_domain_control from homeassistant.helpers.typing import ConfigType from homeassistant.config_entries import ConfigEntry, SOURCE_IMPORT from homeassistant.const import ATTR_ENTITY_ID, CONF_SOURCE, Platform from homeassistant.core import ( DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback ) from homeassistant.exceptions import HomeAssistantError from .const import * from .cfg import BlendedCfg, UpgradeCfg __version__ = '0.9.4' _LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = vol.Schema({ COMPONENT_DOMAIN: vol.Schema({ vol.Optional(CONF_YAML_CONFIG, default=False): cv.boolean, }), }, extra=vol.ALLOW_EXTRA, ) SERVICE_AVAILABILE = 'set_available' SERVICE_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.comp_entity_ids, vol.Required('value'): cv.boolean, }) VIRTUAL_PLATFORMS = [ Platform.BINARY_SENSOR, Platform.COVER, Platform.DEVICE_TRACKER, Platform.FAN, Platform.LIGHT, Platform.LOCK, Platform.NUMBER, Platform.SENSOR, Platform.SWITCH, Platform.VALVE ] def str_to_bool(value) -> bool: value = value.lower() if value in ["y", "yes", "t", "true", "on", "1"]: return True if value in ["n", "no", "f", "false", "off", "0"]: return False raise ValueError async def async_setup(hass, config): """Set up a virtual components. This uses the old mechanism and has to be enabled with 'yaml_config: True' """ # Set up hass data if necessary if COMPONENT_DOMAIN not in hass.data: hass.data[COMPONENT_DOMAIN] = {} hass.data[COMPONENT_SERVICES] = {} hass.data[COMPONENT_CONFIG] = {} # See if yaml support was enabled. if not config.get(COMPONENT_DOMAIN, {}).get(CONF_YAML_CONFIG, False): # New style. We import old config if needed. _LOGGER.debug("setting up new virtual components") hass.data[COMPONENT_CONFIG][CONF_YAML_CONFIG] = False # See if we have already imported the data. If we haven't then do it now. config_entry = _async_find_matching_config_entry(hass) if not config_entry: _LOGGER.debug('importing a YAML setup') hass.async_create_task( hass.config_entries.flow.async_init( COMPONENT_DOMAIN, context={CONF_SOURCE: SOURCE_IMPORT}, data=config ) ) async_create_issue( hass, HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{COMPONENT_DOMAIN}", is_fixable=False, issue_domain=COMPONENT_DOMAIN, severity=IssueSeverity.WARNING, translation_key="deprecated_yaml", translation_placeholders={ "domain": COMPONENT_DOMAIN, "integration_title": "Virtual", }, ) else: _LOGGER.debug('ignoring a YAML setup') else: # Original style. We just use the entities as now. _LOGGER.debug("setting up old virtual components") hass.data[COMPONENT_CONFIG][CONF_YAML_CONFIG] = True @verify_domain_control(COMPONENT_DOMAIN) async def async_virtual_service_set_available(call) -> None: """Call virtual service handler.""" _LOGGER.info("{} service called".format(call.service)) await async_virtual_set_availability_service(hass, call) hass.services.async_register(COMPONENT_DOMAIN, SERVICE_AVAILABILE, async_virtual_service_set_available) return True @callback def _async_find_matching_config_entry(hass): """ If we have anything in config_entries for virtual we consider it configured and will ignore the YAML. """ for entry in hass.config_entries.async_entries(COMPONENT_DOMAIN): return entry async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: _LOGGER.debug(f'async setup {entry.data}') # Set up hass data if necessary if COMPONENT_DOMAIN not in hass.data: hass.data[COMPONENT_DOMAIN] = {} hass.data[COMPONENT_SERVICES] = {} hass.data[COMPONENT_CONFIG] = {} # Get the config. _LOGGER.debug(f"creating new cfg") vcfg = BlendedCfg(hass, entry.data) await vcfg.async_load() # create the devices. _LOGGER.debug("creating the devices") for device in vcfg.devices: _LOGGER.debug(f"creating-device={device}") await _async_get_or_create_virtual_device_in_registry(hass, entry, device) await asyncio.sleep(1) # Delete orphaned devices. for switch, device in vcfg.orphaned_entities.items(): _LOGGER.debug(f"deleting {switch}/{device}") await _async_delete_virtual_device_from_registry(hass, entry, device) # Update the component data. hass.data[COMPONENT_DOMAIN].update({ entry.data[ATTR_GROUP_NAME]: { ATTR_ENTITIES: vcfg.entities, ATTR_DEVICES: vcfg.devices, ATTR_FILE_NAME: entry.data[ATTR_FILE_NAME] } }) _LOGGER.debug(f"update hass data {hass.data[COMPONENT_DOMAIN]}") # Create the entities. _LOGGER.debug("creating the entities") await hass.config_entries.async_forward_entry_setups(entry, VIRTUAL_PLATFORMS) # Install service handler. @verify_domain_control(COMPONENT_DOMAIN) async def async_virtual_service_set_available(call) -> None: """Call virtual service handler.""" _LOGGER.info(f"{call.service} service called") await async_virtual_set_availability_service(hass, call) if not hasattr(hass.data[COMPONENT_SERVICES], COMPONENT_DOMAIN): _LOGGER.debug("installing handlers") hass.data[COMPONENT_SERVICES][COMPONENT_DOMAIN] = 'installed' hass.services.async_register(COMPONENT_DOMAIN, SERVICE_AVAILABILE, async_virtual_service_set_available, schema=SERVICE_SCHEMA) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" _LOGGER.debug(f"unloading virtual group {entry.data[ATTR_GROUP_NAME]}") # _LOGGER.debug(f"before hass={hass.data[COMPONENT_DOMAIN]}") unload_ok = await hass.config_entries.async_unload_platforms(entry, VIRTUAL_PLATFORMS) if unload_ok: _LOGGER.debug("unloaded ok") hass.data[COMPONENT_DOMAIN].pop(entry.data[ATTR_GROUP_NAME]) # _LOGGER.debug(f"ocfg={ocfg}") # _LOGGER.debug(f"after hass={hass.data[COMPONENT_DOMAIN]}") return unload_ok def get_entity_configs(hass, group_name, domain): return hass.data.get(COMPONENT_DOMAIN, {}).get(group_name, {}).get(ATTR_ENTITIES, {}).get(domain, []) def get_entity_from_domain(hass, domain, entity_id): component = hass.data.get(domain) if component is None: raise HomeAssistantError("{} component not set up".format(domain)) entity = component.get_entity(entity_id) if entity is None: raise HomeAssistantError("{} not found".format(entity_id)) return entity async def async_virtual_set_availability_service(hass, call): value = call.data['value'] if type(value) is not bool: value = str_to_bool(value) for entity_id in call.data['entity_id']: domain = entity_id.split(".")[0] _LOGGER.info("{} set_avilable(value={})".format(entity_id, value)) get_entity_from_domain(hass, domain, entity_id).set_available(value) async def _async_get_or_create_virtual_device_in_registry( hass: HomeAssistant, entry: ConfigEntry, device ) -> None: registry = dr.async_get(hass) registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(COMPONENT_DOMAIN, device[ATTR_DEVICE_ID])}, manufacturer=COMPONENT_MANUFACTURER, model=COMPONENT_MODEL, name=device[CONF_NAME], sw_version=__version__ ) async def _async_delete_virtual_device_from_registry( hass: HomeAssistant, _entry: ConfigEntry, device ) -> None: registery = dr.async_get(hass) device_in_registry = registery.async_get_device( identifiers={(COMPONENT_DOMAIN, device[ATTR_DEVICE_ID])}, ) if device_in_registry: _LOGGER.debug(f"found something to delete! {device_in_registry.id}") registery.async_remove_device(device_in_registry.id) else: _LOGGER.info(f"have orphaned device in meta {device[ATTR_DEVICE_ID]}") ================================================ FILE: custom_components/virtual/binary_sensor.py ================================================ """ This component provides support for a virtual binary sensor. """ import logging import voluptuous as vol from collections.abc import Callable import homeassistant.helpers.config_validation as cv from homeassistant.components.binary_sensor import ( BinarySensorEntity, DOMAIN as PLATFORM_DOMAIN ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ENTITY_ID, ATTR_DEVICE_CLASS, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from . import get_entity_from_domain, get_entity_configs from .const import * from .entity import VirtualEntity, virtual_schema _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] DEFAULT_BINARY_SENSOR_VALUE = "off" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(virtual_schema(DEFAULT_BINARY_SENSOR_VALUE, { vol.Optional(CONF_CLASS): cv.string, })) BINARY_SENSOR_SCHEMA = vol.Schema(virtual_schema(DEFAULT_BINARY_SENSOR_VALUE, { vol.Optional(CONF_CLASS): cv.string, })) SERVICE_ON = "turn_on" SERVICE_OFF = "turn_off" SERVICE_TOGGLE = "toggle" SERVICE_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.comp_entity_ids, }) def setup_services(hass: HomeAssistant) -> None: async def async_virtual_service(call): """Call virtual service handler.""" _LOGGER.debug(f"{call.service} service called") if call.service == SERVICE_ON: await async_virtual_on_service(hass, call) if call.service == SERVICE_OFF: await async_virtual_off_service(hass, call) if call.service == SERVICE_TOGGLE: await async_virtual_toggle_service(hass, call) # Build up services... if not hasattr(hass.data[COMPONENT_SERVICES], PLATFORM_DOMAIN): _LOGGER.debug("installing binary_service handlers") hass.data[COMPONENT_SERVICES][PLATFORM_DOMAIN] = 'installed' hass.services.async_register( COMPONENT_DOMAIN, SERVICE_ON, async_virtual_service, schema=SERVICE_SCHEMA, ) hass.services.async_register( COMPONENT_DOMAIN, SERVICE_OFF, async_virtual_service, schema=SERVICE_SCHEMA, ) hass.services.async_register( COMPONENT_DOMAIN, SERVICE_TOGGLE, async_virtual_service, schema=SERVICE_SCHEMA, ) async def async_setup_platform(hass, config, async_add_entities, _discovery_info=None): if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") sensors = [VirtualBinarySensor(config, True)] async_add_entities(sensors, True) setup_services(hass) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = BINARY_SENSOR_SCHEMA(entity) entities.append(VirtualBinarySensor(entity, False)) async_add_entities(entities) setup_services(hass) class VirtualBinarySensor(VirtualEntity, BinarySensorEntity): """An implementation of a Virtual Binary Sensor.""" def __init__(self, config, old_style: bool): """Initialize a Virtual Binary Sensor.""" super().__init__(config, PLATFORM_DOMAIN, old_style) self._attr_device_class = config.get(CONF_CLASS) _LOGGER.info(f"VirtualBinarySensor: {self.name} created") def _create_state(self, config): super()._create_state(config) self._attr_is_on = config.get(CONF_INITIAL_VALUE).lower() == STATE_ON def _restore_state(self, state, config): super()._restore_state(state, config) self._attr_is_on = state.state.lower() == STATE_ON def _update_attributes(self): super()._update_attributes() self._attr_extra_state_attributes.update({ name: value for name, value in ( (ATTR_DEVICE_CLASS, self._attr_device_class), ) if value is not None }) def turn_on(self) -> None: _LOGGER.debug(f"turning {self.name} on") self._attr_is_on = True self.async_schedule_update_ha_state() def turn_off(self) -> None: _LOGGER.debug(f"turning {self.name} off") self._attr_is_on = False self.async_schedule_update_ha_state() def toggle(self) -> None: if self.is_on: self.turn_off() else: self.turn_on() async def async_virtual_on_service(hass, call): for entity_id in call.data['entity_id']: _LOGGER.debug(f"turning on {entity_id}") get_entity_from_domain(hass, PLATFORM_DOMAIN, entity_id).turn_on() async def async_virtual_off_service(hass, call): for entity_id in call.data['entity_id']: _LOGGER.debug(f"turning off {entity_id}") get_entity_from_domain(hass, PLATFORM_DOMAIN, entity_id).turn_off() async def async_virtual_toggle_service(hass, call): for entity_id in call.data['entity_id']: _LOGGER.debug(f"toggling {entity_id}") get_entity_from_domain(hass, PLATFORM_DOMAIN, entity_id).toggle() ================================================ FILE: custom_components/virtual/cfg.py ================================================ """ Handles the file based Virtual configuration. Virtual seems to need a lot device config so rather than get rid of the options or clutter up the config flow system I'm adding a text file where the user can configure things. There are 2 pieces: - `BlendedCfg`; this class is responsible for loading the new file based configuration and merging it with the flow data and options. - `UpgradeCfg`; A helper class to import configuration from the old YAML layout. """ import aiofiles import asyncio import copy import logging import json import voluptuous as vol import uuid from datetime import timedelta from homeassistant.const import ( ATTR_ENTITY_ID, CONF_PLATFORM, CONF_UNIT_OF_MEASUREMENT, Platform ) from homeassistant.helpers import config_validation as cv from homeassistant.util import slugify from homeassistant.util.yaml import parse_yaml, dump from .const import * from .entity import virtual_schema _LOGGER = logging.getLogger(__name__) BINARY_SENSOR_DEFAULT_INITIAL_VALUE = 'off' BINARY_SENSOR_SCHEMA = vol.Schema(virtual_schema(BINARY_SENSOR_DEFAULT_INITIAL_VALUE, { vol.Optional(CONF_CLASS): cv.string, })) SENSOR_DEFAULT_INITIAL_VALUE = '0' SENSOR_SCHEMA = vol.Schema(virtual_schema(SENSOR_DEFAULT_INITIAL_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=""): cv.string, })) _meta_lock = asyncio.Lock() def _fix_value(value): """ If needed, convert value into a type that can be stored in yaml. """ if isinstance(value, timedelta): return max(value.seconds, 1) return value async def _async_load_json(file_name): _LOGGER.debug("_async_load_yaml1 file_name for %s", file_name) try: async with aiofiles.open(file_name, 'r') as meta_file: _LOGGER.debug("_async_load_yaml2 file_name for %s", file_name) contents = await meta_file.read() _LOGGER.debug("_async_load_yaml3 file_name for %s", file_name) return json.loads(contents) except Exception as e: _LOGGER.debug("_async_load_yaml3 file_name for %s", file_name) return {} async def _async_save_json(file_name, data): _LOGGER.debug("_async_save_yaml1 file_name for %s", file_name) try: async with aiofiles.open(file_name, 'w') as meta_file: data = json.dumps(data, indent=4) await meta_file.write(data) except Exception as e: _LOGGER.debug("_async_load_yaml3 file_name for %s", file_name) async def _async_load_yaml(file_name): _LOGGER.debug("_async_load_yaml1 file_name for %s", file_name) try: async with aiofiles.open(file_name, 'r') as meta_file: _LOGGER.debug("_async_load_yaml2 file_name for %s", file_name) contents = await meta_file.read() _LOGGER.debug("_async_load_yaml3 file_name for %s", file_name) return parse_yaml(contents) except Exception as e: _LOGGER.debug("_async_load_yaml3 file_name for %s", file_name) return {} async def _async_save_yaml(file_name, data): _LOGGER.debug("_async_save_yaml1 file_name for %s", file_name) try: async with aiofiles.open(file_name, 'w') as meta_file: data = dump(data) await meta_file.write(data) except Exception as e: _LOGGER.debug("_async_load_yaml3 file_name for %s", file_name) async def _load_meta_data(hass, group_name: str): """Read in meta data for a particular group. """ async with _meta_lock: data = await _async_load_json(default_meta_file(hass)) return data.get(ATTR_DEVICES, {}).get(group_name, {}) async def _save_meta_data(hass, group_name, meta_data): """Save meta data for a particular group name. """ async with _meta_lock: # Read in current meta data devices = await _async_load_json(default_meta_file(hass)) devices = devices.get(ATTR_DEVICES, {}) # Update (or add) the group piece. _LOGGER.debug(f"meta before {devices}") devices.update({ group_name: meta_data }) _LOGGER.debug(f"meta after {devices}") # Write it back out. await _async_save_json(default_meta_file(hass), { ATTR_VERSION: 1, ATTR_DEVICES: devices }) async def _delete_meta_data(hass, group_name): """Save meta data for a particular group name. """ async with _meta_lock: # Read in current meta data devices = await _async_load_json(default_meta_file(hass)) devices = devices.get(ATTR_DEVICES, {}) # Delete the group piece. _LOGGER.debug(f"meta before {devices}") devices.pop(group_name) _LOGGER.debug(f"meta after {devices}") # Write it back out. await _async_save_json(default_meta_file(hass), { ATTR_VERSION: 1, ATTR_DEVICES: devices }) async def _save_user_data(file_name, devices): await _async_save_yaml(file_name, { ATTR_VERSION: 1, ATTR_DEVICES: devices }) async def _load_user_data(file_name): entities = await _async_load_yaml(file_name) # make devices: optional. return entities.get(ATTR_DEVICES, entities) def _fix_config(config): """Find and return the virtual entries from any platform config. """ _LOGGER.debug(f"config={config}") entries = [] for entry in config: if entry[CONF_PLATFORM] == COMPONENT_DOMAIN: entry = copy.deepcopy(entry) entry.pop(CONF_PLATFORM) entries.append(entry) return entries def _upgrade_name(name: str): """We're making the non virtual prefix the default so this flips the naming. """ if name.startswith("!"): return name[1:] elif name.startswith("virtual_"): return f"+{name[8:]}" else: return f"+{name}" def _parse_old_config(devices, configs, platform): """Parse out config into different devices. We do several things: - insert a platform key/value, i.e, this this is a switch - fix the naming - create and store the entity under a device, for imported config there will only be one entity per device """ for config in configs: if not isinstance(config, dict): _LOGGER.debug(f"not dictionary={config}") continue if config[CONF_PLATFORM] != COMPONENT_DOMAIN: continue # Copy and fix up config. config = copy.deepcopy(config) config[CONF_PLATFORM] = platform config[CONF_NAME] = _upgrade_name(config[CONF_NAME]) # Fix values that need to be saved in yaml config = {k: _fix_value(v) for k, v in config.items()} # Insert or create a device for it. if config[CONF_NAME] in devices: devices[config[CONF_NAME]].append(config) else: devices[config[CONF_NAME]] = [config] return devices def _make_original_unique_id(name): if name.startswith("+"): return slugify(name[1:]) else: return slugify(name) def _make_name(name): if name.startswith("+"): return name[1:] return name def _make_entity_id(platform, name): if name.startswith("+"): return f'{platform}.{COMPONENT_DOMAIN}_{slugify(name[1:])}' else: return f'{platform}.{slugify(name)}' def _make_unique_id(): return f'{uuid.uuid4()}.{COMPONENT_DOMAIN}' def _make_suffix(platform, device_class): """Make a suitable suffix for an unnamed entity. Binary sensors, covers and sensors have a class so we append that, everything else gets left as-is. """ if platform in [Platform.BINARY_SENSOR, Platform.COVER, Platform.SENSOR]: if device_class is None: return platform else: return f"{device_class}" return "" class BlendedCfg(object): """Helper class to get at Virtual configuration options. Reads in non config flow settings from the external config file and merges them with flow data and options. """ def __init__(self, hass, flow_data): self._hass = hass self._group_name = flow_data[ATTR_GROUP_NAME] self._file_name = flow_data[ATTR_FILE_NAME] self._meta_data = {} self._orphaned_entities = {} self._devices = [] self._entities = {} async def async_load(self): meta_data = await _load_meta_data(self._hass, self._group_name) devices = await _load_user_data(self._file_name) changed = False _LOGGER.debug(f"loaded-meta-data={meta_data}") _LOGGER.debug(f"loaded-devices={devices}") # Let's fix up the devices/entities for device_name, entities in devices.items(): # Create device. One per all entities. self._devices.append({ ATTR_DEVICE_ID: device_name, CONF_NAME: _make_name(device_name) }) for entity in entities: platform = entity.pop(CONF_PLATFORM) device_class = entity.get(CONF_CLASS, None) # Figure out the name. We use the one provided and if that isn't # there the device name and, optionally, the class. name = entity.get(CONF_NAME, None) if name is None: name = f"{device_name} {_make_suffix(platform, device_class)}" # Look up unique id for this device. If not there this is a new # device. unique_id = meta_data.get(name, {}).get(ATTR_UNIQUE_ID, None) if unique_id is None: _LOGGER.debug(f"creating {name}") unique_id = _make_unique_id() meta_data.update({name: { ATTR_UNIQUE_ID: unique_id, ATTR_ENTITY_ID: _make_entity_id(platform, name), ATTR_DEVICE_ID: device_name }}) changed = True # Now copy over the entity id of the device. Not having this is a # bug. entity_id = meta_data.get(name, {}).get(ATTR_ENTITY_ID, None) if entity_id is None: _LOGGER.info(f"problem creating {name}, no entity id") continue # Add device entry if meta_data.get(name, {}).get(ATTR_DEVICE_ID, None) is None: _LOGGER.info(f"problem creating {name}, no device id") meta_data[name][ATTR_DEVICE_ID] = device_name changed = True # Update the entity. entity.update({ CONF_NAME: _make_name(name), ATTR_ENTITY_ID: entity_id, ATTR_UNIQUE_ID: unique_id, ATTR_DEVICE_ID: device_name }) _LOGGER.debug(f"added entity {platform}/{entity}") # Now store in the correct place. Move off temporary meta # data list. # _LOGGER.debug(f"entities={self._entities}") if platform not in self._entities: self._entities[platform] = [] self._entities[platform].append(entity) self._meta_data.update({ name: meta_data.pop(name) }) # Create orphaned list. If we have anything here we need to update # the saved meta data. for switch, values in meta_data.items(): values[CONF_NAME] = switch self._orphaned_entities.update({ values[ATTR_UNIQUE_ID]: values }) changed = True # Make sure changes are kept. if changed: await _save_meta_data(self._hass, self._group_name, self._meta_data) _LOGGER.debug(f"meta-data={self._meta_data}") _LOGGER.debug(f"devices={self._devices}") _LOGGER.debug(f"entities={self._entities}") _LOGGER.debug(f"orphaned-entities={self._orphaned_entities}") async def async_delete(self): _LOGGER.debug(f"deleting {self._group_name}") await _delete_meta_data(self._hass, self._group_name) @property def devices(self): return self._devices @property def entities(self): return self._entities @property def orphaned_entities(self): return self._orphaned_entities @property def binary_sensor_config(self): return self._entities.get(Platform.BINARY_SENSOR, []) @property def sensor_config(self): return self._entities.get(Platform.SENSOR, []) @property def switch_config(self): return self._entities.get(Platform.SWITCH, []) class UpgradeCfg(object): """Read in the old YAML config and convert it to the new format. """ @staticmethod async def async_import_yaml(hass, config): """ Take the current virtual config and make the new yaml file. Virtual needs a lot of fine tuning so rather than get rid of the options or clutter up the config flow system I'm adding a text file where the user can configure things. """ devices_meta_data = {} devices = {} # Add in the easily formatted devices. for platform in [Platform.BINARY_SENSOR, Platform.SENSOR, Platform.FAN, Platform.LIGHT, Platform.LOCK, Platform.SWITCH]: devices = _parse_old_config(devices, config.get(platform, []), str(platform)) # Device tracker is awkward, we have to split it out and fake looking # like the other entities. all_device_trackers = config.get(Platform.DEVICE_TRACKER, []) for device_trackers in all_device_trackers: if device_trackers[CONF_PLATFORM] != COMPONENT_DOMAIN: continue for device_tracker_name in device_trackers.get("devices", []): if isinstance(device_tracker_name, dict): device_tracker_name = device_tracker_name[CONF_NAME] devices = _parse_old_config(devices, [{ CONF_PLATFORM: COMPONENT_DOMAIN, CONF_NAME: device_tracker_name }], str(Platform.DEVICE_TRACKER)) _LOGGER.info(f"devices={devices}") # Here we have all the original devices we build the meta data. # For import # - we can only have one entity per device, which means... # - devices are their own parent for name, values in devices.items(): unique_id = _make_original_unique_id(name) entity_id = _make_entity_id(values[0][CONF_PLATFORM], name) _LOGGER.debug(f"uid={unique_id}") _LOGGER.debug(f"eid={entity_id}") devices_meta_data.update({name: { ATTR_UNIQUE_ID: unique_id, ATTR_ENTITY_ID: entity_id }}) _LOGGER.debug(f"devices-meta-data={devices_meta_data}") await _save_user_data(default_config_file(hass), devices) await _save_meta_data(hass, IMPORTED_GROUP_NAME, devices_meta_data) @staticmethod def create_flow_data(hass, _config): """ Take the current aarlo config and make the new flow configuration. """ _LOGGER.debug(f"new-config-file={default_config_file(hass)}") _LOGGER.debug(f"new-meta-file={default_meta_file(hass)}") return { ATTR_GROUP_NAME: IMPORTED_GROUP_NAME, ATTR_FILE_NAME: default_config_file(hass) } ================================================ FILE: custom_components/virtual/config_flow.py ================================================ """Config flow for Aarlo""" import logging import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME ) from .const import * from .cfg import UpgradeCfg _LOGGER = logging.getLogger(__name__) class VirtualFlowHandler(config_entries.ConfigFlow, domain=COMPONENT_DOMAIN): """Aarlo config flow.""" VERSION = 1 async def validate_input(self, user_input): for group, values in self.hass.data.get(COMPONENT_DOMAIN, {}).items(): _LOGGER.debug(f"checking {group}") if group == user_input[ATTR_GROUP_NAME]: raise GroupNameAlreadyUsed if values[ATTR_FILE_NAME] == user_input[ATTR_FILE_NAME]: raise FileNameAlreadyUsed return { "title": f"{user_input[ATTR_GROUP_NAME]} - {COMPONENT_DOMAIN}" } async def async_step_user(self, user_input): _LOGGER.debug(f"step user {user_input}") errors = {} if user_input is not None: try: info = await self.validate_input(user_input) return self.async_create_entry(title=info["title"], data={ ATTR_GROUP_NAME: user_input[ATTR_GROUP_NAME], ATTR_FILE_NAME: user_input[ATTR_FILE_NAME], }) except GroupNameAlreadyUsed as e: errors["base"] = "group_name_used" except FileNameAlreadyUsed as e: errors["base"] = "file_name_used" else: # Fill in some defaults. user_input = { ATTR_GROUP_NAME: IMPORTED_GROUP_NAME, ATTR_FILE_NAME: default_config_file(self.hass) } return self.async_show_form( step_id="user", data_schema=vol.Schema({ vol.Required(ATTR_GROUP_NAME, default=user_input[ATTR_GROUP_NAME]): str, vol.Required(ATTR_FILE_NAME, default=user_input[ATTR_FILE_NAME]): str }), errors=errors ) async def async_step_import(self, import_data): """Import momentary config from configuration.yaml.""" _LOGGER.debug(f"importing aarlo YAML {import_data}") await UpgradeCfg.async_import_yaml(self.hass, import_data) data = UpgradeCfg.create_flow_data(self.hass, import_data) return self.async_create_entry( title=f"Imported Virtual Group", data=data ) class GroupNameAlreadyUsed(exceptions.HomeAssistantError): """ Error indicating group name already used. """ class FileNameAlreadyUsed(exceptions.HomeAssistantError): """ Error indicating file name already used. """ ================================================ FILE: custom_components/virtual/const.py ================================================ """Constants for the virtual component. """ COMPONENT_DOMAIN = "virtual" COMPONENT_SERVICES = "virtual-services" COMPONENT_CONFIG = "virtual-config" COMPONENT_MANUFACTURER = "twrecked" COMPONENT_MODEL = "virtual" ATTR_AVAILABLE = 'available' ATTR_DEVICES = "devices" ATTR_DEVICE_ID = "device_id" ATTR_ENTITIES = "entities" ATTR_FILE_NAME = "file_name" ATTR_GROUP_NAME = "group_name" ATTR_PARENT_ID = "parent_id" ATTR_PERSISTENT = 'persistent' ATTR_UNIQUE_ID = 'unique_id' ATTR_VALUE = "value" ATTR_VERSION = "version" CONF_CLASS = "class" CONF_INITIAL_AVAILABILITY = "initial_availability" CONF_INITIAL_VALUE = "initial_value" CONF_MAX = "max" CONF_MIN = "min" CONF_NAME = "name" CONF_OPEN_CLOSE_DURATION = "open_close_duration" CONF_OPEN_CLOSE_TICK = "open_close_tick" CONF_PERSISTENT = "persistent" CONF_YAML_CONFIG = "yaml_config" DEFAULT_AVAILABILITY = True DEFAULT_PERSISTENT = True IMPORTED_GROUP_NAME = "imported" def default_config_file(hass) -> str: return hass.config.path("virtual.yaml") def default_meta_file(hass) -> str: return hass.config.path(".storage/virtual.meta.json") ================================================ FILE: custom_components/virtual/cover.py ================================================ """ This component provides support for a virtual cover. """ import logging import voluptuous as vol from typing import Any from collections.abc import Callable import homeassistant.helpers.config_validation as cv from homeassistant.components.cover import ( CoverEntity, CoverEntityFeature, DOMAIN as PLATFORM_DOMAIN ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from . import get_entity_configs from .const import * from .entity import ( VirtualOpenableEntity, virtual_schema, positive_tick, ) _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] DEFAULT_COVER_VALUE = "open" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(virtual_schema(DEFAULT_COVER_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Optional(CONF_OPEN_CLOSE_DURATION, default=10): cv.positive_int, vol.Optional(CONF_OPEN_CLOSE_TICK, default=1): positive_tick, })) COVER_SCHEMA = vol.Schema(virtual_schema(DEFAULT_COVER_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Optional(CONF_OPEN_CLOSE_DURATION, default=10): cv.positive_int, vol.Optional(CONF_OPEN_CLOSE_TICK, default=1): positive_tick, })) async def async_setup_platform(hass, config, async_add_entities, _discovery_info=None): if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") sensors = [VirtualCover(config, True)] async_add_entities(sensors, True) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = COVER_SCHEMA(entity) entities.append(VirtualCover(entity, False)) async_add_entities(entities) class VirtualCover(VirtualOpenableEntity, CoverEntity): """Representation of a Virtual cover.""" def __init__(self, config, old_style : bool): """Initialize the Virtual cover device.""" super().__init__(config, PLATFORM_DOMAIN, old_style) self._attr_supported_features = CoverEntityFeature( CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.STOP | CoverEntityFeature.SET_POSITION ) _LOGGER.info(f"VirtualCover: {self.name} created") @property def current_cover_position(self) -> int | None: return self._current_position async def async_open_cover(self, **kwargs: Any) -> None: _LOGGER.info(f"opening {self.name}") self._set_position(100) async def async_close_cover(self, **kwargs: Any) -> None: _LOGGER.info(f"closing {self.name}") self._set_position(0) async def async_stop_cover(self, **kwargs: Any) -> None: _LOGGER.info(f"stopping {self.name}") self._stop() async def async_set_cover_position(self, **kwargs: Any) -> None: _LOGGER.info(f"setting {self.name} position {kwargs['position']}") self._set_position(kwargs['position']) ================================================ FILE: custom_components/virtual/device_tracker.py ================================================ """ This component provides support for a virtual device tracker. """ import aiofiles import logging import voluptuous as vol import json from collections.abc import Callable import homeassistant.helpers.config_validation as cv from homeassistant.components.device_tracker import ( DOMAIN as PLATFORM_DOMAIN, SourceType, TrackerEntity, ) from homeassistant.components.zone import ATTR_RADIUS from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_DEVICES ) from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.event import async_track_state_change_event from . import get_entity_from_domain, get_entity_configs from .const import * from .entity import VirtualEntity, virtual_schema _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] CONF_LOCATION = 'location' CONF_GPS = 'gps' CONF_GPS_ACCURACY = 'gps_accuracy' DEFAULT_DEVICE_TRACKER_VALUE = 'home' DEFAULT_LOCATION = 'home' STATE_FILE = "/config/.storage/virtual.restore_state" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_DEVICES, default=[]): cv.ensure_list }) DEVICE_TRACKER_SCHEMA = vol.Schema(virtual_schema(DEFAULT_DEVICE_TRACKER_VALUE, { })) SERVICE_MOVE = "move" SERVICE_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.comp_entity_ids, vol.Optional(CONF_LOCATION): cv.string, vol.Optional(CONF_GPS): { vol.Required(ATTR_LATITUDE): cv.latitude, vol.Required(ATTR_LONGITUDE): cv.longitude, vol.Optional(ATTR_RADIUS): cv.string, }, vol.Optional(CONF_GPS_ACCURACY): cv.positive_int, }) tracker_states = {} async def _async_load_json(file_name): try: async with aiofiles.open(file_name, 'r') as state_file: contents = await state_file.read() return json.loads(contents) except Exception as e: return {} def _write_state(): global tracker_states try: with open(STATE_FILE, 'w') as f: json.dump(tracker_states, f) except: pass def _state_changed(event): entity_id = event.data.get('entity_id', None) new_state = event.data.get('new_state', None) if entity_id is None or new_state is None: _LOGGER.info(f'state changed error') return # update database _LOGGER.info(f"moving {entity_id} to {new_state.state}") global tracker_states tracker_states[entity_id] = new_state.state _write_state() def _shutting_down(event): _LOGGER.info(f'shutting down {event}') _write_state() async def async_setup_scanner(hass, config, async_see, _discovery_info=None): """Set up the virtual tracker.""" if not hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): return True _LOGGER.debug("setting up old device trackers...") # Read in the last known states. old_tracker_states = await _async_load_json(STATE_FILE) new_tracker_states = {} for device in config[CONF_DEVICES]: if not isinstance(device, dict): device = { CONF_NAME: device, } name = device.get(CONF_NAME, 'unknown') location = device.get(CONF_LOCATION, DEFAULT_LOCATION) peristent = device.get(CONF_PERSISTENT, DEFAULT_PERSISTENT) entity_id = f"{PLATFORM_DOMAIN}.{name}" if peristent: location = old_tracker_states.get(entity_id, location) new_tracker_states[entity_id] = location _LOGGER.info(f"setting persistent {entity_id} to {location}") else: _LOGGER.info(f"setting ephemeral {entity_id} to {location}") see_args = { "dev_id": name, "source_type": COMPONENT_DOMAIN, "location_name": location, } hass.async_create_task(async_see(**see_args)) # Start listening if there are persistent entities. global tracker_states tracker_states = new_tracker_states if tracker_states: async_track_state_change_event(hass, tracker_states.keys(), _state_changed) hass.bus.async_listen("homeassistant_stop", _shutting_down) else: _write_state() return True async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the device_tracker entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = DEVICE_TRACKER_SCHEMA(entity) entities.append(VirtualDeviceTracker(entity)) async_add_entities(entities) async def async_virtual_service(call): """Call virtual service handler.""" _LOGGER.debug(f"{call.service} service called") if call.service == SERVICE_MOVE: await async_virtual_move_service(hass, call) # Build up services... if not hasattr(hass.data[COMPONENT_SERVICES], PLATFORM_DOMAIN): _LOGGER.debug("installing handlers") hass.data[COMPONENT_SERVICES][PLATFORM_DOMAIN] = 'installed' hass.services.async_register( COMPONENT_DOMAIN, SERVICE_MOVE, async_virtual_service, schema=SERVICE_SCHEMA, ) class VirtualDeviceTracker(TrackerEntity, VirtualEntity): """Represent a tracked device.""" def __init__(self, config): """Initialize a Virtual Device Tracker.""" # Handle deprecated option. if config.get(CONF_LOCATION, None) is not None: _LOGGER.info("'location' option is deprecated for virtual device trackers, please use 'initial_value'") config[CONF_INITIAL_VALUE] = config.pop(CONF_LOCATION) super().__init__(config, PLATFORM_DOMAIN) self._location = None self._coords = {} self._gps_accuracy = 0 _LOGGER.debug(f"{self._attr_name}, available={self._attr_available}") _LOGGER.debug(f"{self._attr_name}, entity={self.entity_id}") def _create_state(self, config): _LOGGER.debug(f"device_tracker-create=config={config}") super()._create_state(config) self._location = config.get(CONF_INITIAL_VALUE) def _restore_state(self, state, config): _LOGGER.debug(f"device_tracker-restore=state={state.state}") _LOGGER.debug(f"device_tracker-restore=attrs={state.attributes}") if ATTR_AVAILABLE not in state.attributes: _LOGGER.debug("looks wrong, from upgrade? creating instead...") self._create_state(config) return super()._restore_state(state, config) if ATTR_LONGITUDE in state.attributes and ATTR_LATITUDE in state.attributes: self._location = None self._coords = { ATTR_LONGITUDE: state.attributes[ATTR_LONGITUDE], ATTR_LATITUDE: state.attributes[ATTR_LATITUDE], ATTR_RADIUS: 0 } else: self._location = state.state self._coords = {} @property def location_name(self) -> str | None: """Return a location name for the current location of the device.""" return self._location @property def source_type(self) -> SourceType | str: if self._coords: return "gps" return "virtual" @property def latitude(self) -> float | None: """Return latitude value of the device.""" return self._coords.get(ATTR_LATITUDE, None) @property def longitude(self) -> float | None: """Return longitude value of the device.""" return self._coords.get(ATTR_LONGITUDE, None) @property def location_accuracy(self) -> int: return self._gps_accuracy def move_to_location(self, new_location): _LOGGER.debug(f"{self._attr_name} moving to {new_location}") self._location = new_location self._coords = {} self.async_schedule_update_ha_state() def move_to_coords(self, new_coords, accuracy): _LOGGER.debug(f"{self._attr_name} moving via GPS to {new_coords} ({accuracy}m)") self._location = None self._coords = new_coords self._gps_accuracy = accuracy self.async_schedule_update_ha_state() async def async_virtual_move_service(hass, call): for entity_id in call.data['entity_id']: _LOGGER.debug(f"moving {entity_id} --> {call.data}") entity = get_entity_from_domain(hass, PLATFORM_DOMAIN, entity_id) if entity is None: _LOGGER.debug(f"can't find {entity_id}") return location = call.data.get(CONF_LOCATION, None) coords = call.data.get(CONF_GPS, None) if location is not None: entity.move_to_location(location) elif coords is not None: accuracy = call.data.get(CONF_GPS_ACCURACY, 0) entity.move_to_coords(coords, accuracy) else: _LOGGER.debug(f"not moving {entity_id}") ================================================ FILE: custom_components/virtual/entity.py ================================================ """ This component provides support for a virtual sensor. This class adds persistence to an entity. """ import logging import pprint import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.cover import ATTR_CURRENT_POSITION from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ENTITY_ID, STATE_CLOSED, ) from homeassistant.core import callback from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.event import async_call_later from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.util import slugify from .const import * _LOGGER = logging.getLogger(__name__) positive_tick = vol.All(vol.Coerce(float), vol.Range(min=0, min_included=False)) def virtual_schema(default_initial_value: str, extra_attrs): schema = { vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_INITIAL_VALUE, default=default_initial_value): cv.string, vol.Optional(CONF_INITIAL_AVAILABILITY, default=DEFAULT_AVAILABILITY): cv.boolean, vol.Optional(CONF_PERSISTENT, default=DEFAULT_PERSISTENT): cv.boolean, vol.Optional(ATTR_DEVICE_ID, default="NOTYET"): cv.string, vol.Optional(ATTR_ENTITY_ID, default="NOTYET"): cv.string, vol.Optional(ATTR_UNIQUE_ID, default="NOTYET"): cv.string, } schema.update(extra_attrs) return schema class VirtualEntity(RestoreEntity): """A base class to add state restoring. """ # Are we saving/restoring this entity _persistent: bool = True def __init__(self, config, domain, old_style : bool = False): """Initialize an Virtual Sensor.""" _LOGGER.debug(f"creating-virtual-{domain}={config}") self._config = config self._persistent = config.get(CONF_PERSISTENT) if old_style: # Build name, entity id and unique id. We do this because historically # the non-domain piece of the entity_id was prefixed with virtual_ so # we build the pieces manually to make sure. self._attr_name = config.get(CONF_NAME) if self._attr_name.startswith("!"): self._attr_name = self._attr_name[1:] self.entity_id = f'{domain}.{slugify(self._attr_name)}' else: self.entity_id = f'{domain}.{COMPONENT_DOMAIN}_{slugify(self._attr_name)}' self._attr_unique_id = slugify(self._attr_name) else: # Build name, entity id and unique id. We do this because historically # the non-domain piece of the entity_id was prefixed with virtual_ so # we build the pieces manually to make sure. self._attr_name = config.get(CONF_NAME) self.entity_id = config.get(ATTR_ENTITY_ID) if self.entity_id == "NOTYET": if self._attr_name.startswith("+"): self._attr_name = self._attr_name[1:] self.entity_id = f'{domain}.{COMPONENT_DOMAIN}_{slugify(self._attr_name)}' else: self.entity_id = f'{domain}.{slugify(self._attr_name)}' self._attr_unique_id = config.get(ATTR_UNIQUE_ID, None) if self._attr_unique_id == "NOTYET": self._attr_unique_id = slugify(self._attr_name) if config.get(ATTR_DEVICE_ID) != "NOTYET": _LOGGER.debug("setting up device info") self._attr_device_info = DeviceInfo( identifiers={(COMPONENT_DOMAIN, config.get(ATTR_DEVICE_ID))}, manufacturer=COMPONENT_MANUFACTURER, model=COMPONENT_MODEL, ) _LOGGER.info(f'VirtualEntity {self._attr_name} created') def _create_state(self, config): _LOGGER.info(f'VirtualEntity {self.unique_id}: creating initial state') self._attr_available = config.get(CONF_INITIAL_AVAILABILITY) def _restore_state(self, state, config): _LOGGER.info(f'VirtualEntity {self.unique_id}: restoring state') _LOGGER.debug(f'VirtualEntity:: state={pprint.pformat(state.state)}') _LOGGER.debug(f'VirtualEntity:: attr={pprint.pformat(state.attributes)}') self._attr_available = state.attributes.get(ATTR_AVAILABLE) def _update_attributes(self): self._attr_extra_state_attributes = { ATTR_PERSISTENT: self._persistent, ATTR_AVAILABLE: self._attr_available, } if _LOGGER.isEnabledFor(logging.DEBUG): self._attr_extra_state_attributes.update({ ATTR_ENTITY_ID: self.entity_id, ATTR_UNIQUE_ID: self.unique_id, }) async def async_added_to_hass(self) -> None: await super().async_added_to_hass() state = await self.async_get_last_state() if not self._persistent or not state: self._create_state(self._config) else: self._restore_state(state, self._config) self._update_attributes() async def async_will_remove_from_hass(self) -> None: """Call when entity is being removed from hass.""" await super().async_will_remove_from_hass() def set_available(self, value): self._attr_available = value self._update_attributes() self.async_schedule_update_ha_state() class VirtualOpenableEntity(VirtualEntity): """Representation of a Virtual openable. This can handle cover and valve devices. If they diverge too much in the future we will need to rethink this. """ _current_position: float _target_position: float | None _positions_per_tick: float | None _open_close_duration: int _open_close_tick: float _open_close_operation_started: bool | None _attr_is_closed: bool def __init__(self, config, domain, old_style: bool): """Initialize the Virtual openable device.""" _LOGGER.debug(f"creating-virtual-openable-{domain}={config}") super().__init__(config, domain, old_style) self._attr_device_class = config.get(CONF_CLASS) self._open_close_duration = config.get(CONF_OPEN_CLOSE_DURATION) self._open_close_tick = config.get(CONF_OPEN_CLOSE_TICK) self._open_close_operation_started = None self._current_position = 0 self._target_position = None self._positions_per_tick = None _LOGGER.info(f"VirtualOpenable: {self.name} created") def _create_state(self, config): super()._create_state(config) self._attr_is_closed = config.get(CONF_INITIAL_VALUE).lower() == STATE_CLOSED if self._attr_is_closed: self._current_position = 0 else: self._current_position = 100 def _restore_state(self, state, config): super()._restore_state(state, config) # Cover and valve use the same position state. If this changes we will # need to add this into the derived class. if ATTR_CURRENT_POSITION in state.attributes: self._current_position = state.attributes[ATTR_CURRENT_POSITION] self._attr_is_closed = state.state.lower() == STATE_CLOSED def _update_attributes(self): super()._update_attributes() self._attr_extra_state_attributes.update({ name: value for name, value in ( (ATTR_DEVICE_CLASS, self._attr_device_class), ) if value is not None }) def _cancel_timer(self) -> None: """Cancel the current movement timer if active.""" if hasattr(self, '_timer_handle') and self._timer_handle: self._timer_handle() self._timer_handle = None def _stop(self) -> None: _LOGGER.info(f"stopping {self.name} at position {self._current_position}") self._cancel_timer() self._target_position = None self._positions_per_tick = None self._attr_is_opening = False self._attr_is_closing = False self._attr_is_closed = (self._current_position == 0) self.async_write_ha_state() def _set_direction_flags(self, target_position: float) -> None: """Set opening/closing flags based on target position.""" if target_position < self._current_position: self._attr_is_closing = True self._attr_is_opening = False else: self._attr_is_opening = True self._attr_is_closing = False self.async_write_ha_state() def _set_position(self, position: int) -> None: _LOGGER.info(f"setting {self.name} position {position}") self._cancel_timer() position = max(0, min(100, int(position))) self._target_position = position if self._target_position == self._current_position: return if self._open_close_tick > self._open_close_duration: _LOGGER.warning(f"Tick duration {self._open_close_tick} > total duration {self._open_close_duration}, capping to {self._open_close_duration}") self._open_close_tick = self._open_close_duration if self._open_close_duration == 0: # Transition through opening/closing state for automations self._set_direction_flags(self._target_position) # Immediately set final state self._current_position = self._target_position self._attr_is_opening = False self._attr_is_closing = False self._attr_is_closed = (self._current_position == 0) self._target_position = None self.async_schedule_update_ha_state(force_refresh=True) return distance = abs(self._target_position - self._current_position) movement_duration = (distance / 100.0) * self._open_close_duration total_ticks = max(1, int(movement_duration / self._open_close_tick)) self._positions_per_tick = distance / total_ticks self._set_direction_flags(self._target_position) self._timer_handle = async_call_later(self.hass, self._open_close_tick, self._update_position) @callback def _update_position(self, _now) -> None: if self._target_position is None: return if self._attr_is_closing: next_pos = max(self._target_position, self._current_position - self._positions_per_tick) else: next_pos = min(self._target_position, self._current_position + self._positions_per_tick) self._current_position = next_pos if self._current_position == self._target_position: self._stop() else: self.async_write_ha_state() self._timer_handle = async_call_later(self.hass, self._open_close_tick, self._update_position) ================================================ FILE: custom_components/virtual/fan.py ================================================ """ This component provides support for a virtual fan. Borrowed heavily from components/demo/fan.py """ from __future__ import annotations import logging from typing import Any import voluptuous as vol from collections.abc import Callable import homeassistant.helpers.config_validation as cv from homeassistant.components.fan import ( ATTR_DIRECTION, ATTR_OSCILLATING, ATTR_PERCENTAGE, ATTR_PRESET_MODE, DOMAIN as PLATFORM_DOMAIN, FanEntity, FanEntityFeature, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import (PLATFORM_SCHEMA) from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import get_entity_configs from .const import * from .entity import VirtualEntity, virtual_schema _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] CONF_DIRECTION = "direction" CONF_MODES = "modes" CONF_OSCILLATE = "oscillate" CONF_PERCENTAGE = "percentage" CONF_SPEED = "speed" CONF_SPEED_COUNT = "speed_count" DEFAULT_FAN_VALUE = "off" BASE_SCHEMA = virtual_schema(DEFAULT_FAN_VALUE, { vol.Optional(CONF_SPEED, default=False): cv.boolean, vol.Optional(CONF_SPEED_COUNT, default=0): cv.positive_int, vol.Optional(CONF_OSCILLATE, default=False): cv.boolean, vol.Optional(CONF_DIRECTION, default=False): cv.boolean, vol.Optional(CONF_MODES, default=[]): vol.All(cv.ensure_list, [cv.string]), }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(BASE_SCHEMA) FAN_SCHEMA = vol.Schema(BASE_SCHEMA) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, _discovery_info: DiscoveryInfoType | None = None, ) -> None: if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") fans = [VirtualFan(config, True)] async_add_entities(fans, True) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = FAN_SCHEMA(entity) entities.append(VirtualFan(entity, False)) async_add_entities(entities) class VirtualFan(VirtualEntity, FanEntity): """A demonstration fan component.""" def __init__(self, config, old_style: bool): """Initialize the entity.""" super().__init__(config, PLATFORM_DOMAIN, old_style) # Modes if supported self._attr_preset_modes = config.get(CONF_MODES) # Try for speed count then speed. # - speed_count; number of speeds we support # - speed == True; 3 speeds # - speed == False; no speeds self._attr_speed_count = config.get(CONF_SPEED_COUNT) if config.get(CONF_SPEED, False): self._attr_speed_count = 3 self._enable_turn_on_off_backwards_compatibility = False self._attr_supported_features = FanEntityFeature.TURN_ON | FanEntityFeature.TURN_OFF if self._attr_speed_count > 0: self._attr_supported_features |= FanEntityFeature.SET_SPEED if config.get(CONF_OSCILLATE, False): self._attr_supported_features |= FanEntityFeature.OSCILLATE if config.get(CONF_DIRECTION, False): self._attr_supported_features |= FanEntityFeature.DIRECTION _LOGGER.info(f"VirtualFan: {self.name} created") def _create_state(self, config): super()._create_state(config) if self._attr_supported_features & FanEntityFeature.DIRECTION: self._attr_current_direction = "forward" if self._attr_supported_features & FanEntityFeature.OSCILLATE: self._attr_oscillating = False self._attr_percentage = None self._attr_preset_mode = None def _restore_state(self, state, config): super()._restore_state(state, config) if self._attr_supported_features & FanEntityFeature.DIRECTION: self._attr_current_direction = state.attributes.get(ATTR_DIRECTION) if self._attr_supported_features & FanEntityFeature.OSCILLATE: self._attr_oscillating = state.attributes.get(ATTR_OSCILLATING) self._attr_percentage = state.attributes.get(ATTR_PERCENTAGE) self._attr_preset_mode = state.attributes.get(ATTR_PRESET_MODE) def _update_attributes(self): super()._update_attributes() self._attr_extra_state_attributes.update({ name: value for name, value in ( (ATTR_DIRECTION, self._attr_current_direction), (ATTR_OSCILLATING, self._attr_oscillating), (ATTR_PERCENTAGE, self._attr_percentage), (ATTR_PRESET_MODE, self._attr_preset_mode), ) if value is not None }) def _set_percentage(self, percentage: int) -> None: self._attr_percentage = percentage self._attr_preset_mode = None self._update_attributes() def _set_preset_mode(self, preset_mode: str) -> None: if preset_mode in self.preset_modes: self._attr_preset_mode = preset_mode self._attr_percentage = None self._update_attributes() else: raise ValueError(f"Invalid preset mode: {preset_mode}") async def async_set_percentage(self, percentage: int) -> None: """Set the speed of the fan, as a percentage.""" _LOGGER.debug(f"setting {self.name} pcent to {percentage}") self._set_percentage(percentage) async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" _LOGGER.debug(f"setting {self.name} mode to {preset_mode}") self._set_preset_mode(preset_mode) async def async_turn_on( self, percentage: int | None = None, preset_mode: str | None = None, **kwargs: Any, ) -> None: """Turn on the entity.""" _LOGGER.debug(f"turning {self.name} on") if preset_mode: self._set_preset_mode(preset_mode) return if percentage is None: percentage = 67 self._set_percentage(percentage) async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the entity.""" _LOGGER.debug(f"turning {self.name} off") self._set_percentage(0) async def async_set_direction(self, direction: str) -> None: """Set the direction of the fan.""" _LOGGER.debug(f"setting direction of {self.name} to {direction}") self._attr_current_direction = direction self._update_attributes() async def async_oscillate(self, oscillating: bool) -> None: """Set oscillation.""" _LOGGER.debug(f"setting oscillate of {self.name} to {oscillating}") self._attr_oscillating = oscillating self._update_attributes() ================================================ FILE: custom_components/virtual/light.py ================================================ """ This component provides support for a virtual light. """ from __future__ import annotations import logging import pprint import voluptuous as vol from collections.abc import Callable from typing import Any import homeassistant.helpers.config_validation as cv from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_MODE, ATTR_COLOR_TEMP_KELVIN, ATTR_EFFECT, ATTR_EFFECT_LIST, ATTR_HS_COLOR, ColorMode, DOMAIN as PLATFORM_DOMAIN, LightEntity, LightEntityFeature, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import get_entity_configs from .const import * from .entity import VirtualEntity, virtual_schema _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] CONF_SUPPORT_BRIGHTNESS = "support_brightness" CONF_INITIAL_BRIGHTNESS = "initial_brightness" CONF_SUPPORT_COLOR = "support_color" CONF_INITIAL_COLOR = "initial_color" CONF_SUPPORT_COLOR_TEMP = "support_color_temp" CONF_INITIAL_COLOR_TEMP = "initial_color_temp" CONF_SUPPORT_WHITE_VALUE = "support_white_value" CONF_INITIAL_WHITE_VALUE = "initial_white_value" CONF_SUPPORT_EFFECT = "support_effect" CONF_INITIAL_EFFECT = "initial_effect" CONF_INITIAL_EFFECT_LIST = "initial_effect_list" DEFAULT_LIGHT_VALUE = "on" DEFAULT_SUPPORT_BRIGHTNESS = True DEFAULT_INITIAL_BRIGHTNESS = 255 DEFAULT_SUPPORT_COLOR = False DEFAULT_INITIAL_COLOR = [0, 100] DEFAULT_SUPPORT_COLOR_TEMP = False DEFAULT_INITIAL_COLOR_TEMP = 240 DEFAULT_SUPPORT_WHITE_VALUE = False DEFAULT_INITIAL_WHITE_VALUE = 240 DEFAULT_SUPPORT_EFFECT = False DEFAULT_INITIAL_EFFECT = "none" DEFAULT_INITIAL_EFFECT_LIST = ["rainbow", "none"] BASE_SCHEMA = virtual_schema(DEFAULT_LIGHT_VALUE, { vol.Optional(CONF_SUPPORT_BRIGHTNESS, default=DEFAULT_SUPPORT_BRIGHTNESS): cv.boolean, vol.Optional(CONF_INITIAL_BRIGHTNESS, default=DEFAULT_INITIAL_BRIGHTNESS): cv.byte, vol.Optional(CONF_SUPPORT_COLOR, default=DEFAULT_SUPPORT_COLOR): cv.boolean, vol.Optional(CONF_INITIAL_COLOR, default=DEFAULT_INITIAL_COLOR): cv.ensure_list, vol.Optional(CONF_SUPPORT_COLOR_TEMP, default=DEFAULT_SUPPORT_COLOR_TEMP): cv.boolean, vol.Optional(CONF_INITIAL_COLOR_TEMP, default=DEFAULT_INITIAL_COLOR_TEMP): cv.byte, vol.Optional(CONF_SUPPORT_WHITE_VALUE, default=DEFAULT_SUPPORT_WHITE_VALUE): cv.boolean, vol.Optional(CONF_INITIAL_WHITE_VALUE, default=DEFAULT_INITIAL_WHITE_VALUE): cv.byte, vol.Optional(CONF_SUPPORT_EFFECT, default=DEFAULT_SUPPORT_EFFECT): cv.boolean, vol.Optional(CONF_INITIAL_EFFECT, default=DEFAULT_INITIAL_EFFECT): cv.string, vol.Optional(CONF_INITIAL_EFFECT_LIST, default=DEFAULT_INITIAL_EFFECT_LIST): cv.ensure_list }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(BASE_SCHEMA) LIGHT_SCHEMA = vol.Schema(BASE_SCHEMA) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, _discovery_info: DiscoveryInfoType | None = None, ) -> None: if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") lights = [VirtualLight(config, True)] async_add_entities(lights, True) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = LIGHT_SCHEMA(entity) entities.append(VirtualLight(entity, False)) async_add_entities(entities) class VirtualLight(VirtualEntity, LightEntity): def __init__(self, config, old_style: bool): """Initialize a Virtual light.""" super().__init__(config, PLATFORM_DOMAIN, old_style) self._attr_supported_features = LightEntityFeature(0) self._attr_supported_color_modes = set() self._attr_color_mode = ColorMode.UNKNOWN if config.get(CONF_SUPPORT_COLOR_TEMP): self._attr_supported_color_modes.add(ColorMode.COLOR_TEMP) if config.get(CONF_SUPPORT_COLOR): self._attr_supported_color_modes.add(ColorMode.HS) if config.get(CONF_SUPPORT_BRIGHTNESS): if not self._attr_supported_color_modes: self._attr_supported_color_modes.add(ColorMode.BRIGHTNESS) if not self._attr_supported_color_modes: self._attr_supported_color_modes.add(ColorMode.ONOFF) if config.get(CONF_SUPPORT_EFFECT): self._attr_supported_features |= LightEntityFeature.EFFECT self._attr_effect_list = self._config.get(CONF_INITIAL_EFFECT_LIST) @property def brightness(self) -> int | None: return self._attr_brightness if self._attr_is_on else None @property def color_mode(self) -> ColorMode | None: return self._attr_color_mode if self._attr_is_on else None @property def hs_color(self) -> tuple[float, float] | None: return self._attr_hs_color if self._attr_is_on else None @property def color_temp_kelvin(self) -> int | None: return self._attr_color_temp_kelvin if self._attr_is_on else None def _create_state(self, config): super()._create_state(config) self._attr_is_on = config.get(CONF_INITIAL_VALUE).lower() == STATE_ON if ColorMode.BRIGHTNESS in self._attr_supported_color_modes: self._attr_color_mode = ColorMode.BRIGHTNESS self._attr_brightness = config.get(CONF_INITIAL_BRIGHTNESS) if ColorMode.HS in self._attr_supported_color_modes: self._attr_color_mode = ColorMode.HS self._attr_hs_color = config.get(CONF_INITIAL_COLOR) self._attr_brightness = config.get(CONF_INITIAL_BRIGHTNESS) if ColorMode.COLOR_TEMP in self._attr_supported_color_modes: self._attr_color_mode = ColorMode.COLOR_TEMP self._attr_color_temp_kelvin = config.get(CONF_INITIAL_COLOR_TEMP) self._attr_brightness = config.get(CONF_INITIAL_BRIGHTNESS) if self._attr_supported_features & LightEntityFeature.EFFECT: self._attr_effect = config.get(CONF_INITIAL_EFFECT) def _restore_state(self, state, config): super()._restore_state(state, config) self._attr_is_on = state.state.lower() == STATE_ON self._attr_color_mode = state.attributes.get(ATTR_COLOR_MODE, ColorMode.ONOFF) if self._attr_color_mode == ColorMode.BRIGHTNESS: self._attr_brightness = state.attributes.get(ATTR_BRIGHTNESS, config.get(CONF_INITIAL_BRIGHTNESS)) if self._attr_color_mode == ColorMode.HS: self._attr_hs_color = state.attributes.get(ATTR_HS_COLOR, config.get(CONF_INITIAL_COLOR)) self._attr_brightness = state.attributes.get(ATTR_BRIGHTNESS, config.get(CONF_INITIAL_BRIGHTNESS)) if self._attr_color_mode == ColorMode.COLOR_TEMP: self._attr_color_temp_kelvin = state.attributes.get(ATTR_COLOR_TEMP_KELVIN, config.get(CONF_INITIAL_COLOR_TEMP)) self._attr_brightness = state.attributes.get(ATTR_BRIGHTNESS, config.get(CONF_INITIAL_BRIGHTNESS)) if self._attr_supported_features & LightEntityFeature.EFFECT: self._attr_effect = state.attributes.get(ATTR_EFFECT, config.get(CONF_INITIAL_EFFECT)) def _update_attributes(self): """Return the state attributes.""" super()._update_attributes() self._attr_extra_state_attributes.update({ name: value for name, value in ( (ATTR_BRIGHTNESS, self.brightness), (ATTR_COLOR_MODE, self.color_mode), (ATTR_COLOR_TEMP_KELVIN, self.color_temp_kelvin), (ATTR_EFFECT, self._attr_effect), (ATTR_EFFECT_LIST, self._attr_effect_list), (ATTR_HS_COLOR, self.hs_color), ) if value is not None }) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the light on.""" _LOGGER.debug(f"turning {self.name} on {pprint.pformat(kwargs)}") hs_color = kwargs.get(ATTR_HS_COLOR, None) if hs_color is not None and ColorMode.HS in self._attr_supported_color_modes: self._attr_color_mode = ColorMode.HS self._attr_hs_color = hs_color self._attr_color_temp_kelvin = None ct = kwargs.get(ATTR_COLOR_TEMP_KELVIN, None) if ct is not None and ColorMode.COLOR_TEMP in self._attr_supported_color_modes: self._attr_color_mode = ColorMode.COLOR_TEMP self._attr_color_temp_kelvin = ct self._attr_hs_color = None brightness = kwargs.get(ATTR_BRIGHTNESS, None) if brightness is not None: if self._attr_color_mode == ColorMode.UNKNOWN: self._attr_color_mode = ColorMode.BRIGHTNESS self._attr_brightness = brightness if self._attr_color_mode == ColorMode.UNKNOWN: self._attr_color_mode = ColorMode.ONOFF effect = kwargs.get(ATTR_EFFECT, None) if effect is not None and self._attr_supported_features & LightEntityFeature.EFFECT: self._attr_effect = effect self._attr_is_on = True self._update_attributes() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the light off.""" _LOGGER.debug(f"turning {self.name} off {pprint.pformat(kwargs)}") self._attr_is_on = False self._update_attributes() ================================================ FILE: custom_components/virtual/lock.py ================================================ """ This component provides support for a virtual lock. """ import logging import random import voluptuous as vol from collections.abc import Callable from datetime import timedelta from typing import Any import homeassistant.helpers.config_validation as cv from homeassistant.components.lock import ( DOMAIN as PLATFORM_DOMAIN, LockEntity, LockState, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.event import async_call_later from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import get_entity_configs from .const import * from .entity import VirtualEntity, virtual_schema _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] CONF_CHANGE_TIME = "locking_time" CONF_TEST_JAMMING = "jamming_test" DEFAULT_LOCK_VALUE = "locked" DEFAULT_CHANGE_TIME = timedelta(seconds=0) DEFAULT_TEST_JAMMING = 0 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(virtual_schema(DEFAULT_LOCK_VALUE, { vol.Optional(CONF_CHANGE_TIME, default=DEFAULT_CHANGE_TIME): vol.All(cv.time_period, cv.positive_timedelta), vol.Optional(CONF_TEST_JAMMING, default=DEFAULT_TEST_JAMMING): cv.positive_int, })) LOCK_SCHEMA = vol.Schema(virtual_schema(DEFAULT_LOCK_VALUE, { vol.Optional(CONF_CHANGE_TIME, default=DEFAULT_CHANGE_TIME): vol.All(cv.time_period, cv.positive_timedelta), vol.Optional(CONF_TEST_JAMMING, default=DEFAULT_TEST_JAMMING): cv.positive_int, })) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, _discovery_info: DiscoveryInfoType | None = None, ) -> None: if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") locks = [VirtualLock(hass, config, True)] async_add_entities(locks, True) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = LOCK_SCHEMA(entity) entities.append(VirtualLock(hass, entity, False)) async_add_entities(entities) class VirtualLock(VirtualEntity, LockEntity): """Representation of a Virtual lock.""" def __init__(self, hass, config, old_style: bool): """Initialize the Virtual lock device.""" super().__init__(config, PLATFORM_DOMAIN, old_style) self._hass = hass self._change_time = config.get(CONF_CHANGE_TIME) self._test_jamming = config.get(CONF_TEST_JAMMING) _LOGGER.info('VirtualLock: {} created'.format(self.name)) def _create_state(self, config): super()._create_state(config) self._attr_is_locked = config.get(CONF_INITIAL_VALUE).lower() == LockState.LOCKED def _restore_state(self, state, config): super()._restore_state(state, config) self._attr_is_locked = state.state == LockState.LOCKED def _lock(self) -> None: if self._test_jamming == 0 or random.randint(0, self._test_jamming) > 0: _LOGGER.debug(f"locked {self.name}") self._attr_is_locked = True self._attr_is_locking = False self._attr_is_unlocking = False self._attr_is_jammed = False else: self._jam() def _locking(self) -> None: _LOGGER.debug(f"locking {self.name}") self._attr_is_locked = False self._attr_is_locking = True self._attr_is_unlocking = False self._attr_is_jammed = False def _unlock(self) -> None: _LOGGER.debug(f"unlocked {self.name}") self._attr_is_locked = False self._attr_is_locking = False self._attr_is_unlocking = False self._attr_is_jammed = False def _unlocking(self) -> None: _LOGGER.debug(f"unlocking {self.name}") self._attr_is_locked = False self._attr_is_locking = False self._attr_is_unlocking = True self._attr_is_jammed = False def _jam(self) -> None: _LOGGER.debug(f"jamming {self.name}") self._attr_is_locked = False self._attr_is_jammed = True @callback async def _finish_operation(self, _point_in_time) -> None: if self.is_locking: self._lock() if self.is_unlocking: self._unlock() self.async_schedule_update_ha_state() def _start_operation(self): async_call_later(self.hass, self._change_time, self._finish_operation) async def async_lock(self, **kwargs: Any) -> None: if self._change_time == DEFAULT_CHANGE_TIME: self._lock() else: self._locking() self._start_operation() async def async_unlock(self, **kwargs: Any) -> None: if self._change_time == DEFAULT_CHANGE_TIME: self._unlock() else: self._unlocking() self._start_operation() async def async_open(self, **kwargs: Any) -> None: _LOGGER.debug(f"opening {self.name}") self.unlock() ================================================ FILE: custom_components/virtual/manifest.json ================================================ { "domain": "virtual", "name": "Virtual Components", "codeowners": [ "@twrecked" ], "config_flow": true, "documentation": "https://github.com/twrecked/hass-virtual/blob/master/README.md", "iot_class": "local_push", "issue_tracker": "https://github.com/twrecked/hass-virtual/issues", "version": "0.9.4" } ================================================ FILE: custom_components/virtual/number.py ================================================ """ This component provides support for a virtual number. """ import logging import voluptuous as vol from collections.abc import Callable import homeassistant.helpers.config_validation as cv from homeassistant.components.number import ( ATTR_MAX, ATTR_MIN, DOMAIN as PLATFORM_DOMAIN, NumberDeviceClass ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_DEVICE_CLASS, ATTR_UNIT_OF_MEASUREMENT, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_MILLION, CONF_UNIT_OF_MEASUREMENT, LIGHT_LUX, PERCENTAGE, SIGNAL_STRENGTH_DECIBELS, UnitOfApparentPower, UnitOfElectricCurrent, UnitOfElectricPotential, UnitOfEnergy, UnitOfFrequency, UnitOfPower, UnitOfPressure, UnitOfReactivePower, UnitOfVolume, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import get_entity_from_domain, get_entity_configs from .const import * from .entity import VirtualEntity, virtual_schema _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] DEFAULT_NUMBER_VALUE = "0" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(virtual_schema(DEFAULT_NUMBER_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Required(CONF_MIN): vol.Coerce(float), vol.Required(CONF_MAX): vol.Coerce(float), vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=""): cv.string, })) NUMBER_SCHEMA = vol.Schema(virtual_schema(DEFAULT_NUMBER_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Required(CONF_MIN): vol.Coerce(float), vol.Required(CONF_MAX): vol.Coerce(float), vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=""): cv.string, })) UNITS_OF_MEASUREMENT = { NumberDeviceClass.APPARENT_POWER: UnitOfApparentPower.VOLT_AMPERE, # apparent power (VA) NumberDeviceClass.BATTERY: PERCENTAGE, # % of battery that is left NumberDeviceClass.CO: CONCENTRATION_PARTS_PER_MILLION, # ppm of CO concentration NumberDeviceClass.CO2: CONCENTRATION_PARTS_PER_MILLION, # ppm of CO2 concentration NumberDeviceClass.HUMIDITY: PERCENTAGE, # % of humidity in the air NumberDeviceClass.ILLUMINANCE: LIGHT_LUX, # current light level (lx/lm) NumberDeviceClass.NITROGEN_DIOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen dioxide NumberDeviceClass.NITROGEN_MONOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen monoxide NumberDeviceClass.NITROUS_OXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen oxide NumberDeviceClass.OZONE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of ozone NumberDeviceClass.PM1: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM1 NumberDeviceClass.PM10: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM10 NumberDeviceClass.PM25: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM2.5 NumberDeviceClass.SIGNAL_STRENGTH: SIGNAL_STRENGTH_DECIBELS, # signal strength (dB/dBm) NumberDeviceClass.SULPHUR_DIOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of sulphur dioxide NumberDeviceClass.TEMPERATURE: "C", # temperature (C/F) NumberDeviceClass.PRESSURE: UnitOfPressure.HPA, # pressure (hPa/mbar) NumberDeviceClass.POWER: UnitOfPower.KILO_WATT, # power (W/kW) NumberDeviceClass.CURRENT: UnitOfElectricCurrent.AMPERE, # current (A) NumberDeviceClass.ENERGY: UnitOfEnergy.KILO_WATT_HOUR, # energy (Wh/kWh/MWh) NumberDeviceClass.FREQUENCY: UnitOfFrequency.GIGAHERTZ, # energy (Hz/kHz/MHz/GHz) NumberDeviceClass.POWER_FACTOR: PERCENTAGE, # power factor (no unit, min: -1.0, max: 1.0) NumberDeviceClass.REACTIVE_POWER: UnitOfReactivePower.VOLT_AMPERE_REACTIVE, # reactive power (var) NumberDeviceClass.VOLATILE_ORGANIC_COMPOUNDS: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of vocs NumberDeviceClass.VOLTAGE: UnitOfElectricPotential.VOLT, # voltage (V) NumberDeviceClass.GAS: UnitOfVolume.CUBIC_METERS, # gas (m³) } async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, _discovery_info: DiscoveryInfoType | None = None, ) -> None: if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") sensors = [VirtualNumber(config, True)] async_add_entities(sensors, True) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = NUMBER_SCHEMA(entity) entities.append(VirtualNumber(entity, False)) async_add_entities(entities) class VirtualNumber(VirtualEntity, Entity): """An implementation of a Virtual Number.""" def __init__(self, config, old_style: bool): """Initialize an Virtual Number.""" super().__init__(config, PLATFORM_DOMAIN, old_style) self._attr_device_class = config.get(CONF_CLASS) self.min_value = config.get(CONF_MIN) self.max_value = config.get(CONF_MAX) # Set unit of measurement self._attr_unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) if not self._attr_unit_of_measurement and self._attr_device_class in UNITS_OF_MEASUREMENT.keys(): self._attr_unit_of_measurement = UNITS_OF_MEASUREMENT[self._attr_device_class] _LOGGER.info(f"VirtualSensor: {self.name} created") def convert_to_native_value(self, value: float) -> float: return value @property def native_min_value(self): return self.min_value @property def native_max_value(self): return self.max_value def _create_state(self, config): super()._create_state(config) self._attr_state = config.get(CONF_INITIAL_VALUE) def _restore_state(self, state, config): super()._restore_state(state, config) self._attr_state = state.state def _update_attributes(self): super()._update_attributes() self._attr_extra_state_attributes.update({ name: value for name, value in ( (ATTR_DEVICE_CLASS, self._attr_device_class), (ATTR_UNIT_OF_MEASUREMENT, self._attr_unit_of_measurement), (ATTR_MIN, self.min_value), (ATTR_MAX, self.max_value) ) if value is not None }) async def async_set_native_value(self, value: float) -> None: """Set new value.""" await self.hass.async_add_executor_job(self.set, value) def set(self, value) -> None: _LOGGER.debug(f"set {self.name} to {value}") self._attr_state = value #self.async_schedule_update_ha_state() ================================================ FILE: custom_components/virtual/sensor.py ================================================ """ This component provides support for a virtual sensor. """ import logging import voluptuous as vol from collections.abc import Callable import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import ( DOMAIN as PLATFORM_DOMAIN, SensorDeviceClass ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_DEVICE_CLASS, ATTR_UNIT_OF_MEASUREMENT, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_MILLION, CONF_UNIT_OF_MEASUREMENT, LIGHT_LUX, PERCENTAGE, SIGNAL_STRENGTH_DECIBELS, UnitOfApparentPower, UnitOfElectricCurrent, UnitOfElectricPotential, UnitOfEnergy, UnitOfFrequency, UnitOfPower, UnitOfPressure, UnitOfReactivePower, UnitOfVolume, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import get_entity_from_domain, get_entity_configs from .const import * from .entity import VirtualEntity, virtual_schema _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] DEFAULT_SENSOR_VALUE = "0" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(virtual_schema(DEFAULT_SENSOR_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=""): cv.string, })) SENSOR_SCHEMA = vol.Schema(virtual_schema(DEFAULT_SENSOR_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=""): cv.string, })) SERVICE_SET = "set" SERVICE_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.comp_entity_ids, vol.Required(ATTR_VALUE): cv.string, }) UNITS_OF_MEASUREMENT = { SensorDeviceClass.APPARENT_POWER: UnitOfApparentPower.VOLT_AMPERE, # apparent power (VA) SensorDeviceClass.BATTERY: PERCENTAGE, # % of battery that is left SensorDeviceClass.CO: CONCENTRATION_PARTS_PER_MILLION, # ppm of CO concentration SensorDeviceClass.CO2: CONCENTRATION_PARTS_PER_MILLION, # ppm of CO2 concentration SensorDeviceClass.HUMIDITY: PERCENTAGE, # % of humidity in the air SensorDeviceClass.ILLUMINANCE: LIGHT_LUX, # current light level (lx/lm) SensorDeviceClass.NITROGEN_DIOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen dioxide SensorDeviceClass.NITROGEN_MONOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen monoxide SensorDeviceClass.NITROUS_OXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of nitrogen oxide SensorDeviceClass.OZONE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of ozone SensorDeviceClass.PM1: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM1 SensorDeviceClass.PM10: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM10 SensorDeviceClass.PM25: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of PM2.5 SensorDeviceClass.SIGNAL_STRENGTH: SIGNAL_STRENGTH_DECIBELS, # signal strength (dB/dBm) SensorDeviceClass.SULPHUR_DIOXIDE: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of sulphur dioxide SensorDeviceClass.TEMPERATURE: "C", # temperature (C/F) SensorDeviceClass.PRESSURE: UnitOfPressure.HPA, # pressure (hPa/mbar) SensorDeviceClass.POWER: UnitOfPower.KILO_WATT, # power (W/kW) SensorDeviceClass.CURRENT: UnitOfElectricCurrent.AMPERE, # current (A) SensorDeviceClass.ENERGY: UnitOfEnergy.KILO_WATT_HOUR, # energy (Wh/kWh/MWh) SensorDeviceClass.FREQUENCY: UnitOfFrequency.GIGAHERTZ, # energy (Hz/kHz/MHz/GHz) SensorDeviceClass.POWER_FACTOR: PERCENTAGE, # power factor (no unit, min: -1.0, max: 1.0) SensorDeviceClass.REACTIVE_POWER: UnitOfReactivePower.VOLT_AMPERE_REACTIVE, # reactive power (var) SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, # µg/m³ of vocs SensorDeviceClass.VOLTAGE: UnitOfElectricPotential.VOLT, # voltage (V) SensorDeviceClass.GAS: UnitOfVolume.CUBIC_METERS, # gas (m³) } def setup_services(hass: HomeAssistant) -> None: async def async_virtual_service(call): """Call virtual service handler.""" _LOGGER.debug(f"{call.service} service called") await async_virtual_set_service(hass, call) # Build up services... if not hasattr(hass.data[COMPONENT_SERVICES], PLATFORM_DOMAIN): _LOGGER.debug("installing handlers") hass.data[COMPONENT_SERVICES][PLATFORM_DOMAIN] = "installed" hass.services.async_register( COMPONENT_DOMAIN, SERVICE_SET, async_virtual_service, schema=SERVICE_SCHEMA, ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, _discovery_info: DiscoveryInfoType | None = None, ) -> None: if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") sensors = [VirtualSensor(config, True)] async_add_entities(sensors, True) setup_services(hass) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = SENSOR_SCHEMA(entity) entities.append(VirtualSensor(entity, False)) async_add_entities(entities) setup_services(hass) class VirtualSensor(VirtualEntity, Entity): """An implementation of a Virtual Sensor.""" def __init__(self, config, old_style: bool): """Initialize an Virtual Sensor.""" super().__init__(config, PLATFORM_DOMAIN, old_style) self._attr_device_class = config.get(CONF_CLASS) # Set unit of measurement self._attr_unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) if not self._attr_unit_of_measurement and self._attr_device_class in UNITS_OF_MEASUREMENT.keys(): self._attr_unit_of_measurement = UNITS_OF_MEASUREMENT[self._attr_device_class] _LOGGER.info(f"VirtualSensor: {self.name} created") def _create_state(self, config): super()._create_state(config) self._attr_state = config.get(CONF_INITIAL_VALUE) def _restore_state(self, state, config): super()._restore_state(state, config) self._attr_state = state.state def _update_attributes(self): super()._update_attributes() self._attr_extra_state_attributes.update({ name: value for name, value in ( (ATTR_DEVICE_CLASS, self._attr_device_class), (ATTR_UNIT_OF_MEASUREMENT, self._attr_unit_of_measurement), ) if value is not None }) def set(self, value) -> None: _LOGGER.debug(f"set {self.name} to {value}") self._attr_state = value self.async_schedule_update_ha_state() async def async_virtual_set_service(hass, call): for entity_id in call.data[ATTR_ENTITY_ID]: value = call.data[ATTR_VALUE] _LOGGER.debug(f"setting {entity_id} to {value})") get_entity_from_domain(hass, PLATFORM_DOMAIN, entity_id).set(value) ================================================ FILE: custom_components/virtual/services.yaml ================================================ # Describes the format for available virtual services turn_on: name: Turn On description: Turn on a binary sensor. target: entity: integration: virtual domain: binary_sensor turn_off: name: Turn Off description: Turn off a binary sensor. target: entity: integration: virtual domain: binary_sensor toggle: name: Toggle description: Toggle a binary sensor. target: entity: integration: virtual domain: binary_sensor set: name: Set description: Set the value of a sensor. target: entity: integration: virtual domain: sensor fields: value: name: Value description: Value to set state to. required: true example: '10' selector: text: set_available: name: Set Availability description: Set availability of an entity. target: entity: integration: virtual fields: value: name: Value description: Is the entity available. example: false required: true selector: boolean: move: name: Move description: Move a device tracker to a new location. target: entity: integration: virtual domain: device_tracker fields: location: name: Named Location description: Where to move the device tracker to. example: 'home' selector: text: gps: name: GPS Location description: Which coordinates to move the device tracker to. example: '{"latitude": -27.9699373, "longitude": 153.4081865}' selector: location: radius: false gps_accuracy: selector: number: min: 0 mode: box unit_of_measurement: "m" ================================================ FILE: custom_components/virtual/switch.py ================================================ """ This component provides support for a virtual switch. """ import logging import voluptuous as vol from collections.abc import Callable from typing import Any import homeassistant.helpers.config_validation as cv from homeassistant.components.switch import ( DOMAIN as PLATFORM_DOMAIN, SwitchEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_DEVICE_CLASS, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import (PLATFORM_SCHEMA) from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import get_entity_configs from .const import * from .entity import VirtualEntity, virtual_schema _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] DEFAULT_SWITCH_VALUE = "off" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(virtual_schema(DEFAULT_SWITCH_VALUE, { vol.Optional(CONF_CLASS): cv.string, })) SWITCH_SCHEMA = vol.Schema(virtual_schema(DEFAULT_SWITCH_VALUE, { vol.Optional(CONF_CLASS): cv.string, })) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, _discovery_info: DiscoveryInfoType | None = None, ) -> None: if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") switches = [VirtualSwitch(config, True)] async_add_entities(switches, True) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = SWITCH_SCHEMA(entity) entities.append(VirtualSwitch(entity, False)) async_add_entities(entities) class VirtualSwitch(VirtualEntity, SwitchEntity): """Representation of a Virtual switch.""" def __init__(self, config, old_style : bool): """Initialize the Virtual switch device.""" super().__init__(config, PLATFORM_DOMAIN, old_style) self._attr_device_class = config.get(CONF_CLASS) _LOGGER.info(f"VirtualSwitch: {self.name} created") def _create_state(self, config): super()._create_state(config) self._attr_is_on = config.get(CONF_INITIAL_VALUE).lower() == STATE_ON def _restore_state(self, state, config): super()._restore_state(state, config) self._attr_is_on = state.state.lower() == STATE_ON def _update_attributes(self): super()._update_attributes() self._attr_extra_state_attributes.update({ name: value for name, value in ( (ATTR_DEVICE_CLASS, self._attr_device_class), ) if value is not None }) async def async_turn_on(self, **kwargs: Any) -> None: _LOGGER.debug(f"turning {self.name} on") self._attr_is_on = True async def async_turn_off(self, **kwargs: Any) -> None: _LOGGER.debug(f"turning {self.name} off") self._attr_is_on = False ================================================ FILE: custom_components/virtual/translations/cz.json ================================================ { "title": "Virtuální Zařízení", "config": { "error": { "group_name_used": "Tento název skupiny je již použit, zkuste jiný.", "file_name_used": "Tento název souboru je již použit, zkuste jiný." }, "step": { "user": { "title": "Virtuální Databáze", "description": "Zadejte název skupiny a cestu k souboru obsahujícímu virtuální zařízení. Pokud nexistuje, vytvoří se nový.", "data": { "group_name": "Skupina", "file_name": "Soubor" } } } }, "services": { "turn_on": { "name": "Zapnout", "description": "Zapnout binární senzor.", "fields": { "entity_id": { "name": "Id Entity", "description": "Názvy entit, které se mají nastavit" } } }, "turn_off": { "name": "Vypnout", "description": "Vypnout binární senzor.", "fields": { "entity_id": { "name": "Entity Id", "description": "Názvy entit, které se mají nastavit" } } }, "toggle": { "name": "Přepnout", "description": "Přepnout binární senzor.", "fields": { "entity_id": { "name": "Id Entity", "description": "Názvy entit, které se mají nastavit" } } }, "set": { "name": "Nastavit", "description": "Nastavit hodnotu senzoru.", "fields": { "entity_id": { "name": "Id Entity", "description": "Názvy entit, které se mají nastavit" }, "value": { "name": "Hodnota", "description": "Hodnota, na kterou se má nastavit stav senzoru." } } }, "set_available": { "name": "Nastavit dostupnost.", "description": "Nastavit dostupnost entity.", "fields": { "value": { "name": "Hodnota", "description": "Je entita dostupná.." } } }, "move": { "name": "Přesunout", "description": "Přesune sledovač zařízení na novou pozici.", "fields": { "location": { "name": "Pozice", "description": "Kam přesunout sledovač zařízení." } } } } } ================================================ FILE: custom_components/virtual/translations/en.json ================================================ { "title": "Virtual Devices", "config": { "error": { "group_name_used": "That group name is already in use, try another.", "file_name_used": "That file name is already in use, try another." }, "step": { "user": { "title": "Virtual Database", "description": "Enter the group name and path to a file containing the virtual devices. If it does not exist an empty one will be created.", "data": { "group_name": "Group", "file_name": "File" } } } }, "services": { "turn_on": { "name": "Turn On", "description": "Turn on a binary sensor.", "fields": { "entity_id": { "name": "Entity Id", "description": "Name(s) of entities to set" } } }, "turn_off": { "name": "Turn Off", "description": "Turn off a binary sensor.", "fields": { "entity_id": { "name": "Entity Id", "description": "Name(s) of entities to set" } } }, "toggle": { "name": "Toggle", "description": "Toggle a binary sensor.", "fields": { "entity_id": { "name": "Entity Id", "description": "Name(s) of entities to set" } } }, "set": { "name": "Set", "description": "Set the value of a sensor.", "fields": { "entity_id": { "name": "Entity Id", "description": "Name(s) of entities to set" }, "value": { "name": "Value", "description": "Value to set state to." } } }, "set_available": { "name": "Set Availability", "description": "Set availability of an entity.", "fields": { "value": { "name": "Value", "description": "Is the entity available.." } } }, "move": { "name": "Move", "description": "Move a device tracker to a new location.", "fields": { "location": { "name": "Location", "description": "A named location to move the device tracker to." }, "gps": { "name": "GPS", "description": "Which coordinates to move the device tracker to." }, "gps_accuracy": { "name": "GPS accuracy", "description": "Accuracy of the GPS coordinates." } } } } } ================================================ FILE: custom_components/virtual/translations/sk.json ================================================ { "title": "Virtuálne zariadenia", "config": { "error": { "group_name_used": "Tento názov skupiny sa už používa, skúste iný.", "file_name_used": "Tento názov súboru sa už používa, skúste iný." }, "step": { "user": { "title": "Virtuálna databáza", "description": "Zadajte názov skupiny a cestu k súboru obsahujúcemu virtuálne zariadenia. Ak neexistuje, vytvorí sa prázdny.", "data": { "group_name": "Skupina", "file_name": "Súbor" } } } }, "services": { "turn_on": { "name": "Zapnúť", "description": "Zapnite binárny senzor.", "fields": { "entity_id": { "name": "Id entity", "description": "Názvy entít, ktoré sa majú nastaviť" } } }, "turn_off": { "name": "Vypnúť", "description": "Vypnite binárny senzor.", "fields": { "entity_id": { "name": "Id entity", "description": "Názvy entít, ktoré sa majú nastaviť" } } }, "toggle": { "name": "Prepínač", "description": "Prepnúť binárny senzor.", "fields": { "entity_id": { "name": "Id entity", "description": "Názvy entít, ktoré sa majú nastaviť" } } }, "set": { "name": "Nastaviť", "description": "Nastavte hodnotu snímača.", "fields": { "entity_id": { "name": "Id entity", "description": "Názvy entít, ktoré sa majú nastaviť" }, "value": { "name": "Hodnota", "description": "Hodnota, na ktorú sa má stav nastaviť." } } }, "set_available": { "name": "Nastaviť dostupnosť", "description": "Nastavte dostupnosť entity.", "fields": { "value": { "name": "Hodnota", "description": "Je subjekt dostupný.." } } }, "move": { "name": "Presunúť", "description": "Presuňte sledovač zariadenia na nové miesto.", "fields": { "location": { "name": "Umiestnenie", "description": "Kam presunúť sledovač zariadení." }, "gps": { "name": "GPS", "description": "Na ktoré súradnice presunúť sledovač zariadenia." }, "gps_accuracy": { "name": "GPS presnosť", "description": "Presnosť súradníc GPS." } } } } } ================================================ FILE: custom_components/virtual/valve.py ================================================ """ This component provides support for a virtual valve. """ import logging import voluptuous as vol from collections.abc import Callable import homeassistant.helpers.config_validation as cv from homeassistant.components.valve import ( ValveEntity, ValveEntityFeature, DOMAIN as PLATFORM_DOMAIN ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import get_entity_configs from .const import * from .entity import ( VirtualOpenableEntity, virtual_schema, positive_tick, ) _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [COMPONENT_DOMAIN] DEFAULT_VALVE_VALUE = "open" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(virtual_schema(DEFAULT_VALVE_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Optional(CONF_OPEN_CLOSE_DURATION, default=10): cv.positive_int, vol.Optional(CONF_OPEN_CLOSE_TICK, default=1): positive_tick, })) VALVE_SCHEMA = vol.Schema(virtual_schema(DEFAULT_VALVE_VALUE, { vol.Optional(CONF_CLASS): cv.string, vol.Optional(CONF_OPEN_CLOSE_DURATION, default=10): cv.positive_int, vol.Optional(CONF_OPEN_CLOSE_TICK, default=1): positive_tick, })) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, _discovery_info: DiscoveryInfoType | None = None, ) -> None: if hass.data[COMPONENT_CONFIG].get(CONF_YAML_CONFIG, False): _LOGGER.debug("setting up old config...") sensors = [VirtualValve(config, True)] async_add_entities(sensors, True) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> None: _LOGGER.debug("setting up the entries...") entities = [] for entity in get_entity_configs(hass, entry.data[ATTR_GROUP_NAME], PLATFORM_DOMAIN): entity = VALVE_SCHEMA(entity) entities.append(VirtualValve(entity, False)) async_add_entities(entities) class VirtualValve(VirtualOpenableEntity, ValveEntity): def __init__(self, config, old_style: bool): """Initialize the Virtual valve device.""" super().__init__(config, PLATFORM_DOMAIN, old_style) self._attr_supported_features = ValveEntityFeature( ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE | ValveEntityFeature.STOP | ValveEntityFeature.SET_POSITION ) self._attr_reports_position = True _LOGGER.info(f"VirtualValve: {self.name} created") @property def current_valve_position(self) -> int | None: return round(self._current_position) async def async_open_valve(self) -> None: _LOGGER.info(f"opening {self.name}") self._set_position(100) async def async_close_valve(self) -> None: _LOGGER.info(f"closing {self.name}") self._set_position(0) async def async_stop_valve(self) -> None: _LOGGER.info(f"stopping {self.name}") self._stop() async def async_set_valve_position(self, position: int) -> None: _LOGGER.info(f"setting {self.name} position {position}") self._set_position(position) ================================================ FILE: hacs.json ================================================ { "name": "Virtual Components" } ================================================ FILE: info.md ================================================ ### Virtual Components for Home Assistant Virtual components for testing Home Assistant systems. ## Version 0.8 ### **Breaking Changes** I've added persistent support to `binary_sensor`, `fan`, `light`, `lock`, `sensor`, `switch` and `device_tracker`. The persistent saving of state is turned *on* by default. If you do not want this set `persistent: False` in the entity configuration. ## Features It provides: * Virtual binary sensors * Virtual device trackers * Virtual fans * Virtual lights * Virtual locks * Virtual senors * Virtual switches ## Documentation See [here](https://github.com/twrecked/hass-virtual/blob/master/README.md) for full documentation. ================================================ FILE: install ================================================ #!/bin/bash # if [[ "${1}" == "go" ]]; then ECHO= shift else ECHO=echo fi DEST="${1}" if [[ -z "${DEST}" ]]; then echo "*** please supply the home-assistant /config directory" exit 1 fi if [[ ! -d "${DEST}" ]]; then echo "*** please make sure the destination directory exists" exit 1 fi if [[ -n "${ECHO}" ]]; then echo "**** would run the following commands, use './install go $1' to do the work" fi ${ECHO} mkdir -p "${DEST}/custom_components" if [[ -n $(command -v fd) ]]; then fd -e py -e json -e yaml . custom_components --exec ${ECHO} cp -vf --parents {} "${DEST}" ; else ${ECHO} cp -afv custom_components/virtual "${DEST}/custom_components" fi echo -- finished at "$(date '+%A at %H:%M:%S')"