├── .github └── FUNDING.yml ├── API_KEY.py ├── LICENSE.txt ├── README.md ├── fonctions.py ├── frontend ├── deCONZ.html └── deCONZ.js ├── icons ├── batterylevelempty_icons.zip ├── batterylevelfull_icons.zip ├── batterylevellow_icons.zip └── batterylevelok_icons.zip ├── plugin.py └── widget.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [Smanar] 4 | custom: ["https://www.buymeacoffee.com/Smanar"] 5 | -------------------------------------------------------------------------------- /API_KEY.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding: utf-8 -*- 3 | 4 | import sys 5 | import urllib,json 6 | try: 7 | from urllib import request, parse 8 | except: 9 | print('This tool is for python 3, use instead "python3 API_KEY.py" !') 10 | sys.exit(0) 11 | 12 | try: 13 | ip = sys.argv[1] 14 | action = sys.argv[2] 15 | data = sys.argv[3:] 16 | except: 17 | action = 'error' 18 | 19 | if action == 'create': 20 | query_args = '{"devicetype":"Domoticz"}' 21 | data = query_args.encode('utf-8') 22 | req = request.Request('http://' + ip + '/api',data) 23 | #request.add_header('Referer', 'http://www.python.org/') 24 | try: 25 | response = request.urlopen(req,timeout=3).read() 26 | response = response.decode("utf-8", "ignore") 27 | j = json.loads(response) 28 | print ("Your new API key is : " + j[0]["success"]['username']) 29 | 30 | except urllib.error.URLError as e: 31 | if str(e.reason) == 'timed out': 32 | print('Timeout, are you sure for url and port ?') 33 | elif hasattr(e, 'code') and e.code == 403: 34 | print('Please unlock the gateway first and retry !') 35 | else: 36 | print('Connection error : ' + str(e.reason) ) 37 | 38 | elif action == 'list': 39 | if len(data) < 1: 40 | print('Missing params !') 41 | else: 42 | req = request.Request('http://' + ip + '/api/' + data[0] + '/config') 43 | response = request.urlopen(req,timeout=3).read() 44 | response = response.decode("utf-8", "ignore") 45 | j = json.loads(response) 46 | j2 = j['whitelist'] 47 | for i in j2: 48 | print ('KEY : ' + i + ' Name : ' + j2[i]['name'] + ' Last used : ' + j2[i]['last use date'] ) 49 | 50 | elif action == 'clean': 51 | if len(data) < 1: 52 | print('Missing params !') 53 | else: 54 | req = request.Request('http://' + ip + '/api/' + data[0] + '/config') 55 | response = request.urlopen(req,timeout=3).read() 56 | response = response.decode("utf-8", "ignore") 57 | j = json.loads(response) 58 | j2 = j['whitelist'] 59 | for i in j2: 60 | print ('KEY : ' + i + ' Name : ' + j2[i]['name'] + ' Last used : ' + j2[i]['last use date'] ) 61 | if 'deCONZ WebApp' in j2[i]['name'] or 'Phoscon#' in j2[i]['name'] or 'homebridge-hue#' in j2[i]['name'] or 'Hue Essentials#' in j2[i]['name']: 62 | req = request.Request('http://' + ip + '/api/' + data[0] + '/config/whitelist/' + i , method='DELETE') 63 | response = request.urlopen(req).read() 64 | print ('Deleted : ' + str(response) ) 65 | 66 | elif action == 'delete': 67 | if len(data) < 2: 68 | print('Missing params !') 69 | else: 70 | req = request.Request('http://' + ip + '/api/' + data[0] + '/config/whitelist/' + data[1] , method='DELETE') 71 | try: 72 | response = request.urlopen(req,timeout=3).read() 73 | print ('Key deleted') 74 | 75 | except urllib.error.URLError as e: 76 | print('Error : ' + str(e.code)) 77 | print(e.read()) 78 | 79 | elif action == 'info': 80 | if len(data) < 1: 81 | print('Missing params!') 82 | else: 83 | req = request.Request('http://' + ip + '/api/' + data[0] + '/config') 84 | response = request.urlopen(req,timeout=3).read() 85 | response = response.decode("utf-8", "ignore") 86 | j = json.loads(response) 87 | if 'websocketport' in j: 88 | print ("Websocket Port : " + str(j['websocketport']) ) 89 | print ("IP adress: " + j['ipaddress'] ) 90 | print ("Firmware version : " + j['fwversion'] ) 91 | print ("Websocketnotifyall : " + str(j['websocketnotifyall']) ) 92 | else: 93 | print ("Bad API Key") 94 | 95 | 96 | else: 97 | print('Exemples of use') 98 | print('python3 API_KEY.py : \n') 99 | print('python3 API_KEY.py 127.0.0.1:80 create') 100 | print('python3 API_KEY.py 127.0.0.1:80 info B4B018AA61') 101 | print('python3 API_KEY.py 127.0.0.1:80 list B4B018AA61') 102 | print('python3 API_KEY.py 127.0.0.1:80 delete B4B018AA61 CA606DA036') 103 | print('python3 API_KEY.py 127.0.0.1:80 clean B4B018AA61') 104 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # deCONZ bridge, a Zigbee plugin for Domoticz. 2 | It's a python plugin for Domoticz (home automation application). 3 | It uses the deCONZ REST API to make a bridge beetween your zigbee network and Domoticz using a Dresden Elektronik gateway and their application. 4 | 5 | ## Description 6 | To resume: 7 | - you need a Dresden Elektronik gateway, a Raspbee (for raspberry) or Conbee (USB key), it support a lot of Zigbee devices, Xiaomi, Heiman, Ikea, Philips, Osram, Tuya, ect .... 8 | Official compatibility list https://github.com/dresden-elektronik/deconz-rest-plugin/wiki/Supported-Devices 9 | 10 | - You also need deCONZ (their application to control and set up ZigBee network). It can work with an headless mode but you can use their GUI, for maintenance, support, look at traffic, set attributes, manage router, use command like identify: 11 | 12 | ![deconz](https://user-images.githubusercontent.com/20152487/73596164-37766f00-4520-11ea-8101-05a102bd6bdf.jpg) 13 | 14 | 15 | - You can use their Web app, for devices management, pairing, groups, scenes, events, ect ... https://phoscon.de/en/app/doc 16 | 17 | ![phoscon](https://user-images.githubusercontent.com/20152487/73598455-f3439880-4538-11ea-9c56-0fb18576a44b.png) 18 | 19 | 20 | - You can use too some android application like Hue essential compatible with deconz ... https://play.google.com/store/apps/dev?id=7433470895643453779 21 | 22 | ![hue](https://user-images.githubusercontent.com/20152487/189486132-bf16261f-e4d3-40c1-bc9e-23f909c2b166.png) 23 | 24 | 25 | - And use this plugin to bridge between the deCONZ server and domoticz. The plugin have now a Frontend for some actions (thx to @JayPearlman). To use it, just go in "Custom"/"DeCONZ". 26 | 27 | ![domoticz](https://user-images.githubusercontent.com/20152487/102008804-7e81e300-3d33-11eb-8ad4-5949f1eb189e.jpg) 28 | 29 | 30 | ## Requirement. 31 | deCONZ : Last version. 32 | Domoticz : current stable version. 33 | Python : You need the requests library, if you have error message like "Module Import failed: ' Name: requests'", you probably miss it, to install it just type: 34 | ``` 35 | sudo -H pip3 install requests 36 | sudo -H pip install requests 37 | ``` 38 | 39 | ## Installation. 40 | - With command line, go to your plugins directory (domoticz/plugins). 41 | - Run: 42 | ```git clone https://github.com/Smanar/Domoticz-deCONZ.git``` 43 | - (If needed) Make the plugin.py file executable: 44 | ```chmod +x Domoticz-deCONZ/plugin.py``` 45 | - Restart Domoticz. 46 | - Enable the plugin in hardware page (hardware page, select deconz plugin, click "update"). 47 | 48 | You can later update the plugin 49 | - With command line, go to the plugin directory (domoticz/plugin/Domoticz-deCONZ). 50 | - Run: 51 | ```git pull``` 52 | - Restart Domoticz. 53 | 54 | To test the beta branch : 55 | ``` 56 | git pull 57 | git checkout beta 58 | git pull 59 | ``` 60 | 61 | 62 | ## Configuration. 63 | - The plugin works better with websocketnotifyall option set to true (it's the configuration by default). 64 | ```curl -H 'Content-Type: application/json' -X PUT -d '{"websocketnotifyall": true}' http://IP_DECONZ:80/api/API_KEY/config``` 65 | - The plugin doesn't use a special configuration file, except the banned.txt file. 66 | - At every start, it synchronises the deCONZ network with yours domoticz devices, so if you delete a device, at next startup, it will be re-created, so to prevent that, you can put the adress in the banned.txt file. 67 | - If you have problem to find your IP or the used port, take a look at https://phoscon.de/discover (Remember better to use 127.0.0.1 if domoticz and deconz are on the same machine). 68 | - Don't worry about the name, the plugin never updates name even you change it in deCONZ to prevent problems with scripts. 69 | - If you create a group, it's not possible to identify the type of device they are inside, so the type will be by defaut RGBWWZ to have all options, if you want to create only a dimmer group for exemple add "_dim" at the group name. 70 | - For those who have problems with API Key, there is a file called API_KEY.py to help you to create/delete/get list with command line, informations and commands inside the file. It can also give some information like your used websocket port. To show all commands or parameters just use: 71 | ``` 72 | python3 API_KEY.py 73 | ``` 74 | If using default settings you might be able to obtain the API key using: 75 | ``` 76 | python3 API_KEY.py 127.0.0.1:80 create 77 | ``` 78 | And for those who don't know where to find the API key and don't wana use the tool: https://dresden-elektronik.github.io/deconz-rest-doc/getting_started/#acquire-an-api-key 79 | Or you can just use the Front End in Domoticz/Custom/Deconz. 80 | 81 | - By defaut the plugin use standard setting, you can use special one in the field "specials settings" on the hardware panel, available setting are : 82 | 83 | | Option | action | 84 | |--- |--- | 85 | | ENABLEMORESENSOR | enable tension and current sensors | 86 | | ENABLEBATTERYWIDGET | create a special widget by device just for battery | 87 | 88 | 89 | ## Remark. 90 | - There is a deconz Discord channel https://discord.gg/QFhTxqN 91 | 92 | - Take care if you have too many devices, at startup, the plugin adds ALL your devices from deCONZ in domoticz (except those who are in banned file). 93 | 94 | - Finally, you can see more devices than you have in reality. This is normal, deCONZ can create more than 1 device for 1 real, and it can create for example 1 bulb + 2 switches just for 1 physical switch. 95 | 96 | - If you haven't github acount, the support in domoticz forum is here https://www.domoticz.com/forum/viewtopic.php?f=68&t=25631 97 | 98 | - You can't use the native function in domoticz for switch (activation devices), because this plugin trigger device event for useless information, like battery level. So instead of using trigger event, you need to use button detected. You have some LUA examples here : [Use LUA for switch](https://github.com/Smanar/Domoticz-deCONZ/wiki/Examples-to-use-LUA-script-for-switch). 99 | 100 | - You have some others examples here : 101 | >[Some LUA examples for sensors](https://github.com/Smanar/Domoticz-deCONZ/wiki/Examples-to-use-LUA-script-for-various-sensors). 102 | [Using LUA to change setting on the fly](https://github.com/Smanar/Domoticz-deCONZ/wiki/Examples-to-use-LUA-to-change-setting-on-the-fly.). 103 | [Create a color loop effect with zigbee bulb](https://github.com/Smanar/Domoticz-deCONZ/wiki/Example-to-make-a-color-loop-effect). 104 | [Mix temperature/humidity/barometer on the same sensor](https://github.com/Smanar/Domoticz-deCONZ/wiki/Example-to-make-a-LUA-script-to-mix-temperature-humidity-barometer-on-the-same-sensor). 105 | 106 | ## Known issues. 107 | - Don't take care about the error message 108 | ```Error: (deCONZ): Socket Shutdown Error: 9, Bad file descriptor``` 109 | I know where is the problem the problem, but I haven't find a way to avoid it, But it change nothing on working mode. 110 | 111 | - If you add devices or change devices name for example in Phoscon after the plugin have started, the plugin will de desynchronized, and you will have this kind of error message 112 | ```2018-12-29 20:49:32.807 Error: (deConz) Unknow MAJ{'name': 'TRÅDFRI Motion sensor', 'uniqueid': '00:0b:57:ff:xx:xx:xx:xx', 'id': '2', 'r': 'sensors', 't': 'event', 'e': 'changed'}``` 113 | or 114 | ```2018-12-29 20:54:04.979 (deConz) Banned device > 2 (sensors)``` 115 | To solve them, no need to reboot, just restart the plugin, it synchronises at every start. 116 | To restart plugin : Tab "Hardware" > select the hardware "deCONZ" then click "Update" 117 | - If your system doesn't support python "Request" lib, you can try older version < 1.0.9. 118 | 119 | ## Changelog. 120 | - 15/05/25 : 1.0.34 > Make custom page working again, improve Aqara Cube Pro T1 support, thx @Sumd84 . 121 | - 17/03/25 : 1.0.33 > Solve issue for air quality sensor again. 122 | - 20/10/24 : 1.0.32 > Solve issue during installation for dockers users (thx to @RneeJ), solve issue for air quality sensor. 123 | - 27/04/24 : 1.0.31 > Solve issue about "invalid literal", solve issue about CLIPDaylightOffset, solve issue if you use ENABLEBATTERYWIDGET. 124 | - 10/02/24 : 1.0.30 > Solve issue with "mode" widget for thermostat, improve air quality sensor support. 125 | - 28/10/23 : 1.0.29 > Add support for moisture sensor, add support for double consumption, add an error widget about deconz status. 126 | - 24/05/23 : 1.0.28 > Add support for New Xiaomi Cube T1/ T1 pro thx @Sumd84 , the widget created by the option "ENABLEBATTERYWIDGET" have now different icons according to batery level, thx @BabaIsYou , remove error about "capabilities". 127 | - 17/02/23 : 1.0.27 > Add special support for the Ikea Starkvind thx @arjannv , add support for the Alarm System, and the support for keypad, see https://github.com/Smanar/Domoticz-deCONZ/wiki/How-to-add-keypad-to-domoticz thx @BabaIsYou , add new option ENABLEBATTERYWIDGET ,remove "capabilities" error message. 128 | - 12/11/22 : 1.0.26 > Make the widget for covering work again, following the Domoticz update. Create a widget with consumption and power for some devices that are able to support it, (thx @BabaIsYou) 129 | - 10/09/22 : 1.0.25 > It's now possible to clean the unused API key used for Hue Essentials, add support for binary module, with the develco one, add "pulseconfiguration" as possible setting in the GUI, thx @Jemand . 130 | - Correct an issue for thermostat with "mode" not updated. 131 | - 08/05/22 : 1.0.24 > This version contain various correctives for consumption/power sensors. 132 | - 15/03/22 : 1.0.23 > Can create tension and current widget (need to be enabled in hardware panel), new path system for docker installation (to correct front end issue), Add new field in config, to be used as special setting later, somes change on covering support. 133 | - 29/12/21 : 1.0.22 > Add specific widget for the Ikea Styrbar, optimisation/update for covering, some devices correctives, thx to @veitk, @RDols and @sonar98. 134 | - 20/09/21 : 1.0.21 > Warning device use now a selector switch instead of a 2 position one, add some new value for ZGP switches, repair the front end to be able to set "0" value, add a tool to clean the API key list. 135 | - 03/07/21 : 1.0.20 > add primary support for ZHAAirQuality, repair of frontend, now it s possible again to configure device. 136 | - 15/06/21 : 1.0.19 > Make special widget for Tuya switches and philips RWL02 one. Starting to repair siren. Increase Websocket buffer to prevent message "Incomplete JSON keep it for later". Add the possibility to see the deconz config on the front-end. 137 | - 18/04/21 : 1.0.18 > Set light state to off if detected off line (thx @nonolk), starting to implement ZHADoorlock. 138 | - 14/03/21 : 1.0.17 > Grammar corrections, corrective for power sensor, can retreive raw data from Xiaomi cube (to get side), improve widget for extended color light, adding remote covering devices. 139 | - 13/12/20 : 1.0.16 > Correction to support Ally thermostat (@johnsprogs), the Xiaomi sensor return the 3 angles (@flopp999), the xiaomi cube can give complete information (@kispalsz ), Color correction for devices that don't support XY, the frontend (@JayPearlman), support of the Lidl Melinera Smart XMAS LED string lights (@sonar98), can specify type for group (@Plantje). 140 | - 01/08/20 : 1.0.15 > Better support for Friend of HUE device. Disable error message about the gateway. 141 | - 25/06/20 : 1.0.14 > Handle the new websocket "attr", special widget for Xiaomi Aqara single gang (thx to @markiboy2all). 142 | - 28/05/20 : 1.0.13 > Delete banned_devices.txt from github, it will be created by the plugin, create specific widget for Aquara Opple and Xiaomi double gang (thx to @eserero), critic bug correction for Xiaomi plug (thx to @xxLeoxx93). 143 | - 27/01/20 : 1.0.12 > Correction for some Philips hue, correction for thermostat devices, change consumption widget for some devices, remove domoticz batterie alert if device have bad return for battery level, patch for group with UniqueId. 144 | - 09/11/19 : 1.0.11 > All unknows devices will be recognized as on/off controler, because some working device have "Unknow" as type. Improving detection for fan and range extender. Adding Thermostat support (thx to @salopette). Adding support for long press on ikea remote. Reparation for Shutter control. 145 | - 23/08/19 : 1.0.10 > Add message information for missing requests lib, make special device for "Tradfri on/off_switch" (thx @erwan2345). The plugin can now add itself missing groups after the starting. Another division by zero correction. Patch for virtual devices with same UniqueId. 146 | - 20/06/19 : 1.0.9 > Compare database to check deleted devices. Code clean up. The plugin can now add itself missing devices after the starting. Trying to synchronise at start only if the gateway seem ready. Change request code (cf remark). Change Websocket code (thx @salopette). 147 | - 03/05/19 : 1.0.8 > Adding a tool to delete all useless key created everytime launching Phoscon. Setting Websocket port is now useless. Change switches icon for button instead of bulb. Prevent the system be freezed if the gateway don't answer at a request and using queue list for request to prevent collision. Adding scenes control.Adding some missing bulbs. 148 | - 14/04/19 : 1.0.7 > Special version, because of a problem in a feature I have make and a deconz version >= 2.05.62, bulb will be set to off just after set to on. 149 | - 07/04/19 : 1.0.6 > starting to implement vibration sensor/Carbonmonoxide sensor/Window covering/thermostat/door lock. Trying to correct bad JSON data on normal connexion. Enable timeout display for no rechables devices. Devices Units correction (thx @fswmlu). Corrections for initialisation device on plugin start and bug on banning groups (Thx @dobber81). 150 | - 04/03/19 : 1.0.5 > improve the case deCONZ is not on same machine than Domoticz. Groups reparation, now you can send for example a color level to a complete group with only 1 device. Device update modification, for fast event, like if you press a switch too fast. 151 | - 02/02/19 : 1.0.4 > Modification the way the plugin receive data. Decrease the device update amount, less logs, less notifications, but at least 1 update every 24h to see if the device is still alive. 152 | - 22/01/19 : 1.0.3 > Division by zero bug correction, adding some missing devices, and Xiaomi water leak update (thx to @stefan1957 and @AdamWeglarz) 153 | - 12/01/19 : 1.0.2 > Correction in the situation the user don't have a device category, for example, no bulbs. 154 | - 11/01/19 : 1.0.1 > First official version, The Xiaomi cube now use custom sensor for Rotation, it send now numeric value, so you can use it to vary a light or a volume speaker. 155 | -------------------------------------------------------------------------------- /fonctions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding: utf-8 -*- 3 | 4 | from struct import unpack 5 | import json 6 | 7 | #import DomoticzEx as Domoticz 8 | import Domoticz 9 | buffercommand = {} 10 | 11 | BOOLEAN_SENSOR = ['flag', 'water', 'fire', 'presence', 'carbonmonoxide', 'daylight', 'alarm', 'lock'] 12 | 13 | #**************************************************************************************************** 14 | # Global fonctions 15 | 16 | 17 | def get_JSON_payload(data): 18 | """Parse length of payload and return it.""" 19 | start = 2 20 | length = ord(data[1:2]) 21 | if length == 126: 22 | # Payload information are an extra 2 bytes. 23 | start = 4 24 | length, = unpack(">H", data[2:4]) 25 | elif length == 127: 26 | # Payload information are an extra 6 bytes. 27 | start = 8 28 | length, = unpack(">I", data[2:6]) 29 | end = start + length 30 | payload = json.loads(data[start:end].decode()) 31 | extra_data = data[end:] 32 | 33 | return payload, extra_data 34 | 35 | def DecodeByteArray(stringStreamIn): 36 | # Turn string values into opererable numeric byte values 37 | byteArray = [ord(character) for character in stringStreamIn] 38 | datalength = byteArray[1] & 127 39 | indexFirstMask = 2 40 | 41 | if datalength == 126: 42 | indexFirstMask = 4 43 | elif datalength == 127: 44 | indexFirstMask = 10 45 | 46 | indexFirstDataByte = indexFirstMask 47 | 48 | #Data are masked ? 49 | if byteArray[1] & 128: 50 | # Extract masks 51 | masks = [m for m in byteArray[indexFirstMask : indexFirstMask+4]] 52 | indexFirstDataByte = indexFirstDataByte + 4 53 | print (str(masks)) 54 | else: 55 | masks = [0,0,0,0] 56 | 57 | # List of decoded characters 58 | decodedChars = [] 59 | i = indexFirstDataByte 60 | j = 0 61 | 62 | # Loop through each byte that was received 63 | while i < len(byteArray): 64 | 65 | # Unmask this byte and add to the decoded buffer 66 | decodedChars.append( chr(byteArray[i] ^ masks[j % 4]) ) 67 | i += 1 68 | j += 1 69 | 70 | # Return the decoded string 71 | return ''.join(decodedChars).strip() 72 | 73 | def rgb_to_xy(rgb): 74 | ''' convert rgb tuple to xy tuple ''' 75 | red, green, blue = rgb 76 | r = ((red + 0.055) / (1.0 + 0.055))**2.4 if (red > 0.04045) else (red / 12.92) 77 | g = ((green + 0.055) / (1.0 + 0.055))**2.4 if (green > 0.04045) else (green / 12.92) 78 | b = ((blue + 0.055) / (1.0 + 0.055))**2.4 if (blue > 0.04045) else (blue / 12.92) 79 | X = r * 0.664511 + g * 0.154324 + b * 0.162028 80 | Y = r * 0.283881 + g * 0.668433 + b * 0.047685 81 | Z = r * 0.000088 + g * 0.072310 + b * 0.986039 82 | cx = 0 83 | cy = 0 84 | if (X + Y + Z) != 0: 85 | cx = X / (X + Y + Z) 86 | cy = Y / (X + Y + Z) 87 | return (cx, cy) 88 | 89 | def rgb_to_hsl(rgb): 90 | ''' convert rgb tuple to hls tuple ''' 91 | r, g, b = rgb 92 | r = float(r/255) 93 | g = float(g/255) 94 | b = float(b/255) 95 | high = max(r, g, b) 96 | low = min(r, g, b) 97 | h, s, l = ((high + low) / 2,)*3 98 | 99 | if high == low: 100 | h = 0.0 101 | s = 0.0 102 | else: 103 | d = high - low 104 | s = d / (2 - high - low) if l > 0.5 else d / (high + low) 105 | h = { 106 | r: (g - b) / d + (6 if g < b else 0), 107 | g: (b - r) / d + 2, 108 | b: (r - g) / d + 4, 109 | }[high] 110 | h /= 6 111 | 112 | return h, s, l 113 | 114 | def hsl_to_rgb(h, s, l): 115 | def hue_to_rgb(p, q, t): 116 | t += 1 if t < 0 else 0 117 | t -= 1 if t > 1 else 0 118 | if t < 1/6: return p + (q - p) * 6 * t 119 | if t < 1/2: return q 120 | if t < 2/3: p + (q - p) * (2/3 - t) * 6 121 | return p 122 | 123 | if s == 0: 124 | r, g, b = l, l, l 125 | else: 126 | q = l * (1 + s) if l < 0.5 else l + s - l * s 127 | p = 2 * l - q 128 | r = hue_to_rgb(p, q, h + 1/3) 129 | g = hue_to_rgb(p, q, h) 130 | b = hue_to_rgb(p, q, h - 1/3) 131 | 132 | return r, g, b 133 | 134 | def xy_to_rgb(x, y, brightness = 1): 135 | 136 | x = float(x) 137 | y = float(y) 138 | z = 1.0 - x - y; 139 | 140 | #Bad values 141 | if x == 0 or y == 0: 142 | return {'r': 0, 'g': 0, 'b': 0} 143 | 144 | Y = brightness 145 | X = (Y / y) * x 146 | Z = (Y / y) * z 147 | 148 | r = X * 1.656492 - Y * 0.354851 - Z * 0.255038; 149 | g = -X * 0.707196 + Y * 1.655397 + Z * 0.036152; 150 | b = X * 0.051713 - Y * 0.121364 + Z * 1.011530; 151 | 152 | r = 12.92 * r if r <= 0.0031308 else (1.0 + 0.055) * pow(r, (1.0 / 2.4)) - 0.055 153 | g = 12.92 * g if g <= 0.0031308 else (1.0 + 0.055) * pow(g, (1.0 / 2.4)) - 0.055 154 | b = 12.92 * b if b <= 0.0031308 else (1.0 + 0.055) * pow(b, (1.0 / 2.4)) - 0.055 155 | 156 | if (r > b) and (r > g): 157 | if (r > 1.0): 158 | g = g / r 159 | b = b / r 160 | r = 1.0 161 | 162 | elif (g > b) and (g > r): 163 | if (g > 1.0): 164 | r = r / g 165 | b = b / g 166 | g = 1.0 167 | 168 | elif (b > r) and (b > g): 169 | if (b > 1.0): 170 | r = r / b 171 | g = g / b 172 | b = 1.0 173 | 174 | return {'r': int(r * 255), 'g': int(g * 255), 'b': int(b * 255)} 175 | 176 | 177 | def rgb_to_hsv(rgb): 178 | ''' convert rgb tuple to hls tuple ''' 179 | r, g, b = rgb 180 | r = float(r/255) 181 | g = float(g/255) 182 | b = float(b/255) 183 | high = max(r, g, b) 184 | low = min(r, g, b) 185 | h, s, v = high, high, high 186 | 187 | d = high - low 188 | s = 0 if high == 0 else d/high 189 | 190 | if high == low: 191 | h = 0.0 192 | else: 193 | h = { 194 | r: (g - b) / d + (6 if g < b else 0), 195 | g: (b - r) / d + 2, 196 | b: (r - g) / d + 4, 197 | }[high] 198 | h /= 6 199 | 200 | return h, s, v 201 | 202 | 203 | def hsv_to_rgb(h, s, v): 204 | i = math.floor(h*6) 205 | f = h*6 - i 206 | p = v * (1-s) 207 | q = v * (1-f*s) 208 | t = v * (1-(1-f)*s) 209 | 210 | r, g, b = [ 211 | (v, t, p), 212 | (q, v, p), 213 | (p, v, t), 214 | (p, q, v), 215 | (t, p, v), 216 | (v, p, q), 217 | ][int(i%6)] 218 | 219 | return r, g, b 220 | 221 | 222 | def Count_Type(d): 223 | b = l = s = g = o = c = 0 224 | for i in d: 225 | if d[i]['type'] == 'lights': 226 | l += 1 227 | elif d[i]['type'] == 'sensors': 228 | s += 1 229 | elif d[i]['type'] == 'groups': 230 | g += 1 231 | elif d[i]['type'] == 'scenes': 232 | c += 1 233 | else: 234 | o += 1 235 | 236 | if d[i].get('state','unknow') == 'banned': 237 | b += 1 238 | return l,s,g,b,o,c 239 | 240 | def First_Json(data): 241 | s = '' 242 | b = 0 243 | for c in data: 244 | s += c 245 | if c == '{': 246 | b += 1 247 | if c == '}': 248 | b -= 1 249 | if b == 0: 250 | return s 251 | return False 252 | 253 | def JSON_Repair(data): 254 | s = e = p = 0 255 | c = 0 256 | b = '' 257 | 258 | while True: 259 | if c == 0: 260 | p = data.find('[',p) 261 | s = p 262 | else: 263 | p = data.find(']',p) 264 | e = p 265 | c = 1 - c 266 | if p == -1: 267 | break 268 | 269 | if e > s: 270 | if len(b) > 0: 271 | b += ',' 272 | b += data[s + 1:e] 273 | 274 | return '[' + b + ']' 275 | 276 | 277 | 278 | #********************************* 279 | # Table for switch 280 | # 281 | #********************************* 282 | 283 | DevelcoModuleTable = ['1003','1001'] 284 | 285 | XiaomiSingleGangButtonSwitchTable = ['1002','1004','1001'] 286 | 287 | XiaomiDoubleGangButtonSwitchTable = ['1002','2002','3002','1004','2004','3004','1001','2001','3001'] 288 | 289 | IkeaStyrbarButtonSwitchTable = ['1001','1002','1003','2001','2002','2003','3001','3002','3003','4001','4002','4003','5001','5002','5003'] 290 | 291 | 292 | #0 - Off 293 | #single press 294 | #10 - B1 - 1002 295 | #20 - B2 - 2002 296 | #30 - B3 - 3002 297 | #40 - B4 - 4002 298 | #50 - B5 - 5002 299 | #60 - B6 - 6002 300 | #long press 301 | #70 - B1L - 1001 302 | #80 - B2L - 2001 303 | #90 - B3L - 3001 304 | #100 - B4L - 4001 305 | #110 - B5L - 5001 306 | #120 - B6L - 6001 307 | #release afer long press (not working for some reason) 308 | #130 - B1RL - 1003 309 | #140 - B2RL - 2003 310 | #150 - B3RL - 3003 311 | #160 - B4RL - 4003 312 | #170 - B5RL - 5003 313 | #180 - B6RL - 6003 314 | #double press 315 | #190 - B1D - 1004 316 | #200 - B2D - 2004 317 | #210 - B3D - 3004 318 | #220 - B4D - 4004 319 | #230 - B5D - 5004 320 | #240 - B6D - 6004 321 | #tripple press 322 | #250 - B1T - 1005 323 | #260 - B2T - 2005 324 | #270 - B3T - 3005 325 | #280 - B4T - 4005 326 | #290 - B5T - 5005 327 | #300 - B6T - 6005 328 | XiaomiOpple6ButtonSwitchTable = ['1002','2002','3002','4002','5002','6002','1001','2001','3001','4001','5001','6001','1003','2003','3003','4003','5003','6003', 329 | '1004','2004','3004','4004','5004','6004','1005','2005','3005','4005','5005','6005'] 330 | 331 | TuyaXGangButtonSwitchTable = ['1002','1003','1004','2002','2003','2004','3002','3003','3004','4002','4003','4004'] 332 | 333 | PhilipsRWL02ButtonSwitchTable = ['1002','1003','2002','2003','3002','3003','4002','4003'] 334 | 335 | #************************************************************************************************** 336 | # Domoticz fonctions 337 | # 338 | #https://github.com/dresden-elektronik/deconz-rest-plugin/wiki/Supported-Devices 339 | 340 | def ProcessAllConfig(data,model,option): 341 | kwarg = {} 342 | 343 | buffercommand.clear() 344 | 345 | if 'battery' in data: 346 | kwarg.update(ReturnUpdateValue( 'battery' , data['battery'] ) ) 347 | if 'heatsetpoint' in data: 348 | kwarg.update(ReturnUpdateValue( 'heatsetpoint' , data['heatsetpoint'] ) ) 349 | if 'mode' in data: 350 | #if not (data['mode'] == 'off' and data['on'] == True): 351 | kwarg.update(ReturnUpdateValue( 'mode' , data['mode'] , model ) ) 352 | if 'preset' in data: 353 | kwarg.update(ReturnUpdateValue( 'preset' , data['preset'] ) ) 354 | if 'lock' in data: 355 | kwarg.update(ReturnUpdateValue( 'lock' , data['lock'] ) ) 356 | 357 | if 'reachable' in data: 358 | if data['reachable'] == False: 359 | kwarg.update({'TimedOut':1}) 360 | 361 | return kwarg 362 | 363 | def ProcessAllState(data,model,option): 364 | # Lux need to be > lightlevel > daylight > dark 365 | # xy > ct > bri > on/off 366 | # consumption > power 367 | # status > daylight > all 368 | # alert need to be first, bcause less important than other 369 | 370 | buffercommand.clear() 371 | 372 | kwarg = {} 373 | 374 | if 'alert' in data: 375 | kwarg.update(ReturnUpdateValue('alert', data['alert'], model)) 376 | if 'status' in data: 377 | kwarg.update(ReturnUpdateValue('status', data['status'])) 378 | if 'measured_value' in data: 379 | kwarg.update(ReturnUpdateValue('airqualityppb', data['measured_value'], option)) 380 | if 'pm2_5' in data: 381 | kwarg.update(ReturnUpdateValue('airqualityppb', data['pm2_5'], option)) 382 | if 'on' in data: 383 | kwarg.update(ReturnUpdateValue('on', data['on'], model)) 384 | if 'x' in data: 385 | kwarg.update(ReturnUpdateValue('x', data['x'])) 386 | if 'y' in data: 387 | kwarg.update(ReturnUpdateValue('y', data['y'])) 388 | if 'xy' in data: 389 | kwarg.update(ReturnUpdateValue('xy', data['xy'])) 390 | if 'ct' in data: 391 | kwarg.update(ReturnUpdateValue('ct', data['ct'])) 392 | if 'temperature' in data: 393 | kwarg.update(ReturnUpdateValue('temperature', data['temperature'])) 394 | if 'pressure' in data: 395 | kwarg.update(ReturnUpdateValue('pressure', data['pressure'])) 396 | if 'humidity' in data: 397 | kwarg.update(ReturnUpdateValue('humidity', data['humidity'])) 398 | if 'moisture' in data: 399 | kwarg.update(ReturnUpdateValue('moisture', data['moisture'])) 400 | if 'open' in data: 401 | kwarg.update(ReturnUpdateValue('open', data['open'])) 402 | if 'presence' in data: 403 | kwarg.update(ReturnUpdateValue('presence', data['presence'])) 404 | if 'daylight' in data: 405 | kwarg.update(ReturnUpdateValue('daylight', data['daylight'])) 406 | #if 'lightlevel' in data: 407 | # kwarg.update(ReturnUpdateValue('lightlevel', data['lightlevel'])) 408 | if 'lux' in data: 409 | kwarg.update(ReturnUpdateValue('lux', data['lux'])) 410 | if 'power' in data: 411 | kwarg.update(ReturnUpdateValue('power', data['power'])) 412 | if 'consumption' in data: 413 | kwarg.update(ReturnUpdateValue('consumption', data['consumption'], option)) 414 | if 'battery' in data: 415 | kwarg.update(ReturnUpdateValue('battery', data['battery'])) 416 | if 'buttonevent' in data: 417 | kwarg.update(ReturnUpdateValue('buttonevent', data['buttonevent'])) 418 | if 'flag' in data: 419 | kwarg.update(ReturnUpdateValue('flag', data['flag'])) 420 | if 'water' in data: 421 | kwarg.update(ReturnUpdateValue('water', data['water'])) 422 | if 'fire' in data: 423 | kwarg.update(ReturnUpdateValue('fire', data['fire'])) 424 | if 'alarm' in data: 425 | kwarg.update(ReturnUpdateValue('alarm', data['alarm'])) 426 | if 'carbonmonoxide' in data: 427 | kwarg.update(ReturnUpdateValue('carbonmonoxide', data['carbonmonoxide'])) 428 | if 'lockstate' in data: 429 | kwarg.update(ReturnUpdateValue('lockstate', data['lockstate'])) 430 | if 'airqualityppb' in data: 431 | kwarg.update(ReturnUpdateValue('airqualityppb', data['airqualityppb'])) 432 | if 'bri' in data: 433 | kwarg.update(ReturnUpdateValue('bri', data['bri'], model) ) 434 | if 'lift' in data: 435 | kwarg.update(ReturnUpdateValue('lift', data['lift'], model) ) 436 | if 'voltage' in data: 437 | kwarg.update(ReturnUpdateValue( 'voltage' , data['voltage'], model) ) 438 | if 'current' in data: 439 | kwarg.update(ReturnUpdateValue( 'current' , data['current'], model ) ) 440 | if 'action' in data: 441 | kwarg.update(ReturnUpdateValue( 'action' , data['action'], model ) ) 442 | if 'speed' in data: 443 | kwarg.update(ReturnUpdateValue( 'speed' , data['speed'], model ) ) 444 | if 'expectedrotation' in data: 445 | kwarg.update(ReturnUpdateValue( 'expectedrotation' , data['expectedrotation'], model ) ) 446 | #if 'lastupdated' in data: 447 | # kwarg.update(ReturnUpdateValue('lastupdated', data['lastupdated'])) 448 | 449 | #For groups 450 | if 'all_on' in data: 451 | kwarg.update(ReturnUpdateValue('all_on', data['all_on'])) 452 | if 'any_on' in data: 453 | kwarg.update(ReturnUpdateValue('any_on', data['any_on'])) 454 | 455 | #Special 456 | if 'reachable' in data: 457 | if data['reachable'] == False: 458 | kwarg.update({'TimedOut':1}) 459 | 460 | return kwarg 461 | 462 | def ReturnUpdateValue(command, val ,option = None): 463 | 464 | if not val: 465 | val = 0 466 | 467 | val = str(val) 468 | command = str(command) 469 | 470 | kwarg = {} 471 | 472 | #operator 473 | if command == 'on': 474 | if val == 'True': 475 | kwarg['nValue'] = 1 476 | if option == 'Window covering device': 477 | kwarg['sValue'] = '100' 478 | else: 479 | kwarg['sValue'] = 'on' 480 | else: 481 | kwarg['nValue'] = 0 482 | if option == 'Window covering device': 483 | kwarg['sValue'] = '0' 484 | else: 485 | kwarg['sValue'] = 'off' 486 | 487 | if command == 'alert': 488 | #Can be none, lselect, select, blink 489 | if val == 'select': 490 | kwarg['nValue'] = 10 491 | kwarg['sValue'] = '10' 492 | elif val == 'lselect': 493 | kwarg['nValue'] = 20 494 | kwarg['sValue'] = '20' 495 | elif val == 'blink': 496 | kwarg['nValue'] = 30 497 | kwarg['sValue'] = '30' 498 | else: 499 | kwarg['nValue'] = 0 500 | kwarg['sValue'] = 'Off' 501 | 502 | if command == 'lift': 503 | val = int(val) 504 | if val <= 0: 505 | kwarg['sValue'] = '0' 506 | kwarg['nValue'] = 0 507 | elif val >= 100: 508 | kwarg['sValue'] = '100' 509 | kwarg['nValue'] = 1 510 | else: 511 | kwarg['sValue'] = str(val) 512 | kwarg['nValue'] = 2 513 | 514 | if command == 'bri': 515 | #kwarg['nValue'] = 1 516 | val = int(float(val) * 100 / 255 ) 517 | if option == 'Window covering device': 518 | if val < 2: 519 | kwarg['sValue'] = '0' 520 | kwarg['nValue'] = 0 521 | elif val > 99: 522 | kwarg['sValue'] = '100' 523 | kwarg['nValue'] = 1 524 | else: 525 | kwarg['sValue'] = str(val) 526 | kwarg['nValue'] = 2 527 | else: 528 | kwarg['sValue'] = str(val) 529 | 530 | if command == 'x' or command == 'y': 531 | buffercommand[command] = val 532 | if buffercommand.get('x') and buffercommand.get('y'): 533 | rgb = xy_to_rgb(int(buffercommand['x'])/65536.0,int(buffercommand['y'])/65536.0,1) 534 | kwarg['Color'] = '{"b":' + str(rgb['b']) + ',"cw":0,"g":' + str(rgb['g']) + ',"m":3,"r":' + str(rgb['r']) + ',"t":0,"ww":0}' 535 | buffercommand.clear() 536 | 537 | if command == 'xy': 538 | x,y = eval(str(val)) 539 | rgb = xy_to_rgb(x,y,1) 540 | #kwarg['nValue'] = 1 541 | #kwarg['sValue'] = str(255) 542 | kwarg['Color'] = '{"b":' + str(rgb['b']) + ',"cw":0,"g":' + str(rgb['g']) + ',"m":3,"r":' + str(rgb['r']) + ',"t":0,"ww":0}' 543 | 544 | if command == 'ct': 545 | #Correct values are from 153 (6500K) up to 588 (1700K) so uselss if < 1 546 | if int(val) > 1: 547 | ct = 1000000 // int(val) 548 | ct = -((ct - 1700) / ((6500.0-1700.0)/255.0) - 255 ) 549 | ct = int(ct) 550 | if ct < 0: 551 | ct = 0 552 | if ct > 255: 553 | ct = 255 554 | #kwarg['nValue'] = 1 555 | #kwarg['sValue'] = str(255) 556 | if not 'Color' in kwarg: 557 | kwarg['Color'] = '{"m":2,"r":0,"g":0,"b":0,"t":' + str(ct) + ',"ww":' + str(ct) + ',"cw":' + str(255 - ct) + '}' 558 | 559 | #groups 560 | if command == 'all_on' or command == 'any_on': 561 | if val == 'True': 562 | kwarg['nValue'] = 1 563 | kwarg['sValue'] = 'on' 564 | else: 565 | kwarg['nValue'] = 0 566 | kwarg['sValue'] = 'off' 567 | 568 | #sensor 569 | if command == 'open': 570 | if val == 'True': 571 | kwarg['nValue'] = 1 572 | kwarg['sValue'] = 'Open' 573 | else: 574 | kwarg['nValue'] = 0 575 | kwarg['sValue'] = 'Closed' 576 | 577 | if command == 'lockstate': 578 | if val == 'locked': 579 | kwarg['nValue'] = 0 580 | kwarg['sValue'] = 'Closed' 581 | else: 582 | kwarg['nValue'] = 1 583 | kwarg['sValue'] = 'Open' 584 | 585 | if command in BOOLEAN_SENSOR: 586 | if val == 'True': 587 | kwarg['nValue'] = 1 588 | kwarg['sValue'] = 'On' 589 | else: 590 | kwarg['nValue'] = 0 591 | kwarg['sValue'] = 'Off' 592 | 593 | if command == 'temperature': 594 | kwarg['nValue'] = 0 595 | val = round(float(val) / 100, 2 ) 596 | kwarg['sValue'] = str(val) 597 | 598 | if command == 'heatsetpoint': 599 | val = round( int(val) / 100, 2 ) 600 | #ignore boost and off value 601 | if val != 5 and val != 30: 602 | kwarg['heatsetpoint'] = str(val) 603 | 604 | if command == 'mode': 605 | if val == 'off': 606 | kwarg['mode'] = 0 607 | if option == 'ZHAAirPurifier': 608 | #ventilator 609 | if val == 'auto': 610 | kwarg['mode'] = 10 611 | if val == 'speed_1': 612 | kwarg['mode'] = 20 613 | if val == 'speed_2': 614 | kwarg['mode'] = 30 615 | if val == 'speed_3': 616 | kwarg['mode'] = 40 617 | if val == 'speed_4': 618 | kwarg['mode'] = 50 619 | if val == 'speed_5': 620 | kwarg['mode'] = 26 621 | else: 622 | #thermostat 623 | if val == 'heat': 624 | kwarg['mode'] = 10 625 | if val == 'auto': 626 | kwarg['mode'] = 20 627 | 628 | if command == 'preset': 629 | if val == 'off': 630 | kwarg['preset'] = 0 631 | if val == 'holiday': 632 | kwarg['preset'] = 10 633 | if val == 'auto': 634 | kwarg['preset'] = 20 635 | if val == 'manual': 636 | kwarg['preset'] = 30 637 | if val == 'comfort': 638 | kwarg['preset'] = 40 639 | if val == 'eco': 640 | kwarg['preset'] = 50 641 | if val == 'boost': 642 | kwarg['preset'] = 60 643 | if val == 'complex': 644 | kwarg['preset'] = 70 645 | if val == 'program': 646 | kwarg['preset'] = 80 647 | 648 | if command == 'status': 649 | if int(float(val)) == 0: 650 | kwarg['nValue'] = 0 651 | kwarg['sValue'] = str(val) 652 | else: 653 | kwarg['nValue'] = 1 654 | kwarg['sValue'] = str(val) 655 | 656 | if command == 'pressure': 657 | val = int(float(val)) 658 | if val < 1000: 659 | Bar_forecast = 4 660 | elif val < 1020: 661 | Bar_forecast = 3 662 | elif val < 1030: 663 | Bar_forecast = 2 664 | else: 665 | Bar_forecast = 1 666 | kwarg['nValue'] = 0 667 | kwarg['sValue'] = str(val) + ';' + str(Bar_forecast) 668 | 669 | # 0=Normal, 1=Comfortable, 2=Dry, 3=Wet 670 | if command == 'humidity': 671 | val = int(float(val) / 100) 672 | kwarg['nValue'] = val 673 | if val <= 40: 674 | kwarg['sValue'] = '2' 675 | elif val<=70: 676 | kwarg['sValue'] = '1' 677 | else: 678 | kwarg['sValue'] = '3' 679 | 680 | if command == 'moisture': 681 | val = int(float(val) / 100) 682 | # Val is a value 0 to 100, need to be converted in 0 to 200 683 | #00 - 09 = saturated 684 | #10 - 19 = adequately wet 685 | #20 - 59 = irrigation advice 686 | #60 - 99 = irrigation 687 | #100-200 = Dangerously dry 688 | 689 | kwarg['nValue'] = (100-val) * 2 690 | 691 | if (command == 'lightlevel') or (command == 'lux'): 692 | kwarg['nValue'] = 0 693 | kwarg['sValue'] = str(val) 694 | 695 | if command == 'voltage': 696 | kwarg['voltage'] = int(val) 697 | 698 | if command == 'current': 699 | kwarg['current'] = int(val) 700 | 701 | if command == 'airqualityppb': 702 | kwarg['sValue'] = str(float(val)) 703 | kwarg['nValue'] = int(float(val)) 704 | 705 | if command == 'action': 706 | kwarg['nValue'] = 0 707 | kwarg['sValue'] = str(val) 708 | 709 | if command == 'speed': 710 | kwarg['nValue'] = 0 711 | kwarg['sValue'] = str(val) 712 | 713 | if command == 'consumption_2': 714 | buffercommand['consumption_2'] = round(float(val) * 1, 3) 715 | 716 | if command == 'consumption': 717 | #Wh to Kwh 718 | kwh = round(float(val) * 1, 3) 719 | #Device with power and comsuption 720 | if option == 1: 721 | if buffercommand.get('power'): 722 | p = buffercommand['power'] 723 | buffercommand.clear() 724 | kwarg['nValue'] = 0 725 | kwarg['sValue'] = str(p) + ';' + str(kwh) 726 | #device with only consumption 727 | elif option == 0: 728 | kwarg['nValue'] = 0 729 | kwarg['sValue'] = str(kwh) 730 | #Device with consumption_2 731 | else: 732 | if buffercommand.get('consumption_2'): 733 | p = buffercommand['consumption_2'] 734 | buffercommand.clear() 735 | kwarg['nValue'] = 0 736 | kwarg['sValue'] = str(kwh) + ';' + str(p) + ';0;0;0;0' 737 | 738 | if command == 'power': 739 | buffercommand['power'] = val 740 | kwarg['nValue'] = 0 741 | kwarg['sValue'] = str(val) 742 | 743 | if command == 'expectedrotation': 744 | kwarg['nValue'] = int(val) 745 | 746 | if kwarg['nValue'] == 0: 747 | kwarg['sValue'] = 'Off' 748 | else: 749 | kwarg['sValue'] = str( kwarg['nValue'] ) 750 | 751 | 752 | #switch 753 | if command == 'buttonevent': 754 | kwarg['nValue'] = int(val) 755 | kwarg['sValue'] = str(val) 756 | 757 | # other 758 | if command == 'battery': 759 | if (not val.isdigit()) or (val == '0'): 760 | kwarg['BatteryLevel'] = 255 761 | else: 762 | kwarg['BatteryLevel'] = int(val) 763 | 764 | if command == 'xxxx': 765 | kwarg['SignalLevel'] = 100 766 | 767 | #if command == 'lastupdated': 768 | # kwarg['LastUpdate'] = val.replace('T',' ') 769 | 770 | return kwarg 771 | 772 | #https://github.com/dresden-elektronik/deconz-rest-plugin/issues/138 773 | def ButtonconvertionXCUBE_R(val): 774 | kwarg = {} 775 | 776 | kwarg['nValue'] = int(val) 777 | 778 | if kwarg['nValue'] == 0: 779 | kwarg['sValue'] = 'Off' 780 | else: 781 | kwarg['sValue'] = str( kwarg['nValue'] ) 782 | 783 | return kwarg 784 | 785 | def ButtonconvertionXCUBE(val): 786 | kwarg = {} 787 | val = str(val) 788 | v = 0 789 | 790 | if val == '7007':# shake 791 | v = 10 792 | elif val == '7000': # wake 793 | v = 20 794 | elif val == '7008':# drop 795 | v = 30 796 | elif int(val[3]) == (7 - int(val[0])) :# 180 flip 797 | v = 50 798 | elif val[1:] == '000':# push 799 | v = 60 800 | elif val[0] == val[3]:# double tap 801 | v = 70 802 | else:# 90 flip 803 | v = 40 804 | 805 | if v == 0: 806 | kwarg['sValue'] = 'Off' 807 | else: 808 | kwarg['sValue'] = str( v ) 809 | 810 | kwarg['nValue'] = int(val) 811 | 812 | return kwarg 813 | 814 | def ButtonconvertionXCUBET1(val, gesture): 815 | kwarg = {} 816 | gest = int(gesture) 817 | face = str(val) 818 | v = 0 819 | 820 | if gest == 0: # wake 821 | v = 20 822 | elif gest == 1: # shake 823 | v = 10 824 | elif gest == 2: # Drop 825 | v = 30 826 | elif gest == 3: # 90 flip 827 | v = 40 828 | elif gest == 4: # 180 flip 829 | v = 50 830 | elif gest == 5: # push 831 | v = 60 832 | elif gest == 6: # double tap 833 | v = 70 834 | else: # Unknown 835 | v = 0 836 | 837 | if v == 0: 838 | kwarg['sValue'] = 'Off' 839 | else: 840 | kwarg['sValue'] = str( v ) 841 | 842 | kwarg['nValue'] = v 843 | 844 | return kwarg 845 | 846 | def ButtonconvertionXCUBEPROT1(val, gesture): 847 | kwarg = {} 848 | gest = int(gesture) 849 | face = str(val) 850 | v = 0 851 | 852 | if gest == 0: # wake 853 | v = 70 854 | elif gest == 1: # shake 855 | v = 80 856 | elif gest == 2: # Free Fall 857 | v = 110 858 | elif gest == 3: # 90 flip 859 | v = int(face[0]) * 10 #add face up number 860 | elif gest == 4: # 180 flip 861 | v = int(face[0]) * 10 #add face up number 862 | elif gest == 5: # push 863 | v = 90 864 | elif gest == 6: # double tap 865 | v = 100 866 | else:# Unknown 867 | v = 0 868 | 869 | if v == 0: 870 | kwarg['sValue'] = 'Off' 871 | else: 872 | kwarg['sValue'] = str( v ) 873 | 874 | kwarg['nValue'] = v 875 | 876 | return kwarg 877 | 878 | # <=4002 >=5002 +=2002 -=3002 4001/5001/2001/3001 879 | def ButtonconvertionTradfriRemote(val): 880 | kwarg = {} 881 | val = str(val) 882 | 883 | if val == '1002' or val == 1001: 884 | kwarg['nValue'] = 10 885 | elif val == '2002': 886 | kwarg['nValue'] = 20 887 | elif val == '3002': 888 | kwarg['nValue'] = 30 889 | elif val == '4002': 890 | kwarg['nValue'] = 40 891 | elif val == '5002': 892 | kwarg['nValue'] = 50 893 | elif val == '2001': 894 | kwarg['nValue'] = 60 895 | elif val == '3001': 896 | kwarg['nValue'] = 70 897 | elif val == '4001': 898 | kwarg['nValue'] = 80 899 | elif val == '5001': 900 | kwarg['nValue'] = 90 901 | 902 | else: 903 | kwarg['nValue'] = 0 904 | 905 | if kwarg['nValue'] == 0: 906 | kwarg['sValue'] = 'Off' 907 | else: 908 | kwarg['sValue'] = str( kwarg['nValue'] ) 909 | 910 | return kwarg 911 | 912 | def ButtonconvertionTradfriSwitch(val): 913 | kwarg = {} 914 | val = str(val) 915 | 916 | if val == '1002': 917 | kwarg['nValue'] = 10 918 | elif val == '1003': 919 | kwarg['nValue'] = 20 920 | elif val == '2002': 921 | kwarg['nValue'] = 30 922 | elif val == '2003': 923 | kwarg['nValue'] = 40 924 | elif val == '3002': 925 | kwarg['nValue'] = 50 926 | elif val == '4002': 927 | kwarg['nValue'] = 60 928 | elif val == '5002': 929 | kwarg['nValue'] = 70 930 | else: 931 | kwarg['nValue'] = 0 932 | 933 | if kwarg['nValue'] == 0: 934 | kwarg['sValue'] = 'Off' 935 | else: 936 | kwarg['sValue'] = str( kwarg['nValue'] ) 937 | 938 | return kwarg 939 | 940 | def ButtonConvertion(val,model = 0): 941 | kwarg = {} 942 | 943 | kwarg['nValue'] = 0 944 | 945 | #Generic procedure 946 | if model == 0: 947 | 948 | v = 0 949 | Button_Number = 1 950 | e = int(val or 0) 951 | 952 | #Green power device 953 | if e < 1000: 954 | t = [(1,16),(2,17,32),(3,18,33),(4,34),(5,98),(6,99),(7,100),(8,101)] 955 | for i in range(len(t)): 956 | if e in t[i]: 957 | v = (i + 1) * 10 958 | break 959 | 960 | #Normal switch 961 | else: 962 | val = "%04d" % val 963 | Button_Number = val[0] 964 | Button_Action = val[3] 965 | 966 | if Button_Action == '2': # Release (after press) 967 | v = 10 968 | if Button_Action == '3': # Release (after hold) 969 | v = 20 970 | if Button_Action == '4': # Double press 971 | v = 30 972 | if Button_Action == '5': # Triple press 973 | v = 40 974 | if Button_Action == '6': # Quadruple press 975 | v = 50 976 | if Button_Action == '7': # shake 977 | v = 60 978 | 979 | kwarg['nValue'] = v * int(Button_Number) 980 | 981 | else: 982 | val = str(val) 983 | 984 | #Xaomi double gang 985 | if model == 1: 986 | if val in XiaomiDoubleGangButtonSwitchTable: 987 | kwarg['nValue'] = 10 * (1 + XiaomiDoubleGangButtonSwitchTable.index(val)) 988 | #Xaomi Opple 6 buttons 989 | if model == 2: 990 | if val in XiaomiOpple6ButtonSwitchTable: 991 | kwarg['nValue'] = 10 * (1 + XiaomiOpple6ButtonSwitchTable.index(val)) 992 | 993 | if model == 3: 994 | if val in XiaomiSingleGangButtonSwitchTable: 995 | kwarg['nValue'] = 10 * (1 + XiaomiSingleGangButtonSwitchTable.index(val)) 996 | 997 | #Tuya generic 998 | if model == 4: 999 | if val in TuyaXGangButtonSwitchTable: 1000 | kwarg['nValue'] = 10 * (1 + TuyaXGangButtonSwitchTable.index(val)) 1001 | 1002 | #Philips remote 1003 | if model == 5: 1004 | if val in PhilipsRWL02ButtonSwitchTable: 1005 | kwarg['nValue'] = 10 * (1 + PhilipsRWL02ButtonSwitchTable.index(val)) 1006 | 1007 | #Ikea Styrbar 1008 | if model == 6: 1009 | if val in IkeaStyrbarButtonSwitchTable: 1010 | kwarg['nValue'] = 10 * (1 + IkeaStyrbarButtonSwitchTable.index(val)) 1011 | 1012 | #Develco Module 1013 | if model == 7: 1014 | if val in DevelcoModuleTable: 1015 | kwarg['nValue'] = 10 * (1 + DevelcoModuleTable.index(val)) 1016 | 1017 | if kwarg['nValue'] == 0: 1018 | kwarg['sValue'] = 'Off' 1019 | else: 1020 | kwarg['sValue'] = str( kwarg['nValue'] ) 1021 | 1022 | return kwarg 1023 | 1024 | #https://github.com/dresden-elektronik/deconz-rest-plugin/issues/748 1025 | #For the moment only vibrations are working 1026 | def VibrationSensorConvertion(val_v,val_t, val_a): 1027 | 1028 | kwarg = {} 1029 | 1030 | v = 0 1031 | 1032 | if val_v == True: 1033 | v = 10 1034 | 1035 | kwarg['nValue'] = v 1036 | 1037 | if v == 0: 1038 | kwarg['sValue'] = 'Off' 1039 | else: 1040 | kwarg['sValue'] = str( kwarg['nValue'] ) 1041 | 1042 | if val_a: 1043 | kwarg['orientation'] = [ str(val_a), int (val_t or 0) ] 1044 | 1045 | return kwarg 1046 | 1047 | #************************************************************************************************** 1048 | # Front end fonctions 1049 | # 1050 | #************************************************************************************************** 1051 | 1052 | # Code templated from https://github.com/stas-demydiuk/domoticz-zigbee2mqtt-plugin 1053 | def installFE(source_path,templates_path): 1054 | 1055 | import os 1056 | from shutil import copy2 1057 | 1058 | source_path += 'frontend' 1059 | templates_path += 'www/templates' 1060 | 1061 | Domoticz.Status('Source path : ' + str(source_path)) 1062 | Domoticz.Status('Template path : ' + str(templates_path)) 1063 | 1064 | fs = False 1065 | 1066 | try: 1067 | fs = os.path.getsize(templates_path + '/deCONZ.html') 1068 | except: 1069 | pass 1070 | 1071 | #Domoticz.Status('File size : ' + str(fs)) 1072 | 1073 | if fs == 12382: 1074 | Domoticz.Status('Plugin custom pages in date') 1075 | return 1076 | 1077 | Domoticz.Status('Starting the installation of plugin custom page (' + str(fs) + ')...') 1078 | 1079 | try: 1080 | 1081 | Domoticz.Debug('Copying files from ' + source_path + ' to ' + templates_path) 1082 | 1083 | #if not (os.path.isdir(dst_plugin_path)): 1084 | # os.makedirs(dst_plugin_path) 1085 | 1086 | copy2(source_path + '/deCONZ.html', templates_path) 1087 | copy2(source_path + '/deCONZ.js', templates_path) 1088 | 1089 | Domoticz.Log('Installation of plugin custom page completed.') 1090 | except Exception as e: 1091 | Domoticz.Error('Error during the installation of plugin custom page') 1092 | Domoticz.Error(repr(e)) 1093 | 1094 | def uninstallFE(): 1095 | Domoticz.Status('Uninstalling plugin custom page...') 1096 | 1097 | from shutil import rmtree 1098 | 1099 | try: 1100 | templates_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../../www/templates') 1101 | dst_plugin_path = templates_path + '/deCONZ' 1102 | 1103 | Domoticz.Debug('Removing files from ' + templates_path) 1104 | 1105 | #if (os.path.isdir(dst_plugin_path)): 1106 | # rmtree(dst_plugin_path) 1107 | 1108 | if os.path.exists(templates_path + "/deCONZ.html"): 1109 | os.remove(templates_path + "/deCONZ.html") 1110 | 1111 | if os.path.exists(templates_path + "/deCONZ.js"): 1112 | os.remove(templates_path + "/deCONZ.js") 1113 | 1114 | Domoticz.Log('Uninstalled plugin custom page succesfully!') 1115 | except Exception as e: 1116 | Domoticz.Error('Error during uninstalling plugin custom page') 1117 | Domoticz.Error(repr(e)) 1118 | -------------------------------------------------------------------------------- /frontend/deCONZ.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 42 | 43 | 54 | 55 | 93 | 94 | 133 | 134 | 173 | 174 | 212 | 213 | 229 | 230 | 251 | 252 | 319 | -------------------------------------------------------------------------------- /frontend/deCONZ.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'app' 3 | ], 4 | 5 | function(app) { 6 | 7 | var renameDeviceModal = { 8 | templateUrl: 'app/deCONZ/RenameModal.html', 9 | controllerAs: '$ctrl', 10 | controller: function($scope, $rootScope, apiDeCONZ) { 11 | var $ctrl = this; 12 | 13 | $ctrl.isUnchanged = true; 14 | $ctrl.device = Object.assign($scope.device); 15 | $ctrl.myname = $ctrl.device.name 16 | $ctrl.renameDevice = function() { 17 | 18 | $ctrl.isSaving = true; 19 | 20 | // Make api call here 21 | payload = new Object() 22 | payload.name = $ctrl.myname 23 | JSONpayload = angular.toJson(payload) 24 | 25 | // console.log('Renaming -> ' + 'deviceclass: ' + $ctrl.device.deviceclass + '\nDevice ID: ' + $ctrl.device.id + '\nBody: ' + JSONpayload); 26 | 27 | apiDeCONZ.setDeCONZdata($ctrl.device.deviceclass, 'PUT', $ctrl.device.id, JSONpayload,'') 28 | .then(function() { 29 | // console.log('Device name updated') 30 | $scope.$emit("refreshDeCONZfunc", $ctrl.device.deviceclass); 31 | }) 32 | .then($scope.$close()) 33 | } 34 | } 35 | }; 36 | 37 | var includeDeviceModal = { 38 | templateUrl: 'app/deCONZ/IncludeModal.html', 39 | controllerAs: '$ctrl', 40 | controller: function($scope, $rootScope, apiDeCONZ) { 41 | var $ctrl = this; 42 | 43 | $ctrl.isUnchanged = true; 44 | $ctrl.device = Object.assign($scope.device); 45 | $ctrl.myname = "XX:XX:XX:XX:XX:XX:XX:XX-XX-XXXX" 46 | $ctrl.includeDevice = function() { 47 | 48 | $ctrl.isSaving = true; 49 | 50 | // Make api call here 51 | payload = new Object() 52 | JSONpayload = angular.toJson(payload) 53 | 54 | // console.log('Renaming -> ' + 'deviceclass: ' + $ctrl.device.deviceclass + '\nDevice ID: ' + $ctrl.device.id + '\nBody: ' + JSONpayload); 55 | 56 | apiDeCONZ.setDeCONZdata($ctrl.device.deviceclass, 'PUT', '1', JSONpayload,'device/' + $ctrl.myname) 57 | .then(function() { 58 | // console.log('Device name updated') 59 | $scope.$emit("refreshDeCONZfunc", $ctrl.device.deviceclass); 60 | }) 61 | .then($scope.$close()) 62 | } 63 | } 64 | }; 65 | 66 | var includeremDeviceModal = { 67 | templateUrl: 'app/deCONZ/IncluderemModal.html', 68 | controllerAs: '$ctrl', 69 | controller: function($scope, $rootScope, apiDeCONZ) { 70 | var $ctrl = this; 71 | 72 | $ctrl.isUnchanged = true; 73 | $ctrl.device = Object.assign($scope.device); 74 | $ctrl.myname = "XX:XX:XX:XX:XX:XX:XX:XX-XX-XXXX" 75 | $ctrl.includeremDevice = function() { 76 | 77 | $ctrl.isSaving = true; 78 | 79 | // Make api call here 80 | payload = new Object() 81 | payload.name = $ctrl.myname 82 | JSONpayload = angular.toJson(payload) 83 | 84 | // console.log('Renaming -> ' + 'deviceclass: ' + $ctrl.device.deviceclass + '\nDevice ID: ' + $ctrl.device.id + '\nBody: ' + JSONpayload); 85 | 86 | apiDeCONZ.setDeCONZdata($ctrl.device.deviceclass, 'DELETE', $ctrl.device.id, JSONpayload,'') 87 | .then(function() { 88 | // console.log('Device name updated') 89 | $scope.$emit("refreshDeCONZfunc", $ctrl.device.deviceclass); 90 | }) 91 | .then($scope.$close()) 92 | } 93 | } 94 | }; 95 | 96 | var configDeviceModal = { 97 | templateUrl: 'app/deCONZ/ConfigModal.html', 98 | controllerAs: '$ctrl', 99 | controller: function($scope, $rootScope, apiDeCONZ) { 100 | var $ctrl = this; 101 | 102 | $ctrl.isUnchanged = true; 103 | $ctrl.device = Object.assign($scope.device); 104 | $ctrl.myname = $ctrl.device.name 105 | $ctrl.deviceconfig = $ctrl.device.config 106 | let oldconfig = Object.assign({}, $ctrl.device.config); 107 | $ctrl.configDevice = function() { 108 | 109 | $ctrl.isSaving = true; 110 | 111 | // Make api call here 112 | payload = new Object() 113 | 114 | for (const [key, value] of Object.entries($ctrl.deviceconfig)) { 115 | if ( oldconfig[key] != value ) { 116 | newvalue = value 117 | if (!isNaN(newvalue)) 118 | { 119 | newvalue = parseInt(newvalue); 120 | } 121 | if(value[0] == "'") { newvalue = value.slice(1, -1);} 122 | if (newvalue == 'false') { newvalue = false; } 123 | if (newvalue == 'true') { newvalue = true; } 124 | payload[key] = newvalue; 125 | } 126 | } 127 | 128 | //payload.name = $ctrl.myname 129 | JSONpayload = angular.toJson(payload) 130 | 131 | console.log('Config -> ' + 'deviceclass: ' + $ctrl.device.deviceclass + '\nDevice ID: ' + $ctrl.device.id + '\nBody: ' + JSONpayload); 132 | 133 | apiDeCONZ.setDeCONZdata($ctrl.device.deviceclass, 'PUT', $ctrl.device.id, JSONpayload,'config') 134 | .then(function() { 135 | // console.log('Device setting updated') 136 | $scope.$emit("refreshDeCONZfunc", $ctrl.device.deviceclass); 137 | }) 138 | .then($scope.$close()) 139 | 140 | } 141 | } 142 | }; 143 | 144 | var deleteDeviceModal = { 145 | templateUrl: 'app/deCONZ/DeleteModal.html', 146 | controllerAs: '$ctrl', 147 | controller: function($scope, $rootScope, apiDeCONZ) { 148 | var $ctrl = this; 149 | 150 | $ctrl.device = Object.assign($scope.device); 151 | $ctrl.myname = $ctrl.device.name 152 | $ctrl.deleteDevice = function() { 153 | 154 | // Make api call here 155 | // console.log('Deleting -> ' + 'deviceclass: ' + $ctrl.device.deviceclass + '\nDevice ID: ' + $ctrl.device.id ); 156 | 157 | apiDeCONZ.setDeCONZdata($ctrl.device.deviceclass, 'DELETE', $ctrl.device.id,'') 158 | .then(function() { 159 | // console.log('Device deleted') 160 | $scope.$emit("refreshDeCONZfunc", $ctrl.device.deviceclass); 161 | }) 162 | .then($scope.$close()) 163 | 164 | $scope.$close() 165 | } 166 | } 167 | }; 168 | 169 | app.component('zzDeconzPlugin', { 170 | templateUrl: 'app/deCONZ/index.html', 171 | controller: deCONZController, 172 | }) 173 | 174 | app.component('zzDeconzPluginsTable', { 175 | bindings: { 176 | zigdevs: '<', 177 | onSelect: '&', 178 | onUpdate: '&' 179 | }, 180 | template: '
', 181 | controller: zzDeconzPluginsTableController, 182 | }); 183 | 184 | function deCONZController($uibModal, $scope, $location, apiDeCONZ) { 185 | 186 | var $ctrl = this 187 | $ctrl.refreshDeCONZ = refreshDeCONZ; 188 | $ctrl.permitJoins = permitJoins; 189 | $ctrl.autoConfPlugin = autoConfPlugin; 190 | 191 | $ctrl.$onInit = function() { 192 | refreshDeCONZ('lights'); 193 | } 194 | 195 | $scope.$on("refreshDeCONZfunc", function (evt, data) { 196 | refreshDeCONZ(data); 197 | }); 198 | 199 | function refreshDeCONZ(deviceClass) { 200 | apiDeCONZ.getDeCONZdata(deviceClass).then(function(zigdevs) { 201 | // console.log('Returned Data Zigbee Devices') 202 | $ctrl.zigdevs = Object.values(zigdevs) 203 | $ctrl.value = deviceClass 204 | 205 | }) 206 | } 207 | 208 | function permitJoins(seconds = 60) { 209 | var JSONpayload 210 | 211 | $ctrl.isJoining = true; 212 | 213 | payload = new Object() 214 | payload.permitjoin = seconds 215 | JSONpayload = angular.toJson(payload) 216 | 217 | apiDeCONZ.setDeCONZdata('config', 'PUT', '', JSONpayload,'').then(function() { 218 | // console.log('Permit Join activated') 219 | }) 220 | .then($uibModal.open({ 221 | templateUrl: 'app/deCONZ/PermitJoinsModal.html', 222 | controllerAs: '$mctrl', 223 | controller: function($scope, $interval, apiDeCONZ) { 224 | var $mctrl = this; 225 | 226 | $scope.countdown = seconds; 227 | 228 | var timer = $interval(function () { 229 | if ($scope.countdown > 0){ 230 | $scope.countdown--; 231 | } else { 232 | $ctrl.isJoining = false; 233 | $interval.cancel(timer); 234 | // console.log('Countdown end') 235 | apiDeCONZ.getDeCONZdata($ctrl.value).then(function(zigdevs) { 236 | // console.log('Returned Zigbee device data') 237 | $ctrl.zigdevs = Object.values(zigdevs) 238 | }); 239 | $scope.$close(); 240 | } 241 | }, 1000); 242 | 243 | $mctrl.endPermit = function() { 244 | 245 | // console.log('End Permit') 246 | 247 | payload = new Object() 248 | payload.permitjoin = 0 249 | JSONpayload = angular.toJson(payload) 250 | 251 | apiDeCONZ.setDeCONZdata('config', 'PUT', '', JSONpayload,'').then(function() { 252 | // console.log('Permit Join de-activated') 253 | }) 254 | .then(apiDeCONZ.getDeCONZdata($ctrl.value).then(function(zigdevs) { 255 | // console.log('Returned Zigbee device data') 256 | $ctrl.zigdevs = Object.values(zigdevs) 257 | })) 258 | 259 | $ctrl.isJoining = false; 260 | 261 | $scope.$close(); 262 | } 263 | } 264 | }) 265 | ); 266 | } 267 | 268 | function autoConfPlugin() { 269 | let configOutput 270 | 271 | apiDeCONZ.checkDeCONZsetup() 272 | .then(configOutput => $uibModal.open({ 273 | templateUrl: 'app/deCONZ/autoConfPluginModal.html', 274 | controllerAs: '$mctrl', 275 | controller: function($scope, $interval, apiDeCONZ) { 276 | var $mctrl = this; 277 | 278 | $scope.apiShowGet = true 279 | 280 | $scope.apiCancelButton = $.t('Cancel') 281 | 282 | $scope.configOutput = angular.fromJson(configOutput) 283 | 284 | $mctrl.getAPIkey = function() { 285 | 286 | payload = new Object() 287 | payload.devicetype = "domoticz_deconz" 288 | JSONpayload = angular.toJson(payload) 289 | 290 | apiDeCONZ.postDeCONZdata(configOutput[0].internalipaddress, configOutput[0].internalport, 'api', JSONpayload, $mctrl.gwPassword).then(function(response) { 291 | // console.log('Response was: ' + angular.toJson(response, true)) 292 | if ("success" in response[0]) { 293 | response[0].API_KEY = response[0].success.username 294 | delete response[0].success; 295 | $scope.apiShowGet = false 296 | $scope.apiCancelButton = $.t('Close') 297 | } 298 | 299 | $scope.configOutput1 = response 300 | }) 301 | } 302 | 303 | $mctrl.setcode0 = function() { 304 | 305 | payload = new Object() 306 | payload.code0 = $mctrl.gwPassword 307 | JSONpayload = angular.toJson(payload) 308 | apiDeCONZ.setDeCONZdata('alarmsystems', 'PUT', "1", JSONpayload,'config').then(function(response) { 309 | // console.log('Response was: ' + angular.toJson(response, true)) 310 | if ("success" in response[0]) { 311 | response[0].Response = "Code 0 Updated" 312 | delete response[0].success; 313 | $scope.apiShowGet = false 314 | $scope.apiCancelButton = $.t('Close') 315 | } 316 | 317 | $scope.configOutput1 = response 318 | }) 319 | } 320 | 321 | $mctrl.cleanAPIkey = function() { 322 | 323 | payload = new Object() 324 | payload.devicetype = "domoticz_deconz" 325 | key_list = {} 326 | 327 | apiDeCONZ.getDeCONZdata("config").then(function(response) { 328 | // console.log('Returned Data Zigbee Devices') 329 | key_list = angular.toJson(response, true) 330 | key_list = response["whitelist"] 331 | 332 | 333 | for(var k in key_list) { 334 | if ((key_list[k]["name"].indexOf("Phoscon#") != -1) || 335 | (key_list[k]["name"].indexOf("deCONZ WebApp") != -1) || 336 | (key_list[k]["name"].indexOf("Hue Essentials#") != -1) || 337 | (key_list[k]["name"].indexOf("homebridge-hue#") != -1)) 338 | { 339 | apiDeCONZ.setDeCONZdata('config/whitelist/' + k, 'DELETE', '', '','').then(function() { 340 | //console.log('Delete API Key : ' + k ) 341 | }) 342 | } 343 | } 344 | 345 | }) 346 | 347 | } 348 | 349 | $mctrl.ConfPlugin = function() { 350 | 351 | payload = new Object() 352 | payload.devicetype = "domoticz_deconz" 353 | //JSONpayload = angular.toJson(payload) 354 | 355 | apiDeCONZ.getDeCONZdata("config").then(function(response) { 356 | // console.log('Returned Data Zigbee Devices') 357 | bootbox.alert('
' + angular.toJson(response, true) + '
') 358 | }) 359 | } 360 | } 361 | }) 362 | ); 363 | } 364 | 365 | } 366 | 367 | app.factory('apiDeCONZ', function($http, $location, $q, $compile, $rootScope, domoticzApi) { 368 | var requestsCount = 0; 369 | var requestsQueue = []; 370 | var apiHost = ""; 371 | var apiPort = ""; 372 | var apiKey = ""; 373 | var onInit = init(); 374 | 375 | return { 376 | sendRequest: sendRequest, 377 | checkDeCONZsetup: checkDeCONZsetup, 378 | getDeCONZdata: getDeCONZdata, 379 | setDeCONZdata: setDeCONZdata, 380 | postDeCONZdata: postDeCONZdata, 381 | }; 382 | 383 | function init() { 384 | 385 | return domoticzApi.sendRequest({ 386 | type: 'command', 387 | param: 'gethardware', 388 | displayhidden: 1, 389 | filter: 'all', 390 | used: 'all' 391 | }) 392 | .then(domoticzApi.errorHandler) 393 | .then(function(response) { 394 | if (response.result === undefined) { 395 | throw new Error('No Plugin devices found') 396 | } 397 | 398 | var apiDevice = response.result 399 | .find(function(plugin) { 400 | return plugin.Extra === 'deCONZ' 401 | }) 402 | 403 | if (!apiDevice) { 404 | throw new Error('No API Device found') 405 | } 406 | // console.log('Setting API data: ' + apiDevice.Address + '\n' + apiDevice.Port + '\n' + apiDevice.Mode2) 407 | 408 | if (apiDevice.Address == '127.0.0.1' | apiDevice.Address == 'localhost') { 409 | // console.log('host is: ' + $location.host()) 410 | apiHost = $location.host() 411 | } else { 412 | apiHost = apiDevice.Address 413 | } 414 | apiPort = apiDevice.Port 415 | apiKey = apiDevice.Mode2 416 | 417 | return; 418 | }); 419 | } 420 | 421 | function checkDeCONZsetup() { 422 | return onInit.then(function() { 423 | var deferred = $q.defer(); 424 | console.log('Checking DeCONZdsetup') 425 | 426 | url = 'https://phoscon.de/discover' 427 | 428 | $http({ 429 | method: 'GET', 430 | url: url, 431 | 432 | }).then(function successCallback(response) { 433 | // console.log('deCONZ: Discover Recieved') 434 | // console.log('response Data:' + angular.toJson(response.data, true)) 435 | 436 | deferred.resolve(response.data) 437 | },function errorCallback(response) { 438 | console.error('Error getting deCONZ Discover data:' + angular.toJson(response, true) ) 439 | bootbox.alert('

