├── ESP32_RFID_Reader.ino ├── LICENSE ├── README.md ├── RFID.cpp ├── appGlobals.h ├── appSpecific.cpp ├── data ├── RFID.htm └── common.js ├── extras ├── RDM6300.png ├── antennaFreq.xlsx └── lcd.jpg ├── globals.h ├── periphsI2C.cpp ├── prefs.cpp ├── setupAssist.cpp ├── utils.cpp ├── utilsFS.cpp ├── webDav.cpp └── webServer.cpp /ESP32_RFID_Reader.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * App to decode EM4100 or FDX-B tags (pet chips) 3 | * and display reading on a web page and an optional LCD 1602 4 | * 5 | * s60sc 2023 6 | * 7 | */ 8 | 9 | #include "appGlobals.h" 10 | 11 | static bool startedUp = false; 12 | 13 | void setup() { 14 | logSetup(); 15 | // prep SD card storage and load saved user configuration 16 | if (startStorage()) loadConfig(); 17 | 18 | #ifdef DEV_ONLY 19 | devSetup(); 20 | #endif 21 | 22 | // connect wifi or start config AP if router details not available 23 | startWifi(); 24 | 25 | startWebServer(); 26 | if (strlen(startupFailure)) LOG_ERR("%s", startupFailure); 27 | else { 28 | // start rest of services 29 | startI2C(); 30 | rfidSetup(); // setup rfid reader 31 | checkMemory(); 32 | startedUp = true; 33 | } 34 | LOG_INF("=============== Total tasks: %u ===============\n", uxTaskGetNumberOfTasks()); 35 | } 36 | 37 | void loop() { 38 | if (startedUp) rfidRead(); 39 | delay(50); 40 | } 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FDX-B (pet microchip) and EM4100 RFID Reader for ESP32 2 | 3 | This app along with suitable hardware will decode the tags in microchipped pets used in the UK and EU which all use the 134.2kHz biphase encoded FDX-B protocol. 4 | It can also be used to decode the 125kHz Manchester encoded EM4100 tags. 5 | 6 | The library was developed for use in a microchip controlled catflap, however the RDM6300 hardware used did not have sufficient range to be reliable, but is fine for a handheld pet microchip reader. 7 | 8 | The captured tag ID is displayed on a web page and on an optional I2C LCD1602. 9 | 10 | 11 | 12 | 13 | ### Only use this app if you are familiar with electronics and can fix issues yourself 14 | 15 | ## Hardware 16 | 17 | A custom RFID circuit can be used, but RDM6300 125kHz EM4100 RFID readers can be bought very cheaply and converted for 134.2kHz. 18 | 19 | With reference to the picture below: 20 | - the top image shows the decoding circuitry consisting of: 21 | - a microcontroller that both generates the antenna clock signal and decodes the EM4100 protocol 22 | - an LM358 dual op amp that both amplifies the received signal and cleans it up (configured as a Schmitt trigger) 23 | - the bottom image is the underside which shows the antenna circuit. 24 | 25 | To convert it for 134.2kHz pet microchips: 26 | - the microcontroller and the voltage regulator marked with red crosses can be removed or disabled. 27 | - increase the antenna resonant frequency to 134.2kHz, either: 28 | - reduce the value of the capacitor ringed in cyan. 29 | - remove some turns from the antenna supplied with the RDM6300 to reduce its inductance. 30 | - to assist with selecting values use the `antennaFreq.xlsx` spreadsheet in the `extras` folder. 31 | - the ESP32 supplies the input clock signal and decodes the raw data. 32 | - the end of the resistor pointed to by the green arrow is the raw signal output to be sent to the ESP32. 33 | - the end of the resistor pointed to by the pink arrow is for the input clock signal from the ESP32. 34 | - the above connection points can be wired to repurposed header pins circled in orange. 35 | - both of the connections to the ESP32 should be via 5V/3V3 level shifters. 36 | 37 | ![image1](extras/RDM6300.png) 38 | 39 | 40 | ## Installation 41 | 42 | Download GitHub files into the Arduino IDE sketch folder, removing `-master` from the application folder name. 43 | Compile using arduino core v2.x or V3.x (min v3.0.3) with Partition Scheme: `Minimal SPIFFS (...)`. 44 | 45 | On first installation, the application will start in wifi AP mode - connect to SSID: **ESP32_RFID_...**, to allow router and password details to be entered via the web page on 192.168.4.1. The configuration data file (except passwords) is automatically created, and the application web pages automatically downloaded from GitHub to the SD card **/data** folder when an internet connection is available. 46 | 47 | Subsequent updates to the application, or to the **/data** folder contents, can be made using the **OTA Upload** tab. The **/data** folder can also be reloaded from GitHub using the **Reload /data** button on the **Edit Config** tab, or by using a WebDAV client on `ip_address/webdav`. 48 | 49 | 50 | ## Configuration 51 | 52 | The IO Extender web page has the following tabs: 53 | 54 | * **RFID**: Shows selected encoding type, Tag ID if read, encoding type selection, plus button to clear tag display. 55 | 56 | * **Show Log**: Opens web socket to view log messages dynamically. 57 | 58 | * **Edit Config**: 59 | 60 | * **Reboot ESP**: Restart the ESP to apply some configuration changes. 61 | 62 | * **Reload /data**: Reload data files from github. 63 | 64 | * **Clear NVS**: Clear current passwords. 65 | 66 | * **Wifi**: WiFi and webserver settings. 67 | 68 | * **Peripherals**: Enter pins for connection to RDM6300 and optional LCD1602, and optional pin for physical button to clear display. 69 | 70 | * **Save**: Make configuration changes persist over ESP reboots. 71 | 72 | * **OTA Update**: Use OTA to update application firmware using bin file or files in **/data** folder. 73 | 74 | -------------------------------------------------------------------------------- /RFID.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Decode EM4100 or FDX-B tags 3 | * The following library https://github.com/Sthing/AccessThing/tree/master/Arduino/libraries/EM4100 4 | * was used as a starting point to derive this library 5 | * together with info for decoding FDX-B from http://www.gizmolab.co.za/fdx-b-protocol/ 6 | * 7 | * s60sc 2018, 2024 8 | */ 9 | 10 | #include "appGlobals.h" 11 | #include "driver/ledc.h" 12 | 13 | int rfidDemod; // input - demod pin from RDM6300, pullup high 14 | int rfidClock; // output - clock pin to RDM6300 15 | int clearPin; // input - clear tag display 16 | float rfidFreq; // RDM6300 antenna frequency 17 | bool encodeFDX = false; // false for EM4100, true for FXD-B 18 | uint64_t currentTag; // read tag value 19 | char encodingStr[17]; // encoding type string 20 | char currentTagStr[17]; // holds string representation of tag 21 | static bool buttonPressed = false; // to clear tag display 22 | 23 | // Buffer sizing 24 | static const uint16_t bitBufferSize = 256; // Room for 2 x FDX-B codeLength bits, EM4100 is smaller 25 | static uint16_t slBoundary, minPulse, maxPulse; // boundary between long and short pulses 26 | static int codeLength, captureSize; 27 | static const int minLength = 64; // min length for complete tag, for FDX-B, only first 64 bits are relevant 28 | static int captureIndex = 0; 29 | 30 | // Variables used during decoding 31 | static uint8_t columnSums[4]; // Used for EM4100 parity calculation of the four columns 32 | static uint8_t bitBuffer[bitBufferSize]; // Each byte contains data for 4 full bit periods. LSB is first bit. 33 | static const char* codeStr[2] = {"EM4100", "FDX-B"}; 34 | static volatile bool captured = false; // whether sufficient pulses have been captured for processing 35 | static int headerPos = 0; 36 | 37 | // simulation and debugging 38 | #define simulation false 39 | static uint16_t pulses[bitBufferSize * 2]; // save pulse lengths, 1 bit can be represented by 2 pulses 40 | static int pulseIndex = 0; 41 | static uint32_t simPulse; 42 | 43 | // forward refs 44 | static bool parseNibble(word offset, uint8_t *nibble); 45 | static bool parseBitBufferEM(uint8_t currIndex); 46 | static bool parseBitBufferFDX(uint8_t currIndex); 47 | 48 | static void runClock() { 49 | // output PWM clock to RDM6300 at required frequency 50 | int dutyBits = 1; // 50% duty 51 | #if ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(3, 0, 0) 52 | ledcAttach(rfidClock, (int)(rfidFreq * 1000), dutyBits); 53 | ledcWrite(rfidClock, 1); 54 | #else 55 | int rfidChannel = 4; 56 | ledcSetup(rfidChannel, (int)(rfidFreq * 1000), dutyBits); 57 | ledcAttachPin(rfidClock, rfidChannel); 58 | ledcWrite(rfidChannel, 1); 59 | #endif 60 | } 61 | void IRAM_ATTR buttonISR() { 62 | buttonPressed = true; 63 | } 64 | 65 | static void IRAM_ATTR demodISR() { 66 | // obtain the encoded bit stream from the reader demodulated output 67 | // consists of short and long pulses, short pulses must occur in pairs (for one bit) 68 | // FDX-B demodulation: One long pulse = logic 1, two short pulses = logic 0 69 | // EM4100 demodulation: One long pulse = change logic level, two short pulses = same as previous logic level 70 | // - but dont know logic polarity 71 | 72 | bool invalidPulse = false; 73 | static uint8_t level = 1; 74 | static bool gotFirstShort = false; 75 | static uint32_t lastMicros = 0; 76 | uint32_t elapsedMicros; 77 | 78 | if (!captured) { 79 | elapsedMicros = simulation ? simPulse : micros() - lastMicros; 80 | lastMicros = micros(); // elapsed uS between interrupts 81 | if (captureIndex >= captureSize) captured = true; 82 | else { 83 | if (elapsedMicros > minPulse && elapsedMicros < maxPulse) { 84 | // potentially valid pulse 85 | if (elapsedMicros > slBoundary) { 86 | // long pulse 87 | if (gotFirstShort) invalidPulse = true; // as only have single short pulse 88 | else { 89 | if (encodeFDX) bitBuffer[captureIndex++] = 1; // FDX-B long pulse = logic 1 90 | else { 91 | // EM4100 long pulse changes logic level 92 | level ^= 1; 93 | bitBuffer[captureIndex++] = level; 94 | } 95 | } 96 | } else { 97 | // short pulse, FDX-B = logic 0, EM4100 same as previous level 98 | if (gotFirstShort) { 99 | // second of two short pulses 100 | bitBuffer[captureIndex++] = encodeFDX ? 0 : level; 101 | gotFirstShort = false; 102 | } else gotFirstShort = true; 103 | } 104 | pulses[pulseIndex++] = elapsedMicros; // debugging 105 | } else invalidPulse = true; 106 | // restart capture on outliers unless min length achieved 107 | if (invalidPulse) { 108 | gotFirstShort = false; 109 | if (captureIndex < minLength) captureIndex = pulseIndex = 0; // restart capture 110 | else captured = true; // try current capture if minumum capture length achieved 111 | } 112 | } 113 | } 114 | } 115 | 116 | static bool findHeader() { 117 | // Search for the start of the relevant protocol header 118 | // Determine if EM4100 tag or FDX-B tag depending on which header expected 119 | // Header is either: 120 | // - 10 0-bits in a row for FDX-B (eg 100000000001) 121 | // - 9 1-bits in a row for em4100 (eg 01111111110) 122 | // There is no point looking for a header after codelength 123 | 124 | uint8_t theBit; 125 | uint8_t countBit = 0; 126 | uint8_t countEnd = (encodeFDX) ? 10 : 9; 127 | 128 | for (uint16_t i = 0; i <= codeLength; i++) { 129 | theBit = bitBuffer[i]; 130 | // (re)start count on an opposite bit 131 | countBit = theBit ? (encodeFDX ? 0 : countBit + 1) : (encodeFDX ? countBit + 1 : 0); 132 | // if appropriate header found, parse data 133 | if (countBit == countEnd) { 134 | if (encodeFDX) return parseBitBufferFDX(i); 135 | else return parseBitBufferEM(i); 136 | } 137 | } 138 | LOG_VRB("No %s header found", codeStr[encodeFDX]); 139 | return false; 140 | } 141 | 142 | static bool parseBitBufferEM(uint8_t currIndex) { 143 | // match data to EM4100 encoding 144 | uint8_t theBit; 145 | // Clear buffers 146 | for (uint8_t i = 0; i < 4; i++) columnSums[i] = 0; 147 | uint16_t countryId = 0; 148 | uint64_t cardTag = 0; 149 | 150 | // Bit currIndex in bitBuffer is the 9th and final header bit (index 8). 151 | // Verify that bit 64 is 0 (stop bit, index 63)) 152 | uint32_t offset = currIndex - 8; // How many bits were skipped before the header started (ie index of first header bit) 153 | LOG_VRB("%s header start at: %d", codeStr[encodeFDX], offset); 154 | headerPos = offset; 155 | 156 | uint32_t index = offset + 63; 157 | theBit = bitBuffer[index]; 158 | if (theBit) { 159 | LOG_VRB("EM stopbit not 0"); 160 | return false; 161 | } 162 | 163 | // Next: 2+8 rows of 4 bits and an even parity bit. MSB first. 164 | // The first 2 rows are the customer id (or version number/manufacturer code), the last 8 rows the data. 165 | // Collect the data in 8 bit facility (countryId) and 32 bit cardUID [cardTag] 166 | uint8_t nibble; 167 | for (uint8_t count = 0; count < 2; count ++) { 168 | if ( !parseNibble(offset + 9 + 5 * count, &nibble)) { 169 | LOG_VRB(" - Wrong parity for card facility, nibble %d", count); 170 | return false; 171 | } 172 | countryId |= nibble << (4 * (1 - count)); // Most significant nibble first 173 | } 174 | 175 | for (uint8_t count = 0; count < 8; count ++) { 176 | if ( ! parseNibble(offset + 19 + 5 * count, &nibble)) { 177 | LOG_VRB(" EM Wrong parity for card UID, nibble %d", count); 178 | return false; 179 | } 180 | cardTag |= ((long)nibble) << (4 * (7 - count)); // Most significant nibble fir 181 | } 182 | // Finally: 4 column parity bits, even 183 | index = offset + 9 + 10 * 5; 184 | for (uint8_t i = 0; i < 4; i++) { 185 | theBit = bitBuffer[index]; 186 | if ((columnSums[i] & 1) != theBit) { 187 | LOG_VRB(" - Wrong parity for column %d", i); 188 | return false; 189 | } 190 | index++; 191 | } 192 | 193 | // valid tag found 194 | currentTag = countryId; 195 | currentTag = (currentTag<<32) + cardTag; 196 | return true; 197 | } // End parseBitBufferEM() 198 | 199 | static bool parseNibble(word offset, uint8_t *nibble) { 200 | // Extracts a nibble from the given offset in bitBuffer and checks for even parity in the 5th bit. 201 | // returns true if the parity bit matches the data bits. 202 | uint8_t theBit; 203 | uint8_t bitSum = 0; 204 | 205 | *nibble = 0; 206 | for (uint8_t i = 0; i < 4; i++) { 207 | theBit = bitBuffer[offset]; 208 | columnSums[i] += theBit; // Used later for column parity check 209 | bitSum += theBit; 210 | *nibble |= (theBit << (3 - i)); // First bit is MSB 211 | offset++; 212 | } 213 | 214 | // Check for even parity 215 | theBit = bitBuffer[offset]; 216 | if ((bitSum & 1) != theBit) return false; 217 | 218 | return true; 219 | } // End parseNibble() 220 | 221 | static bool parseBitBufferFDX(uint8_t currIndex) { 222 | // Match data to FDX-B encoding. 223 | // If decoding succeeds the results are stored in cardTag and countryId. 224 | // Once tag data read, rest can be ignored 225 | uint8_t theBit; 226 | uint16_t countryId = 0; 227 | uint64_t cardTag = 0; 228 | 229 | // now check that next bit is a 1 230 | currIndex++; 231 | theBit = bitBuffer[currIndex]; 232 | if (!theBit) { 233 | LOG_VRB("FDX-B header not terminated"); 234 | return false; 235 | } 236 | headerPos = currIndex - 10; 237 | LOG_VRB("%s header start at: %d", codeStr[encodeFDX], headerPos); 238 | 239 | // next 54 bits (38 bits + 10 bits + control bits) are card id 240 | // ignore final control bit 241 | uint8_t tagId[48]; 242 | uint8_t idCntr = 0; 243 | word count = 0; 244 | uint8_t offset = currIndex+1; 245 | for (uint8_t i = offset; i < offset+53; i++) { 246 | theBit = bitBuffer[i]; 247 | if (count < 8) { 248 | // save data bit 249 | tagId[idCntr] = theBit; 250 | count++; 251 | idCntr++; 252 | } else { 253 | // check control bit and skip it 254 | if (!theBit) { 255 | LOG_VRB("FDX-B control bit wrong"); 256 | return false; 257 | } else count = 0; 258 | } 259 | } 260 | // convert tag id to decimal, reversing bit order 261 | for (uint8_t i = 38; i > 0; i--) { 262 | cardTag = cardTag << 1; 263 | if (tagId[i-1]) cardTag |= 1; 264 | } 265 | 266 | // convert country code to decimal, reversing bit order 267 | for (uint8_t i = 48; i > 38; i--) { 268 | countryId = countryId << 1; 269 | if (tagId[i-1]) countryId |= 1; 270 | } 271 | 272 | // valid tag found 273 | currentTag = countryId; 274 | currentTag = (currentTag<<38) + cardTag; 275 | LOG_VRB("%s", codeStr[encodeFDX]); 276 | return true; 277 | } // End parseBitBufferFDX() 278 | 279 | static void tagStr() { 280 | // format 64 bit tag into decimal string 281 | // 13 digits for EM41000 282 | // 15 digits for FDX-B 283 | uint64_t thisCardTag; 284 | uint16_t thisCountryId; 285 | uint64_t bitmask = 0x00000000FFFFFFFF; // EM4100 286 | int cardTagBits = 32; // EM4100 287 | int cardTagLen = 10; // EM4100 288 | if (encodeFDX) { // FDX-B 289 | cardTagBits = 38; 290 | cardTagLen = 12; 291 | bitmask = 0x0000003FFFFFFFFF; 292 | } 293 | thisCardTag = (currentTag & bitmask); 294 | thisCountryId = (uint16_t)(currentTag >> cardTagBits); 295 | sprintf(currentTagStr, "%03u", thisCountryId); 296 | // card tag is LSB ordered 297 | for (size_t i = cardTagLen; i--; thisCardTag /= 10) currentTagStr[i + 3] = '0' + (thisCardTag % 10); 298 | currentTagStr[cardTagLen + 3] = 0; 299 | } 300 | 301 | static bool getTag() { 302 | // decode RFID tag 303 | if (findHeader()) { 304 | tagStr(); 305 | LOG_INF("Read tag - %s", currentTagStr); 306 | return true; 307 | } else { 308 | LOG_VRB("Tag not read"); 309 | currentTag = currentTagStr[0] = 0; 310 | } 311 | return false; 312 | } 313 | 314 | static void showRawData(bool haveTag) { 315 | // show captured pulse lengths and decoding for debugging 316 | if (dbgVerbose) { 317 | logPrint("%s", "------------------------------------------\n"); 318 | logPrint("pulses: %d\n", pulseIndex); 319 | logPrint("slBoundary: %d\n", slBoundary); 320 | logPrint("%s", "pulselen: "); 321 | for (int i = 0; i < pulseIndex; i++) logPrint("%d/", pulses[i]); 322 | logPrint("\n%s", "decoded: "); 323 | for (int i = 0; i < captureIndex; i++) logPrint("%u", bitBuffer[i]); 324 | if (haveTag) { 325 | logPrint("\n%s", "tag: "); 326 | for (int i = 0; i < minLength; i++) logPrint("%u", bitBuffer[headerPos + i]); 327 | } 328 | logPrint("%s", "\n------------------------------------------\n\n"); 329 | } 330 | } 331 | 332 | static void demodSim() { 333 | // simulate pulses from rfid reader using pregenerated pulse sequence 334 | uint16_t pulseCount = 0; 335 | 336 | const char* delimiter = "/"; 337 | // EM4100 tag 0290003174496 338 | const char* pulseLensEM = "200/310/457/308/203/306/204/307/204/305/206/302/210/300/210/299/211/300/210/299/211/301/210/301/210/558/208/301/466/300/210/301/210/300/210/306/203/306/205/301/210/556/210/300/210/299/211/299/467/300/210/300/210/299/212/298/212/300/211/554/212/297/468/299/213/297/213/298/213/297/213/299/211/298/213/554/213/297/213/297/469/297/213/553/218/292/213/297/216/289/222/294/216/294/215/295/217/294/215/295/471/295/216/295/216/552/213/297/215/291/219/296/470/551/216/292/474/294/216/295/217/290/220/290/220/291/219/290/220/291/220/290/220/290/220/290/220/290/220/550/216/295/472/289/221/290/220/290/220/290/221/290/219/294/217/546/220/290/220/292/219/290/477/289/221/289/222/288/221/289/221/289/222/546/220/290/476/289/222/289/221/289/222/288/222/289/222/288/222/545/222/288/222/288/479/289/225/542/221/289/221/289/221/289/221/290/220/290/221/290/219/291/220/289/477/289/222/289/222/544/222/288/221/289/222/289/478/544"; 339 | // FDX-B tag 945000001554408 340 | const char* pulseLensFDX = "90/115/100/225/110/110/95/115/105/115/100/120/100/110/95/115/105/115/100/120/100/110/105/105/210/130/95/120/95/115/95/225/110/115/205/225/215/230/210/225/215/125/100/220/210/125/100/225/210/225/215/230/110/110/200/130/95/120/100/115/95/220/110/115/100/115/105/110/100/115/100/115/100/120/100/110/100/120/200/130/95/120/95/115/100/110/105/115/100/120/95/225/105/110/210/125/95/120/100/215/220/125/90/225/210/230/215/120/100/110/105/115/100/120/95/115/100/110/105/115/100/120/95/225/110/105/105/115/100/110/105/115/100/110/105/115/100/115/210/225/105/115/105/110/210/225/110/110/105/110/210/225/215/125/95/225/110/105/105/115/100/115/100/115/205/230/210/125/100/115/95/120/100/115/100/115/100/115/105/110/100/115/100/220/115/110/95/120/100/110/105/115/100/115/95/120/100/110/105/115/210/120/95/120/95/115/105/115/100/110/105/115/95/115/105/115/100/220/110/105/105/115/105/115/95/115/105/110/100/120/100/115/95/115/105/110/100/120/205/120/100/120/95/115/100/225/110/105/210/230/215/225/210/230/215/125/95/220/215/125/100/215/215/230/215/225/110/105/210/130/95/120/95/115/95/225/110/115/100/110/105/110/100/115/105/115/100/115/100/110/100/120/205/130/95/115/95/115"; 341 | 342 | char pulseLens[2048]; // as strtok is destructive of original string 343 | encodeFDX ? strcpy(pulseLens, pulseLensFDX) : strcpy(pulseLens, pulseLensEM); 344 | // Calculate the number of pulses 345 | for (int i = 0; pulseLens[i] != '\0'; ++i) if (pulseLens[i] == '/') ++pulseCount; 346 | 347 | // get each pulse length and process 348 | char* token = strtok(pulseLens, delimiter); 349 | for (int i = 0; i < pulseCount; i++) { 350 | simPulse = static_cast(atoi(token)); 351 | demodISR(); // send simulated pulse 352 | // get next pulse length from string 353 | token = strtok(nullptr, delimiter); 354 | if (token == nullptr) break; 355 | } 356 | captured = true; 357 | } 358 | 359 | void rfidSetup() { 360 | // set encoding to FDX-B (true) or EM4100 (false) 361 | codeLength = (encodeFDX) ? 128 : 64; // FDX-B is 128 bits, EM4100 is 64 bits, 362 | if (!rfidFreq) rfidFreq = (encodeFDX) ? 134.2 : 125.0; // default antenna clock in Hz 363 | // short pulse length in uS between minPulse & slBoundary 364 | // long pulse length in uS between slBoundary & maxPulse 365 | minPulse = (encodeFDX) ? 85 : 170; 366 | maxPulse = (encodeFDX) ? 320 : 560; 367 | slBoundary = (encodeFDX) ? 180 : 360; // boundary between short and long pulse time in uS. 368 | 369 | captureSize = codeLength * 2; // Capture at 2 x codeLength bit periods to catch at a complete tag regardless of start 370 | LOG_VRB("codeLength %d, minPulse %d, maxPulse %d, slBoundary %d, captureSize %d", codeLength, minPulse, maxPulse, slBoundary, captureSize); 371 | if (!simulation) { 372 | // setup connections to RDM6300 373 | pinMode(rfidDemod, INPUT_PULLUP); 374 | pinMode(rfidClock, OUTPUT); 375 | runClock(); // output square wave clock to RDM6300 376 | attachInterrupt(digitalPinToInterrupt(rfidDemod), demodISR, CHANGE); 377 | if (clearPin) { 378 | pinMode(clearPin, INPUT_PULLUP); 379 | attachInterrupt(digitalPinToInterrupt(clearPin), buttonISR, FALLING); 380 | } 381 | } 382 | sprintf(encodingStr, "%s %0.1fkHz", codeStr[encodeFDX], rfidFreq); 383 | updateLcd(false); 384 | LOG_INF("Detect tag type: %s", encodingStr); 385 | } 386 | 387 | void rfidRead() { 388 | // check if tag available to read 389 | static uint64_t lastTag = 0; 390 | bool haveTag = false; 391 | if (!currentTag) lastTag = 0; 392 | if (captured) { 393 | haveTag = getTag(); 394 | if (!haveTag && !encodeFDX) { 395 | // if EM41000, retry after inverting logic 396 | LOG_VRB("%s", "Retry after logic inversion"); 397 | for (int i = 0; i < bitBufferSize; i++) bitBuffer[i] ^= 1; 398 | haveTag = getTag(); 399 | } 400 | showRawData(haveTag); 401 | captureIndex = pulseIndex = 0; // empty buffers ready for next tag 402 | captured = false; 403 | } else if (simulation) demodSim(); 404 | if (buttonPressed) { 405 | updateLcd(false); 406 | buttonPressed = false; 407 | } 408 | if (haveTag) { 409 | if (currentTag != lastTag) { 410 | // to avoid display flicker, only update if different tag 411 | lastTag = currentTag; 412 | updateLcd(true); 413 | } 414 | } 415 | } 416 | -------------------------------------------------------------------------------- /appGlobals.h: -------------------------------------------------------------------------------- 1 | // Global RFID declarations 2 | // 3 | // s60sc 2023 4 | 5 | #pragma once 6 | #include "globals.h" 7 | 8 | #define ALLOW_SPACES false // set true to allow whitespace in configs.txt key values 9 | 10 | // web server ports 11 | #define HTTP_PORT 80 // app access 12 | #define HTTPS_PORT 443 // secure app access 13 | 14 | /*********************** Fixed defines leave as is ***********************/ 15 | /** Do not change anything below here unless you know what you are doing **/ 16 | 17 | //#define DEV_ONLY // leave commented out 18 | #define STATIC_IP_OCTAL "143" // dev only 19 | #define DEBUG_MEM false // leave as false 20 | #define FLUSH_DELAY 0 // for debugging crashes 21 | #define DBG_ON false // esp debug output 22 | #define DOT_MAX 50 23 | #define HOSTNAME_GRP 0 24 | #define USE_IP6 false 25 | 26 | #define APP_NAME "ESP32_RFID" // max 15 chars 27 | #define APP_VER "2.1" 28 | 29 | #define HTTP_CLIENTS 2 // http, ws 30 | #define MAX_STREAMS 0 31 | #define INDEX_PAGE_PATH DATA_DIR "/RFID" HTML_EXT 32 | #define FILE_NAME_LEN 64 33 | #define IN_FILE_NAME_LEN 128 34 | #define JSON_BUFF_LEN (1024 * 4) // set big enough to hold json string 35 | #define MAX_CONFIGS 100 // > number of entries in configs.txt 36 | #define GITHUB_PATH "/s60sc/ESP32_RFID_Reader/master" 37 | 38 | #define STORAGE LittleFS // One of LittleFS or SD_MMC 39 | #define RAMSIZE (1024 * 8) 40 | #define CHUNKSIZE (1024 * 4) 41 | #define MIN_RAM 8 // min object size stored in ram instead of PSRAM default is 4096 42 | #define MAX_RAM 4096 // max object size stored in ram instead of PSRAM default is 4096 43 | #define TLS_HEAP (64 * 1024) // min free heap for TLS session 44 | #define WARN_HEAP (32 * 1024) // low free heap warning 45 | #define WARN_ALLOC (16 * 1024) // low free max allocatable free heap block 46 | #define MAX_ALERT 1024 47 | 48 | #define INCLUDE_FTP_HFS false // ftp.cpp (file upload) 49 | #define INCLUDE_SMTP false // smtp.cpp (email) 50 | #define INCLUDE_MQTT false // mqtt.cpp 51 | #define INCLUDE_TGRAM false // telegram.cpp 52 | #define INCLUDE_CERTS false // certificates.cpp (https and server certificate checking) 53 | #define INCLUDE_WEBDAV true // webDav.cpp (WebDAV protocol) 54 | 55 | #define IS_IO_EXTENDER false // must be false except for IO_Extender 56 | #define EXTPIN 100 57 | 58 | // to determine if newer data files need to be loaded 59 | #define CFG_VER 1 60 | 61 | #ifdef CONFIG_IDF_TARGET_ESP32S3 62 | #define SERVER_STACK_SIZE (1024 * 8) 63 | #define DS18B20_STACK_SIZE (1024 * 2) 64 | #define STICK_STACK_SIZE (1024 * 4) 65 | #else 66 | #define SERVER_STACK_SIZE (1024 * 4) 67 | #define DS18B20_STACK_SIZE (1024) 68 | #define STICK_STACK_SIZE (1024 * 2) 69 | #endif 70 | #define BATT_STACK_SIZE (1024 * 2) 71 | #define EMAIL_STACK_SIZE (1024 * 6) 72 | #define FS_STACK_SIZE (1024 * 4) 73 | #define LOG_STACK_SIZE (1024 * 3) 74 | #define MQTT_STACK_SIZE (1024 * 4) 75 | #define PING_STACK_SIZE (1024 * 5) 76 | #define SERVO_STACK_SIZE (1024) 77 | #define SUSTAIN_STACK_SIZE (1024 * 4) 78 | #define TGRAM_STACK_SIZE (1024 * 6) 79 | #define TELEM_STACK_SIZE (1024 * 4) 80 | #define UART_STACK_SIZE (1024 * 2) 81 | 82 | // task priorities 83 | #define HTTP_PRI 5 84 | #define TGRAM_PRI 1 85 | #define EMAIL_PRI 1 86 | #define FTP_PRI 1 87 | #define LOG_PRI 1 88 | #define UART_PRI 1 89 | #define BATT_PRI 1 90 | #define IDLEMON_PRI 5 91 | 92 | // devices requiring separate libraries 93 | #define USE_BMP280 false 94 | #define USE DS3231 false 95 | #define USE_SSD1306 false 96 | #define USE_DS18B20 false 97 | 98 | // devices not requiring separate libraries 99 | #define USE_LCD1602 true 100 | #define USE_PCF8591 false 101 | #define USE_MPU6050 false 102 | 103 | 104 | /******************** Function declarations *******************/ 105 | 106 | // global app specific functions 107 | bool checkI2Cdevices(bool showWarn = false); 108 | bool startI2C(); 109 | 110 | void rfidSetup(); 111 | void rfidRead(); 112 | 113 | bool lcdInit(); 114 | void lcdPrint(const char* str); 115 | void lcdClear(); 116 | void lcdHome(); 117 | void lcdDisplay(bool setDisplay); 118 | void lcdBlinkCursor(bool showBlink); 119 | void lcdLineCursor(bool showLine); 120 | void lcdScrollText(bool scrollLeft); 121 | void lcdTextDirection(bool scrollLeft); 122 | void lcdAutoScroll(bool autoScroll); 123 | void lcdSetCursorPos(uint8_t row, uint8_t col); 124 | void lcdBacklight(bool lightOn); 125 | void lcdLoadCustom(uint8_t charLoc, uint8_t charmap[]); 126 | void lcdWriteCustom(uint8_t charLoc); 127 | void updateLcd(bool showTag); 128 | 129 | /******************** Global app declarations *******************/ 130 | 131 | extern const char* appConfig; 132 | 133 | extern int I2C_SDA; 134 | extern int I2C_SCL; 135 | 136 | extern int rfidDemod; // input - demod pin from RDM6300, pullup high 137 | extern int rfidClock; // output - clock pin to RDM6300 138 | extern int clearPin; // input - clear tag display 139 | extern float rfidFreq; // antenna frequency in kHz 140 | extern bool encodeFDX; // false for EM4100, true for FXD-B 141 | extern char encodingStr[]; // encoding type string 142 | extern uint64_t currentTag; 143 | extern char currentTagStr[]; // holds string representation of tag 144 | -------------------------------------------------------------------------------- /appSpecific.cpp: -------------------------------------------------------------------------------- 1 | // RFID specific web & prefs functions 2 | // 3 | // s60sc 2023 4 | 5 | #include "appGlobals.h" 6 | 7 | const size_t prvtkey_len = 0; 8 | const size_t cacert_len = 0; 9 | const char* prvtkey_pem = ""; 10 | const char* cacert_pem = ""; 11 | 12 | void updateLcd(bool showTag) { 13 | // output result to LCD if present 14 | lcdClear(); 15 | lcdSetCursorPos(0, 0); 16 | lcdPrint(encodingStr); 17 | lcdSetCursorPos(1, 0); 18 | if (!showTag) { 19 | currentTag = 0; 20 | currentTagStr[0] = 0; 21 | } 22 | // update config for latest stats to return on next main page call 23 | updateConfigVect("EncodeType", encodingStr); 24 | updateConfigVect("currentTag", currentTagStr); 25 | lcdPrint(currentTagStr); 26 | } 27 | 28 | /************************ webServer callbacks *************************/ 29 | 30 | bool updateAppStatus(const char* variable, const char* value, bool fromUser) { 31 | // update vars from configs and browser input 32 | bool res = true; 33 | int intVal = atoi(value); 34 | float fltVal = atof(value); 35 | if (!strcmp(variable, "rfidDemod")) rfidDemod = intVal; 36 | else if (!strcmp(variable, "rfidClock")) rfidClock = intVal; 37 | else if (!strcmp(variable, "rfidFreq")) rfidFreq = fltVal; 38 | else if (!strcmp(variable, "encodeFDX")) encodeFDX = (bool)intVal; 39 | else if (!strcmp(variable, "I2C_SDA")) I2C_SDA = intVal; 40 | else if (!strcmp(variable, "I2C_SCL")) I2C_SCL = intVal; 41 | else if (!strcmp(variable, "clearPin")) clearPin = intVal; 42 | else if (!strcmp(variable, "resetTag")) { 43 | currentTag = 0; 44 | updateLcd(false); 45 | } 46 | return res; 47 | } 48 | 49 | void appSpecificWsBinHandler(uint8_t* wsMsg, size_t wsMsgLen) { 50 | LOG_ERR("Unexpected websocket binary frame"); 51 | } 52 | 53 | void appSpecificWsHandler(const char* wsMsg) { 54 | // message from web socket 55 | int wsLen = strlen(wsMsg) - 1; 56 | switch ((char)wsMsg[0]) { 57 | case 'X': 58 | break; 59 | case 'H': 60 | // keepalive heartbeat, return status 61 | break; 62 | case 'S': 63 | // status request 64 | buildJsonString(wsLen); // required config number 65 | logPrint("%s\n", jsonBuff); 66 | break; 67 | case 'U': 68 | // update or control request 69 | memcpy(jsonBuff, wsMsg + 1, wsLen); // remove 'U' 70 | parseJson(wsLen); 71 | break; 72 | case 'K': 73 | // kill websocket connection 74 | killSocket(); 75 | break; 76 | default: 77 | LOG_WRN("unknown command %c", (char)wsMsg[0]); 78 | break; 79 | } 80 | } 81 | 82 | void buildAppJsonString(bool filter) { 83 | // build app specific part of json string 84 | char* p = jsonBuff + 1; 85 | *p = 0; 86 | } 87 | 88 | esp_err_t appSpecificWebHandler(httpd_req_t *req, const char* variable, const char* value) { 89 | return ESP_OK; 90 | } 91 | 92 | esp_err_t appSpecificSustainHandler(httpd_req_t* req) { 93 | return ESP_OK; 94 | } 95 | 96 | void externalAlert(const char* subject, const char* message) { 97 | // alert any configured external servers 98 | } 99 | 100 | bool appDataFiles() { 101 | // callback from setupAssist.cpp, for any app specific files 102 | return true; 103 | } 104 | 105 | void doAppPing() {} 106 | 107 | void OTAprereq() { 108 | stopPing(); 109 | } 110 | 111 | /************** default app configuration **************/ 112 | const char* appConfig = R"~( 113 | restart~~99~T~na 114 | ST_SSID~~0~T~Wifi SSID name 115 | ST_Pass~~0~T~Wifi SSID password 116 | ST_ip~~0~T~Static IP address 117 | ST_gw~~0~T~Router IP address 118 | ST_sn~255.255.255.0~0~T~Router subnet 119 | ST_ns1~~0~T~DNS server 120 | ST_ns2~~0~T~Alt DNS server 121 | AP_Pass~~0~T~AP Password 122 | AP_ip~~0~T~AP IP Address if not 192.168.4.1 123 | AP_sn~~0~T~AP subnet 124 | AP_gw~~0~T~AP gateway 125 | allowAP~1~0~C~Allow simultaneous AP 126 | timezone~GMT0~0~T~Timezone string: tinyurl.com/TZstring 127 | logType~0~99~N~Output log selection 128 | Auth_Name~~0~T~Optional user name for web page login 129 | Auth_Pass~~0~T~Optional user name for web page password 130 | wifiTimeoutSecs~30~0~N~WiFi connect timeout (secs) 131 | refreshVal~1~0~N~Web page refresh rate (secs) 132 | rfidDemod~~1~N~Input pin for RFID data 133 | rfidClock~~1~N~Output pin for RFID clock 134 | clearPin~~1~N~Input pin to clear tag display 135 | encodeFDX~0~2~B:EM4100:FXD-B~Encoding type 136 | I2C_SDA~21~1~N~I2C_SDA pin 137 | I2C_SCL~22~1~N~I2C_SCL pin 138 | rfidFreq~~1~N~Antenna frequency in kHz (blank for default) 139 | EncodeType~~2~D~RFID Encoding 140 | currentTag~~2~D~Current Tag ID 141 | resetTag~Clear~2~A~Clear Tag 142 | usePing~1~0~C~Use ping 143 | )~"; 144 | -------------------------------------------------------------------------------- /data/RFID.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | 10 | ESP32_RFID 11 | 12 | 13 | 396 | 397 | 398 | 399 |
400 | 401 | 402 | 403 | 404 |
405 |


