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