' + $.t('Error getting deCONZ Discover data') + '


' + 440 | 'https://phoscon.de/discover') 441 | deferred.reject(response) 442 | }); 443 | 444 | return deferred.promise; 445 | }); 446 | } 447 | 448 | function getDeCONZdata(deviceClass, id = '') { 449 | var url; 450 | 451 | return onInit.then(function() { 452 | var deferred = $q.defer(); 453 | // console.log('getDeCONZdata') 454 | 455 | if (apiKey !== "") { 456 | url = 'http://' + apiHost + ':' + apiPort + '/api/' + apiKey + '/' + deviceClass + '/' + id 457 | // console.log('GET API URL is: ' + url) 458 | $http({ 459 | method: 'GET', 460 | url: url, 461 | 462 | }).then(function successCallback(response) { 463 | // console.log('deCONZ: Data Recieved') 464 | // As there is no IDX and the API requires an ID, we must add back the ID to the array 465 | keys = Object.keys(response.data) 466 | 467 | if (deviceClass == "alarmsystems") { 468 | //hack 469 | // response.data['1'].devices = {"ec:1b:bd:ff:fe:6f:c3:4d-01-0501": {"armmask": "none"}}; 470 | // Make header 471 | response.data['1'].id = keys[i] 472 | response.data['1'].uniqueid = 'Master' 473 | response.data['1'].name = 'Alarm System ' + 'Master' 474 | response.data['1'].deviceclass = deviceClass 475 | response.data['1'].type = 'Alarm System Control' 476 | // Make fields, disabled 477 | if (false) { 478 | keys = Object.keys(response.data['1']['devices']) 479 | for (i = 0; i < keys.length; i++) { 480 | response.data[keys[i]].id = keys[i] 481 | response.data[keys[i]].uniqueid = keys[i] 482 | response.data[keys[i]].name = 'Alarm System ' + keys[i] 483 | response.data[keys[i]].deviceclass = keys[i].armmask 484 | response.data[keys[i]].type = 'Alarm System' 485 | } 486 | } 487 | } 488 | else if (deviceClass != "config") { 489 | // loop through count 490 | for (i = 0; i < keys.length; i++) { 491 | // add id to each object 492 | response.data[keys[i]].id = keys[i] 493 | // add class type to allow puts 494 | response.data[keys[i]].deviceclass = deviceClass 495 | } 496 | } 497 | 498 | deferred.resolve(response.data) 499 | },function errorCallback(response) { 500 | // console.log('Error getting deCONZ data:' + response ) 501 | deferred.reject(response) 502 | }); 503 | } 504 | 505 | return deferred.promise; 506 | }); 507 | } 508 | 509 | function setDeCONZdata(deviceClass, method, id = '', body = '', url2 ='') { 510 | var url; 511 | if (url2) { 512 | url2 = '/' + url2 ; 513 | } 514 | 515 | return onInit.then(function() { 516 | var deferred = $q.defer(); 517 | // console.log('setDeCONZdata') 518 | 519 | if (apiKey !== "") { 520 | url = 'http://' + apiHost + ':' + apiPort + '/api/' + apiKey + '/' + deviceClass + '/' + id + url2 521 | // console.log('SET API URL is: ' + url) 522 | $http({ 523 | method: method, 524 | url: url, 525 | data: body, 526 | 527 | }).then(function successCallback(response) { 528 | // console.log('deCONZ: Data Recieved') 529 | // console.log('response Data:' + angular.toJson(response.data, true)) 530 | 531 | deferred.resolve(response.data) 532 | },function errorCallback(response) { 533 | // console.log('Error getting deCONZ data:' + response ) 534 | deferred.reject(response) 535 | }); 536 | } 537 | 538 | return deferred.promise; 539 | }); 540 | } 541 | 542 | function postDeCONZdata(host, port, endpoint, body, gwPass) { 543 | 544 | return onInit.then(function() { 545 | var deferred = $q.defer(); 546 | 547 | token = btoa('delight:' + gwPass) 548 | 549 | if (apiHost !== "") { 550 | 551 | url = 'http://' + host + ':' + port + '/' + endpoint 552 | // console.log('POST API URL is: ' + 'http://' + host + ':' + port + '/' + endpoint) 553 | $http({ 554 | method: 'POST', 555 | url: url, 556 | headers: { 557 | 'Authorization': 'Basic ' + token 558 | }, 559 | data: body, 560 | 561 | }).then(function successCallback(response) { 562 | // console.log('deCONZ: Data Recieved') 563 | // console.log('response Data:' + angular.toJson(response.data, true)) 564 | deferred.resolve(response.data) 565 | },function errorCallback(response) { 566 | console.error('Error getting deCONZ data:' + angular.toJson(response.data, true) ) 567 | bootbox.alert('