406 |
407 |
408 |

409 |
410 |
411 | 412 |
413 |
414 |
415 |
416 |
417 | Select Log 418 |
419 | 420 | 421 | 422 | 423 |
424 |
425 |
426 |
427 | 428 |
429 | 430 | 431 |
432 |
433 |

434 |
435 | 436 | 437 | Refresh Log 438 | 439 |
440 |
441 | 442 | 443 | Clear Log 444 | 445 |
446 |
447 | 448 | 449 | Save 450 | 451 |
452 |
453 | 454 | 455 | Reboot ESP 456 | 457 |
458 |
459 |
460 |
461 |
462 |
463 | 464 |
465 |
466 |
Control
467 |
468 |
469 |
470 | 471 | 472 | Reboot ESP 473 | 474 |
475 |
476 | 477 | 478 | Reload /data 479 | 480 |
481 |
482 | 483 | 484 | Clear NVS 485 | 486 |
487 |
488 |
489 |
Settings
490 |
Press a button to view or modify settings (changed values are not validated)
491 |
Press Save button to make changes permanent
492 |
493 |
494 |
495 | 496 | 497 | Wifi 498 | 499 |
500 |
501 | 502 | 503 | Peripherals 504 | 505 |
506 |
507 | 508 | 509 | Save 510 | 511 |
512 |
513 |
514 |

