├── LICENSE ├── README.md ├── button.cpp ├── button.h ├── connections.jpg ├── dns.cpp ├── dns.h ├── editrule.png ├── led.cpp ├── led.h ├── log.cpp ├── log.h ├── make-certs-256.sh ├── make-tz-h.pl ├── mqtt.cpp ├── mqtt.h ├── ntp.cpp ├── ntp.h ├── password.cpp ├── password.h ├── power.cpp ├── power.h ├── psychoplug.h ├── psychoplug.ino ├── relay.cpp ├── relay.h ├── schedule.cpp ├── schedule.h ├── schedule.png ├── settings.cpp ├── settings.h ├── setup.png ├── timezone.cpp ├── timezone.h ├── tz.h ├── web.cpp └── web.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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PsychoPlug - ESP8266 outlet firmware with standalone HTTPS encrypted interface, in-box scheduler and MQTT integration 2 | 3 | This is a gold-plated replacement firmware for ESP8266-based WIFI controlled outlets. 4 | * HTTPS secured web interface (see https://github.com/esp8266/Arduino/pull/3001 for required changes to Arduino) 5 | * Password protected (over HTTPS for security even with HTTP BAsic Authentication) 6 | * Built-in NTP driven event management and timekeeping with Daylight Savings Time auto-adjustment and world time zones 7 | * Up to 24 daily events configurable on a per-day, per-minute basis 8 | * No MQTT server is *required*, but MQTT (unencrypted and encrypted) is fully supported 9 | * No cloud connection is required for operation 10 | * OTA firmware updates 11 | 12 | ## DISCLAIMER and WARNINGS 13 | Use of this software and procedure are completely at your own risk. This project involves working on devices that control household current. At no time should the remote control outlet be connected to an outlet/power source while either (a) opened, which would possibly expose you to *lethal* voltages, or (b) connected to your computer, which could do *fatal damage* to your computer and attached devices. Perform any disassembly and reassembly with great care ensuring no spare parts or wires are left inside the plug after your intial upload. IF YOU HAVE ANY DOUBT ABOUT PERFORMING THESE OPERATIONS PLEASE DO NOT CONTINUE. 14 | 15 | DO NOT NAT-FORWARD THIS TO THE PUBLIC INTERNET! While I have strived to make this a robust and safe web interface, there is always the possibilty that there are bugs known or unknown which might allow someone other than yourself to control the outlet without authorization. 16 | 17 | INSTEAD, use a VPN into your house or a web-based, SSL encrypted MQTT broker to control things from outside your home. Either way does not require any holes in your NAT firewall on inbound connections, and will fully encrypt any username and passwords send over the public Internet. 18 | 19 | ## Prerequisites 20 | 21 | * Ensure you have the Arduino ESP8266 IDE installed. Note that for Ubuntu the Arduino IDE is *very* old and you'll need to install from http://arduino.cc to get access to the ESP8266 toolchain. 22 | * Install the library "MQTT by Joel Gaehwiler" from the Arduino library manager or from https://github.com/256dpi/arduino-mqtt/ 23 | * Install the library "TimeLib by Paul Stoffregen" (https://github.com/PaulStoffregen/Time) manually 24 | * Select your model and flash size (normally GenericESP8266 and 1M, 64K SPIFFS) 25 | * Select 160MHz in Tools->CPU Frequency->160MHz to make the SSL web interface fast enough to use. 26 | 27 | ## Generating your own SSL certificate before compiling 28 | 29 | Before the first compile, you will need to generate a new SSL key and certificate. No default key is included in the repository, by design. If you don't generate a new key the compilation will fail with an "include file not found(x509.h and key.h)" 30 | 31 | Because the X509 certificate and key can be used to intercept and decrypt all communications between the plug and your web browser, it is imperative that you generate your own pair. 32 | 33 | "make-certs-256.sh" is included to generate these files. On a Linux machine with the standard OpenSSL utilities, simply change to the source directory and run "bash make-certs-256.sh" and it will generate two files, "x509.h" and "key.h" which will be included in the compilation automatically. 34 | 35 | 36 | ## Connecting the plug to your computer 37 | 38 | ![Programmer Connections](connections.jpg "Programmer Connections") 39 | 40 | You can follow the connections and directions given in [2] to upload the image, but if you have a USB to Serial adapter that provides both +5V and +3.3V outputs then you can actually use tha above image as a guide and only have to solder on 3 wires, not 5 (and for me it was a pain soldering the wires to the frame so this was a big win). 41 | 42 | 1. UNPLUG YOUR USB adaptor! 43 | 2. Connect the ground from your USB adapter. I used a grasping logic analyzer probe for this to avoid soldering. 44 | 3. Connect The USB +5V output to the voltage regulator input. I used a cheap grasping logic analyzer probe for this as well. 45 | 4. Connect the USB TX to the 4th pin from the right as shown in the picture (this is the ESP8266 RX pin) 46 | 5. Connect the USB RX to the 5th pin from the right as shown (this is the ESP8266 TX pin) 47 | 6. Connect GPIO (the 1st pin from the right) to the ground ring. You can just hold it to the ring or use a clip. 48 | 7. Plug in the USB adaptor to the PC 49 | 8. Push the pushbutton to enable the bootloader. The red LED will light up (D8 in the image) and you'll hear a satisfying click as the relay engages. 50 | 51 | At this point you should be able to upload images using the Arduino IDE. 52 | 53 | 54 | ## Upload instructions 55 | * DO NOT OPERATE WHILE PLUG IS POWERED FROM AN AC CIRCUIT!!! UNPLUG AND WORK ON YOUR BENCH UNTIL INITIAL UPLOAD AND TESTS COMPLETED AND THE OUTLET COMPLETELY REASSEMBLED!!! 56 | * Disassemble the plug and get access to the ESP8266 control board. 57 | * Tack wires as discussed in [2] and hook to your USB/Serial adapter. 58 | * Build and flash to your plug, it will reboot. 59 | 60 | 61 | ## Initial configuration 62 | 63 | * Connect your phone or laptop WIFI to the plug's configuration access point (PSYCHOPLUG-XXX) 64 | * Go to https://192.168.4.1 (DNS redirection is a WIP, so for now you'll need to use the IP) 65 | * Enter your home's SSID/PSK and other network configurations, passwords, etc. 66 | * Plug will report success and reboot, but because you've just doen a serial upload will hang in the bootloader 67 | * Power cycle the plug (i.e. unplug the USB serial cable then re-plug it in to your computer) to ensure a clean reboot 68 | 69 | The web interface is simple and text based and should be easy to use on any smartphone or tablet if a laptop with WiFi isn't available. It even works in "links," the text-mode web browser. 70 | 71 | ![Setup Web Page](setup.png "Setup Web Page") 72 | 73 | ## Schedule setup 74 | 75 | * Use HTTPS://plugname/ to configure schedules, check state, etc. 76 | * You may need to consult your WiFi AP to find the plug IP (or use a static IP in configuration above) if there are DNS issues with your AP. 77 | * Verify the time looks good on the initial web page, that the relay is working (toggle off and on from the main page) 78 | 79 | ![Main Schedule](schedule.png "Main Schedule Web Page") 80 | 81 | 82 | ## Event configuration 83 | * Be sure to check one or more days of the week are selected, and that the Action is not "None" to ensure the event actually triggers 84 | * Actions Off and On are self-explanatory. Toggle will toggle from whatever the current state is when the event trigger. Pulse Off turns power off for 1/2 second then turns it back on. Pulse On does the opposite. 85 | 86 | ![Editing a Rule](editrule.png "Editing a Rule") 87 | 88 | ## Reassembly 89 | 90 | * Unplug the USB to serial connector to remove power from the exposed outlet. 91 | * Carefully and cleanly remove any wires attached to perform the upload. 92 | * Double check for any possible shorts or exposed wires before closing. 93 | * Carefully reassemble the plug in the reverse order of disassembly. 94 | * Plug into it's final resting spot. The web interface will become available as soon as the outlet reconnects to your AP. 95 | 96 | ## LED status 97 | 98 | * Red LED lit = power to the controlled outler 99 | * Blue LED fast blink = Setup mode, connect with your phone/laptop to PSYCHOPLUG-XXX and configure 100 | * Blue LED slow blink = Attempting to connect to the WIFI AP specified 101 | * Blue LED blink once every ~1.5 seconds = Operating mode, normal operation 102 | If the outlet is unable to connect to the AP it will continually retry. Should it not connect, you can unplug the outlet and get back into setup mode by holding down the button while re-plugging it in and connecting to its configuration AP. 103 | 104 | ## Network reconfiguration 105 | 106 | After initial setup, the control web page also has a "Change Configuration" capability available at the bottom of the page. 107 | 108 | To reconfigure in case of lost password you can hold the power button down while plugging in the switch. 109 | 110 | 111 | ## Web CGI control 112 | 113 | Simple web applications can be used to control the state of the outlet (be sure to use authentication!): 114 | 115 | wget --user=username --password=mypass "https://..../off.html" 116 | wget --user=username --password=mypass "https://..../on.html" 117 | wget --user=username --password=mypass "https://..../toggle.html" 118 | wget --user=username --password=mypass "https://..../pulseoff.html" 119 | wget --user=username --password=mypass "https://..../pulseon.html" 120 | 121 | 122 | ## Factory reset 123 | 124 | Hold down the power button while plugging in the unit to enable reconfiguration. The LED will do a fast flash and you can reconnect to the built-in AP to adjust any settings (like WiFi). If you don't want to change anything, simply unplug and re-plug in the unit and it will return to normal w/o any changes. 125 | 126 | 127 | ## MQTT 128 | 129 | Both SSL encrypted and unencrypted MQTT connections are supported. Be sure to use the correct port (1883 = no SSL, 8883 = SSL) in the setup page for your choice. 130 | 131 | ### MQTT topics published 132 | 133 | .../button (press,release) => When the button is physically pressed or released on the plug 134 | .../powerstate (0,1) => When the controlled appliance is turned off or on 135 | .../event => When an event fires, records the event type in text (Off, On, Toggle, Pulse Low, Pulse High) 136 | 137 | ### MQTT topics subscribed 138 | 139 | .../remotepower (0,1) => Turn the power off or on remotely 140 | 141 | *Note that both the schedule and MQTT are operating in parallel. So if you have a schedule that says "turn off @ 7:00pm" and you publish a .../remotepower=1 event at 6:59pm the outlet will be on for 1 minute and then turn back off at thescheduled time. No schedules are required for full MQTT control.* 142 | 143 | ## UDP logging 144 | 145 | A basic UDP logging mechanism is included (mostly for code development). When a UDP Log Server is entered in the configuration page, the outlet will log information that would normally go to the serial port to UDP-LOG-IP:9911. This allows for safe debugging of code while the outlet is plugged in and operating. 146 | 147 | Under Linux, simply use a NetCat instance to watch this log (it is NOT in syslog format!): 148 | 149 | nc -l -u 9911 150 | 151 | If no IP is specified (IP=0.0.0.0), the serial port will be used (i.e. for desktop debugging) 152 | 153 | ## Time Zones and TimeLib 154 | 155 | The timezones are stored as a custom, post-processed output from the IANA Time Zone Database (http://www.iana.org/time-zones). The included PERL script, make-tz-h.pl, takes the source files in IANA's text format and generates a header file containing several data structures parsed by the file tz.cpp to adjust the UTC time that is stored using TimeLib to the local times. The file tz.cpp can be built by itself under Linux with "gcc -o tz tz.cpp" to do testing. 156 | 157 | The data structures are stored in FLASH in a fast "compressed" format where only the differences between strings are stored to save precious space. 158 | 159 | 160 | ## References and many thanks 161 | 162 | While the code in this repository is my own work, it wouldn't have been possible without the great hacking work done by Scott Gibson [1] and others in uncovering the GPIO and control points for these kinds of switches. 163 | 164 | [1] http://thegreatgeekery.blogspot.ca/2016/02/ecoplug-wifi-switch-hacking.html 165 | 166 | [2] http://www.hagensieker.com/blog/page/?post_id=44&title=esp8266-hack-of-inexpensive-wifi-outlet 167 | 168 | [3] http://www.esp8266.com/viewtopic.php?f=6&t=8044 169 | -------------------------------------------------------------------------------- /button.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include "psychoplug.h" 22 | #include "button.h" 23 | #include "settings.h" 24 | #include "mqtt.h" 25 | #include "relay.h" 26 | #include "log.h" 27 | 28 | static byte DebounceButton(); 29 | 30 | #define PIN_BUTTON (13) 31 | 32 | 33 | void StartButton() 34 | { 35 | pinMode(PIN_BUTTON, INPUT_PULLUP); 36 | } 37 | 38 | // Hendle all power button management (debounce, mqtt, etc.) 39 | void ManageButton() 40 | { 41 | // Let the button toggle the relay always 42 | byte action = DebounceButton(); 43 | 44 | if (action==BUTTON_PRESS) { 45 | SetRelay(!GetRelay()); 46 | } 47 | if (action != BUTTON_NONE) { 48 | MQTTPublish("button", action==BUTTON_PRESS?"press":"release"); 49 | } 50 | } 51 | 52 | bool RawButton() 53 | { 54 | return !digitalRead(PIN_BUTTON); 55 | } 56 | 57 | // Check if button has been pressed (after debounce) and return one event for press and one for release 58 | static byte DebounceButton() 59 | { 60 | static bool ignoring = false; 61 | static unsigned long checkTime = 0; 62 | static bool prevButton = false; 63 | static bool debounceButton = false; 64 | byte event = BUTTON_NONE; 65 | 66 | if (!ignoring) { 67 | bool curButton = !digitalRead(PIN_BUTTON); 68 | if (curButton != prevButton) { 69 | ignoring = true; 70 | checkTime = micros() + 5000; 71 | } 72 | prevButton = curButton; 73 | } else { 74 | bool curButton = !digitalRead(PIN_BUTTON); 75 | if (curButton != prevButton) { 76 | // Noise, reset the clock 77 | ignoring = false; 78 | } else if (micros() > checkTime) { 79 | if (curButton != debounceButton) { 80 | event = (debounceButton)?BUTTON_RELEASE:BUTTON_PRESS; 81 | debounceButton = curButton; 82 | LogPrintf("Button Event: %d\n", event); 83 | } 84 | ignoring = false; 85 | } 86 | } 87 | return event; 88 | } 89 | 90 | -------------------------------------------------------------------------------- /button.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _button_h 22 | #define _button_h 23 | 24 | #include 25 | 26 | // Button event types 27 | #define BUTTON_NONE (0) 28 | #define BUTTON_PRESS (1) 29 | #define BUTTON_RELEASE (2) 30 | 31 | void StartButton(); 32 | 33 | // Check button state and act appropriately 34 | void ManageButton(); 35 | 36 | // Used during setup to see raw state of button, not to be used elsewhere 37 | bool RawButton(); 38 | 39 | #endif 40 | 41 | -------------------------------------------------------------------------------- /connections.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/earlephilhower/psychoplug/11ebfc7b54f0107efb3587451b26c9e827e6ca90/connections.jpg -------------------------------------------------------------------------------- /dns.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | /* Taken and simplified from the DNSServer and example code in the ESP8266 22 | Arduino setup to only reply with our IP and provide some logging and no 23 | malloc()/free()ing. */ 24 | 25 | #include 26 | #include 27 | #include 28 | #include "dns.h" 29 | #include "log.h" 30 | 31 | // Only active during setup to redirect everyone to the setup page 32 | static WiFiUDP dns; 33 | static IPAddress apIP; 34 | 35 | #define DNS_QR_QUERY 0 36 | #define DNS_QR_RESPONSE 1 37 | #define DNS_OPCODE_QUERY 0 38 | 39 | typedef struct DNSHeader 40 | { 41 | uint16_t ID; // identification number 42 | unsigned char RD : 1; // recursion desired 43 | unsigned char TC : 1; // truncated message 44 | unsigned char AA : 1; // authoritive answer 45 | unsigned char OPCode : 4; // message_type 46 | unsigned char QR : 1; // query/response flag 47 | unsigned char RCode : 4; // response code 48 | unsigned char Z : 3; // its z! reserved 49 | unsigned char RA : 1; // recursion available 50 | uint16_t QDCount; // number of question entries 51 | uint16_t ANCount; // number of answer entries 52 | uint16_t NSCount; // number of authority entries 53 | uint16_t ARCount; // number of resource entries 54 | } DNSHeader; 55 | 56 | 57 | void StartDNS(IPAddress *ip) 58 | { 59 | LogPrintf("Starting DNS server\n"); 60 | apIP = *ip; 61 | dns.begin(53); 62 | } 63 | 64 | 65 | static void DumpDNSHeader(DNSHeader *h) 66 | { 67 | LogPrintf("ID = %04x\n", h->ID); 68 | LogPrintf("RD = %d\n", h->RD); 69 | LogPrintf("TC = %d\n", h->TC); 70 | LogPrintf("AA = %d\n", h->AA); 71 | LogPrintf("OPCode = %d\n", h->OPCode); 72 | LogPrintf("QR = %d\n", h->QR); 73 | LogPrintf("RCode = %d\n", h->RCode); 74 | LogPrintf("Z = %d\n", h->Z); 75 | LogPrintf("RA = %d\n", h->RA); 76 | LogPrintf("QDCount = %d\n", ntohs(h->QDCount)); 77 | LogPrintf("ANCount = %d\n", ntohs(h->ANCount)); 78 | LogPrintf("NSCount = %d\n", ntohs(h->NSCount)); 79 | LogPrintf("ARCount = %d\n", ntohs(h->ARCount)); 80 | } 81 | 82 | static void ReplyWithIP(DNSHeader *hdr, unsigned char *buff, int len) 83 | { 84 | if (buff== NULL) return; 85 | hdr->QR = DNS_QR_RESPONSE; 86 | hdr->ANCount = hdr->QDCount; 87 | hdr->RA = 0; 88 | 89 | dns.beginPacket(dns.remoteIP(), dns.remotePort()); 90 | buff[2] = 0x81; 91 | buff[3] = 0x80; 92 | buff[4] = 0; 93 | buff[5] = 1; 94 | buff[6] = 0; 95 | buff[7] = 1; 96 | buff[8] = 0; 97 | buff[9] = 0; 98 | buff[10] = 0; 99 | buff[11] = 0; 100 | dns.write(buff, len); 101 | 102 | dns.write((uint8_t)192); // answer name is a pointer 103 | dns.write((uint8_t)12); // pointer to offset at 0x00c 104 | 105 | dns.write((uint8_t)0); // 0x0001 answer is type A query (host address) 106 | dns.write((uint8_t)1); 107 | 108 | dns.write((uint8_t)0); //0x0001 answer is class IN (internet address) 109 | dns.write((uint8_t)1); 110 | 111 | uint32_t ttl = htonl(600); 112 | dns.write((unsigned char*)&ttl, 4); 113 | 114 | // Length of RData is 4 bytes (because, in this case, RData is IPv4) 115 | dns.write((uint8_t)0); 116 | dns.write((uint8_t)4); 117 | dns.write(apIP[0]); 118 | dns.write(apIP[1]); 119 | dns.write(apIP[2]); 120 | dns.write(apIP[3]); 121 | dns.endPacket(); 122 | } 123 | 124 | 125 | void ManageDNS() 126 | { 127 | int size = dns.parsePacket(); 128 | if (size) { 129 | unsigned char *pkt = (unsigned char *)alloca(size); 130 | dns.read(pkt, size); 131 | Serial.print("DNS: "); for (int i=0; iQR == DNS_QR_QUERY && hdr->OPCode == DNS_OPCODE_QUERY) { 134 | if (ntohs(hdr->QDCount) == 1 && hdr->ANCount == 0 && hdr->NSCount == 0 && hdr->ARCount == 0) { 135 | unsigned char *p = pkt+12; 136 | char nameBuff[256]; 137 | uint8_t j = 0; 138 | while (*p) { 139 | uint8_t cnt = *(p++); 140 | for (uint8_t i=0; i. 19 | */ 20 | 21 | #ifndef _dns_h 22 | #define _dns_h 23 | 24 | // Initializes simple AP DNS 25 | void StartDNS(IPAddress *apIP); 26 | 27 | // Handles DNS queries, very simply 28 | void ManageDNS(); 29 | 30 | #endif 31 | 32 | -------------------------------------------------------------------------------- /editrule.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/earlephilhower/psychoplug/11ebfc7b54f0107efb3587451b26c9e827e6ca90/editrule.png -------------------------------------------------------------------------------- /led.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include "led.h" 23 | 24 | #define PIN_LED (2) 25 | 26 | void StartLED() 27 | { 28 | digitalWrite(PIN_LED, HIGH); 29 | pinMode(PIN_LED, OUTPUT); 30 | } 31 | 32 | static const uint32_t ledBlinkValue[] ICACHE_RODATA_ATTR = { 33 | 0x00000000, // LED_OFF 34 | 0xffffffff, // LED_ON 35 | 0xffff0000, // LED_CONNECTING (slow blink) 36 | 0xaaaaaaaa, // LED_AWAITSETUP (annoying flash) 37 | 0x00000001 // LED_CONNECTED (occasional blip) 38 | }; 39 | 40 | void ManageLED(ledBlink type) 41 | { 42 | byte whichBit = (millis()/100) % 32; 43 | digitalWrite(PIN_LED, ledBlinkValue[type] & (1<. 19 | */ 20 | 21 | #ifndef _led_h 22 | #define _led_h 23 | 24 | void StartLED(); 25 | 26 | 27 | typedef enum { LED_OFF, LED_ON, LED_CONNECTING, LED_AWAITSETUP, LED_CONNECTED } ledBlink; 28 | 29 | void ManageLED(ledBlink type); 30 | 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /log.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | #include "psychoplug.h" 26 | #include "log.h" 27 | #include "settings.h" 28 | 29 | static WiFiUDP udpLog; 30 | 31 | 32 | void StartLog() 33 | { 34 | udpLog.begin(8976); 35 | } 36 | 37 | void StopLog() 38 | { 39 | udpLog.stop(); 40 | } 41 | 42 | void Log(const char *str) 43 | { 44 | static char mac[8] = {0}; 45 | if (mac[0]==0) { 46 | byte hwMAC[12]; 47 | WiFi.macAddress((byte *)hwMAC); 48 | sprintf_P(mac, PSTR("%02x%02x%02x: "), hwMAC[3], hwMAC[4], hwMAC[5]); 49 | } 50 | 51 | if (!isSetup || !settings.logsvr[0]) { 52 | Serial.print(mac); 53 | Serial.print(str); 54 | Serial.flush(); 55 | } else { 56 | udpLog.beginPacket(settings.logsvr, 9911); 57 | udpLog.write(mac, 8); 58 | udpLog.write(str, strlen(str)); 59 | udpLog.endPacket(); 60 | } 61 | } 62 | 63 | 64 | -------------------------------------------------------------------------------- /log.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _log_h 22 | #define _log_h 23 | 24 | // Start and stop logging infrastructure 25 | void StartLog(); 26 | void StopLog(); 27 | 28 | // Write string to the log (serial or UDP) 29 | extern void Log(const char *str); 30 | 31 | // Ease-of-use to send formatted output 32 | #define LogPrintf(fmt, ...) { char buff[256]; snprintf_P(buff, sizeof(buff), PSTR(fmt), ## __VA_ARGS__); Log(buff); } 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /make-certs-256.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 1024 or 512. 512 saves memory... 4 | BITS=512 5 | C=$PWD 6 | pushd /tmp 7 | 8 | openssl genrsa -out tls.ca_key.pem $BITS 9 | openssl genrsa -out tls.key_$BITS.pem $BITS 10 | openssl rsa -in tls.key_$BITS.pem -out tls.key_$BITS -outform DER 11 | cat > certs.conf < "$C/key.h" 28 | xxd -i tls.x509_$BITS.cer | sed 's/.*{//' | sed 's/\};//' | sed 's/unsigned.*//' > "$C/x509.h" 29 | 30 | rm -f tls.ca_key.pem tls.key_$BITS.pem tls.key_$BITS certs.conf tls.ca_x509.req tls.x509_$BITS.req tls.ca_x509.pem tls.x509_$BITS.pem tls.srl tls.x509_$BITS.cer tls.ca_x509.cer 31 | 32 | popd 33 | -------------------------------------------------------------------------------- /make-tz-h.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | 4 | @files = ( "africa", "antarctica", "asia", "australasia", "europe", "northamerica", "southamerica", "pacificnew", "etcetera", "backward" ); 5 | 6 | my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); 7 | $curyear = $year + 1900; 8 | 9 | $month{'Jan'} = "MON_JAN"; 10 | $month{'Feb'} = "MON_FEB"; 11 | $month{'Mar'} = "MON_MAR"; 12 | $month{'Apr'} = "MON_APR"; 13 | $month{'May'} = "MON_MAY"; 14 | $month{'Jun'} = "MON_JUN"; 15 | $month{'Jul'} = "MON_JUL"; 16 | $month{'Aug'} = "MON_AUG"; 17 | $month{'Sep'} = "MON_SEP"; 18 | $month{'Oct'} = "MON_OCT"; 19 | $month{'Nov'} = "MON_NOV"; 20 | $month{'Dec'} = "MON_DEC"; 21 | 22 | # If we don't do these manually, we'll get random integers per month. :( 23 | print "#define MON_JAN (0)\n"; 24 | print "#define MON_FEB (1)\n"; 25 | print "#define MON_MAR (2)\n"; 26 | print "#define MON_APR (3)\n"; 27 | print "#define MON_MAY (4)\n"; 28 | print "#define MON_JUN (5)\n"; 29 | print "#define MON_JUL (6)\n"; 30 | print "#define MON_AUG (7)\n"; 31 | print "#define MON_SEP (8)\n"; 32 | print "#define MON_OCT (9)\n"; 33 | print "#define MON_NOV (10)\n"; 34 | print "#define MON_DEC (11)\n"; 35 | 36 | $daytrig{'Sun>='} = "SUN_GTEQ"; 37 | $daytrig{'Mon>='} = "MON_GTEQ"; 38 | $daytrig{'Tue>='} = "TUE_GTEQ"; 39 | $daytrig{'Wed>='} = "WED_GTEQ"; 40 | $daytrig{'Thu>='} = "THU_GTEQ"; 41 | $daytrig{'Fri>='} = "FRI_GTEQ"; 42 | $daytrig{'Sat>='} = "SAT_GTEQ"; 43 | $daytrig{'lastSun'} = "SUN_LAST"; 44 | $daytrig{'lastMon'} = "MON_LAST"; 45 | $daytrig{'lastTue'} = "TUE_LAST"; 46 | $daytrig{'lastWed'} = "WED_LAST"; 47 | $daytrig{'lastThu'} = "THU_LAST"; 48 | $daytrig{'lastFri'} = "FRI_LAST"; 49 | $daytrig{'lastSat'} = "SAT_LAST"; 50 | $daytrig{'givenDay'} = "GIVEN_DAY"; 51 | 52 | $atref{'local'} = "ATREF_W"; # Wall clock (subject to daylight savings) 53 | $atref{'u'} = "ATREF_U"; # UTC/GMT time 54 | $atref{'s'} = "ATREF_S"; # Local standard w/o taking daylight savings into account 55 | 56 | #$i=0; foreach $k (keys %month) { print "#define $month{$k} ($i)\n"; $i++ } 57 | $i=0; foreach $k (keys %daytrig) { print "#define $daytrig{$k} ($i)\n"; $i++ } 58 | $i=0; foreach $k (keys %atref) { print "#define $atref{$k} ($i)\n"; $i++ } 59 | 60 | 61 | $rulenames{'RULE_NONE'} = 1; 62 | 63 | foreach $f (@files) { 64 | open F, "<$f"; 65 | while ($line = ) { 66 | chomp $line; 67 | $line =~ s/#.*//; 68 | @w = split(/\s+/, $line); 69 | if (($w[0] eq "Rule") and ((($w[3] eq "max") and ($w[2]<=$curyear)) or (($w[3] eq "only")and ($w[2]==$curyear))) ) { 70 | $w[1] =~ s/-/_/g; 71 | $name = "RULE_" . $w[1]; 72 | next if (($name eq "RULE_Morocco") and ($w[2] eq "2013")); # Contradictory info in the Morocco entry, shows a MAX in 2013 and then other entries 73 | $mon = $month{$w[5]}; 74 | $day = $w[6]; 75 | ($day, $daynum) = split(/\=/, $day); 76 | if ($day =~ /^[0-9]+$/) { 77 | $daynum = $day; 78 | $day = "givenDay"; 79 | $day = $daytrig{$day}; 80 | } else { 81 | $day = $day . "=" if ($daynum ne ""); 82 | $day = $daytrig{$day}; 83 | $daynum = "0" if ($daynum eq ""); 84 | } 85 | $time = $w[7]; 86 | if ($time =~ /u$/) {$atus = $atref{'u'}; $time =~ s/u$//; } 87 | elsif ($time =~ /s$/) {$atus = $atref{'s'}; $time =~ s/s$//; } 88 | else { $atus = $atref{'local'}; } 89 | ($ath, $atm) = split(/:/, $time); 90 | if ($ath == 24) { $ath = $23; $atm = 59; } 91 | $ath = int($ath); 92 | $atm = int($atm); 93 | $delta = $w[8]; 94 | ($deltah, $deltam) = split(/:/, $delta); 95 | if ($deltah == 24) { $deltah = $23; $deltam = 59; } 96 | $deltah = int($deltah); 97 | $deltam = int($deltam); 98 | $fmtstr = $w[9]; 99 | $fmtstr = "" if ($fmtstr eq "-"); 100 | $rulenames{$name} = $w[3]; 101 | push @rule, "{$name, $mon, $day, $daynum, $ath, $atm, $atus, $deltah, $deltam, \"$fmtstr\"},\n"; 102 | } 103 | } 104 | close F 105 | } 106 | 107 | $i=0; foreach $k (keys %rulenames) { print "#define $k ($i)\n"; $i++ } 108 | print <> average 121 | } rule_t; 122 | EOF 123 | ; 124 | @rule = sort @rule; 125 | print("static const rule_t rules[] = {\n"); 126 | foreach $k (@rule) { 127 | print "$k" 128 | } 129 | print "};\n"; 130 | 131 | 132 | foreach $f (@files) { 133 | open F, "<$f"; 134 | while ($line = ) { 135 | chomp $line; 136 | $line =~ s/#.*//; 137 | @w = split(/\s+/, $line); 138 | if ($w[0] eq "Zone") { 139 | $zonename = $w[1]; 140 | $gmtoff = $w[2]; 141 | $rules = $w[3]; 142 | $fmt = $w[4]; 143 | $until = $w[5]; 144 | } elsif (($zonename ne "") && ($w[1] ne "")) { 145 | $gmtoff = $w[1]; 146 | $rules = $w[2]; 147 | $fmt = $w[3]; 148 | $until = $w[4]; 149 | } 150 | if (($zonename ne "") && (($until eq "") || ($until >= $curyear)) ) { 151 | $rules = "NONE" if ($rules eq "-"); 152 | $rules =~ s/-/_/g; 153 | $rules = "RULE_" . $rules; 154 | $rules = "RULE_NONE" if (! exists($rulenames{$rules})); # They're not using DST anymore 155 | ($h, $m) = split(/:/, $gmtoff); 156 | $h = 0 if ($h eq ""); 157 | $m = 0 if ($m eq ""); 158 | $h = int($h); 159 | $m = int($m); 160 | push @zone, "{REPLACEME, /*$zonename*/ \"$zonename\", $h, $m, $rules, \"$fmt\"},\n"; 161 | $zonename= ""; 162 | } 163 | } 164 | close F 165 | } 166 | @zone = sort @zone; 167 | 168 | foreach $f (@files) { 169 | open F, "<$f"; 170 | while ($line = ) { 171 | chomp $line; 172 | $line =~ s/#.*//; 173 | @w = split(/\s+/, $line); 174 | if ($w[0] eq "Link") { 175 | $destzone = $w[1]; 176 | $linkname = $w[2]; 177 | for ($i = 0; $i < @zone; $i++) { 178 | $thisname = $zone[$i]; 179 | $thisname =~ s/\"(.*)?\",//; 180 | $thisname = $1; 181 | if ($thisname eq $destzone) { 182 | push @link, "{ REPLACEME, \"$linkname\", $i /*$thisname*/ },\n"; 183 | break; 184 | } 185 | } 186 | } 187 | } 188 | close F; 189 | } 190 | @link = sort @link; 191 | 192 | 193 | print < 31); # 5-bits wide 221 | $delta = substr($thisname, $cnt); 222 | $z =~ s/REPLACEME/$cnt/; 223 | $z =~ s/\".*?\",/\"$delta\",/; 224 | print $z; 225 | $prevname = $thisname; 226 | } 227 | print "};\n"; 228 | 229 | print < 31); # 5-bits wide 252 | $delta = substr($thisname, $cnt); 253 | $z =~ s/REPLACEME/$cnt/; 254 | $z =~ s/\".*?\"/\"$delta\"/; 255 | print $z; 256 | $prevname = $thisname; 257 | } 258 | 259 | 260 | print "};\n" 261 | -------------------------------------------------------------------------------- /mqtt.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | #include "psychoplug.h" 26 | #include "log.h" 27 | #include "mqtt.h" 28 | #include "settings.h" 29 | #include "relay.h" 30 | 31 | // MQTT interface 32 | static WiFiClient *wifiMQTT = NULL; 33 | static MQTTClient mqttClient; 34 | 35 | // Callback for the MQTT library 36 | void messageReceived(String& topic, String& payload) 37 | { 38 | char t[64], p[32]; 39 | 40 | topic.toCharArray(t, sizeof(t)); 41 | payload.toCharArray(p, sizeof(p)); 42 | LogPrintf("MQTT: '%s'='%s'\n", t, p); 43 | 44 | char topicStr[64]; 45 | snprintf_P(topicStr, sizeof(topicStr), PSTR("%s/remotepower"), settings.mqttTopic); 46 | if (!strcmp(topicStr, t)) { 47 | if (!strcasecmp_P(p, PSTR("on")) || !strcmp_P(p, PSTR("1"))) 48 | SetRelay(true); 49 | else if (!strcasecmp_P(p, PSTR("off")) || !strcmp_P(p, PSTR("0"))) 50 | SetRelay(false); 51 | else if (!strcasecmp_P(p, PSTR("toggle")) ) 52 | SetRelay(!GetRelay()); 53 | } 54 | } 55 | 56 | 57 | void StartMQTT() 58 | { 59 | LogPrintf("Starting MQTT\n"); 60 | LogPrintf("Free heap = %d\n", ESP.getFreeHeap()); 61 | LogPrintf("Connecting MQTT...\n"); 62 | if (settings.mqttEnable) { 63 | if (settings.mqttSSL) wifiMQTT = new WiFiClientSecure(); 64 | else wifiMQTT = new WiFiClient(); 65 | mqttClient.begin(settings.mqttHost, settings.mqttPort, *wifiMQTT); 66 | mqttClient.onMessage(messageReceived); 67 | mqttClient.connect(settings.mqttClientID, settings.mqttUser, settings.mqttPass); 68 | if (mqttClient.connected() ) { 69 | char topic[64]; 70 | snprintf_P(topic, sizeof(topic), PSTR("%s/remotepower"), settings.mqttTopic); 71 | mqttClient.subscribe(topic); 72 | } 73 | } 74 | LogPrintf("Free heap = %d after connection\n", ESP.getFreeHeap()); 75 | } 76 | 77 | void ManageMQTT() 78 | { 79 | if (!settings.mqttEnable) return; 80 | 81 | // Only have MQTT loop if we're connected and configured 82 | if (mqttClient.connected()) { 83 | mqttClient.loop(); 84 | delay(10); 85 | } else { 86 | LogPrintf("MQTT disconnected, reconnecting\n"); 87 | mqttClient.connect(settings.mqttClientID, settings.mqttUser, settings.mqttPass); 88 | if (mqttClient.connected() ) { 89 | char topic[64]; 90 | snprintf_P(topic, sizeof(topic), PSTR("%s/remotepower"), settings.mqttTopic); 91 | mqttClient.subscribe(topic); 92 | } 93 | delay(10); 94 | } 95 | } 96 | 97 | void StopMQTT() 98 | { 99 | if (settings.mqttEnable) { 100 | wifiMQTT->flush(); 101 | wifiMQTT->stop(); 102 | mqttClient.disconnect(); 103 | } 104 | } 105 | 106 | void MQTTPublish(const char *key, const char *value) 107 | { 108 | if (isSetup && settings.mqttEnable && mqttClient.connected()) { 109 | char topic[64]; 110 | snprintf_P(topic, sizeof(topic), PSTR("%s/%s"), settings.mqttTopic, key); 111 | mqttClient.publish(topic, value); 112 | } 113 | } 114 | 115 | void MQTTPublishInt(const char *key, const int value) 116 | { 117 | char str[16]; 118 | snprintf_P(str, sizeof(str), PSTR("%d"), value); 119 | MQTTPublish(key, str); 120 | } 121 | 122 | 123 | -------------------------------------------------------------------------------- /mqtt.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _mqtt_h 22 | #define _mqtt_h 23 | 24 | void StartMQTT(); 25 | void ManageMQTT(); 26 | void StopMQTT(); 27 | 28 | void MQTTPublish(const char *key, const char *value); 29 | void MQTTPublishInt(const char *key, const int value); 30 | 31 | #endif 32 | 33 | -------------------------------------------------------------------------------- /ntp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "ntp.h" 27 | #include "settings.h" 28 | #include "log.h" 29 | 30 | static WiFiUDP ntpUDP; 31 | static time_t GetNTPTime(); 32 | static void SendNTPPacket(IPAddress &address, byte *packetBuffer); 33 | 34 | static short syncInterval = 600; 35 | 36 | void StartNTP() 37 | { 38 | // Enable NTP timekeeping 39 | ntpUDP.begin(8675); // 309 40 | setSyncProvider(GetNTPTime); 41 | setSyncInterval(syncInterval); 42 | } 43 | 44 | void StopNTP() 45 | { 46 | ntpUDP.stop(); 47 | } 48 | 49 | 50 | /*-------- NTP code ----------*/ 51 | /* Taken from the ESP8266 WebClient NTP sample */ 52 | #define NTP_PACKET_SIZE (48) // NTP time is in the first 48 bytes of message 53 | 54 | static time_t GetNTPTime() 55 | { 56 | IPAddress ntpServerIP; // NTP server's ip address 57 | byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets 58 | 59 | while (ntpUDP.parsePacket() > 0) ; // discard any previously received packets 60 | // get a random server from the pool 61 | WiFi.hostByName(settings.ntp, ntpServerIP); 62 | SendNTPPacket(ntpServerIP, packetBuffer); 63 | int timeout = 1500; // Avoid issue of millis() rollover 64 | while (timeout--) { 65 | int size = ntpUDP.parsePacket(); 66 | if (size >= NTP_PACKET_SIZE) { 67 | ntpUDP.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer 68 | 69 | #ifdef DEBUG_NTP 70 | for (int i=0; i<6; i++) { 71 | LogPrintf("NTP %02x: ", i*8); 72 | for (int j=0; j<8; j++) LogPrintf("%02x ", packetBuffer[i*8+j]); 73 | LogPrintf("\n"); 74 | } 75 | #endif 76 | 77 | unsigned char stratum = packetBuffer[1]; 78 | if (stratum==0) { 79 | if (!memcmp_P(packetBuffer+12, PSTR("RATE"), 4)) { 80 | LogPrintf("NTP RATE Kiss of Death, setting syncInterval to %d\n", syncInterval); 81 | syncInterval += 10; 82 | setSyncInterval(syncInterval); 83 | } else if (!memcmp_P(packetBuffer+12, PSTR("RSTR"), 4) || !memcmp_P(packetBuffer+12, PSTR("DENY"), 4)) { 84 | LogPrintf("NTP DENY/RSTR Kiss of Death, disabling NTP requests from this IP\n"); 85 | // TBD - should we clear it? No way to notify user easily... settings.ntp[0] = 0; 86 | } else { 87 | LogPrintf("NTP Kiss of Death, Unknown code: %c%c%c%c\n", packetBuffer[12], packetBuffer[13], packetBuffer[14], packetBuffer[15]); 88 | } 89 | return 0; // Some error occurred, can't get the time 90 | } 91 | 92 | unsigned long secsSince1900; 93 | // convert four bytes starting at location 40 to a long integer 94 | secsSince1900 = (unsigned long)packetBuffer[40] << 24; 95 | secsSince1900 |= (unsigned long)packetBuffer[41] << 16; 96 | secsSince1900 |= (unsigned long)packetBuffer[42] << 8; 97 | secsSince1900 |= (unsigned long)packetBuffer[43]; 98 | return secsSince1900 - 2208988800UL /*70 years*/; 99 | } else 100 | delay(1); 101 | } 102 | return 0; // return 0 if unable to get the time 103 | } 104 | 105 | 106 | // send an NTP request to the time server at the given address 107 | static void SendNTPPacket(IPAddress &address, byte *packetBuffer) 108 | { 109 | // set all bytes in the buffer to 0 110 | memset(packetBuffer, 0, NTP_PACKET_SIZE); 111 | // Initialize values needed to form NTP request 112 | // (see URL above for details on the packets) 113 | packetBuffer[0] = 0b11100011; // LI, Version, Mode 114 | packetBuffer[1] = 0; // Stratum, or type of clock 115 | packetBuffer[2] = 6; // Polling Interval 116 | packetBuffer[3] = 0xEC; // Peer Clock Precision 117 | // 8 bytes of zero for Root Delay & Root Dispersion 118 | packetBuffer[12] = 49; 119 | packetBuffer[13] = 0x4E; 120 | packetBuffer[14] = 49; 121 | packetBuffer[15] = 52; 122 | // all NTP fields have been given values, now 123 | // you can send a packet requesting a timestamp: 124 | ntpUDP.beginPacket(address, 123); //NTP requests are to port 123 125 | ntpUDP.write(packetBuffer, NTP_PACKET_SIZE); 126 | ntpUDP.endPacket(); 127 | } 128 | 129 | 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /ntp.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _ntp_h 22 | #define _ntp_h 23 | 24 | // Handle NTP set up from settings variable 25 | void StartNTP(); 26 | 27 | // Stop any NTP operations 28 | void StopNTP(); 29 | 30 | #endif 31 | 32 | -------------------------------------------------------------------------------- /password.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include //sha1 exported here 23 | #include "password.h" 24 | 25 | 26 | // Set the settings.uiPassEnc to the raw password and callthis to make a new salt and run encryption against it 27 | // Output overwrites the uiPassEnc variable 28 | void HashPassword(const char *pass, char *uiSalt, char *uiPassEnc) 29 | { 30 | memset(uiSalt, 0, SALTLEN); // Clear salt to start 31 | memset(uiPassEnc, 0, PASSENCLEN); // Clear salt to start 32 | if (pass[0]==0) return; // No password 33 | for (unsigned int i=0; i. 19 | */ 20 | 21 | #ifndef _password_h 22 | #define _password_h 23 | 24 | #define PASSENCLEN (20) 25 | #define SALTLEN (32) 26 | 27 | // Set the settings.uiPassEnc to the raw password and callthis to make a new salt and run encryption against it 28 | // Output overwrites the uiPassEnc variable 29 | void HashPassword(const char *pass, char *uiSalt, char *uiPassEnc); 30 | 31 | // Check that entered password matches the hash in settings 32 | bool VerifyPassword(char *pass, const char *uiSalt, const char *uiPassEnc); 33 | 34 | #endif 35 | 36 | -------------------------------------------------------------------------------- /power.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | 22 | // Unable to reliably read the power meter, remove it for now. 23 | #if 0 24 | #include 25 | #include 26 | #include "psychoplug.h" 27 | #include "settings.h" 28 | #include "mqtt.h" 29 | #include "log.h" 30 | 31 | 32 | // Noisy current measurement, better than nothing I guess 33 | static int lastCurrentMa = 0; 34 | 35 | #define PIN_SDA (12) 36 | #define PIN_SCL (0) 37 | 38 | 39 | static void ReadPowerMonitor(); 40 | 41 | int GetCurrentMA() 42 | { 43 | return lastCurrentMa; 44 | } 45 | 46 | void StartPowerMonitor() 47 | { 48 | // Power Monitoring 49 | pinMode(PIN_SDA, INPUT_PULLUP); 50 | Wire.begin(PIN_SDA, PIN_SCL); 51 | } 52 | 53 | void ManagePowerMonitor() 54 | { 55 | static unsigned long lastReadMS = 0; 56 | unsigned long ms = millis(); 57 | if (ms < lastReadMS) lastReadMS = ms; // Overflow skip one reading 58 | unsigned long delta = ms - lastReadMS; 59 | if (delta > 10000) { 60 | lastReadMS = millis(); 61 | ReadPowerMonitor(); 62 | MQTTPublishInt("powerma", lastCurrentMa); 63 | } 64 | } 65 | 66 | void StopPowerMonitor() 67 | { 68 | lastCurrentMa = 0; 69 | } 70 | 71 | static void ReadPowerMonitor() 72 | { 73 | char d[12]; 74 | uint32_t rawPwr[3]; 75 | byte count = 0; 76 | int timeout = 1000; 77 | Wire.requestFrom(0, 12); 78 | while (count < 12 && timeout--) { 79 | if (Wire.available()) d[count++] = Wire.read(); 80 | else delay(1); 81 | } 82 | if (timeout <= 0 ) { 83 | rawPwr[0] = rawPwr[1] = rawPwr[2] = 0; 84 | } else { 85 | rawPwr[0] = ((uint32_t)d[0]<<24) | ((uint32_t)d[1]<<16) | ((uint32_t)d[2]<<8) | ((uint32_t)d[3]); 86 | rawPwr[1] = ((uint32_t)d[4]<<24) | ((uint32_t)d[5]<<16) | ((uint32_t)d[6]<<8) | ((uint32_t)d[7]); 87 | rawPwr[2] = ((uint32_t)d[8]<<24) | ((uint32_t)d[9]<<16) | ((uint32_t)d[10]<<8) | ((uint32_t)d[11]); 88 | } 89 | 90 | LogPrintf("%12d(%08x), %12d(%08x), %12d(%08x)", rawPwr[0], rawPwr[0], rawPwr[1], rawPwr[1], rawPwr[2], rawPwr[2]); 91 | LogPrintf(" --- %12d(%08x), %12d(%08x), %12d(%08x)\n", rawPwr[0]&0x7fffffff, rawPwr[0]&0x7fffffff, rawPwr[1&0x7fffffff], rawPwr[1]&0x7fffffff, rawPwr[2]&0x7fffffff, rawPwr[2]&0x7fffffff); 92 | // Current measurement via curve-fit from samples. YMMV, but fits well for me 93 | // Needs Vin to get power (well, and PF, but that's more than we can measure) 94 | double x, y; 95 | x = (double) rawPwr[0]; 96 | y = 29125.43749 * x / (x + 103257.9289) - 12813.31867 * x / (x + 48884.1186); 97 | if (y<0) y=0; 98 | lastCurrentMa = (int)y; 99 | } 100 | 101 | #else 102 | 103 | int GetCurrentMA() { return 0; } 104 | void StartPowerMonitor() {} 105 | void ManagePowerMonitor() {} 106 | void StopPowerMonitor() {} 107 | 108 | #endif 109 | -------------------------------------------------------------------------------- /power.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _power_h 22 | #define _power_h 23 | 24 | void StartPowerMonitor(); 25 | void ManagePowerMonitor(); 26 | void StopPowerMonitor(); 27 | 28 | int GetCurrentMA(); 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /psychoplug.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | 22 | #ifndef _psychoplug_h 23 | #define _psychoplug_h 24 | 25 | 26 | 27 | extern bool isSetup; // Are we configured and connected to a WiFi network? 28 | 29 | #endif 30 | 31 | -------------------------------------------------------------------------------- /psychoplug.ino: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | #include "psychoplug.h" 26 | #include "settings.h" 27 | #include "schedule.h" 28 | #include "mqtt.h" 29 | #include "ntp.h" 30 | #include "button.h" 31 | #include "log.h" 32 | #include "power.h" 33 | #include "password.h" 34 | #include "relay.h" 35 | #include "led.h" 36 | #include "timezone.h" 37 | #include "dns.h" 38 | #include "web.h" 39 | 40 | bool isSetup = false; 41 | 42 | 43 | // Our setup IP 44 | static IPAddress setupIP = {192, 168, 4, 1}; 45 | static IPAddress setupMask = {255, 255, 255, 0}; 46 | 47 | 48 | // All it does is redirect to https:// 49 | static WiFiServer redirector(80); 50 | 51 | // OTA updates on the cheap... 52 | static ESP8266WebServer *otaServer = NULL; 53 | static ESP8266HTTPUpdateServer *otaUpdateServer = NULL; 54 | 55 | 56 | // HTTPS interface 57 | static const uint8_t rsakey[] ICACHE_RODATA_ATTR = { 58 | #include "key.h" 59 | }; 60 | 61 | static const uint8_t x509[] ICACHE_RODATA_ATTR = { 62 | #include "x509.h" 63 | }; 64 | 65 | // Create an instance of the server 66 | // specify the port to listen on as an argument 67 | static WiFiServerSecure https(443); 68 | 69 | // Return a *static* char * to an IP formatted string, so DO NOT USE MORE THAN ONCE PER LINE 70 | const char *FormatIP(const byte ip[4], char *buff, int buffLen) 71 | { 72 | snprintf_P(buff, buffLen, PSTR("%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]); 73 | return buff; 74 | } 75 | 76 | const char *FormatBool(bool b) 77 | { 78 | return b ? "True" : "False"; 79 | } 80 | 81 | 82 | 83 | void PrintSettings(WiFiClient *client) 84 | { 85 | char buff[16]; 86 | 87 | WebPrintf(client, "

WiFi Network

\n"); 88 | WebPrintf(client, "SSID: %s
\n", settings.ssid); 89 | WebPrintf(client, "PSK: %s
\n", settings.psk); 90 | WebPrintf(client, "Hostname: %s
\n", settings.hostname); 91 | WebPrintf(client, "DHCP: %s
\n", FormatBool(settings.useDHCP)); 92 | if (!settings.useDHCP) { 93 | WebPrintf(client, "IP: %s
\n", FormatIP(settings.ip, buff, sizeof(buff))); 94 | WebPrintf(client, "Gateway: %s
\n", FormatIP(settings.gateway, buff, sizeof(buff))); 95 | WebPrintf(client, "Netmask: %s
\n", FormatIP(settings.netmask, buff, sizeof(buff))); 96 | WebPrintf(client, "DNS: %s
\n", FormatIP(settings.dns, buff, sizeof(buff))); 97 | } 98 | WebPrintf(client, "UDP Log Server: %s:9911 (nc -l -u 9911)
\n", FormatIP(settings.logsvr, buff, sizeof(buff))); 99 | 100 | WebPrintf(client, "

Timekeeping

\n"); 101 | WebPrintf(client, "NTP: %s
\n", settings.ntp); 102 | WebPrintf(client, "Timezone: %s
\n", settings.timezone); 103 | WebPrintf(client, "12 hour time format: %s
\n", FormatBool(settings.use12hr)); 104 | WebPrintf(client, "DD/MM/YY date format: %s
\n", FormatBool(settings.usedmy)); 105 | 106 | WebPrintf(client, "

Power Settings

\n"); 107 | // WebPrintf(client, "System Voltage: %d
\n", settings.voltage); 108 | WebPrintf(client, "On after power failure: %s
\n", FormatBool(settings.onAfterPFail)); 109 | 110 | WebPrintf(client, "

MQTT

\n"); 111 | WebPrintf(client, "Enabled: %s
\n", FormatBool(settings.mqttEnable)); 112 | WebPrintf(client, "Host: %s
\n", settings.mqttHost); 113 | WebPrintf(client, "Port: %d
\n", settings.mqttPort); 114 | WebPrintf(client, "Use SSL: %s
\n", FormatBool(settings.mqttSSL)); 115 | WebPrintf(client, "ClientID: %s
\n", settings.mqttClientID); 116 | WebPrintf(client, "Topic: %s
\n", settings.mqttTopic); 117 | WebPrintf(client, "User: %s
\n", settings.mqttUser); 118 | WebPrintf(client, "Pass: %s
\n", settings.mqttPass); 119 | 120 | WebPrintf(client, "

Web UI

\n"); 121 | WebPrintf(client, "Admin User: %s
\n", settings.uiUser); 122 | WebPrintf(client, "Admin Pass: *HIDDEN*
\n"); 123 | } 124 | 125 | 126 | 127 | void MakeSSID(char *ssid, int len) 128 | { 129 | byte mac[6]; 130 | WiFi.macAddress(mac); 131 | snprintf_P(ssid, len, PSTR("PSYCHOPLUG-%02X%02X%02X"), mac[3], mac[4], mac[5]); 132 | } 133 | 134 | 135 | void StartSetupAP() 136 | { 137 | char ssid[32]; 138 | 139 | LogPrintf("Starting Setup AP Mode\n"); 140 | WiFi.mode(WIFI_AP); 141 | 142 | isSetup = false; 143 | MakeSSID(ssid, sizeof(ssid)); 144 | WiFi.softAPConfig(setupIP, setupIP, setupMask); 145 | WiFi.softAP(ssid); 146 | 147 | StartDNS(&setupIP); 148 | 149 | LogPrintf("Waiting for connection\n"); 150 | https.begin(); 151 | https.setNoDelay(true); 152 | redirector.begin(); 153 | redirector.setNoDelay(true); 154 | } 155 | 156 | void StartSTA() 157 | { 158 | LogPrintf("Starting STA Mode\n"); 159 | WiFi.mode(WIFI_STA); 160 | 161 | if (settings.hostname[0]) 162 | WiFi.hostname(settings.hostname); 163 | 164 | if (!settings.useDHCP) { 165 | WiFi.config(settings.ip, settings.gateway, settings.netmask, settings.dns); 166 | } else { 167 | //byte zero[] = {0,0,0,0}; 168 | //WiFi.config(zero, zero, zero, zero); 169 | // Above lines cause DHCP failure on 2.4-rc2. 170 | // TODO -ensure that w/o anything it will request a dynamic address 171 | } 172 | if (settings.psk[0]) WiFi.begin(settings.ssid, settings.psk); 173 | else WiFi.begin(settings.ssid); 174 | 175 | // Try forever 176 | while (WiFi.status() != WL_CONNECTED) { 177 | LogPrintf("Trying to connect to '%s' key '%s'\n", settings.ssid, settings.psk ); 178 | ManageLED(LED_CONNECTING); 179 | ManageButton(); 180 | delay(100); 181 | } 182 | 183 | if (WiFi.status() != WL_CONNECTED) { 184 | Reset(); // Punt, maybe we're in a weird way. Reboot and try it again 185 | } 186 | 187 | IPAddress ip = WiFi.localIP(); 188 | LogPrintf("IP:%d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]); 189 | 190 | StartMQTT(); 191 | 192 | // Start standard interface 193 | https.begin(); 194 | https.setNoDelay(true); 195 | redirector.begin(); 196 | redirector.setNoDelay(true); 197 | StartNTP(); 198 | StartLog(); 199 | 200 | SetTZ(settings.timezone); 201 | char atime[64]; 202 | LogPrintf("Local time is now: %s\n", AscTime(now(), settings.use12hr, settings.usedmy, atime, sizeof(atime))); 203 | } 204 | 205 | 206 | // Setup web page 207 | void SendSetupHTML(WiFiClient *client) 208 | { 209 | char buff[16]; 210 | 211 | LogPrintf("+SendSetupHTML\n"); 212 | WebHeaders(client, NULL); 213 | WebPrintf(client, DOCTYPE); 214 | WebPrintf(client, "PsychoPlug Setup" ENCODING "\n"); 215 | WebPrintf(client, "