' + $.t('Error getting API key') + '


' + 568 | '

' + $.t('This could also indicate a bad password.') + '

' + 569 | '
' + angular.toJson(response.data, true) + '
') 570 | deferred.reject(response) 571 | }); 572 | } 573 | 574 | return deferred.promise; 575 | }); 576 | } 577 | 578 | function sendRequest(command, params) { 579 | return onInit.then(function() { 580 | var deferred = $q.defer(); 581 | var requestId = ++requestsCount; 582 | 583 | var requestInfo = { 584 | requestId: requestId, 585 | deferred: deferred, 586 | }; 587 | 588 | requestsQueue.push(requestInfo); 589 | 590 | return deferred.promise; 591 | }); 592 | } 593 | 594 | function handleResponse(data) { 595 | if (data.type !== 'response' && data.type !== 'status') { 596 | return; 597 | } 598 | 599 | var requestIndex = requestsQueue.findIndex(function(item) { 600 | return item.requestId === data.requestId; 601 | }); 602 | 603 | if (requestIndex === -1) { 604 | return; 605 | } 606 | 607 | var requestInfo = requestsQueue[requestIndex]; 608 | 609 | if (data.type === 'status') { 610 | requestInfo.deferred.notify(data.payload); 611 | return; 612 | } 613 | 614 | if (data.isError) { 615 | requestInfo.deferred.reject(data.payload); 616 | } else { 617 | requestInfo.deferred.resolve(data.payload); 618 | } 619 | 620 | requestsQueue.splice(requestIndex, 1); 621 | } 622 | }) 623 | 624 | function zzDeconzPluginsTableController($scope, $uibModal, $element, bootbox, dataTableDefaultSettings) { 625 | var $ctrl = this; 626 | var table; 627 | 628 | $ctrl.$onInit = function() { 629 | table = $element.find('table').dataTable(Object.assign({}, dataTableDefaultSettings, { 630 | autoWidth: false, 631 | order: [[2, 'asc']], 632 | paging: true, 633 | columns: [ 634 | { title: 'ID', data: 'uniqueid', "defaultContent": "" }, 635 | { title: 'Name', data: 'name'}, 636 | { title: 'Manufacturer', data: 'manufacturername', "defaultContent": "" }, 637 | { title: 'Model', data: 'modelid', "defaultContent": "" }, 638 | { title: 'Type', data: 'type'}, 639 | { title: 'Firmware', data: 'swversion', "defaultContent": "" }, 640 | { title: 'Last Seen', data: 'lastseen', "defaultContent": "" }, 641 | 642 | { 643 | title: '', 644 | className: 'actions-column', 645 | width: '80px', 646 | data: '', 647 | orderable: false, 648 | render: actionsRenderer 649 | }, 650 | ], 651 | })); 652 | 653 | table.on('click', '.js-rename-device', function() { 654 | var row = table.api().row($(this).closest('tr')).data(); 655 | var scope = $scope.$new(true); 656 | scope.device = row; 657 | 658 | $uibModal 659 | .open(Object.assign({ scope: scope }, renameDeviceModal)).result.then(closedCallback, dismissedCallback); 660 | 661 | function closedCallback(){ 662 | // Do something when the modal is closed 663 | // console.log('closed callback') 664 | } 665 | 666 | function dismissedCallback(){ 667 | // Do something when the modal is dismissed 668 | // console.log('cancelled callback') 669 | } 670 | 671 | $scope.$apply(); 672 | 673 | }); 674 | 675 | table.on('click', '.js-include-device', function() { 676 | var row = table.api().row($(this).closest('tr')).data(); 677 | var scope = $scope.$new(true); 678 | scope.device = row; 679 | 680 | $uibModal 681 | .open(Object.assign({ scope: scope }, includeDeviceModal)).result.then(closedCallback, dismissedCallback); 682 | 683 | function closedCallback(){ 684 | // Do something when the modal is closed 685 | // console.log('closed callback') 686 | } 687 | 688 | function dismissedCallback(){ 689 | // Do something when the modal is dismissed 690 | // console.log('cancelled callback') 691 | } 692 | 693 | $scope.$apply(); 694 | 695 | }); 696 | 697 | table.on('click', '.js-includerem-device', function() { 698 | var row = table.api().row($(this).closest('tr')).data(); 699 | var scope = $scope.$new(true); 700 | scope.device = row; 701 | 702 | $uibModal 703 | .open(Object.assign({ scope: scope }, includeremDeviceModal)).result.then(closedCallback, dismissedCallback); 704 | 705 | function closedCallback(){ 706 | // Do something when the modal is closed 707 | // console.log('closed callback') 708 | } 709 | 710 | function dismissedCallback(){ 711 | // Do something when the modal is dismissed 712 | // console.log('cancelled callback') 713 | } 714 | 715 | $scope.$apply(); 716 | 717 | }); 718 | 719 | table.on('click', '.js-config-device', function() { 720 | var row = table.api().row($(this).closest('tr')).data(); 721 | var scope = $scope.$new(true); 722 | scope.device = row; 723 | 724 | $uibModal 725 | .open(Object.assign({ scope: scope }, configDeviceModal)).result.then(closedCallback, dismissedCallback); 726 | 727 | function closedCallback(){ 728 | // Do something when the modal is closed 729 | // console.log('closed callback') 730 | } 731 | 732 | function dismissedCallback(){ 733 | // Do something when the modal is dismissed 734 | // console.log('cancelled callback') 735 | } 736 | 737 | $scope.$apply(); 738 | 739 | }); 740 | 741 | table.on('click', '.js-device-data', function() { 742 | var device = table.api().row($(this).closest('tr')).data(); 743 | 744 | bootbox.alert('
' + angular.toJson(device, true) + '
') 745 | }); 746 | 747 | table.on('click', '.js-remove-device', function() { 748 | var row = table.api().row($(this).closest('tr')).data(); 749 | var scope = $scope.$new(true); 750 | scope.device = row; 751 | 752 | $uibModal 753 | .open(Object.assign({ scope: scope }, deleteDeviceModal)) 754 | 755 | $scope.$apply(); 756 | }); 757 | 758 | render($ctrl.zigdevs); 759 | } 760 | 761 | $ctrl.$onChanges = function(changes) { 762 | if (changes.zigdevs) { 763 | render($ctrl.zigdevs); 764 | } 765 | }; 766 | 767 | function render(items) { 768 | if (!table || !items) { 769 | return; 770 | } 771 | 772 | table.api().clear(); 773 | table.api().rows 774 | .add(items) 775 | .draw(); 776 | } 777 | 778 | function actionsRenderer(value, type, device) { 779 | var actions = []; 780 | var delimiter = ''; 781 | if (device.deviceclass == 'alarmsystems') { 782 | actions.push(''); 783 | } 784 | else { 785 | actions.push(''); 786 | } 787 | if (device.deviceclass == 'sensors' || device.deviceclass == 'alarmsystems') { 788 | actions.push(''); 789 | } 790 | actions.push(''); 791 | if (device.deviceclass == 'alarmsystems') { 792 | actions.push(''); 793 | } 794 | else { 795 | actions.push(''); 796 | } 797 | 798 | return actions.join(' '); 799 | } 800 | } 801 | }); 802 | -------------------------------------------------------------------------------- /icons/batterylevelempty_icons.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Smanar/Domoticz-deCONZ/732dc0dead6fb9acd25d0e8c9b5705dff260d19a/icons/batterylevelempty_icons.zip -------------------------------------------------------------------------------- /icons/batterylevelfull_icons.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Smanar/Domoticz-deCONZ/732dc0dead6fb9acd25d0e8c9b5705dff260d19a/icons/batterylevelfull_icons.zip -------------------------------------------------------------------------------- /icons/batterylevellow_icons.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Smanar/Domoticz-deCONZ/732dc0dead6fb9acd25d0e8c9b5705dff260d19a/icons/batterylevellow_icons.zip -------------------------------------------------------------------------------- /icons/batterylevelok_icons.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Smanar/Domoticz-deCONZ/732dc0dead6fb9acd25d0e8c9b5705dff260d19a/icons/batterylevelok_icons.zip -------------------------------------------------------------------------------- /plugin.py: -------------------------------------------------------------------------------- 1 | # deCONZ Bridge 2 | # 3 | # Author: Smanar 4 | # 5 | """ 6 | 7 | 8 |