515 |
516 |
517 | 518 |
519 | 520 |
521 | 522 | 583 | 584 | 585 | -------------------------------------------------------------------------------- /extras/RDM6300.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/s60sc/ESP32_RFID_Reader/7ebddf62a8aac14205afa48076a279e4d8b1adb3/extras/RDM6300.png -------------------------------------------------------------------------------- /extras/antennaFreq.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/s60sc/ESP32_RFID_Reader/7ebddf62a8aac14205afa48076a279e4d8b1adb3/extras/antennaFreq.xlsx -------------------------------------------------------------------------------- /extras/lcd.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/s60sc/ESP32_RFID_Reader/7ebddf62a8aac14205afa48076a279e4d8b1adb3/extras/lcd.jpg -------------------------------------------------------------------------------- /globals.h: -------------------------------------------------------------------------------- 1 | // Global generic declarations 2 | // 3 | // s60sc 2021, 2022 4 | 5 | #include "esp_arduino_version.h" 6 | #pragma once 7 | // to compile with -Wall -Werror=all -Wextra 8 | #pragma GCC diagnostic ignored "-Wunused-function" 9 | #pragma GCC diagnostic ignored "-Wmissing-field-initializers" 10 | //#pragma GCC diagnostic ignored "-Wunused-variable" 11 | //#pragma GCC diagnostic ignored "-Wunused-but-set-variable" 12 | //#pragma GCC diagnostic ignored "-Wignored-qualifiers" 13 | //#pragma GCC diagnostic ignored "-Wclass-memaccess" 14 | #if (ESP_ARDUINO_VERSION_MAJOR >= 3) 15 | #pragma GCC diagnostic ignored "-Wvolatile" 16 | #else 17 | #pragma GCC diagnostic ignored "-Wformat" 18 | #endif 19 | 20 | /******************** Libraries *******************/ 21 | 22 | #include "Arduino.h" 23 | #include 24 | #include "lwip/sockets.h" 25 | #include 26 | #include "ping/ping_sock.h" 27 | #include 28 | #include 29 | #if !CONFIG_IDF_TARGET_ESP32C3 30 | #include 31 | #endif 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | ////#include // v3.x only 38 | ////#include // v3.x only 39 | #include 40 | #include 41 | #include 42 | #include 43 | 44 | // ADC 45 | #define ADC_ATTEN ADC_11db 46 | #define ADC_SAMPLES 16 47 | #if CONFIG_IDF_TARGET_ESP32S3 48 | #define ADC_BITS 13 49 | #define MAX_ADC 8191 // maximum ADC value at given resolution 50 | #else 51 | #define ADC_BITS 12 52 | #define MAX_ADC 4095 // maximum ADC value at given resolution 53 | #endif 54 | #define CENTER_ADC (MAX_ADC / 2) 55 | 56 | // data folder defs 57 | #define DATA_DIR "/data" 58 | #define HTML_EXT ".htm" 59 | #define TEXT_EXT ".txt" 60 | #define JS_EXT ".js" 61 | #define CSS_EXT ".css" 62 | #define ICO_EXT ".ico" 63 | #define SVG_EXT ".svg" 64 | #define JPG_EXT ".jpg" 65 | #define CONFIG_FILE_PATH DATA_DIR "/configs" TEXT_EXT 66 | #define LOG_FILE_PATH DATA_DIR "/log" TEXT_EXT 67 | #define OTA_FILE_PATH DATA_DIR "/OTA" HTML_EXT 68 | #define COMMON_JS_PATH DATA_DIR "/common" JS_EXT 69 | #define WEBDAV "/webdav" 70 | #define GITHUB_HOST "raw.githubusercontent.com" 71 | 72 | #define FILLSTAR "****************************************************************" 73 | #define DELIM '~' 74 | #define ONEMEG (1024 * 1024) 75 | #define MAX_PWD_LEN 64 76 | #define MAX_HOST_LEN 32 77 | #define MAX_IP_LEN 16 78 | #define BOUNDARY_VAL "123456789000000000000987654321" 79 | #define SF_LEN 128 80 | #define WAV_HDR_LEN 44 81 | #define RAM_LOG_LEN (1024 * 7) // size of system message log in bytes stored in slow RTC ram (max 8KB - vars) 82 | #define MIN_STACK_FREE 512 83 | #define STARTUP_FAIL "Startup Failure: " 84 | #define MAX_PAYLOAD_LEN 256 // set bigger than any websocket payload 85 | #define NULL_TEMP -127 86 | #define OneMHz 1000000 87 | #define USECS 1000000 88 | #define MAGIC_NUM 987654321 89 | #define MAX_FAIL 5 90 | 91 | // global mandatory app specific functions, in appSpecific.cpp 92 | bool appDataFiles(); 93 | esp_err_t appSpecificSustainHandler(httpd_req_t* req); 94 | esp_err_t appSpecificWebHandler(httpd_req_t *req, const char* variable, const char* value); 95 | void appSpecificWsBinHandler(uint8_t* wsMsg, size_t wsMsgLen); 96 | void appSpecificWsHandler(const char* wsMsg); 97 | void appSpecificTelegramTask(void* p); 98 | void buildAppJsonString(bool filter); 99 | bool updateAppStatus(const char* variable, const char* value, bool fromUser = true); 100 | 101 | // global general utility functions in utils.cpp / utilsFS.cpp / peripherals.cpp 102 | void buildJsonString(uint8_t filter); 103 | bool calcProgress(int progressVal, int totalVal, int percentReport, uint8_t &pcProgress); 104 | bool changeExtension(char* fileName, const char* newExt); 105 | bool checkAlarm(); 106 | bool checkDataFiles(); 107 | bool checkFreeStorage(); 108 | void checkMemory(const char* source = ""); 109 | uint32_t checkStackUse(TaskHandle_t thisTask, int taskIdx); 110 | void debugMemory(const char* caller); 111 | void dateFormat(char* inBuff, size_t inBuffLen, bool isFolder); 112 | void deleteFolderOrFile(const char* deleteThis); 113 | void devSetup(); 114 | void doAppPing(); 115 | void doRestart(const char* restartStr); 116 | esp_err_t downloadFile(File& df, httpd_req_t* req); 117 | void emailAlert(const char* _subject, const char* _message); 118 | const char* encode64(const char* inp); 119 | const uint8_t* encode64chunk(const uint8_t* inp, int rem); 120 | const char* espErrMsg(esp_err_t errCode); 121 | void externalAlert(const char* subject, const char* message); 122 | bool externalPeripheral(byte pinNum, uint32_t outputData = 0); 123 | esp_err_t extractHeaderVal(httpd_req_t *req, const char* variable, char* value); 124 | esp_err_t extractQueryKeyVal(httpd_req_t *req, char* variable, char* value); 125 | esp_err_t fileHandler(httpd_req_t* req, bool download = false); 126 | void flush_log(bool andClose = false); 127 | char* fmtSize (uint64_t sizeVal); 128 | void forceCrash(); 129 | void formatElapsedTime(char* timeStr, uint32_t timeVal, bool noDays = false); 130 | void formatHex(const char* inData, size_t inLen); 131 | bool fsStartTransfer(const char* fileFolder); 132 | const char* getEncType(int ssidIndex); 133 | void getExtIP(); 134 | time_t getEpoch(); 135 | size_t getFreeStorage(); 136 | bool getLocalNTP(); 137 | float getNTCcelsius(uint16_t resistance, float oldTemp); 138 | void goToSleep(int wakeupPin, bool deepSleep); 139 | bool handleWebDav(httpd_req_t* rreq); 140 | void initStatus(int cfgGroup, int delayVal); 141 | void killSocket(int skt = -99); 142 | void listBuff(const uint8_t* b, size_t len); 143 | bool listDir(const char* fname, char* jsonBuff, size_t jsonBuffLen, const char* extension); 144 | bool loadConfig(); 145 | void logLine(); 146 | void logPrint(const char *fmtStr, ...); 147 | void logSetup(); 148 | void OTAprereq(); 149 | bool parseJson(int rxSize); 150 | void prepPeripherals(); 151 | void prepSMTP(); 152 | bool prepTelegram(); 153 | void prepTemperature(); 154 | void prepUart(); 155 | void prepUpload(); 156 | void reloadConfigs(); 157 | float readTemperature(bool isCelsius, bool onlyDS18 = false); 158 | float readVoltage(); 159 | void remote_log_init(); 160 | void remoteServerClose(WiFiClientSecure& sclient); 161 | bool remoteServerConnect(WiFiClientSecure& sclient, const char* serverName, uint16_t serverPort, const char* serverCert, uint8_t connIdx); 162 | void remoteServerReset(); 163 | void removeChar(char* s, char c); 164 | void replaceChar(char* s, char c, char r); 165 | void reset_log(); 166 | void resetWatchDog(); 167 | bool retrieveConfigVal(const char* variable, char* value); 168 | esp_err_t sendChunks(File df, httpd_req_t *req, bool endChunking = true); 169 | void setFolderName(const char* fname, char* fileName); 170 | void setPeripheralResponse(const byte pinNum, const uint32_t responseData); 171 | void setupADC(); 172 | void showProgress(const char* marker = "."); 173 | void showHttpHeaders(httpd_req_t *req); 174 | uint16_t smoothAnalog(int analogPin, int samples = ADC_SAMPLES); 175 | float smoothSensor(float latestVal, float smoothedVal, float alpha); 176 | void startOTAtask(); 177 | void startSecTimer(bool startTimer); 178 | bool startStorage(); 179 | void startWebServer(); 180 | bool startWifi(bool firstcall = true); 181 | void stopPing(); 182 | void syncToBrowser(uint32_t browserUTC); 183 | bool updateConfigVect(const char* variable, const char* value); 184 | void updateStatus(const char* variable, const char* _value, bool fromUser = true); 185 | esp_err_t uploadHandler(httpd_req_t *req); 186 | void urlDecode(char* inVal); 187 | bool urlEncode(const char* inVal, char* encoded, size_t maxSize); 188 | uint32_t usePeripheral(const byte pinNum, const uint32_t receivedData); 189 | esp_sleep_wakeup_cause_t wakeupResetReason(); 190 | void wsAsyncSend(const char* wsData); 191 | // mqtt.cpp 192 | void startMqttClient(); 193 | void stopMqttClient(); 194 | void mqttPublish(const char* payload); 195 | void mqttPublishPath(const char* suffix, const char* payload); 196 | // telegram.cpp 197 | bool getTgramUpdate(char* response); 198 | bool sendTgramMessage(const char* info, const char* item, const char* parseMode); 199 | bool sendTgramPhoto(uint8_t* photoData, size_t photoSize, const char* caption); 200 | bool sendTgramFile(const char* fileName, const char* contentType, const char* caption); 201 | void tgramAlert(const char* subject, const char* message); 202 | // externalHeartbeat.cpp 203 | void sendExternalHeartbeat(); 204 | 205 | /******************** Global utility declarations *******************/ 206 | 207 | extern char AP_SSID[]; 208 | extern char AP_Pass[]; 209 | extern char AP_ip[]; 210 | extern char AP_sn[]; 211 | extern char AP_gw[]; 212 | 213 | extern char hostName[]; //Host name for ddns 214 | extern char ST_SSID[]; //Router ssid 215 | extern char ST_Pass[]; //Router passd 216 | extern bool useHttps; 217 | extern bool useSecure; 218 | extern bool useFtps; 219 | 220 | extern char ST_ip[]; //Leave blank for dhcp 221 | extern char ST_sn[]; 222 | extern char ST_gw[]; 223 | extern char ST_ns1[]; 224 | extern char ST_ns2[]; 225 | extern char extIP[]; 226 | 227 | extern char Auth_Name[]; 228 | extern char Auth_Pass[]; 229 | 230 | extern int responseTimeoutSecs; // how long to wait for remote server in secs 231 | extern bool allowAP; // set to true to allow AP to startup if cannot reconnect to STA (router) 232 | extern uint32_t wifiTimeoutSecs; // how often to check wifi status 233 | extern uint8_t percentLoaded; 234 | extern int refreshVal; 235 | extern bool dataFilesChecked; 236 | extern char ipExtAddr[]; 237 | extern bool doGetExtIP; 238 | extern bool usePing; // set to false if problems related to this issue occur: https://github.com/s60sc/ESP32-CAM_MJPEG2SD/issues/221 239 | extern bool wsLog; 240 | extern uint16_t sustainId; 241 | 242 | // remote file server 243 | extern char fsServer[]; 244 | extern char ftpUser[]; 245 | extern uint16_t fsPort; 246 | extern char FS_Pass[]; 247 | extern char fsWd[]; 248 | extern bool autoUpload; 249 | extern bool deleteAfter; 250 | extern bool fsUse; 251 | extern char inFileName[]; 252 | 253 | // SMTP server 254 | extern char smtp_login[]; 255 | extern char SMTP_Pass[]; 256 | extern char smtp_email[]; 257 | extern char smtp_server[]; 258 | extern uint16_t smtp_port; 259 | extern bool smtpUse; // whether or not to use smtp 260 | extern int emailCount; 261 | 262 | // Mqtt broker 263 | extern bool mqtt_active; 264 | extern char mqtt_broker[]; 265 | extern char mqtt_port[]; 266 | extern char mqtt_user[]; 267 | extern char mqtt_user_Pass[]; 268 | extern char mqtt_topic_prefix[]; 269 | 270 | // control sending alerts 271 | extern size_t alertBufferSize; 272 | extern byte* alertBuffer; 273 | 274 | // Telegram 275 | extern bool tgramUse; 276 | extern char tgramToken[]; 277 | extern char tgramChatId[]; 278 | extern char tgramHdr[]; 279 | 280 | // certificates 281 | extern const char* git_rootCACertificate; 282 | extern const char* ftps_rootCACertificate; 283 | extern const char* smtp_rootCACertificate; 284 | extern const char* mqtt_rootCACertificate; 285 | extern const char* telegram_rootCACertificate; 286 | extern const char* hfs_rootCACertificate; 287 | extern const char* prvtkey_pem; // app https server private key 288 | extern const char* cacert_pem; // app https server public certificate 289 | 290 | // app status 291 | extern char timezone[]; 292 | extern char ntpServer[]; 293 | extern uint8_t alarmHour; 294 | extern char* jsonBuff; 295 | extern bool dbgVerbose; 296 | extern bool sdLog; 297 | extern char alertMsg[]; 298 | extern int logType; 299 | extern char messageLog[]; 300 | extern uint16_t mlogEnd; 301 | extern bool timeSynchronized; 302 | extern bool monitorOpen; 303 | extern const char* setupPage_html; 304 | extern const char* otaPage_html; 305 | extern SemaphoreHandle_t wsSendMutex; 306 | extern char startupFailure[]; 307 | extern time_t currEpoch; 308 | 309 | extern UBaseType_t uxHighWaterMarkArr[]; 310 | 311 | // SD storage 312 | extern int sdMinCardFreeSpace; // Minimum amount of card free Megabytes before freeSpaceMode action is enabled 313 | extern int sdFreeSpaceMode; // 0 - No Check, 1 - Delete oldest dir, 2 - Upload to ftp and then delete folder on SD 314 | extern bool formatIfMountFailed ; // Auto format the file system if mount failed. Set to false to not auto format. 315 | 316 | #define HTTP_METHOD_STRING(method) \ 317 | (method == HTTP_DELETE) ? "DELETE" : \ 318 | (method == HTTP_GET) ? "GET" : \ 319 | (method == HTTP_HEAD) ? "HEAD" : \ 320 | (method == HTTP_POST) ? "POST" : \ 321 | (method == HTTP_PUT) ? "PUT" : \ 322 | (method == HTTP_CONNECT) ? "CONNECT" : \ 323 | (method == HTTP_OPTIONS) ? "OPTIONS" : \ 324 | (method == HTTP_TRACE) ? "TRACE" : \ 325 | (method == HTTP_COPY) ? "COPY" : \ 326 | (method == HTTP_LOCK) ? "LOCK" : \ 327 | (method == HTTP_MKCOL) ? "MKCOL" : \ 328 | (method == HTTP_MOVE) ? "MOVE" : \ 329 | (method == HTTP_PROPFIND) ? "PROPFIND" : \ 330 | (method == HTTP_PROPPATCH) ? "PROPPATCH" : \ 331 | (method == HTTP_SEARCH) ? "SEARCH" : \ 332 | (method == HTTP_UNLOCK) ? "UNLOCK" : \ 333 | (method == HTTP_BIND) ? "BIND" : \ 334 | (method == HTTP_REBIND) ? "REBIND" : \ 335 | (method == HTTP_UNBIND) ? "UNBIND" : \ 336 | (method == HTTP_ACL) ? "ACL" : \ 337 | (method == HTTP_REPORT) ? "REPORT" : \ 338 | (method == HTTP_MKACTIVITY) ? "MKACTIVITY" : \ 339 | (method == HTTP_CHECKOUT) ? "CHECKOUT" : \ 340 | (method == HTTP_MERGE) ? "MERGE" : \ 341 | (method == HTTP_MSEARCH) ? "MSEARCH" : \ 342 | (method == HTTP_NOTIFY) ? "NOTIFY" : \ 343 | (method == HTTP_SUBSCRIBE) ? "SUBSCRIBE" : \ 344 | (method == HTTP_UNSUBSCRIBE) ? "UNSUBSCRIBE" : \ 345 | (method == HTTP_PATCH) ? "PATCH" : \ 346 | (method == HTTP_PURGE) ? "PURGE" : \ 347 | (method == HTTP_MKCALENDAR) ? "MKCALENDAR" : \ 348 | (method == HTTP_LINK) ? "LINK" : \ 349 | (method == HTTP_UNLINK) ? "UNLINK" : \ 350 | "UNKNOWN" 351 | 352 | enum RemoteFail {SETASSIST, GETEXTIP, TGRAMCONN, FSFTP, EMAILCONN, EXTERNALHB, BLOCKLIST, REMFAILCNT}; // REMFAILCNT always last 353 | 354 | /*********************** Log formatting ************************/ 355 | 356 | //#define USE_LOG_COLORS // uncomment to colorise log messages (eg if using idf.py, but not arduino) 357 | #ifdef USE_LOG_COLORS 358 | #define LOG_COLOR_ERR "\033[0;31m" // red 359 | #define LOG_COLOR_WRN "\033[0;33m" // yellow 360 | #define LOG_COLOR_VRB "\033[0;36m" // cyan 361 | #define LOG_NO_COLOR "\033[0m" 362 | #else 363 | #define LOG_COLOR_ERR 364 | #define LOG_COLOR_WRN 365 | #define LOG_COLOR_VRB 366 | #define LOG_NO_COLOR 367 | #endif 368 | 369 | #define INF_FORMAT(format) "[%s %s] " format "\n", esp_log_system_timestamp(), __FUNCTION__ 370 | #define LOG_INF(format, ...) logPrint(INF_FORMAT(format), ##__VA_ARGS__) 371 | #define LOG_ALT(format, ...) logPrint(INF_FORMAT(format "~"), ##__VA_ARGS__) 372 | #define WRN_FORMAT(format) LOG_COLOR_WRN "[%s WARN %s] " format LOG_NO_COLOR "\n", esp_log_system_timestamp(), __FUNCTION__ 373 | #define LOG_WRN(format, ...) logPrint(WRN_FORMAT(format "~"), ##__VA_ARGS__) 374 | #define ERR_FORMAT(format) LOG_COLOR_ERR "[%s ERROR @ %s:%u] " format LOG_NO_COLOR "\n", esp_log_system_timestamp(), pathToFileName(__FILE__), __LINE__ 375 | #define LOG_ERR(format, ...) logPrint(ERR_FORMAT(format "~"), ##__VA_ARGS__) 376 | #define VRB_FORMAT(format) LOG_COLOR_VRB "[%s VERBOSE @ %s:%u] " format LOG_NO_COLOR "\n", esp_log_system_timestamp(), pathToFileName(__FILE__), __LINE__ 377 | #define LOG_VRB(format, ...) if (dbgVerbose) logPrint(VRB_FORMAT(format), ##__VA_ARGS__) 378 | #define DBG_FORMAT(format) LOG_COLOR_ERR "[###### DBG @ %s:%u] " format LOG_NO_COLOR "\n", pathToFileName(__FILE__), __LINE__ 379 | #define LOG_DBG(format, ...) do { logPrint(DBG_FORMAT(format), ##__VA_ARGS__); delay(FLUSH_DELAY); } while (0) 380 | #define LOG_PRT(buff, bufflen) log_print_buf((const uint8_t*)buff, bufflen) 381 | -------------------------------------------------------------------------------- /periphsI2C.cpp: -------------------------------------------------------------------------------- 1 | 2 | // I2C driver and devices 3 | // 4 | // OLED SSD1306 display 128*64 5 | // PCF8591 ADC 6 | // BM*280 temperature, pressure, altitude, + humidity for BME280 7 | // DS3231 RTC 8 | // LCD 1602 display 2*16 9 | // MPU6050 6 axis accel & gyro 10 | // 11 | // s60sc 2023 12 | 13 | #include "appGlobals.h" 14 | #include 15 | 16 | // global constants 17 | int I2C_SDA; 18 | int I2C_SCL; 19 | 20 | static byte I2CDATA[10]; // store I2C data received or to be sent 21 | 22 | // I2C device names, indexed by address 23 | static bool deviceStatus[128] = {false}; // whether device present 24 | static const char* clientName[128] = { 25 | "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 26 | "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 27 | "", "", "", "", "", "", "", "LCD1602", "", "", "", "", "", "", "", "", 28 | "", "", "", "", "", "", "", "", "", "", "", "", "SSD1306", "SSD1306", "", "", 29 | "", "", "", "", "", "", "", "", "PCF8591", "", "", "", "", "", "", "", 30 | "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 31 | "", "", "", "", "", "", "", "", "DS3231/MPU6050", "MPU6050", "", "", "", "", "", "", 32 | "", "", "", "", "", "", "BM*280", "BM*280", "", "", "", "", "", "", "", ""}; 33 | 34 | 35 | /********************* Generic I2C Utilities ***********************/ 36 | 37 | static bool sendTransmission(int clientAddr, bool scanning) { 38 | // common function used to send request to I2C device and determine outcome 39 | byte result = Wire.endTransmission(true); 40 | /*1: data too long to fit in transmit buffer 41 | 2: received NACK on transmit of address 42 | 3: received NACK on transmit of data 43 | 4: other error, e.g. switched off 44 | 5: i2c busy 45 | 8: unknown pcf8591 status */ 46 | 47 | if (!scanning && result > 0) LOG_WRN("Client %s at 0x%x with connection error: %d", clientName[clientAddr], clientAddr, result); 48 | return (result == 0) ? true : false; 49 | } 50 | 51 | static bool scanI2C() { 52 | // find details of any active I2C devices 53 | LOG_INF("I2C device scanning"); 54 | int nDevices = 0; 55 | for (byte address = 0; address < 127; address++) { 56 | Wire.beginTransmission(address); 57 | // only report error if client device meant to be present 58 | if (sendTransmission(address, true)) { 59 | LOG_INF("I2C device %s present at address: 0x%x", clientName[address], address); 60 | nDevices++; 61 | deviceStatus[address] = true; 62 | } 63 | } 64 | LOG_INF("I2C devices found: %d", nDevices); 65 | return (bool)nDevices; 66 | } 67 | 68 | bool startI2C() { 69 | if (I2C_SDA == I2C_SCL) LOG_ALT("I2C pins not defined"); 70 | else { 71 | // list I2C devices available 72 | Wire.begin(I2C_SDA, I2C_SCL); // join i2c bus as master 73 | if (scanI2C()) return checkI2Cdevices(true); // start available devices 74 | else return false; 75 | } 76 | return false; 77 | } 78 | 79 | static bool getI2Cdata (uint8_t clientAddr, uint8_t controlByte, uint8_t numBytes) { 80 | // send command to I2C client and receive response 81 | // clientAddr is the I2C address 82 | // controlByte is the control instruction 83 | // numBytes is number of bytes to request 84 | Wire.beginTransmission(clientAddr); // select which client to use 85 | Wire.write(controlByte); // send device command 86 | if (sendTransmission(clientAddr, false)) { 87 | // get required number of bytes 88 | Wire.requestFrom (clientAddr, numBytes); 89 | for (int i=0; i=0; i--) Wire.write(I2CDATA[i]); 103 | return sendTransmission(clientAddr, false); 104 | } 105 | 106 | 107 | /***************************************** OLED Display *************************************/ 108 | 109 | #define SSD1306_BIaddr 0x3d // built in oled 110 | #define SSD1306_Extaddr 0x3c // external oled 111 | #if USE_SSD1306 112 | #include "SSD1306Wire.h" 113 | SSD1306Wire oledBI(SSD1306_BIaddr); 114 | SSD1306Wire oledExt(SSD1306_Extaddr); 115 | SSD1306Wire* thisOled; 116 | #endif 117 | 118 | static bool oledOK = false; 119 | bool flipOled = false; // true if oled pins oriented above display 120 | 121 | // OLED SSD1306 display 128*64 122 | void oledLine(const char* msg, int hpos, int vpos, int msgwidth, int fontsize) { 123 | #if (USE_SSD1306) 124 | // display text message on OLED SSD1306 display 125 | // to avoid flicker, only call periodically 126 | // args: message string, horizontal pixel start, vertical pixel start, width to clear, font type 127 | // clear original line 128 | if (oledOK) { 129 | thisOled->setTextAlignment(TEXT_ALIGN_LEFT); 130 | thisOled->setColor(BLACK); 131 | thisOled->fillRect(hpos, vpos, msgwidth, fontsize*5/4); // allow for tails on fonts 132 | // display given text, fontsizes are 10, 16, 24, starting at horiz pixel hpos & vertical pixel vpos 133 | thisOled->setFont(ArialMT_Plain_10); 134 | if (fontsize == 16) thisOled->setFont(ArialMT_Plain_16); 135 | if (fontsize == 24) thisOled->setFont(ArialMT_Plain_24); 136 | thisOled->setColor(WHITE); 137 | thisOled->drawString(hpos, vpos, msg); 138 | } 139 | #endif 140 | } 141 | 142 | static void tellTale() { 143 | #if (USE_SSD1306) 144 | static bool ledState = false; 145 | ledState = !ledState; 146 | static const char* tellTaleStr[] = {"*", ""}; // shows that oled (& I2C) are running 147 | oledLine(tellTaleStr[ledState],124,60,4,10); 148 | #endif 149 | } 150 | 151 | void oledDisplay() { 152 | #if (USE_SSD1306) 153 | if (oledOK) { 154 | tellTale(); // oled telltale 155 | thisOled->display(); 156 | } 157 | #endif 158 | } 159 | 160 | static bool setupOled(bool showWarn) { 161 | #if (USE_SSD1306) 162 | if (!oledOK) { 163 | oledOK = true; 164 | if (deviceStatus[SSD1306_BIaddr]) thisOled = &oledBI; 165 | else if (deviceStatus[SSD1306_Extaddr]) thisOled = &oledExt; 166 | else oledOK = false; 167 | if (oledOK) { 168 | thisOled->end(); 169 | if (thisOled->init()) { if (flipOled) thisOled->flipScreenVertically(); } 170 | else oledOK = false; 171 | } 172 | if (!oledOK && showWarn) LOG_WRN("SSD1306 oled not available"); 173 | } 174 | #endif 175 | return oledOK; 176 | } 177 | 178 | void finalMsg(const char* finalTxt) { 179 | #if (USE_SSD1306) 180 | if (oledOK) { 181 | // display message on persistent oled screen before esp32 goes to sleep 182 | thisOled->resetDisplay(); 183 | oledLine(finalTxt,0,0,128,16); 184 | thisOled->display(); 185 | delay(2000); //// keep tag displayed 186 | } 187 | #endif 188 | } 189 | 190 | /*********************** PCF8591 ************************/ 191 | 192 | #define PCF8591addr 0x48 // PCF8591 ADC 193 | 194 | byte* getPCF8591() { // analog channels 195 | /* 196 | YL-40 module 197 | return the 4 ADC channel 8 bit values, using auto increment control instruction 198 | PC8591 commands: 199 | bits 0-1: channel 0 (00) -> 3 (11) 200 | bit 3: autoincrement 201 | bits 4-5: input programming, separate inputs (00), etc 202 | bit 6: analog out enable 203 | */ 204 | static byte PCF8591[4] = {0}; 205 | if (USE_PCF8591) { 206 | if (deviceStatus[PCF8591addr]) { 207 | if (getI2Cdata(PCF8591addr, 0x44, 5)) { 208 | // need to read 5 bytes, but ignore first as it is previous 0 channel 209 | // order high -> low channels 3 2 1 0 210 | for (int i = 0; i < 4; i++) PCF8591[i] = smoothAnalog(I2CDATA[i + 1]); 211 | } 212 | } else LOG_WRN("PCF8591 ADC not available"); 213 | } 214 | return PCF8591; 215 | } 216 | 217 | /********************************** BMP280 ************************************/ 218 | 219 | #define BMP280_Def 0x76 // BMP280 default address 220 | #define BMP280_Alt 0x77 // BMP280 alternative address 221 | #define SEA_LEVEL 1013.25 // reference pressure in mB/hPa at sea level 222 | 223 | #if USE_BMP280 224 | #include 225 | BMx280I2C bmpDef(BMP280_Def); 226 | BMx280I2C bmpAlt(BMP280_Alt); 227 | BMx280I2C* thisBmp; 228 | #endif 229 | 230 | static bool BMPok = false; 231 | static bool isBME = false; 232 | 233 | float* getBMP280() { // temp & pressure 234 | static float BMP280[4] = {0}; 235 | #if USE_BMP280 236 | if (BMPok) { 237 | if (thisBmp->hasValue()) { 238 | // PSI = pascals * 0.000145 239 | BMP280[0] = thisBmp->getPressure() * 0.01; // pascals to mB/hPa 240 | // ambient temperature (but affected by chip heating) 241 | BMP280[1] = thisBmp->getTemperature(); // celsius 242 | BMP280[2] = 44330.0 * (1.0 - pow(BMP280[0] / SEA_LEVEL, 1.0 / 5.255)); // altitude in meters 243 | if (isBME) BMP280[3] = thisBmp->getHumidity(); // % relative humidity 244 | } 245 | } 246 | #endif 247 | return BMP280; 248 | } 249 | 250 | static bool setupBMP(bool showWarn) { 251 | #if USE_BMP280 252 | // check if BM*280 is available 253 | if (!BMPok) { 254 | BMPok = true; 255 | if (deviceStatus[BMP280_Def]) thisBmp = &bmpDef; 256 | else if (deviceStatus[BMP280_Alt]) thisBmp = &bmpAlt; 257 | else BMPok = false; 258 | if (BMPok) { 259 | BMPok = thisBmp->begin(); 260 | if (BMPok) { 261 | isBME = thisBmp->isBME280(); 262 | thisBmp->resetToDefaults(); 263 | thisBmp->writeOversamplingPressure(BMx280MI::OSRS_P_x16); 264 | thisBmp->writeOversamplingTemperature(BMx280MI::OSRS_T_x16); 265 | if (isBME) thisBmp->writeOversamplingHumidity(BMx280MI::OSRS_H_x16); 266 | thisBmp->measure(); 267 | } 268 | } 269 | if (!BMPok && showWarn) LOG_WRN("BM*280 not available"); 270 | } 271 | #endif 272 | return BMPok; 273 | } 274 | 275 | bool isBME280() { 276 | return isBME; 277 | } 278 | 279 | /********************************** MPU6050 ************************************/ 280 | 281 | // MPU6050 definitions - not gyroscope 282 | #define SENS_2G (32768.0/2.0) // divider for 2G sensitivity reading 283 | #define ACCEL_BYTES 6 // 2 bytes per axis 284 | #define CONFIG 0x1A 285 | #define ACCEL_CONFIG 0x1C 286 | #define ACCEL_XOUT_H 0x3B 287 | #define PWR_MGMT_1 0x6B 288 | 289 | #define MPU6050_HIGH 0x69 // MPU6050 I2C address if AD0 pulled high 290 | #define MPU6050_LOW 0x68 // MPU6050 I2C address if AD0 grounded 291 | 292 | static uint8_t MPU6050addr; 293 | static bool MPU6050ok = false; 294 | 295 | bool sleepMPU6050(bool doSleep) { 296 | // power down or wake up MPU6050 297 | I2CDATA[0] = doSleep ? 0x40 : 0x01; 298 | // PWR_MGMT_1 register set to sleep 299 | return sendI2Cdata(MPU6050addr, PWR_MGMT_1, 1); 300 | } 301 | 302 | static bool setupMPU6050(bool showWarn) { 303 | if (USE_MPU6050 && !MPU6050ok) { 304 | MPU6050ok = true; 305 | if (deviceStatus[MPU6050_HIGH]) MPU6050addr = MPU6050_HIGH; 306 | else if (deviceStatus[MPU6050_LOW]) MPU6050addr = MPU6050_LOW; 307 | else MPU6050ok = false; 308 | if (MPU6050ok) { 309 | // set full range 310 | I2CDATA[0] = 0x00; 311 | MPU6050ok = sendI2Cdata(MPU6050addr, CONFIG, 1); 312 | // wakeup the sensor 313 | if (MPU6050ok) sleepMPU6050(false); 314 | } 315 | if (!MPU6050ok && showWarn) LOG_WRN("MPU6050 6 axis not available"); 316 | } 317 | return MPU6050ok; 318 | } 319 | 320 | float* readMPU6050() { 321 | // get data from MPU6050 322 | static float Gforce[4] = {0}; 323 | if (MPU6050ok) { 324 | if (getI2Cdata(MPU6050addr, ACCEL_XOUT_H, ACCEL_BYTES+2)) { 325 | // read 3 axis accelerometer & temperature 326 | int16_t raw[4]; // X, Y, Z, Temp 327 | for (int i=0; i<4; i++) raw[i] = I2CDATA[i*2] << 8 | I2CDATA[(i*2)+1]; 328 | // each axis G force value, straight down is 1.0 if stationary 329 | for (int i=0; i<3; i++) Gforce[i] = raw[i] / SENS_2G; 330 | // determine gravity from all 3 axes (no linear velocity) 331 | float gXYZ = sqrt(pow(Gforce[0],2)+pow(Gforce[1],2)+pow(Gforce[2],2)); 332 | LOG_VRB("gXYZ should be close to 1, is: %0.2f", gXYZ); 333 | // pitch in degrees - X axis 334 | float ratio = Gforce[0] / gXYZ; 335 | Gforce[0] = (float)((ratio < 0.5) ? 90-fabs(asin(ratio)*RAD_TO_DEG) : fabs(acos(ratio)*RAD_TO_DEG)); 336 | // yaw in degrees - Y axis 337 | ratio = Gforce[1] / gXYZ; 338 | Gforce[1] = (float)((ratio < 0.5) ? 90-fabs(asin(ratio)*RAD_TO_DEG) : fabs(acos(ratio)*RAD_TO_DEG)); 339 | // roll in degrees - Z axis 340 | ratio = Gforce[2] / gXYZ; 341 | Gforce[2] = (float)((ratio < 0.5) ? 90-fabs(asin(ratio)*RAD_TO_DEG) : fabs(acos(ratio)*RAD_TO_DEG)); 342 | // temperature in degrees celsius 343 | Gforce[3] = ((float)raw[3] / 340.0) + 36.53; 344 | } 345 | } 346 | return Gforce; 347 | } 348 | 349 | 350 | /********************************* DS3231 RTC ************************************/ 351 | 352 | #if USE_DS3231 353 | #include "driver/rtc_io.h" 354 | #include 355 | RtcDS3231 Rtc(Wire); 356 | #endif 357 | 358 | #define DS3231_RTC 0x68 // real time clock (address may conflict with MPU6050 359 | 360 | static bool DS3231ok = false; 361 | static volatile bool RTCalarmFlag = false; 362 | 363 | static void IRAM_ATTR RTCalarmISR() { 364 | BaseType_t xHigherPriorityTaskWoken = pdFALSE; 365 | RTCalarmFlag = true; 366 | if (xHigherPriorityTaskWoken == pdTRUE) portYIELD_FROM_ISR(); 367 | } 368 | 369 | static bool setupRTC(bool showWarn) { 370 | #if USE_DS3231 371 | // CONNECTIONS: 372 | // DS3231 SDA --> SDA 373 | // DS3231 SCL --> SCL 374 | // DS3231 VCC --> 3.3v or 5v 375 | // DS3231 GND --> GND 376 | // DS3231 SQW --> Alarm Interrupt Pin - needs pullup 377 | 378 | // set the interrupt pin to input mode with pullup 379 | static bool SQWpin = -1; // needs to be config item 380 | if (!DS3231ok) { 381 | if (deviceStatus[DS3231_RTC]) { 382 | pinMode(SQWpin, INPUT_PULLUP); 383 | 384 | Rtc.Begin(); 385 | RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__); // compilation time 386 | if (!Rtc.IsDateTimeValid()) { 387 | LOG_WRN("RTC lost confidence in the DateTime"); 388 | Rtc.SetDateTime(compiled); 389 | } 390 | 391 | if (!Rtc.GetIsRunning()) { 392 | LOG_WRN("RTC was not actively running, starting now"); 393 | Rtc.SetIsRunning(true); 394 | } 395 | 396 | RtcDateTime now = Rtc.GetDateTime(); 397 | if (now < compiled) { 398 | LOG_WRN("RTC is older than compile time, updating DateTime"); 399 | Rtc.SetDateTime(compiled); 400 | } 401 | 402 | Rtc.Enable32kHzPin(false); 403 | Rtc.SetSquareWavePin(DS3231SquareWavePin_ModeAlarmBoth); // set to be alarm output 404 | Rtc.LatchAlarmsTriggeredFlags(); // throw away any old alarm state before we ran 405 | // setup alarm interrupt 406 | attachInterrupt(digitalPinToInterrupt(SQWpin), RTCalarmISR, FALLING); 407 | 408 | DS3231ok = true; 409 | } else DS3231ok = false; 410 | } 411 | if (!DS3231ok && showWarn) LOG_WRN("DS3231 RTC not available"); 412 | #endif 413 | return DS3231ok; 414 | } 415 | 416 | int cycleRange(int currVal, int minVal, int maxVal) { 417 | // cycle round values 418 | if (currVal < minVal) return maxVal; 419 | if (currVal > maxVal) return minVal; 420 | return currVal; 421 | } 422 | 423 | void setRTCintervalAlarm(int alarmHour, int alarmMin) { 424 | #if USE_DS3231 425 | // Alarm 1 can be once per second, or at given time - seconds accuracy 426 | // Used here for repeated interval time (hours & minutes of interval) - so set multiple times 427 | // occurs on 30 secs mark to avoid clash with setRTCrolloverAlarm() 428 | // args are hours and mins to occur after current time 429 | if (DS3231ok) { 430 | int nextHour = cycleRange(Rtc.GetDateTime().Hour()+alarmHour, 0, 23); 431 | int nextMin = cycleRange(Rtc.GetDateTime().Minute()+alarmMin, 0, 59); 432 | DS3231AlarmOne alarm1(0, nextHour, nextMin, 30, DS3231AlarmOneControl_HoursMinutesSecondsMatch); 433 | Rtc.SetAlarmOne(alarm1); 434 | } 435 | #endif 436 | } 437 | 438 | void setRTCspecificAlarm(int alarmHour, int alarmMin) { 439 | #if USE_DS3231 440 | // Alarm 1 can be once per second, or at given time - seconds accuracy 441 | // Used here for specific time (hours & minutes of day) - so can be set multiple times 442 | // occurs on 30 secs mark to avoid clash with setRTCrolloverAlarm() 443 | // args are specific hour and minute of day to occur 444 | if (DS3231ok) { 445 | DS3231AlarmOne alarm1(0, alarmHour, alarmMin, 30, DS3231AlarmOneControl_HoursMinutesSecondsMatch); 446 | Rtc.SetAlarmOne(alarm1); 447 | } 448 | #endif 449 | } 450 | 451 | void setRTCrolloverAlarm(int alarmHour, int alarmMin) { 452 | #if USE_DS3231 453 | // Alarm 2 can be once per minute, or at a given time - minute accuracy 454 | // Used here for daily rollover alarm - set once 455 | if (DS3231ok) { 456 | DS3231AlarmTwo alarm2(0, alarmHour, alarmMin, DS3231AlarmTwoControl_HoursMinutesMatch); 457 | Rtc.SetAlarmTwo(alarm2); 458 | } 459 | #endif 460 | } 461 | 462 | uint32_t getRTCtime() { 463 | #if USE_DS3231 464 | // get current RTC time as epoch 465 | if (DS3231ok) { 466 | if (!Rtc.IsDateTimeValid()) LOG_WRN("RTC lost confidence in the DateTime!"); 467 | return (uint32_t) Rtc.GetDateTime(); 468 | } 469 | #endif 470 | return 0; 471 | } 472 | 473 | int RTCalarmed() { 474 | // check if RTC alarm occurred and return alarm number 475 | int wasAlarmed = 0; 476 | #if USE_DS3231 477 | if (DS3231ok) { 478 | if (RTCalarmFlag) { 479 | RTCalarmFlag = false; // reset the flag 480 | DS3231AlarmFlag flag = Rtc.LatchAlarmsTriggeredFlags(); // which alarms triggered and reset for next 481 | if (flag & DS3231AlarmFlag_Alarm1) wasAlarmed = 1; 482 | if (flag & DS3231AlarmFlag_Alarm2) wasAlarmed = 2; 483 | } 484 | } 485 | #endif 486 | return wasAlarmed; 487 | } 488 | 489 | float RTCtemperature() { 490 | #if USE_DS3231 491 | // internal temperature of DS3231 492 | if (DS3231ok) { 493 | RtcTemperature temp = Rtc.GetTemperature(); 494 | return temp.AsFloatDegC(); 495 | } 496 | #endif 497 | return 0; 498 | } 499 | 500 | void RTCdatetime(char* datestring, int datestringLen) { 501 | #if USE_DS3231 502 | // return RTC formatted date time string 503 | if (DS3231ok) { 504 | if (!Rtc.IsDateTimeValid()) log_wrn("RTC lost confidence in the DateTime!"); 505 | RtcDateTime dt = Rtc.GetDateTime(); // seconds since jan 1 2000 506 | snprintf(datestring, datestringLen, "%02u/%02u/%04u %02u:%02u:%02u", 507 | dt.Day(), dt.Month(), dt.Year(), dt.Hour(), dt.Minute(), dt.Second()); 508 | } 509 | #endif 510 | } 511 | 512 | 513 | /**************************** LCD1602 ******************************/ 514 | // I2C LCD display: 2 lines, 16 cols 515 | // Derived from https://github.com/arduino-libraries/LiquidCrystal 516 | 517 | #define LCD1602 0x27 // 16 chars by 2 lines LCD 518 | 519 | // commands 520 | #define LCD_CLEARDISPLAY 0x01 521 | #define LCD_RETURNHOME 0x02 522 | #define LCD_ENTRYMODESET 0x04 523 | #define LCD_DISPLAYCONTROL 0x08 524 | #define LCD_CURSORSHIFT 0x10 525 | #define LCD_FUNCTIONSET 0x20 526 | #define LCD_SETCGRAMADDR 0x40 527 | #define LCD_SETDDRAMADDR 0x80 528 | 529 | // flags for display entry mode 530 | #define LCD_ENTRYRIGHT 0x00 531 | #define LCD_ENTRYLEFT 0x02 532 | #define LCD_ENTRYSHIFTINCREMENT 0x01 533 | #define LCD_ENTRYSHIFTDECREMENT 0x00 534 | 535 | // flags for display on/off control 536 | #define LCD_DISPLAYON 0x04 537 | #define LCD_DISPLAYOFF 0x00 538 | #define LCD_CURSORON 0x02 539 | #define LCD_CURSOROFF 0x00 540 | #define LCD_BLINKON 0x01 541 | #define LCD_BLINKOFF 0x00 542 | 543 | // flags for display/cursor shift 544 | #define LCD_DISPLAYMOVE 0x08 545 | #define LCD_CURSORMOVE 0x00 546 | #define LCD_MOVERIGHT 0x04 547 | #define LCD_MOVELEFT 0x00 548 | 549 | // flags for function set 550 | #define LCD_8BITMODE 0x10 551 | #define LCD_4BITMODE 0x00 552 | #define LCD_2LINE 0x08 553 | #define LCD_1LINE 0x00 554 | #define LCD_5x10DOTS 0x04 555 | #define LCD_5x8DOTS 0x00 556 | 557 | // flags for backlight control 558 | #define LCD_BACKLIGHT 0x08 559 | #define LCD_NOBACKLIGHT 0x00 560 | 561 | #define En 0b00000100 // Enable bit 562 | #define Rw 0b00000010 // Read/Write bit 563 | #define Rs 0b00000001 // Register select bit 564 | 565 | #define NUM_ROWS 2 566 | #define NUM_COLS 16 567 | 568 | static bool LCD1602ok = false; 569 | static uint8_t displaycontrol; 570 | static uint8_t displaymode; 571 | static uint8_t backlightval; 572 | 573 | static void lcdWrite(uint8_t data) { 574 | if (LCD1602ok) { 575 | I2CDATA[0] = data | backlightval; 576 | sendI2Cdata(LCD1602, 0, 1); 577 | } 578 | } 579 | 580 | static void writeNibble(uint8_t value) { 581 | lcdWrite(value); 582 | lcdWrite(value | En); // En high 583 | delayMicroseconds(1); // pulse 584 | lcdWrite(value & ~En); // En low 585 | delayMicroseconds(50); // commands need > 37us to settle 586 | } 587 | 588 | static void lcdSend(uint8_t value, uint8_t mode = 0) { 589 | // write either command (mode = 0) or data, as two 4 bit values 590 | if (LCD1602ok) { 591 | writeNibble((value & 0xf0) | mode); 592 | writeNibble(((value << 4 ) & 0xf0) | mode); 593 | } 594 | } 595 | 596 | void lcdBacklight(bool lightOn) { 597 | // Turn the backlight on / off 598 | backlightval = (lightOn) ? LCD_BACKLIGHT : LCD_NOBACKLIGHT; 599 | lcdWrite(backlightval); 600 | } 601 | 602 | void lcdClear() { 603 | // clear display, set cursor position to zero 604 | lcdSend(LCD_CLEARDISPLAY); 605 | delayMicroseconds(2000); 606 | } 607 | 608 | void lcdHome() { 609 | // set cursor position to zero 610 | lcdSend(LCD_RETURNHOME); 611 | delayMicroseconds(2000); 612 | } 613 | 614 | void lcdDisplay(bool setDisplay) { 615 | // Turn the display on / off (not backlight) 616 | if (setDisplay) displaycontrol |= LCD_DISPLAYON; 617 | else displaycontrol &= ~LCD_DISPLAYON; 618 | lcdSend(LCD_DISPLAYCONTROL | displaycontrol); 619 | } 620 | 621 | static bool setupLCD1602(bool showWarn) { 622 | if (USE_LCD1602 && !LCD1602ok) { 623 | if (deviceStatus[LCD1602]) { 624 | LCD1602ok = true; 625 | delay(50); 626 | lcdBacklight(false); 627 | delay(1000); 628 | 629 | // can only use 4 bit mode with PCF8574 as not enough pins for HD44780 8 bit. 630 | // use magic sequence to set it 631 | writeNibble(0x03 << 4); 632 | delayMicroseconds(4500); // wait min 4.1ms 633 | writeNibble(0x03 << 4); 634 | delayMicroseconds(4500); // wait min 4.1ms 635 | writeNibble(0x03 << 4); 636 | delayMicroseconds(150); 637 | writeNibble(0x02 << 4); 638 | 639 | // set initial display format 640 | lcdSend(LCD_FUNCTIONSET | LCD_4BITMODE | LCD_2LINE | LCD_5x8DOTS); 641 | 642 | // turn on display and clear content 643 | displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; 644 | lcdDisplay(true); 645 | lcdClear(); 646 | 647 | // set the entry mode and set cursor position to top left 648 | displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; 649 | lcdSend(LCD_ENTRYMODESET | displaymode); 650 | lcdHome(); 651 | lcdBacklight(true); 652 | } else LCD1602ok = false; 653 | if (!LCD1602ok && showWarn) LOG_WRN("LCD1602 display not available"); 654 | } 655 | return LCD1602ok; 656 | } 657 | 658 | void lcdPrint(const char* str) { 659 | // write string to lcd 660 | for (int i=0; i NUM_ROWS) row = NUM_ROWS - 1; 667 | if (col > NUM_COLS) col = NUM_COLS - 1; 668 | lcdSend(LCD_SETDDRAMADDR | (col + row_offsets[row])); 669 | } 670 | 671 | void lcdLineCursor(bool showLine) { 672 | // Turn the underline cursor on / off 673 | if (showLine) displaycontrol |= LCD_CURSORON; 674 | else displaycontrol &= ~LCD_CURSORON; 675 | lcdSend(LCD_DISPLAYCONTROL | displaycontrol); 676 | } 677 | 678 | void lcdBlinkCursor(bool showBlink) { 679 | // Turn the blinking cursor on / off 680 | if (showBlink) displaycontrol |= LCD_BLINKON; 681 | else displaycontrol &= ~LCD_BLINKON; 682 | lcdSend(LCD_DISPLAYCONTROL | displaycontrol); 683 | } 684 | 685 | void lcdScrollText(bool scrollLeft) { 686 | // scroll the current display left or right one position (no wrapping) 687 | uint8_t moveDir = (scrollLeft) ? LCD_MOVELEFT : LCD_MOVERIGHT; 688 | lcdSend(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | moveDir); 689 | } 690 | 691 | void lcdTextDirection(bool scrollLeft) { 692 | // write text forward or backward from cursor 693 | if (scrollLeft) displaymode &= ~LCD_ENTRYLEFT; 694 | else displaymode |= LCD_ENTRYLEFT; 695 | lcdSend(LCD_ENTRYMODESET | displaymode); 696 | } 697 | 698 | void lcdAutoScroll(bool autoScroll) { 699 | // As each character entered at cursor, scroll previous text left 700 | if (autoScroll) displaymode |= LCD_ENTRYSHIFTINCREMENT; 701 | else displaymode &= ~LCD_ENTRYSHIFTINCREMENT; 702 | lcdSend(LCD_ENTRYMODESET | displaymode); 703 | } 704 | 705 | void lcdLoadCustom(uint8_t charLoc, uint8_t charmap[]) { 706 | // Load custom character 707 | // To create, see https://maxpromer.github.io/LCD-Character-Creator/ 708 | // array of 8 lines of 5 bits, where bits represent pixel on / off 709 | // eg define & load custom char (degrees celsius symbol) 710 | // uint8_t celsius[] = {B01000, B10100, B01011, B00100, B00100, B00100, B00011, B00000}; 711 | // enum customChar {CELSIUS, CC1, CC2, CC3, CC4, CC5, CC6, CC7}; 712 | // lcdLoadCustom(CELSIUS, celsius); 713 | // lcdWriteCustom(CELSIUS); 714 | if (charLoc > 7) LOG_WRN("custom char number %u out of range", charLoc); 715 | else { 716 | charLoc &= 0x7; // CGRAM location to load 0 - 7 717 | lcdSend(LCD_SETCGRAMADDR | (charLoc << 3)); 718 | for (int i=0; i<8; i++) lcdSend(charmap[i], Rs); 719 | } 720 | } 721 | 722 | void lcdWriteCustom(uint8_t charLoc) { 723 | // write one of 8 custom chars 724 | if (charLoc > 7) LOG_WRN("custom char number %u out of range", charLoc); 725 | else lcdSend(charLoc, Rs); 726 | } 727 | 728 | /**************************** Setup ******************************/ 729 | 730 | bool checkI2Cdevices(bool showWarn) { 731 | // check if I2C devices available and setup 732 | setupOled(showWarn); 733 | setupBMP(showWarn); 734 | setupMPU6050(showWarn); 735 | setupRTC(showWarn); 736 | setupLCD1602(showWarn); 737 | return true; 738 | } 739 | -------------------------------------------------------------------------------- /prefs.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Management and storage of application configuration state. 4 | Configuration file stored on flash or SD, except passwords which are stored in NVS 5 | 6 | Workflow: 7 | loadConfig: 8 | file -> loadConfigVect+loadKeyVal -> vector -> getNextKeyVal+updatestatus+updateAppStatus -> vars 9 | retrieveConfigVal (as required) 10 | statusHandler: 11 | vector -> buildJsonString+buildAppJsonString -> browser 12 | controlHandler: 13 | browser -> updateStatus+updateAppStatus -> updateConfigVect -> vector -> saveConfigVect -> file 14 | -> vars 15 | 16 | config field types: 17 | - T : Text 18 | - N : Number 19 | - S : Select options S:lab1:lab2:etc 20 | - C : Checkbox (as slider) 21 | - D : Display only 22 | - R : Range (as slider) R:min:max:step 23 | - B : Radio Buttons B:lab1:lab2:etc 24 | 25 | s60sc 2022, 2024 26 | */ 27 | 28 | #include "appGlobals.h" 29 | 30 | static fs::FS fp = STORAGE; 31 | static std::vector> configs; 32 | static Preferences prefs; 33 | char* jsonBuff = NULL; 34 | static char appId[16]; 35 | static char variable[FILE_NAME_LEN] = {0}; 36 | static char value[IN_FILE_NAME_LEN] = {0}; 37 | time_t currEpoch = 0; 38 | 39 | /********************* generic Config functions ****************************/ 40 | 41 | static bool getNextKeyVal() { 42 | // return next key and value from configs on each call in key order 43 | static int row = 0; 44 | if (row++ < configs.size()) { 45 | strncpy(variable, configs[row - 1][0].c_str(), sizeof(variable) - 1); 46 | strncpy(value, configs[row - 1][1].c_str(), sizeof(value) - 1); 47 | return true; 48 | } 49 | // end of vector reached, reset 50 | row = 0; 51 | return false; 52 | } 53 | 54 | void showConfigVect() { 55 | for (const std::vector& innerVector : configs) { 56 | // Print each element of the inner vector 57 | for (const std::string& element : innerVector) printf("%s,", element.c_str()); 58 | printf("\n"); // Add a newline after each inner vector 59 | } 60 | } 61 | 62 | void reloadConfigs() { 63 | while (getNextKeyVal()) updateStatus(variable, value, false); 64 | #if INCLUDE_MQTT 65 | if (mqtt_active) { 66 | buildJsonString(1); 67 | mqttPublishPath("config", jsonBuff); 68 | } 69 | #endif 70 | } 71 | 72 | static int getKeyPos(std::string thisKey) { 73 | // get location of given key to retrieve other elements 74 | if (configs.empty()) return -1; 75 | auto lower = std::lower_bound(configs.begin(), configs.end(), thisKey, []( 76 | const std::vector &a, const std::string &b) { 77 | return a[0] < b;} 78 | ); 79 | int keyPos = std::distance(configs.begin(), lower); 80 | if (keyPos < configs.size() && thisKey == configs[keyPos][0]) return keyPos; 81 | // else LOG_VRB("Key %s not found", thisKey.c_str()); 82 | return -1; // not found 83 | } 84 | 85 | bool updateConfigVect(const char* variable, const char* value) { 86 | std::string thisKey(variable); 87 | std::string thisVal(value); 88 | int keyPos = getKeyPos(thisKey); 89 | if (keyPos >= 0) { 90 | // update value 91 | if (psramFound()) heap_caps_malloc_extmem_enable(MIN_RAM); 92 | configs[keyPos][1] = thisVal; 93 | if (psramFound()) heap_caps_malloc_extmem_enable(MAX_RAM); 94 | return true; 95 | } 96 | return false; 97 | } 98 | 99 | bool retrieveConfigVal(const char* variable, char* value) { 100 | std::string thisKey(variable); 101 | int keyPos = getKeyPos(thisKey); 102 | if (keyPos >= 0) { 103 | strcpy(value, configs[keyPos][1].c_str()); 104 | return true; 105 | } else { 106 | value[0] = 0; // empty string 107 | LOG_WRN("Key %s not set", variable); 108 | } 109 | return false; 110 | } 111 | 112 | static void loadVectItem(const std::string keyValGrpLabel) { 113 | // extract a config tokens from input and load into configs vector 114 | // comprises key : val : group : type : label 115 | const int tokens = 5; 116 | std::string token[tokens]; 117 | int i = 0; 118 | if (keyValGrpLabel.length()) { 119 | std::istringstream ss(keyValGrpLabel); 120 | while (std::getline(ss, token[i++], DELIM)); 121 | if (i != tokens+1) LOG_ERR("Unable to parse '%s', len %u", keyValGrpLabel.c_str(), keyValGrpLabel.length()); 122 | else { 123 | if (!ALLOW_SPACES) token[1].erase(std::remove(token[1].begin(), token[1].end(), ' '), token[1].end()); 124 | if (token[tokens-1][token[tokens-1].size() - 1] == '\r') token[tokens-1].erase(token[tokens-1].size() - 1); 125 | configs.push_back({token[0], token[1], token[2], token[3], token[4]}); 126 | } 127 | } 128 | if (configs.size() > MAX_CONFIGS) LOG_ERR("Config file entries: %u exceed max: %u", configs.size(), MAX_CONFIGS); 129 | } 130 | 131 | static void saveConfigVect() { 132 | File file = fp.open(CONFIG_FILE_PATH, FILE_WRITE); 133 | char configLine[FILE_NAME_LEN + 101]; 134 | if (!file) LOG_WRN("Failed to save to configs file"); 135 | else { 136 | sort(configs.begin(), configs.end()); 137 | configs.erase(unique(configs.begin(), configs.end()), configs.end()); // remove any dups 138 | for (const auto& row: configs) { 139 | // recreate config file with updated content 140 | if (!strcmp(row[0].c_str() + strlen(row[0].c_str()) - 5, "_Pass")) 141 | // replace passwords with asterisks 142 | snprintf(configLine, FILE_NAME_LEN + 100, "%s%c%.*s%c%s%c%s%c%s\n", row[0].c_str(), DELIM, strlen(row[1].c_str()), FILLSTAR, DELIM, row[2].c_str(), DELIM, row[3].c_str(), DELIM, row[4].c_str()); 143 | else snprintf(configLine, FILE_NAME_LEN + 100, "%s%c%s%c%s%c%s%c%s\n", row[0].c_str(), DELIM, row[1].c_str(), DELIM, row[2].c_str(), DELIM, row[3].c_str(), DELIM, row[4].c_str()); 144 | file.write((uint8_t*)configLine, strlen(configLine)); 145 | } 146 | LOG_ALT("Config file saved"); 147 | } 148 | file.close(); 149 | } 150 | 151 | static bool loadConfigVect() { 152 | // force config vector into psram if available 153 | if (psramFound()) heap_caps_malloc_extmem_enable(MIN_RAM); 154 | configs.reserve(MAX_CONFIGS); 155 | // extract each config line from file 156 | File file = fp.open(CONFIG_FILE_PATH, FILE_READ); 157 | while (file.available()) { 158 | String configLineStr = file.readStringUntil('\n'); 159 | if (configLineStr.length()) loadVectItem(configLineStr.c_str()); 160 | } 161 | // sort vector by key (element 0 in row) 162 | std::sort(configs.begin(), configs.end(), [] ( 163 | const std::vector &a, const std::vector &b) { 164 | return a[0] < b[0];} 165 | ); 166 | // return malloc to default 167 | if (psramFound()) heap_caps_malloc_extmem_enable(MAX_RAM); 168 | file.close(); 169 | return true; 170 | } 171 | 172 | static bool savePrefs(bool retain = true) { 173 | // use preferences for passwords 174 | if (!prefs.begin(APP_NAME, false)) { 175 | LOG_WRN("Failed to save preferences"); 176 | return false; 177 | } 178 | if (!retain) { 179 | prefs.clear(); 180 | LOG_INF("Cleared preferences"); 181 | return true; 182 | } 183 | prefs.putString("ST_SSID", ST_SSID); 184 | prefs.putString("ST_Pass", ST_Pass); 185 | prefs.putString("AP_Pass", AP_Pass); 186 | prefs.putString("Auth_Pass", Auth_Pass); 187 | #if INCLUDE_FTP_HFS 188 | prefs.putString("FS_Pass", FS_Pass); 189 | #endif 190 | #if INCLUDE_SMTP 191 | prefs.putString("SMTP_Pass", SMTP_Pass); 192 | #endif 193 | #if INCLUDE_MQTT 194 | prefs.putString("mqtt_user_Pass", mqtt_user_Pass); 195 | #endif 196 | prefs.end(); 197 | LOG_INF("Saved preferences"); 198 | return true; 199 | } 200 | 201 | static bool loadPrefs() { 202 | // use preferences for passwords 203 | if (!prefs.begin(APP_NAME, false)) { 204 | savePrefs(); // if prefs do not yet exist 205 | return false; 206 | } 207 | if (!strlen(ST_SSID)) { 208 | // first call only after instal 209 | prefs.getString("ST_SSID", ST_SSID, MAX_PWD_LEN); // max 15 chars 210 | updateConfigVect("ST_SSID", ST_SSID); 211 | } 212 | 213 | prefs.getString("ST_Pass", ST_Pass, MAX_PWD_LEN); 214 | updateConfigVect("ST_Pass", ST_Pass); 215 | prefs.getString("AP_Pass", AP_Pass, MAX_PWD_LEN); 216 | prefs.getString("Auth_Pass", Auth_Pass, MAX_PWD_LEN); 217 | #if INCLUDE_FTP_HFS 218 | prefs.getString("FS_Pass", FS_Pass, MAX_PWD_LEN); 219 | #endif 220 | #if INCLUDE_SMTP 221 | prefs.getString("SMTP_Pass", SMTP_Pass, MAX_PWD_LEN); 222 | #endif 223 | #if INCLUDE_MQTT 224 | prefs.getString("mqtt_user_Pass", mqtt_user_Pass, MAX_PWD_LEN); 225 | #endif 226 | prefs.end(); 227 | return true; 228 | } 229 | 230 | void updateStatus(const char* variable, const char* _value, bool fromUser) { 231 | // called from controlHandler() to update app status from changes made on browser 232 | // or from loadConfig() to update app status from stored preferences 233 | bool res = true; 234 | char value[IN_FILE_NAME_LEN]; 235 | strncpy(value, _value, sizeof(value)); 236 | #if INCLUDE_MQTT 237 | if (mqtt_active) { 238 | char buff[(IN_FILE_NAME_LEN * 2)]; 239 | snprintf(buff, IN_FILE_NAME_LEN * 2, "%s=%s", variable, value); 240 | mqttPublish(buff); 241 | } 242 | #endif 243 | 244 | int intVal = atoi(value); 245 | if (!strcmp(variable, "hostName")) strncpy(hostName, value, MAX_HOST_LEN-1); 246 | else if (!strcmp(variable, "ST_SSID")) strncpy(ST_SSID, value, MAX_HOST_LEN-1); 247 | else if (!strcmp(variable, "ST_Pass") && value[0] != '*') strncpy(ST_Pass, value, MAX_PWD_LEN-1); 248 | 249 | else if (!strcmp(variable, "ST_ip")) strncpy(ST_ip, value, MAX_IP_LEN-1); 250 | else if (!strcmp(variable, "ST_gw")) strncpy(ST_gw, value, MAX_IP_LEN-1); 251 | else if (!strcmp(variable, "ST_sn")) strncpy(ST_sn, value, MAX_IP_LEN-1); 252 | else if (!strcmp(variable, "ST_ns1")) strncpy(ST_ns1, value, MAX_IP_LEN-1); 253 | else if (!strcmp(variable, "ST_ns1")) strncpy(ST_ns2, value, MAX_IP_LEN-1); 254 | else if (!strcmp(variable, "Auth_Name")) strncpy(Auth_Name, value, MAX_HOST_LEN-1); 255 | else if (!strcmp(variable, "Auth_Pass") && value[0] != '*') strncpy(Auth_Pass, value, MAX_PWD_LEN-1); 256 | else if (!strcmp(variable, "AP_ip")) strncpy(AP_ip, value, MAX_IP_LEN-1); 257 | else if (!strcmp(variable, "AP_gw")) strncpy(AP_gw, value, MAX_IP_LEN-1); 258 | else if (!strcmp(variable, "AP_sn")) strncpy(AP_sn, value, MAX_IP_LEN-1); 259 | else if (!strcmp(variable, "AP_SSID")) strncpy(AP_SSID, value, MAX_HOST_LEN-1); 260 | else if (!strcmp(variable, "AP_Pass") && value[0] != '*') strncpy(AP_Pass, value, MAX_PWD_LEN-1); 261 | else if (!strcmp(variable, "allowAP")) allowAP = (bool)intVal; 262 | else if (!strcmp(variable, "useHttps")) useHttps = (bool)intVal; 263 | else if (!strcmp(variable, "useSecure")) useSecure = (bool)intVal; 264 | else if (!strcmp(variable, "doGetExtIP")) doGetExtIP = (bool)intVal; 265 | else if (!strcmp(variable, "extIP")) strncpy(extIP, value, MAX_IP_LEN-1); 266 | #if INCLUDE_TGRAM 267 | else if (!strcmp(variable, "tgramUse")) { 268 | tgramUse = (bool)intVal; 269 | if (tgramUse) { 270 | #if INCLUDE_SMTP 271 | smtpUse = false; 272 | #endif 273 | updateConfigVect("smtpUse", "0"); 274 | } 275 | } 276 | else if (!strcmp(variable, "tgramToken")) strncpy(tgramToken, value, MAX_PWD_LEN-1); 277 | else if (!strcmp(variable, "tgramChatId")) strncpy(tgramChatId, value, MAX_IP_LEN-1); 278 | #endif 279 | #if INCLUDE_FTP_HFS 280 | else if (!strcmp(variable, "fsServer")) strncpy(fsServer, value, MAX_HOST_LEN-1); 281 | else if (!strcmp(variable, "fsPort")) fsPort = intVal; 282 | else if (!strcmp(variable, "ftpUser")) strncpy(ftpUser, value, MAX_HOST_LEN-1); 283 | else if (!strcmp(variable, "FS_Pass") && value[0] != '*') strncpy(FS_Pass, value, MAX_PWD_LEN-1); 284 | else if (!strcmp(variable, "fsWd")) strncpy(fsWd, value, FILE_NAME_LEN-1); 285 | else if(!strcmp(variable, "fsUse")) fsUse = (bool)intVal; 286 | else if(!strcmp(variable, "autoUpload")) autoUpload = (bool)intVal; 287 | else if(!strcmp(variable, "deleteAfter")) deleteAfter = (bool)intVal; 288 | else if(!strcmp(variable, "useFtps")) useFtps = (bool)intVal; 289 | #endif 290 | #if INCLUDE_SMTP 291 | else if (!strcmp(variable, "smtpUse")) { 292 | smtpUse = (bool)intVal; 293 | if (smtpUse) { 294 | #if INCLUDE_TGRAM 295 | tgramUse = false; 296 | #endif 297 | updateConfigVect("tgramUse", "0"); 298 | } 299 | } 300 | else if (!strcmp(variable, "smtp_login")) strncpy(smtp_login, value, MAX_HOST_LEN-1); 301 | else if (!strcmp(variable, "smtp_server")) strncpy(smtp_server, value, MAX_HOST_LEN-1); 302 | else if (!strcmp(variable, "smtp_email")) strncpy(smtp_email, value, MAX_HOST_LEN-1); 303 | else if (!strcmp(variable, "SMTP_Pass") && value[0] != '*') strncpy(SMTP_Pass, value, MAX_PWD_LEN-1); 304 | else if (!strcmp(variable, "smtp_port")) smtp_port = intVal; 305 | else if (!strcmp(variable, "smtpMaxEmails")) alertMax = intVal; 306 | #endif 307 | #if INCLUDE_MQTT 308 | else if (!strcmp(variable, "mqtt_active")) { 309 | mqtt_active = (bool)intVal; 310 | if (!mqtt_active) stopMqttClient(); 311 | } 312 | else if (!strcmp(variable, "mqtt_broker")) strncpy(mqtt_broker, value, MAX_HOST_LEN-1); 313 | else if (!strcmp(variable, "mqtt_port")) strncpy(mqtt_port, value, 4); 314 | else if (!strcmp(variable, "mqtt_user")) strncpy(mqtt_user, value, MAX_HOST_LEN-1); 315 | else if (!strcmp(variable, "mqtt_user_Pass") && value[0] != '*') strncpy(mqtt_user_Pass, value, MAX_PWD_LEN-1); 316 | else if (!strcmp(variable, "mqtt_topic_prefix")) strncpy(mqtt_topic_prefix, value, (FILE_NAME_LEN/2)-1); 317 | #endif 318 | 319 | // Other settings 320 | else if (!strcmp(variable, "clockUTC")) syncToBrowser((uint32_t)intVal); 321 | else if (!strcmp(variable, "timezone")) strncpy(timezone, value, FILE_NAME_LEN-1); 322 | else if (!strcmp(variable, "ntpServer")) strncpy(ntpServer, value, FILE_NAME_LEN-1); 323 | else if (!strcmp(variable, "alarmHour")) alarmHour = (uint8_t)intVal; 324 | else if (!strcmp(variable, "sdMinCardFreeSpace")) sdMinCardFreeSpace = intVal; 325 | else if (!strcmp(variable, "sdFreeSpaceMode")) sdFreeSpaceMode = intVal; 326 | else if (!strcmp(variable, "responseTimeoutSecs")) responseTimeoutSecs = intVal; 327 | else if (!strcmp(variable, "wifiTimeoutSecs")) wifiTimeoutSecs = intVal; 328 | else if (!strcmp(variable, "usePing")) usePing = (bool)intVal; 329 | else if (!strcmp(variable, "dbgVerbose")) { 330 | dbgVerbose = (intVal) ? true : false; 331 | Serial.setDebugOutput(dbgVerbose); 332 | } 333 | else if (!strcmp(variable, "logType")) { 334 | logType = intVal; 335 | wsLog = (logType == 1) ? true : false; 336 | remote_log_init(); 337 | } 338 | else if (!strcmp(variable, "sdLog")) { 339 | sdLog = (bool)intVal; 340 | remote_log_init(); 341 | } 342 | else if (!strcmp(variable, "refreshVal")) refreshVal = intVal; 343 | else if (!strcmp(variable, "formatIfMountFailed")) formatIfMountFailed = (bool)intVal; 344 | else if (!strcmp(variable, "resetLog")) reset_log(); 345 | else if (!strcmp(variable, "clear")) savePrefs(false); // /control?clear=1 346 | else if (!strcmp(variable, "deldata")) { 347 | if (intVal) deleteFolderOrFile(DATA_DIR); // entire folder 348 | else { 349 | // manually specified file, eg control?deldata=favicon.ico 350 | char delFile[FILE_NAME_LEN]; 351 | int dlen = snprintf(delFile, FILE_NAME_LEN, "%s/%s", DATA_DIR, value); 352 | if (dlen > FILE_NAME_LEN) LOG_WRN("File name %s too long", value); 353 | else deleteFolderOrFile(delFile); 354 | } 355 | doRestart("user requested restart after data deletion"); 356 | } 357 | else if (!strcmp(variable, "save")) { 358 | if (intVal) savePrefs(); 359 | saveConfigVect(); 360 | } else { 361 | res = updateAppStatus(variable, value, fromUser); 362 | if (!res) LOG_VRB("Unrecognised config: %s", variable); 363 | } 364 | if (res) updateConfigVect(variable, value); 365 | } 366 | 367 | void buildJsonString(uint8_t filter) { 368 | // called from statusHandler() to build json string with current status to return to browser 369 | char* p = jsonBuff; 370 | *p++ = '{'; 371 | if (filter < 2) { 372 | // build json string for main page refresh 373 | buildAppJsonString((bool)filter); 374 | p += strlen(jsonBuff) - 1; 375 | p += sprintf(p, "\"cfgGroup\":\"-1\","); 376 | p += sprintf(p, "\"alertMsg\":\"%s\",", alertMsg); 377 | alertMsg[0] = 0; 378 | // generic footer 379 | currEpoch = getEpoch(); 380 | p += sprintf(p, "\"clockUTC\":\"%lu\",", (uint32_t)currEpoch); 381 | char timeBuff[20]; 382 | strftime(timeBuff, 20, "%Y-%m-%d %H:%M:%S", localtime(&currEpoch)); 383 | p += sprintf(p, "\"clock\":\"%s\",", timeBuff); 384 | formatElapsedTime(timeBuff, millis()); 385 | p += sprintf(p, "\"up_time\":\"%s\",", timeBuff); 386 | p += sprintf(p, "\"free_heap\":\"%s\",", fmtSize(ESP.getFreeHeap())); 387 | p += sprintf(p, "\"wifi_rssi\":\"%i dBm\",", WiFi.RSSI() ); 388 | p += sprintf(p, "\"fw_version\":\"%s\",", APP_VER); 389 | p += sprintf(p, "\"macAddressEfuse\":\"%012llX\",", ESP.getEfuseMac() ); 390 | p += sprintf(p, "\"macAddressWiFi\":\"%s\",", WiFi.macAddress().c_str() ); 391 | p += sprintf(p, "\"extIP\":\"%s\",", extIP); 392 | p += sprintf(p, "\"httpPort\":\"%u\",", HTTP_PORT); 393 | p += sprintf(p, "\"httpsPort\":\"%u\",", HTTPS_PORT); 394 | if (!filter) { 395 | // populate first part of json string from config vect 396 | for (const auto& row : configs) 397 | p += sprintf(p, "\"%s\":\"%s\",", row[0].c_str(), row[1].c_str()); 398 | p += sprintf(p, "\"logType\":\"%d\",", logType); 399 | // passwords stored in prefs on NVS 400 | p += sprintf(p, "\"ST_Pass\":\"%.*s\",", strlen(ST_Pass), FILLSTAR); 401 | p += sprintf(p, "\"AP_Pass\":\"%.*s\",", strlen(AP_Pass), FILLSTAR); 402 | p += sprintf(p, "\"Auth_Pass\":\"%.*s\",", strlen(Auth_Pass), FILLSTAR); 403 | #if INCLUDE_FTP_HFS 404 | p += sprintf(p, "\"FS_Pass\":\"%.*s\",", strlen(FS_Pass), FILLSTAR); 405 | #endif 406 | #if INCLUDE_SMTP 407 | p += sprintf(p, "\"SMTP_Pass\":\"%.*s\",", strlen(SMTP_Pass), FILLSTAR); 408 | #endif 409 | #if INCLUDE_MQTT 410 | p += sprintf(p, "\"mqtt_user_Pass\":\"%.*s\",", strlen(mqtt_user_Pass), FILLSTAR); 411 | #endif 412 | } 413 | } else { 414 | // build json string for requested config group 415 | updateAppStatus("custom", ""); 416 | uint8_t cfgGroup = filter - 10; // filter number is length of url query string, config group number is length of string - 10 417 | p += sprintf(p, "\"cfgGroup\":\"%u\",", cfgGroup); 418 | char pwdHide[MAX_PWD_LEN] = {0, }; // used to replace password value with asterisks 419 | for (const auto& row : configs) { 420 | if (atoi(row[2].c_str()) == cfgGroup) { 421 | int valSize = strlen(row[1].c_str()); 422 | if (valSize < sizeof(pwdHide)) { 423 | strncpy(pwdHide, FILLSTAR, valSize); 424 | pwdHide[valSize] = 0; 425 | } 426 | // for each config item, list - key:value, key:label text, key:type identifier 427 | p += sprintf(p, "\"%s\":\"%s\",\"lab%s\":\"%s\",\"typ%s\":\"%s\",", row[0].c_str(), 428 | strstr(row[0].c_str(), "_Pass") == NULL ? row[1].c_str() : pwdHide, row[0].c_str(), row[4].c_str(), row[0].c_str(), row[3].c_str()); 429 | } 430 | } 431 | } 432 | *p = 0; 433 | *(--p) = '}'; // overwrite final comma 434 | if (p - jsonBuff >= JSON_BUFF_LEN) LOG_ERR("jsonBuff overrun by: %u bytes", (p - jsonBuff) - JSON_BUFF_LEN); 435 | } 436 | 437 | void initStatus(int cfgGroup, int delayVal) { 438 | // update app status for given config group 439 | for (const auto& row : configs) { 440 | if (atoi(row[2].c_str()) == cfgGroup) updateAppStatus(row[0].c_str(), row[1].c_str()); 441 | delay(delayVal); 442 | } 443 | } 444 | 445 | static bool checkConfigFile() { 446 | // check config file exists 447 | File file; 448 | if (!STORAGE.exists(CONFIG_FILE_PATH)) { 449 | // create from default in appGlobals.h 450 | file = fp.open(CONFIG_FILE_PATH, FILE_WRITE); 451 | if (file) { 452 | // apply initial defaults 453 | file.write((uint8_t*)appConfig, strlen(appConfig)); 454 | sprintf(hostName, "%s_%012llX", APP_NAME, ESP.getEfuseMac()); 455 | char cfg[100]; 456 | sprintf(cfg, "appId~%s~99~~na\n", APP_NAME); 457 | file.write((uint8_t*)cfg, strlen(cfg)); 458 | sprintf(cfg, "hostName~%s~%d~T~Device host name\n", hostName, HOSTNAME_GRP); 459 | file.write((uint8_t*)cfg, strlen(cfg)); 460 | sprintf(cfg, "AP_SSID~%s~0~T~AP SSID name\n", hostName); 461 | file.write((uint8_t*)cfg, strlen(cfg)); 462 | sprintf(cfg, "cfgVer~%u~99~T~na\n", CFG_VER); 463 | file.write((uint8_t*)cfg, strlen(cfg)); 464 | file.close(); 465 | LOG_INF("Created %s from local store", CONFIG_FILE_PATH); 466 | return true; 467 | } else { 468 | LOG_WRN("Failed to create file %s", CONFIG_FILE_PATH); 469 | return false; 470 | } 471 | } 472 | 473 | // file exists, check if valid 474 | bool goodFile = true; 475 | file = fp.open(CONFIG_FILE_PATH, FILE_READ); 476 | if (!file || !file.size()) { 477 | LOG_WRN("Failed to load file %s", CONFIG_FILE_PATH); 478 | goodFile = false; 479 | } else { 480 | // check file contents are valid 481 | loadConfigVect(); 482 | if (!retrieveConfigVal("cfgVer", appId)) goodFile = false; // obsolete config file 483 | else if (atoi(appId) != CFG_VER) goodFile = false; // outdated config file 484 | if (!goodFile) LOG_WRN("Delete old %s", CONFIG_FILE_PATH); 485 | else { 486 | // cleanup storage if config file for different app 487 | retrieveConfigVal("appId", appId); 488 | if (strcmp(appId, APP_NAME)) { 489 | LOG_WRN("Delete invalid %s, expected %s, got %s", CONFIG_FILE_PATH, APP_NAME, appId); 490 | savePrefs(false); 491 | goodFile = false; 492 | } 493 | } 494 | configs.clear(); 495 | } 496 | file.close(); 497 | if (!goodFile) { 498 | deleteFolderOrFile(DATA_DIR); 499 | STORAGE.mkdir(DATA_DIR); 500 | } 501 | return goodFile; 502 | } 503 | 504 | bool loadConfig() { 505 | // called on startup 506 | LOG_INF("Load config"); 507 | if (jsonBuff == NULL) { 508 | jsonBuff = psramFound() ? (char*)ps_malloc(JSON_BUFF_LEN) : (char*)malloc(JSON_BUFF_LEN); 509 | } 510 | bool res = checkConfigFile(); 511 | if (!res) res = checkConfigFile(); // to recreate file if deleted on first call 512 | if (res) { 513 | loadConfigVect(); 514 | //showConfigVect(); 515 | loadPrefs(); // overwrites any corresponding entries in config 516 | // load variables from stored config vector 517 | reloadConfigs(); 518 | debugMemory("loadConfig"); 519 | return true; 520 | } 521 | // no config file 522 | snprintf(startupFailure, SF_LEN, STARTUP_FAIL "No file: %s", CONFIG_FILE_PATH); 523 | return false; 524 | } 525 | -------------------------------------------------------------------------------- /setupAssist.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Assist setup for new app installations 3 | // original provided by gemi254 4 | // 5 | // s60sc 2023 6 | 7 | #include "appGlobals.h" 8 | 9 | #if (!INCLUDE_CERTS) 10 | const char* git_rootCACertificate = ""; 11 | #endif 12 | 13 | static fs::FS fp = STORAGE; 14 | 15 | static bool wgetFile(const char* filePath) { 16 | // download required data file from github repository and store 17 | bool res = false; 18 | if (fp.exists(filePath)) { 19 | // if file exists but is empty, delete it to allow re-download 20 | File f = fp.open(filePath, FILE_READ); 21 | size_t fSize = f.size(); 22 | f.close(); 23 | if (!fSize) fp.remove(filePath); 24 | } 25 | if (!fp.exists(filePath)) { 26 | char downloadURL[150]; 27 | snprintf(downloadURL, 150, "%s%s", GITHUB_PATH, filePath); 28 | File f = fp.open(filePath, FILE_WRITE); 29 | if (f) { 30 | WiFiClientSecure wclient; 31 | if (remoteServerConnect(wclient, GITHUB_HOST, HTTPS_PORT, git_rootCACertificate, SETASSIST)) { 32 | HTTPClient https; 33 | if (https.begin(wclient, GITHUB_HOST, HTTPS_PORT, downloadURL, true)) { 34 | LOG_INF("Downloading %s from %s", filePath, downloadURL); 35 | int httpCode = https.GET(); 36 | int fileSize = 0; 37 | if (httpCode == HTTP_CODE_OK) { 38 | fileSize = https.writeToStream(&f); 39 | if (fileSize <= 0) { 40 | LOG_WRN("Download failed: writeToStream - %s", https.errorToString(fileSize).c_str()); 41 | httpCode = 0; 42 | } else LOG_INF("Downloaded %s, size %s", filePath, fmtSize(fileSize)); 43 | } else LOG_WRN("Download failed, error: %s", https.errorToString(httpCode).c_str()); 44 | https.end(); 45 | f.close(); 46 | if (httpCode == HTTP_CODE_OK) { 47 | if (!strcmp(filePath, CONFIG_FILE_PATH)) doRestart("Config file downloaded"); 48 | res = true; 49 | } else { 50 | LOG_WRN("HTTP Get failed with code: %d", httpCode); 51 | fp.remove(filePath); 52 | } 53 | } 54 | } 55 | remoteServerClose(wclient); 56 | } else LOG_WRN("Open failed: %s", filePath); 57 | } else res = true; 58 | return res; 59 | } 60 | 61 | bool checkDataFiles() { 62 | // Download any missing data files 63 | bool res = false; 64 | if (strlen(GITHUB_PATH)) { 65 | res = wgetFile(COMMON_JS_PATH); 66 | if (res) res = wgetFile(INDEX_PAGE_PATH); 67 | if (res) res = appDataFiles(); 68 | } else res = true; // no download needed 69 | return res; 70 | } 71 | 72 | const char* setupPage_html = R"~( 73 | 74 | 75 | 76 | 77 | 78 | Application setup 79 | 80 | 91 | 92 |
93 |
94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 111 |
Wifi setup..
SSID 
Password 
109 |   110 |
112 |

