├── .gitignore ├── LICENSE ├── README.md ├── demo3.py ├── examples ├── door.py ├── switch.py ├── thermostat-poll.py └── thermostat.py └── vivint.py /.gitignore: -------------------------------------------------------------------------------- 1 | scratch/ 2 | __pycache__ 3 | *pyc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vivint.py: Reverse Engineered Python Access to Vivint's Cloud API 2 | 3 | This is a simple Python file that can be imported into projects, and provides access to some of Vivint's cloud API through a Python object model. 4 | 5 | Feature support right now is minimal and limited to what I personally need, but PRs are welcome, as well as issues that request new features. 6 | 7 | In terms of overall code quality, this is very proof-of-concept. 8 | 9 | ## Features currently in place 10 | 11 | ### Authentication 12 | 13 | Authentication is handled in one of two ways: 14 | 15 | - By taking in a username and password, and obtaining an OpenID bearer token 16 | - By taking an existing valid oauth state and oidc nonce pair, and requesting a new bearer token 17 | 18 | As long as the process is running and state is maintained (think as a systemd process, script, long-lived container, or lambda function that doesn't 'time out'), the bearer token is automatically refreshed regularly, or when it expires (if regular refreshes were not successful). 19 | 20 | **NOTE:** The tokens obtained from an email login are valid for refresh for up to 6 hours. Beyond that you will need to re-authenticate. This occurs automatically if the session was created with a username and email, in which case a fresh login will be attempted if a token refresh fails. 21 | 22 | ### Thermostats 23 | 24 | Thermostat functionality was the main driver for this project, as currently you cannot have both the Smart Assistant control the thermostat, as well as a schedule for temperature setpoints. Rules can control the fan (on/off/toggle) based on time of day and duration, but not temperature. 25 | 26 | - The ability to set the mode of operation for heating/cooling as well as the fan mode of operation. 27 | - The ability to set the setpoint for the thermostat. This includes setting the cooling and heating setpoints separately. 28 | 29 | Note that temperature units are in whatever your account/panel are set to. 30 | 31 | ### Not yet implemented devices 32 | 33 | Any unimplemented device types are optionally just exposed as base JSON documents for you to poke at. In general you can PUT to the API endpoint and set any of the values in the device body to set it. 34 | 35 | ### PubNub Updates (NOT IMPLEMENTED) 36 | 37 | The actual Vivint web interface and probably the mobile applications use pubnub to receive updates on the status of the system. They use long HTTP polling (determined by the remote endpoint, so ensuring the client timeout is long) between a few seconds and several minutes, and receive a complicated body back. 38 | 39 | Because this isn't updated, to get updates on the state of system elements, you need to run the panel object's `update_devices()` function which will update all devices attached or generated from that panel. Because of the likely distributed nature of the server side, it can take a few seconds before either the systems API endpoint, or the PubNub notification, reflects any state changes you've made. 40 | 41 | An example PubNub message is included for information, resulting from changing the thermostat state from `sleep` to `home`. 42 | 43 | ```json 44 | GET @ "https://ps18.pubnub.com/subscribe/sub-c-638b7dcf-84f3-442b-8eca-f3efa4bd057c/PlatformChannel" 45 | 46 | [ 47 | [ // If the 48 | { 49 | "_id": 42138025481253, 50 | "da": { 51 | "csce": "home", 52 | "plctx": { 53 | "ctxd": null, 54 | "ctxid": "edf467e797842913f97b11bb", 55 | "ctxt": 10, 56 | "mid": "585c79932593243672c5d8a8", 57 | "ts": "2018-05-27T22:23:05.049000" 58 | }, 59 | "proph.csce": [ // Note the .notation to index into a document in the object it cares about 60 | { 61 | "val": "sleep" 62 | }, 63 | { 64 | "val": "home" 65 | } 66 | ] 67 | }, 68 | "dseq": 4795401, 69 | "op": "u", 70 | "panid": 42138025481253, 71 | "t": "account_system" 72 | } 73 | ], 74 | "15274606422065826" // Timestamp in 100ns units 75 | ] 76 | ``` 77 | 78 | ## General Notes 79 | 80 | It appears that timestamps are in Unix epoch time, but some are in the units of us, or 100ns, ns, or other funky units. Just use caution. 81 | 82 | ## Reverse Engineering Notes 83 | 84 | ### Authentication 85 | 86 | Vivint uses, as far as I can tell, PingFederate to handle their SSO, and this includes the web login. There's some illuminating commentary on [this support thread](https://support.pingidentity.com/Topic-Detail/PF-Cookie) that references the "HTML Form adapter", which is the behaviour we see. This is relevant as the PF token is a PingFederate token, which explains a fair bit. 87 | -------------------------------------------------------------------------------- /demo3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Demonstrats a long-lived polling thread that checks the state of all thermostats and writes them to stdout. 4 | """ 5 | 6 | from __future__ import print_function 7 | import os 8 | import sys 9 | import json 10 | import time 11 | import argparse 12 | 13 | import vivint 14 | 15 | running = True 16 | 17 | state_change_time = "18:04:00" 18 | last_state_change = {"date": ""} 19 | 20 | 21 | class StringJsonEncoder(json.JSONEncoder): 22 | def default(self, obj): # pylint: disable=E0202 23 | try: 24 | return json.JSONEncoder.default(self, obj) 25 | except: 26 | try: 27 | return str(obj) 28 | except: 29 | return repr(obj) 30 | 31 | 32 | def __log(s, v): 33 | if v: 34 | print(s, file=sys.stderr) 35 | 36 | 37 | def periodic_update(interval, out_file, verbose): 38 | if out_file is None: 39 | fp = sys.stdout 40 | else: 41 | # Open the file for appending 42 | fp = open(out_file, "a") 43 | 44 | __log("Establishing session", verbose) 45 | session = vivint.VivintCloudSession(os.environ["USERNAME"], 46 | os.environ["PASSWORD"]) 47 | __log("Listing panels", verbose) 48 | panels = session.get_panels() 49 | while running: 50 | for panel in panels: 51 | __log("Updating panel %d" % panel.id(), verbose) 52 | panel.update_devices() 53 | __log("Listing thermosats", verbose) 54 | thermostats = panel.get_devices(device_type_set=[ 55 | vivint.VivintCloudSession.VivintDevice.DEVICE_TYPE_THERMOSTAT 56 | ]) 57 | for thermostat in thermostats: 58 | __log( 59 | "Getting state of thermostat %d on panel %d" % 60 | (thermostat.id(), panel.id()), verbose) 61 | state = thermostat.current_state() 62 | 63 | # Now bolt the other context to the state, and write it out. 64 | state["panel_arm_state"] = panel.get_armed_state() 65 | state["panel_id"] = panel.id() 66 | state["thermostat_id"] = thermostat.id() 67 | state["timestamp"] = time.time() 68 | __log("Logging state", verbose) 69 | fp.write(json.dumps(state, sort_keys=True) + "\n") 70 | fp.flush() 71 | 72 | # Now, change the state to the night-time one if we're home at the same time every 73 | # day. 74 | print( 75 | json.dumps([ 76 | state, 77 | time.strftime("%FT%T"), last_state_change, 78 | state_change_time, state["climate_state"] == "home", 79 | time.strftime("%F") != last_state_change["date"], 80 | time.strftime("%T") >= state_change_time 81 | ]), 82 | file=sys.stdout, 83 | flush=True) 84 | if state["climate_state"] == "home" and time.strftime( 85 | "%F") != last_state_change["date"] and time.strftime( 86 | "%T") >= state_change_time: 87 | thermostat.set_state("sleep") 88 | last_state_change["date"] = time.strftime("%F") 89 | __log("Sleeping", verbose) 90 | time.sleep(interval) 91 | 92 | 93 | if __name__ == "__main__": 94 | parser = argparse.ArgumentParser() 95 | parser.add_argument( 96 | "--interval", 97 | "-i", 98 | help="Delay, in seconds, between polling", 99 | type=float, 100 | required=False, 101 | default=60.0) 102 | parser.add_argument( 103 | "--output", 104 | "-o", 105 | help="Output file name, otherwise it goes to stdout", 106 | required=False, 107 | default=None) 108 | parser.add_argument( 109 | "--verbose", 110 | "-v", 111 | help="Display log messages on stderr", 112 | required=False, 113 | default=False, 114 | action="store_true") 115 | 116 | pargs = parser.parse_args() 117 | 118 | while True: 119 | try: 120 | periodic_update(pargs.interval, pargs.output, pargs.verbose) 121 | except Exception as e: 122 | with open(pargs.output + ".errlog", "w+") as fp: 123 | fp.write( 124 | json.dumps({ 125 | "dict": e.__dict__, 126 | "repr": repr(e), 127 | "str": str(e) 128 | }, 129 | cls=StringJsonEncoder)) 130 | -------------------------------------------------------------------------------- /examples/door.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import time 4 | import vivint 5 | 6 | # Set up the connection to the cloud session 7 | session = vivint.VivintCloudSession("john.smith@example.com", 8 | "SuperSecretPassword") 9 | 10 | # List all panels (sites) that this user account has access to 11 | panels = session.get_panels() 12 | 13 | for panel in panels: 14 | logger.debug("devices in panel {}: {}".format(panel, panel.get_devices())) 15 | 16 | # In this case, get the first door from the first site 17 | door = panels[0].get_devices(device_type_set=[ 18 | vivint.VivintCloudSession.VivintDevice.DEVICE_TYPE_DOOR_LOCK 19 | ])[0] 20 | 21 | # Get the current state and print it out 22 | print("Door state:", door.current_state()) 23 | 24 | # Let the change propagate for a bit 25 | time.sleep(2) 26 | for panel in panels: 27 | # Update every panel. Doing this also updates devices that 28 | # were spawned from those panels in-place, unless you set 29 | # devices' receive_updates property is set to False. 30 | panel.update_devices() 31 | 32 | # This will likely now reflect the current state of the door 33 | print(door.current_state()) 34 | -------------------------------------------------------------------------------- /examples/switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import time 4 | import os 5 | import vivint 6 | from datetime import datetime 7 | 8 | # Set up the connection to the cloud session 9 | session = vivint.VivintCloudSession(os.environ["USERNAME"], 10 | os.environ["PASSWORD"]) 11 | 12 | # Sensors and Switches 13 | # switch_one_name = "Living Room Main Lights" 14 | # switch_two_name = "Dining Room Lights" 15 | 16 | # sensor_one_name = "Living Room Motion Detector" 17 | # sensor_two_name = "Dining Room Motion Detector" 18 | 19 | # List all panels (sites) that this user account has access to 20 | panels = session.get_panels() 21 | 22 | 23 | multiswitches = panels[0].get_devices(device_type_set=[ 24 | vivint.VivintCloudSession.VivintDevice.DEVICE_TYPE_LIGHT_MODULE 25 | ]) 26 | 27 | sensors = panels[0].get_devices(device_type_set=[ 28 | vivint.VivintCloudSession.VivintDevice.DEVICE_TYPE_WIRELESS_SENSOR 29 | ]) 30 | 31 | # Let the change propagate for a bit 32 | time.sleep(2) 33 | for panel in panels: 34 | # Update every panel. Doing this also updates devices that 35 | # were spawned from those panels in-place, unless you set 36 | # devices' receive_updates property is set to False. 37 | panel.update_devices() 38 | 39 | for multiswitch in multiswitches: 40 | state = multiswitch.current_state() 41 | print("Multiswitch:", state) 42 | 43 | # if state.get("name") == switch_one_name: 44 | # switch_one_state = state.get("val") 45 | # switch_one = multiswitch 46 | # if state.get("name") == switch_two_name: 47 | # switch_two_state = state.get("val") 48 | # switch_two = multiswitch 49 | 50 | for sensor in sensors: 51 | state = sensor.current_state() 52 | print("Sensor:", state) 53 | 54 | # #use proximity sensors to detect movement in a room, then turn on lights 55 | # if state.get("name") == sensor_one_name: 56 | # #just a fun light turn on and off sequence 57 | # switch_one.set_switch(100) 58 | # switch_one.set_switch(80) 59 | # switch_one.set_switch(40) 60 | # switch_one.set_switch(0) 61 | 62 | # if state.get("name") == sensor_two_name: 63 | # switch_two.set_switch(100) 64 | # switch_two.set_switch(80) 65 | # switch_two.set_switch(40) 66 | # switch_two.set_switch(0) -------------------------------------------------------------------------------- /examples/thermostat-poll.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Demonstrats a long-lived polling thread that checks the state of all thermostats and writes them to stdout. 4 | """ 5 | 6 | from __future__ import print_function 7 | import os 8 | import sys 9 | import json 10 | import time 11 | import argparse 12 | 13 | import vivint 14 | 15 | running = True 16 | 17 | 18 | class StringJsonEncoder(json.JSONEncoder): 19 | def default(self, obj): # pylint: disable=E0202 20 | try: 21 | return json.JSONEncoder.default(self, obj) 22 | except: 23 | try: 24 | return str(obj) 25 | except: 26 | return repr(obj) 27 | 28 | 29 | def __log(s, v): 30 | if v: 31 | print(s, file=sys.stderr) 32 | 33 | 34 | def periodic_update(interval, out_file, verbose): 35 | if out_file is None: 36 | fp = sys.stdout 37 | else: 38 | # Open the file for appending 39 | fp = open(out_file, "a") 40 | 41 | __log("Establishing session", verbose) 42 | session = vivint.VivintCloudSession(os.environ["USERNAME"], 43 | os.environ["PASSWORD"]) 44 | __log("Listing panels", verbose) 45 | panels = session.get_panels() 46 | while running: 47 | for panel in panels: 48 | __log("Updating panel %d" % panel.id(), verbose) 49 | panel.update_devices() 50 | __log("Listing thermosats", verbose) 51 | thermostats = panel.get_devices(device_type_set=[ 52 | vivint.VivintCloudSession.VivintDevice.DEVICE_TYPE_THERMOSTAT 53 | ]) 54 | for thermostat in thermostats: 55 | __log( 56 | "Getting state of thermostat %d on panel %d" % 57 | (thermostat.id(), panel.id()), verbose) 58 | state = thermostat.current_state() 59 | 60 | # Now bolt the other context to the state, and write it out. 61 | state["panel_arm_state"] = panel.get_armed_state() 62 | state["panel_id"] = panel.id() 63 | state["thermostat_id"] = thermostat.id() 64 | state["timestamp"] = time.time() 65 | __log("Logging state", verbose) 66 | fp.write(json.dumps(state, sort_keys=True) + "\n") 67 | fp.flush() 68 | __log("Sleeping", verbose) 69 | time.sleep(interval) 70 | 71 | 72 | if __name__ == "__main__": 73 | parser = argparse.ArgumentParser() 74 | parser.add_argument( 75 | "--interval", 76 | "-i", 77 | help="Delay, in seconds, between polling", 78 | type=float, 79 | required=False, 80 | default=60.0) 81 | parser.add_argument( 82 | "--output", 83 | "-o", 84 | help="Output file name, otherwise it goes to stdout", 85 | required=False, 86 | default=None) 87 | parser.add_argument( 88 | "--verbose", 89 | "-v", 90 | help="Display log messages on stderr", 91 | required=False, 92 | default=False, 93 | action="store_true") 94 | 95 | pargs = parser.parse_args() 96 | 97 | while True: 98 | try: 99 | periodic_update(pargs.interval, pargs.output, pargs.verbose) 100 | except Exception as e: 101 | with open(pargs.output + ".errlog", "w+") as fp: 102 | fp.write( 103 | json.dumps({ 104 | "dict": e.__dict__, 105 | "repr": repr(e), 106 | "str": str(e) 107 | }, 108 | cls=StringJsonEncoder)) 109 | -------------------------------------------------------------------------------- /examples/thermostat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import time 4 | import vivint 5 | 6 | # Set up the connection to the cloud session 7 | session = vivint.VivintCloudSession("john.smith@example.com", 8 | "SuperSecretPassword") 9 | 10 | # List all panels (sites) that this user account has access to 11 | panels = session.get_panels() 12 | 13 | # In this case, get the first thermostat from the first site 14 | thermostat = panels[0].get_devices(device_type_set=[ 15 | vivint.VivintCloudSession.VivintDevice.DEVICE_TYPE_THERMOSTAT 16 | ])[0] 17 | 18 | # Get the current state and print it out 19 | print(thermostat.current_state()) 20 | 21 | # Set a few thermostat things. 22 | thermostat.set_operation_mode("heat") 23 | thermostat.set_fan_mode("always") 24 | thermostat.set_temperature(10) 25 | 26 | # Let the change propagate for a bit 27 | time.sleep(2) 28 | for panel in panels: 29 | # Update every panel. Doing this also updates devices that 30 | # were spawned from those panels in-place, unless you set 31 | # devices' receive_updates property is set to False. 32 | panel.update_devices() 33 | 34 | # This will likely now reflect the current state of the thermostat 35 | print(thermostat.current_state()) 36 | -------------------------------------------------------------------------------- /vivint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Provides an interface to the Vivint cloud service by authenticating to the API with the 4 | account's username and password. 5 | """ 6 | 7 | import os 8 | import re 9 | import sys 10 | import time 11 | import json 12 | import base64 13 | import urllib3 14 | import argparse 15 | import threading 16 | 17 | from datetime import datetime 18 | 19 | try: 20 | import certifi 21 | except: 22 | pass 23 | 24 | from http.cookies import SimpleCookie 25 | 26 | # pylint: disable=E0611,E0401 27 | from urllib.parse import urlencode, unquote, quote, quote_plus 28 | 29 | VIVINT_API_ENDPOINT = "https://www.vivintsky.com" 30 | 31 | 32 | def _flip_dict(d): 33 | """ 34 | Flip a dictionary to map values to keys 35 | """ 36 | return dict([(v, k) for k, v in d.items()]) 37 | 38 | 39 | def _urllib_pool(): 40 | if "certifi" not in sys.modules: 41 | return urllib3.PoolManager() 42 | else: 43 | return urllib3.PoolManager(cert_reqs='CERT_REQUIRED', 44 | ca_certs=certifi.where()) 45 | 46 | 47 | class VivintCloudSession(object): 48 | """ 49 | Implements the surrounding components for authenticating, retrieving a session token, 50 | and refreshing the token as necessary. This is required for all other cloud-related 51 | operations. 52 | """ 53 | class VivintDevice(object): 54 | """ 55 | A top level abstract type that represents all types of Vivint devices. 56 | """ 57 | # This one applies to a variety of sensors: 58 | # - Heat detectors 59 | # - Freeze detectors 60 | # - Smoke detectors 61 | # - Door/window sensors 62 | # - Glass break sensors 63 | DEVICE_TYPE_WIRELESS_SENSOR = "wireless_sensor" 64 | 65 | # This may only represent newer touch panels, not the older style 66 | DEVICE_TYPE_TOUCH_PANEL = "primary_touch_link_device" 67 | 68 | DEVICE_TYPE_DOOR_LOCK = "door_lock_device" 69 | 70 | # Doorbells appear as cameras too, you can tell just by the name. 71 | DEVICE_CAMERA = "camera_device" 72 | 73 | # This may only apply to Element thermostats? 74 | DEVICE_TYPE_THERMOSTAT = "thermostat_device" 75 | 76 | # This is likely separate from other kinds of switches 77 | # This specifically is the multi-level light module. 78 | DEVICE_TYPE_LIGHT_MODULE = "multilevel_switch_device" 79 | 80 | # Represents wireless sensors like door sensors but also hard wired motion detectors 81 | DEVICE_TYPE_MOTION_SENSOR = "wireless_sensor" 82 | 83 | def __init__(self, body, panel_root): 84 | self._body = body 85 | self.__panel_root = panel_root 86 | self._pool = _urllib_pool() 87 | 88 | # When set to False, this device will not be updated when the panel root's 89 | # update_devices() method is called. 90 | self.receive_updates = True 91 | 92 | def get_authorization_headers(self): 93 | return self.__panel_root.get_authorization_headers() 94 | 95 | def get_panel_root(self): 96 | """ 97 | Returns the root panel for this device. 98 | """ 99 | return self.__panel_root 100 | 101 | def get_body(self): 102 | """ 103 | Return the bare dictionary that describes this object, as returned by the 104 | Vivint API, and was used to construct this initially. 105 | """ 106 | return self._body 107 | 108 | def update_body(self, body, panel_update=False): 109 | """ 110 | Abstracts updating the body components of the device. 111 | """ 112 | # Don't apply updates from the parent panel if the receive_updates 113 | if panel_update and not self.receive_updates: 114 | pass 115 | else: 116 | self._body = body 117 | 118 | def id(self): 119 | return self._body["_id"] 120 | 121 | @staticmethod 122 | def get_class(type_string): 123 | mapping = { 124 | VivintCloudSession.VivintDevice.DEVICE_TYPE_THERMOSTAT: 125 | VivintCloudSession.Thermostat, 126 | VivintCloudSession.VivintDevice.DEVICE_TYPE_LIGHT_MODULE: 127 | VivintCloudSession.MultiSwitch, 128 | VivintCloudSession.VivintDevice.DEVICE_TYPE_MOTION_SENSOR: 129 | VivintCloudSession.MotionSensor, 130 | VivintCloudSession.VivintDevice.DEVICE_TYPE_WIRELESS_SENSOR: 131 | VivintCloudSession.WirelessSensor, 132 | VivintCloudSession.VivintDevice.DEVICE_TYPE_DOOR_LOCK: 133 | VivintCloudSession.DoorLock, 134 | VivintCloudSession.VivintDevice.DEVICE_CAMERA: 135 | VivintCloudSession.Camera 136 | } 137 | return mapping.get(type_string, VivintCloudSession.UnknownDevice) 138 | 139 | class PanelRoot(VivintDevice): 140 | """ 141 | Represents the top-level device that is a panel at a Vivint enabled location. 142 | """ 143 | 144 | ARM_STATE_DISARMED = 0 145 | ARM_STATE_ARMED_STAY = 3 146 | ARM_STATE_ARMED_AWAY = 4 147 | __ARM_STATES = { 148 | ARM_STATE_DISARMED: "disarmed", 149 | ARM_STATE_ARMED_STAY: "armed_stay", 150 | ARM_STATE_ARMED_AWAY: "armed_away" 151 | } 152 | 153 | def __init__(self, session, panel_descriptor): 154 | super().__init__(panel_descriptor, self) 155 | self.__session = session 156 | self.__pool = _urllib_pool() 157 | self.__description = panel_descriptor 158 | self.__system = self.__get_system() 159 | self.__child_devices = [] 160 | self.__active_partition = 1 161 | self.get_devices() 162 | 163 | def __get_system(self): 164 | resp = self.__pool.request( 165 | method="GET", 166 | url="%s/api/systems/%d" % 167 | (VIVINT_API_ENDPOINT, self.__description["panid"]), 168 | headers=self.get_authorization_headers()) 169 | 170 | return json.loads(resp.data.decode()) 171 | 172 | def get_active_partition(self): 173 | return self.__active_partition 174 | 175 | def get_authorization_headers(self): 176 | return self.__session.get_authorization_headers() 177 | 178 | def partition_count(self): 179 | return len(self.__system["system"]["par"]) 180 | 181 | def set_active_partition(self, partition_id): 182 | if not (isinstance(partition_id, int) and partition_id <= 0 183 | and partition_id > self.partition_count()): 184 | raise ValueError( 185 | "Partition ID must be a positive integer less than or equal to the number of partitions", 186 | self.partition_count()) 187 | 188 | self.__active_partition = int(partition_id) 189 | self.update_devices() 190 | 191 | def update_devices(self, device_list=None): 192 | """ 193 | Re-poll the systems endpoint, and update all devices, unless a list of 194 | devices is specified, then only update those in the list (as long as those 195 | specified are children of this root). 196 | """ 197 | # Update the system body 198 | self.__system = self.__get_system() 199 | 200 | if device_list is None: 201 | device_list = self.__child_devices 202 | 203 | device_list = [ 204 | d for d in self.__child_devices 205 | if d.receive_updates and d.get_panel_root() == self 206 | ] 207 | 208 | device_dict = dict([ 209 | (d["_id"], d) 210 | for d in self.__system["system"]["par"][self.__active_partition 211 | - 1]["d"] 212 | ]) 213 | 214 | for device in device_list: 215 | device.update_body(device_dict[device.id()]) 216 | 217 | def get_rtsp_credentials(self): 218 | resp = self.__pool.request( 219 | method="GET", 220 | url="%s/api/panel-login/%d" % 221 | (VIVINT_API_ENDPOINT, self.__description["panid"]), 222 | headers=self.get_authorization_headers()) 223 | 224 | if resp.status != 200: 225 | raise Exception("Unable to fetch RTSP credentials", resp) 226 | 227 | resp_json = json.loads(resp.data.decode()) 228 | username = resp_json["n"] 229 | password = resp_json["pswd"] 230 | 231 | return {"username": username, "password": password} 232 | 233 | def id(self): 234 | """ 235 | Return the panel's ID 236 | """ 237 | return self.__description["panid"] 238 | 239 | def get_armed_state(self): 240 | """ 241 | Return the panel's arm state 242 | """ 243 | return self.__ARM_STATES[self.__system["system"]["par"][ 244 | self.__active_partition - 1]["proph"]["s"][0]["val"]] 245 | 246 | def set_armed_state(self, state): 247 | """ 248 | Arming the panel involves PUTing against the /api/${PanelId}/${PartitionId}/armedstates endpoint 249 | """ 250 | if isinstance(state, 251 | int) and state not in self.__ARM_STATES.keys(): 252 | raise ValueError( 253 | "When using numeric arming state, value must be one of the provided constants" 254 | ) 255 | elif isinstance(state, 256 | str) and state not in self.__ARM_STATES.values(): 257 | raise ValueError( 258 | "When using string values for arming states, value must be one of allowed values", 259 | list(self.__ARM_STATES.values())) 260 | 261 | resp = self.__pool.request( 262 | method="PUT", 263 | url="%s/api/%d/%d/armedstates" % 264 | (VIVINT_API_ENDPOINT, self.__description["panid"], 265 | self.__active_partition), 266 | body=json.dumps({ 267 | "systemId": 268 | self.__description["panid"], 269 | "partitionId": 270 | self.__active_partition, 271 | "forceArm": 272 | False, 273 | "armState": 274 | _flip_dict(self.__ARM_STATES)[state] if isinstance( 275 | state, str) else state 276 | }).encode("utf-8"), 277 | headers={ 278 | **{ 279 | "Content-Type": "application/json;charset=utf-8" 280 | }, 281 | **self.get_authorization_headers() 282 | }) 283 | 284 | if resp.status != 200: 285 | raise Exception( 286 | "Expected 200 response when setting armed state", resp) 287 | 288 | return 289 | 290 | def address(self): 291 | """ 292 | Return the panel's address 293 | """ 294 | return self.__description["add"] 295 | 296 | def climate_state(self): 297 | """ 298 | Return the climate state of the panel 299 | """ 300 | return self.__system["system"]["csce"] 301 | 302 | def get_devices(self, device_type_set=None, include_unknown=False): 303 | """ 304 | Return a list of all devices where the class is, optionally, in the set 305 | of device types provided. 306 | """ 307 | # ASSUMPTION 308 | # This assumes that there's only one item in the "par" key, which corresponds to 309 | # only one partition. 310 | devices = [ 311 | VivintCloudSession.VivintDevice.get_class(device["t"])(device, 312 | self) 313 | for device in self.__system["system"]["par"][ 314 | self.__active_partition - 1]["d"] 315 | if device_type_set is None or device["t"] in device_type_set 316 | ] 317 | 318 | if not include_unknown: 319 | devices = [ 320 | d for d in devices 321 | if type(d) != VivintCloudSession.UnknownDevice 322 | ] 323 | 324 | self.__child_devices += devices 325 | return devices 326 | 327 | class UnknownDevice(VivintDevice): 328 | """ 329 | Represents a device that does not have a model associated with the type. 330 | """ 331 | def __init__(self, body, panel_root): 332 | super().__init__(body, panel_root) 333 | 334 | class Camera(VivintDevice): 335 | """ 336 | Represents a basic camera able to expose a few pieces of information. 337 | 338 | This is primarily here to be able to expose the public and private RTSP endpoints. 339 | """ 340 | def __init__(self, body, panel_root): 341 | super().__init__(body, panel_root) 342 | 343 | def name(self): 344 | return self._body["n"] 345 | 346 | def private_rtsp_endpoint(self): 347 | return { 348 | "hd_video": self._body["ciu"][0], 349 | "sd_video": self._body["cius"][0], 350 | "audio_only": self._body["cea"][0] 351 | } 352 | 353 | def hd_video_resolution(self): 354 | return [int(dim) for dim in self._body["hdr"].split("x")] 355 | 356 | def public_rtsp_endpoint(self): 357 | return { 358 | "hd_video": self._body["cetu"][0], 359 | "sd_video": self._body["cetus"][0], 360 | "audio_only": self._body["cea"][0] 361 | } 362 | 363 | def rtsp_authentication_url(self, url): 364 | return "%s://%s:%s@%s" % ( 365 | "rtsps" if ":443/" in url else "rtsp", 366 | self.get_panel_root().get_rtsp_credentials()["username"], 367 | self.get_panel_root().get_rtsp_credentials()["password"], 368 | url[7:]) 369 | 370 | class MotionSensor(VivintDevice): 371 | def __init__(self, body, panel_root): 372 | super().__init__(body, panel_root) 373 | 374 | def current_state(self): 375 | active = self._body["ts"] 376 | time = datetime.strptime(active, '%Y-%m-%dT%H:%M:%S.%f') 377 | name = self._body["n"] 378 | return {"activitytime": time, "name": name} 379 | 380 | class WirelessSensor(VivintDevice): 381 | # I'm just guessing at state=1 here... 382 | # Legit not feeling like walking all the way downstairs to open a door and test. 😅 383 | states = {0: "enabled", 2: "bypassed"} 384 | 385 | def __init__(self, body, panel_root): 386 | super().__init__(body, panel_root) 387 | 388 | def current_state(self): 389 | active = self._body["ts"] 390 | time = datetime.strptime(active, '%Y-%m-%dT%H:%M:%S.%f') 391 | return { 392 | "id": self.id(), 393 | "activitytime": time, 394 | "name": self._body["n"], 395 | "triggered": self._body["s"], 396 | "enabled": self._body["b"] == 0, 397 | "battery_level_percent": self._body.get("bl", None) 398 | } 399 | 400 | def __set(self, val): 401 | # To bypass the sensor, you set "b" to True, and to re-enable you set it to false 402 | # This manifests as either 0 or 2 in the value when it gets updated. 403 | # 404 | # It's weird, and I don't like it. 405 | request_body = {"_id": self.id(), "b": val} 406 | 407 | request_kwargs = dict( 408 | method="PUT", 409 | url="%s/api/%d/%d/sensors/%d" % 410 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 411 | self.get_panel_root().get_active_partition(), self.id()), 412 | body=json.dumps(request_body).encode("utf-8"), 413 | headers={ 414 | **{ 415 | "Content-Type": "application/json;charset=utf-8" 416 | }, 417 | **self.get_authorization_headers() 418 | }) 419 | resp = self._pool.request(**request_kwargs) 420 | 421 | if resp.status != 200: 422 | raise Exception("Unable to set wireless sensor state", ( 423 | resp.status, "%s/api/%d/%d/sensors/%d" % 424 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 425 | self.get_panel_root().get_active_partition(), self.id()))) 426 | else: 427 | self._body["b"] = 2 if val else 0 428 | 429 | def bypass(self): 430 | self.__set(True) 431 | 432 | def enable(self): 433 | self.__set(False) 434 | 435 | class MultiSwitch(VivintDevice): 436 | def __init__(self, body, panel_root): 437 | super().__init__(body, panel_root) 438 | 439 | def set_switch(self, val): 440 | request_body = {"_id": self.id(), "val": val} 441 | 442 | request_kwargs = dict( 443 | method="PUT", 444 | url="%s/api/%d/%d/switches/%d" % 445 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 446 | self.get_panel_root().get_active_partition(), self.id()), 447 | body=json.dumps(request_body).encode("utf-8"), 448 | headers={ 449 | **{ 450 | "Content-Type": "application/json;charset=utf-8" 451 | }, 452 | **self.get_authorization_headers() 453 | }) 454 | resp = self._pool.request(**request_kwargs) 455 | 456 | if resp.status != 200: 457 | raise Exception("Unable to set multiswitch state", ( 458 | resp.status, "%s/api/%d/%d/switches/%d" % 459 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 460 | self.get_panel_root().get_active_partition(), self.id()))) 461 | else: 462 | self._body["val"] = val 463 | 464 | def current_state(self): 465 | current = self._body["val"] 466 | name = self._body["n"] 467 | return {"val": current, "name": name} 468 | 469 | class DoorLock(VivintDevice): 470 | """ 471 | Represents a door lock. 472 | """ 473 | def __init__(self, body, panel_root): 474 | super().__init__(body, panel_root) 475 | 476 | def __set(self, val): 477 | request_body = {"_id": self.id(), "s": val} 478 | 479 | request_kwargs = dict( 480 | method="PUT", 481 | url="%s/api/%d/%d/locks/%d" % 482 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 483 | self.get_panel_root().get_active_partition(), self.id()), 484 | body=json.dumps(request_body).encode("utf-8"), 485 | headers={ 486 | **{ 487 | "Content-Type": "application/json;charset=utf-8" 488 | }, 489 | **self.get_authorization_headers() 490 | }) 491 | resp = self._pool.request(**request_kwargs) 492 | 493 | if resp.status != 200: 494 | raise Exception("Unable to set door lock state", ( 495 | resp.status, "%s/api/%d/%d/locks/%d" % 496 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 497 | self.get_panel_root().get_active_partition(), self.id()))) 498 | else: 499 | self._body["s"] = val 500 | 501 | def lock(self): 502 | self.__set(True) 503 | 504 | def unlock(self): 505 | self.__set(False) 506 | 507 | def current_state(self): 508 | return { 509 | "battery_level_percent": self._body.get("bl", None), 510 | "is_locked": self._body["s"] 511 | } 512 | 513 | class Thermostat(VivintDevice): 514 | """ 515 | Represents a Vivint thermostat generic device, supporting generic thermostat 516 | controls and functionality. 517 | """ 518 | 519 | OPERATION_MODES = {0: "off", 1: "heat", 2: "cool", 3: "heat-cool"} 520 | FAN_MODES = {0: "off", 1: "always", 99: "15m", 100: "30m", 101: "60m"} 521 | CLIMATE_STATES = ["home", "away", "sleep", "vacation"] 522 | 523 | # Some general notes: 524 | # 525 | # The restore-estimates endpoint provides estimates of the time, in seconds, to 526 | # heat or cool to the listed temperature. 527 | # 528 | # An example URL for that is: 529 | # Request URL: https://vivintsky.com/api/restore-estimates/${PanelId}/${ThermostatId} 530 | 531 | def __init__(self, body, panel_root): 532 | super().__init__(body, panel_root) 533 | 534 | def set_state(self, state): 535 | """ 536 | Set the state of the panel location to one of the Smart Assistant states. 537 | 538 | This is a bit of a semantic oddity, as the change is made to the panel 539 | object, but it only ever makes sense in the context of a thermostat in the 540 | apps, except in the rules section. 541 | """ 542 | if state not in self.CLIMATE_STATES: 543 | raise ValueError("State must be one of %s" % 544 | repr(self.CLIMATE_STATES)) 545 | 546 | request_kwargs = dict( 547 | method="PUT", 548 | url="%s/api/systems/%d?includerules=false" % 549 | (VIVINT_API_ENDPOINT, self.get_panel_root().id()), 550 | body=json.dumps({ 551 | "csce": state 552 | }).encode(("utf-8")), 553 | headers={ 554 | **{ 555 | "Content-Type": "application/json;charset=utf-8" 556 | }, 557 | **self.get_authorization_headers() 558 | }) 559 | resp = self._pool.request(**request_kwargs) 560 | 561 | if resp.status != 200: 562 | raise Exception("Setting state resulted in non-200 response", 563 | resp) 564 | 565 | def set_operation_mode(self, mode): 566 | """ 567 | Changes the mode of operation. 568 | """ 569 | request_kwargs = dict( 570 | method="PUT", 571 | url="%s/api/%d/%d/thermostats/%d" % 572 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 573 | self.get_panel_root().get_active_partition(), self.id()), 574 | body=json.dumps({ 575 | "_id": self.id(), 576 | "om": _flip_dict(self.OPERATION_MODES)[mode] 577 | }).encode("utf-8"), 578 | headers={ 579 | **{ 580 | "Content-Type": "application/json;charset=utf-8" 581 | }, 582 | **self.get_authorization_headers() 583 | }) 584 | resp = self._pool.request(**request_kwargs) 585 | 586 | if resp.status != 200: 587 | raise Exception( 588 | "Setting operation mode resulted in non-200 response") 589 | 590 | def set_fan_mode(self, mode): 591 | """ 592 | Changes the mode of fan operation. 593 | """ 594 | request_kwargs = dict( 595 | method="PUT", 596 | url="%s/api/%d/%d/thermostats/%d" % 597 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 598 | self.get_panel_root().get_active_partition(), self.id()), 599 | body=json.dumps({ 600 | "_id": self.id(), 601 | "fm": _flip_dict(self.FAN_MODES)[mode] 602 | }).encode("utf-8"), 603 | headers={ 604 | **{ 605 | "Content-Type": "application/json;charset=utf-8" 606 | }, 607 | **self.get_authorization_headers() 608 | }) 609 | resp = self._pool.request(**request_kwargs) 610 | 611 | if resp.status != 200: 612 | raise Exception( 613 | "Setting fan mode resulted in non-200 response") 614 | 615 | def set_temperature(self, 616 | setpoint=None, 617 | cool_setpoint=None, 618 | heat_setpoint=None): 619 | """ 620 | Set the setpoint temperature for cooling and heating. 621 | """ 622 | mode = self._body["om"] 623 | request_body = { 624 | "_id": self.id(), 625 | "currentAutoMode": 2 # NOTE No clue what this is. :D 626 | } 627 | 628 | # By deafult, if there are explicit values, set them 629 | if heat_setpoint is not None: 630 | request_body["hsp"] = heat_setpoint 631 | if cool_setpoint is not None: 632 | request_body["csp"] = cool_setpoint 633 | 634 | # Heat not explicitly set, heating mode, setpoint set 635 | if mode == 1 and "hsp" not in request_body and setpoint is not None: 636 | request_body["hsp"] = setpoint 637 | # Cool not explicitly set, cooling mode, setpoint set 638 | elif mode == 2 and "csp" not in request_body and setpoint is not None: 639 | request_body["csp"] = setpoint 640 | # Heat/Cool 641 | elif mode == 3: 642 | # Heat explicitly set, cold not explicitly set, setpoint set 643 | if heat_setpoint is not None and "csp" not in request_body and \ 644 | setpoint is not None: 645 | request_body["csp"] = setpoint 646 | # Heat explicitly set, cold not explicitly set, setpoint set 647 | if cool_setpoint is not None and "hsp" not in request_body and \ 648 | setpoint is not None: 649 | request_body["hsp"] = setpoint 650 | 651 | request_kwargs = dict( 652 | method="PUT", 653 | url="%s/api/%d/%d/thermostats/%d" % 654 | (VIVINT_API_ENDPOINT, self.get_panel_root().id(), 655 | self.get_panel_root().get_active_partition(), self.id()), 656 | body=json.dumps(request_body).encode("utf-8"), 657 | headers={ 658 | **{ 659 | "Content-Type": "application/json;charset=utf-8" 660 | }, 661 | **self.get_authorization_headers() 662 | }) 663 | resp = self._pool.request(**request_kwargs) 664 | 665 | if resp.status != 200: 666 | raise Exception( 667 | "Setting temperature resulted in non-200 response") 668 | 669 | # NOTE 670 | # This response may contain some suggestions, and a reasonable body. 671 | # Here's an example; 672 | # 673 | # { 674 | # "awareness_message": { 675 | # "pans": [ 676 | # { 677 | # "l": "Yes", 678 | # "val": "yes" 679 | # }, 680 | # { 681 | # "l": "No", 682 | # "val": "no" 683 | # } 684 | # ], 685 | # "stat": null, 686 | # "igt": "2018-05-27 17:16:16.739727", 687 | # "uid": "edf467e797842913f97b11bb", 688 | # "dest": "thermostats", 689 | # "ts": "2018-05-27 17:11:16.776699", 690 | # "plctx": { 691 | # "ctxid": "edf467e797842913f97b11bb", 692 | # "ctxt": 10, 693 | # "mid": "585c79932593243672c5d8a8", 694 | # "ts": "2018-05-27 17:11:16.778789+00:00", 695 | # "ctxd": { 696 | # "currentAutoMode": 2, 697 | # "_id": 33, 698 | # "csp": 23.5 699 | # } 700 | # }, 701 | # "q": "Would you like to switch to Away mode?", 702 | # "did": 33, 703 | # "t": null, 704 | # "in": true, 705 | # "amtid": 4, 706 | # "_id": "585c79932593243672c5d8a8", 707 | # "panid": 42138025481253 708 | # } 709 | # } 710 | 711 | def current_state(self): 712 | """ 713 | Poll the thermostat endpoint to retrieve the temperature setpoints and 714 | other information. 715 | """ 716 | mode_id = self._body["om"] 717 | current = self._body["val"] 718 | hsp = self._body["hsp"] 719 | csp = self._body["csp"] 720 | 721 | if mode_id == 0: 722 | setpoint = None 723 | elif mode_id == 1: 724 | setpoint = hsp 725 | elif mode_id == 2: 726 | setpoint = csp 727 | elif mode_id == 3: 728 | # For the heat/cool situation, the setpoint is whichever one is active, 729 | # and if neither are active, then it is whichever we are closer to (if 730 | # the current temperature is between the two setpoints). 731 | if current <= hsp: 732 | setpoint = hsp 733 | elif current >= csp: 734 | setpoint = csp 735 | else: 736 | cdelta = abs(csp - current) 737 | hdelta = abs(hsp - current) 738 | if cdelta == hdelta: 739 | setpoint = float('nan') 740 | else: 741 | setpoint = min([csp, cdelta], [hsp, hdelta], 742 | key=lambda i: i[1])[0] 743 | 744 | return { 745 | "climate_state": self.get_panel_root().climate_state(), 746 | "fan_mode": self.FAN_MODES[self._body["fm"]], 747 | "humidity": self._body["hmdt"], 748 | "temperature": current, 749 | "mode": self.OPERATION_MODES[mode_id], 750 | "active_setpoint": setpoint, 751 | "cooling_setpoint": csp, 752 | "heating_setpoint": hsp 753 | } 754 | 755 | def __init__(self, 756 | username=None, 757 | password=None, 758 | state=None, 759 | nonce=None, 760 | pf_token=None): 761 | self.__pool = _urllib_pool() 762 | 763 | # Prefer username/password authentication if both are provided. 764 | if username is not None and password is not None: 765 | self.__login(username, password) 766 | # TODO Obfuscate the username and password here 767 | self.__username = username 768 | self.__password = password 769 | elif state is not None and nonce is not None and pf_token is not None: 770 | self.__username = None 771 | self.__password = None 772 | 773 | self.__auth_elements = {"headers": None} 774 | self.__refresh_token() 775 | else: 776 | raise ValueError( 777 | "Must supply either a username/password pair or a authorization cookie" 778 | ) 779 | 780 | self.__auth_user_data = self.__authuser() 781 | 782 | self.__run_threads = True 783 | self.__refresh_thread = self.__make_refresh_thread() 784 | 785 | def __refresh_handler(self): 786 | """ 787 | Keep track of a cloud session's id tokens, and whenever one is nearing expiry, refresh it. 788 | """ 789 | # TODO Make this exception-safe 790 | while self.__run_threads: 791 | if self.__parse_credential_expiry() - time.time() < 60: 792 | self.__refresh_token() 793 | time.sleep(60) 794 | 795 | def __make_refresh_thread(self): 796 | """ 797 | Build a refresh thread that runs in the background and refreshes the token before it expires. 798 | """ 799 | thread = threading.Thread(target=self.__refresh_handler) 800 | thread.daemon = True 801 | thread.start() 802 | return thread 803 | 804 | def __parse_credential_expiry(self): 805 | return time.time() + 120 806 | 807 | def __refresh_token(self): 808 | self.__auth_elements = self.__auth_elements 809 | authuser_resp = self.__pool.request( 810 | method="GET", 811 | url="%s/api/authuser" % VIVINT_API_ENDPOINT, 812 | headers=self.get_authorization_headers()) 813 | 814 | ### TODO Error handling here in case the set-cookie header is missing. 815 | self.__auth_elements["headers"] = { 816 | "Cookie": authuser_resp.headers["Set-Cookie"] 817 | } 818 | 819 | def __login(self, username, password): 820 | """ 821 | Login into the Vivint Sky platform with the given username and password 822 | 823 | Returns an object that includes the appropriate OpenID components. 824 | """ 825 | 826 | login_resp = self.__pool.request(method="POST", 827 | url="%s/api/login" % 828 | (VIVINT_API_ENDPOINT), 829 | body=json.dumps({ 830 | "username": username, 831 | "password": password 832 | }).encode("utf-8")) 833 | 834 | if login_resp.headers.get("Set-Cookie", None) is None: 835 | raise Exception("Unable to get Set-Cookie header from response") 836 | 837 | self.__auth_elements = dict( 838 | headers={"Cookie": login_resp.headers["Set-Cookie"]}) 839 | 840 | def get_authorization_headers(self): 841 | return self.__auth_elements["headers"] 842 | 843 | def __authuser(self): 844 | """ 845 | Poll the Vivint authuser API endpoint resource to gather user-related data including 846 | enumeration of the systems that user has access to. 847 | """ 848 | resp = self.__pool.request(method="GET", 849 | url="%s/api/authuser" % VIVINT_API_ENDPOINT, 850 | headers=self.get_authorization_headers()) 851 | 852 | return json.loads(resp.data.decode()) 853 | 854 | def get_panels(self): 855 | """ 856 | Return object for each panel that this logged in user has access to 857 | """ 858 | return [ 859 | self.PanelRoot(self, panel) 860 | for panel in self.__auth_user_data["u"]["system"] 861 | ] 862 | --------------------------------------------------------------------------------