PsychoPlug Setup

\n"); 216 | WebPrintf(client, "
\n"); 217 | 218 | WebPrintf(client, "

WiFi Network

\n"); 219 | WebFormText(client, PSTR("SSID"), "ssid", settings.ssid, true); 220 | int cnt = WiFi.scanNetworks(); 221 | if (cnt==0) { 222 | WebPrintf(client, "Discovered networks: No WIFI networks detected.
\n"); 223 | } else { 224 | WebPrintf(client, "Discovered networks:
\n"); 230 | WebPrintf(client, "\n"); 231 | } 232 | WebFormText(client, PSTR("Password"), "pass", settings.psk, true); 233 | WebFormText(client, PSTR("Hostname"), "hn", settings.hostname, true); 234 | const char *ary1[] = {"ip", "nm", "gw", "dns", ""}; 235 | WebFormCheckboxDisabler(client, PSTR("DHCP Networking"), "dh", false, settings.useDHCP, true, ary1 ); 236 | WebFormText(client, PSTR("IP"), "ip", FormatIP(settings.ip, buff, sizeof(buff)), !settings.useDHCP); 237 | WebFormText(client, PSTR("Netmask"), "nm", FormatIP(settings.netmask, buff, sizeof(buff)), !settings.useDHCP); 238 | WebFormText(client, PSTR("Gateway"), "gw", FormatIP(settings.gateway, buff, sizeof(buff)), !settings.useDHCP); 239 | WebFormText(client, PSTR("DNS"), "dns", FormatIP(settings.dns, buff, sizeof(buff)), !settings.useDHCP); 240 | WebFormText(client, PSTR("UDP Log Server"), "logsvr", FormatIP(settings.logsvr, buff, sizeof(buff)), true); 241 | delay(0); 242 | WebPrintf(client, "