113 |
114 | 115 | 116 | )~"; 117 | 118 | const char* otaPage_html = R"~( 119 | 120 | 121 | OTA 122 | 131 | 132 | 133 |
134 |

Upload data file or bin file to ESP32

135 |
136 | Go Back 137 |


138 |
139 |
140 |
141 | % 142 |

143 |

144 |
145 | 146 | 191 | 192 | 193 | )~"; 194 | -------------------------------------------------------------------------------- /utilsFS.cpp: -------------------------------------------------------------------------------- 1 | // General purpose SD card and flash storage utilities 2 | // 3 | // s60sc 2021, 2022 4 | 5 | #include "appGlobals.h" 6 | 7 | // Storage settings 8 | int sdMinCardFreeSpace = 100; // Minimum amount of card free Megabytes before sdFreeSpaceMode action is enabled 9 | int sdFreeSpaceMode = 1; // 0 - No Check, 1 - Delete oldest dir, 2 - Upload oldest dir to FTP/HFS and then delete on SD 10 | bool formatIfMountFailed = true; // Auto format the file system if mount failed. Set to false to not auto format. 11 | static fs::FS fp = STORAGE; 12 | 13 | // hold sorted list of filenames/folders names in order of newest first 14 | static std::vector fileVec; 15 | static auto currentDir = "/~current"; 16 | static auto previousDir = "/~previous"; 17 | static char fsType[10] = {0}; 18 | 19 | static void infoSD() { 20 | #if !(CONFIG_IDF_TARGET_ESP32C3) 21 | uint8_t cardType = SD_MMC.cardType(); 22 | if (cardType == CARD_NONE) LOG_WRN("No SD card attached"); 23 | else { 24 | char typeStr[8] = "UNKNOWN"; 25 | if (cardType == CARD_MMC) strcpy(typeStr, "MMC"); 26 | else if (cardType == CARD_SD) strcpy(typeStr, "SDSC"); 27 | else if (cardType == CARD_SDHC) strcpy(typeStr, "SDHC"); 28 | LOG_INF("SD card type %s, Size: %s", typeStr, fmtSize(SD_MMC.cardSize())); 29 | } 30 | #endif 31 | } 32 | 33 | static bool prepSD_MMC() { 34 | bool res = false; 35 | #if !(CONFIG_IDF_TARGET_ESP32C3) 36 | /* open SD card in MMC 1 bit mode 37 | MMC4 MMC1 ESP32 ESP32S3 38 | D2 12 39 | D3 .. 13 40 | CMD CMD 15 38 41 | CLK CLK 14 39 42 | D0 D0 2 40 43 | D1 4 44 | */ 45 | if (psramFound()) heap_caps_malloc_extmem_enable(MIN_RAM); // small number to force vector into psram 46 | fileVec.reserve(1000); 47 | if (psramFound()) heap_caps_malloc_extmem_enable(MAX_RAM); 48 | #if CONFIG_IDF_TARGET_ESP32S3 49 | #if !defined(SD_MMC_CLK) 50 | LOG_WRN("SD card pins not defined"); 51 | return false; 52 | #else 53 | SD_MMC.setPins(SD_MMC_CLK, SD_MMC_CMD, SD_MMC_D0); 54 | #endif 55 | #endif 56 | 57 | res = SD_MMC.begin("/sdcard", true, formatIfMountFailed); 58 | #if defined(CAMERA_MODEL_AI_THINKER) 59 | pinMode(4, OUTPUT); 60 | digitalWrite(4, 0); // set lamp pin fully off as sd_mmc library still initialises pin 4 in 1 line mode 61 | #endif 62 | if (res) { 63 | fp.mkdir(DATA_DIR); 64 | infoSD(); 65 | res = true; 66 | } else { 67 | LOG_WRN("SD card mount failed"); 68 | res = false; 69 | } 70 | #endif 71 | return res; 72 | } 73 | 74 | static void listFolder(const char* rootDir) { 75 | // list contents of folder 76 | LOG_INF("Sketch size %s", fmtSize(ESP.getSketchSize())); 77 | File root = fp.open(rootDir); 78 | File file = root.openNextFile(); 79 | while (file) { 80 | LOG_INF("File: %s, size: %s", file.path(), fmtSize(file.size())); 81 | file = root.openNextFile(); 82 | } 83 | char totalBytes[20]; 84 | strcpy(totalBytes, fmtSize(STORAGE.totalBytes())); 85 | LOG_INF("%s: %s used of %s", fsType, fmtSize(STORAGE.usedBytes()), totalBytes); 86 | } 87 | 88 | bool startStorage() { 89 | // start required storage device (SD card or flash file system) 90 | bool res = false; 91 | #if !(CONFIG_IDF_TARGET_ESP32C3) 92 | if ((fs::SDMMCFS*)&STORAGE == &SD_MMC) { 93 | strcpy(fsType, "SD_MMC"); 94 | res = prepSD_MMC(); 95 | if (res) listFolder(DATA_DIR); 96 | else snprintf(startupFailure, SF_LEN, STARTUP_FAIL "Check SD card inserted"); 97 | debugMemory("startStorage"); 98 | return res; 99 | } 100 | #endif 101 | // One of SPIFFS or LittleFS 102 | if (!strlen(fsType)) { 103 | #ifdef _SPIFFS_H_ 104 | if ((fs::SPIFFSFS*)&STORAGE == &SPIFFS) { 105 | strcpy(fsType, "SPIFFS"); 106 | res = SPIFFS.begin(formatIfMountFailed); 107 | } 108 | #endif 109 | #ifdef _LITTLEFS_H_ 110 | if ((fs::LittleFSFS*)&STORAGE == &LittleFS) { 111 | strcpy(fsType, "LittleFS"); 112 | res = LittleFS.begin(formatIfMountFailed); 113 | // create data folder if not present 114 | if (res) LittleFS.mkdir(DATA_DIR); 115 | } 116 | #endif 117 | if (res) { 118 | // list details of files on file system 119 | const char* rootDir = !strcmp(fsType, "LittleFS") ? DATA_DIR : "/"; 120 | listFolder(rootDir); 121 | } 122 | } else { 123 | snprintf(startupFailure, SF_LEN, STARTUP_FAIL "Failed to mount %s", fsType); 124 | dataFilesChecked = true; // disable setupAssist as no file system 125 | } 126 | debugMemory("startStorage"); 127 | return res; 128 | } 129 | 130 | static void getOldestDir(char* oldestDir) { 131 | // get oldest folder by its date name 132 | File root = fp.open("/"); 133 | File file = root.openNextFile(); 134 | if (file) strcpy(oldestDir, file.path()); // initialise oldestDir 135 | while (file) { 136 | if (file.isDirectory() && strstr(file.name(), "System") == NULL // ignore Sys Vol Info 137 | && strstr(DATA_DIR, file.name()) == NULL) { // ignore data folder 138 | if (strcmp(oldestDir, file.path()) > 0) strcpy(oldestDir, file.path()); 139 | } 140 | file = root.openNextFile(); 141 | } 142 | } 143 | 144 | void inline getFileDate(File& file, char* fileDate) { 145 | // get last write date of file as string 146 | time_t writeTime = file.getLastWrite(); 147 | struct tm lt; 148 | localtime_r(&writeTime, <); 149 | strftime(fileDate, sizeof(fileDate), "%Y-%m-%d %H:%M:%S", <); 150 | } 151 | 152 | bool checkFreeStorage() { 153 | // Check for sufficient space on storage 154 | bool res = false; 155 | size_t freeSize = (size_t)((STORAGE.totalBytes() - STORAGE.usedBytes()) / ONEMEG); 156 | if (!sdFreeSpaceMode && freeSize < sdMinCardFreeSpace) 157 | LOG_WRN("Space left %uMB is less than minimum %uMB", freeSize, sdMinCardFreeSpace); 158 | else { 159 | // delete to make space 160 | while (freeSize < sdMinCardFreeSpace) { 161 | char oldestDir[FILE_NAME_LEN]; 162 | getOldestDir(oldestDir); 163 | LOG_WRN("Deleting oldest folder: %s %s", oldestDir, sdFreeSpaceMode == 2 ? "after uploading" : ""); 164 | #if INCLUDE_FTP_HFS 165 | if (sdFreeSpaceMode == 2) fsStartTransfer(oldestDir); // transfer and then delete oldest folder 166 | #endif 167 | deleteFolderOrFile(oldestDir); 168 | freeSize = (size_t)((STORAGE.totalBytes() - STORAGE.usedBytes()) / ONEMEG); 169 | } 170 | LOG_INF("Storage free space: %s", fmtSize(STORAGE.totalBytes() - STORAGE.usedBytes())); 171 | res = true; 172 | } 173 | return res; 174 | } 175 | 176 | void setFolderName(const char* fname, char* fileName) { 177 | // set current or previous folder 178 | char partName[FILE_NAME_LEN]; 179 | if (strchr(fname, '~') != NULL) { 180 | if (!strcmp(fname, currentDir)) { 181 | dateFormat(partName, sizeof(partName), true); 182 | strcpy(fileName, partName); 183 | LOG_INF("Current directory set to %s", fileName); 184 | } 185 | else if (!strcmp(fname, previousDir)) { 186 | struct timeval tv; 187 | gettimeofday(&tv, NULL); 188 | struct tm* tm = localtime(&tv.tv_sec); 189 | tm->tm_mday -= 1; 190 | time_t prev = mktime(tm); 191 | strftime(partName, sizeof(partName), "/%Y%m%d", localtime(&prev)); 192 | strcpy(fileName, partName); 193 | LOG_INF("Previous directory set to %s", fileName); 194 | } else strcpy(fileName, ""); 195 | } else strcpy(fileName, fname); 196 | } 197 | 198 | bool listDir(const char* fname, char* jsonBuff, size_t jsonBuffLen, const char* extension) { 199 | // either list day folders in root, or files in a day folder 200 | bool hasExtension = false; 201 | char partJson[200]; // used to build SD page json buffer 202 | bool noEntries = true; 203 | char fileName[FILE_NAME_LEN]; 204 | setFolderName(fname, fileName); 205 | 206 | // check if folder or file 207 | if (strstr(fileName, extension) != NULL) { 208 | // required file type selected 209 | hasExtension = true; 210 | noEntries = true; 211 | strcpy(jsonBuff, "{}"); 212 | } else { 213 | // ignore leading '/' if not the only character 214 | bool returnDirs = strlen(fileName) > 1 ? (strchr(fileName+1, '/') == NULL ? false : true) : true; 215 | // open relevant folder to list contents 216 | File root = fp.open(fileName); 217 | if (strlen(fileName)) { 218 | if (!root) LOG_WRN("Failed to open directory %s", fileName); 219 | else if (!root.isDirectory()) LOG_WRN("Not a directory %s", fileName); 220 | LOG_VRB("Retrieving %s in %s", returnDirs ? "folders" : "files", fileName); 221 | } 222 | 223 | // build relevant option list 224 | strcpy(jsonBuff, returnDirs ? "{" : "{\"/\":\".. [ Up ]\","); 225 | File file = root.openNextFile(); 226 | if (psramFound()) heap_caps_malloc_extmem_enable(MIN_RAM); // small number to force vector into psram 227 | while (file) { 228 | if (returnDirs && file.isDirectory() && strstr(DATA_DIR, file.name()) == NULL) { 229 | // build folder list, ignore data folder 230 | sprintf(partJson, "\"%s\":\"%s\",", file.path(), file.name()); 231 | fileVec.push_back(std::string(partJson)); 232 | noEntries = false; 233 | } 234 | if (!returnDirs && !file.isDirectory()) { 235 | // build file list 236 | if (strstr(file.name(), extension) != NULL) { 237 | sprintf(partJson, "\"%s\":\"%s %s\",", file.path(), file.name(), fmtSize(file.size())); 238 | fileVec.push_back(std::string(partJson)); 239 | noEntries = false; 240 | } 241 | } 242 | file = root.openNextFile(); 243 | } 244 | if (psramFound()) heap_caps_malloc_extmem_enable(MAX_RAM); 245 | } 246 | 247 | if (noEntries && !hasExtension) sprintf(jsonBuff, "{\"/\":\"List folders\",\"%s\":\"Go to current (today)\",\"%s\":\"Go to previous (yesterday)\"}", currentDir, previousDir); 248 | else { 249 | // build json string content 250 | sort(fileVec.begin(), fileVec.end(), std::greater()); 251 | for (auto fileInfo : fileVec) { 252 | if (strlen(jsonBuff) + strlen(fileInfo.c_str()) < jsonBuffLen) strcat(jsonBuff, fileInfo.c_str()); 253 | else { 254 | LOG_WRN("Too many folders/files to list %u+%u in %u bytes", strlen(jsonBuff), strlen(partJson), jsonBuffLen); 255 | break; 256 | } 257 | } 258 | jsonBuff[strlen(jsonBuff)-1] = '}'; // lose trailing comma 259 | } 260 | fileVec.clear(); 261 | return hasExtension; 262 | } 263 | 264 | static void deleteOthers(const char* baseFile) { 265 | #ifdef ISCAM 266 | // delete corresponding csv and srt files if exist 267 | char otherDeleteName[FILE_NAME_LEN]; 268 | strcpy(otherDeleteName, baseFile); 269 | changeExtension(otherDeleteName, CSV_EXT); 270 | if (STORAGE.remove(otherDeleteName)) LOG_INF("File %s deleted", otherDeleteName); 271 | changeExtension(otherDeleteName, SRT_EXT); 272 | if (STORAGE.remove(otherDeleteName)) LOG_INF("File %s deleted", otherDeleteName); 273 | #endif 274 | } 275 | 276 | void deleteFolderOrFile(const char* deleteThis) { 277 | // delete supplied file or folder, unless it is a reserved folder 278 | char fileName[FILE_NAME_LEN]; 279 | setFolderName(deleteThis, fileName); 280 | File df = fp.open(fileName); 281 | if (!df) { 282 | LOG_WRN("Failed to open %s", fileName); 283 | return; 284 | } 285 | if (df.isDirectory() && (strstr(fileName, "System") != NULL 286 | || strstr("/", fileName) != NULL)) { 287 | df.close(); 288 | LOG_WRN("Deletion of %s not permitted", fileName); 289 | delay(1000); // reduce thrashing on same error 290 | return; 291 | } 292 | LOG_INF("Deleting : %s", fileName); 293 | // Empty named folder first 294 | if (df.isDirectory() || ((!strcmp(fsType, "SPIFFS")) && strstr("/", fileName) != NULL)) { 295 | LOG_INF("Folder %s contents", fileName); 296 | File file = df.openNextFile(); 297 | while (file) { 298 | char filepath[FILE_NAME_LEN]; 299 | strcpy(filepath, file.path()); 300 | if (file.isDirectory()) LOG_INF(" DIR : %s", filepath); 301 | else { 302 | size_t fSize = file.size(); 303 | file.close(); 304 | LOG_INF(" FILE : %s Size : %s %sdeleted", filepath, fmtSize(fSize), STORAGE.remove(filepath) ? "" : "not "); 305 | deleteOthers(filepath); 306 | } 307 | file = df.openNextFile(); 308 | } 309 | // Remove the folder 310 | if (df.isDirectory()) LOG_ALT("Folder %s %sdeleted", fileName, STORAGE.rmdir(fileName) ? "" : "not "); 311 | else df.close(); 312 | } else { 313 | // delete individual file 314 | df.close(); 315 | LOG_ALT("File %s %sdeleted", deleteThis, STORAGE.remove(deleteThis) ? "" : "not "); //Remove the file 316 | deleteOthers(deleteThis); 317 | } 318 | } 319 | 320 | /************** uncompressed tarball **************/ 321 | 322 | #define BLOCKSIZE 512 323 | 324 | static esp_err_t writeHeader(File& inFile, httpd_req_t* req) { 325 | char tarHeader[BLOCKSIZE] = {}; // 512 bytes tar header 326 | strncpy(tarHeader, inFile.name(), 99); // name of file 327 | sprintf(tarHeader + 100, "0000666"); // file permissions stored as ascii octal number 328 | sprintf(tarHeader + 124, "%011o", inFile.size()); // length of file in bytes as 6 digit ascii octal number 329 | memcpy(tarHeader + 148, " ", 8); // init as 8 spaces to calc checksum 330 | tarHeader[156] = '0'; // type of entry - 0 for ordinary file 331 | strcpy(tarHeader + 257, "ustar"); // magic 332 | memcpy(tarHeader + 263, "00", 2); // version as two 0 digits 333 | 334 | // Calculate and set the checksum 335 | uint32_t checksum = 0; 336 | for (const auto& ch : tarHeader) checksum += ch; 337 | sprintf(tarHeader + 148, "%06lo", checksum); // six digit octal number with leading zeroes followed by a NUL and then a space. 338 | 339 | return httpd_resp_send_chunk(req, tarHeader, BLOCKSIZE); 340 | } 341 | 342 | esp_err_t downloadFile(File& df, httpd_req_t* req) { 343 | // download file as attachment, required file name in inFileName 344 | // setup download header, create zip file if required, and download file 345 | esp_err_t res = ESP_OK; 346 | bool needZip = false; 347 | char downloadName[FILE_NAME_LEN]; 348 | strcpy(downloadName, df.name()); 349 | size_t downloadSize = df.size(); 350 | char fsSavePath[FILE_NAME_LEN]; 351 | strcpy(fsSavePath, inFileName); 352 | #ifdef ISCAM 353 | changeExtension(fsSavePath, CSV_EXT); 354 | 355 | // check if ancillary files present 356 | needZip = STORAGE.exists(fsSavePath); 357 | const char* extensions[3] = {AVI_EXT, CSV_EXT, SRT_EXT}; 358 | if (needZip) { 359 | // ancillary files, calculate total size for http header 360 | downloadSize = 0; 361 | for (const auto& ext : extensions) { 362 | changeExtension(fsSavePath, ext); 363 | File inFile = STORAGE.open(fsSavePath, FILE_READ); 364 | if (inFile) { 365 | // round up file size to 512 byte boundary and add header size 366 | downloadSize += (((inFile.size() + BLOCKSIZE - 1) / BLOCKSIZE) * BLOCKSIZE) + BLOCKSIZE; 367 | strcpy(downloadName, inFile.name()); 368 | inFile.close(); 369 | } 370 | } 371 | downloadSize += BLOCKSIZE * 2; // end of tarball marker 372 | changeExtension(downloadName, "zip"); 373 | } 374 | #endif 375 | 376 | // create http header 377 | LOG_INF("Download file: %s, size: %s", downloadName, fmtSize(downloadSize)); 378 | httpd_resp_set_type(req, "application/octet-stream"); 379 | // header field values must remain valid until first send 380 | char contentDisp[IN_FILE_NAME_LEN + 50]; 381 | snprintf(contentDisp, sizeof(contentDisp) - 1, "attachment; filename=%s", downloadName); 382 | httpd_resp_set_hdr(req, "Content-Disposition", contentDisp); 383 | char contentLength[10]; 384 | snprintf(contentLength, sizeof(contentLength) - 1, "%i", downloadSize); 385 | httpd_resp_set_hdr(req, "Content-Length", contentLength); 386 | 387 | if (needZip) { 388 | #ifdef ISCAM 389 | // package avi file and ancillary files into uncompressed tarball 390 | for (const auto& ext : extensions) { 391 | changeExtension(fsSavePath, ext); 392 | File inFile = STORAGE.open(fsSavePath, FILE_READ); 393 | if (inFile) { 394 | res = writeHeader(inFile, req); 395 | if (res == ESP_OK) res = sendChunks(inFile, req, false); 396 | if (res == ESP_OK) { 397 | // write end of file filler 398 | size_t remainingBytes = inFile.size() % BLOCKSIZE; 399 | if (remainingBytes) { 400 | char zeroBlock[BLOCKSIZE - remainingBytes] = {}; 401 | res = httpd_resp_send_chunk(req, zeroBlock, sizeof(zeroBlock)); 402 | } 403 | inFile.close(); 404 | } 405 | } 406 | } 407 | 408 | // Write two blocks filled with zeros to mark the end of the archive 409 | char zeroBlock[BLOCKSIZE] = {}; 410 | res = httpd_resp_send_chunk(req, zeroBlock, BLOCKSIZE); 411 | res = httpd_resp_send_chunk(req, zeroBlock, BLOCKSIZE); 412 | res = httpd_resp_sendstr_chunk(req, NULL); 413 | #endif 414 | } else res = sendChunks(df, req); // send AVI 415 | return res; 416 | } 417 | -------------------------------------------------------------------------------- /webDav.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Using the WebDAV server: 4 | Windows: 5 | - Windows file explorer, in address bar enter: /webdav 6 | - Map Network Drive, connect to: \\\webdav 7 | 8 | Android: 9 | - Solid Explorer, enter for Remote host name, webdav for Path 10 | 11 | Not tested: 12 | MacOS: 13 | - Finder: command-K > http:///webdav (do not select anonymous to have write access) 14 | - cmdline: mkdir -p /tmp/esp; mount_webdav -S -i -v esp32 /webdav /tmp/esp && echo OK 15 | 16 | linux: 17 | - mount -t davs2 http:///webdav /mnt/ 18 | - gio/gvfs/nautilus/YourFileExplorer http:///webdav 19 | 20 | Uses ideas from https://github.com/d-a-v/ESPWebDAV 21 | 22 | s60sc 2024 23 | */ 24 | 25 | #include "appGlobals.h" 26 | 27 | #if INCLUDE_WEBDAV 28 | #define ALLOW "PROPPATCH,PROPFIND,OPTIONS,DELETE,MOVE,COPY,HEAD,POST,PUT,GET" 29 | #define XML1 "" 30 | #define XML2 "" 31 | #define XML3 "HTTP/1.1 200 OK" 32 | #define XML4 "" 33 | #define XML5 "" 34 | #define XML6 "" 35 | 36 | static char pathName[IN_FILE_NAME_LEN]; 37 | static httpd_req_t* req; 38 | static char formattedTime[80]; 39 | static const char* extensions[] = {"dummy", ".htm", ".css", ".txt", ".js", ".json", ".png", ".gif", ".jpg", ".ico", ".svg", ".xml", ".pdf", ".zip", ".gz"}; 40 | static const char* mimeTypes[] = {"application/octet-stream", "text/html", "text/html", "text/css", "text/plain", "application/javascript", "application/json", "image/png", "image/gif", "image/jpeg", "image/x-icon", "image/svg+xml", "text/xml", "application/pdf", "application/zip", "application/x-gzip"}; 41 | 42 | static int getMimeType(const char* path) { 43 | // determine mime type for give file extension 44 | int mimePtr = 1; 45 | size_t len = strlen(path); 46 | for (const char* ext : extensions) { 47 | size_t slen = strlen(ext); 48 | if (!strncmp(path + len - slen, ext, slen)) return mimePtr; 49 | mimePtr++; 50 | } 51 | return 0; // default mime type 52 | } 53 | 54 | static void formatTime(time_t t) { 55 | // format time for XML property values 56 | tm* timeinfo = gmtime(&t); 57 | strftime(formattedTime, sizeof(formattedTime), "%a, %d %b %Y %H:%M:%S %Z", timeinfo); 58 | } 59 | 60 | static bool haveResource(bool ignore = false) { 61 | // check if file or folder exists 62 | if (STORAGE.exists(pathName)) return true; 63 | else if (!ignore) httpd_resp_send_404(req); 64 | return false; 65 | } 66 | 67 | static bool isFolder() { 68 | // identify if resource is file of folder 69 | File root = STORAGE.open(pathName); 70 | bool res = root.isDirectory(); 71 | root.close(); 72 | return res; 73 | } 74 | 75 | static void sendContentProp(const char* prop, const char* value) { 76 | // set individual XML properties in response 77 | char propStr[strlen(prop) * 2 + strlen(value) + 15]; 78 | sprintf(propStr, "%s", prop, value, prop); 79 | httpd_resp_sendstr_chunk(req, propStr); 80 | LOG_VRB("propStr %s", propStr); 81 | } 82 | 83 | static void sendPropResponse(File& file, const char* payload) { 84 | // send SD properties details to PC 85 | size_t encodeLen = 3 + strlen(file.path()) * 2; 86 | size_t maxLen = strlen(XML2) + encodeLen + strlen(XML3); 87 | char resp[maxLen + 1]; 88 | snprintf(resp, maxLen, "%s%s%s", XML2, file.path(), XML3); 89 | httpd_resp_sendstr_chunk(req, resp); 90 | LOG_VRB("resp xml: %s", resp); 91 | 92 | formatTime(file.getLastWrite()); 93 | sendContentProp("getlastmodified", formattedTime); 94 | sendContentProp("creationdate", formattedTime); 95 | 96 | if (file.isDirectory()) sendContentProp("resourcetype", ""); 97 | else { 98 | char fsizeStr[15]; 99 | sprintf(fsizeStr, "%u", file.size()); 100 | sendContentProp("getcontentlength", fsizeStr); 101 | sendContentProp("getcontenttype", mimeTypes[getMimeType(file.path())]); 102 | httpd_resp_sendstr_chunk(req, ""); 103 | } 104 | sendContentProp("displayname", file.name()); 105 | 106 | if (strlen(payload)) { 107 | // return quota data if requested 108 | if (strstr(payload, "quota-available-bytes") != NULL || strstr(payload, "quota-used-bytes") != NULL) { 109 | char numberStr[15]; 110 | sprintf(numberStr, "%llu", (uint64_t)STORAGE.totalBytes() - (uint64_t)STORAGE.usedBytes()); 111 | sendContentProp("quota-available-bytes", numberStr); 112 | sprintf(numberStr, "%llu", (uint64_t)STORAGE.usedBytes()); 113 | sendContentProp("quota-used-bytes", numberStr); 114 | } 115 | } 116 | httpd_resp_sendstr_chunk(req, XML4); 117 | } 118 | 119 | static bool getPayload(char* payload) { 120 | // get payload in PROPFIND message 121 | int bytesRead = -1; 122 | size_t offset = 0; 123 | size_t psize = req->content_len; 124 | if (psize) { 125 | do { 126 | bytesRead = httpd_req_recv(req, payload + offset, psize - offset); 127 | if (bytesRead < 0) { 128 | if (bytesRead == HTTPD_SOCK_ERR_TIMEOUT) { 129 | delay(10); 130 | continue; 131 | } else { 132 | LOG_WRN("Transfer request failed with status %i", bytesRead); 133 | psize = 0; 134 | break; 135 | } 136 | } else offset += bytesRead; 137 | } while (bytesRead > 0); 138 | payload[psize] = 0; 139 | LOG_VRB("payload: %s\n", payload); 140 | } 141 | return bytesRead < 0 ? false : true; 142 | } 143 | 144 | static bool handleProp() { 145 | // provide details of SD content to PC 146 | if (!haveResource()) return false; 147 | // get depth header 148 | bool depth = false; 149 | char value[10]; 150 | if (extractHeaderVal(req, "Depth", value) == ESP_OK) depth = (!strcmp(value, "0")) ? false : true; 151 | 152 | // get request payload content if present 153 | char payload[req->content_len + 1] = {0}; 154 | if (req->content_len) getPayload(payload); 155 | 156 | // common header 157 | httpd_resp_set_status(req, "207 Multi-Status"); 158 | httpd_resp_set_type(req, "application/xml;charset=utf-8"); 159 | httpd_resp_sendstr_chunk(req, XML1); 160 | 161 | // return details of selected folder 162 | File root = STORAGE.open(pathName); 163 | sendPropResponse(root, payload); 164 | if (depth && root.isDirectory()) { 165 | // if requested return details of each resource in folder 166 | File entry = root.openNextFile(); 167 | while (entry) { 168 | sendPropResponse(entry, ""); 169 | entry.close(); 170 | entry = root.openNextFile(); 171 | } 172 | } 173 | root.close(); 174 | httpd_resp_sendstr_chunk(req, ""); 175 | httpd_resp_sendstr_chunk(req, NULL); 176 | return true; 177 | } 178 | 179 | static bool handleOptions() { 180 | httpd_resp_sendstr(req, NULL); 181 | return true; 182 | } 183 | 184 | static bool handleGet() { 185 | // transfer file to PC 186 | if (!haveResource()) return false; 187 | if (isFolder()) { 188 | httpd_resp_send_404(req); 189 | return false; 190 | } else { 191 | httpd_resp_set_type(req, mimeTypes[getMimeType(pathName)]); 192 | strcpy(inFileName, pathName); 193 | esp_err_t res = fileHandler(req); // file content 194 | return res == ESP_OK ? true : false; 195 | } 196 | return true; 197 | } 198 | 199 | static bool handleHead() { 200 | if (!haveResource()) return false; 201 | httpd_resp_sendstr(req, NULL); 202 | return true; 203 | } 204 | 205 | static bool handleLock() { 206 | // provide (dummy) lock while file open 207 | const char* lockToken = "0123456789012345"; 208 | httpd_resp_set_hdr(req, "Lock-Token", lockToken); 209 | char resp[strlen(XML5) + strlen(lockToken) + strlen(XML6) + 1]; 210 | sprintf(resp, "%s%s%s", XML5, lockToken, XML6); 211 | httpd_resp_set_type(req, "application/xml;charset=utf-8"); 212 | httpd_resp_sendstr(req, resp); 213 | return true; 214 | } 215 | 216 | static bool handleUnlock() { 217 | // unlock file when closed 218 | httpd_resp_set_status(req, "204 No Content"); 219 | httpd_resp_sendstr(req, NULL); 220 | return true; 221 | } 222 | 223 | static bool handlePut() { 224 | // transfer file from PC 225 | if (isFolder()) return false; 226 | if (!haveResource(true) || !req->content_len) { 227 | // if no content, create file entry only 228 | File file = STORAGE.open(pathName, FILE_WRITE); 229 | file.close(); 230 | httpd_resp_set_status(req, "201 Created"); 231 | httpd_resp_sendstr(req, NULL); 232 | } 233 | if (req->content_len) { 234 | // transfer file content to SD 235 | strcpy(inFileName, pathName); 236 | esp_err_t res = uploadHandler(req); 237 | return res == ESP_OK ? true : false; 238 | } 239 | return true; 240 | } 241 | 242 | static bool handleDelete() { 243 | // delete file or folder 244 | if (!haveResource()) return false; 245 | // for this app, single folder level only 246 | deleteFolderOrFile(pathName); 247 | httpd_resp_sendstr(req, NULL); 248 | return true; 249 | } 250 | 251 | static bool handleMkdir() { 252 | // create new folder 253 | if (haveResource(true)) return false; // already exists 254 | bool res = STORAGE.mkdir(pathName); 255 | if (res) httpd_resp_set_status(req, "201 Created"); 256 | else httpd_resp_set_status(req, "500 Internal Server Error"); 257 | httpd_resp_sendstr(req, NULL); 258 | return res; 259 | } 260 | 261 | static bool checkSamePath(const char *source_path, const char *dest_path) { 262 | // Compare paths, excluding filenames 263 | char source_dir[strlen(source_path) + 1]; 264 | char dest_dir[strlen(dest_path) + 1]; 265 | strncpy(source_dir, source_path, strrchr(source_path, '/') - source_path); 266 | source_dir[strrchr(source_path, '/') - source_path] = 0; 267 | strncpy(dest_dir, dest_path, strrchr(dest_path, '/') - dest_path); 268 | dest_dir[strrchr(dest_path, '/') - dest_path] = 0; 269 | return strcmp(source_dir, dest_dir) == 0; 270 | } 271 | 272 | static bool handleMove() { 273 | // rename file or folder, or change file location 274 | bool res = false; 275 | char dest[100]; 276 | if (extractHeaderVal(req, "Destination", dest) == ESP_OK) { 277 | // obtain destination filename 278 | res = true; 279 | urlDecode(dest); 280 | char* pos = strstr(dest, WEBDAV); 281 | memmove(dest, pos + strlen(WEBDAV), strlen(dest)); 282 | 283 | // only allow renaming if a folder 284 | if (isFolder()) res = checkSamePath(pathName, dest); 285 | if (res) { 286 | res = STORAGE.rename(pathName, dest); 287 | if (res) httpd_resp_set_status(req, "201 Created"); 288 | else httpd_resp_set_status(req, "500 Internal Server Error"); 289 | httpd_resp_sendstr(req, NULL); 290 | return true; 291 | } 292 | } 293 | httpd_resp_send_404(req); 294 | return false; 295 | } 296 | 297 | static bool handleCopy() { 298 | // copy folder - not implemented 299 | // files can be copied by copy / paste actions 300 | httpd_resp_send_404(req); 301 | return false; 302 | } 303 | 304 | bool handleWebDav(httpd_req_t* rreq) { 305 | // extract method to determine which WebDAV action to take 306 | //showHttpHeaders(rreq); 307 | req = rreq; 308 | sprintf(pathName, "%s", req->uri + strlen(WEBDAV)); // strip out "/webdav" 309 | if (pathName[strlen(pathName) - 1] == '/') pathName[strlen(pathName) - 1] = 0; // remove final / if present 310 | if (!strlen(pathName)) strcpy(pathName, "/"); // if pathname empty, use single / 311 | urlDecode(pathName); 312 | 313 | // common response header 314 | httpd_resp_set_hdr(req, "DAV", "1"); 315 | httpd_resp_set_hdr(req, "Allow", ALLOW); 316 | 317 | switch(req->method) { 318 | case HTTP_PUT: return handlePut(); // file create/uploads 319 | case HTTP_PROPFIND: return handleProp(); // get file or directory properties 320 | case HTTP_PROPPATCH: return handleProp(); // set file or directory properties 321 | case HTTP_GET: return handleGet(); // file downloads 322 | case HTTP_HEAD: return handleHead(); // file properties 323 | case HTTP_OPTIONS: return handleOptions(); // supported options 324 | case HTTP_LOCK: return handleLock(); // open file lock 325 | case HTTP_UNLOCK: return handleUnlock(); // close file lock 326 | case HTTP_MKCOL: return handleMkdir(); // folder creation 327 | case HTTP_MOVE: return handleMove(); // rename or move file or directory 328 | case HTTP_DELETE: return handleDelete(); // delete a file or directory 329 | case HTTP_COPY: return handleCopy(); // copy a file or directory 330 | default: { 331 | LOG_ERR("Unhandled method %s", HTTP_METHOD_STRING(req->method)); 332 | httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Unhandled method"); 333 | return false; 334 | } 335 | } 336 | return true; 337 | } 338 | 339 | #endif 340 | -------------------------------------------------------------------------------- /webServer.cpp: -------------------------------------------------------------------------------- 1 | // Provides web server for user control of app 2 | // 3 | // s60sc 2022 - 2023 4 | 5 | #include "appGlobals.h" 6 | 7 | #define MAX_HANDLERS 12 8 | 9 | char inFileName[IN_FILE_NAME_LEN]; 10 | static char variable[FILE_NAME_LEN]; 11 | static char value[FILE_NAME_LEN]; 12 | static char retainAction[2]; 13 | int refreshVal = 5000; // msecs 14 | 15 | static httpd_handle_t httpServer = NULL; // web server port 16 | static int fdWs = -1; // websocket sockfd 17 | bool useHttps = false; 18 | bool useSecure = false; 19 | 20 | static fs::FS fp = STORAGE; 21 | static byte* chunk; 22 | 23 | esp_err_t sendChunks(File df, httpd_req_t *req, bool endChunking) { 24 | // use chunked encoding to send large content to browser 25 | size_t chunksize = 0; 26 | while ((chunksize = df.read(chunk, CHUNKSIZE))) { 27 | if (httpd_resp_send_chunk(req, (char*)chunk, chunksize) != ESP_OK) break; 28 | // httpd_sess_update_lru_counter(req->handle, httpd_req_to_sockfd(req)); 29 | } 30 | if (endChunking) { 31 | df.close(); 32 | httpd_resp_sendstr_chunk(req, NULL); 33 | } 34 | if (chunksize) { 35 | LOG_WRN("Failed to send %s to browser", inFileName); 36 | httpd_resp_set_status(req, "500 Failed to send file"); 37 | httpd_resp_sendstr(req, NULL); 38 | } 39 | return chunksize ? ESP_FAIL : ESP_OK; 40 | } 41 | 42 | esp_err_t fileHandler(httpd_req_t* req, bool download) { 43 | // send file contents to browser 44 | httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); 45 | if (!strcmp(inFileName, LOG_FILE_PATH)) flush_log(false); 46 | File df = fp.open(inFileName); 47 | if (!df) { 48 | LOG_WRN("File does not exist or cannot be opened: %s", inFileName); 49 | httpd_resp_send_404(req); 50 | return ESP_FAIL; 51 | } 52 | if (!df.size()) { 53 | // file is empty 54 | df.close(); 55 | httpd_resp_sendstr(req, NULL); 56 | return ESP_OK; 57 | } 58 | return (download) ? downloadFile(df, req) : sendChunks(df, req); 59 | } 60 | 61 | static void displayLog(httpd_req_t *req) { 62 | // output ram log to browser 63 | if (logType == 0) { 64 | int startPtr, endPtr; 65 | startPtr = endPtr = mlogEnd; 66 | httpd_resp_set_type(req, "text/plain"); 67 | 68 | // output log in chunks 69 | do { 70 | int maxChunk = startPtr < endPtr ? endPtr - startPtr : RAM_LOG_LEN - startPtr; 71 | size_t chunkSize = std::min(CHUNKSIZE, maxChunk); 72 | if (chunkSize > 0) httpd_resp_send_chunk(req, messageLog + startPtr, chunkSize); 73 | startPtr += chunkSize; 74 | if (startPtr >= RAM_LOG_LEN) startPtr = 0; 75 | } while (startPtr != endPtr); 76 | httpd_resp_sendstr_chunk(req, NULL); 77 | } 78 | } 79 | 80 | static esp_err_t indexHandler(httpd_req_t* req) { 81 | strcpy(inFileName, INDEX_PAGE_PATH); 82 | httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); 83 | // first check if a startup failure needs to be reported 84 | if (strlen(startupFailure)) { 85 | httpd_resp_set_type(req, "text/html"); 86 | return httpd_resp_sendstr(req, startupFailure); 87 | } 88 | // Show wifi wizard if not setup, using access point mode 89 | if (!fp.exists(INDEX_PAGE_PATH) && WiFi.status() != WL_CONNECTED) { 90 | // Open a basic wifi setup page 91 | httpd_resp_set_type(req, "text/html"); 92 | return httpd_resp_sendstr(req, setupPage_html); 93 | } else { 94 | // first check if authentication is required 95 | if (strlen(Auth_Name)) { 96 | // authentication required 97 | size_t credLen = strlen(Auth_Name) + strlen(Auth_Pass) + 2; // +2 for colon & terminator 98 | char credentials[credLen]; 99 | snprintf(credentials, credLen, "%s:%s", Auth_Name, Auth_Pass); 100 | size_t authLen = httpd_req_get_hdr_value_len(req, "Authorization") + 1; 101 | if (authLen) { 102 | // check credentials supplied are valid 103 | char auth[authLen]; 104 | httpd_req_get_hdr_value_str(req, "Authorization", auth, authLen); 105 | if (!strstr(auth, encode64(credentials))) authLen = 0; // credentials not valid 106 | } 107 | if (!authLen) { 108 | // not authenticated 109 | httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic"); 110 | httpd_resp_set_status(req, "401 Unauthorised"); 111 | return httpd_resp_sendstr(req, NULL); 112 | } 113 | } 114 | } 115 | return fileHandler(req); 116 | } 117 | 118 | esp_err_t extractHeaderVal(httpd_req_t *req, const char* variable, char* value) { 119 | // check if header field present, if so extract value 120 | esp_err_t res = ESP_FAIL; 121 | size_t hdrFieldLen = httpd_req_get_hdr_value_len(req, variable); 122 | if (!hdrFieldLen) return ESP_ERR_INVALID_ARG; // header not present 123 | else if (hdrFieldLen >= IN_FILE_NAME_LEN - 1) LOG_WRN("Field %s value too long (%d)", variable, hdrFieldLen); 124 | else { 125 | res = httpd_req_get_hdr_value_str(req, variable, value, hdrFieldLen + 1); 126 | if (res != ESP_OK) LOG_ERR("Value for %s could not be retrieved: %s", variable, espErrMsg(res)); 127 | } 128 | return res; 129 | } 130 | 131 | esp_err_t extractQueryKeyVal(httpd_req_t *req, char* variable, char* value) { 132 | // get variable and value pair from URL query 133 | size_t queryLen = httpd_req_get_url_query_len(req) + 1; 134 | httpd_req_get_url_query_str(req, variable, queryLen); 135 | urlDecode(variable); 136 | // extract key 137 | char* endPtr = strchr(variable, '='); 138 | if (endPtr != NULL) { 139 | *endPtr = 0; // split variable into 2 strings, first is key name 140 | strcpy(value, variable + strlen(variable) + 1); // value is now second part of string 141 | } else { 142 | LOG_ERR("Invalid query string %s", variable); 143 | httpd_resp_set_status(req, "400 Invalid query string"); 144 | httpd_resp_sendstr(req, NULL); 145 | return ESP_FAIL; 146 | } 147 | return ESP_OK; 148 | } 149 | 150 | static esp_err_t webHandler(httpd_req_t* req) { 151 | // return required web page or component to browser using filename from query string 152 | size_t queryLen = httpd_req_get_url_query_len(req) + 1; 153 | httpd_req_get_url_query_str(req, variable, queryLen); 154 | urlDecode(variable); 155 | 156 | // check file extension to determine required processing before response sent to browser 157 | if (!strcmp(variable, "OTA.htm")) { 158 | // request for built in OTA page, if index html defective 159 | httpd_resp_set_type(req, "text/html"); 160 | return httpd_resp_sendstr(req, otaPage_html); 161 | } else if (!strcmp(HTML_EXT, variable+(strlen(variable)-strlen(HTML_EXT)))) { 162 | // any other html file 163 | httpd_resp_set_type(req, "text/html"); 164 | } else if (!strcmp(JS_EXT, variable+(strlen(variable)-strlen(JS_EXT)))) { 165 | // any js file 166 | httpd_resp_set_type(req, "text/javascript"); 167 | httpd_resp_set_hdr(req, "Cache-Control", "public, max-age=604800"); 168 | } else if (!strcmp(CSS_EXT, variable+(strlen(variable)-strlen(CSS_EXT)))) { 169 | // any css file 170 | httpd_resp_set_type(req, "text/css"); 171 | httpd_resp_set_hdr(req, "Cache-Control", "max-age=604800"); 172 | } else if (!strcmp(TEXT_EXT, variable+(strlen(variable)-strlen(TEXT_EXT)))) { 173 | // any text file 174 | httpd_resp_set_type(req, "text/plain"); 175 | } else if (!strcmp(ICO_EXT, variable+(strlen(variable)-strlen(ICO_EXT)))) { 176 | // any icon file 177 | httpd_resp_set_type(req, "image/x-icon"); 178 | } else if (!strcmp(SVG_EXT, variable+(strlen(variable)-strlen(SVG_EXT)))) { 179 | // any svg file 180 | httpd_resp_set_type(req, "image/svg+xml"); 181 | } else LOG_WRN("Unknown file type %s", variable); 182 | int dlen = snprintf(inFileName, IN_FILE_NAME_LEN - 1, "%s/%s", DATA_DIR, variable); 183 | if (dlen >= IN_FILE_NAME_LEN) LOG_WRN("file name truncated"); 184 | return fileHandler(req); 185 | } 186 | 187 | static esp_err_t controlHandler(httpd_req_t *req) { 188 | // process control query from browser 189 | // obtain details from query string 190 | httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); 191 | if (extractQueryKeyVal(req, variable, value) != ESP_OK) return ESP_FAIL; 192 | if (!strcmp(variable, "displayLog")) displayLog(req); 193 | else { 194 | strcpy(value, variable + strlen(variable) + 1); // value points to second part of string 195 | if (!strcmp(variable, "reset")) { 196 | httpd_resp_sendstr(req, NULL); // stop browser resending reset 197 | doRestart("User requested restart"); 198 | return ESP_OK; 199 | } 200 | if (!strcmp(variable, "startOTA")) snprintf(inFileName, IN_FILE_NAME_LEN - 1, "%s/%s", DATA_DIR, value); 201 | else { 202 | updateStatus(variable, value); 203 | appSpecificWebHandler(req, variable, value); 204 | } 205 | } 206 | httpd_resp_sendstr(req, NULL); 207 | return ESP_OK; 208 | } 209 | 210 | static esp_err_t statusHandler(httpd_req_t *req) { 211 | uint8_t filter = (uint8_t)httpd_req_get_url_query_len(req); // filter number is length of query string 212 | buildJsonString(filter); 213 | httpd_resp_set_type(req, "application/json"); 214 | httpd_resp_sendstr(req, jsonBuff); 215 | return ESP_OK; 216 | } 217 | 218 | bool parseJson(int rxSize) { 219 | // process json in jsonBuff to extract properly formatted flat key:value pairs 220 | jsonBuff[rxSize - 1] = ','; // replace final '}' 221 | jsonBuff[rxSize] = 0; // terminator 222 | char* ptr = jsonBuff + 1; // skip over initial '{' 223 | size_t itemLen = 0; 224 | bool retAction = false; 225 | do { 226 | // get and process each key:value in turn 227 | char* endItem = strchr(ptr += itemLen, ':'); 228 | itemLen = endItem - ptr; 229 | memcpy(variable, ptr, itemLen); 230 | variable[itemLen] = 0; 231 | removeChar(variable, '"'); 232 | ptr++; 233 | endItem = strchr(ptr += itemLen, ','); 234 | itemLen = endItem - ptr; 235 | memcpy(value, ptr, itemLen); 236 | value[itemLen] = 0; 237 | removeChar(value, '"'); 238 | ptr++; 239 | if (!strcmp(variable, "action")) { 240 | strcpy(retainAction, value); 241 | retAction = true; 242 | } else updateStatus(variable, value); 243 | } while (ptr + itemLen - jsonBuff < rxSize); 244 | return retAction; 245 | } 246 | 247 | static esp_err_t updateHandler(httpd_req_t *req) { 248 | // bulk update of config, extract key pairs from received json string 249 | size_t rxSize = min(req->content_len, (size_t)JSON_BUFF_LEN); 250 | int ret = 0; 251 | // obtain json payload 252 | do { 253 | ret = httpd_req_recv(req, jsonBuff, rxSize); 254 | if (ret < 0) { 255 | if (ret == HTTPD_SOCK_ERR_TIMEOUT) continue; 256 | else { 257 | LOG_WRN("Update request failed with status %i", ret); 258 | } 259 | } 260 | } while (ret > 0); 261 | httpd_resp_sendstr(req, NULL); 262 | if (ret >= 0 && parseJson(rxSize)) appSpecificWebHandler(req, "action", retainAction); 263 | return ret < 0 ? ESP_FAIL : ESP_OK; 264 | } 265 | 266 | void progress(size_t prg, size_t sz) { 267 | static uint8_t pcProgress = 0; 268 | if (calcProgress(prg, sz, 5, pcProgress)) LOG_INF("OTA uploaded %d%%", pcProgress); 269 | } 270 | 271 | esp_err_t uploadHandler(httpd_req_t *req) { 272 | // upload file for storage or firmware update 273 | esp_err_t res = ESP_OK; 274 | size_t fileSize = req->content_len; 275 | size_t rxSize = min(fileSize, (size_t)JSON_BUFF_LEN); 276 | int bytesRead = -1; 277 | LOG_INF("Upload file %s", inFileName); 278 | 279 | if (strstr(inFileName, ".bin") != NULL) { 280 | // partition update - sketch or SPIFFS 281 | LOG_INF("Firmware update using file %s", inFileName); 282 | OTAprereq(); 283 | if (fdWs >= 0) httpd_sess_trigger_close(httpServer, fdWs); 284 | // a spiffs binary must have 'spiffs' in the filename 285 | int cmd = (strstr(inFileName, "spiffs") != NULL) ? U_SPIFFS : U_FLASH; 286 | if (cmd == U_SPIFFS) STORAGE.end(); // close relevant file system 287 | if (Update.begin(UPDATE_SIZE_UNKNOWN, cmd)) { 288 | do { 289 | bytesRead = httpd_req_recv(req, jsonBuff, rxSize); 290 | if (bytesRead < 0) { 291 | if (bytesRead == HTTPD_SOCK_ERR_TIMEOUT) { 292 | delay(10); 293 | continue; 294 | } else { 295 | LOG_WRN("Upload request failed with status %i", bytesRead); 296 | break; 297 | } 298 | } 299 | Update.write((uint8_t*)jsonBuff, (size_t)bytesRead); 300 | Update.onProgress(progress); 301 | fileSize -= bytesRead; 302 | } while (bytesRead > 0); 303 | if (!fileSize) Update.end(true); // true to set the size to the current progress 304 | } 305 | if (Update.hasError()) LOG_WRN("OTA failed with error: %s", Update.errorString()); 306 | else LOG_INF("OTA update complete for %s", cmd == U_FLASH ? "Sketch" : "SPIFFS"); 307 | httpd_resp_set_hdr(req, "Connection", "close"); 308 | httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); 309 | httpd_resp_sendstr(req, Update.hasError() ? "OTA update failed, restarting ..." : "OTA update complete, restarting ..."); 310 | doRestart("Restart after OTA"); 311 | 312 | } else { 313 | // create / replace data file on storage 314 | File uf = fp.open(inFileName, FILE_WRITE); 315 | if (!uf) LOG_WRN("Failed to open %s on storage", inFileName); 316 | else { 317 | // obtain file content 318 | do { 319 | bytesRead = httpd_req_recv(req, jsonBuff, rxSize); 320 | if (bytesRead < 0) { 321 | if (bytesRead == HTTPD_SOCK_ERR_TIMEOUT) { 322 | delay(10); 323 | continue; 324 | } else { 325 | LOG_WRN("Upload request failed with status %i", bytesRead); 326 | break; 327 | } 328 | } 329 | uf.write((const uint8_t*)jsonBuff, bytesRead); 330 | } while (bytesRead > 0); 331 | uf.close(); 332 | res = bytesRead < 0 ? ESP_FAIL : ESP_OK; 333 | httpd_resp_sendstr(req, res == ESP_OK ? "Completed upload file" : "Failed to upload file, retry"); 334 | if (res == ESP_OK) LOG_INF("Uploaded file %s", inFileName); 335 | else LOG_WRN("Failed to upload file %s", inFileName); 336 | } 337 | } 338 | return res; 339 | } 340 | 341 | void showHttpHeaders(httpd_req_t *req) { 342 | // httpd_req_aux struct members hidden so need to access them via offsets 343 | // to calculate offset any element not on 4 byte boundary has to be packed 344 | LOG_DBG("HTTP: %s %s", HTTP_METHOD_STRING(req->method), req->uri); 345 | size_t maxHdrLen = max(HTTPD_MAX_REQ_HDR_LEN, HTTPD_MAX_URI_LEN); 346 | uint32_t req_hdrs_count = *((uint8_t*)req->aux + 4 + maxHdrLen + 1 + 3 + 4 + 4 + 4 + 1 + 3); 347 | char* header = (char*)req->aux + 4; // start of scratch buffer containing headers 348 | // get each header string in turn 349 | while(req_hdrs_count--) { 350 | LOG_DBG(" %s", header); 351 | header += strlen(header) + 2; 352 | } 353 | } 354 | 355 | static esp_err_t sendCrossOriginHeader(httpd_req_t *req) { 356 | // prevent CORS from blocking request 357 | httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); 358 | httpd_resp_set_hdr(req, "Access-Control-Max-Age", "600"); 359 | httpd_resp_set_hdr(req, "Access-Control-Allow-Methods", "POST,GET,HEAD,OPTIONS"); 360 | httpd_resp_set_hdr(req, "Access-Control-Allow-Headers", "*"); 361 | httpd_resp_set_status(req, "204"); 362 | httpd_resp_sendstr(req, NULL); 363 | return ESP_OK; 364 | } 365 | 366 | void wsAsyncSend(const char* wsData) { 367 | // websockets send function, used for async logging and status updates 368 | if (fdWs >= 0) { 369 | // send if connection active 370 | httpd_ws_frame_t wsPkt; 371 | wsPkt.payload = (uint8_t*)wsData; 372 | wsPkt.len = strlen(wsData); 373 | wsPkt.type = HTTPD_WS_TYPE_TEXT; 374 | wsPkt.final = true; 375 | esp_err_t ret = httpd_ws_send_frame_async(httpServer, fdWs, &wsPkt); 376 | if (ret != ESP_OK) LOG_WRN("websocket send failed with %s", esp_err_to_name(ret)); 377 | } // else ignore 378 | } 379 | 380 | static esp_err_t wsHandler(httpd_req_t *req) { 381 | // receive websocket data and determine response 382 | // if a new connection is received, the old connection is closed, but the browser 383 | // page on the newer connection may need to be manually refreshed to take over the log 384 | esp_err_t ret = ESP_OK; 385 | if (req->method == HTTP_GET) { 386 | // websocket connection request from browser client 387 | if (fdWs != -1) { 388 | if (fdWs != httpd_req_to_sockfd(req)) { 389 | // websocket connection from browser when another browser connection is active 390 | LOG_WRN("closing connection, as newer Websocket on %u", httpd_req_to_sockfd(req)); 391 | // kill older connection 392 | httpd_sess_trigger_close(httpServer, fdWs); 393 | } 394 | } 395 | fdWs = httpd_req_to_sockfd(req); 396 | if (fdWs < 0) { 397 | LOG_WRN("failed to get socket number"); 398 | ret = ESP_FAIL; 399 | } else LOG_INF("Websocket connection: %d", fdWs); 400 | } else { 401 | // data content received 402 | httpd_ws_frame_t wsPkt; 403 | uint8_t wsMsg[MAX_PAYLOAD_LEN]; 404 | memset(&wsPkt, 0, sizeof(httpd_ws_frame_t)); 405 | wsPkt.payload = wsMsg; 406 | ret = httpd_ws_recv_frame(req, &wsPkt, MAX_PAYLOAD_LEN); 407 | if (ret == ESP_OK) { 408 | if (wsPkt.len >= MAX_PAYLOAD_LEN) LOG_ERR("websocket payload too long %d", wsPkt.len); 409 | wsMsg[wsPkt.len] = 0; // terminator 410 | if (wsPkt.type == HTTPD_WS_TYPE_BINARY && wsPkt.len) appSpecificWsBinHandler(wsMsg, wsPkt.len); 411 | else if (wsPkt.type == HTTPD_WS_TYPE_TEXT) appSpecificWsHandler((const char*)wsMsg); 412 | else if (wsPkt.type == HTTPD_WS_TYPE_CLOSE) appSpecificWsHandler("X"); 413 | } else LOG_ERR("websocket receive failed with %s", esp_err_to_name(ret)); 414 | } 415 | return ret; 416 | } 417 | 418 | void killSocket(int skt) { 419 | // user requested 420 | if (skt == -99) { 421 | skt = fdWs; 422 | fdWs = -1; 423 | } 424 | if (skt >= 0) httpd_sess_trigger_close(httpServer, skt); 425 | } 426 | 427 | /* 428 | static void https_server_user_callback(esp_https_server_user_cb_arg_t *user_cb) { 429 | LOG_DBG("Session created, socket: %d", user_cb->tls->sockfd); 430 | } 431 | */ 432 | 433 | static esp_err_t customOrNotFoundHandler(httpd_req_t *req, httpd_err_code_t err) { 434 | // either handle WebDAV methods or report non existent URI 435 | if (req->method == HTTP_OPTIONS) sendCrossOriginHeader(req); 436 | #if INCLUDE_WEBDAV 437 | if (strncmp(req->uri, WEBDAV, strlen(WEBDAV)) == 0) return handleWebDav(req) ? ESP_OK : ESP_FAIL; 438 | #endif 439 | // For any other URI send 404 and close socket 440 | httpd_resp_send_404(req); 441 | return ESP_FAIL; 442 | } 443 | 444 | void startWebServer() { 445 | esp_err_t res = ESP_FAIL; 446 | chunk = psramFound() ? (byte*)ps_malloc(CHUNKSIZE) : (byte*)malloc(CHUNKSIZE); 447 | #if INCLUDE_CERTS 448 | size_t prvtkey_len = strlen(prvtkey_pem); 449 | size_t cacert_len = strlen(cacert_pem); 450 | if (useHttps && (!cacert_len || !prvtkey_len)) { 451 | useHttps = false; 452 | LOG_ALT("HTTPS not available as server keys not defined, using HTTP"); 453 | } 454 | if (useHttps) { 455 | // HTTPS server 456 | httpd_ssl_config_t config = HTTPD_SSL_CONFIG_DEFAULT(); 457 | #if CONFIG_IDF_TARGET_ESP32S3 458 | config.httpd.stack_size = SERVER_STACK_SIZE; 459 | #endif 460 | config.cacert_pem = (const uint8_t*)cacert_pem; 461 | config.cacert_len = cacert_len + 1; 462 | config.prvtkey_pem = (const uint8_t*)prvtkey_pem; 463 | config.prvtkey_len = prvtkey_len + 1; 464 | //config.user_cb = https_server_user_callback; 465 | config.httpd.server_port = HTTPS_PORT; 466 | config.httpd.ctrl_port = HTTPS_PORT; 467 | config.httpd.lru_purge_enable = true; // close least used socket 468 | config.httpd.max_uri_handlers = MAX_HANDLERS; 469 | config.httpd.max_open_sockets = HTTP_CLIENTS + MAX_STREAMS; 470 | config.httpd.task_priority = HTTP_PRI; 471 | //config.httpd.uri_match_fn = httpd_uri_match_wildcard; 472 | res = httpd_ssl_start(&httpServer, &config); 473 | } else { 474 | #endif 475 | // HTTP server 476 | httpd_config_t config = HTTPD_DEFAULT_CONFIG(); 477 | #if CONFIG_IDF_TARGET_ESP32S3 478 | config.stack_size = SERVER_STACK_SIZE; 479 | #endif 480 | config.server_port = HTTP_PORT; 481 | config.ctrl_port = HTTP_PORT; 482 | config.lru_purge_enable = true; 483 | config.max_uri_handlers = MAX_HANDLERS; 484 | config.max_open_sockets = HTTP_CLIENTS + MAX_STREAMS; 485 | config.task_priority = HTTP_PRI; 486 | //config.uri_match_fn = httpd_uri_match_wildcard; 487 | res = httpd_start(&httpServer, &config); 488 | #if INCLUDE_CERTS 489 | } 490 | #endif 491 | 492 | httpd_uri_t indexUri = {.uri = "/", .method = HTTP_GET, .handler = indexHandler, .user_ctx = NULL}; 493 | httpd_uri_t webUri = {.uri = "/web", .method = HTTP_GET, .handler = webHandler, .user_ctx = NULL}; 494 | httpd_uri_t controlUri = {.uri = "/control", .method = HTTP_GET, .handler = controlHandler, .user_ctx = NULL}; 495 | httpd_uri_t updateUri = {.uri = "/update", .method = HTTP_POST, .handler = updateHandler, .user_ctx = NULL}; 496 | httpd_uri_t statusUri = {.uri = "/status", .method = HTTP_GET, .handler = statusHandler, .user_ctx = NULL}; 497 | httpd_uri_t wsUri = {.uri = "/ws", .method = HTTP_GET, .handler = wsHandler, .user_ctx = NULL, .is_websocket = true}; 498 | httpd_uri_t uploadUri = {.uri = "/upload", .method = HTTP_POST, .handler = uploadHandler, .user_ctx = NULL}; 499 | httpd_uri_t sustainUri = {.uri = "/sustain", .method = HTTP_GET, .handler = appSpecificSustainHandler, .user_ctx = NULL}; 500 | httpd_uri_t checkUri = {.uri = "/sustain", .method = HTTP_HEAD, .handler = appSpecificSustainHandler, .user_ctx = NULL}; 501 | 502 | if (res == ESP_OK) { 503 | httpd_register_uri_handler(httpServer, &indexUri); 504 | httpd_register_uri_handler(httpServer, &webUri); 505 | httpd_register_uri_handler(httpServer, &controlUri); 506 | httpd_register_uri_handler(httpServer, &updateUri); 507 | httpd_register_uri_handler(httpServer, &statusUri); 508 | httpd_register_uri_handler(httpServer, &wsUri); 509 | httpd_register_uri_handler(httpServer, &uploadUri); 510 | httpd_register_uri_handler(httpServer, &sustainUri); 511 | httpd_register_uri_handler(httpServer, &checkUri); 512 | httpd_register_err_handler(httpServer, HTTPD_404_NOT_FOUND, customOrNotFoundHandler); 513 | 514 | LOG_INF("Starting web server on port: %u", useHttps ? HTTPS_PORT : HTTP_PORT); 515 | LOG_INF("Remote server certificates %s checked", useSecure ? "are" : "not"); 516 | if (DEBUG_MEM) { 517 | uint32_t freeStack = (uint32_t)uxTaskGetStackHighWaterMark(NULL); 518 | LOG_INF("Task httpServer stack space %u", freeStack); 519 | } 520 | } else LOG_WRN("Failed to start web server"); 521 | debugMemory("startWebserver"); 522 | } 523 | --------------------------------------------------------------------------------