├── LICENSE ├── PnP-scripts ├── autodiscovery.pl └── autodiscovery_homeassistant.pl ├── README.md ├── dimmer.cpp ├── dimmer.h ├── esp-sensors.h ├── esp-sensors.ino ├── internal.cpp ├── internal.h ├── moveir.cpp ├── moveir.h ├── mqtt-support.cpp ├── mqtt-support.h ├── sonar.cpp ├── sonar.h ├── switch.cpp ├── switch.h ├── thermostat.cpp ├── thermostat.h ├── weather.cpp └── weather.h /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /PnP-scripts/autodiscovery.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | use strict; 4 | 5 | my $openhabItemsDir = "/etc/openhab2/items"; 6 | my $brokerName = "mybroker"; 7 | my $groupsFile = $openhabItemsDir . '/' . '000groups.items'; 8 | 9 | my %topics; 10 | 11 | open(INTOPICS, "timeout 10 mosquitto_sub -u testuser -P testtest -t /myhome/PNP/# -v |"); 12 | while () { 13 | if (/^\/myhome\/PNP(\/[^\/][^\s]+)\s+(.*)$/) { 14 | $topics{$1} = $2; 15 | } 16 | } 17 | close(INTOPICS); 18 | 19 | my %devices; 20 | my %allgroups; 21 | 22 | foreach my $key (keys %topics) { 23 | print "Topic: $key\n"; 24 | my @subkeys = split(/\//, $key); 25 | if (!exists($devices{$subkeys[2]})) { 26 | $devices{$subkeys[2]} = {}; 27 | } 28 | if (!exists($devices{$subkeys[2]}{$subkeys[3]})) { 29 | $devices{$subkeys[2]}{$subkeys[3]} = {'topic' => '/' . $subkeys[1] . '/' . $subkeys[2] . '/' . $subkeys[3] . '/status'}; 30 | } 31 | $devices{$subkeys[2]}{$subkeys[3]}{$subkeys[4]} = $topics{$key}; 32 | } 33 | 34 | # Add new groups to a groups file (and be sure it will be reloaded before all others) 35 | foreach my $device (keys %devices) { 36 | my @deviceParts = split(/[_-]/, $device); 37 | my %items = %{$devices{$device}}; 38 | $allgroups{$deviceParts[0]} = 1; 39 | # Find all groups 40 | foreach my $item (keys %items) { 41 | my %cur = %{$items{$item}}; 42 | my @curGroups = split(/ /, $cur{'groups'}); 43 | push @curGroups, $deviceParts[0]; 44 | $items{$item}{'arrGroups'} = \@curGroups; 45 | foreach my $addGroup (@curGroups) { 46 | $allgroups{$addGroup} = 1; 47 | } 48 | } 49 | } 50 | 51 | my %curgroups; 52 | open(IN, $groupsFile); 53 | while () { 54 | chomp; 55 | if (/^\s*#?\s*Group\s+([^\s]*)\s*$/) { 56 | $curgroups{$1} = 1; 57 | } 58 | } 59 | close(IN); 60 | open(OUT, ">>" . $groupsFile); 61 | foreach my $group (keys %allgroups) { 62 | if (!exists($curgroups{$group}) && ("$group" ne "")) { 63 | print OUT "Group $group\n"; 64 | } 65 | } 66 | close(OUT); 67 | system("chown openhab:openhab $groupsFile"); 68 | sleep(5); 69 | 70 | foreach my $device (keys %devices) { 71 | my $deviceFile = $openhabItemsDir . "/" . $device . ".items"; 72 | if (! -f $deviceFile && ("$device" ne "")) { 73 | print "Creating items file $deviceFile\n"; 74 | open(OUT, ">", $deviceFile); 75 | my %items = %{$devices{$device}}; 76 | my @deviceParts = split(/[_-]/, $device); 77 | print $deviceParts[0] . "\n"; 78 | foreach my $item (sort keys %items) { 79 | my %cur = %{$items{$item}}; 80 | my $itemGroups = join(',', @{$items{$item}{'arrGroups'}}); 81 | my @itemType = split(/:/, $cur{'type'}); 82 | if (exists $itemType[1]) { 83 | my $fullName = $device . "_" . $item; 84 | $fullName =~ s/-/_/g; 85 | print OUT $itemType[1] . " " . $fullName . " \"" 86 | . $fullName . " " . $cur{'name'} . " [%s]\""; 87 | print OUT " (" . $itemGroups . ") "; 88 | my $inTopic = ">[$brokerName:" . $cur{'topic'} . ":state:*:default]"; 89 | my $outTopic = "<[$brokerName:" . $cur{'topic'} . ":state:default]"; 90 | if ($itemType[0] eq 'I') { 91 | print OUT "{mqtt=\"$inTopic\"}"; 92 | } elsif ($itemType[0] eq 'O') { 93 | print OUT "{mqtt=\"$outTopic\"}"; 94 | } else { 95 | print OUT "{mqtt=\"$inTopic,$outTopic\"}"; 96 | } 97 | } 98 | print OUT "\n"; 99 | } 100 | close(OUT); 101 | system("chown openhab:openhab $deviceFile"); 102 | } 103 | } 104 | 105 | -------------------------------------------------------------------------------- /PnP-scripts/autodiscovery_homeassistant.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | use strict; 4 | 5 | my $hassItemsDir = "/home/homeassistant/.homeassistant"; 6 | my $brokerName = "mybroker"; 7 | my $hassIgnoreDir = "/home/homeassistant/.homeassistant/ignore"; 8 | 9 | my %topics; 10 | 11 | 12 | sub genTextSensor; 13 | sub genTextDimmer; 14 | sub genTextSwitch; 15 | 16 | open(INTOPICS, "timeout 10 mosquitto_sub -u testuser -P testtest -t /myhome/PNP/# -v |"); 17 | while () { 18 | if (/^\/myhome\/PNP(\/[^\/][^\s]+)\s+(.*)$/) { 19 | $topics{$1} = $2; 20 | } 21 | } 22 | close(INTOPICS); 23 | 24 | my %devices; 25 | 26 | foreach my $key (keys %topics) { 27 | print "Topic: $key\n"; 28 | my @subkeys = split(/\//, $key); 29 | if (!exists($devices{$subkeys[2]})) { 30 | $devices{$subkeys[2]} = {}; 31 | } 32 | if (!exists($devices{$subkeys[2]}{$subkeys[3]})) { 33 | $devices{$subkeys[2]}{$subkeys[3]} = {'topic' => '/' . $subkeys[1] . '/' . $subkeys[2] . '/' . $subkeys[3] . '/status'}; 34 | } 35 | $devices{$subkeys[2]}{$subkeys[3]}{$subkeys[4]} = $topics{$key}; 36 | } 37 | use Data::Dumper; 38 | print Dumper \%devices; 39 | 40 | my %groups; 41 | my @excludeHistory; 42 | 43 | foreach my $device (keys %devices) { 44 | my %items = %{$devices{$device}}; 45 | if ($device eq "") 46 | next; 47 | my @deviceParts = split(/[_-]/, $device); 48 | print "Device $device\n"; 49 | foreach my $item (keys %items) { 50 | print "Item $item\n"; 51 | my %cur = %{$items{$item}}; 52 | my $fullId = $device . "_" . $item; 53 | $fullId =~ s/-//g; 54 | my $name = $fullId . ' ' . $cur{'name'}; 55 | $cur{'descname'} = $name; 56 | my @curGroups = split(/ /, $cur{'groups'}); 57 | my @itemType = split(/:/, $cur{'type'}); 58 | my %existGroups = map { $_ => 1 } @curGroups; 59 | my $hassItemDom; 60 | my $hassItemText; 61 | if ($itemType[1] eq 'Number') { 62 | $hassItemDom = 'sensor'; 63 | $hassItemText = genTextSensor(\%cur); 64 | } elsif ($itemType[1] eq 'Dimmer') { 65 | $hassItemDom = 'light'; 66 | $hassItemText = genTextDimmer(\%cur); 67 | } else { 68 | $hassItemDom = 'switch'; 69 | $hassItemText = genTextSwitch(\%cur); 70 | } 71 | # Disable history for movement sensors, buttons, builtin leds and such 72 | if (exists($existGroups{'Movement'}) || exists($existGroups{'Builtin'}) || exists($existGroups{'ADC'})) { 73 | my $sensId = lc($name); 74 | $sensId =~ s/ /_/g; 75 | $sensId =~ s/-//g; 76 | push @excludeHistory, $hassItemDom . '.' . $sensId; 77 | } 78 | my $itemFile = $hassItemsDir . '/' . $hassItemDom . '/' . $fullId . '.yaml'; 79 | if (! -f $itemFile) { 80 | open(OUT, ">" . $itemFile); 81 | print OUT $hassItemText; 82 | close(OUT); 83 | system("chown homeassistant:homeassistant $itemFile"); 84 | } 85 | } 86 | } 87 | 88 | # Add ignore files (you can comment inside the file later!) 89 | foreach my $ignore (@excludeHistory) { 90 | my $ignoreFile = $hassIgnoreDir . "/" . $ignore . ".yaml"; 91 | if (! -f $ignoreFile) { 92 | open(OUT, ">" . $ignoreFile); 93 | print OUT "$ignore\n"; 94 | close(OUT); 95 | } 96 | } 97 | exit(0); 98 | 99 | sub genTextSensor { 100 | my $item = shift; 101 | 102 | my $text = <{'topic'}" 105 | name: "$item->{'descname'}" 106 | END_TEXT 107 | return $text; 108 | } 109 | 110 | sub genTextDimmer { 111 | my $item = shift; 112 | 113 | my $text = <{'topic'}" 116 | name: "$item->{'descname'}" 117 | qos: 1 118 | command_on_template: > 119 | {\% if brightness is defined \%} 120 | {{ (brightness * 100 / 255)| round(0) }} 121 | {\% else \%} 122 | 100 123 | {\% endif \%} 124 | command_off_template: "{{ 0 }}" 125 | brightness_template: > 126 | {\% if value == 'OFF' or value == 'off' \%} 127 | 0 128 | {\% else \%} 129 | {\% if value == 'ON' or value == 'on' \%} 130 | 255 131 | {\% else \%} 132 | {{ (float(value) * 255 / 100) | round(0) }} 133 | {\% endif \%} 134 | {\% endif \%} 135 | optimistic: true 136 | state_template: > 137 | {\% if (value | float > 0.0) \%} 138 | on 139 | {\% else \%} 140 | off 141 | {\% endif \%} 142 | END_TEXT 143 | return $text; 144 | } 145 | 146 | sub genTextSwitch { 147 | my $item = shift; 148 | 149 | my $text = <{'descname'}" 152 | state_topic: "$item->{'topic'}" 153 | command_topic: "$item->{'topic'}" 154 | payload_on: "ON" 155 | payload_off: "OFF" 156 | optimistic: false 157 | qos: 1 158 | retain: true 159 | END_TEXT 160 | return $text; 161 | } 162 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This arduino firmware turns ESP-8266 into MQTT-enabled plug&play sensor platform. It allows to receive updates and control for following sensors and devices: 2 | 3 | * Movement detection sensors (optical IR sensors and Parralax X-Band motion detector, up to 3 at one device) 4 | * DHT22 and GY-39 (serial mode) weather sensors 5 | * 4-ch LED strips dimmer through Modbus/RS-485: http://github.com/vasimv/StmDimmer-4ch 6 | * Internal ADC reading, flash button (GPIO0) and LED (GPIO2) 7 | * Simple thermostat (requires DHT-22) with two relays to control indoor (fan) and outdoor (compressor) units 8 | * HC-SR04 and Maxbotix serial sonars 9 | * Sonoff basic switch and Sonoff touch wall switch (last one can be configured to automatically turn on relay when pressed button or to control it through OpenHAB or HomeAssistant) 10 | 11 | Plug&Play feature uses scripts (see PnP-scripts directory) to update OpenHAB or HomeAssistant configuration when new device with the firmware is added to network by calling the script (manually or by cron). For openHAB it'll create items and groups file to include all sensors connected to the device. 12 | 13 | Other features are On-The-Air firmware update through ArduinoOTA, automatically switching to configuration mode to set WiFi-network authentication and MQTT broker's IP address, reporting to MQTT when the device is rebooted or reconnected to the MQTT broker. 14 | 15 | 16 | CONFIGURING 17 | 18 | Before compile you have to update file esp-sensors.h to uncomment modules you need and comment other ones (some modules are conflicting with eath other, see comments). The firmware needs some arduino libraries installed - Adafruit unified DHT22, PubSubClient. 19 | 20 | At first start - it'll switch to configuration mode to set Wifi and MQTT parameters. The device will start its own WiFi network with name like "espx-xxxxxxxx". You must connect to the network (default password is "passtest"), then go to "http://192.168.4.1" and set WiFi network name, password and MQTT broker's IP address (default username/password for MQTT is "testuser"/"testtest", you can redefine them in esp-sensors.h at compilation). 21 | 22 | If the device loses the network for long time (more than 60 seconds) - it'll turn configuration mode for 3 minutes (after this it'll try to connect to your network again). 23 | 24 | Some sensors can be turned off (DHT-22, internal ADC) through MQTT. 25 | 26 | 27 | ADVANCED 28 | 29 | It isn't hard to add other sensors/devices to this firmware, you have to create module with few functions to control it and report its statuses through MQTT. Modules are defined in source files: 30 | 31 | * Sonars - sonar.h/sonar.cpp 32 | * Movement detection - moveir.h/moveir.cpp 33 | * Internal LED and button - internal.h/internal.cpp 34 | * Sonoff basic and touch - switch.h/switch.cpp 35 | * Thermostat - thermostat.h/thermostat.cpp 36 | * Dimmer - dimmer.h/dimmer.cpp 37 | * DHT22 - weather.h/weather.cpp 38 | * GY-39 (serial) - weather.h/weather.cpp 39 | 40 | * void setup_*() functions do initialize hardware (pins and such) 41 | * void loop_*() functions do iterations at about every 10ms (can be delayed because other modules and stuff) 42 | * void refresh_*(boolean flagForce) functions will be called at every 200 ms (REFRESH_TIME in esp-sensors.h), only when connected to MQTT broker. Variable flagForce is set at every 2 seconds, modules will republish its values even if nothing changed 43 | * void pnp_*() functions will be called after connecting to broker, to publish Plug&play information about sensors 44 | * void subscribe_*() functions will be called at same time as pnp_* to subscribe to topics 45 | * boolean mqtt_*(char *topicCut, char *payload) will be called at incoming MQTT messages, should return true if found topic for the module 46 | -------------------------------------------------------------------------------- /dimmer.cpp: -------------------------------------------------------------------------------- 1 | // 4ch dimmer 2 | 3 | #include 4 | #include 5 | #include "dimmer.h" 6 | #include "mqtt-support.h" 7 | 8 | // publish PNP information to MQTT 9 | void pnp_dimmer() { 10 | pnp_mqtt(TOPIC_R_LED, "Red LED", "Dimmers LEDs Light", "I:Dimmer", NULL, NULL); 11 | pnp_mqtt(TOPIC_G_LED, "Green LED", "Dimmers LEDs Light", "I:Dimmer", NULL, NULL); 12 | pnp_mqtt(TOPIC_B_LED, "Blue LED", "Dimmers LEDs Light", "I:Dimmer", NULL, NULL); 13 | pnp_mqtt(TOPIC_W_LED, "White LED", "Dimmers LEDs Light", "I:Dimmer", NULL, NULL); 14 | pnp_mqtt(TOPIC_GRADUALLY, "Gradually on/off", "LEDs Switches", "I:Switch", NULL, NULL); 15 | } // void pnp_dimmer() 16 | 17 | // subscribe to MQTT topics 18 | void subscribe_dimmer() { 19 | subscribe_mqtt(TOPIC_R_LED); 20 | subscribe_mqtt(TOPIC_G_LED); 21 | subscribe_mqtt(TOPIC_B_LED); 22 | subscribe_mqtt(TOPIC_W_LED); 23 | subscribe_mqtt(TOPIC_GRADUALLY); 24 | } // void subscribe_dimmer() 25 | 26 | // LEDs state 27 | int16_t cLED[4]; 28 | // LEDs target luminiosity 29 | int16_t tLED[4]; 30 | 31 | int8_t FlagChangeLED = 0; 32 | uint8_t FlagGradually = 0; 33 | 34 | unsigned long startEffects = 0; 35 | unsigned long lastChangeEffect = 0; 36 | uint8_t stepEffect = 0; 37 | 38 | // Luminosity->PWM table (64->1024) 39 | // thank to Jared Sanson, https://jared.geek.nz/2013/feb/linear-led-pwm 40 | const uint16_t cie[127] = { 41 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 42 | 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 43 | 21, 23, 24, 26, 28, 30, 32, 34, 36, 38, 44 | 41, 43, 46, 49, 51, 54, 57, 60, 63, 67, 45 | 70, 74, 77, 81, 85, 89, 93, 98, 102, 107, 46 | 111, 116, 121, 126, 131, 137, 142, 148, 154, 160, 47 | 166, 172, 178, 185, 192, 199, 206, 213, 220, 228, 48 | 236, 244, 255, 260, 268, 277, 286, 295, 304, 313, 49 | 323, 333, 343, 353, 363, 374, 385, 395, 407, 418, 50 | 430, 441, 453, 466, 478, 491, 504, 511, 530, 544, 51 | 557, 571, 586, 600, 615, 630, 645, 660, 676, 692, 52 | 708, 725, 741, 758, 775, 793, 811, 828, 847, 865, 53 | 884, 903, 922, 942, 962, 982, 1002, 1023, 54 | }; 55 | 56 | uint16_t cieR[LED_PWMRANGE + 1]; 57 | 58 | // set up a new serial port 59 | SoftwareSerial mySerial(SW_rxPin, SW_txPin, false); 60 | 61 | // Find closest number in cie table 62 | int findCie(uint16_t pwm) { 63 | int prevP = 0; 64 | int i; 65 | 66 | for (i = 0; i < (sizeof(cie) / sizeof(cie[0])); i++) { 67 | if (pwm == cie[i]) 68 | return i; 69 | if (pwm < cie[i]) { 70 | if (abs(pwm - prevP) < abs(pwm - cie[i])) 71 | return i-1; 72 | return i; 73 | } 74 | prevP = cie[i]; 75 | } 76 | return i - 1; 77 | } // int findCie(uint16_t pwm) 78 | 79 | // Fast search in cieR table 80 | int findCieR(uint16_t pwm) { 81 | if (pwm > LED_PWMRANGE) 82 | pwm = LED_PWMRANGE; 83 | return cieR[pwm]; 84 | } // int findCieR(uint16_t pwm) 85 | 86 | // Set LEDs according ALL led status (with effects) 87 | void SetAllLED() { 88 | int i; 89 | int diff; 90 | 91 | if (!FlagGradually) { 92 | // Set luminosity immediately 93 | for (i = 0; i < 4; i++) { 94 | if (cLED[i] != tLED[i]) { 95 | cLED[i] = tLED[i]; 96 | FlagChangeLED = 2; 97 | } 98 | } 99 | } else { 100 | // Set luminosity gradually 101 | for (i = 0; i < 4; i++) { 102 | if (cLED[i] != tLED[i]) { 103 | int nCie = findCieR(cLED[i]); 104 | #ifdef DEBUG 105 | Serial.printf("findCieR(%d)=%d %u ms\n", cLED[i], nCie, millis()); 106 | #endif 107 | if (tLED[i] < cLED[i]) 108 | nCie--; 109 | else 110 | nCie++; 111 | if (nCie < 0) { 112 | nCie = 0; 113 | tLED[i] = cie[nCie]; 114 | } 115 | if (nCie > (sizeof(cie)/sizeof(cie[0]))) { 116 | nCie--; 117 | tLED[i] = cie[nCie]; 118 | } 119 | cLED[i] = cie[nCie]; 120 | FlagChangeLED = 2; 121 | } 122 | } 123 | } 124 | } // void SetAllLED() 125 | 126 | uint8_t bufModbusOut[128]; 127 | uint16_t cntOut = 0; 128 | 129 | // Calculate CRC for modbus frame 130 | uint16_t ModbusCrc(uint8_t *buf, int len) { 131 | uint32_t tmp, tmp2; 132 | uint8_t Flag; 133 | uint16_t i, j; 134 | 135 | tmp = 0xFFFF; 136 | for (i = 0; i < len; i++) { 137 | tmp = tmp ^ buf[i]; 138 | for (j = 1; j <= 8; j++) { 139 | Flag = tmp & 0x0001; 140 | tmp >>= 1; 141 | if (Flag) 142 | tmp ^= 0xA001; 143 | } 144 | } 145 | tmp2 = tmp >> 8; 146 | tmp = (tmp << 8) | tmp2; 147 | tmp &= 0xFFFF; 148 | return (uint16_t) tmp; 149 | } // uint16_t ModbusCrc(char *buf, int len) 150 | 151 | // Add CRC to output modbus packet 152 | void AddModbusCrc() { 153 | uint16_t tCrc; 154 | 155 | tCrc = ModbusCrc(bufModbusOut, cntOut); 156 | bufModbusOut[cntOut] = (tCrc >> 8) & 0xff; 157 | cntOut++; 158 | bufModbusOut[cntOut] = tCrc & 0xff; 159 | cntOut++; 160 | } // void AddModbusCrc() 161 | unsigned long lastRepeat = 0; 162 | 163 | // Send LEDs statuses to the dimmer by Modbus 164 | void SendLED() { 165 | int i; 166 | 167 | if (FlagChangeLED > 0) { 168 | if ((FlagChangeLED == 1) && ((millis() - lastRepeat) < 100)) 169 | return; 170 | bufModbusOut[0] = 247; 171 | bufModbusOut[1] = 16; 172 | bufModbusOut[2] = 0; 173 | bufModbusOut[3] = 0; 174 | bufModbusOut[4] = 0; 175 | bufModbusOut[5] = 4; 176 | bufModbusOut[6] = 8; 177 | for (i = 0; i < 4; i++) { 178 | #ifdef DEBUG 179 | Serial.print(i); 180 | Serial.print(':'); 181 | Serial.println(cLED[i]); 182 | #endif 183 | bufModbusOut[i * 2 + 7] = (cLED[i] >> 8) & 0xff; 184 | bufModbusOut[i * 2 + 8] = cLED[i] & 0xff; 185 | } 186 | lastRepeat = millis(); 187 | cntOut = 15; 188 | AddModbusCrc(); 189 | #ifdef DEBUG 190 | for (i = 0; i < cntOut; i++) { 191 | Serial.println(bufModbusOut[i]); 192 | } 193 | #endif 194 | digitalWrite(RS485_DE_PIN, HIGH); 195 | delay(1); 196 | mySerial.write(bufModbusOut, cntOut); 197 | digitalWrite(RS485_DE_PIN, LOW); 198 | #ifdef DEBUG 199 | Serial.write(bufModbusOut, cntOut); 200 | #endif 201 | FlagChangeLED--; 202 | if (FlagChangeLED < 0) 203 | FlagChangeLED = 0; 204 | } 205 | } // void SendLED() 206 | 207 | // Setup hardware (pins, etc) 208 | void setup_dimmer() { 209 | #ifndef DIMMER_SIMPLE_LEDS 210 | pinMode(RS485_DE_PIN, OUTPUT); 211 | digitalWrite(RS485_DE_PIN, LOW); 212 | mySerial.begin(38400); 213 | #else 214 | pinMode(LED_RED_PIN, OUTPUT); 215 | digitalWrite(LED_RED_PIN, LOW); 216 | pinMode(LED_BLUE_PIN, OUTPUT); 217 | digitalWrite(LED_BLUE_PIN, LOW); 218 | pinMode(LED_GREEN_PIN, OUTPUT); 219 | digitalWrite(LED_GREEN_PIN, LOW); 220 | pinMode(LED_WHITE_PIN, OUTPUT); 221 | digitalWrite(LED_WHITE_PIN, LOW); 222 | #endif 223 | 224 | memset((void *) cLED, 0, sizeof(cLED)); 225 | #ifdef DIMMER_START_FULL 226 | tLED[0] = LED_PWMRANGE; 227 | tLED[1] = LED_PWMRANGE; 228 | tLED[2] = LED_PWMRANGE; 229 | tLED[3] = LED_PWMRANGE; 230 | FlagGradually = 1; 231 | #else 232 | memset((void *) tLED, 0, sizeof(cLED)); 233 | #endif 234 | FlagChangeLED = 2; 235 | for (int i = 0; i <= LED_PWMRANGE; i++) 236 | cieR[i] = findCie(i); 237 | } // void setup_dimmer() 238 | 239 | unsigned long lastDimmer = 0; 240 | 241 | // must be called from loop() 242 | void loop_dimmer() { 243 | if ((millis() - lastDimmer) < 30) 244 | return; 245 | lastDimmer = millis(); 246 | SetAllLED(); 247 | // Repeat dimmer set frame every second (just in case) 248 | if (!FlagChangeLED && (millis() - lastRepeat) > 1000) 249 | FlagChangeLED = 1; 250 | #ifndef DIMMER_SIMPLE_LEDS 251 | SendLED(); 252 | #else 253 | analogWrite(LED_RED_PIN, cLED[0]); 254 | analogWrite(LED_GREEN_PIN, cLED[1]); 255 | analogWrite(LED_BLUE_PIN, cLED[2]); 256 | analogWrite(LED_WHITE_PIN, cLED[3]); 257 | #endif 258 | } // void loop_dimmer() 259 | 260 | // periodic refreshing values to MQTT 261 | void refresh_dimmer(boolean flagForce) { 262 | if (flagForce) { 263 | publish_mqttS(TOPIC_GRADUALLY, (char *) (FlagGradually ? "ON" : "OFF"), true); 264 | publish_mqttI(TOPIC_R_LED, (cLED[0] * 100) / LED_PWMRANGE, true); 265 | publish_mqttI(TOPIC_G_LED, (cLED[1] * 100) / LED_PWMRANGE, true); 266 | publish_mqttI(TOPIC_B_LED, (cLED[2] * 100) / LED_PWMRANGE, true); 267 | publish_mqttI(TOPIC_W_LED, (cLED[3] * 100) / LED_PWMRANGE, true); 268 | } 269 | } // void refresh_dimmer(boolean flagForce) 270 | 271 | // Check message for ON/OFF or number in percents 272 | int dimmerLight(char *payload) { 273 | if (cmpPayloadON(payload)) 274 | return 100; 275 | if (cmpPayloadOFF(payload)) 276 | return 0; 277 | return strtod(payload, NULL); 278 | } // int dimmerLight(char *payload) 279 | 280 | // Check case when we're turning off lights with gradually on 281 | void checkGradually(int lightNum) { 282 | // Set target to closest value of cie table 283 | tLED[lightNum] = cie[findCieR(tLED[lightNum])]; 284 | int differ = cLED[lightNum] - tLED[lightNum]; 285 | 286 | // Not gradually or turning on - just set choosed level 287 | if (!FlagGradually || (differ <= 0)) 288 | return; 289 | // Gradually OFF - drop level to 50% at first! 290 | #ifdef DIMMER_GRADUALLY_FAST_OFF 291 | cLED[lightNum] = cLED[lightNum] - differ / 2; 292 | #endif 293 | } // void checkGradually(int lightNum) 294 | 295 | // hook for incoming MQTT messages 296 | boolean mqtt_dimmer(char *topicCut, char *payload) { 297 | if (cmpTopic(topicCut, TOPIC_R_LED)) { 298 | tLED[0] = (dimmerLight(payload) * LED_PWMRANGE) / 100; 299 | checkGradually(0); 300 | #ifdef DEBUG 301 | Serial.print("Red color: "); 302 | Serial.println(tLED[0]); 303 | #endif 304 | return true; 305 | } else if (cmpTopic(topicCut, TOPIC_G_LED)) { 306 | tLED[1] = (dimmerLight(payload) * LED_PWMRANGE) / 100; 307 | checkGradually(1); 308 | #ifdef DEBUG 309 | Serial.print("Green color: "); 310 | Serial.println(tLED[1]); 311 | #endif 312 | return true; 313 | } else if (cmpTopic(topicCut, TOPIC_B_LED)) { 314 | tLED[2] = (dimmerLight(payload) * LED_PWMRANGE) / 100; 315 | checkGradually(2); 316 | #ifdef DEBUG 317 | Serial.print("Blue color: "); 318 | Serial.println(tLED[2]); 319 | #endif 320 | return true; 321 | } else if (cmpTopic(topicCut, TOPIC_W_LED)) { 322 | tLED[3] = (dimmerLight(payload) * LED_PWMRANGE) / 100; 323 | checkGradually(3); 324 | #ifdef DEBUG 325 | Serial.print("White color: "); 326 | Serial.println(tLED[3]); 327 | #endif 328 | return true; 329 | } else if (cmpTopic(topicCut, TOPIC_GRADUALLY)) { 330 | if (cmpPayloadON(payload)) 331 | FlagGradually = 1; 332 | else 333 | FlagGradually = 0; 334 | return true; 335 | } 336 | return false; 337 | } // boolean mqtt_dimmer(char *topicCut, char *payload) 338 | -------------------------------------------------------------------------------- /dimmer.h: -------------------------------------------------------------------------------- 1 | // 4ch dimmer 2 | 3 | #ifndef _DIMMER_H 4 | #define _DIMMER_H 5 | 6 | #include "esp-sensors.h" 7 | 8 | 9 | // publish PNP information to MQTT 10 | void pnp_dimmer(); 11 | 12 | // subscribe to MQTT topics 13 | void subscribe_dimmer(); 14 | 15 | // Setup hardware (pins, etc) 16 | void setup_dimmer(); 17 | 18 | // must be called from loop() 19 | void loop_dimmer(); 20 | 21 | // periodic refreshing values to MQTT 22 | void refresh_dimmer(boolean flagForce); 23 | 24 | // hook for incoming MQTT messages 25 | boolean mqtt_dimmer(char *topicCut, char *payload); 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /esp-sensors.h: -------------------------------------------------------------------------------- 1 | // Main configuration and includes 2 | 3 | #ifndef _ESP_SENSORS_H 4 | #define _ESP_SENSORS_H 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | // Call ESP.restart() after timeout in configure mode 14 | #define RESTART_AFTER_CONFIGURE 15 | 16 | // What modules to use: 17 | // HC-SR04 sonar (conflicts with MAXBOTIX_CONTROL!), sonar.cpp 18 | // #define HCSR04_CONTROL 19 | 20 | // Maxbotix serial sonar (conflicts with HCSR04_CONTROL and DIMMER_CONTROL!), sonar.cpp 21 | // #define MAXBOTIX_CONTROL 22 | 23 | // Modbus 4-ch dimmer (conflicts with MAXBOTIX_CONTROL!), dimmer.cpp 24 | #define DIMMER_CONTROL 25 | 26 | // Switch to direct four LEDs control instead modbus dimmer [RGBW stripe with N-FET Mosfet control] 27 | // (conflicts with MOVEMENT_CONTROL, HCSR04_CONTROL, SONOFF_CONTROL, MAXBOTIX_CONTROL, THERMOSTAT_CONTROL!), dimmer.cpp 28 | // #define DIMMER_SIMPLE_LEDS 29 | 30 | // Fast turning off when gradually is on 31 | //#define DIMMER_GRADUALLY_FAST_OFF 32 | 33 | // Slowly turn on dimmer at start 34 | #define DIMMER_START_FULL 35 | 36 | // Simple thermostat control (conflicts with MOVEMENT_CONTROL and SONOFF_CONTROL!), thermostat.cpp 37 | // #define THERMOSTAT_CONTROL 38 | 39 | // IR and X-band radio movement sensors (conflicts with THERMOSTAT_CONTROL and SONOFF_CONTROL!), moveir.cpp 40 | #define MOVEMENT_CONTROL 41 | 42 | // DHT22 weather sensor (must be included for THERMOSTAT_CONTROL, conflicts with GY39_CONTROL!), weather.cpp 43 | // #define DHT22_CONTROL 44 | 45 | // GY-39 weather sensor over serial port (conflicts with DHT22_CONTROL!), weather.cpp 46 | // #define GY39_CONTROL 47 | 48 | // Sonoff basic and Sonoff touch (conflicts with MOVEMENT_CONTROL!), switch.cpp 49 | // #define SONOFF_CONTROL 50 | 51 | 52 | // Configuration stuff: 53 | // Debug output to serial port 54 | // #define DEBUG 55 | 56 | // How often to call refresh_* functions, milliseconds 57 | #define REFRESH_TIME 200 58 | 59 | // How often to call refresh_* functions with flagForce, milliseconds 60 | #define FORCE_TIME 2000 61 | 62 | // Disable internal led blinking at connecting 63 | //#define DISABE_BLINK 64 | 65 | // Configuration Wifi network password 66 | #define WIFI_CONFIGURE_PASS "passtest" 67 | 68 | // MQTT username and password 69 | #define MQTT_USER_NAME "testuser" 70 | #define MQTT_PASSWORD "testtest" 71 | #define MQTT_PORT 1883 72 | 73 | // MQTT Prefixes 74 | #define MQTT_PREFIX "/myhome/ESPX-" 75 | #define MQTT_NAME "espx-" 76 | #define MQTT_PNP_PREFIX "/myhome/PNP" 77 | 78 | // OTA firmware upload password 79 | #define OTA_UPLOAD_PASS "Bi38s2iw" 80 | 81 | // Dimmer's PWM maximum (must be 255/511/1023 82 | #define LED_PWMRANGE 1023 83 | 84 | // Hystersis of thermostat regulation (in celsius) 85 | #define THERMOSTAT_HYSTERSIS 1.0f 86 | 87 | 88 | // Pins definition 89 | // HC-SR04 sonar pins 90 | #define HCSR04_ECHO 4 91 | #define HCSR04_TRIG 15 92 | 93 | // Serial port pins (for dimmer or maxbotix) 94 | #define SW_rxPin 16 95 | #define SW_txPin 4 96 | #define RS485_DE_PIN 15 97 | 98 | // Thermostat pins 99 | #define FAN_RELAY 4 100 | #define COMPRESSOR_RELAY 15 101 | #define LED_OFF 14 102 | #define LED_ON 12 103 | #define LED_GND 13 104 | 105 | // DHT22 pin 106 | #define DHTPIN 5 107 | 108 | // GY39 pin 109 | #define GY39PIN 5 110 | 111 | // Internal LED and button pins 112 | #define LED 2 113 | #define BUTTON 0 114 | 115 | // Movement sensors pins 116 | #define IR_SENSE 14 117 | #define RADIO_SENSE 12 118 | #define ADD_SENSE 13 119 | 120 | // Sonoff basic and Sonoff touch AC relay pin 121 | #define RELAY 12 122 | 123 | // Four LEDs control 124 | #define LED_RED_PIN 14 125 | #define LED_BLUE_PIN 13 126 | #define LED_GREEN_PIN 4 127 | #define LED_WHITE_PIN 12 128 | 129 | // MQTT Topics names 130 | // esp-sensors.cpp 131 | #define TOPIC_REBOOT "REBOOT" 132 | #define TOPIC_RECONNECT "RECONNECT" 133 | 134 | // internal.cpp 135 | #define TOPIC_BUTTON "BUTTON" 136 | #define TOPIC_LED "LED" 137 | #define TOPIC_ADC "ADC" 138 | #define TOPIC_ADC_CONTROL "ADCSWITCH" 139 | #define TOPIC_MILLIS "MILLIS" 140 | 141 | // moveir.cpp 142 | #define TOPIC_IR_SENSE "MOVEIR" 143 | #define TOPIC_RADIO_SENSE "MOVERADIO" 144 | #define TOPIC_ADDITIONAL "MOVEADD" 145 | 146 | // sonar.cpp 147 | #define TOPIC_DISTANCE "DISTANCE" 148 | 149 | // dimmer.cpp 150 | #define TOPIC_R_LED "LED_RED" 151 | #define TOPIC_G_LED "LED_GREEN" 152 | #define TOPIC_B_LED "LED_BLUE" 153 | #define TOPIC_W_LED "LED_WHITE" 154 | #define TOPIC_GRADUALLY "GRADUALLY" 155 | 156 | // weather.cpp 157 | #define TOPIC_DHT "DHT" 158 | #define TOPIC_TEMPERATURE "TEMPERATURE" 159 | #define TOPIC_HUMIDITY "HUMIDITY" 160 | #define TOPIC_GY39 "GY39" 161 | #define TOPIC_ILLUMINATION "ILLUMINATION" 162 | #define TOPIC_PRESSURE "PRESSURE" 163 | 164 | // switch.cpp 165 | #define TOPIC_RELAY "RELAY" 166 | #define TOPIC_AUTO_RELAY "AUTOSWITCH" 167 | 168 | // thermostat.cpp 169 | #define TOPIC_FAN_AUTO "FAN_AUTO" 170 | #define TOPIC_FAN "FAN" 171 | #define TOPIC_FAN_MANUAL "FAN_MANUAL" 172 | #define TOPIC_COMPRESSOR_AUTO "COMPRESSOR_AUTO" 173 | #define TOPIC_COMPRESSOR_STATUS "COMPRESSOR_STATUS" 174 | #define TOPIC_COMPRESSOR "COMPRESSOR" 175 | #define TOPIC_TEMP_AUTO "AUTO_TEMP" 176 | #define TOPIC_LED_ON "LED_ON" 177 | #define TOPIC_LED_OFF "LED_OFF" 178 | 179 | 180 | extern WiFiClient wifi; 181 | extern PubSubClient myClient; 182 | 183 | #ifndef SW_SERIAL_UNUSED_PIN 184 | #define SW_SERIAL_UNUSED_PIN -1 185 | #endif 186 | 187 | #endif 188 | -------------------------------------------------------------------------------- /esp-sensors.ino: -------------------------------------------------------------------------------- 1 | // ESP-8266 as MQTT sensors platform 2 | 3 | #include "esp-sensors.h" 4 | #include "mqtt-support.h" 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "dimmer.h" 12 | #include "moveir.h" 13 | #include "internal.h" 14 | #include "sonar.h" 15 | #include "switch.h" 16 | #include "thermostat.h" 17 | #include "weather.h" 18 | 19 | // Configure web server 20 | ESP8266WebServer server(80); 21 | 22 | // Wifi and MQTT connections 23 | WiFiClient wifi; 24 | PubSubClient myClient(wifi); 25 | 26 | // Configure mode flag (create AP with web server to configure wifi and mqtt server) 27 | uint8_t FlagConfigure; 28 | boolean signatureConf = false; 29 | 30 | // Full MQTT prefix (with chip serial ID) 31 | char mqttPrefixNameS[32]; 32 | uint8_t mqttPrefixNameLength; 33 | 34 | // MQTT Client name (with chip serial ID) 35 | char mqttClientName[32]; 36 | 37 | // Wifi and MQTT connection parameters 38 | char wifiSsid[32]; 39 | char wifiPass[16]; 40 | char mqttServer[16]; 41 | 42 | // Connected to MQTT flag 43 | boolean connected = false; 44 | 45 | // MQTT callback function (incoming messages) 46 | void mqttCallback(char* topic, byte* payload, unsigned int length) { 47 | char *topicCut; 48 | char payloadBuffer[32]; 49 | int lengthBuffer; 50 | 51 | lengthBuffer = length; 52 | if (length >= sizeof(payloadBuffer)) 53 | lengthBuffer = sizeof(payloadBuffer) - 1; 54 | memcpy(payloadBuffer, payload, lengthBuffer); 55 | payloadBuffer[lengthBuffer] = 0; 56 | topicCut = topic + mqttPrefixNameLength; 57 | #ifdef DEBUG 58 | Serial.print("Topic received: "); 59 | Serial.println(topicCut); 60 | Serial.print("Payload: "); 61 | Serial.println((char *) payloadBuffer); 62 | #endif 63 | 64 | // Now check all modules if the message for one of them 65 | if (mqtt_internal(topicCut, payloadBuffer)) 66 | return; 67 | 68 | #ifdef MOVEMENT_CONTROL 69 | if (mqtt_moveir(topicCut, payloadBuffer)) 70 | return; 71 | #endif 72 | #ifdef DIMMER_CONTROL 73 | if (mqtt_dimmer(topicCut, payloadBuffer)) 74 | return; 75 | #endif 76 | #if defined(MAXBOTIX_CONTROL) || defined(HCSR04_CONTROL) 77 | if (mqtt_sonar(topicCut, payloadBuffer)) 78 | return; 79 | #endif 80 | #if defined(DHT22_CONTROL) || defined(GY39_CONTROL) 81 | if (mqtt_weather(topicCut, payloadBuffer)) 82 | return; 83 | #endif 84 | #ifdef SONOFF_CONTROL 85 | if (mqtt_switch(topicCut, payloadBuffer)) 86 | return; 87 | #endif 88 | #ifdef THERMOSTAT_CONTROL 89 | if (mqtt_thermostat(topicCut, payloadBuffer)) 90 | return; 91 | #endif 92 | #ifdef DEBUG 93 | Serial.println("Unknown message, no modules for it!"); 94 | #endif 95 | } // void mqttCallback(char* topic, byte* payload, unsigned int length) 96 | 97 | // Subscribe and publish Plug&Play information to MQTT 98 | void pnpAndSubscribe() { 99 | // Reset & reconnect flags pnp information 100 | pnp_mqtt(TOPIC_REBOOT, "Reboot alarm flag", "Builtin Switches Alarm", "O:Switch", NULL, NULL); 101 | pnp_mqtt(TOPIC_RECONNECT, "Reconnect alarm flag", "Builtin Switches Alarm", "O:Switch", NULL, NULL); 102 | 103 | // All modules subscribe & PnP 104 | pnp_internal(); 105 | subscribe_internal(); 106 | #ifdef MOVEMENT_CONTROL 107 | pnp_moveir(); 108 | subscribe_moveir(); 109 | #endif 110 | #ifdef DIMMER_CONTROL 111 | pnp_dimmer(); 112 | subscribe_dimmer(); 113 | #endif 114 | #if defined(MAXBOTIX_CONTROL) || defined(HCSR04_CONTROL) 115 | pnp_sonar(); 116 | subscribe_sonar(); 117 | #endif 118 | #if defined(DHT22_CONTROL) || defined(GY39_CONTROL) 119 | pnp_weather(); 120 | subscribe_weather(); 121 | #endif 122 | #ifdef SONOFF_CONTROL 123 | pnp_switch(); 124 | subscribe_switch(); 125 | #endif 126 | #ifdef THERMOSTAT_CONTROL 127 | pnp_thermostat(); 128 | subscribe_thermostat(); 129 | #endif 130 | } // void pnpAndSubscribe() 131 | 132 | // Use chip ID to generate unique MQTT prefix 133 | void generateMqttName() { 134 | sprintf(mqttPrefixNameS, "%s%08X/", MQTT_PREFIX, ESP.getChipId()); 135 | mqttPrefixName = mqttPrefixNameS; 136 | mqttPrefixNameLength = strlen(mqttPrefixNameS); 137 | sprintf(mqttClientName, "%s%08X", MQTT_NAME, ESP.getChipId()); 138 | #ifdef DEBUG 139 | Serial.print("Auto-generated MQTT prefix: "); 140 | Serial.println(mqttPrefixName); 141 | Serial.print("Auto-generated MQTT name: "); 142 | Serial.println(mqttClientName); 143 | #endif 144 | } // void generateMQTTName() 145 | 146 | // When we started configure mode 147 | unsigned long startConfigure = 0; 148 | // When we started wifi fconnecting 149 | unsigned long startConnecting = 0; 150 | // Reboot and reconnects report timers (if == 1 then report it for 10 seconds) 151 | unsigned long lastReboot = 1; 152 | unsigned long lastReconnect = 1; 153 | 154 | String content; 155 | int statusCode; 156 | 157 | // Create web server in configure mode 158 | void createWebServer() { 159 | server.begin(); 160 | server.on("/", []() { 161 | IPAddress ip = WiFi.softAPIP(); 162 | String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]); 163 | content = "\r\nHello from ESP8266 at "; 164 | content += ipStr; 165 | content += "

"; 166 | content += "

"; 167 | content += "
"; 168 | content += "

"; 169 | content += ""; 170 | server.send(200, "text/html", content); 171 | startConfigure = millis(); 172 | }); 173 | server.on("/setting", []() { 174 | String qsid = server.arg("ssid"); 175 | String qpass = server.arg("pass"); 176 | String mqttip = server.arg("mqttip"); 177 | if ((qsid.length() > 0) && (qpass.length() > 0) && (mqttip.length() > 0)) { 178 | #ifdef DEBUG 179 | Serial.println("Writing to EEPROM"); 180 | Serial.println("writing eeprom ssid:"); 181 | #endif 182 | EEPROM.begin(512); 183 | // Write signature 184 | EEPROM.write(0, 0xA5); 185 | strncpy(wifiSsid, qsid.c_str(), sizeof(wifiSsid) - 1); 186 | wifiSsid[sizeof(wifiSsid) - 1] = '\0'; 187 | strncpy(wifiPass, qpass.c_str(), sizeof(wifiPass) - 1); 188 | wifiPass[sizeof(wifiPass) - 1] = '\0'; 189 | strncpy(mqttServer, mqttip.c_str(), sizeof(mqttServer) - 1); 190 | mqttServer[sizeof(mqttServer) - 1] = '\0'; 191 | for (int i = 0; i < sizeof(wifiSsid); i++) { 192 | EEPROM.write(i + 1, wifiSsid[i]); 193 | #ifdef DEBUG 194 | Serial.print("Wrote: "); 195 | Serial.println(wifiSsid[i]); 196 | #endif 197 | } 198 | #ifdef DEBUG 199 | Serial.println("writing eeprom pass:"); 200 | #endif 201 | for (int i = 0; i < sizeof(wifiPass); i++) { 202 | EEPROM.write(i + sizeof(wifiSsid) + 1, wifiPass[i]); 203 | #ifdef DEBUG 204 | Serial.print("Wrote: "); 205 | Serial.println(wifiPass[i]); 206 | #endif 207 | } 208 | #ifdef DEBUG 209 | Serial.println("writing eeprom mqtt broker ip:"); 210 | #endif 211 | for (int i = 0; i < sizeof(mqttServer); i++) { 212 | EEPROM.write(i + sizeof(wifiSsid) + sizeof(wifiPass) + 1, mqttServer[i]); 213 | #ifdef DEBUG 214 | Serial.print("Wrote: "); 215 | Serial.println(mqttServer[i]); 216 | #endif 217 | } 218 | EEPROM.commit(); 219 | EEPROM.end(); 220 | content = "{\"Success\":\"saved to eeprom... restarting to boot into new wifi\"}"; 221 | statusCode = 200; 222 | server.send(statusCode, "application/json", content); 223 | FlagConfigure = 0; 224 | delay(1000); 225 | WiFi.disconnect(); 226 | ESP.restart(); 227 | } else { 228 | content = "{\"Error\":\"404 not found\"}"; 229 | statusCode = 404; 230 | Serial.println("Sending 404"); 231 | server.send(statusCode, "application/json", content); 232 | } 233 | }); 234 | } // void createWebServer() 235 | 236 | // Connect to wifi 237 | void setupWifi(boolean configureNetwork) { 238 | int numAttempts = 0; 239 | 240 | connected = false; 241 | #ifdef DEBUG 242 | Serial.print("wifi status (before disconnect): "); 243 | Serial.println(WiFi.status()); 244 | #endif 245 | WiFi.mode(WIFI_STA); 246 | WiFi.disconnect(); 247 | delay(10); 248 | 249 | if (!configureNetwork) { 250 | // We start by connecting to a WiFi network 251 | #ifdef DEBUG 252 | Serial.println(); 253 | Serial.print("Connecting to "); 254 | Serial.println(wifiSsid); 255 | #endif 256 | 257 | FlagConfigure = 0; 258 | WiFi.mode(WIFI_STA); 259 | WiFi.begin(wifiSsid, wifiPass); 260 | startConnecting = millis(); 261 | } else { 262 | #ifdef DEBUG 263 | Serial.println("Switching to configure mode!"); 264 | #endif 265 | FlagConfigure = 1; 266 | WiFi.mode(WIFI_STA); 267 | WiFi.disconnect(); 268 | #ifdef DEBUG 269 | Serial.print("Create AP to configure wifi parameters, SSID="); 270 | Serial.println(mqttClientName); 271 | #endif 272 | WiFi.mode(WIFI_AP); 273 | WiFi.softAP(mqttClientName, WIFI_CONFIGURE_PASS); 274 | createWebServer(); 275 | startConfigure = millis(); 276 | } 277 | } // void setup_wifi() 278 | 279 | // Check MQTT and Wifi connection, reconnect if needed 280 | void checkConnection() { 281 | int numAttempts = 0; 282 | 283 | if (WiFi.status() != WL_CONNECTED) { 284 | // Check if we lost connection just 285 | if (connected) { 286 | connected = false; 287 | setupWifi(false); 288 | return; 289 | } 290 | 291 | if ((millis() - startConnecting) > 60000) { 292 | if (!FlagConfigure) 293 | setupWifi(true); 294 | else { 295 | if (signatureConf && ((millis() - startConfigure) > 180000)) { 296 | #ifdef RESTART_AFTER_CONFIGURE 297 | ESP.restart(); 298 | #endif 299 | setupWifi(false); 300 | } 301 | } 302 | } 303 | return; 304 | } 305 | 306 | if (!connected) { 307 | // OTA setup 308 | delay(20); 309 | ArduinoOTA.setPort(8266); 310 | ArduinoOTA.setHostname(mqttClientName); 311 | ArduinoOTA.setPassword(OTA_UPLOAD_PASS); 312 | ArduinoOTA.begin(); 313 | } 314 | 315 | // Loop until we're reconnected 316 | while (!check_mqtt()) { 317 | #ifdef DEBUG 318 | Serial.print("Attempting MQTT connection..."); 319 | #endif 320 | lastReconnect = 1; 321 | 322 | // Attempt to connect to MQTT broker 323 | if (connect_mqtt(mqttServer, mqttClientName, MQTT_USER_NAME, MQTT_PASSWORD, mqttCallback)) { 324 | #ifdef DEBUG 325 | Serial.println("connected to MQTT"); 326 | Serial.println("Resubscribing to MQTT topics"); 327 | #endif 328 | pnpAndSubscribe(); 329 | } else { 330 | #ifdef DEBUG 331 | Serial.print("failed, rc="); 332 | Serial.print(myClient.state()); 333 | Serial.println(" try again in 5 seconds"); 334 | #endif 335 | // Wait 5 seconds before retrying 336 | #ifndef DISABLE_BLINK 337 | for (int i = 0; i < 5; i++) { 338 | digitalWrite(LED, LOW); 339 | delay(500); 340 | digitalWrite(LED, HIGH); 341 | delay(500); 342 | } 343 | #else 344 | delay(10); 345 | #endif 346 | numAttempts++; 347 | // Check if we have enough of this and start in configure mode 348 | if (numAttempts > 5) { 349 | #ifdef DEBUG 350 | Serial.println("Switching to configure mode!"); 351 | #endif 352 | setupWifi(true); 353 | return; 354 | } 355 | } 356 | } 357 | connected = true; 358 | } // void check_connection() 359 | 360 | // Main setup function 361 | void setup() { 362 | lastReboot = 1; 363 | Serial.begin(38400); 364 | #ifdef DEBUG 365 | Serial.println("Reboot"); 366 | #endif 367 | generateMqttName(); 368 | 369 | // Setup for all modules 370 | setup_internal(); 371 | #ifdef MOVEMENT_CONTROL 372 | setup_moveir(); 373 | #endif 374 | #ifdef DIMMER_CONTROL 375 | setup_dimmer(); 376 | #endif 377 | #if defined(MAXBOTIX_CONTROL) || defined(HCSR04_CONTROL) 378 | setup_sonar(); 379 | #endif 380 | #if defined(DHT22_CONTROL) || defined(GY39_CONTROL) 381 | setup_weather(); 382 | #endif 383 | #ifdef SONOFF_CONTROL 384 | setup_switch(); 385 | #endif 386 | #ifdef THERMOSTAT_CONTROL 387 | setup_thermostat(); 388 | #endif 389 | 390 | ESP.wdtDisable(); 391 | ESP.wdtEnable(3000); 392 | 393 | EEPROM.begin(512); 394 | #ifdef DEBUG 395 | Serial.print("Signature in EEPROM: "); 396 | Serial.println(EEPROM.read(0)); 397 | #endif 398 | // Check if we have stored configuration data 399 | if (EEPROM.read(0) != 0xA5) { 400 | // No parameters in EEPROM, start configuration mode 401 | signatureConf = false; 402 | setupWifi(true); 403 | } else { 404 | signatureConf = true; 405 | for (int i = 0; i < sizeof(wifiSsid); i++) 406 | wifiSsid[i] = EEPROM.read(i + 1); 407 | for (int i = 0; i < sizeof(wifiPass); i++) 408 | wifiPass[i] = EEPROM.read(i + sizeof(wifiSsid) + 1); 409 | for (int i = 0; i < sizeof(mqttServer); i++) 410 | mqttServer[i] = EEPROM.read(i + sizeof(wifiSsid) + sizeof(wifiPass) + 1); 411 | #ifdef DEBUG 412 | Serial.print("Found WIFI parameters in EEPROM: "); 413 | Serial.print(wifiSsid); 414 | Serial.print(" "); 415 | Serial.print(wifiPass); 416 | Serial.print(" "); 417 | Serial.println(mqttServer); 418 | #endif 419 | setupWifi(false); 420 | } 421 | EEPROM.end(); 422 | } // void setup() 423 | 424 | // Force send gratious ARP to prevent losing network 425 | extern "C" { 426 | extern struct netif *netif_list; 427 | uint8_t etharp_request(char *, char *); 428 | } 429 | 430 | unsigned long lastARP = 0; 431 | 432 | void forceARP() { 433 | char *netif = (char *) netif_list; 434 | 435 | if ((millis() - lastARP) < 500) 436 | return; 437 | lastARP = millis(); 438 | 439 | while (netif) { 440 | etharp_request((netif), (netif + 4)); 441 | netif = *((char **) netif); 442 | } 443 | } // void forceARP() 444 | 445 | 446 | unsigned long lastRefresh = 0; 447 | unsigned long lastLEDToggle = 0; 448 | unsigned long lastForce = 0; 449 | 450 | // Main loop function 451 | void loop() { 452 | unsigned long lastCycle = millis(); 453 | int delayNeeded; 454 | 455 | // Check Wifi and MQTT connections 456 | checkConnection(); 457 | 458 | // Loop check for all modules (even if not connected) 459 | loop_internal(); 460 | #ifdef MOVEMENT_CONTROL 461 | loop_moveir(); 462 | #endif 463 | #ifdef DIMMER_CONTROL 464 | loop_dimmer(); 465 | #endif 466 | #if defined(MAXBOTIX_CONTROL) || defined(HCSR04_CONTROL) 467 | loop_sonar(); 468 | #endif 469 | #if defined(DHT22_CONTROL) || defined(GY39_CONTROL) 470 | loop_weather(); 471 | #endif 472 | #ifdef SONOFF_CONTROL 473 | loop_switch(); 474 | #endif 475 | #ifdef THERMOSTAT_CONTROL 476 | loop_thermostat(); 477 | #endif 478 | 479 | // MQTT loop check 480 | if (check_mqtt()) 481 | mqtt_loop(); 482 | 483 | // Arduino OTA check and force send gratious ARP 484 | if (WiFi.status() == WL_CONNECTED) { 485 | ArduinoOTA.handle(); 486 | forceARP(); 487 | } 488 | 489 | // Check configuration web server 490 | if (FlagConfigure) 491 | server.handleClient(); 492 | 493 | 494 | // Periodic call to refresh functions (if we're connected only!) 495 | if (check_mqtt() && ((millis() - lastRefresh) > REFRESH_TIME)) { 496 | boolean flagForce = false; 497 | 498 | lastRefresh = millis(); 499 | 500 | if ((millis() - lastForce) > FORCE_TIME) { 501 | lastForce = millis(); 502 | flagForce = true; 503 | } 504 | 505 | // Repeat reconnect and reboot flags for 10 seconds after it is on 506 | if (lastReboot) { 507 | if (lastReboot == 1) 508 | lastReboot = millis(); 509 | 510 | if ((millis() - lastReboot) < 10000) { 511 | publish_mqttS(TOPIC_REBOOT, "ON"); 512 | } else { 513 | // reset reboot report flag 514 | publish_mqttS(TOPIC_REBOOT, "OFF"); 515 | lastReboot = 0; 516 | } 517 | } else 518 | if (flagForce) 519 | publish_mqttS(TOPIC_REBOOT, "OFF"); 520 | if (lastReconnect) { 521 | if (lastReconnect == 1) 522 | lastReconnect = millis(); 523 | 524 | if ((millis() - lastReconnect) < 10000) { 525 | publish_mqttS(TOPIC_RECONNECT, "ON"); 526 | } else { 527 | // reset reconnect report flag 528 | publish_mqttS(TOPIC_RECONNECT, "OFF"); 529 | lastReconnect = 0; 530 | } 531 | } else 532 | if (flagForce) 533 | publish_mqttS(TOPIC_RECONNECT, "OFF"); 534 | 535 | 536 | // Refreshing all modules 537 | refresh_internal(flagForce); 538 | #ifdef MOVEMENT_CONTROL 539 | refresh_moveir(flagForce); 540 | #endif 541 | #ifdef DIMMER_CONTROL 542 | refresh_dimmer(flagForce); 543 | #endif 544 | #if defined(MAXBOTIX_CONTROL) || defined(HCSR04_CONTROL) 545 | refresh_sonar(flagForce); 546 | #endif 547 | #if defined(DHT22_CONTROL) || defined(GY39_CONTROL) 548 | refresh_weather(flagForce); 549 | #endif 550 | #ifdef SONOFF_CONTROL 551 | refresh_switch(flagForce); 552 | #endif 553 | #ifdef THERMOSTAT_CONTROL 554 | refresh_thermostat(flagForce); 555 | #endif 556 | } 557 | 558 | #ifndef DISABLE_BLINK 559 | // Blink LED at connect/configure 560 | if (!connected) { 561 | int delayBlink = 500; 562 | 563 | if (FlagConfigure) 564 | delayBlink = 75; 565 | if ((millis() - lastLEDToggle) > delayBlink) { 566 | lastLEDToggle = millis(); 567 | ledState = !ledState; 568 | } 569 | } 570 | #endif 571 | 572 | // Delay for 1..10 milliseconds (ESP-8266 internal routines need that) 573 | delayNeeded = 10 - (millis() - lastCycle); 574 | if (delayNeeded <= 0) 575 | delayNeeded = 1; 576 | ESP.wdtFeed(); 577 | delay(delayNeeded); 578 | } // void loop() 579 | -------------------------------------------------------------------------------- /internal.cpp: -------------------------------------------------------------------------------- 1 | // Internal ESP's sensors (ADC, button, led) 2 | 3 | #include "internal.h" 4 | #include "mqtt-support.h" 5 | 6 | boolean ledState = false; 7 | 8 | boolean FlagADC = false; 9 | 10 | int buttonState; 11 | int cntButton = 0; 12 | 13 | // publish PNP information to MQTT 14 | void pnp_internal() { 15 | pnp_mqtt(TOPIC_LED, "Built-in LED", "Builtin LEDs Switches", "I:Switch", NULL, NULL); 16 | pnp_mqtt(TOPIC_BUTTON, "FLASH button", "Builtin Switches Buttons", "O:Switch", NULL, NULL); 17 | pnp_mqtt(TOPIC_ADC, "ADC read", "Analogue ADC", "O:Number", "0", "1023"); 18 | pnp_mqtt(TOPIC_MILLIS, "Millis time", "Time", "O:Number", "0", "9999999999"); 19 | pnp_mqtt(TOPIC_ADC_CONTROL, "ADC on/off", "Builtin Switches ADC", "I:Switch", NULL, NULL); 20 | } // void pnp_internal() 21 | 22 | // subscribe to MQTT topics 23 | void subscribe_internal() { 24 | subscribe_mqtt(TOPIC_ADC_CONTROL); 25 | subscribe_mqtt(TOPIC_LED); 26 | } // void subscribe_internal() 27 | 28 | // Setup hardware (pins, etc) 29 | void setup_internal() { 30 | pinMode(BUTTON, INPUT); 31 | buttonState = digitalRead(BUTTON); 32 | pinMode(LED, OUTPUT); 33 | digitalWrite(LED, HIGH); 34 | } // void setup_internal() 35 | 36 | // must be called from loop() 37 | void loop_internal() { 38 | // Update LED 39 | digitalWrite(LED, ledState ? LOW : HIGH); 40 | 41 | // Check button 42 | if (buttonState != digitalRead(BUTTON)) { 43 | cntButton++; 44 | if (cntButton > 3) { 45 | buttonState = digitalRead(BUTTON); 46 | publish_mqttS(TOPIC_BUTTON, (char *) (buttonState ? "OFF" : "ON")); 47 | } 48 | } else 49 | cntButton = 0; 50 | } // void loop_internal() 51 | 52 | // last states (to prevent spamming) 53 | boolean lastButtonState = false; 54 | int lastADC = -1; 55 | 56 | // periodic refreshing values to MQTT 57 | void refresh_internal(boolean flagForce) { 58 | if (flagForce) { 59 | publish_mqttS(TOPIC_BUTTON, (char *) (buttonState ? "OFF" : "ON")); 60 | publish_mqttS(TOPIC_ADC_CONTROL, (char *) (FlagADC ? "ON" : "OFF"), true); 61 | publish_mqttS(TOPIC_LED, (char *) (ledState ? "ON" : "OFF"), true); 62 | publish_mqttI(TOPIC_MILLIS, millis()); 63 | } 64 | 65 | if (FlagADC) { 66 | if (flagForce || (analogRead(A0) != lastADC)) { 67 | lastADC = analogRead(A0); 68 | publish_mqttI(TOPIC_ADC, lastADC); 69 | } 70 | } 71 | } // void refresh_internal(boolean flagForce) 72 | 73 | // hook for incoming MQTT messages 74 | boolean mqtt_internal(char *topicCut, char *payload) { 75 | if (cmpTopic(topicCut, TOPIC_ADC_CONTROL)) { 76 | if (cmpPayloadON(payload)) 77 | FlagADC = true; 78 | else 79 | FlagADC = false; 80 | #ifdef DEBUG 81 | Serial.print("ADC switch update: "); 82 | Serial.println(FlagADC); 83 | #endif 84 | return true; 85 | } else if (cmpTopic(topicCut, TOPIC_LED)) { 86 | ledState = cmpPayloadON(payload); 87 | digitalWrite(LED, ledState ? LOW : HIGH); 88 | #ifdef DEBUG 89 | Serial.print("LED update: "); 90 | Serial.println(ledState); 91 | #endif 92 | return true; 93 | } 94 | return false; 95 | } // boolean mqtt_internal(char *topicCut, char *payload) 96 | -------------------------------------------------------------------------------- /internal.h: -------------------------------------------------------------------------------- 1 | // ESP's internal sensors (ADC, button, led) 2 | 3 | #ifndef _INTERNAL_H 4 | #define _INTERNAL_H 5 | 6 | #include "esp-sensors.h" 7 | 8 | // LED control 9 | extern boolean ledState; 10 | 11 | // publish PNP information to MQTT 12 | void pnp_internal(); 13 | 14 | // subscribe to MQTT topics 15 | void subscribe_internal(); 16 | 17 | // Setup hardware (pins, etc) 18 | void setup_internal(); 19 | 20 | // must be called from loop() 21 | void loop_internal(); 22 | 23 | // periodic refreshing values to MQTT 24 | void refresh_internal(boolean flagForce); 25 | 26 | // hook for incoming MQTT messages 27 | boolean mqtt_internal(char *topicCut, char *payload); 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /moveir.cpp: -------------------------------------------------------------------------------- 1 | // Movement sensors (IR and X-band radio) 2 | 3 | #include "moveir.h" 4 | #include "mqtt-support.h" 5 | 6 | // publish PNP information to MQTT 7 | void pnp_moveir() { 8 | pnp_mqtt(TOPIC_IR_SENSE, "IR sensor", "Sensors Movement IR", "O:Number", "0", "100"); 9 | pnp_mqtt(TOPIC_RADIO_SENSE, "Radio sensor", "Sensors Movement Radio", "O:Number", "0", "100"); 10 | pnp_mqtt(TOPIC_ADDITIONAL, "Additional IR sensor", "Sensors Movement IR", "O:Number", "0", "100"); 11 | } // void pnp_moveir() 12 | 13 | // subscribe to MQTT topics 14 | void subscribe_moveir() { 15 | } // void subscribe_moveir() 16 | 17 | // Vars 18 | int FlagIrSense = 0; 19 | int FlagRadioSense = 0; 20 | int FlagAddSense = 0; 21 | 22 | int lastIrSense = 0; 23 | int lastRadioSense = 0; 24 | int lastAddSense = 0; 25 | 26 | // Last states (to not report same value too often) 27 | int lastRadioSenseState = -1; 28 | int lastIrSenseState = -1; 29 | int lastAddIrSenseState = -1; 30 | 31 | // Setup hardware (pins, etc) 32 | void setup_moveir() { 33 | pinMode(IR_SENSE, INPUT); 34 | pinMode(RADIO_SENSE, INPUT); 35 | pinMode(ADD_SENSE, INPUT); 36 | } // void setup_moveir() 37 | 38 | // must be called from loop() 39 | void loop_moveir() { 40 | unsigned long startDelay = millis(); 41 | 42 | // Check sensors for 9ms 43 | while ((millis() - startDelay) < 9) { 44 | if (digitalRead(IR_SENSE) != lastIrSense) { 45 | FlagIrSense++; 46 | lastIrSense = digitalRead(IR_SENSE); 47 | } 48 | if (digitalRead(RADIO_SENSE) != lastRadioSense) { 49 | FlagRadioSense++; 50 | lastRadioSense = digitalRead(RADIO_SENSE); 51 | } 52 | if (digitalRead(ADD_SENSE) != lastAddSense) { 53 | FlagAddSense++; 54 | lastAddSense = digitalRead(ADD_SENSE); 55 | } 56 | } 57 | } // void loop_moveir() 58 | 59 | // periodic refreshing values to MQTT 60 | void refresh_moveir(boolean flagForce) { 61 | int tmp; 62 | 63 | // Publish statuses of IR/RADIO sensors 64 | tmp = (FlagIrSense > 100) ? 100 : FlagIrSense; 65 | if (flagForce || (lastIrSenseState != tmp)) { 66 | #ifdef DEBUG 67 | Serial.println("Reporting changed IR status"); 68 | #endif 69 | lastIrSenseState = tmp; 70 | publish_mqttI(TOPIC_IR_SENSE, tmp); 71 | } 72 | tmp = (FlagRadioSense > 100) ? 100 : FlagRadioSense; 73 | if (flagForce || (lastRadioSenseState != tmp)) { 74 | #ifdef DEBUG 75 | Serial.println("Reporting changed RADIO status"); 76 | #endif 77 | lastRadioSenseState = tmp; 78 | publish_mqttI(TOPIC_RADIO_SENSE, tmp); 79 | } 80 | tmp = (FlagAddSense > 100) ? 100 : FlagAddSense; 81 | if (flagForce || (lastAddIrSenseState != tmp)) { 82 | #ifdef DEBUG 83 | Serial.println("Reporting changed ADDIR status"); 84 | #endif 85 | lastAddIrSenseState = tmp; 86 | publish_mqttI(TOPIC_ADDITIONAL, tmp); 87 | } 88 | 89 | FlagRadioSense = 0; 90 | FlagIrSense = 0; 91 | FlagAddSense = 0; 92 | } // void refresh_moveir(boolean flagForce) 93 | 94 | // hook for incoming MQTT messages 95 | boolean mqtt_moveir(char *topicCut, char *payload) { 96 | return false; 97 | } // boolean mqtt_moveir(char *topicCut, char *payload) 98 | -------------------------------------------------------------------------------- /moveir.h: -------------------------------------------------------------------------------- 1 | // Movement sensors (IR and X-band radio) 2 | 3 | #ifndef _MOVEIR_H 4 | #define _MOVEIR_H 5 | 6 | #include "esp-sensors.h" 7 | 8 | 9 | // publish PNP information to MQTT 10 | void pnp_moveir(); 11 | 12 | // subscribe to MQTT topics 13 | void subscribe_moveir(); 14 | 15 | // Setup hardware (pins, etc) 16 | void setup_moveir(); 17 | 18 | // must be called from loop() 19 | void loop_moveir(); 20 | 21 | // periodic refreshing values to MQTT 22 | void refresh_moveir(boolean flagForce); 23 | 24 | // hook for incoming MQTT messages 25 | boolean mqtt_moveir(char *topicCut, char *payload); 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /mqtt-support.cpp: -------------------------------------------------------------------------------- 1 | // MQTT support routines 2 | 3 | #include "esp-sensors.h" 4 | #include "mqtt-support.h" 5 | 6 | // Prefix for MQTT topics 7 | char *mqttPrefixName; 8 | 9 | // Check connection to MQTT broker 10 | boolean check_mqtt() { 11 | if (myClient.connected()) 12 | return true; 13 | return false; 14 | } // boolean check_mqtt() 15 | 16 | // Internal mqtt stuff 17 | void mqtt_loop() { 18 | myClient.loop(); 19 | } // void mqtt_loop() 20 | 21 | char tmpMqttTopic[256]; 22 | 23 | // Use unique MQTT prefix to generate topic name (be sure outBuffer has enough space - +32 bytes!!!) 24 | void generateMqttTopic(char *outBuffer, char *topic, char *subtopic, boolean verification) { 25 | if (!verification) 26 | sprintf(outBuffer, "%s%s/%s", mqttPrefixName, topic, subtopic); 27 | else 28 | sprintf(outBuffer, "%s%s_CURRENT/%s", mqttPrefixName, topic, subtopic); 29 | } // void generateMqttTopic(char *outbuffer, char *topic, char *subtopic) 30 | 31 | // Connect to MQTT broker, returns true if connected 32 | boolean connect_mqtt(char *mqttServer, char *mqttClientName, char *mqttUser, char *mqttPass, std::function mqttCallback) { 33 | if (myClient.connected()) 34 | return true; 35 | myClient.setServer(mqttServer, MQTT_PORT); 36 | myClient.setCallback(mqttCallback); 37 | if (myClient.connect(mqttClientName, mqttUser, mqttPass)) { 38 | #ifdef DEBUG 39 | Serial.println("Connected to MQTT broker"); 40 | #endif 41 | return true; 42 | } else { 43 | #ifdef DEBUG 44 | Serial.println("Failed to connect to MQTT broker!"); 45 | #endif 46 | return false; 47 | } 48 | } // boolean connect_mqtt(char *mqttServer, char *mqttClientName, char *mqttUser, char *mqttPass, std::function mqttCallback) 49 | 50 | char tmpBuf[256]; 51 | char tmpBufO[256]; 52 | char tmpBufT[256]; 53 | 54 | // Publish Plug&Play info to MQTT 55 | void pnp_mqtt(char *topic, char *name, char *groups, char *type, char *min, char *max) { 56 | if (!myClient.connected()) 57 | return; 58 | snprintf(tmpBuf, sizeof(tmpBuf) - 1, "%s%s%s/%s", MQTT_PNP_PREFIX, mqttPrefixName, topic, "name"); 59 | myClient.publish(tmpBuf, name, true); 60 | #ifdef DEBUG 61 | Serial.println("PnP: "); 62 | Serial.print(tmpBuf); 63 | Serial.print(':'); 64 | Serial.print(name); 65 | #endif 66 | snprintf(tmpBuf, sizeof(tmpBuf) - 1, "%s%s%s/%s", MQTT_PNP_PREFIX, mqttPrefixName, topic, "groups"); 67 | myClient.publish(tmpBuf, groups, true); 68 | #ifdef DEBUG 69 | Serial.println("PnP: "); 70 | Serial.print(tmpBuf); 71 | Serial.print(':'); 72 | Serial.print(groups); 73 | #endif 74 | snprintf(tmpBuf, sizeof(tmpBuf) - 1, "%s%s%s/%s", MQTT_PNP_PREFIX, mqttPrefixName, topic, "type"); 75 | myClient.publish(tmpBuf, type, true); 76 | #ifdef DEBUG 77 | Serial.println("PnP: "); 78 | Serial.print(tmpBuf); 79 | Serial.print(':'); 80 | Serial.print(type); 81 | #endif 82 | if (min != NULL) { 83 | snprintf(tmpBuf, sizeof(tmpBuf) - 1, "%s%s%s/%s", MQTT_PNP_PREFIX, mqttPrefixName, topic, "min"); 84 | myClient.publish(tmpBuf, min, true); 85 | } 86 | if (max != NULL) { 87 | snprintf(tmpBuf, sizeof(tmpBuf) - 1, "%s%s%s/%s", MQTT_PNP_PREFIX, mqttPrefixName, topic, "max"); 88 | myClient.publish(tmpBuf, max, true); 89 | } 90 | delay(10); 91 | 92 | // Add output _CURRENT topic for input topics 93 | if (type[0] == 'I') { 94 | snprintf(tmpBufO, sizeof(tmpBufO) - 1, "%s_CURRENT", topic); 95 | snprintf(tmpBufT, sizeof(tmpBufT) - 1, "%s", type); 96 | tmpBufT[0] = 'O'; 97 | pnp_mqtt(tmpBufO, "", "Verification", tmpBufT, min, max); 98 | } 99 | } // void pnp_mqtt(char *topic, char *name, char *groups, char *type, char *min, char *max) 100 | 101 | // Subscribe to MQTT topics 102 | void subscribe_mqtt(char *topic) { 103 | if (!myClient.connected()) 104 | return; 105 | generateMqttTopic(tmpMqttTopic, topic, "status", false); 106 | myClient.subscribe(tmpMqttTopic); 107 | myClient.loop(); 108 | #ifdef DEBUG 109 | Serial.print("Subscribe: "); 110 | Serial.println(tmpMqttTopic); 111 | #endif 112 | delay(10); 113 | } // void subscribe_mqtt(char *topic) 114 | 115 | char tmpValue[64]; 116 | 117 | // Publish to topic (int) 118 | void publish_mqttI(char *topic, int value, boolean verification) { 119 | sprintf(tmpValue, "%d", value); 120 | publish_mqttS(topic, tmpValue, verification); 121 | } // void publish_mqttI(char *topic, int value) 122 | 123 | // Publish to topic (string) 124 | void publish_mqttS(char *topic, char *value, boolean verification) { 125 | if (!myClient.connected()) 126 | return; 127 | generateMqttTopic(tmpMqttTopic, topic, "status", verification); 128 | myClient.publish(tmpMqttTopic, value, true); 129 | #ifdef DEBUG 130 | Serial.print(tmpMqttTopic); 131 | Serial.print('='); 132 | Serial.println(value); 133 | #endif 134 | } // void publish_mqttS(char *topic, char *value) 135 | 136 | // Publish to topic (float) 137 | void publish_mqttF(char *topic, float value, boolean verification) { 138 | char *p; 139 | char floatBuf[16]; 140 | 141 | p = dtostrf(value, 5, 2, floatBuf); 142 | // Cut leading space 143 | while (*p == ' ') 144 | p++; 145 | publish_mqttS(topic, p, verification); 146 | } // void publish_mqttF(char *topic, float value) 147 | 148 | // Compare message for "ON" 149 | boolean cmpPayloadON(char *msg) { 150 | if ((msg[1] == 'N') || (msg[1] == 'n')) 151 | return true; 152 | return false; 153 | } // boolean cmpPayloadON(char *msg) 154 | 155 | // Compare message for "OFF" 156 | boolean cmpPayloadOFF(char *msg) { 157 | if ((msg[1] == 'F') || (msg[1] == 'f')) 158 | return true; 159 | return false; 160 | } // boolean cmpPayloadOFF(char *msg) 161 | 162 | // Compare string to topic name 163 | boolean cmpTopic(char *incoming, char *topic) { 164 | int topicLength = strlen(topic); 165 | 166 | if (memcmp(incoming, topic, topicLength)) 167 | return false; 168 | if ((incoming[topicLength] != '/') || (incoming[topicLength + 1] == '\0')) 169 | return false; 170 | if (!strcmp(incoming + topicLength + 1, "status")) 171 | return true; 172 | return false; 173 | } // boolean cmpTopic(char *incoming, char *topic) 174 | -------------------------------------------------------------------------------- /mqtt-support.h: -------------------------------------------------------------------------------- 1 | // Common MQTT stuff 2 | 3 | #ifndef _MQTT_SUPPORT_H 4 | #define _MQTT_SUPPORT_H 5 | 6 | #include "esp-sensors.h" 7 | #include 8 | 9 | // MQTT prefix name (like "/myhome/ESPX-0003DCE2") 10 | extern char *mqttPrefixName; 11 | 12 | // Connect to MQTT broker, returns true if connected 13 | boolean connect_mqtt(char *mqttServer, char *mqttClientName, char *mqttUser, char *mqttPass, std::function mqttCallback); 14 | 15 | // Check connection to MQTT broker 16 | boolean check_mqtt(); 17 | 18 | // Internal mqtt stuff 19 | void mqtt_loop(); 20 | 21 | // Publish PNP info to MQTT (will add topic+"_CURRENT" output topic for any input topic) 22 | void pnp_mqtt(char *topic, char *name, char *groups, char *type, char *min, char *max); 23 | 24 | // Subscribe to MQTT topics 25 | void subscribe_mqtt(char *topic); 26 | 27 | // Publish to topic (int) 28 | void publish_mqttI(char *topic, int value, boolean verification = false); 29 | 30 | // Publish to topic (string) 31 | void publish_mqttS(char *topic, char *value, boolean verification = false); 32 | 33 | // Publish to topic (float) 34 | void publish_mqttF(char *topic, float value, boolean verification = false); 35 | 36 | // Compare string to topic name 37 | boolean cmpTopic(char *incoming, char *topic); 38 | 39 | // Compare message for "ON" 40 | boolean cmpPayloadON(char *msg); 41 | 42 | // Compare message for "OFF" 43 | boolean cmpPayloadOFF(char *msg); 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /sonar.cpp: -------------------------------------------------------------------------------- 1 | // Sonars support 2 | 3 | #include "sonar.h" 4 | #include "mqtt-support.h" 5 | #ifdef MAXBOTIX_CONTROL 6 | #include 7 | 8 | SoftwareSerial mySerial = SoftwareSerial(SW_rxPin, SW_txPin, false); 9 | #endif 10 | 11 | // publish PNP information to MQTT 12 | void pnp_sonar() { 13 | pnp_mqtt(TOPIC_DISTANCE, "Distance", "Analogue Distance Sonar", "O:Number", "0", "500"); 14 | } // void pnp_sonar() 15 | 16 | // subscribe to MQTT topics 17 | void subscribe_sonar() { 18 | } // void subscribe_sonar() 19 | 20 | // Setup hardware (pins, etc) 21 | void setup_sonar() { 22 | #ifdef HCSR04_CONTROL 23 | pinMode(HCSR04_TRIG, OUTPUT); 24 | digitalWrite(HCSR04_TRIG, LOW); 25 | pinMode(HCSR04_ECHO, INPUT); 26 | #else 27 | #ifdef MAXBOTIX_CONTROL 28 | mySerial.begin(9600); 29 | #endif 30 | #endif 31 | } // void setup_sonar() 32 | 33 | #ifdef HCSR04_CONTROL 34 | #define MIN_DISTANCE 3 35 | int recursion = 0; 36 | 37 | // Find distance with HC-SR04 38 | int findDistanceSR() { 39 | uint32_t duration; 40 | int cm; 41 | 42 | digitalWrite(HCSR04_TRIG, LOW); 43 | delayMicroseconds(5); 44 | digitalWrite(HCSR04_TRIG, HIGH); 45 | delayMicroseconds(10); 46 | digitalWrite(HCSR04_TRIG, LOW); 47 | 48 | duration = pulseIn(HCSR04_ECHO, HIGH, 30000); 49 | cm = (duration / 2) / 29.1; 50 | #ifdef DEBUG 51 | Serial.print("Distance = "); 52 | Serial.println(cm); 53 | #endif 54 | if ((cm <= 0) || (cm > 600)) { 55 | pinMode(HCSR04_ECHO, OUTPUT); 56 | digitalWrite(HCSR04_ECHO, LOW); 57 | delay(100); 58 | pinMode(HCSR04_ECHO, INPUT); 59 | cm = findDistance(); 60 | recursion++; 61 | if (recursion < 3) 62 | return findDistance(); 63 | } 64 | recursion = 0; 65 | return cm; 66 | } // int findDistanceSR() 67 | #endif 68 | 69 | #ifdef MAXBOTIX_CONTROL 70 | #define MIN_DISTANCE 14 71 | // Find distance with Maxbotix sonars 72 | int findDistanceMB() { 73 | char rxBuf[16]; 74 | char rcv; 75 | char *p; 76 | int cm = -1; 77 | 78 | p = rxBuf; 79 | while (mySerial.available()) { 80 | rcv = mySerial.read(); 81 | switch (rcv) { 82 | case 'R': 83 | p = rxBuf; 84 | break; 85 | case '\n': 86 | case '\r': 87 | *p = '\0'; 88 | cm = ((float) strtol(rxBuf, NULL, 10) * 2.54); 89 | p = rxBuf; 90 | break; 91 | default: 92 | *p = rcv; 93 | p++; 94 | if (p > (rxBuf + sizeof(rxBuf) - 1)) 95 | p = rxBuf; 96 | break; 97 | } 98 | if (cm > 0) 99 | return cm; 100 | } 101 | return 0; 102 | } // int findDistanceMB() 103 | #endif 104 | 105 | int findDistance() { 106 | #ifdef HCSR04_CONTROL 107 | return findDistanceSR(); 108 | #endif 109 | #ifdef MAXBOTIX_CONTROL 110 | return findDistanceMB(); 111 | #endif 112 | return 0; 113 | } // int findDistance() 114 | 115 | unsigned long lastSonar = 0; 116 | int lastSonarState = -1; 117 | 118 | // must be called from loop() 119 | void loop_sonar() { 120 | int tmp; 121 | 122 | if ((millis() - lastSonar) > 200) { 123 | lastSonar = millis(); 124 | tmp = findDistance(); 125 | if ((tmp > 0) && (lastSonarState != tmp)) { 126 | #ifdef DEBUG 127 | Serial.println("Reporting changed sonar distance"); 128 | #endif 129 | lastSonarState = tmp; 130 | publish_mqttI(TOPIC_DISTANCE, lastSonarState); 131 | } 132 | } 133 | } // void loop_sonar() 134 | 135 | // periodic refreshing values to MQTT 136 | void refresh_sonar(boolean flagForce) { 137 | if (flagForce) 138 | publish_mqttI(TOPIC_DISTANCE, lastSonarState); 139 | } // void refresh_sonar(boolean flagForce) 140 | 141 | // hook for incoming MQTT messages 142 | boolean mqtt_sonar(char *topicCut, char *payload) { 143 | return false; 144 | } // boolean mqtt_sonar(char *topicCut, char *payload) 145 | -------------------------------------------------------------------------------- /sonar.h: -------------------------------------------------------------------------------- 1 | // Sonar's support (HC-SR04 and maxbotix with serial) 2 | 3 | #ifndef _SONAR_H 4 | #define _SONAR_H 5 | 6 | #include "esp-sensors.h" 7 | 8 | // publish PNP information to MQTT 9 | void pnp_sonar(); 10 | 11 | // subscribe to MQTT topics 12 | void subscribe_sonar(); 13 | 14 | // Setup hardware (pins, etc) 15 | void setup_sonar(); 16 | 17 | // must be called from loop() 18 | void loop_sonar(); 19 | 20 | // periodic refreshing values to MQTT 21 | void refresh_sonar(boolean flagForce); 22 | 23 | // hook for incoming MQTT messages 24 | boolean mqtt_sonar(char *topicCut, char *payload); 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /switch.cpp: -------------------------------------------------------------------------------- 1 | // "Sonoff switch" and "Sonoff touch" support 2 | 3 | #include "switch.h" 4 | #include "mqtt-support.h" 5 | 6 | // publish PNP information to MQTT 7 | void pnp_switch() { 8 | pnp_mqtt(TOPIC_RELAY, "AC relay", "Relays Switches AC", "I:Switch", NULL, NULL); 9 | pnp_mqtt(TOPIC_AUTO_RELAY, "Auto relay on/off", "Switches", "I:Switch", NULL, NULL); 10 | } // void pnp_switch() 11 | 12 | // subscribe to MQTT topics 13 | void subscribe_switch() { 14 | subscribe_mqtt(TOPIC_RELAY); 15 | subscribe_mqtt(TOPIC_AUTO_RELAY); 16 | } // void subscribe_switch() 17 | 18 | boolean FlagRelay = true; 19 | boolean relayState = false; 20 | 21 | int touchState; 22 | int cntTouch = 0; 23 | 24 | // Setup hardware (pins, etc) 25 | void setup_switch() { 26 | pinMode(RELAY, OUTPUT); 27 | digitalWrite(RELAY, relayState ? HIGH : LOW); 28 | touchState = digitalRead(BUTTON); 29 | } // void setup_switch() 30 | 31 | // must be called from loop() 32 | void loop_switch() { 33 | // Check touch button 34 | if (touchState != digitalRead(BUTTON)) { 35 | cntTouch++; 36 | if (cntTouch > 3) { 37 | touchState = digitalRead(BUTTON); 38 | if (touchState == LOW) { 39 | // Light up LED while button is pressed 40 | analogWrite(LED, 512); 41 | // Auto switch relay 42 | if (FlagRelay) { 43 | relayState = !relayState; 44 | digitalWrite(RELAY, relayState ? HIGH : LOW); 45 | publish_mqttS(TOPIC_RELAY, (char *) (relayState ? "ON" : "OFF")); 46 | } 47 | } else 48 | digitalWrite(LED, HIGH); 49 | } 50 | } else 51 | cntTouch = 0; 52 | } // void loop_switch() 53 | 54 | // periodic refreshing values to MQTT 55 | void refresh_switch(boolean flagForce) { 56 | if (flagForce) { 57 | publish_mqttS(TOPIC_RELAY, (char *) (relayState ? "ON" : "OFF")); 58 | publish_mqttS(TOPIC_RELAY, (char *) (relayState ? "ON" : "OFF"), true); 59 | publish_mqttS(TOPIC_AUTO_RELAY, (char *) (FlagRelay ? "ON" : "OFF"), true); 60 | } 61 | } // void refresh_switch(boolean flagForce) 62 | 63 | // hook for incoming MQTT messages 64 | boolean mqtt_switch(char *topicCut, char *payload) { 65 | if (cmpTopic(topicCut, TOPIC_RELAY)) { 66 | if (cmpPayloadON(payload)) { 67 | digitalWrite(RELAY, HIGH); 68 | relayState = true; 69 | } else { 70 | digitalWrite(RELAY, LOW); 71 | relayState = false; 72 | } 73 | #ifdef DEBUG 74 | Serial.print("Relay status update: "); 75 | Serial.println(relayState); 76 | #endif 77 | return true; 78 | } else if (cmpTopic(topicCut, TOPIC_AUTO_RELAY)) { 79 | if (cmpPayloadON(payload)) 80 | FlagRelay = true; 81 | else 82 | FlagRelay = false; 83 | #ifdef DEBUG 84 | Serial.print("Auto relay switch update: "); 85 | Serial.println(FlagRelay); 86 | #endif 87 | return true; 88 | } 89 | return false; 90 | } // boolean mqtt_switch(char *topicCut, char *payload) 91 | -------------------------------------------------------------------------------- /switch.h: -------------------------------------------------------------------------------- 1 | // Sonoff basic switch and Sonoff touch support 2 | 3 | #ifndef _SWITCH_H 4 | #define _SWITCH_H 5 | 6 | #include "esp-sensors.h" 7 | 8 | // publish PNP information to MQTT 9 | void pnp_switch(); 10 | 11 | // subscribe to MQTT topics 12 | void subscribe_switch(); 13 | 14 | // Setup hardware (pins, etc) 15 | void setup_switch(); 16 | 17 | // must be called from loop() 18 | void loop_switch(); 19 | 20 | // periodic refreshing values to MQTT 21 | void refresh_switch(boolean flagForce); 22 | 23 | // hook for incoming MQTT messages 24 | boolean mqtt_switch(char *topicCut, char *payload); 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /thermostat.cpp: -------------------------------------------------------------------------------- 1 | // Simple thermostat control (two relays control fan and compressor units) 2 | 3 | #include "thermostat.h" 4 | #include "weather.h" 5 | #include "mqtt-support.h" 6 | 7 | boolean fanAuto = false; 8 | boolean fanOverride = false; 9 | boolean compressorAuto = false; 10 | float tempMin = 25.0f; 11 | float tempMax = 26.0f; 12 | 13 | // publish PNP information to MQTT 14 | void pnp_thermostat() { 15 | pnp_mqtt(TOPIC_LED_OFF, "Off LED", "Thermostat LEDs Switches", "I:Switch", NULL, NULL); 16 | pnp_mqtt(TOPIC_LED_ON, "On LED", "Thermostat LEDs Switches", "I:Switch", NULL, NULL); 17 | pnp_mqtt(TOPIC_FAN_AUTO, "Enable fan always when auto-control is on", "Thermostat Fan Climate Switches", "I:Switch", NULL, NULL); 18 | pnp_mqtt(TOPIC_FAN, "Fan status", "Thermostat Fan Climate Switches", "O:Switch", NULL, NULL); 19 | pnp_mqtt(TOPIC_FAN_MANUAL, "Fan manual control", "Thermostat Fan Climate Switches", "I:Switch", NULL, NULL); 20 | pnp_mqtt(TOPIC_COMPRESSOR_AUTO, "Cooling auto control", "Thermostat Cooling Climate Switches", "I:Switch", NULL, NULL); 21 | pnp_mqtt(TOPIC_COMPRESSOR, "Cooling unit relay status", "Thermostat Compressor Cooling Climate Switches", "O:Switch", NULL, NULL); 22 | pnp_mqtt(TOPIC_COMPRESSOR_STATUS, "Cooling auto status", "Thermostat Compressor Cooling Climate Switches", "O:Switch", NULL, NULL); 23 | pnp_mqtt(TOPIC_TEMP_AUTO, "Thermostat temperature", "Thermostat Temperature Climate", "I:Number", "18", "35"); 24 | } // void pnp_thermostat() 25 | 26 | // subscribe to MQTT topics 27 | void subscribe_thermostat() { 28 | subscribe_mqtt(TOPIC_LED_OFF); 29 | subscribe_mqtt(TOPIC_LED_ON); 30 | subscribe_mqtt(TOPIC_FAN_AUTO); 31 | subscribe_mqtt(TOPIC_FAN_MANUAL); 32 | subscribe_mqtt(TOPIC_COMPRESSOR_AUTO); 33 | subscribe_mqtt(TOPIC_TEMP_AUTO); 34 | } // void subscribe_thermostat() 35 | 36 | // Setup hardware (pins, etc) 37 | void setup_thermostat() { 38 | pinMode(FAN_RELAY, OUTPUT); 39 | digitalWrite(FAN_RELAY, LOW); 40 | pinMode(COMPRESSOR_RELAY, OUTPUT); 41 | digitalWrite(COMPRESSOR_RELAY, LOW); 42 | 43 | pinMode(LED_OFF, OUTPUT); 44 | digitalWrite(LED_OFF, LOW); 45 | pinMode(LED_ON, OUTPUT); 46 | digitalWrite(LED_ON, LOW); 47 | 48 | pinMode(LED_GND, OUTPUT); 49 | digitalWrite(LED_GND, LOW); 50 | } // void setup_thermostat() 51 | 52 | unsigned long lastButtonPress = 0; 53 | unsigned long lastThermostat = 0; 54 | 55 | // must be called from loop() 56 | void loop_thermostat() { 57 | // We turn on DHT22 always 58 | FlagReportWeather = true; 59 | 60 | // We process button press without MQTT in thermostat mode 61 | if ((digitalRead(BUTTON) == LOW) && ((millis() - lastButtonPress) > 1000)) { 62 | lastButtonPress = millis(); 63 | if (compressorAuto) { 64 | compressorAuto = false; 65 | digitalWrite(LED_OFF, HIGH); 66 | digitalWrite(FAN_RELAY, LOW); 67 | digitalWrite(COMPRESSOR_RELAY, LOW); 68 | } else { 69 | compressorAuto = true; 70 | digitalWrite(LED_ON, HIGH); 71 | } 72 | publish_mqttS(TOPIC_COMPRESSOR_STATUS, (char *) (compressorAuto ? "ON" : "OFF")); 73 | 74 | delay(1000); 75 | digitalWrite(LED_OFF, LOW); 76 | digitalWrite(LED_ON, LOW); 77 | } 78 | 79 | // Control thermostat check (every 300 ms) 80 | if ((millis() - lastThermostat) > 300) { 81 | lastThermostat = millis(); 82 | if (compressorAuto) { 83 | // Thermostat control 84 | if (tempMax <= temperatureCurrent) { 85 | // We always turn on fan together with compressor unit to prevent ice 86 | digitalWrite(FAN_RELAY, HIGH); 87 | digitalWrite(COMPRESSOR_RELAY, HIGH); 88 | #ifdef DEBUG 89 | Serial.println("Temperature is bigger than maximum, turning on fan/compressor"); 90 | #endif 91 | } 92 | if (tempMin >= temperatureCurrent) { 93 | // We don't turn off FAN if fan isn't in auto mode or manually turned on 94 | if (!fanAuto && !fanOverride) 95 | digitalWrite(FAN_RELAY, LOW); 96 | digitalWrite(COMPRESSOR_RELAY, LOW); 97 | #ifdef DEBUG 98 | Serial.println("Temperature is lower than minimum, turning off fan/compressor"); 99 | #endif 100 | } 101 | #ifdef DEBUG 102 | Serial.print("FAN/COMPRESSOR status: "); 103 | Serial.print(digitalRead(FAN_RELAY)); 104 | Serial.print(" "); 105 | Serial.println(digitalRead(COMPRESSOR_RELAY)); 106 | #endif 107 | } else 108 | if (!fanOverride) 109 | digitalWrite(FAN_RELAY, LOW); 110 | } 111 | } // void loop_thermostat() 112 | 113 | // periodic refreshing values to MQTT 114 | void refresh_thermostat(boolean flagForce) { 115 | if (flagForce) { 116 | publish_mqttS(TOPIC_COMPRESSOR, (char *) ((digitalRead(COMPRESSOR_RELAY) == HIGH) ? "ON" : "OFF")); 117 | publish_mqttS(TOPIC_FAN, (char *) ((digitalRead(FAN_RELAY) == HIGH) ? "ON" : "OFF")); 118 | publish_mqttS(TOPIC_FAN_AUTO, (char *) (fanAuto ? "ON" : "OFF"), true); 119 | publish_mqttS(TOPIC_COMPRESSOR_AUTO, (char *) (compressorAuto ? "ON" : "OFF"), true); 120 | publish_mqttS(TOPIC_FAN_MANUAL, (char *) (fanOverride ? "ON" : "OFF"), true); 121 | publish_mqttS(TOPIC_LED_OFF, (char *) ((digitalRead(LED_OFF) == HIGH) ? "ON" : "OFF"), true); 122 | publish_mqttS(TOPIC_LED_ON, (char *) ((digitalRead(LED_ON) == HIGH) ? "ON" : "OFF"), true); 123 | } 124 | } // void refresh_thermostat() 125 | 126 | // hook for incoming MQTT messages 127 | boolean mqtt_thermostat(char *topicCut, char *payload) { 128 | if (cmpTopic(topicCut, TOPIC_FAN_AUTO)) { 129 | if (cmpPayloadON(payload)) 130 | fanAuto = true; 131 | else { 132 | fanAuto = false; 133 | // Turn off compressor and fan if needed 134 | if (!compressorAuto) 135 | digitalWrite(COMPRESSOR_RELAY, LOW); 136 | if (!fanOverride && !compressorAuto) 137 | digitalWrite(FAN_RELAY, LOW); 138 | } 139 | #ifdef DEBUG 140 | Serial.print("Fan auto control: "); 141 | Serial.println(fanAuto); 142 | #endif 143 | return true; 144 | } else if (cmpTopic(topicCut, TOPIC_COMPRESSOR_AUTO)) { 145 | if (cmpPayloadON(payload)) 146 | compressorAuto = true; 147 | else { 148 | compressorAuto = false; 149 | // Turn off compressor and fan 150 | digitalWrite(COMPRESSOR_RELAY, LOW); 151 | if (!fanOverride) 152 | digitalWrite(FAN_RELAY, LOW); 153 | } 154 | #ifdef DEBUG 155 | Serial.print("Compressor auto control: "); 156 | Serial.println(compressorAuto); 157 | #endif 158 | return true; 159 | } else if (cmpTopic(topicCut, TOPIC_FAN_MANUAL)) { 160 | if (cmpPayloadON(payload)) { 161 | fanOverride = true; 162 | digitalWrite(FAN_RELAY, HIGH); 163 | } else { 164 | fanOverride = false; 165 | if (!compressorAuto) 166 | digitalWrite(FAN_RELAY, LOW); 167 | } 168 | #ifdef DEBUG 169 | Serial.print("FAN manual switch: "); 170 | Serial.println(fanOverride); 171 | #endif 172 | return true; 173 | } else if (cmpTopic(topicCut, TOPIC_LED_OFF)) { 174 | if (cmpPayloadON(payload)) 175 | digitalWrite(LED_OFF, HIGH); 176 | else 177 | digitalWrite(LED_OFF, LOW); 178 | return true; 179 | } else if (cmpTopic(topicCut, TOPIC_LED_ON)) { 180 | if (cmpPayloadON(payload)) 181 | digitalWrite(LED_ON, HIGH); 182 | else 183 | digitalWrite(LED_ON, LOW); 184 | return true; 185 | } if (cmpTopic(topicCut, TOPIC_TEMP_AUTO)) { 186 | int16_t temp; 187 | 188 | temp = strtod((char *) payload, NULL); 189 | if ((temp >= 18) || (temp <= 35)) { 190 | tempMin = temp; 191 | tempMax = temp + THERMOSTAT_HYSTERSIS; 192 | #ifdef DEBUG 193 | Serial.print("Thermostat new temperature: "); 194 | Serial.println(tempMin); 195 | #endif 196 | } 197 | return true; 198 | } 199 | return false; 200 | } // boolean mqtt_thermostat(char *topicCut, char *payload) 201 | -------------------------------------------------------------------------------- /thermostat.h: -------------------------------------------------------------------------------- 1 | // Simple thermostat control (with two relays for fan and compressor units) 2 | 3 | #ifndef _THERMOSTAT_H 4 | #define _THERMOSTAT_H 5 | 6 | #include "esp-sensors.h" 7 | #include "weather.h" 8 | 9 | // publish PNP information to MQTT 10 | void pnp_thermostat(); 11 | 12 | // subscribe to MQTT topics 13 | void subscribe_thermostat(); 14 | 15 | // Setup hardware (pins, etc) 16 | void setup_thermostat(); 17 | 18 | // must be called from loop() 19 | void loop_thermostat(); 20 | 21 | // periodic refreshing values to MQTT 22 | void refresh_thermostat(boolean flagForce); 23 | 24 | // hook for incoming MQTT messages 25 | boolean mqtt_thermostat(char *topicCut, char *payload); 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /weather.cpp: -------------------------------------------------------------------------------- 1 | // DHT22 weather sensor support 2 | 3 | #include "weather.h" 4 | #include "mqtt-support.h" 5 | 6 | #ifdef DHT22_CONTROL 7 | #include 8 | #include 9 | #include 10 | #endif 11 | 12 | #ifdef GY39_CONTROL 13 | #include 14 | #endif 15 | 16 | 17 | // Last temperature read 18 | float temperatureCurrent = 25; 19 | 20 | // Last humidity read 21 | float humidityCurrent = 75; 22 | 23 | // Last pressure read 24 | float pressureCurrent = 100000; 25 | 26 | // Last illumination read 27 | float illuminationCurrent = 100; 28 | 29 | // last values reported (to prevent spamming) 30 | float lastTemperature = -1; 31 | float lastHumidity = -1; 32 | float lastPressure = -1; 33 | float lastIllumination = -1; 34 | 35 | // publish PNP information to MQTT 36 | void pnp_weather() { 37 | #ifdef DHT22_CONTROL 38 | pnp_mqtt(TOPIC_DHT, "DHT22 enable", "DHT22 Weather Switches", "I:Switch", NULL, NULL); 39 | pnp_mqtt(TOPIC_TEMPERATURE, "Temperature", "Analogue Weather DHT22 Temperature", "O:Number", "-40.0", "80.0"); 40 | pnp_mqtt(TOPIC_HUMIDITY, "Humidity", "Analogue Weather DHT22 Humidity", "O:Number", "0.0", "100.0"); 41 | #endif 42 | #ifdef GY39_CONTROL 43 | pnp_mqtt(TOPIC_GY39, "GY-39 enable", "GY39 Weather Switches", "I:Switch", NULL, NULL); 44 | pnp_mqtt(TOPIC_TEMPERATURE, "Temperature", "Analogue Weather GY39 Temperature", "O:Number", "-40.0", "80.0"); 45 | pnp_mqtt(TOPIC_HUMIDITY, "Humidity", "Analogue Weather GY39 Humidity", "O:Number", "0.0", "100.0"); 46 | pnp_mqtt(TOPIC_ILLUMINATION, "Illumination", "Analogue Weather GY39 Illumination Light", "O:Number", "0.0", "190000.0"); 47 | pnp_mqtt(TOPIC_PRESSURE, "Pressure", "Analogue Weather GY39 Pressure", "O:Number", "0.0", "200000.0"); 48 | #endif 49 | } // void pnp_weather() 50 | 51 | // subscribe to MQTT topics 52 | void subscribe_weather() { 53 | #ifdef DHT22_CONTROL 54 | subscribe_mqtt(TOPIC_DHT); 55 | #endif 56 | #ifdef GY39_CONTROL 57 | subscribe_mqtt(TOPIC_GY39); 58 | #endif 59 | } // void subscribe_weather() 60 | 61 | boolean FlagReportWeather = false; 62 | 63 | // hook for incoming MQTT messages 64 | boolean mqtt_weather(char *topicCut, char *payload) { 65 | if (cmpTopic(topicCut, TOPIC_DHT) || cmpTopic(topicCut, TOPIC_GY39)) { 66 | if (cmpPayloadON(payload)) 67 | FlagReportWeather = true; 68 | else 69 | FlagReportWeather = false; 70 | #ifdef DEBUG 71 | Serial.print("Weather flag update: "); 72 | Serial.println(FlagReportWeather); 73 | #endif 74 | return true; 75 | } 76 | return false; 77 | } // boolean mqtt_weather(char *topicCut, char *payload) 78 | 79 | #ifdef DHT22_CONTROL 80 | DHT_Unified dht(DHTPIN, DHT22); 81 | uint32_t lastDHT = 0; 82 | 83 | // Setup hardware (pins, etc) 84 | void setup_weather() { 85 | } // void setup_weather() 86 | 87 | // Read temperature 88 | void check_dht_temperature() { 89 | sensors_event_t event; 90 | char *p; 91 | int numDHTAttempts; 92 | 93 | // Crude fix to DHT22's problem with reading (just repeat few times) 94 | numDHTAttempts = 0; 95 | do { 96 | dht.temperature().getEvent(&event); 97 | numDHTAttempts++; 98 | if (isnan(event.temperature)) 99 | delay(10); 100 | } while (isnan(event.temperature) && (numDHTAttempts < 5)); 101 | 102 | if (!isnan(event.temperature)) { 103 | #ifdef DEBUG 104 | Serial.print("Temperature: "); 105 | Serial.print(event.temperature); 106 | Serial.println("C"); 107 | #endif 108 | temperatureCurrent = event.temperature; 109 | } 110 | } // void check_dht_temperature() 111 | 112 | // Read humidity 113 | void check_dht_humidity() { 114 | sensors_event_t event; 115 | char *p; 116 | 117 | dht.humidity().getEvent(&event); 118 | if (!isnan(event.relative_humidity)) { 119 | #ifdef DEBUG 120 | Serial.print("Humidity: "); 121 | Serial.print(event.relative_humidity); 122 | Serial.println("%"); 123 | #endif 124 | humidityCurrent = event.relative_humidity; 125 | } 126 | } // void check_dht_humidity() 127 | 128 | 129 | // must be called from loop() 130 | void loop_weather() { 131 | if (FlagReportWeather && ((millis() - lastDHT) > 10000)) { 132 | lastDHT = millis(); 133 | check_dht_temperature(); 134 | check_dht_humidity(); 135 | } 136 | } // void loop_weather() 137 | 138 | // periodic refreshing values to MQTT 139 | void refresh_weather(boolean flagForce) { 140 | if (FlagReportWeather) { 141 | if (flagForce || (lastTemperature != temperatureCurrent)) { 142 | lastTemperature = temperatureCurrent; 143 | publish_mqttF(TOPIC_TEMPERATURE, temperatureCurrent); 144 | } 145 | if (flagForce || (lastHumidity != humidityCurrent)) { 146 | lastHumidity = humidityCurrent; 147 | publish_mqttF(TOPIC_HUMIDITY, humidityCurrent); 148 | } 149 | } 150 | if (flagForce) 151 | publish_mqttS(TOPIC_DHT, (char *) (FlagReportWeather ? "ON" : "OFF"), true); 152 | } // void refresh_weather(boolean flagForce) 153 | #endif 154 | 155 | #ifdef GY39_CONTROL 156 | SoftwareSerial sUart(GY39PIN, SW_SERIAL_UNUSED_PIN, false); 157 | 158 | // Setup hardware (pins, etc) 159 | void setup_weather() { 160 | sUart.begin(9600); 161 | } // void setup_weather() 162 | 163 | // Output variables 164 | // Light level data ready 165 | boolean gy39ReadyLight = false; 166 | // Light level data (in lux, lumen per square meter) 167 | float gy39Lux; 168 | // Environment data ready 169 | boolean gy39ReadyEnv = false; 170 | // Temperature (in Celsius) 171 | float gy39Temperature; 172 | // Humidity (in percents) 173 | float gy39Humidity; 174 | // Pressure (in Pa) 175 | float gy39Pressure; 176 | // Altitude above sea level (in meters), very estimate 177 | float gy39Altitude; 178 | 179 | // Internal variables of processGY39 180 | int gy39State = 0; 181 | int gy39Type; 182 | int countCharGY39 = 0; 183 | unsigned int gy39Checksum = 0; 184 | int countWaitGY39 = 0; 185 | unsigned long lastGY39Char = 0; 186 | uint8_t bufGY39[11]; 187 | 188 | 189 | // process character from GY-39 190 | void processGY39(char c) { 191 | // Reset if we wait too long (more than second) 192 | if ((millis() - lastGY39Char) > 1000) { 193 | lastGY39Char = millis(); 194 | gy39State = 0; 195 | countCharGY39 = 0; 196 | } 197 | 198 | // Serial.printf("gy39 PRE state: %d, countchar: %d\n", gy39State, countCharGY39); 199 | switch (gy39State) { 200 | // Waiting for ZZ (begin of packet) 201 | case 0: 202 | // Not 'Z', reset counter 203 | if (c != 'Z') { 204 | countCharGY39 = 0; 205 | break; 206 | } 207 | if (countCharGY39 == 1) { 208 | gy39State = 1; 209 | countCharGY39 = 0; 210 | } else { 211 | // Reset checksum, wait for second 'Z' 212 | gy39Checksum = 0; 213 | countCharGY39 = 1; 214 | } 215 | break; 216 | // Get packet type 217 | case 1: 218 | // Unknown packet type, reset 219 | if ((c != 0x15) && (c != 0x45)) { 220 | gy39State = 0; 221 | countCharGY39 = 0; 222 | break; 223 | } 224 | gy39Type = c; 225 | gy39State = 2; 226 | break; 227 | // Get number of bytes 228 | case 2: 229 | // Wrong length for packet, reset 230 | if (((gy39Type == 0x15) && (c != 0x04)) || ((gy39Type == 0x45) && (c != 0x0A))) { 231 | gy39State = 0; 232 | countCharGY39 = 0; 233 | break; 234 | } 235 | gy39State = 3; 236 | countWaitGY39 = (int) c + 1; 237 | countCharGY39 = 0; 238 | break; 239 | // Receive data part of packet with checksum 240 | case 3: 241 | // Put char in buffer 242 | bufGY39[countCharGY39] = (uint8_t) c; 243 | countCharGY39++; 244 | // Check if have received full packet with checksum 245 | if (countCharGY39 >= countWaitGY39) { 246 | // Prepare for next packet 247 | gy39State = 0; 248 | countCharGY39 = 0; 249 | // Wrong checksum, do nothing 250 | if (bufGY39[countWaitGY39 - 1] != (gy39Checksum & 0xff)) 251 | break; 252 | // Parse data 253 | if (gy39Type == 0x15) { 254 | // 0x15 - Light 255 | gy39Lux = ((float) ((((uint32_t) bufGY39[0]) << 24) | (((uint32_t) bufGY39[1]) << 16) | (((uint32_t) bufGY39[2]) << 8) | (uint32_t) bufGY39[0])) / 100.0f; 256 | gy39ReadyLight = true; 257 | } else { 258 | // 0x45 - Environment temperature/pressure/humidity 259 | gy39Temperature = ((float) ((((uint16_t) bufGY39[0]) << 8) | (uint16_t) bufGY39[1])) / 100.0f; 260 | gy39Pressure = ((float) ((((uint32_t) bufGY39[2]) << 24) | (((uint32_t) bufGY39[3]) << 16) | (((uint32_t) bufGY39[4]) << 8) | (uint32_t) bufGY39[5])) / 100.0f; 261 | gy39Humidity = ((float) ((((uint16_t) bufGY39[6]) << 8) | (uint16_t) bufGY39[7])) / 100.0f; 262 | gy39Altitude = ((float) ((((uint16_t) bufGY39[8]) << 8) | (uint16_t) bufGY39[9])) / 100.0f; 263 | gy39ReadyEnv = true; 264 | } 265 | } 266 | break; 267 | default: 268 | // Shouldn't happen 269 | gy39State = 0; 270 | countCharGY39 = 0; 271 | break; 272 | } 273 | gy39Checksum += (unsigned int) c; 274 | return; 275 | } // void processGY39(char c) 276 | 277 | // must be called from loop() 278 | void loop_weather() { 279 | if (FlagReportWeather) 280 | while (sUart.available()) 281 | processGY39(sUart.read()); 282 | } // void loop_weather() 283 | 284 | // periodic refreshing values to MQTT 285 | void refresh_weather(boolean flagForce) { 286 | if (FlagReportWeather) { 287 | if (gy39ReadyLight) { 288 | gy39ReadyLight = false; 289 | illuminationCurrent = gy39Lux; 290 | } 291 | if (gy39ReadyEnv) { 292 | gy39ReadyEnv = false; 293 | temperatureCurrent = gy39Temperature; 294 | humidityCurrent = gy39Humidity; 295 | pressureCurrent = gy39Pressure; 296 | } 297 | if (flagForce || (lastTemperature != temperatureCurrent)) { 298 | lastTemperature = temperatureCurrent; 299 | publish_mqttF(TOPIC_TEMPERATURE, temperatureCurrent); 300 | } 301 | if (flagForce || (lastHumidity != humidityCurrent)) { 302 | lastHumidity = humidityCurrent; 303 | publish_mqttF(TOPIC_HUMIDITY, humidityCurrent); 304 | } 305 | if (flagForce || (lastPressure != pressureCurrent)) { 306 | lastPressure = pressureCurrent; 307 | publish_mqttF(TOPIC_PRESSURE, pressureCurrent); 308 | } 309 | if (flagForce || (lastIllumination != illuminationCurrent)) { 310 | lastIllumination = illuminationCurrent; 311 | publish_mqttF(TOPIC_ILLUMINATION, illuminationCurrent); 312 | } 313 | } 314 | if (flagForce) 315 | publish_mqttS(TOPIC_GY39, (char *) (FlagReportWeather ? "ON" : "OFF"), true); 316 | } // void refresh_weather(boolean flagForce) 317 | #endif 318 | -------------------------------------------------------------------------------- /weather.h: -------------------------------------------------------------------------------- 1 | // DHT22 weather sensor support 2 | 3 | #ifndef _WEATHER_H 4 | #define _WEATHER_H 5 | 6 | #include "esp-sensors.h" 7 | 8 | // publish PNP information to MQTT 9 | void pnp_weather(); 10 | 11 | // subscribe to MQTT topics 12 | void subscribe_weather(); 13 | 14 | // Setup hardware (pins, etc) 15 | void setup_weather(); 16 | 17 | // must be called from loop() 18 | void loop_weather(); 19 | 20 | // periodic refreshing values to MQTT 21 | void refresh_weather(boolean flagForce); 22 | 23 | // hook for incoming MQTT messages 24 | boolean mqtt_weather(char *topicCut, char *payload); 25 | 26 | // Last temperature read 27 | extern float temperatureCurrent; 28 | 29 | // Last humidity read 30 | extern float humidityCurrent; 31 | 32 | // Last pressure read (only for GY-39) 33 | extern float pressureCurrent; 34 | 35 | // Last illumination read (only for GY-39) 36 | extern float illuminationCurrent; 37 | 38 | // Check/report DHT22 or GY-39 readings flag 39 | extern boolean FlagReportWeather; 40 | 41 | #endif 42 | --------------------------------------------------------------------------------