Timekeeping

\n"); 243 | WebFormText(client, PSTR("NTP Server"), "ntp", settings.ntp, true); 244 | WebTimezonePicker(client, settings.timezone); 245 | WebFormCheckbox(client, PSTR("12hr Time Format"), "use12hr", settings.use12hr, true); 246 | WebFormCheckbox(client, PSTR("DD/MM/YY Date Format"), "usedmy", settings.usedmy, true); 247 | delay(0); 248 | WebPrintf(client, "

Power

\n"); 249 | //WebFormText(client, PSTR("Mains Voltage"), "voltage", settings.voltage, true); 250 | WebFormCheckbox(client, PSTR("Start powered up after power loss"), "pf", settings.onAfterPFail, true); 251 | 252 | WebPrintf(client, "

MQTT

\n"); 253 | const char *ary2[] = { "mhost", "mport", "mssl", "muser", "mpass", "mtopic", "mclientid", "" }; 254 | WebFormCheckboxDisabler(client, PSTR("Enable MQTT"), "mEn", true, settings.mqttEnable, true, ary2 ); 255 | WebFormText(client, PSTR("Host"), "mhost", settings.mqttHost, settings.mqttEnable); 256 | WebFormText(client, PSTR("Port"), "mport", settings.mqttPort, settings.mqttEnable); 257 | WebFormCheckbox(client, PSTR("Use SSL"), "mssl", settings.mqttSSL, settings.mqttEnable); 258 | WebFormText(client, PSTR("User"), "muser", settings.mqttUser, settings.mqttEnable); 259 | WebFormText(client, PSTR("Pass"), "mpass", settings.mqttPass, settings.mqttEnable); 260 | WebFormText(client, PSTR("ClientID"), "mclientid", settings.mqttClientID, settings.mqttEnable); 261 | WebFormText(client, PSTR("Topic"), "mtopic", settings.mqttTopic, settings.mqttEnable); 262 | 263 | WebPrintf(client, "

Web UI

\n"); 264 | WebFormText(client, PSTR("Admin User"), "uiuser", settings.uiUser, true); 265 | WebFormText(client, PSTR("Admin Password"), "uipass", "*****", true); 266 | 267 | WebPrintf(client, "\n"); 268 | WebPrintf(client, "
\n"); 269 | LogPrintf("-SendSetupHTML\n"); 270 | } 271 | 272 | 273 | // Status Web Page 274 | void SendStatusHTML(WiFiClient *client) 275 | { 276 | bool curPower = GetRelay(); 277 | char tmp[64]; 278 | 279 | WebHeaders(client, NULL); 280 | WebPrintf(client, DOCTYPE); 281 | WebPrintf(client, "%s Status" ENCODING "\n", settings.hostname); 282 | WebPrintf(client, "\n"); 283 | WebPrintf(client, "Hostname: %s
\n", settings.hostname); 284 | MakeSSID(tmp, sizeof(tmp)); 285 | WebPrintf(client, "SSID: %s
\n", tmp); 286 | WebPrintf(client, "Current Time: %s
\n", AscTime(now(), settings.use12hr, settings.usedmy, tmp, sizeof(tmp))); 287 | unsigned long ms = millis(); 288 | unsigned long days = ms / (24L * 60L * 60L * 1000L); 289 | ms -= days * (24L * 60L * 60L * 1000L); 290 | unsigned long hours = ms / (60L * 60L * 1000L); 291 | ms -= hours * (60L * 60L * 1000L); 292 | unsigned long mins = ms / (60L * 1000L); 293 | ms -= mins * (60L * 1000L); 294 | unsigned long secs = ms / (1000L); 295 | WebPrintf(client, "Uptime: %d days, %d hours, %d minutes, %d seconds
\n", days, hours, mins, secs); 296 | WebPrintf(client, "Power: %s Toggle