9 |

deCONZ Bridge


10 | It use the deCONZ rest api to make a bridge beetween your zigbee network and Domoticz (Using Conbee or Raspbee) 11 |

12 |

Remark

13 |
    14 |
  • You can use the file API_KEY.py if you have problems to get your API Key or your Websocket Port.
  • 15 |
  • You can find updated files for deCONZ on their github : https://github.com/dresden-elektronik/deconz-rest-plugin.
  • 16 |
  • If you want the plugin works without connection, use as IP 127.0.0.1 (if deCONZ and domoticz are on same machine).
  • 17 |
  • If you are running the plugin for the first time, better to enable debug log (Take Debug info Only).
  • 18 |
  • You can find a front-end on the Domoticz menu "Custom" > "Deconz", you can use it to get the API key, configure sensors or alarm system.
  • 19 |
20 |

Supported Devices

21 |
    22 |
  • https://github.com/dresden-elektronik/deconz-rest-plugin/wiki/Supported-Devices
  • 23 |
24 |

Configuration

25 | Gateway configuration 26 |
27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 43 | 44 | 45 |
46 | """ 47 | 48 | # All imports 49 | import Domoticz 50 | 51 | import urllib, time 52 | 53 | try: 54 | import simplejson as json 55 | except ImportError: 56 | import json 57 | 58 | REQUESTPRESENT = True 59 | try: 60 | import requests 61 | except: 62 | REQUESTPRESENT = False 63 | 64 | from fonctions import rgb_to_xy, rgb_to_hsv, xy_to_rgb 65 | from fonctions import Count_Type, ProcessAllState, ProcessAllConfig, First_Json, JSON_Repair, get_JSON_payload 66 | from fonctions import ButtonconvertionTradfriRemote, ButtonconvertionTradfriSwitch 67 | from fonctions import ButtonconvertionXCUBE, ButtonconvertionXCUBET1, ButtonconvertionXCUBEPROT1 68 | from fonctions import ButtonconvertionXCUBE_R 69 | from fonctions import ButtonConvertion, VibrationSensorConvertion 70 | from fonctions import installFE, uninstallFE 71 | from widget import Createdatawidget 72 | 73 | #Better to use 'localhost' ? 74 | DOMOTICZ_IP = '127.0.0.1' 75 | 76 | LIGHTLOG = True #To disable some activation, log will be lighter, but less informations. 77 | SETTODEFAULT = False #To set device in default state after a rejoin 78 | ENABLEMORESENSOR = False #Create more sensors, like tension and current 79 | ENABLEBATTERYWIDGET = False #Create 1 more widget by battery devices 80 | 81 | FullSpecialDeviceList = ["orientation", "heatsetpoint", "mode", "preset", "lock", "current", "voltage"] 82 | 83 | #https://github.com/febalci/DomoticzEarthquake/blob/master/plugin.py 84 | #https://stackoverflow.com/questions/32436864/raw-post-request-with-json-in-body 85 | 86 | # option list 87 | #1 = Power+Consumption 88 | #2 = Consumption_2 89 | #3 = pm2_5 90 | 91 | class BasePlugin: 92 | 93 | #enabled = False 94 | 95 | def __init__(self): 96 | self.Devices = {} # id, type, state (banned/missing/working) , model, option 97 | self.NeedToReset = [] 98 | self.Ready = False 99 | self.Buffer_Command = [] 100 | self.Buffer_Time = '' 101 | self.WebSocket = None 102 | self.WebsoketBuffer = '' 103 | self.Banned_Devices = [] 104 | self.BufferReceive = '' 105 | self.DeconzInfoUnit = False 106 | 107 | self.IDGateway = -1 108 | 109 | self.INIT_STEP = ['config', 'lights', 'sensors', 'groups', 'alarmsystems'] 110 | 111 | self.SpecialDeviceList = ["orientation", "heatsetpoint", "mode", "preset", "lock"] 112 | 113 | return 114 | 115 | def onStart(self): 116 | Domoticz.Debug("onStart called") 117 | #CreateDevice('sirene test','En test','Warning device') 118 | 119 | #Check Domoticz IP 120 | if Parameters["Address"] != '127.0.0.1' and Parameters["Address"] != 'localhost': 121 | global DOMOTICZ_IP 122 | DOMOTICZ_IP = get_ip() 123 | Domoticz.Log("You are not using 127.0.0.1 as IP, so I suppose deCONZ and Domoticz aren't on same machine") 124 | Domoticz.Log("Taking " + DOMOTICZ_IP + " as Domoticz IP") 125 | 126 | if DOMOTICZ_IP == Parameters["Address"]: 127 | Domoticz.Status("You seem to use the IP for deCONZ and Domoticz. Why don't you use 127.0.0.1 as IP?") 128 | else: 129 | Domoticz.Log("Domoticz and deCONZ are installed on the same machine.") 130 | 131 | if Parameters["Mode3"] != "0": 132 | Domoticz.Debugging(int(Parameters["Mode3"])) 133 | #DumpConfigToLog() 134 | 135 | #Create info widget 136 | self.DeconzInfoUnit = GetDomoDeviceInfo("DeconzInfo") 137 | if not self.DeconzInfoUnit: 138 | Domoticz.Log("Creation of Info Widget.") 139 | Domoticz.Device(Name="Status", DeviceID="DeconzInfo", Unit=FreeUnit(), TypeName='Alert').Create() 140 | 141 | if "ENABLEMORESENSOR" in Parameters["Mode4"]: 142 | Domoticz.Status("Enabling special setting ENABLEMORESENSOR") 143 | global ENABLEMORESENSOR 144 | ENABLEMORESENSOR = True 145 | self.SpecialDeviceList = self.SpecialDeviceList + ["current", "voltage"] 146 | 147 | if "ENABLEBATTERYWIDGET" in Parameters["Mode4"]: 148 | Domoticz.Status("Enabling special setting ENABLEBATTERYWIDGET") 149 | global ENABLEBATTERYWIDGET 150 | ENABLEBATTERYWIDGET = True 151 | 152 | #Custom icon files for battery level 153 | #https://github.com/999LV/BatteryLevel 154 | icons = {"batterylevelfull": "icons/batterylevelfull_icons.zip", 155 | "batterylevelok": "icons/batterylevelok_icons.zip", 156 | "batterylevellow": "icons/batterylevellow_icons.zip", 157 | "batterylevelempty": "icons/batterylevelempty_icons.zip"} 158 | 159 | # load custom battery images 160 | for key, value in icons.items(): 161 | if key not in Images: 162 | Domoticz.Image(value).Create() 163 | Domoticz.Status("Added icon: " + key + " from file " + value) 164 | Domoticz.Status("Number of icons loaded = " + str(len(Images))) 165 | for image in Images: 166 | Domoticz.Log("Icon Used by the plugin : " + str(Images[image].ID) + ">" + Images[image].Name) 167 | 168 | #Read banned devices 169 | try: 170 | with open(Parameters["HomeFolder"]+"banned_devices.txt", 'r') as myPluginConfFile: 171 | for line in myPluginConfFile: 172 | if not line.startswith('#'): 173 | Domoticz.Log("Adding banned device : " + line.strip()) 174 | self.Banned_Devices.append(line.strip()) 175 | except (IOError,FileNotFoundError): 176 | #File not exist create it with example 177 | Domoticz.Status("Creating banned device file") 178 | with open(Parameters["HomeFolder"]+"banned_devices.txt", 'w') as myPluginConfFile: 179 | myPluginConfFile.write("#Alarm on Detector\n00:15:8d:00:02:36:c2:3f-01-0500") 180 | 181 | myPluginConfFile.close() 182 | 183 | #check and load Front end 184 | installFE(Parameters['HomeFolder'], Parameters['StartupFolder']) 185 | 186 | #Read and Set config 187 | #json = '{"websocketnotifyall":true}' 188 | #url = '/api/' + Parameters["Mode2"] + '/config/' 189 | #self.SendCommand(url,json) 190 | 191 | # Disabled, not working for selector ... 192 | #check for new icons 193 | #if 'bulbs_group' not in Images: 194 | # try: 195 | # Domoticz.Image('icons/bulbs_group.zip').Create() 196 | # except: 197 | # Domoticz.Error("Can't create new icons") 198 | 199 | def onStop(self): 200 | Domoticz.Debug("onStop called") 201 | if self.WebSocket: 202 | self.WebSocket.Disconnect() 203 | 204 | def onConnect(self, Connection, Status, Description): 205 | Domoticz.Debug("onConnect called") 206 | 207 | if Connection.Name == 'deCONZ_WebSocket': 208 | 209 | if (Status != 0): 210 | Domoticz.Error("WebSocket connection error : " + str(Connection)) 211 | Domoticz.Error("Status : " + str(Status) + " Description : " + str(Description) ) 212 | return 213 | 214 | Domoticz.Status("Launching WebSocket on port " + str(Connection.Port) ) 215 | #Need to Add Sec-Websocket-Protocol : domoticz ???? 216 | #Boring error > Socket Shutdown Error: 9, Bad file descriptor 217 | wsHeader = "GET / HTTP/1.1\r\n" \ 218 | "Host: "+ Parameters["Address"] + ':' + str(Connection.Port) + "\r\n" \ 219 | "User-Agent: Domoticz/1.0\r\n" \ 220 | "Sec-WebSocket-Version: 13\r\n" \ 221 | "Origin: http://" + DOMOTICZ_IP + "\r\n" \ 222 | "Sec-WebSocket-Key: qqMLBxyyjz9Tog1bll7K6A==\r\n" \ 223 | "Connection: keep-alive, Upgrade\r\n" \ 224 | "Upgrade: websocket\r\n\r\n" 225 | #"Accept: Content-Type: text/html; charset=UTF-8\r\n" \ 226 | #"Pragma: no-cache\r\n" \ 227 | #"Cache-Control: no-cache\r\n" \ 228 | #"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" \ 229 | self.WebSocket.Send(wsHeader) 230 | 231 | else: 232 | Domoticz.Error("Unknown Connection: " + str(Connection)) 233 | Domoticz.Error("Status : " + str(Status) + " Description : " + str(Description) ) 234 | return 235 | 236 | def onMessage(self, Connection, Data): 237 | Domoticz.Debug("onMessage called") 238 | 239 | _Data = [] 240 | 241 | if self.WebsoketBuffer: 242 | Data = self.WebsoketBuffer + Data 243 | self.WebsoketBuffer = '' 244 | 245 | #Domoticz.Log("Data : " + str(Data)) 246 | #Domoticz.Log("Connexion : " + str(Connection)) 247 | #Domoticz.Log("Byte needed : " + str(Connection.BytesTransferred()) + "ATM : " + str(len(Data))) 248 | #The max is 4096 so if the data size excess 4096 byte it will be cut 249 | 250 | #Websocket data ? 251 | if (Connection.Name == 'deCONZ_WebSocket'): 252 | #Data = b'\x81W{"e":"changed","id":"7","r":"groups","state":{"all_on":true,"any_on":true}}' 253 | #Data = b'\x81W{"e":"changed","id":"5","r":"groups","state":{"all_on":true,"any_on"' 254 | 255 | if Data.startswith(b'\x81'): 256 | while len(Data) > 0: 257 | try: 258 | payload, extra_data = get_JSON_payload(Data) 259 | except: 260 | if (Data[0:1] == b'\x81') and (len(str(Data)) < 1000) : 261 | self.WebsoketBuffer = Data 262 | Domoticz.Log("Incomplete JSON keep it for later : " + str(self.WebsoketBuffer) ) 263 | else: 264 | Domoticz.Error("Malformed JSON response, can't repair : " + str(Data) ) 265 | break 266 | _Data.append(payload) 267 | Data = extra_data 268 | 269 | for js in _Data: 270 | self.WebSocketConnexion(js) 271 | else: 272 | Domoticz.Log("WebSocket Handshake : " + str(Data.decode("utf-8", "ignore").replace('\n','***')) ) 273 | 274 | else: 275 | Domoticz.Log("Unknown Connection" + str(Connection)) 276 | Domoticz.Log("Data : " + str(Data)) 277 | return 278 | 279 | def onCommand(self, Unit, Command, Level, Hue): 280 | Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level) + ", Hue: " + str(Hue)) 281 | 282 | if not self.Ready == True: 283 | Domoticz.Error("deCONZ not ready") 284 | return 285 | 286 | _type,deCONZ_ID = self.GetDevicedeCONZ(Devices[Unit].DeviceID) 287 | 288 | if not deCONZ_ID: 289 | # Not in deconz but Alarm System ? 290 | if Devices[Unit].DeviceID == 'Alarm_System_1': 291 | if Devices[Unit].Description: 292 | url = '/api/' + Parameters["Mode2"] + '/alarmsystems/1/' + ['disarm','arm_away','arm_stay','arm_night'][int(Level/10)] 293 | self.SendCommand(url,{'code0':str(Devices[Unit].Description)}) 294 | else: 295 | Domoticz.Error("Missing code0 in alarm system widget description") 296 | else: 297 | Domoticz.Error("Device not ready : " + str(Unit) ) 298 | return 299 | 300 | if _type == 'sensors': 301 | Domoticz.Error("This device doesn't support action") 302 | return 303 | 304 | IEEE = Devices[Unit].DeviceID 305 | 306 | #Get device type 307 | device_type = self.Devices[IEEE].get('model','Unknow') 308 | 309 | _json = {} 310 | 311 | #on/off 312 | if Command == 'On': 313 | if device_type == 'Warning device': 314 | _json['alert'] = 'lselect' 315 | #Force Update using domoticz, because some device don't have return 316 | UpdateDeviceProc({'nValue': 1, 'sValue': 'On'}, Unit) 317 | elif device_type.startswith('Window covering'): 318 | _json['open'] = False 319 | else: 320 | _json['on'] = True 321 | if Level: 322 | _json['bri'] = round(Level*254/100) 323 | if _type == 'config': 324 | if Devices[Unit].DeviceID.endswith('_lock'): 325 | _json = {'lock':True} 326 | elif Command == 'Off': 327 | if device_type == 'Warning device': 328 | _json['alert'] = 'none' 329 | #Force Update using domoticz, because some device don't have return 330 | UpdateDeviceProc({'nValue': 0, 'sValue': 'Off'}, Unit) 331 | elif device_type.startswith('Window covering'): 332 | _json['open'] = True 333 | else: 334 | _json['on'] = False 335 | if _type == 'config': 336 | if Devices[Unit].DeviceID.endswith('_mode'): 337 | _json = {'mode':'off'} 338 | elif Devices[Unit].DeviceID.endswith('_lock'): 339 | _json = {'lock':False} 340 | 341 | #level 342 | if Command == 'Set Level': 343 | if device_type.startswith('Window covering'): 344 | _json['lift'] = Level 345 | else: 346 | #To prevent bug 347 | _json['on'] = True 348 | 349 | _json['bri'] = round(Level*254/100) 350 | 351 | #Special situation 352 | if _type == 'config': 353 | _json.clear() 354 | #Ventilator 355 | if device_type == 'Purifier_Mode': 356 | v = ["off","auto","speed_1","speed_2","speed_3","speed_4","speed_5"][int(Level/10)] 357 | _json['mode'] = v 358 | #Thermostat 359 | elif Devices[Unit].DeviceID.endswith('_heatsetpoint'): 360 | _json['heatsetpoint'] = int(Level * 100) 361 | dummy,deCONZ_ID_2 = self.GetDevicedeCONZ(Devices[Unit].DeviceID.replace('_heatsetpoint','_mode')) 362 | if deCONZ_ID_2 and ("auto" in Devices[Unit].Options.get('LevelNames','')): 363 | _json['mode'] = "auto" 364 | elif Devices[Unit].DeviceID.endswith('_preset'): 365 | v = ["off","holiday","auto","manual","comfort","eco","boost","complex","program"][int(Level/10)] 366 | _json['preset'] = v 367 | elif Devices[Unit].DeviceID.endswith('_mode'): 368 | if Level == 0: 369 | _json['mode'] = "off" 370 | if Level == 10: 371 | _json['mode'] = "heat" 372 | if Level == 20: 373 | _json['mode'] = "auto" 374 | #retreive previous value from domoticz 375 | IEEE2 = Devices[Unit].DeviceID.replace('_mode','_heatsetpoint') 376 | Hp = int(100*float(Devices[GetDomoDeviceInfo(IEEE2)].sValue)) 377 | _json['heatsetpoint'] = Hp 378 | #Chritsmas tree 379 | elif Devices[Unit].DeviceID.endswith('_effect'): 380 | v = ["none","steady","snow","rainbow","snake","twinkle","fireworks","flag","waves","updown","vintage","fading","collide","strobe","sparkles","carnival","glow"][int(Level/10) - 1] 381 | _json['effect'] = v 382 | 383 | UpdateDeviceProc({'nValue': Level, 'sValue': str(Level)}, Unit) 384 | 385 | #Set special options 386 | try : 387 | for o in Devices[Unit].Description.split("\n"): 388 | o2 = o.split("=") 389 | if o2[0] == 'effectSpeed': 390 | _json['effectSpeed'] = int(o2[1]) 391 | if o2[0] == 'effectColours': 392 | _json['effectColours'] = json.loads(o2[1]) 393 | 394 | except: 395 | Domoticz.Log("No special effect options") 396 | 397 | # Get light device 398 | _type,deCONZ_ID = self.GetDevicedeCONZ(Devices[Unit].DeviceID.replace("_effect","")) 399 | 400 | #Special code to force devive update for group 401 | elif _type == 'groups': 402 | UpdateDeviceProc({'nValue': 1, 'sValue': str(Level)}, Unit) 403 | 404 | #Special devices 405 | if device_type == 'Warning device': 406 | #Heyman Siren 407 | _json.clear() 408 | if Level == 10: 409 | _json['alert'] = "select" 410 | elif Level == 20: 411 | _json['alert'] = "lselect" 412 | elif Level == 30: 413 | _json['alert'] = "blink" 414 | else: 415 | _json['alert'] = "none" 416 | 417 | #Force Update using domoticz, because some device don't have return 418 | UpdateDeviceProc({'nValue': Level, 'sValue': str(Level)}, Unit) 419 | 420 | #Pach for special device 421 | if 'NO DIMMER' in Devices[Unit].Description and 'bri' in _json: 422 | _json.pop('bri') 423 | _json['transitiontime'] = 0 424 | 425 | #covering 426 | if Command == 'Open': 427 | _json['open'] = False 428 | elif Command == 'Close': 429 | _json['open'] = True 430 | elif Command == 'Stop': 431 | _json = {'stop':True} 432 | 433 | #color 434 | if Command == 'Set Color': 435 | 436 | #To prevent bug 437 | _json['on'] = True 438 | 439 | Hue_List = json.loads(Hue) 440 | 441 | #ColorModeNone = 0 // Illegal 442 | #ColorModeNone = 1 // White. Valid fields: none 443 | if Hue_List['m'] == 1: 444 | ww = int(Hue_List['ww']) # Can be used as level for monochrome white 445 | #TODO : Jamais vu un device avec ca encore 446 | Domoticz.Debug("Not implemented device color 1") 447 | 448 | #ColorModeTemp = 2 // White with color temperature. Valid fields: t 449 | if Hue_List['m'] == 2: 450 | #Value is in mireds (not kelvin) 451 | #Correct values are from 153 (6500K) up to 588 (1700K) 452 | # t is 0 > 255 453 | TempKelvin = int(((255 - int(Hue_List['t']))*(6500-1700)/255)+1700); 454 | TempMired = 1000000 // TempKelvin 455 | #if previous not working 456 | #TempMired = round(float(Hue_List['t'])*(500.0f - 153.0f) / 255.0f + 153.0f) 457 | _json['ct'] = TempMired 458 | 459 | # temporary patch 460 | if self.Devices.get(IEEE + "_effect"): 461 | _json.clear() 462 | _json['sat'] = 0 463 | _json['bri'] = int(Hue_List['t']) 464 | 465 | #ColorModeRGB = 3 // Color. Valid fields: r, g, b. 466 | elif Hue_List['m'] == 3: 467 | if self.Devices[IEEE].get('colormode','Unknow') == 'hs': 468 | h,s,v = rgb_to_hsv((int(Hue_List['r']),int(Hue_List['g']),int(Hue_List['b']))) 469 | hue = int(h * 65535) 470 | saturation = int(s * 254) 471 | lightness = int(v * 254) 472 | _json['hue'] = hue 473 | _json['sat'] = saturation 474 | #Using a hack here, because this mode is not for this kind of bulb 475 | _json['bri'] = round(Level*lightness/100) 476 | _json['transitiontime'] = 0 477 | else: 478 | x, y = rgb_to_xy((int(Hue_List['r']),int(Hue_List['g']),int(Hue_List['b']))) 479 | x = round(x,6) 480 | y = round(y,6) 481 | _json['xy'] = [x,y] 482 | 483 | #ColorModeCustom = 4, // Custom (color + white). Valid fields: r, g, b, cw, ww, depending on device capabilities 484 | elif Hue_List['m'] == 4: 485 | #process white color 486 | ww = int(Hue_List['ww']) 487 | cw = int(Hue_List['cw']) 488 | TempKelvin = int(((255 - int(Hue_List['t']))*(6500-1700)/255)+1700); 489 | TempMired = 1000000 // TempKelvin 490 | _json['ct'] = TempMired 491 | #process RGB color now 492 | h,s,v = rgb_to_hsv((int(Hue_List['r']),int(Hue_List['g']),int(Hue_List['b']))) 493 | hue = int(h * 65535) 494 | saturation = int(s * 254) 495 | lightness = int(v * 254) 496 | _json['hue'] = hue 497 | _json['sat'] = saturation 498 | _json['bri'] = lightness 499 | _json['transitiontime'] = 0 500 | 501 | #To prevent bug 502 | if 'bri' not in _json: 503 | _json['bri'] = round(Level*254/100) 504 | _json['transitiontime'] = 0 505 | 506 | url = '/api/' + Parameters["Mode2"] + '/' + _type + '/' + str(deCONZ_ID) 507 | if _type == 'lights': 508 | url = url + '/state' 509 | elif _type == 'config': 510 | url = '/api/' + Parameters["Mode2"] + '/sensors/' + str(deCONZ_ID) + '/config' 511 | elif _type == 'scenes': 512 | url = '/api/' + Parameters["Mode2"] + '/groups/' + deCONZ_ID.split('/')[0] + '/scenes/' + deCONZ_ID.split('/')[1] + '/recall' 513 | _json = {} # to force PUT 514 | else: 515 | url = url + '/action' 516 | 517 | #if 'Thermostat' in self.Devices[IEEE]['model']: 518 | # Domoticz.Status("Thermostat debug : " + url + ' with ' + str(_json)) 519 | 520 | self.SendCommand(url,_json) 521 | 522 | def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile): 523 | Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile) 524 | 525 | def onDisconnect(self, Connection): 526 | Domoticz.Status("onDisconnect called for " + str(Connection.Name) ) 527 | 528 | def onHeartbeat(self): 529 | Domoticz.Debug("onHeartbeat called") 530 | 531 | #Check for freeze 532 | if len(self.Buffer_Command) > 0: 533 | self.UpdateBuffer() 534 | 535 | #Initialisation 536 | if self.Ready != True: 537 | if len(self.INIT_STEP) > 0: 538 | Domoticz.Debug("### Initialisation > " + str(self.INIT_STEP[0])) 539 | self.ManageInit() 540 | 541 | #Stop all here 542 | return 543 | else: 544 | self.Ready = True 545 | 546 | #Check websocket connexion 547 | if self.WebSocket: 548 | if not self.WebSocket.Connected(): 549 | Domoticz.Error("WebSocket Disconnected, reconnecting... ") 550 | self.WebSocket.Connect() 551 | 552 | #reset switchs 553 | if len(self.NeedToReset) > 0 : 554 | for IEEE in self.NeedToReset: 555 | _id = False 556 | for i in self.Devices: 557 | if i == IEEE: 558 | _id = self.Devices[i]['id'] 559 | UpdateDevice(_id,'sensors', { 'nValue' : 0 , 'sValue' : 'Off' }, self.SpecialDeviceList ) 560 | self.NeedToReset = [] 561 | 562 | #Devices[27].Update(nValue=0, sValue='11;22' ) 563 | 564 | def onDeviceRemoved(self,unit): 565 | Domoticz.Log("Device Removed") 566 | #TODO : Need to rescan all 567 | 568 | #--------------------------------------------------------------------------------------- 569 | 570 | def ManageInit(self,pop = False): 571 | 572 | if pop: 573 | self.INIT_STEP.pop(0) 574 | if len(self.INIT_STEP) < 1: 575 | self.Ready = True 576 | 577 | Domoticz.Status("### deCONZ ready") 578 | l,s,g,b,o,c = Count_Type(self.Devices) 579 | Domoticz.Status("### Found " + str(l) + " Operators, " + str(s) + " Sensors, " + str(g) + " Groups, " + str(c) + " Scenes and " + str(o) + " others, with " + str(b) + " Ignored") 580 | try: 581 | Domoticz.Status("### You can still create " + str(255-len(Devices.keys())) + " widgets in domoticz") 582 | except: 583 | pass 584 | self.DisplayDeconzInfo("Deconz ready !",1) 585 | 586 | # Compare devices bases 587 | for i in Devices: 588 | if Devices[i].DeviceID not in self.Devices: 589 | if Devices[i].DeviceID != "Alarm_System_1": 590 | Domoticz.Status('### Device ' + Devices[i].DeviceID + '(' + Devices[i].Name + ') Not in deCONZ ATM, the device is deleted or not ready.') 591 | 592 | return 593 | 594 | #No flood during initialisation 595 | if len(self.Buffer_Command) > 0: 596 | u,d = self.Buffer_Command[-1] 597 | if "/" + self.INIT_STEP[0] + "/" in u: 598 | Domoticz.Log("### Still waiting") 599 | return 600 | 601 | Domoticz.Log("### Request " + self.INIT_STEP[0]) 602 | self.SendCommand("/api/" + Parameters["Mode2"] + "/" + self.INIT_STEP[0] + "/") 603 | 604 | def InitDomoticzDB(self,key,_Data,Type_device): 605 | 606 | #Lights or sensors ? 607 | if not 'devicemembership' in _Data: 608 | 609 | IEEE = str(_Data['uniqueid']) 610 | Name = str(_Data['name']) 611 | Type = str(_Data['type']) 612 | Model = str(_Data.get('modelid','')) 613 | Manuf = str(_Data.get('manufacturername','')) 614 | StateList = _Data.get('state',[]) 615 | ConfigList = _Data.get('config',[]) 616 | 617 | Domoticz.Log("### Device > " + str(key) + ' Name:' + Name + ' Type:' + Type + ' Details:' + str(StateList) + ' and ' + str(ConfigList) ) 618 | 619 | #Skip useless devices 620 | if Type == 'Configuration tool' : 621 | Domoticz.Log("Skipping Device (Useless) : " + str(IEEE) ) 622 | self.IDGateway = key 623 | return 624 | if (Type == 'Unknown') and (len(StateList) == 1) and ('reachable' in StateList): 625 | Domoticz.Log("Skipping Device (Useless) : " + str(IEEE) ) 626 | if self.IDGateway == -1: 627 | self.IDGateway = key 628 | return 629 | if Type == 'CLIPDaylightOffset': 630 | self.Banned_Devices.append(str(IEEE)) 631 | 632 | self.Devices[IEEE] = {'id' : key , 'type' : Type_device , 'model' : Type , 'state' : 'working'} 633 | 634 | #Skip banned devices 635 | if IEEE in self.Banned_Devices: 636 | Domoticz.Log("Skipping Device (Banned) : " + str(IEEE) ) 637 | self.Devices[IEEE]['state'] = 'banned' 638 | return 639 | if Type == 'ZHATime': 640 | self.Devices[IEEE]['state'] = 'banned' 641 | return 642 | 643 | #Get some infos 644 | kwarg = {} 645 | if StateList: 646 | kwarg.update(ProcessAllState(StateList,Model,0)) 647 | if 'colormode' in StateList: 648 | cm = StateList['colormode'] 649 | if (cm == 'xy') and ('hue' in StateList): 650 | cm = 'hs' 651 | self.Devices[IEEE]['colormode'] = StateList['colormode'] 652 | 653 | if ConfigList: 654 | kwarg.update(ProcessAllConfig(ConfigList,Model,0)) 655 | 656 | #It's a switch ? Need special process 657 | if Type == 'ZHASwitch' or Type == 'ZGPSwitch' or Type == 'CLIPSwitch': 658 | 659 | #Set it to off 660 | kwarg.update({'sValue': 'Off', 'nValue': 0}) 661 | 662 | #ignore ZHASwitch if vibration sensor 663 | if 'sensitivity' in ConfigList: 664 | return 665 | #Used by Xiaomi Cube T1 666 | if 'lumi.remote.cagl01' in Model: 667 | if IEEE.endswith('-03-000c'): 668 | Type = 'XCube_R' 669 | elif IEEE.endswith('-02-0012'): 670 | Type = 'XCubeT1_C' 671 | else: 672 | # Useless device 673 | self.Devices[IEEE]['state'] = 'banned' 674 | return 675 | #Used by Xiaomi Cube T1 Pro 676 | elif 'lumi.remote.cagl02' in Model: 677 | if IEEE.endswith('-03-000c'): 678 | Type = 'XCube_R' 679 | elif IEEE.endswith('-02-0012'): 680 | Type = 'XCubeProT1_C' 681 | else: 682 | # Useless device 683 | self.Devices[IEEE]['state'] = 'banned' 684 | return 685 | #Used by olders cube version 686 | elif 'lumi.sensor_cube' in Model: 687 | if IEEE.endswith('-03-000c'): 688 | Type = 'XCube_R' 689 | elif IEEE.endswith('-02-0012'): 690 | Type = 'XCube_C' 691 | else: 692 | # Useless device 693 | self.Devices[IEEE]['state'] = 'banned' 694 | return 695 | elif 'TRADFRI remote control' in Model: 696 | Type = 'Tradfri_remote' 697 | elif 'TRADFRI on/off switch' in Model: 698 | Type = 'Tradfri_on/off_switch' 699 | elif 'lumi.remote.b186acn01' in Model: 700 | Type = 'Xiaomi_single_gang' 701 | elif Model.startswith('lumi.remote.b286acn0'): 702 | Type = 'Xiaomi_double_gang' 703 | #Used for all opple switches 704 | elif Model.endswith('86opcn01'): 705 | Type = 'Xiaomi_Opple_6_button_switch' 706 | #Used for all tuya switch 707 | elif Model.startswith('TS004'): 708 | Type = 'Tuya_button_switch' 709 | #Used by philips remote 710 | elif Model == 'RWL021': 711 | Type = 'Philips_button_switch' 712 | #used by ikea Stybar 713 | elif 'Remote Control N2' in Model: 714 | Type = 'Styrbar_remote' 715 | #used by Develco 716 | elif 'IOMZB-110' in Model: 717 | Type = 'Binary_module' 718 | 719 | else: 720 | Type = 'Switch_Generic' 721 | 722 | self.Devices[IEEE]['model'] = Type 723 | 724 | if self.Ready == True: 725 | Domoticz.Status("Adding missing device: " + str(key) + ' Type:' + str(Type)) 726 | 727 | #lidl strip 728 | if Model == 'HG06467': 729 | #Create a widget for effect 730 | self.Devices[IEEE + "_effect"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'Chrismast_E' } 731 | self.CreateIfnotExist(IEEE + "_effect",'Chrismast_E',Name) 732 | #Correction 733 | self.Devices[IEEE]['colormode'] = 'hs' 734 | Type = 'Color Temperature dimmable light' 735 | #lidl led strip 736 | if Model == 'HG06104A': 737 | #Correction 738 | self.Devices[IEEE]['colormode'] = 'xy' 739 | Type = 'Extended color light' 740 | #Special devices 741 | if Type == 'ZHAThermostat': 742 | # Not working for cable outlet yet. 743 | if not Model == 'Cable outlet': 744 | #Create a setpoint device 745 | if 'heatsetpoint' in ConfigList: 746 | self.Devices[IEEE + "_heatsetpoint"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'ZHAThermostat' } 747 | self.CreateIfnotExist(IEEE + "_heatsetpoint",'ZHAThermostat',Name) 748 | #Create a mode device 749 | if 'mode' in ConfigList: 750 | self.Devices[IEEE + "_mode"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'Thermostat_Mode' } 751 | self.CreateIfnotExist(IEEE + "_mode",'Thermostat_Mode',Name) 752 | #Create a preset device 753 | if 'preset' in ConfigList: 754 | self.Devices[IEEE + "_preset"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'Thermostat_Preset' } 755 | self.CreateIfnotExist(IEEE + "_preset",'Thermostat_Preset',Name) 756 | #Create the current device but as temperature device 757 | self.CreateIfnotExist(IEEE,'ZHATemperature',Name) 758 | elif Type == 'ZHAAirPurifier': 759 | #Create a mode fan 760 | if 'mode' in ConfigList: 761 | self.Devices[IEEE + "_mode"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'Purifier_Mode' } 762 | self.CreateIfnotExist(IEEE + "_mode",'Purifier_Mode',Name) 763 | #Create fan speed 764 | self.CreateIfnotExist(IEEE,'ZHAAirPurifier',Name) 765 | elif Type == 'ZHAAirQuality' or Type == 'ZHAParticulateMatter': 766 | self.Devices[IEEE]['option'] = 3 767 | if 'pm2_5' in StateList: 768 | self.CreateIfnotExist(IEEE,'ZHAAirQuality',Name,1) 769 | else: 770 | self.CreateIfnotExist(IEEE,'ZHAAirQuality',Name) 771 | elif Type == 'ZHAVibration': 772 | #Create a Angle device 773 | self.Devices[IEEE + "_orientation"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'Vibration_Orientation' } 774 | self.CreateIfnotExist(IEEE + "_orientation",'Vibration_Orientation',Name) 775 | #Create the current device 776 | self.CreateIfnotExist(IEEE,'ZHAVibration',Name) 777 | elif Type == 'ZHADoorLock': 778 | #Create a locker device 779 | self.Devices[IEEE + "_lock"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'Door Lock' } 780 | self.CreateIfnotExist(IEEE + "_lock",'Door Lock',Name) 781 | #Create the current device 782 | self.CreateIfnotExist(IEEE,'ZHADoorLock',Name) 783 | if Type == 'ZHAConsumption': 784 | # power and consumption on the same endpoint 785 | if Model == 'ZHEMI101' or Model == 'TH1124ZB' or Model == 'OTH4000-ZB' or Model == '45856' or Model == 'E1C-NB7': 786 | self.Devices[IEEE]['option'] = 1 787 | self.CreateIfnotExist(IEEE,Type,Name,1) 788 | # Support of consumption_2 789 | elif 'consumption_2' in StateList: 790 | self.Devices[IEEE]['option'] = 2 791 | self.CreateIfnotExist(IEEE,Type,Name,3) 792 | #Classic one 793 | else: 794 | self.CreateIfnotExist(IEEE,Type,Name) 795 | #defaut sensor 796 | else: 797 | self.CreateIfnotExist(IEEE,Type,Name) 798 | 799 | #Bonus sensor ? 800 | if ENABLEMORESENSOR: 801 | # Voltage sensor ? 802 | if 'voltage' in StateList: 803 | self.Devices[IEEE + "_voltage"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'ZHAPower_voltage' } 804 | self.CreateIfnotExist(IEEE + "_voltage",'ZHAPower_voltage',Name) 805 | # Current Sensor ? 806 | if 'current' in StateList: 807 | self.Devices[IEEE + "_current"] = {'id' : key , 'type' : 'config' , 'state' : 'working' , 'model' : 'ZHAPower_current' } 808 | self.CreateIfnotExist(IEEE + "_current",'ZHAPower_current',Name) 809 | if ENABLEBATTERYWIDGET: 810 | # Battery sensor ? 811 | if 'battery' in ConfigList: 812 | #But only 1 by device 813 | NewIEE = IEEE.split("-")[0] 814 | if NewIEE + "_battery" not in self.Devices: 815 | self.Devices[NewIEE + "_battery"] = {'id' : key , 'type' : 'state' , 'state' : 'working' , 'model' : 'ZHABattery' } 816 | self.CreateIfnotExist(NewIEE + "_battery",'ZHABattery',Name) 817 | 818 | #update 819 | if kwarg: 820 | UpdateDevice(key, Type_device, kwarg, self.SpecialDeviceList) 821 | 822 | #groups 823 | else: 824 | 825 | Name = str(_Data['name']) 826 | Type = str(_Data['type']) 827 | Domoticz.Log("### Groupe > " + str(key) + ' Name:' + Name ) 828 | Dev_name = 'GROUP_' + Name.replace(' ','_') 829 | self.Devices[Dev_name] = {'id' : key , 'type' : 'groups' , 'model' : 'groups', 'state' : 'working'} 830 | 831 | # Skip banned group 832 | if Dev_name in self.Banned_Devices: 833 | Domoticz.Log("Skipping Group (Banned) : " + str(Dev_name) ) 834 | self.Devices[Dev_name]['state'] = 'banned' 835 | 836 | else: 837 | #Check for scene 838 | scenes = _Data.get('scenes',[]) 839 | if len(scenes) > 0: 840 | for j in scenes: 841 | Domoticz.Log("### Scenes associated with group " + str(key) + " > ID:" + str(j['id']) + " Name:" + str(j['name']) ) 842 | Scene_name = 'SCENE_' + str(j['name']).replace(' ','_') 843 | self.Devices[Scene_name] = {'id' : str(key) + '/' + str(j['id']) , 'type' : 'scenes' , 'model' : 'scenes'} 844 | #^scene not exist > create 845 | if GetDomoDeviceInfo(Scene_name) == False: 846 | CreateDevice(Scene_name,str(j['name']),'Scenes') 847 | 848 | #Group not exist > create 849 | if GetDomoDeviceInfo(Dev_name) == False: 850 | CreateDevice(Dev_name,Name,Type) 851 | 852 | def CreateIfnotExist(self, __IEEE, __Type, Name, opt = 0): 853 | if GetDomoDeviceInfo(__IEEE) == False: 854 | CreateDevice(__IEEE, Name, __Type, opt) 855 | 856 | def NormalConnexion(self,_Data): 857 | 858 | Domoticz.Debug("Classic Data : " + str(_Data) ) 859 | 860 | #JSON with data returned >> _Data = [{'success': {'/lights/2/state/on': True}}, {'success': {'/lights/2/state/bri': 251}}] 861 | if isinstance(_Data, list): 862 | self.ReadReturn(_Data) 863 | else: 864 | if (self.Ready != True): 865 | #JSON with config 866 | if 'bridgeid' in _Data: 867 | if 'websocketnotifyall' in _Data: 868 | self.ReadConfig(_Data) 869 | else: 870 | Domoticz.Error("Incorrect or unknown API KEY!") 871 | 872 | else: 873 | #JSON with device info like {'1': {'data:1}} 874 | for i in _Data: 875 | if 'config' in _Data[i] and 'disarmed_entry_delay' in _Data[i]['config']: 876 | # Alarm System 877 | Domoticz.Status("Alarm System configured :" + str(_Data[i]['config']['configured'])) 878 | nbre = len(_Data[i]['devices']) 879 | if nbre > 0 : 880 | CreateAlarmSystemControl() 881 | Domoticz.Status("Number of devices inside :" + str(nbre)) 882 | UpdatelarmSystemControl(_Data[i]['state']['armstate']) 883 | else: 884 | self.InitDomoticzDB(i,_Data[i],self.INIT_STEP[0]) 885 | 886 | #Update initialisation 887 | self.ManageInit(True) 888 | else: 889 | #JSON with device info like {'data:1} 890 | # Groups ? 891 | if 'devicemembership' in _Data: 892 | _id = _Data.get('id','') 893 | if _id: 894 | self.InitDomoticzDB(_id,_Data,'groups') 895 | # simple device ? 896 | else: 897 | typ,_id = self.GetDevicedeCONZ(_Data.get('uniqueid','') ) 898 | if _id: 899 | self.InitDomoticzDB(_id,_Data,typ) 900 | 901 | def ReadReturn(self,_Data): 902 | kwarg = {} 903 | _id = False 904 | _type = False 905 | 906 | for _Data2 in _Data: 907 | 908 | First_item = next(iter(_Data2)) 909 | 910 | #Command Error 911 | if First_item == 'error': 912 | Domoticz.Error("deCONZ error :" + str(_Data2)) 913 | self.DisplayDeconzInfo("Error: " + _Data2['error']['address'] + " > " + _Data2['error']['description'],4) 914 | if (_Data2['error']['type'] == 3) or (_Data2['error']['type'] == 202): 915 | Domoticz.Log("Seems like disconnected") 916 | dev = _Data2['error']['address'].split('/') 917 | _id = dev[2] 918 | _type = dev[1] 919 | #Set red header 920 | kwarg.update({'TimedOut':1}) 921 | 922 | #Command sucess 923 | elif First_item == 'success': 924 | 925 | data = _Data2['success'] 926 | dev = (list(data.keys())[0] ).split('/') 927 | val = data[list(data.keys())[0]] 928 | 929 | if len(dev) < 3: 930 | pass 931 | else: 932 | if not _id: 933 | _id = dev[2] 934 | _type = dev[1] 935 | 936 | if dev[1] == 'config': 937 | Domoticz.Status("Editing configuration: " + str(data)) 938 | #if dev[1] == 'lights' and dev[4] == 'alert': 939 | # kwarg.update(ProcessAllState({'alert':val} ,'')) 940 | 941 | else: 942 | Domoticz.Error("Not managed return JSON: " + str(_Data2) ) 943 | 944 | if kwarg: 945 | UpdateDevice(_id, _type ,kwarg, self.SpecialDeviceList) 946 | 947 | def ReadConfig(self,_Data): 948 | #trick to test is deconz is ready 949 | fw = _Data['fwversion'] 950 | if fw == '0x00000000': 951 | Domoticz.Error("Startup failed. retrying....") 952 | #Cancel this part to restart it after 1 heartbeat (10s) 953 | return 954 | Domoticz.Status("Firmware version: " + _Data['fwversion'] ) 955 | Domoticz.Status("Websocketnotifyall: " + str(_Data['websocketnotifyall'])) 956 | if not _Data['websocketnotifyall'] == True: 957 | Domoticz.Error("Websocketnotifyall is not set to True") 958 | if len(_Data['whitelist']) > 10: 959 | Domoticz.Status("You have " + str(len(_Data['whitelist'])) + " API keys memorised, some of them are probably useless, can use the API_KEY.py tool or the Front end to clean them") 960 | 961 | #Launch Web socket connexion 962 | self.WebSocket = Domoticz.Connection(Name="deCONZ_WebSocket", Transport="TCP/IP", Address=Parameters["Address"], Port=str(_Data['websocketport']) ) 963 | self.WebSocket.Connect() 964 | 965 | self.ManageInit(True) 966 | 967 | def WebSocketConnexion(self,_Data): 968 | 969 | Domoticz.Debug("### WebSocket Data : " + str(_Data) ) 970 | 971 | if not self.Ready == True: 972 | Domoticz.Error("deCONZ not ready") 973 | return 974 | 975 | if 'e' in _Data: 976 | if _Data['e'] == 'deleted': 977 | return 978 | if _Data['e'] == 'added': 979 | return 980 | if _Data['e'] == 'scene-called': 981 | Domoticz.Log("Playing scene > group:" + str(_Data['gid']) + " Scene:" + str(_Data['scid']) ) 982 | return 983 | 984 | #Remove all uniqueid that can be have in group 985 | if 'r' in _Data: 986 | if _Data['r'] == 'groups' and 'uniqueid' in _Data: 987 | _Data.pop('uniqueid') 988 | 989 | #Take care, no uniqueid for groups 990 | IEEE,state = self.GetDeviceIEEE(_Data['id'],_Data['r']) 991 | 992 | #Patch for device with double UniqueID, can't be light 993 | if (not IEEE) and ('uniqueid' in _Data) and _Data['r'] != 'lights': 994 | typ,_id = self.GetDevicedeCONZ(_Data['uniqueid'] ) 995 | if _id and (typ == _Data['r']): 996 | Domoticz.Log("Double UniqueID correction : " + _Data['id'] + ' > ' + str(_id) ) 997 | _Data['id'] = _id 998 | IEEE,state = self.GetDeviceIEEE(_Data['id'],_Data['r']) 999 | 1000 | if not IEEE: 1001 | if 'uniqueid' in _Data: 1002 | Domoticz.Error("Websocket error, unknown device > " + str(_Data['id']) + ' (' + str(_Data['r']) + ') Asking for information') 1003 | IEEE = str(_Data['uniqueid']) 1004 | #Try getting informations 1005 | self.Devices[IEEE] = {'id' : str(_Data['id']) , 'type' : str(_Data['r']) , 'state' : 'missing'} 1006 | self.SendCommand('/api/' + Parameters["Mode2"] + '/' + str(_Data['r']) + '/' + str(_Data['id']) ) 1007 | else: 1008 | if str(_Data['r']) == 'alarmsystems': 1009 | if 'state' in _Data: 1010 | UpdatelarmSystemControl(_Data['state']['armstate']) 1011 | else: 1012 | Domoticz.Error("Websocket error, unknown device > " + str(_Data['id']) + ' (' + str(_Data['r']) + ')') 1013 | #Try getting informations 1014 | if str(_Data['r']) == 'groups': 1015 | #Name = str(_Data['name']) 1016 | #Dev_name = 'GROUP_' + Name.replace(' ','_') 1017 | #self.Devices[Dev_name] = {'id' : str(_Data['id']) , 'type' : 'groups' , 'model' : 'groups', 'state' : 'missing'} 1018 | self.SendCommand('/api/' + Parameters["Mode2"] + '/groups/' + str(_Data['id']) ) 1019 | 1020 | return 1021 | if state == 'banned': 1022 | Domoticz.Debug("Banned/Ignored device > " + str(_Data['id']) + ' (' + str(_Data['r']) + ')') 1023 | return 1024 | if state == 'missing': 1025 | Domoticz.Error("Missing device > " + str(_Data['id']) + ' (' + str(_Data['r']) + ')') 1026 | return 1027 | 1028 | model = self.Devices[IEEE].get('model','') 1029 | 1030 | #if 'Thermostat' in model: 1031 | # Domoticz.Status("Thermostat debug : " + str(_Data)) 1032 | 1033 | kwarg = {} 1034 | 1035 | #MAJ State : _Data['e'] == 'changed' 1036 | if 'state' in _Data: 1037 | state = _Data['state'] 1038 | kwarg.update(ProcessAllState(state , model, self.Devices[IEEE].get('option',0))) 1039 | 1040 | if 'buttonevent' in state: 1041 | if model == 'XCube_C': 1042 | kwarg.update(ButtonconvertionXCUBE(state['buttonevent']) ) 1043 | elif model == 'XCubeT1_C': 1044 | kwarg.update(ButtonconvertionXCUBET1(state['buttonevent'], state['gesture']) ) 1045 | elif model == 'XCubeProT1_C': 1046 | kwarg.update(ButtonconvertionXCUBEPROT1(state['buttonevent'], state['gesture']) ) 1047 | elif model == 'XCube_R': 1048 | kwarg.update(ButtonconvertionXCUBE_R(state['buttonevent']) ) 1049 | elif model == 'Tradfri_remote': 1050 | kwarg.update(ButtonconvertionTradfriRemote(state['buttonevent']) ) 1051 | elif model == 'Tradfri_on/off_switch': 1052 | kwarg.update(ButtonconvertionTradfriSwitch(state['buttonevent']) ) 1053 | elif model == 'Xiaomi_double_gang': 1054 | kwarg.update(ButtonConvertion(state['buttonevent'], 1 ) ) 1055 | elif model == 'Xiaomi_Opple_6_button_switch': 1056 | kwarg.update(ButtonConvertion(state['buttonevent'], 2) ) 1057 | elif model == 'Xiaomi_single_gang': 1058 | kwarg.update(ButtonConvertion(state['buttonevent'], 3) ) 1059 | elif model == "Tuya_button_switch": 1060 | kwarg.update(ButtonConvertion(state['buttonevent'], 4) ) 1061 | elif model == "Philips_button_switch": 1062 | kwarg.update(ButtonConvertion(state['buttonevent'], 5) ) 1063 | elif model == "Styrbar_remote": 1064 | kwarg.update(ButtonConvertion(state['buttonevent'], 6) ) 1065 | elif model == "Binary_module": 1066 | kwarg.update(ButtonConvertion(state['buttonevent'], 7) ) 1067 | else: 1068 | kwarg.update(ButtonConvertion(state['buttonevent']) ) 1069 | if (IEEE not in self.NeedToReset) and (model != "Binary_module"): 1070 | self.NeedToReset.append(IEEE) 1071 | 1072 | if 'vibration' in state: 1073 | kwarg.update(VibrationSensorConvertion( state['vibration'] , state.get('tiltangle',None), state.get('orientation',None)) ) 1074 | 1075 | if 'reachable' in state: 1076 | if state['reachable'] == True: 1077 | Unit = GetDomoDeviceInfo(IEEE) 1078 | #Jump following action if Unit content is not valid 1079 | if Unit != False: 1080 | LUpdate = Devices[Unit].LastUpdate 1081 | LUpdate=time.mktime(time.strptime(LUpdate,"%Y-%m-%d %H:%M:%S")) 1082 | current = time.time() 1083 | 1084 | if (SETTODEFAULT): 1085 | #Check if the device has been see, at least 10 s ago 1086 | if (current-LUpdate) > 10: 1087 | Domoticz.Status("###### Device just reconnected: " + str(_Data) + "Set to default state") 1088 | self.SetDeviceDefautState(IEEE,_Data['r']) 1089 | else: 1090 | Domoticz.Status("###### Device just reconnected: " + str(_Data) + "But ignored") 1091 | 1092 | if ('tampered' in state) or ('lowbattery' in state): 1093 | tampered = state.get('tampered',False) 1094 | lowbattery = state.get('lowbattery',False) 1095 | if tampered or lowbattery: 1096 | kwarg.update({'TimedOut':1}) 1097 | Domoticz.Error("###### Device with hardware default: " + str(_Data)) 1098 | self.DisplayDeconzInfo("Device with hardware default: " + IEEE + " > " + str(state),4) 1099 | 1100 | #MAJ config 1101 | elif 'config' in _Data: 1102 | config = _Data['config'] 1103 | kwarg.update(ProcessAllConfig(config,model,0)) 1104 | 1105 | #MAJ attr, not used yet 1106 | elif 'attr' in _Data: 1107 | attr = _Data['attr'] 1108 | 1109 | #MAJ capabilities, not used yet 1110 | elif 'capabilities' in _Data: 1111 | capabilities = _Data['capabilities'] 1112 | 1113 | else: 1114 | Domoticz.Error("Unknow MAJ: " + str(_Data) ) 1115 | 1116 | if kwarg: 1117 | UpdateDevice(_Data['id'], _Data['r'], kwarg, self.SpecialDeviceList) 1118 | 1119 | def DeleteDeviceFromdeCONZ(self,_id): 1120 | 1121 | url = '/api/' + Parameters["Mode2"] + '/sensors/' + str(_id) 1122 | 1123 | self.Buffer_Command.append((url,'delete')) 1124 | self.UpdateBuffer() 1125 | 1126 | Domoticz.Status("### Deleting device " + str(_id)) 1127 | 1128 | def SendCommand(self,url,data=None): 1129 | 1130 | Domoticz.Debug("Send Command " + url + " with " + str(data) + ' (' + str(len(self.Buffer_Command)) + ' in buffer)') 1131 | 1132 | sendData = (url , data) 1133 | self.Buffer_Command.append(sendData) 1134 | self.UpdateBuffer() 1135 | 1136 | def GetDevicedeCONZ(self,IEEE): 1137 | if IEEE in self.Devices: 1138 | return self.Devices[IEEE]['type'],self.Devices[IEEE]['id'] 1139 | 1140 | return False,False 1141 | 1142 | def UpdateBuffer(self): 1143 | if len(self.Buffer_Command) == 0: 1144 | return 1145 | 1146 | debut_time = time.time() 1147 | 1148 | while len(self.Buffer_Command) > 0: 1149 | 1150 | u , c = self.Buffer_Command.pop(0) 1151 | 1152 | _Data = MakeRequest('http://' + Parameters["Address"] + ':' + Parameters["Port"] + str(u) , c) 1153 | 1154 | #If not data usefull 1155 | if len(_Data) == 0: 1156 | return 1157 | 1158 | #Clean data 1159 | #_Data = _Data.replace('true','True').replace('false','False').replace('null','None').replace('\n','***').replace('\00','') 1160 | try: 1161 | _Data = json.loads(_Data) 1162 | except: 1163 | #Sometime the connexion bug, trying to repair 1164 | Domoticz.Error("Malformed JSON response, Trying to repair: " + str(_Data) ) 1165 | _Data = JSON_Repair(_Data) 1166 | try: 1167 | _Data = json.loads(_Data) 1168 | Domoticz.Error("New Data repaired: " + str(_Data)) 1169 | except: 1170 | Domoticz.Error("Can't repair malformed JSON: " + str(_Data) ) 1171 | _Data = None 1172 | 1173 | #traitement 1174 | if not _Data == None: #WARNING None because can be {} 1175 | self.NormalConnexion(_Data) 1176 | 1177 | fin_time = time.time() 1178 | 1179 | # if the process take more than 1s, skip all, not normal 1180 | if fin_time - debut_time > 1 : 1181 | Domoticz.Error("Process request took to long: " + str(fin_time - debut_time) + ' s') 1182 | break 1183 | 1184 | return 1185 | 1186 | def GetDeviceIEEE(self,_id,_type): 1187 | if _id == self.IDGateway and _type == 'lights': 1188 | return True, "banned" 1189 | 1190 | for IEEE in self.Devices: 1191 | if (self.Devices[IEEE]['type'] == _type) and (self.Devices[IEEE]['id'] == _id): 1192 | return IEEE,self.Devices[IEEE].get('state','unknow') 1193 | 1194 | return False,'unknow' 1195 | 1196 | def SetDeviceDefautState(self,IEEE,_type): 1197 | # Set bulb on same state than in domoticz 1198 | if _type == 'lights': 1199 | Unit = GetDomoDeviceInfo(IEEE) 1200 | if Devices[Unit].nValue == 0: 1201 | _json = '{"on":false}' 1202 | else: 1203 | _json = '{"on":true}' 1204 | dummy,deCONZ_ID = self.GetDevicedeCONZ(IEEE) 1205 | url = '/api/' + Parameters["Mode2"] + '/lights/' + str(deCONZ_ID) + '/state' 1206 | self.SendCommand(url,_json) 1207 | 1208 | def DisplayDeconzInfo(self,text,level=0): 1209 | if not self.DeconzInfoUnit: 1210 | return 1211 | Devices[self.DeconzInfoUnit].Update(nValue=level, sValue=str(text)) 1212 | 1213 | 1214 | global _plugin 1215 | _plugin = BasePlugin() 1216 | 1217 | def onStart(): 1218 | global _plugin 1219 | _plugin.onStart() 1220 | 1221 | def onStop(): 1222 | global _plugin 1223 | _plugin.onStop() 1224 | 1225 | def onConnect(Connection, Status, Description): 1226 | global _plugin 1227 | _plugin.onConnect(Connection, Status, Description) 1228 | 1229 | def onMessage(Connection, Data): 1230 | global _plugin 1231 | _plugin.onMessage(Connection, Data) 1232 | 1233 | def onCommand(Unit, Command, Level, Hue): 1234 | global _plugin 1235 | _plugin.onCommand(Unit, Command, Level, Hue) 1236 | 1237 | def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile): 1238 | global _plugin 1239 | _plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile) 1240 | 1241 | def onDisconnect(Connection): 1242 | global _plugin 1243 | _plugin.onDisconnect(Connection) 1244 | 1245 | def onHeartbeat(): 1246 | global _plugin 1247 | _plugin.onHeartbeat() 1248 | 1249 | def onDeviceRemoved(unit): 1250 | global _plugin 1251 | _plugin.onDeviceRemoved(unit) 1252 | 1253 | # Generic helper functions 1254 | def DumpConfigToLog(): 1255 | for x in Parameters: 1256 | if Parameters[x] != "": 1257 | Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'") 1258 | Domoticz.Debug("Device count: " + str(len(Devices))) 1259 | for x in Devices: 1260 | Domoticz.Debug("Device: " + str(x) + " - " + str(Devices[x])) 1261 | Domoticz.Debug("Device ID: '" + str(Devices[x].ID) + "'") 1262 | Domoticz.Debug("Device Name: '" + Devices[x].Name + "'") 1263 | Domoticz.Debug("Device nValue: " + str(Devices[x].nValue)) 1264 | Domoticz.Debug("Device sValue: '" + Devices[x].sValue + "'") 1265 | Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel)) 1266 | return 1267 | 1268 | def GetDeviceIEEE(id,type): 1269 | global _plugin 1270 | return _plugin.GetDeviceIEEE(id,type) 1271 | 1272 | def DisplayDeconzInfo(text,level=0): 1273 | global _plugin 1274 | return _plugin.DisplayDeconzInfo(text,level) 1275 | 1276 | #***************************************************************************************************** 1277 | 1278 | def MakeRequest(url,param=None): 1279 | 1280 | Domoticz.Debug("Making Request: " + url + ' with params ' + str(param) ) 1281 | 1282 | data = '' 1283 | 1284 | try: 1285 | if not param == None: 1286 | if param == 'delete': 1287 | result=requests.delete(url, headers={'Content-Type': 'application/json' }, timeout=1) 1288 | else: 1289 | headers={'Content-Type': 'application/json' } 1290 | result=requests.put(url , headers=headers, json = param, timeout=1) 1291 | #result=requests.put(url , headers=headers, data = json.dumps(param), timeout=1) 1292 | else : 1293 | result=requests.get(url, headers={'Content-Type': 'application/json' }, timeout=1) 1294 | 1295 | if result.status_code == 200 : 1296 | data = result.content 1297 | else: 1298 | Domoticz.Error( "Connection problem (1) with Gateway : " + str(result.status_code) ) 1299 | return '' 1300 | except: 1301 | if not REQUESTPRESENT: 1302 | Domoticz.Error("Your python version is missing the requests library") 1303 | Domoticz.Error("To install it, type : sudo -H pip3 install requests | sudo -H pip install requests") 1304 | else: 1305 | try: 1306 | Domoticz.Error( "Connection problem (2) with Gateway : " + str(result.status_code) ) 1307 | except: 1308 | Domoticz.Error( "Connection problem (3) with Gateway, check your API key, or Use Request lib > V2.4.2") 1309 | return '' 1310 | 1311 | Domoticz.Debug('Request Return: ' + str(data.decode("utf-8", "ignore")) ) 1312 | 1313 | return data.decode("utf-8", "ignore") 1314 | 1315 | def get_ip(): 1316 | import socket 1317 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 1318 | try: 1319 | # doesn't even have to be reachable 1320 | s.connect(('10.255.255.255', 1)) 1321 | IP = s.getsockname()[0] 1322 | except: 1323 | IP = '127.0.0.1' 1324 | finally: 1325 | s.close() 1326 | return IP 1327 | 1328 | def GetDomoDeviceInfo(IEEE): 1329 | for x in Devices: 1330 | if Devices[x].DeviceID == str(IEEE) : 1331 | return x 1332 | return False 1333 | 1334 | def FreeUnit() : 1335 | FreeUnit = "" 1336 | for x in range(1,255): 1337 | if x not in Devices : 1338 | FreeUnit=x 1339 | return FreeUnit 1340 | if FreeUnit == "" : 1341 | FreeUnit=len(Devices)+1 1342 | return FreeUnit 1343 | 1344 | def GetDomoUnit(_id,_type): 1345 | try: 1346 | IEEE,state = GetDeviceIEEE(_id,_type) 1347 | 1348 | if IEEE == False: 1349 | Domoticz.Log("Device not in base, needs resynchronisation ? > " + str(_id) + ' (' + str(_type) + ')') 1350 | return False 1351 | elif state == 'banned': 1352 | Domoticz.Log("Banned device > " + str(_id) + ' (' + str(_type) + ')') 1353 | return False 1354 | elif state == 'missing': 1355 | Domoticz.Log("missing device > " + str(_id) + ' (' + str(_type) + ')') 1356 | return False 1357 | 1358 | return GetDomoDeviceInfo(IEEE) 1359 | except: 1360 | return False 1361 | 1362 | return False 1363 | 1364 | def UpdateDevice_Special(_id,_type,kwarg, field): 1365 | value = kwarg.get(field ,False) 1366 | 1367 | IEEE,dummy = GetDeviceIEEE(_id,_type) 1368 | 1369 | #select special device 1370 | Unit2 = GetDomoDeviceInfo(IEEE + '_' + field) 1371 | 1372 | kwarg2 = kwarg.copy() 1373 | 1374 | if (field == 'mode') or (field == 'preset'): 1375 | kwarg2['nValue'] = value 1376 | kwarg2['sValue'] = str(value) 1377 | 1378 | elif field == 'orientation': 1379 | kwarg2['nValue'] = value[1] 1380 | kwarg2['sValue'] = value[0] 1381 | 1382 | else: # used for voltage, current 1383 | kwarg2['nValue'] = 0 1384 | kwarg2['sValue'] = str(value) 1385 | 1386 | if not Unit2 : 1387 | Domoticz.Debug("Can't Update Unit > " + str(_id) + ' (' + str(_type) + ') Special part' ) 1388 | return 1389 | 1390 | #Update it 1391 | UpdateDeviceProc(kwarg2,Unit2) 1392 | 1393 | def UpdateDevice(_id, _type, kwarg, SpecList): 1394 | 1395 | Unit = GetDomoUnit(_id,_type) 1396 | 1397 | if not Unit or not kwarg: 1398 | Domoticz.Error("Can't Update Unit > " + str(_id) + ' (' + str(_type) + ') : ' + str(kwarg) ) 1399 | return 1400 | 1401 | #Check for special device, and remove special kwarg 1402 | for d in SpecList: 1403 | if d in kwarg: 1404 | UpdateDevice_Special(_id, _type, kwarg, d) 1405 | 1406 | #Update the device 1407 | UpdateDeviceProc(kwarg,Unit) 1408 | 1409 | def UpdateDeviceProc(kwarg,Unit): 1410 | #Do we need to update the sensor ? 1411 | NeedUpdate = False 1412 | IsUpdate = False 1413 | 1414 | if ('nValue' in kwarg) or ('sValue' in kwarg): 1415 | IsUpdate = True 1416 | 1417 | for d in FullSpecialDeviceList: 1418 | if d in kwarg: 1419 | kwarg.pop(d) 1420 | 1421 | for a in kwarg: 1422 | if kwarg[a] != getattr(Devices[Unit], a ): 1423 | NeedUpdate = True 1424 | break 1425 | 1426 | #Force update even there is no change, for exemple in case the user press a switch too fast, to not miss an event 1427 | # Only for switch > 'LevelNames' in Devices[Unit].Options 1428 | # Only sensors > _type == 'sensors' 1429 | if IsUpdate and ('LevelNames' in Devices[Unit].Options) and (kwarg['nValue'] != 0): 1430 | NeedUpdate = True 1431 | 1432 | #hack to make graph more realistic, we loose the first value, but have at least a good value every hour. 1433 | if (Devices[Unit].Type == 113) or (Devices[Unit].Type == 248): 1434 | if NeedUpdate: 1435 | pass 1436 | #LUpdate = Devices[Unit].LastUpdate 1437 | #LUpdate=time.mktime(time.strptime(LUpdate,"%Y-%m-%d %H:%M:%S")) 1438 | #current = time.time() 1439 | #if (current-LUpdate) > 3600: 1440 | # kwarg['nValue'] = Devices[Unit].nValue 1441 | # kwarg['sValue'] = Devices[Unit].sValue 1442 | # Domoticz.Status("### debug 2 ("+Devices[Unit].Name+") : " + str(kwarg)) 1443 | else: 1444 | # Code to autorise update at least 1 time by hour if you have same data. 1445 | LUpdate = Devices[Unit].LastUpdate 1446 | LUpdate=time.mktime(time.strptime(LUpdate,"%Y-%m-%d %H:%M:%S")) 1447 | current = time.time() 1448 | if (current-LUpdate) > 3600: 1449 | NeedUpdate = True 1450 | 1451 | #Disabled because no update for battery or last seen for exemple 1452 | #No need to trigger in this situation 1453 | #if (kwarg['nValue'] == Devices[Unit].nValue) and (kwarg['nValue'] == Devices[Unit].nValue) and ('Color' not in kwarg): 1454 | # kwarg['SuppressTriggers'] = True 1455 | 1456 | #Always update for Color Bulb 1457 | if 'Color' in kwarg: 1458 | NeedUpdate = True 1459 | 1460 | #force update, at least 1 every 24h 1461 | if (not NeedUpdate) and IsUpdate: 1462 | LUpdate = Devices[Unit].LastUpdate 1463 | LUpdate=time.mktime(time.strptime(LUpdate,"%Y-%m-%d %H:%M:%S")) 1464 | current = time.time() 1465 | if (current-LUpdate) > 86400: 1466 | NeedUpdate = True 1467 | 1468 | #Need to remove the warning/defaut flag on widget ? 1469 | if Devices[Unit].TimedOut != 0 and (kwarg.get('TimedOut',0) == 0) and IsUpdate: 1470 | NeedUpdate = True 1471 | kwarg['TimedOut'] = 0 1472 | 1473 | #Theses value are needed for Domoticz 1474 | if 'nValue' not in kwarg: 1475 | kwarg['nValue'] = Devices[Unit].nValue 1476 | if 'sValue' not in kwarg: 1477 | kwarg['sValue'] = Devices[Unit].sValue 1478 | 1479 | #Do we need to update the special battery sensor ? 1480 | if ENABLEBATTERYWIDGET: 1481 | if 'BatteryLevel' in kwarg and kwarg['BatteryLevel'] != 255: 1482 | NewIEE = Devices[Unit].DeviceID.split("-")[0] 1483 | Unit2 = GetDomoDeviceInfo(NewIEE + '_battery') 1484 | if Unit2 and getattr(Devices[Unit2],'BatteryLevel') != kwarg['BatteryLevel']: 1485 | levelBatt=kwarg['BatteryLevel'] 1486 | if levelBatt >= 75: 1487 | icon = "batterylevelfull" 1488 | elif levelBatt >= 50: 1489 | icon = "batterylevelok" 1490 | elif levelBatt >= 25: 1491 | icon = "batterylevellow" 1492 | else: 1493 | icon = "batterylevelempty" 1494 | kwarg2 = {"nValue":0, "sValue":str(kwarg["BatteryLevel"]),"Image":Images[icon].ID} 1495 | Devices[Unit2].Update(**kwarg2) 1496 | Domoticz.Debug("### Update special device ("+NewIEE+") : " + str(kwarg)) 1497 | 1498 | if NeedUpdate or not LIGHTLOG: 1499 | Domoticz.Debug("### Update device ("+Devices[Unit].Name+") : " + str(kwarg)) 1500 | 1501 | #Disable offline light ? 1502 | if (Devices[Unit].Type == 241) or ((Devices[Unit].Type == 244) and (Devices[Unit].SubType == 73) and (Devices[Unit].SwitchType == 7)): 1503 | if (kwarg.get('TimedOut',0) != 0) and (Devices[Unit].nValue != 0) : 1504 | Domoticz.Debug("Will handle Timeout like off args: " + str(kwarg)) 1505 | kwarg['nValue'] = 0 1506 | kwarg['sValue'] = 'Off' 1507 | 1508 | Devices[Unit].Update(**kwarg) 1509 | 1510 | else: 1511 | Domoticz.Debug("### Update device ("+Devices[Unit].Name+") : " + str(kwarg) + ", IGNORED , no changes !") 1512 | 1513 | def UpdatelarmSystemControl(etat): 1514 | Unit = GetDomoDeviceInfo('Alarm_System_1') 1515 | if not Unit: 1516 | return 1517 | 1518 | try: 1519 | v = 10 * ['disarmed','armed_away','armed_stay','armed_night'].index(etat) 1520 | UpdateDeviceProc({'nValue': v, 'sValue': str(v)}, Unit) 1521 | except: 1522 | pass 1523 | 1524 | 1525 | def CreateAlarmSystemControl(): 1526 | 1527 | if GetDomoDeviceInfo('Alarm_System_1') != False: 1528 | return 1529 | 1530 | kwarg = {} 1531 | Unit = FreeUnit() 1532 | TypeName = '' 1533 | 1534 | kwarg['Type'] = 244 1535 | kwarg['Subtype'] = 62 1536 | kwarg['Switchtype'] = 18 1537 | kwarg['Image'] = 13 1538 | kwarg['Options'] = {"LevelActions": "||||", "LevelNames": "Disarm|Arm_away|Arm_stay|Arm_night", "LevelOffHidden": "false", "SelectorStyle": "0"} 1539 | 1540 | kwarg['DeviceID'] = 'Alarm_System_1' 1541 | kwarg['Name'] = 'Alarm System' 1542 | kwarg['Unit'] = Unit 1543 | Domoticz.Device(**kwarg).Create() 1544 | 1545 | Domoticz.Status("### Create Alarm System Device as Unit " + str(Unit) ) 1546 | 1547 | def CreateDevice(IEEE, _Name, _Type, opt = 0): 1548 | kwarg = Createdatawidget(IEEE, _Name, _Type, opt) 1549 | Unit = FreeUnit() 1550 | TypeName = '' 1551 | 1552 | if not kwarg: 1553 | Domoticz.Error("Unknow device type " + _Type ) 1554 | return 1555 | 1556 | kwarg['DeviceID'] = IEEE 1557 | kwarg['Name'] = _Name 1558 | kwarg['Unit'] = Unit 1559 | Domoticz.Device(**kwarg).Create() 1560 | 1561 | Domoticz.Status("### Create Device " + IEEE + " > " + _Name + ' (' + _Type +') as Unit ' + str(Unit) ) #Devices[Unit].ID 1562 | -------------------------------------------------------------------------------- /widget.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding: utf-8 -*- 3 | 4 | def Createdatawidget(IEEE, _Name, _Type, opt): 5 | 6 | kwarg = {} 7 | 8 | #Operator 9 | if _Type == 'Color light' or _Type == 'Color dimmable light': 10 | kwarg['Type'] = 241 11 | kwarg['Subtype'] = 2 12 | kwarg['Switchtype'] = 7 13 | 14 | elif _Type == 'Extended color light': 15 | kwarg['Type'] = 241 16 | kwarg['Subtype'] = 7 17 | kwarg['Switchtype'] = 7 18 | 19 | elif _Type == 'Color temperature light': 20 | kwarg['Type'] = 241 21 | kwarg['Subtype'] = 8 22 | kwarg['Switchtype'] = 7 23 | 24 | elif _Type == 'Dimmable light' or _Type == 'Dimmable plug-in unit' or _Type == 'Dimmer switch': 25 | kwarg['Type'] = 244 26 | kwarg['Subtype'] = 73 27 | kwarg['Switchtype'] = 7 28 | 29 | elif _Type == 'Smart plug' or _Type == 'On/Off plug-in unit': 30 | kwarg['Type'] = 244 31 | kwarg['Subtype'] = 73 32 | kwarg['Switchtype'] = 0 33 | kwarg['Image'] = 1 34 | 35 | elif _Type == 'On/Off light' or _Type == 'On/Off output' or _Type == 'On/Off light switch': 36 | kwarg['Type'] = 244 37 | kwarg['Subtype'] = 73 38 | kwarg['Switchtype'] = 0 39 | 40 | elif _Type == 'Level control switch': 41 | kwarg['Type'] = 244 42 | kwarg['Subtype'] = 73 43 | kwarg['Switchtype'] = 0 44 | 45 | elif _Type == 'Color Temperature dimmable light': 46 | kwarg['Type'] = 241 47 | kwarg['Subtype'] = 4 48 | kwarg['Switchtype'] = 7 49 | 50 | #Some device have unknow as type, but are full working. 51 | elif _Type == 'Unknown': 52 | Domoticz.Error("Unknow device : assume a light " + IEEE + " > " + _Name + ' (' + _Type +')' ) 53 | kwarg['Type'] = 244 54 | kwarg['Subtype'] = 73 55 | kwarg['Switchtype'] = 0 56 | 57 | elif _Type == 'Window covering device' or _Type == 'Window covering controller' : 58 | kwarg['Type'] = 244 59 | kwarg['Subtype'] = 73 60 | kwarg['Switchtype'] = 15 61 | 62 | elif _Type == 'Door Lock': 63 | kwarg['Type'] = 244 64 | kwarg['Subtype'] = 73 65 | kwarg['Switchtype'] = 0 66 | 67 | elif _Type == 'Fan': 68 | kwarg['Type'] = 244 69 | kwarg['Subtype'] = 73 70 | kwarg['Switchtype'] = 0 71 | kwarg['Image'] = 7 72 | 73 | elif _Type == 'Range extender': 74 | kwarg['Type'] = 244 75 | kwarg['Subtype'] = 73 76 | kwarg['Switchtype'] = 0 77 | kwarg['Image'] = 17 78 | 79 | elif _Type == 'Warning device': 80 | kwarg['Type'] = 244 81 | kwarg['Subtype'] = 62 82 | kwarg['Switchtype'] = 18 83 | kwarg['Image'] = 13 84 | kwarg['Options'] = {"LevelActions": "|||", "LevelNames": "none|select|lselect|blink", "LevelOffHidden": "false", "SelectorStyle": "0"} 85 | 86 | #Sensors 87 | elif _Type == 'Daylight': 88 | kwarg['Type'] = 244 89 | kwarg['Subtype'] = 73 90 | kwarg['Switchtype'] = 9 91 | 92 | elif _Type == 'ZHATemperature' or _Type == 'CLIPTemperature': 93 | kwarg['TypeName'] = 'Temperature' 94 | 95 | elif _Type == 'ZHAHumidity' or _Type == 'CLIPHumidity': 96 | kwarg['TypeName'] = 'Humidity' 97 | 98 | elif _Type == 'ZHAMoisture': 99 | kwarg['TypeName'] = 'Soil Moisture' 100 | 101 | elif _Type == 'ZHAPressure'or _Type == 'CLIPPressure': 102 | kwarg['TypeName'] = 'Barometer' 103 | 104 | elif _Type == 'ZHAAirQuality' or _Type == 'ZHAParticulateMatter': 105 | #kwarg['TypeName'] = 'Air Quality' 106 | kwarg['TypeName'] = 'Custom' 107 | if opt == 1: 108 | kwarg['Options'] = {"Custom": ("1;μg/m³")} 109 | else: 110 | kwarg['Options'] = {"Custom": ("1;ppb")} 111 | 112 | elif _Type == 'ZHAAirPurifier': 113 | kwarg['TypeName'] = 'Custom' 114 | kwarg['Image'] = 7 115 | kwarg['Options'] = {"Custom": ("1;m/s")} 116 | 117 | elif _Type == 'ZHAOpenClose' or _Type == 'CLIPOpenClose' or _Type == 'ZHADoorLock': 118 | kwarg['Type'] = 244 119 | kwarg['Subtype'] = 73 120 | kwarg['Switchtype'] = 11 121 | 122 | elif _Type == 'ZHAPresence' or _Type == 'CLIPPresence': 123 | kwarg['Type'] = 244 124 | kwarg['Subtype'] = 73 125 | kwarg['Switchtype'] = 8 126 | 127 | elif _Type == 'ZHALightLevel' or _Type == 'CLIPLightLevel' or _Type == 'ZHALight': 128 | kwarg['TypeName'] = 'Illumination' 129 | 130 | elif _Type == 'ZHAConsumption':# in kWh 131 | #Device with only comsumption 132 | if opt == 0: 133 | kwarg['Type'] = 113 134 | kwarg['Subtype'] = 0 135 | kwarg['Switchtype'] = 0 136 | elif opt == 1: 137 | #Device with power and energy 138 | kwarg['TypeName'] = 'kWh' 139 | else: 140 | #Device with consumption_2 141 | kwarg['Type'] = 250 142 | kwarg['Subtype'] = 1 143 | 144 | elif _Type == 'ZHAPower':# in W 145 | kwarg['TypeName'] = 'Usage' 146 | elif _Type == 'ZHAPower_voltage': 147 | kwarg['Type'] = 243 148 | kwarg['Subtype'] = 8 149 | elif _Type == 'ZHAPower_current': 150 | kwarg['Type'] = 243 151 | kwarg['Subtype'] = 23 152 | 153 | elif _Type == 'ZHAAncillaryControl': 154 | kwarg['Type'] = 243 155 | kwarg['Subtype'] = 22 156 | 157 | elif _Type == 'ZHAVibration': 158 | kwarg['Type'] = 244 159 | kwarg['Subtype'] = 62 160 | kwarg['Switchtype'] = 18 161 | kwarg['Options'] = {"LevelActions": "|||", "LevelNames": "Off|Vibrate|Rotation|Drop", "LevelOffHidden": "true", "SelectorStyle": "0"} 162 | 163 | elif _Type == 'ZHAThermostat' or _Type == 'CLIPThermostat': 164 | kwarg['Type'] = 242 165 | kwarg['Subtype'] = 1 166 | 167 | elif _Type == 'ZHAAlarm': 168 | kwarg['Type'] = 244 169 | kwarg['Subtype'] = 73 170 | kwarg['Switchtype'] = 2 171 | 172 | elif _Type == 'ZHAWater': 173 | kwarg['Type'] = 244 174 | kwarg['Subtype'] = 62 175 | kwarg['Switchtype'] = 5 176 | kwarg['Image'] = 11 # Visible only on floorplan 177 | 178 | elif _Type == 'ZHAFire' or _Type == 'ZHACarbonMonoxide': 179 | kwarg['Type'] = 244 180 | kwarg['Subtype'] = 62 181 | kwarg['Switchtype'] = 5 182 | 183 | elif _Type == 'ZHABattery': 184 | kwarg['TypeName'] = 'Percentage' 185 | 186 | elif _Type == 'CLIPGenericStatus': 187 | kwarg['TypeName'] = 'Text' 188 | 189 | elif _Type == 'CLIPGenericFlag': 190 | kwarg['Type'] = 244 191 | kwarg['Subtype'] = 62 192 | kwarg['Switchtype'] = 0 193 | kwarg['Image'] = 9 194 | 195 | #Switch 196 | elif _Type == 'Xiaomi_single_gang': 197 | kwarg['Type'] = 244 198 | kwarg['Subtype'] = 62 199 | kwarg['Switchtype'] = 18 200 | kwarg['Image'] = 9 201 | kwarg['Options'] = {"LevelActions": "||||", "LevelNames": "Off|single press|double press|hold", "LevelOffHidden": "true", "SelectorStyle": "0"} 202 | 203 | elif _Type == 'Switch_Generic' or _Type == 'Xiaomi_double_gang': 204 | kwarg['Type'] = 244 205 | kwarg['Subtype'] = 62 206 | kwarg['Switchtype'] = 18 207 | kwarg['Image'] = 9 208 | kwarg['Options'] = {"LevelActions": "||||||", "LevelNames": "Off|B1|B2|B3|B4|B5|B6|B7|B8|B9", "LevelOffHidden": "true", "SelectorStyle": "0"} 209 | elif _Type == 'Xiaomi_Opple_6_button_switch': 210 | kwarg['Type'] = 244 211 | kwarg['Subtype'] = 62 212 | kwarg['Switchtype'] = 18 213 | kwarg['Image'] = 9 214 | kwarg['Options'] = {"LevelActions": "|||||||||||||||||", "LevelNames": "Off|B1|B2|B3|B4|B5|B6|B1L|B2L|B3L|B4L|B5L|B6L|B1RL|B2RL|B3RL|B4RL|B5RL|B6RL|B1D|B2D|B3D|B4D|B5D|B6D|B1T|B2T|B3T|B4T|B5T|B6T", "LevelOffHidden": "true", "SelectorStyle": "1"} 215 | elif _Type == 'Tuya_button_switch': 216 | kwarg['Type'] = 244 217 | kwarg['Subtype'] = 62 218 | kwarg['Switchtype'] = 18 219 | kwarg['Image'] = 9 220 | kwarg['Options'] = {"LevelActions": "|||||||||||||", "LevelNames": "Off|B1|L1|D1|B2|L2|D2|B3|L3|D3|B4|L4|D4", "LevelOffHidden": "true", "SelectorStyle": "1"} 221 | elif _Type == 'Philips_button_switch': 222 | kwarg['Type'] = 244 223 | kwarg['Subtype'] = 62 224 | kwarg['Switchtype'] = 18 225 | kwarg['Image'] = 9 226 | kwarg['Options'] = {"LevelActions": "|||||||||", "LevelNames": "Off|B1|L1|B2|L2|B3|L3|B4|L4", "LevelOffHidden": "true", "SelectorStyle": "1"} 227 | elif _Type == 'Binary_module': 228 | kwarg['Type'] = 244 229 | kwarg['Subtype'] = 62 230 | kwarg['Switchtype'] = 18 231 | kwarg['Image'] = 9 232 | kwarg['Options'] = {"LevelActions": "|||", "LevelNames": "Unknow|On|Off", "LevelOffHidden": "true", "SelectorStyle": "1"} 233 | 234 | elif _Type == 'Styrbar_remote': 235 | kwarg['Type'] = 244 236 | kwarg['Subtype'] = 62 237 | kwarg['Switchtype'] = 18 238 | kwarg['Image'] = 9 239 | kwarg['Options'] = {"LevelActions": "||||||||||||", "LevelNames": "V0|V1|V2|V3|V4|V5|V6|V7|V8|V9|V10|V11|V12", "LevelOffHidden": "true", "SelectorStyle": "0"} 240 | 241 | elif _Type == 'Tradfri_remote': 242 | kwarg['Type'] = 244 243 | kwarg['Subtype'] = 62 244 | kwarg['Switchtype'] = 18 245 | kwarg['Image'] = 9 246 | kwarg['Options'] = {"LevelActions": "|||||||||", "LevelNames": "Off|On|+|-|<|>|L +|L -|L <|L >", "LevelOffHidden": "true", "SelectorStyle": "0"} 247 | 248 | elif _Type == 'Tradfri_on/off_switch': 249 | kwarg['Type'] = 244 250 | kwarg['Subtype'] = 62 251 | kwarg['Switchtype'] = 18 252 | kwarg['Options'] = {"LevelActions": "|||||", "LevelNames": "Off|B1C|B1L|B2C|B2L", "LevelOffHidden": "true", "SelectorStyle": "0"} 253 | 254 | elif _Type == 'XCube_C' or _Type == 'XCubeT1_C': 255 | kwarg['Type'] = 244 256 | kwarg['Subtype'] = 62 257 | kwarg['Switchtype'] = 18 258 | kwarg['Image'] = 9 259 | kwarg['Options'] = {"LevelActions": "||||||||", "LevelNames": "Off|Shak|Wake|Drop|90°|180°|Push|Tap", "LevelOffHidden": "true", "SelectorStyle": "0"} 260 | 261 | elif _Type == 'XCubeProT1_C': 262 | kwarg['Type'] = 244 263 | kwarg['Subtype'] = 62 264 | kwarg['Switchtype'] = 18 265 | kwarg['Image'] = 9 266 | kwarg['Options'] = {"LevelActions": "||||||||||||", "LevelNames": "Off|F1|F2|F3|F4|F5|F6|Wake|Shake|Push|Tap|Drop", "LevelOffHidden": "true", "SelectorStyle": "0"} 267 | 268 | elif _Type == 'XCube_R': 269 | kwarg['TypeName'] = 'Custom' 270 | kwarg['Options'] = {"Custom": ("1;degree")} 271 | 272 | elif _Type == 'ZHARelativeRotary': 273 | kwarg['TypeName'] = 'Custom' 274 | kwarg['Options'] = {"Custom": ("1;degree")} 275 | 276 | elif _Type == 'Thermostat_Mode': 277 | kwarg['Type'] = 244 278 | kwarg['Subtype'] = 62 279 | kwarg['Switchtype'] = 18 280 | kwarg['Options'] = {"LevelActions": "|||", "LevelNames": "Off|Heat|Auto", "LevelOffHidden": "false", "SelectorStyle": "0"} 281 | 282 | elif _Type == 'Purifier_Mode': 283 | kwarg['Type'] = 244 284 | kwarg['Subtype'] = 62 285 | kwarg['Switchtype'] = 18 286 | kwarg['Image'] = 7 287 | kwarg['Options'] = {"LevelActions": "|||||||", "LevelNames": "Off|Auto|S1|S2|S3|S4|S5", "LevelOffHidden": "false", "SelectorStyle": "0"} 288 | 289 | elif _Type == 'Thermostat_Preset': 290 | kwarg['Type'] = 244 291 | kwarg['Subtype'] = 62 292 | kwarg['Switchtype'] = 18 293 | kwarg['Options'] = {"LevelActions": "|||||||||", "LevelNames": "Off|holiday|auto|manual|comfort|eco|boost|complex|program", "LevelOffHidden": "true", "SelectorStyle": "1"} 294 | 295 | elif _Type == 'Chrismast_E': 296 | kwarg['Type'] = 244 297 | kwarg['Subtype'] = 62 298 | kwarg['Switchtype'] = 18 299 | kwarg['Image'] = 14 300 | kwarg['Options'] = {"LevelActions": "||||||||||||||||", "LevelNames": "off|none|steady|snow|rainbow|snake|twinkle|fireworks|flag|waves|updown|vintage|fading|collide|strobe|sparkles|carnival|glow", "LevelOffHidden": "true", "SelectorStyle": "1"} 301 | 302 | elif _Type == 'Vibration_Orientation': 303 | kwarg['Type'] = 243 304 | kwarg['Subtype'] = 19 305 | 306 | #groups 307 | elif _Type == 'LightGroup' or _Type == 'groups': 308 | if "_dim" in _Name: 309 | kwarg['Type'] = 244 310 | kwarg['Subtype'] = 62 311 | kwarg['Switchtype'] = 7 312 | else: 313 | kwarg['Type'] = 241 314 | kwarg['Subtype'] = 7 315 | kwarg['Switchtype'] = 7 316 | #if 'bulbs_group' in Images: 317 | # kwarg['Image'] = Images['bulbs_group'].ID 318 | 319 | #Scenes 320 | elif _Type == 'Scenes': 321 | kwarg['Type'] = 244 322 | kwarg['Subtype'] = 62 323 | kwarg['Switchtype'] = 9 324 | kwarg['Image'] = 9 325 | 326 | return kwarg 327 | --------------------------------------------------------------------------------