\n",curPower?"ON":"OFF", curPower?"off.html":"on.html"); 297 | // WebPrintf(client, "Current: %dmA (%dW @ %dV)
\n", GetCurrentMA(), (GetCurrentMA()* settings.voltage) / 1000, settings.voltage); 298 | 299 | WebPrintf(client, "\n"); 300 | WebPrintf(client, "\n"); 301 | char *buff = (char *)alloca(500); // By construction this will fit a row of the table 302 | for (byte i=0; i"), i+1); 305 | len += strlen(buff+len); 306 | for (byte j=0; j<7; j++) { 307 | sprintf_P(buff+len, PSTR(""), (settings.event[i].dayMask & (1<%d:%02d %s"), prthr, settings.event[i].minute, (settings.event[i].hour<12)?"AM":"PM"); 314 | len += strlen(buff+len); 315 | } else { 316 | sprintf_P(buff+len, PSTR(""), settings.event[i].hour, settings.event[i].minute); 317 | len += strlen(buff+len); 318 | } 319 | char str[16]; 320 | sprintf_P(buff+len, PSTR(""), GetActionString(settings.event[i].action, str, sizeof(str))); 321 | len += strlen(buff+len); 322 | sprintf_P(buff+len, PSTR("\r\n"), i); 323 | client->print(buff); 324 | } 325 | WebPrintf(client, "
#SunMonTueWedThuFriSatTimeActionEDIT
%d.%s%d:%02d%sEdit

\n"); 326 | WebPrintf(client, "Change System Configuration

\n"); 327 | 328 | WebPrintf(client, "CGI Action URLs: On Off Toggle Pulse Off "); 329 | WebPrintf(client, "Pulse On Status Reset
\n"); 330 | WebPrintf(client, "
\nEnable HTTP update of firmware for 10 minutes\n"); 331 | WebPrintf(client, "\n"); 332 | } 333 | 334 | // Edit Rule 335 | void SendEditHTML(WiFiClient *client, int id) 336 | { 337 | WebHeaders(client, NULL); 338 | WebPrintf(client, DOCTYPE); 339 | WebPrintf(client, "PsychoPlug Rule Edit" ENCODING "\n"); 340 | WebPrintf(client, "\n"); 341 | WebPrintf(client, "

Editing rule %d

\n", id+1); 342 | 343 | WebPrintf(client, "
\n"); 344 | WebPrintf(client, "\n", id); 345 | WebPrintf(client, "\n"); 346 | WebPrintf(client, "\n"); 347 | WebPrintf(client, "\n", id+1); 348 | WebPrintf(client, "\n"); 353 | for (byte j=0; j<7; j++) { 354 | WebPrintf(client, "\n", 'a'+j, 'a'+j, settings.event[id].dayMask & (1<: "); 377 | if (settings.use12hr) 378 | WebPrintf(client, "", settings.event[id].hour<12?"selected":"", settings.event[id].hour>=12?"selected":""); 379 | WebPrintf(client, "
#AllSunMonTueWedThuFriSatTimeAction
%d.\n

\n"); 383 | WebPrintf(client, "\n"); 384 | WebPrintf(client, "
\n"); 385 | } 386 | 387 | // Success page, auto-refresh in 1 sec to index 388 | void SendSuccessHTML(WiFiClient *client) 389 | { 390 | WebHeaders(client, PSTR("Refresh: 1; url=index.html\r\n")); 391 | WebPrintf(client, DOCTYPE); 392 | WebPrintf(client, "Success" ENCODING "

Success. Click here if not auto-refreshed

\n"); 393 | } 394 | 395 | 396 | void setup() 397 | { 398 | Serial.begin(115200); 399 | Serial.flush(); 400 | delay(100); 401 | LogPrintf("Starting up...\n"); 402 | delay(10); 403 | 404 | LogPrintf("Settings size=%d\n", sizeof(settings)); 405 | 406 | StartButton(); 407 | StartLED(); 408 | StartPowerMonitor(); 409 | 410 | LogPrintf("Loading Settings\n"); 411 | 412 | bool ok = LoadSettings(RawButton()); 413 | StartRelay(settings.onAfterPFail?true:false); 414 | 415 | // Load our certificate and key from FLASH before we start 416 | https.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509)); 417 | 418 | // Make sure ESP isn't doing any wifi operations. Sometimes starts back up in AP mode, for example 419 | WiFi.disconnect(); 420 | WiFi.softAPdisconnect(true); 421 | 422 | if (ok) { 423 | isSetup = true; 424 | StartSTA(); 425 | } else { 426 | isSetup = false; 427 | StartSetupAP(); 428 | } 429 | 430 | LogPrintf("End setup()\n"); 431 | } 432 | 433 | 434 | void ParseSetupForm(char *params) 435 | { 436 | char *valPtr; 437 | char *namePtr; 438 | 439 | // Checkboxes don't actually return values if they're unchecked, so by default these get false 440 | settings.useDHCP = false; 441 | settings.onAfterPFail = false; 442 | settings.mqttEnable = false; 443 | settings.mqttSSL = false; 444 | settings.use12hr = false; 445 | settings.usedmy = false; 446 | 447 | while (ParseParam(¶ms, &namePtr, &valPtr)) { 448 | ParamText("ssid", settings.ssid); 449 | ParamText("pass", settings.psk); 450 | ParamText("hn", settings.hostname); 451 | ParamCheckbox("dh", settings.useDHCP); 452 | Param4Int("ip", settings.ip); 453 | Param4Int("nm", settings.netmask); 454 | Param4Int("gw", settings.gateway); 455 | Param4Int("dns", settings.dns); 456 | Param4Int("logsvr", settings.logsvr); 457 | 458 | ParamText("ntp", settings.ntp); 459 | ParamText("tz", settings.timezone); 460 | ParamCheckbox("use12hr", settings.use12hr); 461 | ParamCheckbox("usedmy", settings.usedmy); 462 | 463 | ParamCheckbox("pf", settings.onAfterPFail); 464 | 465 | ParamCheckbox("mEn", settings.mqttEnable); 466 | ParamText("mhost", settings.mqttHost); 467 | ParamInt("mport", settings.mqttPort); 468 | // int v; 469 | // ParamInt("voltage", v); 470 | // if ((v<80) || (v>255)) v=120; // Sanity-check 471 | // settings.voltage = v; 472 | ParamCheckbox("mssl", settings.mqttSSL); 473 | ParamText("mtopic", settings.mqttTopic); 474 | ParamText("mclientid", settings.mqttClientID); 475 | ParamText("muser", settings.mqttUser); 476 | ParamText("mpass", settings.mqttPass); 477 | 478 | ParamText("uiuser", settings.uiUser); 479 | char tempPass[64]; 480 | ParamText("uipass", tempPass); 481 | if (strcmp_P(tempPass, PSTR("*****"))) { 482 | // Was changed, regenerate salt and store it 483 | HashPassword(tempPass, settings.uiSalt, settings.uiPassEnc); 484 | } 485 | memset(tempPass, 0, sizeof(tempPass)); // I think I'm paranoid 486 | } 487 | } 488 | 489 | void SendRebootHTML(WiFiClient *client) 490 | { 491 | WebHeaders(client, NULL); 492 | WebPrintf(client, DOCTYPE); 493 | WebPrintf(client, "Setting Configuration" ENCODING "\n"); 494 | WebPrintf(client, "

Setting Configuration

"); 495 | WebPrintf(client, "
\n"); 496 | PrintSettings(client); 497 | if (isSetup) WebPrintf(client, "

Click here to reconnect after 5 seconds.

\n") 498 | else WebPrintf(client, "

PsychoPlug will now reboot and connect to given network

"); 499 | WebPrintf(client, ""); 500 | } 501 | 502 | void SendResetHTML(WiFiClient *client) 503 | { 504 | WebHeaders(client, NULL); 505 | WebPrintf(client, DOCTYPE); 506 | WebPrintf(client, "Resetting PsychoPlug" ENCODING "\n"); 507 | WebPrintf(client, "

Resetting the plug, please manually reconnect in 5 seconds.

"); 508 | WebPrintf(client, ""); 509 | } 510 | 511 | void SendGoToConfigureHTTPS(WiFiClient *client) 512 | { 513 | LogPrintf("+SendGoToConfigureHTTPS\n"); 514 | WebHeaders(client, NULL); 515 | LogPrintf("SendGoToConfigureHTTPS: Sent headers\n"); 516 | WebPrintf(client, DOCTYPE); 517 | WebPrintf(client, "Configure PsychoPlug" ENCODING "\n"); 518 | WebPrintf(client, "

Go to configuration

", setupIP[0], setupIP[1], setupIP[2], setupIP[3]); 519 | WebPrintf(client, ""); 520 | } 521 | 522 | void Reset() 523 | { 524 | SaveSettings(); 525 | StopSettings(); 526 | 527 | // Will hang if you just did serial upload. Needs powercycle once after upload to function properly. 528 | ESP.restart(); 529 | 530 | // Should never hit here... 531 | delay(1000000); 532 | } 533 | 534 | 535 | void HandleConfigSubmit(WiFiClient *client, char *params) 536 | { 537 | ParseSetupForm(params); 538 | SaveSettings(); 539 | SendRebootHTML(client); 540 | Reset(); // Restarting safer than trying to change wifi/mqtt/etc. 541 | } 542 | 543 | void HandleUpdateSubmit(WiFiClient *client, char *params) 544 | { 545 | char *namePtr; 546 | char *valPtr; 547 | 548 | // Any of these not defined in the submit, error 549 | int id = -1; 550 | int hr = -1; 551 | int mn = -1; 552 | int ampm = -1; 553 | int action = -1; 554 | byte mask = 0; // Day bitmap 555 | while (ParseParam(¶ms, &namePtr, &valPtr)) { 556 | ParamInt("id", id); 557 | ParamInt("hr", hr); 558 | ParamInt("mn", mn); 559 | if (settings.use12hr) { 560 | if (!strcmp_P(namePtr, PSTR("ampm"))) { 561 | if (!strcmp_P(valPtr, PSTR("AM"))) ampm=0; 562 | else ampm=1; 563 | } 564 | } else { 565 | ampm = 0; 566 | } 567 | if (!strcmp_P(namePtr, PSTR("action"))) { 568 | char str[16]; 569 | for (int i=0; i<=ACTION_MAX; i++) 570 | if (!strcmp(valPtr, GetActionString(i, str, sizeof(str)))) action = i; 571 | } 572 | if (namePtr[0]>='a' && namePtr[0]<='g' && namePtr[1]==0) { 573 | if (!strcmp_P(valPtr, PSTR("on"))) mask |= 1<<(namePtr[0]-'a'); 574 | } 575 | } 576 | bool err = false; 577 | // Check settings are good 578 | if (id < 0 || id >= MAXEVENTS) err = true; 579 | if (settings.use12hr) { 580 | if (hr < 0 || hr > 12) err = true; 581 | } else { 582 | if (hr < 0 || hr > 23) err = true; 583 | } 584 | if (mn < 0 || mn >= 60) err = true; 585 | if (ampm < 0 || ampm > 1) err = true; 586 | if (action < 0 || action > ACTION_MAX ) err = true; 587 | 588 | if (hr==12 && ampm==0 && settings.use12hr) { hr = 0; } 589 | if (err) { 590 | WebError(client, 400, NULL); 591 | } else { 592 | // Update the entry, send refresh page to send back to index 593 | settings.event[id].dayMask = mask; 594 | settings.event[id].hour = hr + 12 * ampm; // !use12hr => ampm=0, so safe 595 | settings.event[id].minute = mn; 596 | settings.event[id].action = action; 597 | SaveSettings(); // Store in flash 598 | SendSuccessHTML(client); 599 | } 600 | } 601 | 602 | void HandleEditHTML(WiFiClient *client, char *params) 603 | { 604 | int id = -1; 605 | char *namePtr; 606 | char *valPtr; 607 | while (ParseParam(¶ms, &namePtr, &valPtr)) { 608 | ParamInt("id", id); 609 | } 610 | if (id >=0 && id < MAXEVENTS) { 611 | SendEditHTML(client, id); 612 | } else { 613 | WebError(client, 400, NULL); 614 | } 615 | } 616 | 617 | 618 | void SendOTARedirect(WiFiClient *client) 619 | { 620 | LogPrintf("+SendOTARedirect\n"); 621 | IPAddress ip = WiFi.localIP(); 622 | WebHeaders(client, NULL); 623 | WebPrintf(client, DOCTYPE); 624 | WebPrintf(client, "OTA Enabled" ENCODING "\n"); 625 | WebPrintf(client, "

Go to OTA page

", ip[0], ip[1], ip[2], ip[3]); 626 | WebPrintf(client, ""); 627 | } 628 | 629 | 630 | 631 | 632 | void loop() 633 | { 634 | static unsigned long lastMS = 0; 635 | static unsigned long killUpdateTime = 0; 636 | 637 | // Time to restart the plug if the update window is over 638 | if (killUpdateTime && (millis() > killUpdateTime) ) { 639 | LogPrintf("Restarting ESP due to update timeout\n"); 640 | ESP.restart(); 641 | } else if (otaServer) { 642 | otaServer->handleClient(); 643 | } 644 | 645 | if (lastMS>millis() || (millis()-lastMS)>5000) { 646 | lastMS = millis(); 647 | LogPrintf("@%d: ESP Heap Free=%d\n", lastMS, ESP.getFreeHeap()); 648 | } 649 | 650 | // Let the button toggle the relay always 651 | ManageButton(); 652 | 653 | // Blink the LED appropriate to the state 654 | ManageLED(isSetup ? LED_CONNECTED : LED_AWAITSETUP); 655 | 656 | // Pump DNS queue 657 | if (!isSetup) { 658 | ManageDNS(); 659 | } 660 | 661 | char *url; 662 | char *params; 663 | 664 | // Any HTTP request, send it to https:// on our IP 665 | WiFiClient redir = redirector.available(); 666 | if (redir) { 667 | LogPrintf("HTTP Redirector available\n"); 668 | if (WebReadRequest(&redir, &url, ¶ms, false)) { 669 | LogPrintf("HTTP Redirector request: %s\n", url); 670 | char newLoc[64]; 671 | if (isSetup) { 672 | IPAddress ip = WiFi.localIP(); 673 | snprintf_P(newLoc, sizeof(newLoc), PSTR("Location: https://%d.%d.%d.%d/%s"), ip[0], ip[1], ip[2], ip[3], url[0]?url:"index.html"); 674 | WebError(&redir, 301, newLoc, false); 675 | } else { 676 | if (!strcmp_P(url, PSTR("favicon.ico"))) { 677 | WebError(&redir, 404, NULL); 678 | } else if (!strcmp_P(url, PSTR("generate_204"))) { 679 | LogPrintf("Sending 301 redirector to https://<>/configure.html\n"); 680 | snprintf_P(newLoc, sizeof(newLoc), PSTR("Location: https://%d.%d.%d.%d/configure.html"), setupIP[0], setupIP[1], setupIP[2], setupIP[3]); 681 | WebError(&redir, 301, newLoc, false); 682 | } else { 683 | LogPrintf("Sending redirector web page listing config https link\n"); 684 | SendGoToConfigureHTTPS(&redir); 685 | LogPrintf("Sent\n"); 686 | } 687 | } 688 | redir.flush(); 689 | redir.stop(); 690 | LogPrintf("redir.stop()\n"); 691 | } 692 | } else if (!isSetup) { 693 | WiFiClientSecure client = https.available(); 694 | if (client) { 695 | LogPrintf("+HTTPS setup request\n"); 696 | if (WebReadRequest(&client, &url, ¶ms, false)) { 697 | Serial.printf("url: '%s'\n", url); 698 | if (IsIndexHTML(url) || !strcmp_P(url, PSTR("configure.html"))) { 699 | SendSetupHTML(&client); 700 | } else if (!strcmp_P(url, PSTR("config.html")) && *params) { 701 | HandleConfigSubmit(&client, params); 702 | } else { 703 | WebError(&client, 404, NULL); 704 | } 705 | } 706 | client.flush(); 707 | client.stop(); 708 | LogPrintf("-HTTPS setup request\n"); 709 | } 710 | } else { 711 | if (!otaServer) ManageMQTT(); 712 | ManageSchedule(); 713 | ManagePowerMonitor(); 714 | 715 | WiFiClientSecure client = https.available(); 716 | if (client) { 717 | StopMQTT(); // 718 | if (WebReadRequest(&client, &url, ¶ms, true, settings.uiUser, settings.uiSalt, settings.uiPassEnc)) { 719 | if (IsIndexHTML(url)) { 720 | SendStatusHTML(&client); 721 | } else if (!strcmp_P(url, PSTR("on.html"))) { 722 | PerformAction(ACTION_ON); 723 | SendSuccessHTML(&client); 724 | } else if (!strcmp_P(url, PSTR("off.html"))) { 725 | PerformAction(ACTION_OFF); 726 | SendSuccessHTML(&client); 727 | } else if (!strcmp_P(url, PSTR("toggle.html"))) { 728 | PerformAction(ACTION_TOGGLE); 729 | SendSuccessHTML(&client); 730 | } else if (!strcmp_P(url, PSTR("pulseoff.html"))) { 731 | PerformAction(ACTION_PULSEOFF); 732 | SendSuccessHTML(&client); 733 | } else if (!strcmp_P(url, PSTR("pulseon.html"))) { 734 | PerformAction(ACTION_PULSEON); 735 | SendSuccessHTML(&client); 736 | } else if (!strcmp_P(url, PSTR("status.html"))) { 737 | WebPrintf(&client, "%d", GetRelay()?1:0); 738 | } else if (!strcmp_P(url, PSTR("hang.html"))) { 739 | SendResetHTML(&client); 740 | Reset(); // Restarting safer than trying to change wifi/mqtt/etc. 741 | } else if (!strcmp_P(url, PSTR("edit.html")) && *params) { 742 | HandleEditHTML(&client, params); 743 | } else if (!strcmp_P(url, PSTR("update.html")) && *params) { 744 | HandleUpdateSubmit(&client, params); 745 | } else if (!strcmp_P(url, PSTR("reconfig.html"))) { 746 | SendSetupHTML(&client); 747 | } else if (!strcmp_P(url, PSTR("config.html")) && *params) { 748 | HandleConfigSubmit(&client, params); 749 | } else if (!strcmp_P(url, PSTR("enableupdate.html"))) { 750 | StopMQTT(); 751 | otaUpdateServer = new ESP8266HTTPUpdateServer; 752 | otaServer = new ESP8266WebServer(8080); 753 | otaUpdateServer->setup(otaServer); 754 | otaServer->begin(); 755 | killUpdateTime = millis() + 10*60*1000; // now + 10 mins 756 | SendOTARedirect(&client); 757 | } else { 758 | WebError(&client, 404, NULL); 759 | } 760 | } 761 | client.flush(); 762 | client.stop(); 763 | } 764 | } 765 | } 766 | -------------------------------------------------------------------------------- /relay.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include "relay.h" 23 | #include "mqtt.h" 24 | #include "log.h" 25 | 26 | #define PIN_RELAY (15) 27 | 28 | 29 | // Initializes relay control pins (relay state undefined) 30 | void StartRelay(bool state) 31 | { 32 | SetRelay(state); 33 | pinMode(PIN_RELAY, OUTPUT); 34 | } 35 | 36 | // Sets the relay on or off and handles any logging required 37 | void SetRelay(bool on) 38 | { 39 | digitalWrite(PIN_RELAY, on ? HIGH:LOW ); 40 | MQTTPublishInt("powerstate", on ? 1 : 0); 41 | } 42 | 43 | // Returns relay state 44 | bool GetRelay() 45 | { 46 | return digitalRead(PIN_RELAY)==LOW?false:true; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /relay.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _relay_h 22 | #define _relay_h 23 | 24 | // Initializes relay control pins (relay state undefined) 25 | void StartRelay(bool state); 26 | 27 | // Sets the relay on or off and handles any logging required 28 | void SetRelay(bool on); 29 | 30 | // Returns current state of relay 31 | bool GetRelay(); 32 | 33 | #endif 34 | 35 | -------------------------------------------------------------------------------- /schedule.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include "psychoplug.h" 24 | #include "schedule.h" 25 | #include "settings.h" 26 | #include "mqtt.h" 27 | #include "relay.h" 28 | #include "timezone.h" 29 | 30 | 31 | char *GetActionString(int idx, char *str, int len) { 32 | switch (idx) { 33 | case 0 : strncpy_P(str, PSTR("None"), len); break; 34 | case 1 : strncpy_P(str, PSTR("On"), len); break; 35 | case 2 : strncpy_P(str, PSTR("Off"), len); break; 36 | case 3 : strncpy_P(str, PSTR("Toggle"), len); break; 37 | case 4 : strncpy_P(str, PSTR("Pulse Off"), len); break; 38 | case 5 : strncpy_P(str, PSTR("Pulse On"), len); break; 39 | default: strncpy_P(str, PSTR("Invalid"), len); break; 40 | } 41 | return str; 42 | } 43 | 44 | void PerformAction(int action) 45 | { 46 | if (action != ACTION_NONE) { 47 | char str[16]; 48 | MQTTPublish("event", GetActionString(action, str, sizeof(str))); 49 | } 50 | 51 | switch (action) { 52 | case ACTION_NONE: break; 53 | case ACTION_ON: SetRelay(true); break; 54 | case ACTION_OFF: SetRelay(false); break; 55 | case ACTION_TOGGLE: SetRelay(!GetRelay()); break; 56 | case ACTION_PULSEOFF: SetRelay(false); delay(2000); SetRelay(true); break; 57 | case ACTION_PULSEON: SetRelay(true); delay(2000); SetRelay(false); break; 58 | } 59 | 60 | } 61 | 62 | 63 | // Handle automated on/off simply on the assumption we don't lose any minutes 64 | static char lastHour = 25; 65 | static char lastMin = -1; 66 | static char lastDOW = -1; 67 | void ManageSchedule() 68 | { 69 | // Can't run schedule if we don't know what the time is! 70 | if (timeStatus() == timeNotSet) return; 71 | 72 | // Sane startup time values 73 | if (lastHour == 25) { 74 | time_t t = LocalTime(now()); 75 | lastHour = hour(t); 76 | lastMin = minute(t); 77 | lastDOW = weekday(t) - 1; // We 0-index, weekday() 1-indexes 78 | } 79 | 80 | // If this is a new h/m/dow then go through all events and see if we need to do an action. 81 | // Only execute after we scan everything, so only last action done once even if there are 82 | // multiple entries for the same time or multiple times scanned. 83 | 84 | time_t t = LocalTime(now()); 85 | int newHour = hour(t); 86 | int newMin = minute(t); 87 | int newDOW = weekday(t)-1; 88 | if (newHour != lastHour || newMin != lastMin || newDOW != lastDOW) { 89 | int action = ACTION_NONE; 90 | // This *should* be fast unless we lose a day somewhere (NTP problems?) 91 | while (newHour != lastHour || newMin != lastMin || newDOW != lastDOW) { 92 | lastMin++; 93 | if (lastMin==60) { lastHour++; lastMin = 0; } 94 | if (lastHour==24) { delay(1); /* allow ctx switch */ lastDOW++; lastHour = 0; } 95 | if (lastDOW==7) lastDOW = 0; // Sat->Sun 96 | for (int i=0; i. 19 | */ 20 | 21 | #ifndef _schedule_h 22 | #define _schedule_h 23 | 24 | #include 25 | 26 | // Maximum # of events to operate upon 27 | #define MAXEVENTS (24) 28 | 29 | typedef struct { 30 | byte dayMask; // binary flags per-day 31 | byte hour; 32 | byte minute; 33 | byte action; 34 | } Event; 35 | 36 | #define ACTION_NONE (0) 37 | #define ACTION_ON (1) 38 | #define ACTION_OFF (2) 39 | #define ACTION_TOGGLE (3) 40 | #define ACTION_PULSEOFF (4) 41 | #define ACTION_PULSEON (5) 42 | #define ACTION_MAX (5) 43 | extern char *GetActionString(int idx, char *str, int len); 44 | extern void PerformAction(int action); 45 | 46 | 47 | // Handle scheduled operations 48 | void ManageSchedule(); 49 | void StopSchedule(); 50 | 51 | #endif 52 | 53 | -------------------------------------------------------------------------------- /schedule.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/earlephilhower/psychoplug/11ebfc7b54f0107efb3587451b26c9e827e6ca90/schedule.png -------------------------------------------------------------------------------- /settings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include "settings.h" 24 | #include "password.h" 25 | #include "log.h" 26 | 27 | static byte CalcSettingsChecksum(); 28 | 29 | Settings settings; 30 | 31 | 32 | void StartSettings() 33 | { 34 | EEPROM.begin(sizeof(settings)+2); 35 | } 36 | 37 | void StopSettings() 38 | { 39 | EEPROM.commit(); 40 | EEPROM.end(); 41 | } 42 | 43 | bool LoadSettings(bool reset) 44 | { 45 | bool ok = false; 46 | 47 | StartSettings(); 48 | 49 | // Try and read from "EEPROM", if that fails use defaults 50 | byte *p = (byte *)&settings; 51 | for (unsigned int i=0; i. 19 | */ 20 | 21 | #ifndef _settings_h 22 | #define _settings_h 23 | 24 | #include 25 | #include "password.h" 26 | #include "schedule.h" 27 | 28 | #define SETTINGSVERSION (2) 29 | 30 | typedef struct { 31 | byte version; 32 | char ssid[32]; 33 | char psk[32]; 34 | char hostname[32]; 35 | bool useDHCP; 36 | byte ip[4]; 37 | byte dns[4]; 38 | byte gateway[4]; 39 | byte netmask[4]; 40 | byte logsvr[4]; 41 | char ntp[48]; 42 | bool use12hr; 43 | bool usedmy; 44 | char timezone[32]; 45 | 46 | bool onAfterPFail; 47 | // byte voltage; 48 | 49 | // MQTT Configuration 50 | bool mqttEnable; 51 | char mqttHost[48]; 52 | int mqttPort; 53 | bool mqttSSL; 54 | char mqttClientID[32]; 55 | char mqttTopic[32]; 56 | char mqttUser[32]; 57 | char mqttPass[32]; 58 | 59 | // Web Interface 60 | char uiUser[32]; 61 | char uiPassEnc[PASSENCLEN]; 62 | char uiSalt[SALTLEN]; 63 | 64 | // Events to process 65 | Event event[MAXEVENTS]; 66 | } Settings; 67 | extern Settings settings; 68 | 69 | void StartSettings(); 70 | bool LoadSettings(bool reset); 71 | void SaveSettings(); 72 | void StopSettings(); 73 | 74 | #endif 75 | 76 | -------------------------------------------------------------------------------- /setup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/earlephilhower/psychoplug/11ebfc7b54f0107efb3587451b26c9e827e6ca90/setup.png -------------------------------------------------------------------------------- /timezone.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef TEST_TIMEZONE 22 | #include 23 | #include 24 | #include "timezone.h" 25 | #include "log.h" 26 | 27 | #include "tz.h" 28 | /* 29 | typedef struct tm { 30 | uint8_t tm_sec; 31 | uint8_t tm_min; 32 | uint8_t tm_hour; 33 | uint8_t tm_wday; 34 | uint8_t tm_mday; 35 | uint8_t tm_mon; 36 | uint16_t tm_year; 37 | uint8_t tm_isdst; 38 | } tm; 39 | */ 40 | 41 | time_t mktime(struct tm *tm) 42 | { 43 | tmElements_t tme; 44 | tme.Second = tm->tm_sec; 45 | tme.Minute = tm->tm_min; 46 | tme.Hour = tm->tm_hour; 47 | tme.Wday = tm->tm_wday+1; // day of week, sunday is day 1 48 | tme.Day = tm->tm_mday; 49 | tme.Month = tm->tm_mon+1; // Jan = 1 in tme, 0 in tm 50 | tme.Year = (uint8_t)(tm->tm_year - 70); // offset from 1970; 51 | time_t t = makeTime(tme); // convert time elements into time_t 52 | return t; 53 | 54 | } 55 | 56 | struct tm *gmtime_r(const time_t *timep, struct tm *tm) 57 | { 58 | tmElements_t tme; 59 | breakTime(*timep, tme); // break time_t into elements 60 | tm->tm_sec = tme.Second; 61 | tm->tm_min = tme.Minute; 62 | tm->tm_hour = tme.Hour; 63 | tm->tm_wday = tme.Wday-1; // Sun=0 in tm, 1 in tme 64 | tm->tm_mday = tme.Day; 65 | tm->tm_mon = tme.Month-1; // Jan=0 in tm, 1 in tme 66 | tm->tm_year = tme.Year + 70; // 0=1900 in tm, 1970 in tme 67 | return tm; 68 | } 69 | 70 | #else 71 | #include 72 | #include 73 | #include 74 | #include 75 | #include 76 | 77 | #define ICACHE_RODATA_ATTR 78 | #define PSTR 79 | #include "tz.h" 80 | 81 | #define memcpy_P memcpy 82 | #define snprintf_P snprintf 83 | #define strlcpy strncpy 84 | #define strncpy_P strncpy 85 | #define LogPrintf printf 86 | #define SECS_PER_MIN (60) 87 | #define SECS_PER_HOUR (60*60) 88 | #define SECS_PER_DAY (60*60*24) 89 | #endif 90 | 91 | 92 | char *GetNextTZ(bool reset, char *buff, char buffLen) 93 | { 94 | static uint16_t idxTZ = 0; 95 | static uint16_t idxLink = 0; 96 | if (reset) { 97 | idxLink = 0; 98 | idxTZ = 0; 99 | } 100 | 101 | const int tzcount = sizeof(mtimezone)/sizeof(mtimezone[0]); 102 | const int linkcount = sizeof(link)/sizeof(link[0]); 103 | if (idxTZ < tzcount) { 104 | timezone_t l; 105 | memcpy_P(&l, &mtimezone[idxTZ], sizeof(l)); 106 | strlcpy(buff + l.zoneNameFromPrev,l.zonename, buffLen - l.zoneNameFromPrev); 107 | idxTZ++; 108 | return buff; 109 | } else if (idxLink < linkcount) { 110 | link_t l; 111 | memcpy_P(&l, &link[idxLink], sizeof(l)); 112 | strlcpy(buff + l.zoneNameFromPrev, l.zonename, buffLen - l.zoneNameFromPrev); 113 | idxLink++; 114 | return buff; 115 | } else { 116 | return NULL; 117 | } 118 | } 119 | 120 | int FindTZName(const char *tzname) 121 | { 122 | char buff[64]; 123 | const int tzcount = sizeof(mtimezone)/sizeof(mtimezone[0]); 124 | const int linkcount = sizeof(link)/sizeof(link[0]); 125 | for (int i=0; i < tzcount; i++) { 126 | timezone_t l; 127 | memcpy_P(&l, &mtimezone[i], sizeof(l)); 128 | strlcpy(buff + l.zoneNameFromPrev, l.zonename, sizeof(buff) - l.zoneNameFromPrev); 129 | if (!strcmp(buff, tzname)) return i; 130 | } 131 | for (int i=0; i < linkcount; i++) { 132 | link_t l; 133 | memcpy_P(&l, &link[i], sizeof(l)); 134 | strlcpy(buff + l.zoneNameFromPrev, l.zonename, sizeof(buff) - l.zoneNameFromPrev); 135 | if (!strcmp(buff, tzname)) return link[i].timezone; 136 | } 137 | return -1; 138 | } 139 | 140 | static timezone_t myTimezone; // Which timezone are we in? 141 | static time_t utcOffsetSecs = 0; // Unadjusted UTC offset 142 | static bool useDSTRule = false; // Does the current TZ need DST handling? 143 | static uint16_t dstYear = 1900; // What year the cached computations below are falid for 144 | static time_t dstChangeAtUTC[2]; // UTC time when the offset below takes effect 145 | static time_t dstOffsetSecs[2]; // Delta from default UTC offset to apply 146 | static char timezoneStr[16]; // Human readable string w/format specifiers for DST/non-DST 147 | static char dstString[2][4]; // Format specifier replacement 148 | 149 | void UpdateDSTInfo(time_t whenUTC) 150 | { 151 | const int ruleCount = sizeof(rules)/sizeof(rules[0]); 152 | rule_t dstRule[2]; 153 | struct tm t; 154 | int ruleIdx; 155 | 156 | LogPrintf("+UpdateDSTInfo(%ld)\n", (long)whenUTC); 157 | 158 | ruleIdx = 0; 159 | for (int i=0; i= dstChangeAtUTC[0]) && (whenUTC < dstChangeAtUTC[1])) { 334 | // At 1st DST change 335 | return whenUTC + utcOffsetSecs + dstOffsetSecs[0]; 336 | } else { 337 | // After 2nd change or before 1st 338 | return whenUTC + utcOffsetSecs + dstOffsetSecs[1]; 339 | } 340 | } 341 | 342 | static char *Weekday(int wd, char *dest, int len) 343 | { 344 | switch (wd) { 345 | case 1: strncpy_P(dest, PSTR("Sunday"), len); break; 346 | case 2: strncpy_P(dest, PSTR("Monday"), len); break; 347 | case 3: strncpy_P(dest, PSTR("Tuesday"), len); break; 348 | case 4: strncpy_P(dest, PSTR("Wednesday"), len); break; 349 | case 5: strncpy_P(dest, PSTR("Thursday"), len); break; 350 | case 6: strncpy_P(dest, PSTR("Friday"), len); break; 351 | case 7: strncpy_P(dest, PSTR("Saturday"), len); break; 352 | } 353 | return dest; 354 | } 355 | 356 | char *AscTime(time_t whenUTC, bool use12Hr, bool useDMY, char *buff, int buffLen) 357 | { 358 | time_t t = LocalTime(whenUTC); 359 | 360 | char tzID[16]; 361 | if (!useDSTRule) { 362 | // Just replace any string with "S" for standard 363 | snprintf(tzID, sizeof(tzID), timezoneStr, "S"); 364 | } else if ((whenUTC >= dstChangeAtUTC[0]) && (whenUTC < dstChangeAtUTC[1])) { 365 | // At 1st DST change 366 | snprintf(tzID, sizeof(tzID), timezoneStr, dstString[0]); 367 | } else { 368 | // After 2nd change or before 1st 369 | snprintf(tzID, sizeof(tzID), timezoneStr, dstString[1]); 370 | } 371 | 372 | #ifdef TEST_TIMEZONE 373 | struct tm q; 374 | gmtime_r(&t, &q); 375 | int h = q.tm_hour; 376 | int m = q.tm_min; 377 | int s = q.tm_sec; 378 | int wd = q.tm_wday+1; 379 | int mn = q.tm_mon+1; 380 | int dy = q.tm_mday; 381 | int yr = q.tm_year; 382 | #else 383 | int h = hour(t); 384 | int m = minute(t); 385 | int s = second(t); 386 | int wd = weekday(t); 387 | int mn = month(t); 388 | int dy = day(t); 389 | int yr = year(t); 390 | #endif 391 | 392 | const char *ampm = ""; 393 | if (use12Hr) { 394 | if (h==0) { h = 12; ampm = "AM"; } 395 | else if (h==12) { ampm = "PM"; } 396 | else if (h<12) { ampm = "AM"; } 397 | else { h -= 12; ampm = "PM"; } 398 | } 399 | char wdName[16]; 400 | snprintf_P(buff, buffLen, PSTR("%2d:%02d:%02d%s %s, %s %d/%d/%d"), h, m, s, ampm, tzID, Weekday(wd, wdName, sizeof(wdName)), useDMY?dy:mn, useDMY?mn:dy, yr); 401 | 402 | return buff; 403 | } 404 | 405 | 406 | #ifdef TEST_TIMEZONE 407 | int main(int argc, const char *argv[]) 408 | { 409 | setenv("TZ", "", 1); 410 | if (argc<2) { printf("Please enter a timezone parameter\n"); exit(1); } 411 | SetTZ(argv[1]); 412 | 413 | time_t now; 414 | time(&now); 415 | now -= SECS_PER_DAY; 416 | for (int i =0; i<365; i++) { 417 | for (int j=0; j<24; j++) { 418 | for (int k=0; k<60; k++) { 419 | time_t local = LocalTime(now); 420 | struct tm t; 421 | memcpy(&t, gmtime(&local), sizeof(t)); 422 | // printf("%d/%02d/%d @ %d:%02d\n", t.tm_mon+1, t.tm_mday, t.tm_year+1900, t.tm_hour, t.tm_min); 423 | char b[128]; 424 | printf("%s\n", AscTime(local, true, false, b, 128)); 425 | now += SECS_PER_MIN; 426 | } 427 | } 428 | } 429 | return 0; 430 | } 431 | #endif 432 | -------------------------------------------------------------------------------- /timezone.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _timezone_h 22 | #define _timezone_h 23 | 24 | #include 25 | 26 | extern char *GetNextTZ(bool reset, char *buff, char buffLen); 27 | extern time_t LocalTime(time_t whenUTC); 28 | extern bool SetTZ(const char *tzName); 29 | extern char *AscTime(time_t whenUTC, bool use12hr, bool usrDMY, char *buff, int buffLen); 30 | #endif 31 | -------------------------------------------------------------------------------- /tz.h: -------------------------------------------------------------------------------- 1 | #define MON_JAN (0) 2 | #define MON_FEB (1) 3 | #define MON_MAR (2) 4 | #define MON_APR (3) 5 | #define MON_MAY (4) 6 | #define MON_JUN (5) 7 | #define MON_JUL (6) 8 | #define MON_AUG (7) 9 | #define MON_SEP (8) 10 | #define MON_OCT (9) 11 | #define MON_NOV (10) 12 | #define MON_DEC (11) 13 | #define MON_GTEQ (0) 14 | #define FRI_GTEQ (1) 15 | #define WED_GTEQ (2) 16 | #define TUE_LAST (3) 17 | #define MON_LAST (4) 18 | #define SAT_GTEQ (5) 19 | #define SUN_GTEQ (6) 20 | #define SAT_LAST (7) 21 | #define GIVEN_DAY (8) 22 | #define SUN_LAST (9) 23 | #define FRI_LAST (10) 24 | #define THU_LAST (11) 25 | #define TUE_GTEQ (12) 26 | #define THU_GTEQ (13) 27 | #define WED_LAST (14) 28 | #define ATREF_U (0) 29 | #define ATREF_W (1) 30 | #define ATREF_S (2) 31 | #define RULE_Thule (0) 32 | #define RULE_E_EurAsia (1) 33 | #define RULE_EU (2) 34 | #define RULE_Palestine (3) 35 | #define RULE_Syria (4) 36 | #define RULE_Troll (5) 37 | #define RULE_Cuba (6) 38 | #define RULE_LH (7) 39 | #define RULE_NONE (8) 40 | #define RULE_Moldova (9) 41 | #define RULE_Chatham (10) 42 | #define RULE_Brazil (11) 43 | #define RULE_Zion (12) 44 | #define RULE_AV (13) 45 | #define RULE_Para (14) 46 | #define RULE_AS (15) 47 | #define RULE_EUAsia (16) 48 | #define RULE_Tonga (17) 49 | #define RULE_Jordan (18) 50 | #define RULE_C_Eur (19) 51 | #define RULE_Lebanon (20) 52 | #define RULE_AT (21) 53 | #define RULE_Fiji (22) 54 | #define RULE_NZ (23) 55 | #define RULE_US (24) 56 | #define RULE_E_Eur (25) 57 | #define RULE_Chile (26) 58 | #define RULE_Namibia (27) 59 | #define RULE_WS (28) 60 | #define RULE_Mexico (29) 61 | #define RULE_W_Eur (30) 62 | #define RULE_Morocco (31) 63 | #define RULE_AN (32) 64 | #define RULE_Canada (33) 65 | 66 | typedef struct { 67 | uint8_t name : 6; // Empirical 68 | uint8_t month : 4; // 0...11 69 | uint8_t daytrig : 4; // 0...14 70 | uint8_t daynum : 5; // 0...31 71 | uint8_t athr : 4; // 0..11 72 | uint8_t atmin : 6; // 0..59 73 | uint8_t atref : 2; // 0..2 74 | uint8_t offsethrs : 2; // 0..2 75 | uint8_t offsetmins : 6; // 0..59 76 | char fmtstr[4]; // Empirical, longest is >> average 77 | } rule_t; 78 | static const rule_t rules[] ICACHE_RODATA_ATTR = { 79 | {RULE_AN, MON_APR, SUN_GTEQ, 1, 2, 0, ATREF_S, 0, 0, "S"}, 80 | {RULE_AN, MON_OCT, SUN_GTEQ, 1, 2, 0, ATREF_S, 1, 0, "D"}, 81 | {RULE_AS, MON_APR, SUN_GTEQ, 1, 2, 0, ATREF_S, 0, 0, "S"}, 82 | {RULE_AS, MON_OCT, SUN_GTEQ, 1, 2, 0, ATREF_S, 1, 0, "D"}, 83 | {RULE_AT, MON_APR, SUN_GTEQ, 1, 2, 0, ATREF_S, 0, 0, "S"}, 84 | {RULE_AT, MON_OCT, SUN_GTEQ, 1, 2, 0, ATREF_S, 1, 0, "D"}, 85 | {RULE_AV, MON_APR, SUN_GTEQ, 1, 2, 0, ATREF_S, 0, 0, "S"}, 86 | {RULE_AV, MON_OCT, SUN_GTEQ, 1, 2, 0, ATREF_S, 1, 0, "D"}, 87 | {RULE_Brazil, MON_OCT, SUN_GTEQ, 15, 0, 0, ATREF_W, 1, 0, "S"}, 88 | {RULE_C_Eur, MON_MAR, SUN_LAST, 0, 2, 0, ATREF_S, 1, 0, "S"}, 89 | {RULE_C_Eur, MON_OCT, SUN_LAST, 0, 2, 0, ATREF_S, 0, 0, ""}, 90 | {RULE_Canada, MON_MAR, SUN_GTEQ, 8, 2, 0, ATREF_W, 1, 0, "D"}, 91 | {RULE_Canada, MON_NOV, SUN_GTEQ, 1, 2, 0, ATREF_W, 0, 0, "S"}, 92 | {RULE_Chatham, MON_APR, SUN_GTEQ, 1, 2, 45, ATREF_S, 0, 0, "S"}, 93 | {RULE_Chatham, MON_SEP, SUN_LAST, 0, 2, 45, ATREF_S, 1, 0, "D"}, 94 | {RULE_Chile, MON_AUG, SUN_GTEQ, 9, 4, 0, ATREF_U, 1, 0, "S"}, 95 | {RULE_Chile, MON_MAY, SUN_GTEQ, 9, 3, 0, ATREF_U, 0, 0, ""}, 96 | {RULE_Cuba, MON_MAR, SUN_GTEQ, 8, 0, 0, ATREF_S, 1, 0, "D"}, 97 | {RULE_Cuba, MON_NOV, SUN_GTEQ, 1, 0, 0, ATREF_S, 0, 0, "S"}, 98 | {RULE_EU, MON_MAR, SUN_LAST, 0, 1, 0, ATREF_U, 1, 0, "S"}, 99 | {RULE_EU, MON_OCT, SUN_LAST, 0, 1, 0, ATREF_U, 0, 0, ""}, 100 | {RULE_EUAsia, MON_MAR, SUN_LAST, 0, 1, 0, ATREF_U, 1, 0, "S"}, 101 | {RULE_EUAsia, MON_OCT, SUN_LAST, 0, 1, 0, ATREF_U, 0, 0, ""}, 102 | {RULE_E_Eur, MON_MAR, SUN_LAST, 0, 0, 0, ATREF_W, 1, 0, "S"}, 103 | {RULE_E_Eur, MON_OCT, SUN_LAST, 0, 0, 0, ATREF_W, 0, 0, ""}, 104 | {RULE_E_EurAsia, MON_MAR, SUN_LAST, 0, 0, 0, ATREF_W, 1, 0, "S"}, 105 | {RULE_E_EurAsia, MON_OCT, SUN_LAST, 0, 0, 0, ATREF_W, 0, 0, ""}, 106 | {RULE_Fiji, MON_JAN, SUN_GTEQ, 15, 3, 0, ATREF_W, 0, 0, ""}, 107 | {RULE_Fiji, MON_NOV, SUN_GTEQ, 1, 2, 0, ATREF_W, 1, 0, "S"}, 108 | {RULE_Jordan, MON_MAR, THU_LAST, 0, 0, 59, ATREF_W, 1, 0, "S"}, 109 | {RULE_Jordan, MON_OCT, FRI_LAST, 0, 0, 0, ATREF_S, 0, 0, ""}, 110 | {RULE_LH, MON_APR, SUN_GTEQ, 1, 2, 0, ATREF_W, 0, 0, "S"}, 111 | {RULE_LH, MON_OCT, SUN_GTEQ, 1, 2, 0, ATREF_W, 0, 30, "D"}, 112 | {RULE_Lebanon, MON_MAR, SUN_LAST, 0, 0, 0, ATREF_W, 1, 0, "S"}, 113 | {RULE_Lebanon, MON_OCT, SUN_LAST, 0, 0, 0, ATREF_W, 0, 0, ""}, 114 | {RULE_Mexico, MON_APR, SUN_GTEQ, 1, 2, 0, ATREF_W, 1, 0, "D"}, 115 | {RULE_Mexico, MON_OCT, SUN_LAST, 0, 2, 0, ATREF_W, 0, 0, "S"}, 116 | {RULE_Moldova, MON_MAR, SUN_LAST, 0, 2, 0, ATREF_W, 1, 0, "S"}, 117 | {RULE_Moldova, MON_OCT, SUN_LAST, 0, 3, 0, ATREF_W, 0, 0, ""}, 118 | {RULE_Morocco, MON_JUL, GIVEN_DAY, 2, 2, 0, ATREF_W, 1, 0, "S"}, 119 | {RULE_Morocco, MON_MAY, GIVEN_DAY, 21, 3, 0, ATREF_W, 0, 0, ""}, 120 | {RULE_NZ, MON_APR, SUN_GTEQ, 1, 2, 0, ATREF_S, 0, 0, "S"}, 121 | {RULE_NZ, MON_SEP, SUN_LAST, 0, 2, 0, ATREF_S, 1, 0, "D"}, 122 | {RULE_Namibia, MON_APR, SUN_GTEQ, 1, 2, 0, ATREF_W, 0, 0, ""}, 123 | {RULE_Namibia, MON_SEP, SUN_GTEQ, 1, 2, 0, ATREF_W, 1, 0, "S"}, 124 | {RULE_Palestine, MON_MAR, SAT_LAST, 0, 1, 0, ATREF_W, 1, 0, "S"}, 125 | {RULE_Palestine, MON_OCT, SAT_LAST, 0, 1, 0, ATREF_W, 0, 0, ""}, 126 | {RULE_Para, MON_MAR, SUN_GTEQ, 22, 0, 0, ATREF_W, 0, 0, ""}, 127 | {RULE_Para, MON_OCT, SUN_GTEQ, 1, 0, 0, ATREF_W, 1, 0, "S"}, 128 | {RULE_Syria, MON_MAR, FRI_LAST, 0, 0, 0, ATREF_W, 1, 0, "S"}, 129 | {RULE_Syria, MON_OCT, FRI_LAST, 0, 0, 0, ATREF_W, 0, 0, ""}, 130 | {RULE_Thule, MON_MAR, SUN_GTEQ, 8, 2, 0, ATREF_W, 1, 0, "D"}, 131 | {RULE_Thule, MON_NOV, SUN_GTEQ, 1, 2, 0, ATREF_W, 0, 0, "S"}, 132 | {RULE_Tonga, MON_JAN, SUN_GTEQ, 15, 3, 0, ATREF_W, 0, 0, ""}, 133 | {RULE_Tonga, MON_NOV, SUN_GTEQ, 1, 2, 0, ATREF_W, 1, 0, "S"}, 134 | {RULE_Troll, MON_MAR, SUN_LAST, 0, 1, 0, ATREF_U, 2, 0, "+02"}, 135 | {RULE_Troll, MON_OCT, SUN_LAST, 0, 1, 0, ATREF_U, 0, 0, "+00"}, 136 | {RULE_US, MON_MAR, SUN_GTEQ, 8, 2, 0, ATREF_W, 1, 0, "D"}, 137 | {RULE_US, MON_NOV, SUN_GTEQ, 1, 2, 0, ATREF_W, 0, 0, "S"}, 138 | {RULE_WS, MON_APR, SUN_GTEQ, 1, 4, 0, ATREF_W, 0, 0, "S"}, 139 | {RULE_WS, MON_SEP, SUN_LAST, 0, 3, 0, ATREF_W, 1, 0, "D"}, 140 | {RULE_W_Eur, MON_MAR, SUN_LAST, 0, 1, 0, ATREF_S, 1, 0, "S"}, 141 | {RULE_W_Eur, MON_OCT, SUN_LAST, 0, 1, 0, ATREF_S, 0, 0, ""}, 142 | {RULE_Zion, MON_MAR, FRI_GTEQ, 23, 2, 0, ATREF_W, 1, 0, "D"}, 143 | {RULE_Zion, MON_OCT, SUN_LAST, 0, 2, 0, ATREF_W, 0, 0, "S"}, 144 | }; 145 | typedef struct { 146 | uint8_t zoneNameFromPrev : 5; // 0..31 147 | char zonename[21]; // Make the string live in ROM 148 | int8_t gmtoffhr : 5; // -12...+12 149 | uint8_t gmtoffmin : 6; // 0..59 150 | uint8_t rule : 6; // Empirical 44 rules 151 | char formatstr[12]; // Empirical lots of variation 152 | } timezone_t; 153 | 154 | static const timezone_t mtimezone[] ICACHE_RODATA_ATTR = { 155 | {0, /*Africa/Abidjan*/ "Africa/Abidjan", 0, 0, RULE_NONE, "GMT"}, 156 | {8, /*Africa/Accra*/ "ccra", 0, 0, RULE_NONE, "%s"}, 157 | {8, /*Africa/Algiers*/ "lgiers", 1, 0, RULE_NONE, "CET"}, 158 | {7, /*Africa/Bissau*/ "Bissau", 0, 0, RULE_NONE, "GMT"}, 159 | {7, /*Africa/Cairo*/ "Cairo", 2, 0, RULE_NONE, "EE%sT"}, 160 | {9, /*Africa/Casablanca*/ "sablanca", 0, 0, RULE_Morocco, "WE%sT"}, 161 | {8, /*Africa/Ceuta*/ "euta", 1, 0, RULE_EU, "CE%sT"}, 162 | {7, /*Africa/El_Aaiun*/ "El_Aaiun", 0, 0, RULE_Morocco, "WE%sT"}, 163 | {7, /*Africa/Johannesburg*/ "Johannesburg", 2, 0, RULE_NONE, "SAST"}, 164 | {7, /*Africa/Khartoum*/ "Khartoum", 3, 0, RULE_NONE, "EAT"}, 165 | {7, /*Africa/Lagos*/ "Lagos", 1, 0, RULE_NONE, "WAT"}, 166 | {7, /*Africa/Maputo*/ "Maputo", 2, 0, RULE_NONE, "CAT"}, 167 | {8, /*Africa/Monrovia*/ "onrovia", 0, 0, RULE_NONE, "GMT"}, 168 | {7, /*Africa/Nairobi*/ "Nairobi", 3, 0, RULE_NONE, "EAT"}, 169 | {8, /*Africa/Ndjamena*/ "djamena", 1, 0, RULE_NONE, "WAT"}, 170 | {7, /*Africa/Tripoli*/ "Tripoli", 2, 0, RULE_NONE, "EET"}, 171 | {8, /*Africa/Tunis*/ "unis", 1, 0, RULE_NONE, "CE%sT"}, 172 | {7, /*Africa/Windhoek*/ "Windhoek", 1, 0, RULE_Namibia, "WA%sT"}, 173 | {1, /*America/Adak*/ "merica/Adak", -10, 0, RULE_US, "H%sT"}, 174 | {9, /*America/Anchorage*/ "nchorage", -9, 0, RULE_US, "AK%sT"}, 175 | {9, /*America/Araguaina*/ "raguaina", -3, 0, RULE_NONE, "-03"}, 176 | {10, /*America/Argentina/Buenos_Aires*/ "gentina/Buenos_Aires", -3, 0, RULE_NONE, "-03/-02"}, 177 | {18, /*America/Argentina/Catamarca*/ "Catamarca", -3, 0, RULE_NONE, "-03"}, 178 | {19, /*America/Argentina/Cordoba*/ "ordoba", -3, 0, RULE_NONE, "-03/-02"}, 179 | {18, /*America/Argentina/Jujuy*/ "Jujuy", -3, 0, RULE_NONE, "-03"}, 180 | {18, /*America/Argentina/La_Rioja*/ "La_Rioja", -3, 0, RULE_NONE, "-03"}, 181 | {18, /*America/Argentina/Mendoza*/ "Mendoza", -3, 0, RULE_NONE, "-03"}, 182 | {18, /*America/Argentina/Rio_Gallegos*/ "Rio_Gallegos", -3, 0, RULE_NONE, "-03"}, 183 | {18, /*America/Argentina/Salta*/ "Salta", -3, 0, RULE_NONE, "-03"}, 184 | {20, /*America/Argentina/San_Juan*/ "n_Juan", -3, 0, RULE_NONE, "-03"}, 185 | {22, /*America/Argentina/San_Luis*/ "Luis", -3, 0, RULE_NONE, "-03"}, 186 | {18, /*America/Argentina/Tucuman*/ "Tucuman", -3, 0, RULE_NONE, "-03/-02"}, 187 | {18, /*America/Argentina/Ushuaia*/ "Ushuaia", -3, 0, RULE_NONE, "-03"}, 188 | {9, /*America/Asuncion*/ "suncion", -4, 0, RULE_Para, "-04/-03"}, 189 | {9, /*America/Atikokan*/ "tikokan", -5, 0, RULE_NONE, "EST"}, 190 | {8, /*America/Bahia*/ "Bahia", -3, 0, RULE_NONE, "-03"}, 191 | {13, /*America/Bahia_Banderas*/ "_Banderas", -6, 0, RULE_Mexico, "C%sT"}, 192 | {10, /*America/Barbados*/ "rbados", -4, 0, RULE_NONE, "A%sT"}, 193 | {9, /*America/Belem*/ "elem", -3, 0, RULE_NONE, "-03"}, 194 | {11, /*America/Belize*/ "ize", -6, 0, RULE_NONE, "%s"}, 195 | {9, /*America/Blanc-Sablon*/ "lanc-Sablon", -4, 0, RULE_NONE, "AST"}, 196 | {9, /*America/Boa_Vista*/ "oa_Vista", -4, 0, RULE_NONE, "-04"}, 197 | {10, /*America/Bogota*/ "gota", -5, 0, RULE_NONE, "-05/-04"}, 198 | {10, /*America/Boise*/ "ise", -7, 0, RULE_US, "M%sT"}, 199 | {8, /*America/Cambridge_Bay*/ "Cambridge_Bay", -7, 0, RULE_Canada, "M%sT"}, 200 | {11, /*America/Campo_Grande*/ "po_Grande", -4, 0, RULE_Brazil, "-04/-03"}, 201 | {10, /*America/Cancun*/ "ncun", -5, 0, RULE_NONE, "EST"}, 202 | {10, /*America/Caracas*/ "racas", -4, 0, RULE_NONE, "-04"}, 203 | {10, /*America/Cayenne*/ "yenne", -3, 0, RULE_NONE, "-03"}, 204 | {9, /*America/Chicago*/ "hicago", -6, 0, RULE_US, "C%sT"}, 205 | {11, /*America/Chihuahua*/ "huahua", -7, 0, RULE_Mexico, "M%sT"}, 206 | {9, /*America/Costa_Rica*/ "osta_Rica", -6, 0, RULE_NONE, "C%sT"}, 207 | {9, /*America/Creston*/ "reston", -7, 0, RULE_NONE, "MST"}, 208 | {9, /*America/Cuiaba*/ "uiaba", -4, 0, RULE_Brazil, "-04/-03"}, 209 | {10, /*America/Curacao*/ "racao", -4, 0, RULE_NONE, "AST"}, 210 | {8, /*America/Danmarkshavn*/ "Danmarkshavn", 0, 0, RULE_NONE, "GMT"}, 211 | {10, /*America/Dawson*/ "wson", -8, 0, RULE_Canada, "P%sT"}, 212 | {14, /*America/Dawson_Creek*/ "_Creek", -7, 0, RULE_NONE, "MST"}, 213 | {9, /*America/Denver*/ "enver", -7, 0, RULE_US, "M%sT"}, 214 | {10, /*America/Detroit*/ "troit", -5, 0, RULE_US, "E%sT"}, 215 | {8, /*America/Edmonton*/ "Edmonton", -7, 0, RULE_Canada, "M%sT"}, 216 | {9, /*America/Eirunepe*/ "irunepe", -5, 0, RULE_NONE, "-05"}, 217 | {9, /*America/El_Salvador*/ "l_Salvador", -6, 0, RULE_NONE, "C%sT"}, 218 | {8, /*America/Fort_Nelson*/ "Fort_Nelson", -7, 0, RULE_NONE, "MST"}, 219 | {12, /*America/Fortaleza*/ "aleza", -3, 0, RULE_NONE, "-03"}, 220 | {8, /*America/Glace_Bay*/ "Glace_Bay", -4, 0, RULE_Canada, "A%sT"}, 221 | {9, /*America/Godthab*/ "odthab", -3, 0, RULE_EU, "-03/-02"}, 222 | {10, /*America/Goose_Bay*/ "ose_Bay", -4, 0, RULE_Canada, "A%sT"}, 223 | {9, /*America/Grand_Turk*/ "rand_Turk", -4, 0, RULE_NONE, "AST"}, 224 | {9, /*America/Guatemala*/ "uatemala", -6, 0, RULE_NONE, "C%sT"}, 225 | {11, /*America/Guayaquil*/ "yaquil", -5, 0, RULE_NONE, "-05/-04"}, 226 | {10, /*America/Guyana*/ "yana", -4, 0, RULE_NONE, "-04"}, 227 | {8, /*America/Halifax*/ "Halifax", -4, 0, RULE_Canada, "A%sT"}, 228 | {10, /*America/Havana*/ "vana", -5, 0, RULE_Cuba, "C%sT"}, 229 | {9, /*America/Hermosillo*/ "ermosillo", -7, 0, RULE_NONE, "MST"}, 230 | {8, /*America/Indiana/Indianapolis*/ "Indiana/Indianapolis", -5, 0, RULE_US, "E%sT"}, 231 | {16, /*America/Indiana/Knox*/ "Knox", -6, 0, RULE_US, "C%sT"}, 232 | {16, /*America/Indiana/Marengo*/ "Marengo", -5, 0, RULE_US, "E%sT"}, 233 | {16, /*America/Indiana/Petersburg*/ "Petersburg", -5, 0, RULE_US, "E%sT"}, 234 | {16, /*America/Indiana/Tell_City*/ "Tell_City", -6, 0, RULE_US, "C%sT"}, 235 | {16, /*America/Indiana/Vevay*/ "Vevay", -5, 0, RULE_US, "E%sT"}, 236 | {17, /*America/Indiana/Vincennes*/ "incennes", -5, 0, RULE_US, "E%sT"}, 237 | {16, /*America/Indiana/Winamac*/ "Winamac", -5, 0, RULE_US, "E%sT"}, 238 | {10, /*America/Inuvik*/ "uvik", -7, 0, RULE_Canada, "M%sT"}, 239 | {9, /*America/Iqaluit*/ "qaluit", -5, 0, RULE_Canada, "E%sT"}, 240 | {8, /*America/Jamaica*/ "Jamaica", -5, 0, RULE_NONE, "EST"}, 241 | {9, /*America/Juneau*/ "uneau", -9, 0, RULE_US, "AK%sT"}, 242 | {8, /*America/Kentucky/Louisville*/ "Kentucky/Louisville", -5, 0, RULE_US, "E%sT"}, 243 | {17, /*America/Kentucky/Monticello*/ "Monticello", -5, 0, RULE_US, "E%sT"}, 244 | {8, /*America/La_Paz*/ "La_Paz", -4, 0, RULE_NONE, "-04"}, 245 | {9, /*America/Lima*/ "ima", -5, 0, RULE_NONE, "-05/-04"}, 246 | {9, /*America/Los_Angeles*/ "os_Angeles", -8, 0, RULE_US, "P%sT"}, 247 | {8, /*America/Maceio*/ "Maceio", -3, 0, RULE_NONE, "-03"}, 248 | {10, /*America/Managua*/ "nagua", -6, 0, RULE_NONE, "C%sT"}, 249 | {12, /*America/Manaus*/ "us", -4, 0, RULE_NONE, "-04"}, 250 | {10, /*America/Martinique*/ "rtinique", -4, 0, RULE_NONE, "AST"}, 251 | {10, /*America/Matamoros*/ "tamoros", -6, 0, RULE_US, "C%sT"}, 252 | {10, /*America/Mazatlan*/ "zatlan", -7, 0, RULE_Mexico, "M%sT"}, 253 | {9, /*America/Menominee*/ "enominee", -6, 0, RULE_US, "C%sT"}, 254 | {10, /*America/Merida*/ "rida", -6, 0, RULE_Mexico, "C%sT"}, 255 | {10, /*America/Metlakatla*/ "tlakatla", -9, 0, RULE_US, "AK%sT"}, 256 | {10, /*America/Mexico_City*/ "xico_City", -6, 0, RULE_Mexico, "C%sT"}, 257 | {9, /*America/Miquelon*/ "iquelon", -3, 0, RULE_Canada, "-03/-02"}, 258 | {9, /*America/Moncton*/ "oncton", -4, 0, RULE_Canada, "A%sT"}, 259 | {11, /*America/Monterrey*/ "terrey", -6, 0, RULE_Mexico, "C%sT"}, 260 | {13, /*America/Montevideo*/ "video", -3, 0, RULE_NONE, "-03/-02"}, 261 | {8, /*America/Nassau*/ "Nassau", -5, 0, RULE_US, "E%sT"}, 262 | {9, /*America/New_York*/ "ew_York", -5, 0, RULE_US, "E%sT"}, 263 | {9, /*America/Nipigon*/ "ipigon", -5, 0, RULE_Canada, "E%sT"}, 264 | {9, /*America/Nome*/ "ome", -9, 0, RULE_US, "AK%sT"}, 265 | {10, /*America/Noronha*/ "ronha", -2, 0, RULE_NONE, "-02"}, 266 | {11, /*America/North_Dakota/Beulah*/ "th_Dakota/Beulah", -6, 0, RULE_US, "C%sT"}, 267 | {21, /*America/North_Dakota/Center*/ "Center", -6, 0, RULE_US, "C%sT"}, 268 | {21, /*America/North_Dakota/New_Salem*/ "New_Salem", -6, 0, RULE_US, "C%sT"}, 269 | {8, /*America/Ojinaga*/ "Ojinaga", -7, 0, RULE_US, "M%sT"}, 270 | {8, /*America/Panama*/ "Panama", -5, 0, RULE_NONE, "EST"}, 271 | {11, /*America/Pangnirtung*/ "gnirtung", -5, 0, RULE_Canada, "E%sT"}, 272 | {10, /*America/Paramaribo*/ "ramaribo", -3, 0, RULE_NONE, "-03"}, 273 | {9, /*America/Phoenix*/ "hoenix", -7, 0, RULE_NONE, "MST"}, 274 | {9, /*America/Port-au-Prince*/ "ort-au-Prince", -5, 0, RULE_NONE, "E%sT"}, 275 | {12, /*America/Port_of_Spain*/ "_of_Spain", -4, 0, RULE_NONE, "AST"}, 276 | {12, /*America/Porto_Velho*/ "o_Velho", -4, 0, RULE_NONE, "-04"}, 277 | {9, /*America/Puerto_Rico*/ "uerto_Rico", -4, 0, RULE_NONE, "AST"}, 278 | {10, /*America/Punta_Arenas*/ "nta_Arenas", -3, 0, RULE_NONE, "-03"}, 279 | {8, /*America/Rainy_River*/ "Rainy_River", -6, 0, RULE_Canada, "C%sT"}, 280 | {10, /*America/Rankin_Inlet*/ "nkin_Inlet", -6, 0, RULE_Canada, "C%sT"}, 281 | {9, /*America/Recife*/ "ecife", -3, 0, RULE_NONE, "-03"}, 282 | {10, /*America/Regina*/ "gina", -6, 0, RULE_NONE, "CST"}, 283 | {10, /*America/Resolute*/ "solute", -6, 0, RULE_Canada, "C%sT"}, 284 | {9, /*America/Rio_Branco*/ "io_Branco", -5, 0, RULE_NONE, "-05"}, 285 | {8, /*America/Santarem*/ "Santarem", -3, 0, RULE_NONE, "-03"}, 286 | {12, /*America/Santiago*/ "iago", -4, 0, RULE_Chile, "-04/-03"}, 287 | {12, /*America/Santo_Domingo*/ "o_Domingo", -4, 0, RULE_NONE, "AST"}, 288 | {10, /*America/Sao_Paulo*/ "o_Paulo", -3, 0, RULE_Brazil, "-03/-02"}, 289 | {9, /*America/Scoresbysund*/ "coresbysund", -1, 0, RULE_EU, "-01/+00"}, 290 | {9, /*America/Sitka*/ "itka", -9, 0, RULE_US, "AK%sT"}, 291 | {9, /*America/St_Johns*/ "t_Johns", -3, 30, RULE_Canada, "N%sT"}, 292 | {9, /*America/Swift_Current*/ "wift_Current", -6, 0, RULE_NONE, "CST"}, 293 | {8, /*America/Tegucigalpa*/ "Tegucigalpa", -6, 0, RULE_NONE, "C%sT"}, 294 | {9, /*America/Thule*/ "hule", -4, 0, RULE_Thule, "A%sT"}, 295 | {11, /*America/Thunder_Bay*/ "nder_Bay", -5, 0, RULE_Canada, "E%sT"}, 296 | {9, /*America/Tijuana*/ "ijuana", -8, 0, RULE_US, "P%sT"}, 297 | {9, /*America/Toronto*/ "oronto", -5, 0, RULE_Canada, "E%sT"}, 298 | {8, /*America/Vancouver*/ "Vancouver", -8, 0, RULE_Canada, "P%sT"}, 299 | {8, /*America/Whitehorse*/ "Whitehorse", -8, 0, RULE_Canada, "P%sT"}, 300 | {9, /*America/Winnipeg*/ "innipeg", -6, 0, RULE_Canada, "C%sT"}, 301 | {8, /*America/Yakutat*/ "Yakutat", -9, 0, RULE_US, "AK%sT"}, 302 | {9, /*America/Yellowknife*/ "ellowknife", -7, 0, RULE_Canada, "M%sT"}, 303 | {1, /*Antarctica/Casey*/ "ntarctica/Casey", 11, 0, RULE_NONE, "+11"}, 304 | {11, /*Antarctica/Davis*/ "Davis", 7, 0, RULE_NONE, "+07"}, 305 | {12, /*Antarctica/DumontDUrville*/ "umontDUrville", 10, 0, RULE_NONE, "+10"}, 306 | {11, /*Antarctica/Macquarie*/ "Macquarie", 11, 0, RULE_NONE, "+11"}, 307 | {13, /*Antarctica/Mawson*/ "wson", 5, 0, RULE_NONE, "+05"}, 308 | {11, /*Antarctica/Palmer*/ "Palmer", -3, 0, RULE_NONE, "-03"}, 309 | {11, /*Antarctica/Rothera*/ "Rothera", -3, 0, RULE_NONE, "-03"}, 310 | {11, /*Antarctica/Syowa*/ "Syowa", 3, 0, RULE_NONE, "+03"}, 311 | {11, /*Antarctica/Troll*/ "Troll", 0, 0, RULE_Troll, "%s"}, 312 | {11, /*Antarctica/Vostok*/ "Vostok", 6, 0, RULE_NONE, "+06"}, 313 | {1, /*Asia/Almaty*/ "sia/Almaty", 6, 0, RULE_NONE, "+06"}, 314 | {6, /*Asia/Amman*/ "mman", 2, 0, RULE_Jordan, "EE%sT"}, 315 | {6, /*Asia/Anadyr*/ "nadyr", 12, 0, RULE_NONE, "+12"}, 316 | {6, /*Asia/Aqtau*/ "qtau", 5, 0, RULE_NONE, "+05"}, 317 | {8, /*Asia/Aqtobe*/ "obe", 5, 0, RULE_NONE, "+05"}, 318 | {6, /*Asia/Ashgabat*/ "shgabat", 5, 0, RULE_NONE, "+05"}, 319 | {6, /*Asia/Atyrau*/ "tyrau", 5, 0, RULE_NONE, "+05"}, 320 | {5, /*Asia/Baghdad*/ "Baghdad", 3, 0, RULE_NONE, "+03/+04"}, 321 | {7, /*Asia/Baku*/ "ku", 4, 0, RULE_NONE, "+04/+05"}, 322 | {7, /*Asia/Bangkok*/ "ngkok", 7, 0, RULE_NONE, "+07"}, 323 | {7, /*Asia/Barnaul*/ "rnaul", 7, 0, RULE_NONE, "+07"}, 324 | {6, /*Asia/Beirut*/ "eirut", 2, 0, RULE_Lebanon, "EE%sT"}, 325 | {6, /*Asia/Bishkek*/ "ishkek", 6, 0, RULE_NONE, "+06"}, 326 | {6, /*Asia/Brunei*/ "runei", 8, 0, RULE_NONE, "+08"}, 327 | {5, /*Asia/Chita*/ "Chita", 9, 0, RULE_NONE, "+09"}, 328 | {7, /*Asia/Choibalsan*/ "oibalsan", 8, 0, RULE_NONE, "+08/+09"}, 329 | {6, /*Asia/Colombo*/ "olombo", 5, 30, RULE_NONE, "+0530"}, 330 | {5, /*Asia/Damascus*/ "Damascus", 2, 0, RULE_Syria, "EE%sT"}, 331 | {6, /*Asia/Dhaka*/ "haka", 6, 0, RULE_NONE, "+06/+07"}, 332 | {6, /*Asia/Dili*/ "ili", 9, 0, RULE_NONE, "+09"}, 333 | {6, /*Asia/Dubai*/ "ubai", 4, 0, RULE_NONE, "+04"}, 334 | {7, /*Asia/Dushanbe*/ "shanbe", 5, 0, RULE_NONE, "+05"}, 335 | {5, /*Asia/Famagusta*/ "Famagusta", 3, 0, RULE_NONE, "+03"}, 336 | {5, /*Asia/Gaza*/ "Gaza", 2, 0, RULE_Palestine, "EE%sT"}, 337 | {5, /*Asia/Hebron*/ "Hebron", 2, 0, RULE_Palestine, "EE%sT"}, 338 | {6, /*Asia/Ho_Chi_Minh*/ "o_Chi_Minh", 7, 0, RULE_NONE, "+07"}, 339 | {7, /*Asia/Hong_Kong*/ "ng_Kong", 8, 0, RULE_NONE, "HK%sT"}, 340 | {7, /*Asia/Hovd*/ "vd", 7, 0, RULE_NONE, "+07/+08"}, 341 | {5, /*Asia/Irkutsk*/ "Irkutsk", 8, 0, RULE_NONE, "+08"}, 342 | {5, /*Asia/Jakarta*/ "Jakarta", 7, 0, RULE_NONE, "WIB"}, 343 | {7, /*Asia/Jayapura*/ "yapura", 9, 0, RULE_NONE, "WIT"}, 344 | {6, /*Asia/Jerusalem*/ "erusalem", 2, 0, RULE_Zion, "I%sT"}, 345 | {5, /*Asia/Kabul*/ "Kabul", 4, 30, RULE_NONE, "+0430"}, 346 | {7, /*Asia/Kamchatka*/ "mchatka", 12, 0, RULE_NONE, "+12"}, 347 | {7, /*Asia/Karachi*/ "rachi", 5, 0, RULE_NONE, "PK%sT"}, 348 | {7, /*Asia/Kathmandu*/ "thmandu", 5, 45, RULE_NONE, "+0545"}, 349 | {6, /*Asia/Khandyga*/ "handyga", 9, 0, RULE_NONE, "+09"}, 350 | {6, /*Asia/Kolkata*/ "olkata", 5, 30, RULE_NONE, "IST"}, 351 | {6, /*Asia/Krasnoyarsk*/ "rasnoyarsk", 7, 0, RULE_NONE, "+07"}, 352 | {6, /*Asia/Kuala_Lumpur*/ "uala_Lumpur", 8, 0, RULE_NONE, "+08"}, 353 | {7, /*Asia/Kuching*/ "ching", 8, 0, RULE_NONE, "+08"}, 354 | {5, /*Asia/Macau*/ "Macau", 8, 0, RULE_NONE, "C%sT"}, 355 | {7, /*Asia/Magadan*/ "gadan", 11, 0, RULE_NONE, "+11"}, 356 | {7, /*Asia/Makassar*/ "kassar", 8, 0, RULE_NONE, "WITA"}, 357 | {7, /*Asia/Manila*/ "nila", 8, 0, RULE_NONE, "+08/+09"}, 358 | {5, /*Asia/Nicosia*/ "Nicosia", 2, 0, RULE_EUAsia, "EE%sT"}, 359 | {6, /*Asia/Novokuznetsk*/ "ovokuznetsk", 7, 0, RULE_NONE, "+07"}, 360 | {9, /*Asia/Novosibirsk*/ "sibirsk", 7, 0, RULE_NONE, "+07"}, 361 | {5, /*Asia/Omsk*/ "Omsk", 6, 0, RULE_NONE, "+06"}, 362 | {6, /*Asia/Oral*/ "ral", 5, 0, RULE_NONE, "+05"}, 363 | {5, /*Asia/Pontianak*/ "Pontianak", 7, 0, RULE_NONE, "WIB"}, 364 | {6, /*Asia/Pyongyang*/ "yongyang", 8, 30, RULE_NONE, "KST"}, 365 | {5, /*Asia/Qatar*/ "Qatar", 3, 0, RULE_NONE, "+03"}, 366 | {6, /*Asia/Qyzylorda*/ "yzylorda", 6, 0, RULE_NONE, "+06"}, 367 | {5, /*Asia/Riyadh*/ "Riyadh", 3, 0, RULE_NONE, "+03"}, 368 | {5, /*Asia/Sakhalin*/ "Sakhalin", 11, 0, RULE_NONE, "+11"}, 369 | {7, /*Asia/Samarkand*/ "markand", 5, 0, RULE_NONE, "+05"}, 370 | {6, /*Asia/Seoul*/ "eoul", 9, 0, RULE_NONE, "K%sT"}, 371 | {6, /*Asia/Shanghai*/ "hanghai", 8, 0, RULE_NONE, "C%sT"}, 372 | {6, /*Asia/Singapore*/ "ingapore", 8, 0, RULE_NONE, "+08"}, 373 | {6, /*Asia/Srednekolymsk*/ "rednekolymsk", 11, 0, RULE_NONE, "+11"}, 374 | {5, /*Asia/Taipei*/ "Taipei", 8, 0, RULE_NONE, "C%sT"}, 375 | {7, /*Asia/Tashkent*/ "shkent", 5, 0, RULE_NONE, "+05"}, 376 | {6, /*Asia/Tbilisi*/ "bilisi", 4, 0, RULE_NONE, "+04"}, 377 | {6, /*Asia/Tehran*/ "ehran", 3, 30, RULE_NONE, "+0330/+0430"}, 378 | {6, /*Asia/Thimphu*/ "himphu", 6, 0, RULE_NONE, "+06"}, 379 | {6, /*Asia/Tokyo*/ "okyo", 9, 0, RULE_NONE, "J%sT"}, 380 | {7, /*Asia/Tomsk*/ "msk", 7, 0, RULE_NONE, "+07"}, 381 | {5, /*Asia/Ulaanbaatar*/ "Ulaanbaatar", 8, 0, RULE_NONE, "+08/+09"}, 382 | {6, /*Asia/Urumqi*/ "rumqi", 6, 0, RULE_NONE, "+06"}, 383 | {6, /*Asia/Ust-Nera*/ "st-Nera", 10, 0, RULE_NONE, "+10"}, 384 | {5, /*Asia/Vladivostok*/ "Vladivostok", 10, 0, RULE_NONE, "+10"}, 385 | {5, /*Asia/Yakutsk*/ "Yakutsk", 9, 0, RULE_NONE, "+09"}, 386 | {7, /*Asia/Yangon*/ "ngon", 6, 30, RULE_NONE, "+0630"}, 387 | {6, /*Asia/Yekaterinburg*/ "ekaterinburg", 5, 0, RULE_NONE, "+05"}, 388 | {7, /*Asia/Yerevan*/ "revan", 4, 0, RULE_NONE, "+04/+05"}, 389 | {1, /*Atlantic/Azores*/ "tlantic/Azores", -1, 0, RULE_EU, "-01/+00"}, 390 | {9, /*Atlantic/Bermuda*/ "Bermuda", -4, 0, RULE_US, "A%sT"}, 391 | {9, /*Atlantic/Canary*/ "Canary", 0, 0, RULE_EU, "WE%sT"}, 392 | {11, /*Atlantic/Cape_Verde*/ "pe_Verde", -1, 0, RULE_NONE, "CVT"}, 393 | {9, /*Atlantic/Faroe*/ "Faroe", 0, 0, RULE_EU, "WE%sT"}, 394 | {9, /*Atlantic/Madeira*/ "Madeira", 0, 0, RULE_EU, "WE%sT"}, 395 | {9, /*Atlantic/Reykjavik*/ "Reykjavik", 0, 0, RULE_NONE, "GMT"}, 396 | {9, /*Atlantic/South_Georgia*/ "South_Georgia", -2, 0, RULE_NONE, "-02"}, 397 | {10, /*Atlantic/Stanley*/ "tanley", -3, 0, RULE_NONE, "-03"}, 398 | {1, /*Australia/Adelaide*/ "ustralia/Adelaide", 9, 30, RULE_AS, "AC%sT"}, 399 | {10, /*Australia/Brisbane*/ "Brisbane", 10, 0, RULE_NONE, "AE%sT"}, 400 | {12, /*Australia/Broken_Hill*/ "oken_Hill", 9, 30, RULE_AS, "AC%sT"}, 401 | {10, /*Australia/Currie*/ "Currie", 10, 0, RULE_AT, "AE%sT"}, 402 | {10, /*Australia/Darwin*/ "Darwin", 9, 30, RULE_NONE, "AC%sT"}, 403 | {10, /*Australia/Eucla*/ "Eucla", 8, 45, RULE_NONE, "+0845/+0945"}, 404 | {10, /*Australia/Hobart*/ "Hobart", 10, 0, RULE_AT, "AE%sT"}, 405 | {10, /*Australia/Lindeman*/ "Lindeman", 10, 0, RULE_NONE, "AE%sT"}, 406 | {11, /*Australia/Lord_Howe*/ "ord_Howe", 10, 30, RULE_LH, "+1030/+11"}, 407 | {10, /*Australia/Melbourne*/ "Melbourne", 10, 0, RULE_AV, "AE%sT"}, 408 | {10, /*Australia/Perth*/ "Perth", 8, 0, RULE_NONE, "AW%sT"}, 409 | {10, /*Australia/Sydney*/ "Sydney", 10, 0, RULE_AN, "AE%sT"}, 410 | {0, /*CET*/ "CET", 1, 0, RULE_C_Eur, "CE%sT"}, 411 | {1, /*CST6CDT*/ "ST6CDT", -6, 0, RULE_US, "C%sT"}, 412 | {0, /*EET*/ "EET", 2, 0, RULE_EU, "EE%sT"}, 413 | {1, /*EST*/ "ST", -5, 0, RULE_NONE, "EST"}, 414 | {3, /*EST5EDT*/ "5EDT", -5, 0, RULE_US, "E%sT"}, 415 | {1, /*Etc/GMT*/ "tc/GMT", 0, 0, RULE_NONE, "GMT"}, 416 | {7, /*Etc/GMT+1*/ "+1", -1, 0, RULE_NONE, "-01"}, 417 | {9, /*Etc/GMT+10*/ "0", -10, 0, RULE_NONE, "-10"}, 418 | {9, /*Etc/GMT+11*/ "1", -11, 0, RULE_NONE, "-11"}, 419 | {9, /*Etc/GMT+12*/ "2", -12, 0, RULE_NONE, "-12"}, 420 | {8, /*Etc/GMT+2*/ "2", -2, 0, RULE_NONE, "-02"}, 421 | {8, /*Etc/GMT+3*/ "3", -3, 0, RULE_NONE, "-03"}, 422 | {8, /*Etc/GMT+4*/ "4", -4, 0, RULE_NONE, "-04"}, 423 | {8, /*Etc/GMT+5*/ "5", -5, 0, RULE_NONE, "-05"}, 424 | {8, /*Etc/GMT+6*/ "6", -6, 0, RULE_NONE, "-06"}, 425 | {8, /*Etc/GMT+7*/ "7", -7, 0, RULE_NONE, "-07"}, 426 | {8, /*Etc/GMT+8*/ "8", -8, 0, RULE_NONE, "-08"}, 427 | {8, /*Etc/GMT+9*/ "9", -9, 0, RULE_NONE, "-09"}, 428 | {7, /*Etc/GMT-1*/ "-1", 1, 0, RULE_NONE, "+01"}, 429 | {9, /*Etc/GMT-10*/ "0", 10, 0, RULE_NONE, "+10"}, 430 | {9, /*Etc/GMT-11*/ "1", 11, 0, RULE_NONE, "+11"}, 431 | {9, /*Etc/GMT-12*/ "2", 12, 0, RULE_NONE, "+12"}, 432 | {9, /*Etc/GMT-13*/ "3", 13, 0, RULE_NONE, "+13"}, 433 | {9, /*Etc/GMT-14*/ "4", 14, 0, RULE_NONE, "+14"}, 434 | {8, /*Etc/GMT-2*/ "2", 2, 0, RULE_NONE, "+02"}, 435 | {8, /*Etc/GMT-3*/ "3", 3, 0, RULE_NONE, "+03"}, 436 | {8, /*Etc/GMT-4*/ "4", 4, 0, RULE_NONE, "+04"}, 437 | {8, /*Etc/GMT-5*/ "5", 5, 0, RULE_NONE, "+05"}, 438 | {8, /*Etc/GMT-6*/ "6", 6, 0, RULE_NONE, "+06"}, 439 | {8, /*Etc/GMT-7*/ "7", 7, 0, RULE_NONE, "+07"}, 440 | {8, /*Etc/GMT-8*/ "8", 8, 0, RULE_NONE, "+08"}, 441 | {8, /*Etc/GMT-9*/ "9", 9, 0, RULE_NONE, "+09"}, 442 | {4, /*Etc/UCT*/ "UCT", 0, 0, RULE_NONE, "UCT"}, 443 | {5, /*Etc/UTC*/ "TC", 0, 0, RULE_NONE, "UTC"}, 444 | {1, /*Europe/Amsterdam*/ "urope/Amsterdam", 1, 0, RULE_EU, "CE%sT"}, 445 | {8, /*Europe/Andorra*/ "ndorra", 1, 0, RULE_EU, "CE%sT"}, 446 | {8, /*Europe/Astrakhan*/ "strakhan", 4, 0, RULE_NONE, "+04"}, 447 | {8, /*Europe/Athens*/ "thens", 2, 0, RULE_EU, "EE%sT"}, 448 | {7, /*Europe/Belgrade*/ "Belgrade", 1, 0, RULE_EU, "CE%sT"}, 449 | {9, /*Europe/Berlin*/ "rlin", 1, 0, RULE_EU, "CE%sT"}, 450 | {8, /*Europe/Brussels*/ "russels", 1, 0, RULE_EU, "CE%sT"}, 451 | {8, /*Europe/Bucharest*/ "ucharest", 2, 0, RULE_EU, "EE%sT"}, 452 | {9, /*Europe/Budapest*/ "dapest", 1, 0, RULE_EU, "CE%sT"}, 453 | {7, /*Europe/Chisinau*/ "Chisinau", 2, 0, RULE_Moldova, "EE%sT"}, 454 | {8, /*Europe/Copenhagen*/ "openhagen", 1, 0, RULE_EU, "CE%sT"}, 455 | {7, /*Europe/Dublin*/ "Dublin", 0, 0, RULE_EU, "GMT/IST"}, 456 | {7, /*Europe/Gibraltar*/ "Gibraltar", 1, 0, RULE_EU, "CE%sT"}, 457 | {7, /*Europe/Helsinki*/ "Helsinki", 2, 0, RULE_EU, "EE%sT"}, 458 | {7, /*Europe/Istanbul*/ "Istanbul", 3, 0, RULE_NONE, "+03"}, 459 | {7, /*Europe/Kaliningrad*/ "Kaliningrad", 2, 0, RULE_NONE, "EET"}, 460 | {8, /*Europe/Kiev*/ "iev", 2, 0, RULE_EU, "EE%sT"}, 461 | {9, /*Europe/Kirov*/ "rov", 3, 0, RULE_NONE, "+03"}, 462 | {7, /*Europe/Lisbon*/ "Lisbon", 0, 0, RULE_EU, "WE%sT"}, 463 | {8, /*Europe/London*/ "ondon", 0, 0, RULE_EU, "GMT/BST"}, 464 | {8, /*Europe/Luxembourg*/ "uxembourg", 1, 0, RULE_EU, "CE%sT"}, 465 | {7, /*Europe/Madrid*/ "Madrid", 1, 0, RULE_EU, "CE%sT"}, 466 | {9, /*Europe/Malta*/ "lta", 1, 0, RULE_EU, "CE%sT"}, 467 | {8, /*Europe/Minsk*/ "insk", 3, 0, RULE_NONE, "+03"}, 468 | {8, /*Europe/Monaco*/ "onaco", 1, 0, RULE_EU, "CE%sT"}, 469 | {9, /*Europe/Moscow*/ "scow", 3, 0, RULE_NONE, "MSK"}, 470 | {7, /*Europe/Oslo*/ "Oslo", 1, 0, RULE_EU, "CE%sT"}, 471 | {7, /*Europe/Paris*/ "Paris", 1, 0, RULE_EU, "CE%sT"}, 472 | {8, /*Europe/Prague*/ "rague", 1, 0, RULE_EU, "CE%sT"}, 473 | {7, /*Europe/Riga*/ "Riga", 2, 0, RULE_EU, "EE%sT"}, 474 | {8, /*Europe/Rome*/ "ome", 1, 0, RULE_EU, "CE%sT"}, 475 | {7, /*Europe/Samara*/ "Samara", 4, 0, RULE_NONE, "+04"}, 476 | {9, /*Europe/Saratov*/ "ratov", 4, 0, RULE_NONE, "+04"}, 477 | {8, /*Europe/Simferopol*/ "imferopol", 3, 0, RULE_NONE, "MSK"}, 478 | {8, /*Europe/Sofia*/ "ofia", 2, 0, RULE_EU, "EE%sT"}, 479 | {8, /*Europe/Stockholm*/ "tockholm", 1, 0, RULE_EU, "CE%sT"}, 480 | {7, /*Europe/Tallinn*/ "Tallinn", 2, 0, RULE_EU, "EE%sT"}, 481 | {8, /*Europe/Tirane*/ "irane", 1, 0, RULE_EU, "CE%sT"}, 482 | {7, /*Europe/Ulyanovsk*/ "Ulyanovsk", 4, 0, RULE_NONE, "+04"}, 483 | {8, /*Europe/Uzhgorod*/ "zhgorod", 2, 0, RULE_EU, "EE%sT"}, 484 | {7, /*Europe/Vienna*/ "Vienna", 1, 0, RULE_EU, "CE%sT"}, 485 | {9, /*Europe/Vilnius*/ "lnius", 2, 0, RULE_EU, "EE%sT"}, 486 | {8, /*Europe/Volgograd*/ "olgograd", 3, 0, RULE_NONE, "+03"}, 487 | {7, /*Europe/Warsaw*/ "Warsaw", 1, 0, RULE_EU, "CE%sT"}, 488 | {7, /*Europe/Zaporozhye*/ "Zaporozhye", 2, 0, RULE_EU, "EE%sT"}, 489 | {8, /*Europe/Zurich*/ "urich", 1, 0, RULE_EU, "CE%sT"}, 490 | {0, /*HST*/ "HST", -10, 0, RULE_NONE, "HST"}, 491 | {0, /*Indian/Chagos*/ "Indian/Chagos", 6, 0, RULE_NONE, "+06"}, 492 | {9, /*Indian/Christmas*/ "ristmas", 7, 0, RULE_NONE, "+07"}, 493 | {8, /*Indian/Cocos*/ "ocos", 6, 30, RULE_NONE, "+0630"}, 494 | {7, /*Indian/Kerguelen*/ "Kerguelen", 5, 0, RULE_NONE, "+05"}, 495 | {7, /*Indian/Mahe*/ "Mahe", 4, 0, RULE_NONE, "SCT"}, 496 | {9, /*Indian/Maldives*/ "ldives", 5, 0, RULE_NONE, "+05"}, 497 | {9, /*Indian/Mauritius*/ "uritius", 4, 0, RULE_NONE, "MU%sT"}, 498 | {7, /*Indian/Reunion*/ "Reunion", 4, 0, RULE_NONE, "RET"}, 499 | {0, /*MET*/ "MET", 1, 0, RULE_C_Eur, "ME%sT"}, 500 | {1, /*MST*/ "ST", -7, 0, RULE_NONE, "MST"}, 501 | {3, /*MST7MDT*/ "7MDT", -7, 0, RULE_US, "M%sT"}, 502 | {0, /*PST8PDT*/ "PST8PDT", -8, 0, RULE_US, "P%sT"}, 503 | {1, /*Pacific/Apia*/ "acific/Apia", 13, 0, RULE_WS, "+13/+14"}, 504 | {9, /*Pacific/Auckland*/ "uckland", 12, 0, RULE_NZ, "NZ%sT"}, 505 | {8, /*Pacific/Bougainville*/ "Bougainville", 11, 0, RULE_NONE, "+11"}, 506 | {8, /*Pacific/Chatham*/ "Chatham", 12, 45, RULE_Chatham, "+1245/+1345"}, 507 | {10, /*Pacific/Chuuk*/ "uuk", 10, 0, RULE_NONE, "+10"}, 508 | {8, /*Pacific/Easter*/ "Easter", -6, 0, RULE_Chile, "-06/-05"}, 509 | {9, /*Pacific/Efate*/ "fate", 11, 0, RULE_NONE, "+11/+12"}, 510 | {9, /*Pacific/Enderbury*/ "nderbury", 13, 0, RULE_NONE, "+13"}, 511 | {8, /*Pacific/Fakaofo*/ "Fakaofo", 13, 0, RULE_NONE, "+13"}, 512 | {9, /*Pacific/Fiji*/ "iji", 12, 0, RULE_Fiji, "+12/+13"}, 513 | {9, /*Pacific/Funafuti*/ "unafuti", 12, 0, RULE_NONE, "+12"}, 514 | {8, /*Pacific/Galapagos*/ "Galapagos", -6, 0, RULE_NONE, "-06/-05"}, 515 | {10, /*Pacific/Gambier*/ "mbier", -9, 0, RULE_NONE, "-09"}, 516 | {9, /*Pacific/Guadalcanal*/ "uadalcanal", 11, 0, RULE_NONE, "+11"}, 517 | {11, /*Pacific/Guam*/ "m", 10, 0, RULE_NONE, "ChST"}, 518 | {8, /*Pacific/Honolulu*/ "Honolulu", -10, 0, RULE_NONE, "HST"}, 519 | {8, /*Pacific/Kiritimati*/ "Kiritimati", 14, 0, RULE_NONE, "+14"}, 520 | {9, /*Pacific/Kosrae*/ "osrae", 11, 0, RULE_NONE, "+11"}, 521 | {9, /*Pacific/Kwajalein*/ "wajalein", 12, 0, RULE_NONE, "+12"}, 522 | {8, /*Pacific/Majuro*/ "Majuro", 12, 0, RULE_NONE, "+12"}, 523 | {10, /*Pacific/Marquesas*/ "rquesas", -9, 30, RULE_NONE, "-0930"}, 524 | {8, /*Pacific/Nauru*/ "Nauru", 12, 0, RULE_NONE, "+12"}, 525 | {9, /*Pacific/Niue*/ "iue", -11, 0, RULE_NONE, "-11"}, 526 | {9, /*Pacific/Norfolk*/ "orfolk", 11, 0, RULE_NONE, "+11"}, 527 | {10, /*Pacific/Noumea*/ "umea", 11, 0, RULE_NONE, "+11/+12"}, 528 | {8, /*Pacific/Pago_Pago*/ "Pago_Pago", -11, 0, RULE_NONE, "SST"}, 529 | {10, /*Pacific/Palau*/ "lau", 9, 0, RULE_NONE, "+09"}, 530 | {9, /*Pacific/Pitcairn*/ "itcairn", -8, 0, RULE_NONE, "-08"}, 531 | {9, /*Pacific/Pohnpei*/ "ohnpei", 11, 0, RULE_NONE, "+11"}, 532 | {10, /*Pacific/Port_Moresby*/ "rt_Moresby", 10, 0, RULE_NONE, "+10"}, 533 | {8, /*Pacific/Rarotonga*/ "Rarotonga", -10, 0, RULE_NONE, "-10/-0930"}, 534 | {8, /*Pacific/Tahiti*/ "Tahiti", -10, 0, RULE_NONE, "-10"}, 535 | {10, /*Pacific/Tarawa*/ "rawa", 12, 0, RULE_NONE, "+12"}, 536 | {9, /*Pacific/Tongatapu*/ "ongatapu", 13, 0, RULE_Tonga, "+13/+14"}, 537 | {8, /*Pacific/Wake*/ "Wake", 12, 0, RULE_NONE, "+12"}, 538 | {10, /*Pacific/Wallis*/ "llis", 12, 0, RULE_NONE, "+12"}, 539 | {0, /*WET*/ "WET", 0, 0, RULE_EU, "WE%sT"}, 540 | }; 541 | typedef struct { 542 | uint8_t zoneNameFromPrev : 5; // 0..31 543 | char zonename[24]; // Make it live in ROM 544 | uint16_t timezone : 9; // Empirical # of timezones < 511 545 | } link_t; 546 | 547 | static const link_t link[] ICACHE_RODATA_ATTR = { 548 | { 0, "Africa/Addis_Ababa", 13 /*Africa/Nairobi*/ }, 549 | { 8, "smara", 13 /*Africa/Nairobi*/ }, 550 | { 10, "era", 13 /*Africa/Nairobi*/ }, 551 | { 7, "Bamako", 0 /*Africa/Abidjan*/ }, 552 | { 9, "ngui", 10 /*Africa/Lagos*/ }, 553 | { 10, "jul", 0 /*Africa/Abidjan*/ }, 554 | { 8, "lantyre", 11 /*Africa/Maputo*/ }, 555 | { 8, "razzaville", 10 /*Africa/Lagos*/ }, 556 | { 8, "ujumbura", 11 /*Africa/Maputo*/ }, 557 | { 7, "Conakry", 0 /*Africa/Abidjan*/ }, 558 | { 7, "Dakar", 0 /*Africa/Abidjan*/ }, 559 | { 9, "r_es_Salaam", 13 /*Africa/Nairobi*/ }, 560 | { 8, "jibouti", 13 /*Africa/Nairobi*/ }, 561 | { 8, "ouala", 10 /*Africa/Lagos*/ }, 562 | { 7, "Freetown", 0 /*Africa/Abidjan*/ }, 563 | { 7, "Gaborone", 11 /*Africa/Maputo*/ }, 564 | { 7, "Harare", 11 /*Africa/Maputo*/ }, 565 | { 7, "Juba", 9 /*Africa/Khartoum*/ }, 566 | { 7, "Kampala", 13 /*Africa/Nairobi*/ }, 567 | { 8, "igali", 11 /*Africa/Maputo*/ }, 568 | { 9, "nshasa", 10 /*Africa/Lagos*/ }, 569 | { 7, "Libreville", 10 /*Africa/Lagos*/ }, 570 | { 8, "ome", 0 /*Africa/Abidjan*/ }, 571 | { 8, "uanda", 10 /*Africa/Lagos*/ }, 572 | { 9, "bumbashi", 11 /*Africa/Maputo*/ }, 573 | { 9, "saka", 11 /*Africa/Maputo*/ }, 574 | { 7, "Malabo", 10 /*Africa/Lagos*/ }, 575 | { 9, "seru", 8 /*Africa/Johannesburg*/ }, 576 | { 8, "babane", 8 /*Africa/Johannesburg*/ }, 577 | { 8, "ogadishu", 13 /*Africa/Nairobi*/ }, 578 | { 7, "Niamey", 10 /*Africa/Lagos*/ }, 579 | { 8, "ouakchott", 0 /*Africa/Abidjan*/ }, 580 | { 7, "Ouagadougou", 0 /*Africa/Abidjan*/ }, 581 | { 7, "Porto-Novo", 10 /*Africa/Lagos*/ }, 582 | { 7, "Sao_Tome", 0 /*Africa/Abidjan*/ }, 583 | { 7, "Timbuktu", 0 /*Africa/Abidjan*/ }, 584 | { 1, "merica/Anguilla", 120 /*America/Port_of_Spain*/ }, 585 | { 10, "tigua", 120 /*America/Port_of_Spain*/ }, 586 | { 9, "rgentina/ComodRivadavia", 22 /*America/Argentina/Catamarca*/ }, 587 | { 10, "uba", 54 /*America/Curacao*/ }, 588 | { 9, "tka", 18 /*America/Adak*/ }, 589 | { 8, "Buenos_Aires", 21 /*America/Argentina/Buenos_Aires*/ }, 590 | { 8, "Catamarca", 22 /*America/Argentina/Catamarca*/ }, 591 | { 10, "yman", 115 /*America/Panama*/ }, 592 | { 9, "oral_Harbour", 34 /*America/Atikokan*/ }, 593 | { 11, "doba", 23 /*America/Argentina/Cordoba*/ }, 594 | { 8, "Dominica", 120 /*America/Port_of_Spain*/ }, 595 | { 8, "Ensenada", 141 /*America/Tijuana*/ }, 596 | { 8, "Fort_Wayne", 75 /*America/Indiana/Indianapolis*/ }, 597 | { 8, "Grenada", 120 /*America/Port_of_Spain*/ }, 598 | { 9, "uadeloupe", 120 /*America/Port_of_Spain*/ }, 599 | { 8, "Indianapolis", 75 /*America/Indiana/Indianapolis*/ }, 600 | { 8, "Jujuy", 24 /*America/Argentina/Jujuy*/ }, 601 | { 8, "Knox_IN", 76 /*America/Indiana/Knox*/ }, 602 | { 9, "ralendijk", 54 /*America/Curacao*/ }, 603 | { 8, "Louisville", 87 /*America/Kentucky/Louisville*/ }, 604 | { 10, "wer_Princes", 54 /*America/Curacao*/ }, 605 | { 8, "Marigot", 120 /*America/Port_of_Spain*/ }, 606 | { 9, "endoza", 26 /*America/Argentina/Mendoza*/ }, 607 | { 9, "ontreal", 142 /*America/Toronto*/ }, 608 | { 12, "serrat", 120 /*America/Port_of_Spain*/ }, 609 | { 8, "Porto_Acre", 129 /*America/Rio_Branco*/ }, 610 | { 8, "Rosario", 23 /*America/Argentina/Cordoba*/ }, 611 | { 8, "Santa_Isabel", 141 /*America/Tijuana*/ }, 612 | { 9, "hiprock", 58 /*America/Denver*/ }, 613 | { 9, "t_Barthelemy", 120 /*America/Port_of_Spain*/ }, 614 | { 11, "Kitts", 120 /*America/Port_of_Spain*/ }, 615 | { 11, "Lucia", 120 /*America/Port_of_Spain*/ }, 616 | { 11, "Thomas", 120 /*America/Port_of_Spain*/ }, 617 | { 11, "Vincent", 120 /*America/Port_of_Spain*/ }, 618 | { 8, "Tortola", 120 /*America/Port_of_Spain*/ }, 619 | { 8, "Virgin", 120 /*America/Port_of_Spain*/ }, 620 | { 1, "ntarctica/McMurdo", 349 /*Pacific/Auckland*/ }, 621 | { 11, "South_Pole", 349 /*Pacific/Auckland*/ }, 622 | { 1, "rctic/Longyearbyen", 315 /*Europe/Oslo*/ }, 623 | { 1, "sia/Aden", 212 /*Asia/Riyadh*/ }, 624 | { 6, "shkhabad", 163 /*Asia/Ashgabat*/ }, 625 | { 5, "Bahrain", 210 /*Asia/Qatar*/ }, 626 | { 5, "Calcutta", 195 /*Asia/Kolkata*/ }, 627 | { 6, "hongqing", 216 /*Asia/Shanghai*/ }, 628 | { 7, "ungking", 216 /*Asia/Shanghai*/ }, 629 | { 5, "Dacca", 176 /*Asia/Dhaka*/ }, 630 | { 5, "Harbin", 216 /*Asia/Shanghai*/ }, 631 | { 5, "Istanbul", 303 /*Europe/Istanbul*/ }, 632 | { 5, "Kashgar", 227 /*Asia/Urumqi*/ }, 633 | { 7, "tmandu", 193 /*Asia/Kathmandu*/ }, 634 | { 6, "uwait", 212 /*Asia/Riyadh*/ }, 635 | { 5, "Macao", 199 /*Asia/Macau*/ }, 636 | { 6, "uscat", 178 /*Asia/Dubai*/ }, 637 | { 5, "Phnom_Penh", 167 /*Asia/Bangkok*/ }, 638 | { 5, "Rangoon", 231 /*Asia/Yangon*/ }, 639 | { 5, "Saigon", 183 /*Asia/Ho_Chi_Minh*/ }, 640 | { 5, "Tel_Aviv", 189 /*Asia/Jerusalem*/ }, 641 | { 6, "himbu", 223 /*Asia/Thimphu*/ }, 642 | { 5, "Ujung_Pandang", 201 /*Asia/Makassar*/ }, 643 | { 6, "lan_Bator", 226 /*Asia/Ulaanbaatar*/ }, 644 | { 5, "Vientiane", 167 /*Asia/Bangkok*/ }, 645 | { 1, "tlantic/Faeroe", 238 /*Atlantic/Faroe*/ }, 646 | { 9, "Jan_Mayen", 315 /*Europe/Oslo*/ }, 647 | { 9, "St_Helena", 0 /*Africa/Abidjan*/ }, 648 | { 1, "ustralia/ACT", 254 /*Australia/Sydney*/ }, 649 | { 10, "Canberra", 254 /*Australia/Sydney*/ }, 650 | { 10, "LHI", 251 /*Australia/Lord_Howe*/ }, 651 | { 10, "NSW", 254 /*Australia/Sydney*/ }, 652 | { 11, "orth", 247 /*Australia/Darwin*/ }, 653 | { 10, "Queensland", 244 /*Australia/Brisbane*/ }, 654 | { 10, "South", 243 /*Australia/Adelaide*/ }, 655 | { 10, "Tasmania", 249 /*Australia/Hobart*/ }, 656 | { 10, "Victoria", 252 /*Australia/Melbourne*/ }, 657 | { 10, "West", 253 /*Australia/Perth*/ }, 658 | { 10, "Yancowinna", 245 /*Australia/Broken_Hill*/ }, 659 | { 0, "Brazil/Acre", 129 /*America/Rio_Branco*/ }, 660 | { 7, "DeNoronha", 110 /*America/Noronha*/ }, 661 | { 7, "East", 133 /*America/Sao_Paulo*/ }, 662 | { 7, "West", 94 /*America/Manaus*/ }, 663 | { 0, "Canada/Atlantic", 72 /*America/Halifax*/ }, 664 | { 7, "Central", 145 /*America/Winnipeg*/ }, 665 | { 7, "East-Saskatchewan", 127 /*America/Regina*/ }, 666 | { 11, "ern", 142 /*America/Toronto*/ }, 667 | { 7, "Mountain", 60 /*America/Edmonton*/ }, 668 | { 7, "Newfoundland", 136 /*America/St_Johns*/ }, 669 | { 7, "Pacific", 143 /*America/Vancouver*/ }, 670 | { 7, "Saskatchewan", 127 /*America/Regina*/ }, 671 | { 7, "Yukon", 144 /*America/Whitehorse*/ }, 672 | { 1, "hile/Continental", 131 /*America/Santiago*/ }, 673 | { 6, "EasterIsland", 353 /*Pacific/Easter*/ }, 674 | { 1, "uba", 73 /*America/Havana*/ }, 675 | { 0, "Egypt", 4 /*Africa/Cairo*/ }, 676 | { 1, "ire", 300 /*Europe/Dublin*/ }, 677 | { 1, "tc/GMT+0", 260 /*Etc/GMT*/ }, 678 | { 7, "-0", 260 /*Etc/GMT*/ }, 679 | { 7, "0", 260 /*Etc/GMT*/ }, 680 | { 5, "reenwich", 260 /*Etc/GMT*/ }, 681 | { 4, "Universal", 288 /*Etc/UTC*/ }, 682 | { 4, "Zulu", 288 /*Etc/UTC*/ }, 683 | { 1, "urope/Belfast", 308 /*Europe/London*/ }, 684 | { 8, "ratislava", 317 /*Europe/Prague*/ }, 685 | { 8, "usingen", 334 /*Europe/Zurich*/ }, 686 | { 7, "Guernsey", 308 /*Europe/London*/ }, 687 | { 7, "Isle_of_Man", 308 /*Europe/London*/ }, 688 | { 7, "Jersey", 308 /*Europe/London*/ }, 689 | { 7, "Ljubljana", 293 /*Europe/Belgrade*/ }, 690 | { 7, "Mariehamn", 302 /*Europe/Helsinki*/ }, 691 | { 7, "Nicosia", 203 /*Asia/Nicosia*/ }, 692 | { 7, "Podgorica", 293 /*Europe/Belgrade*/ }, 693 | { 7, "San_Marino", 319 /*Europe/Rome*/ }, 694 | { 9, "rajevo", 293 /*Europe/Belgrade*/ }, 695 | { 8, "kopje", 293 /*Europe/Belgrade*/ }, 696 | { 7, "Tiraspol", 298 /*Europe/Chisinau*/ }, 697 | { 7, "Vaduz", 334 /*Europe/Zurich*/ }, 698 | { 9, "tican", 319 /*Europe/Rome*/ }, 699 | { 7, "Zagreb", 293 /*Europe/Belgrade*/ }, 700 | { 0, "GB", 308 /*Europe/London*/ }, 701 | { 2, "-Eire", 308 /*Europe/London*/ }, 702 | { 1, "MT", 260 /*Etc/GMT*/ }, 703 | { 3, "+0", 260 /*Etc/GMT*/ }, 704 | { 3, "-0", 260 /*Etc/GMT*/ }, 705 | { 3, "0", 260 /*Etc/GMT*/ }, 706 | { 1, "reenwich", 260 /*Etc/GMT*/ }, 707 | { 0, "Hongkong", 184 /*Asia/Hong_Kong*/ }, 708 | { 0, "Iceland", 240 /*Atlantic/Reykjavik*/ }, 709 | { 1, "ndian/Antananarivo", 13 /*Africa/Nairobi*/ }, 710 | { 7, "Comoro", 13 /*Africa/Nairobi*/ }, 711 | { 7, "Mayotte", 13 /*Africa/Nairobi*/ }, 712 | { 1, "ran", 222 /*Asia/Tehran*/ }, 713 | { 1, "srael", 189 /*Asia/Jerusalem*/ }, 714 | { 0, "Jamaica", 85 /*America/Jamaica*/ }, 715 | { 2, "pan", 224 /*Asia/Tokyo*/ }, 716 | { 0, "Kwajalein", 366 /*Pacific/Kwajalein*/ }, 717 | { 0, "Libya", 15 /*Africa/Tripoli*/ }, 718 | { 0, "Mexico/BajaNorte", 141 /*America/Tijuana*/ }, 719 | { 11, "Sur", 97 /*America/Mazatlan*/ }, 720 | { 7, "General", 101 /*America/Mexico_City*/ }, 721 | { 0, "NZ", 349 /*Pacific/Auckland*/ }, 722 | { 2, "-CHAT", 351 /*Pacific/Chatham*/ }, 723 | { 1, "avajo", 58 /*America/Denver*/ }, 724 | { 0, "PRC", 216 /*Asia/Shanghai*/ }, 725 | { 1, "acific/Johnston", 363 /*Pacific/Honolulu*/ }, 726 | { 8, "Midway", 373 /*Pacific/Pago_Pago*/ }, 727 | { 8, "Ponape", 376 /*Pacific/Pohnpei*/ }, 728 | { 8, "Saipan", 362 /*Pacific/Guam*/ }, 729 | { 10, "moa", 373 /*Pacific/Pago_Pago*/ }, 730 | { 8, "Truk", 352 /*Pacific/Chuuk*/ }, 731 | { 8, "Yap", 352 /*Pacific/Chuuk*/ }, 732 | { 1, "oland", 332 /*Europe/Warsaw*/ }, 733 | { 2, "rtugal", 307 /*Europe/Lisbon*/ }, 734 | { 0, "ROC", 219 /*Asia/Taipei*/ }, 735 | { 2, "K", 215 /*Asia/Seoul*/ }, 736 | { 0, "Singapore", 217 /*Asia/Singapore*/ }, 737 | { 0, "Turkey", 303 /*Europe/Istanbul*/ }, 738 | { 0, "UCT", 287 /*Etc/UCT*/ }, 739 | { 1, "S/Alaska", 19 /*America/Anchorage*/ }, 740 | { 5, "eutian", 18 /*America/Adak*/ }, 741 | { 4, "rizona", 118 /*America/Phoenix*/ }, 742 | { 3, "Central", 49 /*America/Chicago*/ }, 743 | { 3, "East-Indiana", 75 /*America/Indiana/Indianapolis*/ }, 744 | { 7, "ern", 107 /*America/New_York*/ }, 745 | { 3, "Hawaii", 363 /*Pacific/Honolulu*/ }, 746 | { 3, "Indiana-Starke", 76 /*America/Indiana/Knox*/ }, 747 | { 3, "Michigan", 59 /*America/Detroit*/ }, 748 | { 4, "ountain", 58 /*America/Denver*/ }, 749 | { 3, "Pacific", 91 /*America/Los_Angeles*/ }, 750 | { 10, "-New", 91 /*America/Los_Angeles*/ }, 751 | { 3, "Samoa", 373 /*Pacific/Pago_Pago*/ }, 752 | { 1, "TC", 288 /*Etc/UTC*/ }, 753 | { 1, "niversal", 288 /*Etc/UTC*/ }, 754 | { 0, "W-SU", 314 /*Europe/Moscow*/ }, 755 | { 0, "Zulu", 288 /*Etc/UTC*/ }, 756 | }; 757 | -------------------------------------------------------------------------------- /web.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | 24 | #include "log.h" 25 | #include "web.h" 26 | #include "password.h" 27 | #include "timezone.h" 28 | 29 | 30 | 31 | 32 | void WebPrintError(WiFiClient *client, int code) 33 | { 34 | switch(code) { 35 | case 301: WebPrintf(client, "301 Moved Permanently"); break; 36 | case 400: WebPrintf(client, "400 Bad Request"); break; 37 | case 401: WebPrintf(client, "401 Unauthorized"); break; 38 | case 404: WebPrintf(client, "404 Not Found"); break; 39 | case 405: WebPrintf(client, "405 Method Not Allowed"); break; 40 | default: WebPrintf(client, "500 Server Error"); break; 41 | } 42 | } 43 | 44 | 45 | void WebError(WiFiClient *client, int code, const char *headers, bool usePMEM) 46 | { 47 | LogPrintf("+WebError: Begin, free=%d\n", ESP.getFreeHeap()); 48 | LogPrintf(" Sending headers...\n"); 49 | WebPrintf(client, "HTTP/1.1 %d\r\n", code); 50 | WebPrintf(client, "Server: PsychoPlug\r\n"); 51 | WebPrintf(client, "Content-type: text/html\r\n"); 52 | WebPrintf(client, "Cache-Control: no-cache, no-store, must-revalidate\r\n"); 53 | WebPrintf(client, "Pragma: no-cache\r\n"); 54 | WebPrintf(client, "Expires: 0\r\n"); 55 | WebPrintf(client, "Connection: close\r\n"); 56 | LogPrintf("+WebError: Writing error headers: %08x\n", headers); 57 | if (headers) { 58 | if (!usePMEM) { 59 | WebPrintf(client, "%s", headers); 60 | } else { 61 | WebPrintfPSTR(client, headers); 62 | } 63 | } 64 | WebPrintf(client, "\r\n\r\n"); 65 | WebPrintf(client, DOCTYPE); 66 | WebPrintf(client, ""); 67 | WebPrintError(client, code); 68 | WebPrintf(client, "" ENCODING "\n"); 69 | WebPrintf(client, "

"); 70 | WebPrintError(client, code); 71 | WebPrintf(client, "

\r\n"); 72 | LogPrintf("-WebError\n"); 73 | } 74 | 75 | 76 | 77 | void WebHeaders(WiFiClient *client, PGM_P /*const char **/headers) 78 | { 79 | WebPrintf(client, "HTTP/1.1 200 OK\r\n"); 80 | WebPrintf(client, "Server: PsychoPlug\r\n"); 81 | WebPrintf(client, "Content-type: text/html\r\n"); 82 | WebPrintf(client, "Cache-Control: no-cache, no-store, must-revalidate\r\n"); 83 | WebPrintf(client, "Pragma: no-cache\r\n"); 84 | WebPrintf(client, "Connection: close\r\n"); 85 | WebPrintf(client, "Expires: 0\r\n"); 86 | if (headers) { 87 | WebPrintfPSTR(client, headers); 88 | } 89 | WebPrintf(client, "\r\n"); 90 | } 91 | 92 | 93 | 94 | 95 | // In-place decoder, overwrites source with decoded values. Needs 0-termination on input 96 | // Try and keep memory needs low, speed not critical 97 | static uint8_t b64lut(uint8_t i) 98 | { 99 | if (i >= 'A' && i <= 'Z') return i - 'A'; 100 | if (i >= 'a' && i <= 'z') return i - 'a' + 26; 101 | if (i >= '0' && i <= '9') return i - '0' + 52; 102 | if (i == '-') return 62; 103 | if (i == '_') return 63; 104 | else return 64;// sentinel 105 | } 106 | 107 | void Base64Decode(char *str) 108 | { 109 | char *dest; 110 | dest = str; 111 | 112 | if (strlen(str)%4) return; // Not multiple of 4 == error 113 | 114 | while (*str) { 115 | uint8_t a = b64lut(*(str++)); 116 | uint8_t b = b64lut(*(str++)); 117 | uint8_t c = b64lut(*(str++)); 118 | uint8_t d = b64lut(*(str++)); 119 | *(dest++) = (a << 2) | ((b & 0x30) >> 4); 120 | if (c == 64) break; 121 | *(dest++) = ((b & 0x0f) << 4) | ((c & 0x3c) >> 2); 122 | if (d == 64) break; 123 | *(dest++) = ((c & 0x03) << 6) | d; 124 | } 125 | *dest = 0; // Terminate the string 126 | } 127 | 128 | 129 | void URLDecode(char *ptr) 130 | { 131 | while (*ptr) { 132 | if (*ptr == '+') { 133 | *ptr = ' '; 134 | } else if (*ptr == '%') { 135 | if (*(ptr+1) && *(ptr+2)) { 136 | byte a = *(ptr + 1); 137 | byte b = *(ptr + 2); 138 | if (a>='0' && a<='9') a -= '0'; 139 | else if (a>='a' && a<='f') a = a - 'a' + 10; 140 | else if (a>='A' && a<='F') a = a - 'A' + 10; 141 | if (b>='0' && b<='9') b -= '0'; 142 | else if (b>='a' && b<='f') b = b - 'a' + 10; 143 | else if (b>='A' && b<='F') b = b - 'A' + 10; 144 | *ptr = ((a&0x0f)<<4) | (b&0x0f); 145 | // Safe strcpy the rest of the string back 146 | char *p1 = ptr + 1; 147 | char *p2 = ptr + 3; 148 | while (*p2) { *p1 = *p2; p1++; p2++; } 149 | *p1 = 0; 150 | } 151 | // OTW this is a bad encoding, just pass unchanged 152 | } 153 | ptr++; 154 | } 155 | } 156 | 157 | 158 | 159 | // Parse (authenticated) HTTP request, request authentication if not authorized 160 | bool WebReadRequest(WiFiClient *client, char **urlStr, char **paramStr, bool authReq, const char *uiUser, const char *uiSalt, const char *uiPassEnc) 161 | { 162 | static char NUL = 0; // Get around writable strings... 163 | char hdrBuff[128]; 164 | char authBuff[128]; 165 | char reqBuff[384]; 166 | 167 | *urlStr = NULL; 168 | *paramStr = NULL; 169 | 170 | LogPrintf("+WebReadRequest @ %d\n", millis()); 171 | unsigned long timeoutMS = millis() + 5000; // Max delay before we timeout 172 | while (!client->available() && millis() < timeoutMS) { delay(10); } 173 | if (!client->available()) { 174 | LogPrintf("-WebReadRequest: Timeout @ %d\n", millis()); 175 | return false; 176 | } 177 | int wlen = client->readBytesUntil('\r', reqBuff, sizeof(reqBuff)-1); 178 | reqBuff[wlen] = 0; 179 | 180 | int hlen = 0; 181 | authBuff[0] = 0; // Start w/o authorization hdr 182 | // Parse through all headers until \r\n\r\n 183 | do { 184 | uint8_t newline; 185 | client->read(&newline, 1); // Get rid of \n 186 | hlen = (byte)client->readBytesUntil('\r', hdrBuff, sizeof(hdrBuff)-1); 187 | hdrBuff[hlen] = 0; 188 | if (!strncmp_P(hdrBuff, PSTR("Authorization: Basic "), 21)) { 189 | strncpy(authBuff, hdrBuff, sizeof(authBuff)); 190 | } 191 | } while (hlen > 0); 192 | 193 | // Check for no password... 194 | bool empty = true; 195 | for (unsigned int i=0; uiSalt!=NULL && iflush(); // Don't need anything here... 224 | 225 | // Break into URL and form data 226 | url = reqBuff+4; 227 | while (*url && *url=='/') url++; // Strip off leading /s 228 | qp = strchr(url, '?'); 229 | if (qp) { 230 | *qp = 0; // End URL 231 | qp++; 232 | } else { 233 | qp = &NUL; 234 | } 235 | } else if (!memcmp_P(reqBuff, PSTR("POST "), 5)) { 236 | uint8_t newline; 237 | client->read(&newline, 1); // Get rid of \n 238 | 239 | url = reqBuff+5; 240 | while (*url && *url=='/') url++; // Strip off leading /s 241 | qp = strchr(url, '?'); 242 | if (qp) *qp = 0; // End URL @ ? 243 | // In a POST the params are in the body 244 | int sizeleft = sizeof(reqBuff) - strlen(reqBuff) - 1; 245 | qp = reqBuff + strlen(reqBuff) + 1; 246 | int wlen = client->readBytesUntil('\r', qp, sizeleft-1); 247 | qp[wlen] = 0; 248 | client->flush(); 249 | URLDecode(qp); 250 | } else { 251 | // Not a GET or POST, error 252 | WebError(client, 405, PSTR("Allow: GET, POST")); 253 | LogPrintf("-WebReadRequest(): Illegal command\n"); 254 | return false; 255 | } 256 | 257 | if (urlStr) *urlStr = url; 258 | if (paramStr) *paramStr = qp; 259 | 260 | LogPrintf("-WebReadRequest(): Success\n"); 261 | return true; 262 | } 263 | 264 | 265 | 266 | // Scan out and update a pointeinto the param string, returning the name and value or false if done 267 | bool ParseParam(char **paramStr, char **name, char **value) 268 | { 269 | char *data = *paramStr; 270 | 271 | if (*data==0) return false; 272 | 273 | char *namePtr = data; 274 | while ((*data != 0) && (*data != '=') && (*data != '&')) data++; 275 | if (*data) { *data = 0; data++; } 276 | char *valPtr = data; 277 | if (*data == '=') data++; 278 | while ((*data != 0) && (*data != '=') && (*data != '&')) data++; 279 | if (*data) { *data = 0; data++;} 280 | 281 | *paramStr = data; 282 | *name = namePtr; 283 | *value = valPtr; 284 | 285 | return true; 286 | } 287 | 288 | bool IsIndexHTML(const char *url) 289 | { 290 | if (!url) return false; 291 | if (*url==0 || !strcmp_P(url, PSTR("/")) || !strcmp_P(url, PSTR("/index.html")) || !strcmp_P(url, PSTR("index.html"))) return true; 292 | else return false; 293 | } 294 | 295 | 296 | 297 | 298 | 299 | void WebFormText(WiFiClient *client, /*const char **/ PGM_P label, const char *name, const char *value, bool enabled) 300 | { 301 | WebPrintfPSTR(client, label); 302 | WebPrintf(client, ":
\n", name, name, value, !enabled?"disabled":""); 303 | } 304 | void WebFormText(WiFiClient *client, /*const char **/ PGM_P label, const char *name, const int value, bool enabled) 305 | { 306 | WebPrintfPSTR(client, label); 307 | WebPrintf(client, ":
\n", name, name, value, !enabled?"disabled":""); 308 | } 309 | void WebFormCheckbox(WiFiClient *client, /*const char **/ PGM_P label, const char *name, bool checked, bool enabled) 310 | { 311 | WebPrintf(client, " ", name, name, checked?"checked":"", !enabled?"disabled":""); 312 | WebPrintfPSTR(client, label); 313 | WebPrintf(client, "
\n"); 314 | } 315 | void WebFormCheckboxDisabler(WiFiClient *client, PGM_P /*const char **/label, const char *name, bool invert, bool checked, bool enabled, const char *ids[]) 316 | { 317 | WebPrintf(client," ", checked?"checked":"", !enabled?"disabled":"") 324 | WebPrintfPSTR(client, label); 325 | WebPrintf(client, "
\n"); 326 | } 327 | 328 | // We do the sort in the browser because it has more memory than us. :( 329 | void WebTimezonePicker(WiFiClient *client, const char *timezone) 330 | { 331 | bool reset = true; 332 | WebPrintf(client, "Timezone:
\n"); 361 | free(buff); 362 | 363 | // Javascript to sort alphabetically... 364 | WebPrintf(client, "\n"); 391 | } 392 | 393 | 394 | 395 | 396 | 397 | // Scan an integer from a string, place it into dest, and then return # of bytes scanned 398 | int ParseInt(char *src, int *dest) 399 | { 400 | byte count = 0; 401 | bool neg = false; 402 | int res = 0; 403 | if (!src) return 0; 404 | if (src[0] == '-') {neg = true; src++; count++;} 405 | while (*src && (*src>='0') && (*src<='9')) { 406 | res = res * 10; 407 | res += *src - '0'; 408 | src++; 409 | count++; 410 | } 411 | if (neg) res *= -1; 412 | if (dest) *dest = res; 413 | return count; 414 | } 415 | 416 | void Read4Int(char *str, byte *p) 417 | { 418 | int i; 419 | str += ParseInt(str, &i); p[0] = i; if (*str) str++; 420 | str += ParseInt(str, &i); p[1] = i; if (*str) str++; 421 | str += ParseInt(str, &i); p[2] = i; if (*str) str++; 422 | str += ParseInt(str, &i); p[3] = i; 423 | } 424 | -------------------------------------------------------------------------------- /web.h: -------------------------------------------------------------------------------- 1 | /* 2 | PsychoPlug 3 | ESP8266 based remote outlet with standalone timer and MQTT integration 4 | 5 | Copyright (C) 2017 Earle F. Philhower, III 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _web_h 22 | #define _web_h 23 | 24 | // Global way of writing out dynamic HTML to socket 25 | // snprintf guarantees a null termination 26 | #define WebPrintf(c, fmt, ...) { char webBuff[192]; snprintf_P(webBuff, sizeof(webBuff), PSTR(fmt), ## __VA_ARGS__); (c)->print(webBuff); delay(10);} 27 | #define WebPrintfPSTR(c, fmt, ...) { char webBuff[192]; snprintf_P(webBuff, sizeof(webBuff), (fmt), ## __VA_ARGS__); (c)->print(webBuff); delay(10);} 28 | 29 | // Common HTTP header bits 30 | #define DOCTYPE "" 31 | #define ENCODING "\n" 32 | 33 | 34 | // Web header creation 35 | void WebPrintError(WiFiClient *client, int code); // Sends only the error code string and a description 36 | void WebError(WiFiClient *client, int code, const char *headers, bool usePMEM = true); // Sends whole HTTP error headers 37 | void WebHeaders(WiFiClient *client, PGM_P /*const char **/headers); // Send success headers 38 | 39 | // Web decoding utilities 40 | void Base64Decode(char *str); // In-place B64 decode 41 | void URLDecode(char *ptr); // In-place URL decode 42 | 43 | // GET/POST parsing 44 | bool WebReadRequest(WiFiClient *client, char **urlStr, char **paramStr, bool authReq, const char *uiUser = NULL, const char *uiSalt = NULL, const char *uiPassEnc= NULL); // Parse HTTP request, ensure authentication passes 45 | bool ParseParam(char **paramStr, char **name, char **value); // Get next name/parameter from a param string 46 | bool IsIndexHTML(const char *url); // Is this meant to be index.html (/, index.htm, etc.) 47 | 48 | // HTML FORM generation 49 | void WebFormText(WiFiClient *client, /*const char **/ PGM_P label, const char *name, const char *value, bool enabled); 50 | void WebFormText(WiFiClient *client, /*const char **/ PGM_P label, const char *name, const int value, bool enabled); 51 | void WebFormCheckbox(WiFiClient *client, /*const char **/ PGM_P label, const char *name, bool checked, bool enabled); 52 | void WebFormCheckboxDisabler(WiFiClient *client, PGM_P /*const char **/label, const char *name, bool invert, bool checked, bool enabled, const char *ids[]); 53 | void WebTimezonePicker(WiFiClient *client, const char *timezone); 54 | 55 | // HTML FORM parsing 56 | int ParseInt(char *src, int *dest); 57 | void Read4Int(char *str, byte *p); 58 | #define ParamText(name, dest) { if (!strcmp(namePtr, (name))) strlcpy((dest), valPtr, sizeof(dest)); } 59 | #define ParamCheckbox(name, dest) { if (!strcmp(namePtr, (name))) (dest) = !strcmp("on", valPtr); } 60 | #define ParamInt(name, dest) { if (!strcmp(namePtr, (name))) ParseInt(valPtr, &dest); } 61 | #define Param4Int(name, dest) { if (!strcmp(namePtr, (name))) Read4Int(valPtr, (dest)); } 62 | 63 | 64 | #endif 65 | 66 | --------------------------------------------------------------------------------