├── ESP_Sleep.h
├── LICENSE
├── Page_Root.h
├── Page_Script.js.h
├── Page_Style.css.h
├── Pages.h
├── README.md
├── data
└── index.htm
├── esp8266WebSerial.ino
├── example.h
├── global.h
└── helpers.h
/ESP_Sleep.h:
--------------------------------------------------------------------------------
1 | #ifndef ESP_SLEEP_H
2 | #define ESP_SLEEP_H
3 |
4 | #define RTCMEMORYSTART 65
5 | #define RTCMEMORYLEN 127
6 |
7 | #define MICROSECONDS 1000000
8 |
9 | /*
10 | http://www.esp8266.com/wiki/doku.php?id=esp8266_power_usage
11 | https://github.com/esp8266/Arduino/blob/master/doc/libraries.md#esp-specific-apis
12 |
13 | ESP.deepSleep(uint32t SLEEPTIME_MICROSECONDS);
14 | ESP.deepSleep(uint32t SLEEPTIME_MICROSECONDS, /mode/);
15 |
16 | Note this will wake up in the setup routine, NOT in the loop!
17 |
18 | Mode Description
19 | 0 WAKE_RF_DEFAULT Radio calibration after deep-sleep wake up depends on init data byte 108.
20 | 1 WAKE_RFCAL Radio calibration is done after deep-sleep wake up; this increases the current consumption.
21 | 2 WAKE_NO_RFCAL No radio calibration after deep-sleep wake up; this reduces the current consumption.
22 | 4 WAKE_RF_DISABLED Disable RF after deep-sleep wake up, just like modem sleep; this has the least current consumption;
23 | the device is not able to transmit or receive data after wake up.
24 |
25 |
26 | */
27 |
28 | /*
29 | rst_info *reset;
30 | reset = ESP.getResetInfoPtr();
31 | select reset->reason
32 | Reason
33 | 0 REASON_DEFAULT_RST normal startup by power on
34 | 1 REASON_WDT_RST hardware watch dog reset
35 | 2 REASON_EXCEPTION_RST exception reset, GPIO status won’t change
36 | 3 REASON_SOFT_WDT_RST software watch dog reset, GPIO status won’t change
37 | 4 REASON_SOFT_RESTART software restart ,system_restart , GPIO status won’t change
38 | 5 REASON_DEEP_SLEEP_AWAKE wake up from deep-sleep via RTC
39 | 6 REASON_EXT_SYS_RST external system reset
40 | */
41 |
42 | /*
43 |
44 | https://github.com/esp8266/Arduino/blob/master/doc/libraries.md#esp-specific-apis
45 | https://github.com/esp8266/Arduino/blob/master/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino
46 |
47 | ESP.rtcUserMemoryWrite(offset, &data, sizeof(data))
48 | ESP.rtcUserMemoryRead(offset, &data, sizeof(data))
49 | allow data to be stored in and retrieved from the RTC user memory of the chip respectively.
50 | Total size of RTC user memory is 512 bytes, so offset + sizeof(data) shouldn't exceed 512.
51 | Data should be 4-byte aligned. The stored data can be retained between deep sleep cycles.
52 | However, the data might be lost after power cycling the chip. data must be cast to (uint32_t*)
53 |
54 | struct {
55 | float count;
56 | int other;
57 | //...whatever you want in here.
58 | } rtcmem;
59 | static_assert (sizeof(rtcmem) < 512, "RTC can't hold more than 512 bytes");
60 |
61 | //in setup, if reset->reason == REASON_DEEP_SLEEP_AWAKE
62 | ESP.rtcUserMemoryRead(0, (uint32_t*) &rtcmem, sizeof(rtcmem));
63 |
64 | //to save and go to sleep
65 | ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcmem, sizeof(rtcmem)); //write data to RTC memory so we don't loose it.
66 | ESP.deepSleep(MICROSECONDS, WAKE_NO_RFCAL); //deep sleep, assume RF ok, wake back up in setup.
67 |
68 | */
69 |
70 |
71 | #endif ESP_SLEEP_H
72 |
73 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Page_Root.h:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * TODO: You can't use libraries from the internet here if the client is directly connected to the ESP...
4 | * because then your client doesn't have access to the internet, now does it? Switch back to microAjax.
5 | */
6 |
7 | const char PAGE_Root[] PROGMEM = R"=====(
8 |
9 |
10 |
11 |
12 | ESP8266 IOT Serial to Web
13 |
16 |
17 |
18 |
19 |
52 |
53 |
";
582 | }
583 | String values ="";
584 | values += "connectionstate|" + state + "|div\n";
585 | values += "networks|" + Networks + "|div\n";
586 | request->send ( 200, "text/plain", values);
587 | debugbuf+=__FUNCTION__;
588 | }
589 |
590 |
591 | /**** ADMIN NETWORK TIME SETTINGS PAGE ****/
592 | const char PAGE_NTPConfiguration[] PROGMEM = R"=====(
593 |
594 |
595 |
596 |
597 |
598 |
599 |
600 | <NTP Settings
601 |
602 |
648 |
649 |
672 |
673 |
674 | )=====";
675 |
676 | void send_NTP_configuration_html(AsyncWebServerRequest *request) {
677 | if (request->args() > 0 ) { // Save Settings
678 | config.daylight = false;
679 | String temp = "";
680 | for ( uint8_t i = 0; i < request->args(); i++ ) {
681 | if (request->argName(i) == "ntpserver") urldecode( request->arg(i), config.ntpServerName, sizeof(config.ntpServerName));
682 | if (request->argName(i) == "update") config.Update_Time_Via_NTP_Every = request->arg(i).toInt();
683 | if (request->argName(i) == "tz") config.timezone = request->arg(i).toInt();
684 | if (request->argName(i) == "dst") config.daylight = true;
685 | }
686 | WriteConfig();
687 | firstStart = true;
688 | }
689 | request->send ( 200, "text/html", PAGE_NTPConfiguration );
690 | debugbuf+=__FUNCTION__;
691 | }
692 |
693 | void send_NTP_configuration_values_html(AsyncWebServerRequest *request){
694 | String values ="";
695 | values += "ntpserver|" + (String) config.ntpServerName + "|input\n";
696 | values += "update|" + (String) config.Update_Time_Via_NTP_Every + "|input\n";
697 | values += "tz|" + (String) config.timezone + "|input\n";
698 | values += "dst|" + (String) (config.daylight ? "checked" : "") + "|chk\n";
699 | request->send ( 200, "text/plain", values);
700 | debugbuf+=__FUNCTION__;
701 | }
702 |
703 |
704 | #endif
705 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # esp8266WebSerial
2 | Put anything with a TTL serial connection on the local network with browser access or log to a server... for under 10 bucks
3 |
4 | - ESPAsyncWebServer for reliable operation, local config in browser, direct web based serial "terminal", etc...
5 | - File system support to upload custom default web page, libraries, css, etc... via "hidden" page to avoid end user confusion.
6 | This allows customization and rebranding for your solution without the need for Arduino code development. Put your own html/javascript in the device for user interface.
7 | - Log incoming data / status to server, stream commands from server out to the connected device
8 | - Low power cycle config: sleep for x seconds, wake send data / status to server as available or every x wake cycles.
9 | - "Blink Detect" input to watch error lights, etc... on remote devices (with optional photodiode and flipflop for detection during sleep)
10 | - Wake without radio for very low power input monitoring
11 | - "Pico Jason" interpreter for commands from server to ESP to configure power cycles, logging.
12 | - Support for ST7735 and ILI9341 and other LCD displays via [TFT_eSPI](https://github.com/Bodmer/TFT_eSPI#tft_espi) _in overlap mode only_ for MAC, SSID / IP address display and
13 | device data extraction / display via scanf codes, slope, and offset.
14 | - Device uses alternate TX/RX pins so power up bootloader messages are NOT sent to device and debug messages are available on Serial Monitor.
15 | - Basic X-ON/X-OFF support to avoid buffer overruns on connected device (TODO: CTS monitoring)
16 | - Configurable device port enable / disable to avoid powering level converters or triggering device connect power up.
17 | - Configurable device baud rate, power on initialization message, and data extraction triggers.
18 | - Optional support for "NeoPixel" LEDs (commented out by default).
19 |
20 | Notes:
21 |
22 |
23 | Due to a [bug / limitation in ESPAsyncWebServer's template system](https://github.com/me-no-dev/ESPAsyncWebServer/issues/333#issuecomment-370595466), and the fact that % is often used in the device configuration, you have to edit the /src/WebResponseImpl.h file in that library to change:
24 | ````
25 | #define TEMPLATE_PLACEHOLDER '%'
26 | ````
27 | to
28 | ````
29 | #define TEMPLATE_PLACEHOLDER '`'
30 | ````
31 |
32 | P.S. Don't even try to get this to work with an ESP-8266 module that wasn't made by AI-THINKER. [The knock offs will NOT work](https://github.com/me-no-dev/ESPAsyncWebServer/issues/374).
33 |
34 | See:
35 | http://techref.massmind.org/techref/ESP8266/WebSerial.htm for documentation, screenshots, and examples
36 | http://techref.massmind.org/techref/esp-8266.htm For notes on the esp-8266, how to connect and program it from the Arduino IDE.
37 |
--------------------------------------------------------------------------------
/data/index.htm:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ESP8266 IOT Serial to Web
6 |
9 |
10 |
11 |
12 |
45 |
46 |
47 |
48 |
51 |
Settings
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/esp8266WebSerial.ino:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | esp8266WebSerial
4 | Version: 1.3.2 - 2018-07-02 by James Newton
5 | -DEBUG levels: 1 for serial only, 2 for serial and display.
6 | -User config device baudrate, poweron initialization string, data extraction and display:
7 | -- New /device.html page to configure all connected device options
8 | -- Send config.pwronstr to device pwrondelay seconds after startup
9 | -- Extract up to 3 data items returned from device for local display via scanf code:
10 | http://www.cplusplus.com/reference/cstdio/scanf/
11 | -- Extracted values multiplied by slope plus offset and shown with name on the display
12 | -global.h config load/save simplified with EEPROM.get / EEPROM.put.
13 | -CONFIG_VER version number added. This update will clear prior config data to default!
14 | -txbuf to hold data waiting to be sent to the device so we can send this in a debug message
15 | -Support "hidden" /update page to upload web/js/css/etc files into SPIFFS for web server.
16 | This allows customization and rebranding for your solution without the need for Arduino code development.
17 | Put your own html/javascript in the device for user interface.
18 | -Default web page is index.htm from SPIFFS. /root is handle_root from Page_Root.h
19 | i.e. http://ip/ will display nothing until index.htm is uploaded via http://ip/update.
20 | If you want to use the built in homepage, go to http://ip/root
21 | TODO: serve root automatically if no index.htm in SPIFFS
22 | -Built in /root page converted from jquery to raw javascript for increased reliability and smaller size.
23 | This is critical when working in poor RF environments while directly connected to the device.
24 | -Use template processor in ESPAsyncWebServer for config pages. There are problems with this, see:
25 | -- https://github.com/me-no-dev/ESPAsyncWebServer/issues/333 Must change TEMPLATE_PLACEHOLDER to '`'
26 | in \libraries\ESPAsyncWebServer\src\WebResponseImpl.h and trigger library re-compile
27 | -- https://github.com/me-no-dev/ESPAsyncWebServer/issues/374 Must use "AI-THINKER" ESP-12E units
28 | -- Network setup /config.html NOT updated to templates for this reason.
29 | -Moving to a single general tag processor function "send_tag_values"
30 | -Moving to standard linking to .css and .js resources from config pages instead of the javascript window.onload functions.
31 | -Add debugq macro to append to debugbuf for later output. This avoids delays when debugging web responses
32 | -Increase max string length of ReadStringFromEEPROM from 60 to 65
33 | -urldecode, avoids Strings, returns char*, expects length.
34 | -urlencode, expects char* vs String (still returns String). Simplified via nibble2hex.
35 | -HTMLencode added inorder to support all strings for scanf codes.
36 | -Optional support for NeoPixel LEDs. NOT enabled by default.
37 | -Start on a command processor language from server response or user input
38 | BUGFIX:
39 | IO pin 10 is NOT usable as SERIAL_ENABLE_PIN, back to IO5 D1
40 | parseServer p1,p2 had not been initialized. Data returned from server for device could be lost.
41 |
42 | Version: 1.3.1 - 2018-02-12 by James Newton
43 | Support for ST7735 and ILI9341 and other LCD displays via TFT_eSPI
44 |
45 | Version: 1.3.0 - 2017-12-xx by James Newton
46 | ESPAsyncWebServer for reliable operation
47 | Log incoming data / status to server, stream commands from server out to the connected device
48 | Low power cycle config: sleep for x seconds, wake send data / status to server as available or every x wake cycles.
49 | "Blink Detect" input to watch error lights, etc... on remote devices (with optional photodiode and flipflop for detection during sleep)
50 | Wake without radio for very low power input monitoring
51 | "Pico Jason" interpreter for commands from server to ESP to configure power cycles, logging.
52 |
53 | Version: 1.2.0 - 2016-09-xx by James Newton
54 | https://github.com/JamesNewton/esp8266WebSerial
55 |
56 | Based on:
57 | ESP_WebConfig
58 | http://www.john-lassen.de/index.php/projects/esp-8266-arduino-ide-webconfig
59 | Copyright (c) 2015 John Lassen. All rights reserved.
60 | This is free software; you can redistribute it and/or
61 | modify it under the terms of the GNU Lesser General Public
62 | License as published by the Free Software Foundation; either
63 | version 2.1 of the License, or (at your option) any later version.
64 | This software is distributed in the hope that it will be useful,
65 | but WITHOUT ANY WARRANTY; without even the implied warranty of
66 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
67 | Lesser General Public License for more details.
68 | You should have received a copy of the GNU Lesser General Public
69 | License along with this library; if not, write to the Free Software
70 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
71 | -----------------------------------------------------------------------------------------------
72 | History
73 |
74 | Version: 1.1.3 - 2015-07-20
75 | Changed the loading of the Javascript and CCS Files, so that they will successively loaded
76 | and that only one request goes to the ESP.
77 |
78 |
79 | Version: 1.1.2 - 2015-07-17
80 | Added URLDECODE for some input-fields (SSID, PASSWORD...)
81 |
82 | Version 1.1.1 - 2015-07-12
83 | First initial version to the public
84 |
85 |
86 | John Lassen version had problems. First, with the web server operated by polling in the loop,
87 | the little ESP is doing good to deliver one page, but making every click load that page, and the
88 | styles, and the js, and the icon, and the values is just too much. Many of those issues are
89 | resolved by moving to ESPAsyncWebServer
90 |
91 | It wouldn't be so bad if we could enable casheing of the pages, but that requires a nasty conversion of the time for
92 | the Last-Modified header value. Actually... maybe it doesn't... it would appear that a fixed, fake, Last-Modified with
93 | a fixed Cache-Control: max-age=### works ok. At least in Chrome.
94 | response->addHeader ( "Last-Modified", "Wed, 25 Feb 2015 12:00:00 GMT" );
95 | response->addHeader ( "Cache-Control", "max-age=86400" );
96 | Actually, the Last-Modified doesn't seem to be needed... Chrome gets by fine with just max-age. Good enough for now.
97 |
98 | Putting each page all in one string would be more reliable, but wastes gobs of memory.
99 | Or we could make ONE page with everything and sections in tabs:
100 | http://callmenick.com/post/simple-responsive-tabs-javascript-css
101 | that still leaves us with an ajax request for all the data.
102 |
103 | Building up a single page from multiple constant strings wastes ram and sending page parts is more complex with
104 | the request->send code because the total content length must be known. But perhaps we can do chunked content? By
105 | using CONTENT_LENGTH_UNKNOWN and then multiple calls to server.sendContent ala:
106 | http://www.esp8266.com/viewtopic.php?p=34858&sid=e4749ea6b5cca73257f7829adb682f09#p34858
107 | https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WebServer/examples/SDWebServer
108 | This requires that we assume HTTP 1.1 clients... shouldn't be an issue.
109 | Why doesn't that code have to close the connection? E.g. how does server know content is finished? Should it
110 | use server.close()? Opened an issue about it.
111 | https://github.com/esp8266/Arduino/issues/2481
112 |
113 | TODO: Looks ESPAsyncWebServer has support for all that already built in:
114 | https://github.com/me-no-dev/ESPAsyncWebServer#template-processing
115 |
116 | Added serial data flow from simple web form to serial port and from serial port to web via regular polling.
117 | Debug msgs and startup garbage from bootloader are on the standard serial lines TX GPIO1, RX GPIO3.
118 | Need to keep actual serial data seperated. Use this serial.swap() to move to different pins, TX GPIO15, RX GPIO13
119 | and connect /those/ pins to the device.
120 | http://arduino.esp8266.com/versions/1.6.5-1160-gef26c5f/doc/reference.html#serial
121 | the original pins get connected to the bootloader for firmware updates only.
122 | TODO: Change debug(msg) and debugln(msg) in helpers.h file to check that no serial data is being sent,
123 | do the swap, serial.send, wait for completion serial.flush, and then swap back.
124 |
125 | DB9
126 | 2 BRN TX (driven by logger)
127 | 3 RED RX (listened to by logger)
128 | 4 ORG
129 | 5 YEL GND
130 | */
131 |
132 | /* DISPLAY / DEBUG: Select at most 1 display type.
133 | No workee... you also have to set it in the TFT_eSPI user_setup_select.h file
134 | */
135 | #define TFT_ADAFRUIT_2088 //original 128x128
136 | //#define TFT_ADAFRUIT_358 //new 128x160
137 | //#define TFT_ILI9341
138 | //#define EPAPER 1.5
139 |
140 | //to drive NeoPixels, SK6812, WS2811, WS2812 and WS2813 with hex P command.
141 | //#define PIXELS 26
142 | #define DEBUGGING 1
143 | //1 for serial only.
144 | //2 for serial and TFT
145 |
146 |
147 | /* PIN SETUP: Note these are GPIO numbers, NOT "D" number ala NodeMCU
148 | static const uint8_t D0 = 16;
149 | static const uint8_t D1 = 5;
150 | static const uint8_t D2 = 4;
151 | static const uint8_t D3 = 0;
152 | static const uint8_t D4 = 2;
153 | static const uint8_t D5 = 14;
154 | static const uint8_t D6 = 12;
155 | static const uint8_t D7 = 13;
156 | static const uint8_t D8 = 15;
157 | static const uint8_t D9 = 3;
158 | static const uint8_t D10 = 1;
159 | */
160 |
161 | #define SERIAL_ENABLE_PIN 5
162 | //#define SERIAL_ENABLE_PIN 10 //NO! IO 10 is NOT available.
163 | //AkA CONNECT in web config or F_ON (force on) in schematic.
164 | //Changed from pin GPIO5 to GPIO10 (aka NodeMCU SD D3 or just SD3) on 02/15/2018
165 | #define WAS_BLINK 4 //D2
166 | #define CLEAR_BLINK 2 //D4 also used for NeoPixels via Serial1 hack
167 | #define TX2 15 //D8
168 | #define RX2 13 //D7
169 | #define CTS_IN 12 //D6
170 | //TFT pins (optional) also uses CLK, SD0(MISO)?, SD1(MOSI), SD3(IO 10),
171 | #define TFT_DC 14 //D5
172 | #define TFT_CS 0 //D3
173 |
174 | //TODO: Actually watch this if customer configures.
175 | //#define RTS_OUT 14
176 | //RTS not used or connected to sleep. GPIO14, D5 used as TFT_DC
177 |
178 | //Default: user configurable device baud rate on device screen
179 | //#define BAUD_RATE 38400
180 | #define BAUD_RATE 9600
181 |
182 | //TODO: Support seperate baud rate for debug messages?
183 | #define DEBUG_BAUD_RATE 38400
184 |
185 | #define AdminTimeOut 0
186 | //600
187 | // Defines the Time in Seconds, when the Admin-Mode will be diabled
188 | //set to 0 to never disable
189 |
190 | #define ACCESS_POINT_NAME "MassMind.org@192.168.4.1"
191 | //Change this to whatever you like. E.g.
192 | //#define ACCESS_POINT_NAME "Dascor@192.168.4.1"
193 | /*
194 | Section 7.3.2.1 of the 802.11-2007 specification
195 | http://standards.ieee.org/getieee802/download/802.11-2007.pdf
196 | defines a valid SSID as 0-32 octets with arbitrary contents.
197 | */
198 | #define ACCESS_POINT_PASSWORD "192.168.4.1"
199 | //TODO: Make it respond to ALL ip addresses when in Admin mode or
200 | // pop up a web page automatically on connection ala sign in to WiFi pages.
201 | // ACCESS_POINT_IP 192.168.4.1
202 |
203 |
204 | #include
205 | //#include
206 | #include
207 | #include
208 | //https://github.com/me-no-dev/AsyncTCP is required by:
209 | #include
210 | //https://github.com/me-no-dev/ESPAsyncWebServer
211 | #include
212 | //#include SUCKS!
213 |
214 | //#include
215 | //https://github.com/nickgammon/Regexp
216 | //#include "cstdio.h"
217 | //for sscanf
218 |
219 | #include
220 | //https://github.com/esp8266/Arduino/tree/master/libraries/Ticker
221 |
222 | #include
223 | #include //SPIFFS file system
224 | //https://github.com/esp8266/Arduino/blob/master/doc/filesystem.rst
225 |
226 | //#include //not needed unless we want to support ultra fast UDP 2 way coms.
227 | //https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/WiFiUdp.cpp
228 | //#include "ESP_Sleep.h"
229 |
230 | #ifdef TFT_ILI9341
231 | #define TFT_DISPLAY
232 | //#define ILI9341_DRIVER //No workee... you have to set it in the TFT_eSPI user_setup_select.h file
233 | #endif
234 |
235 | #ifdef TFT_ADAFRUIT_358 //Newer 128x160
236 | #define TFT_DISPLAY
237 | //#define ST7735_DRIVER //No workee... you have to set it in the TFT_eSPI user_setup_select.h file
238 | #define TFT_WIDTH 128
239 | #define TFT_HEIGHT 160
240 | #endif
241 |
242 | #ifdef TFT_ADAFRUIT_2088 //original 128x128
243 | #define TFT_DISPLAY
244 | //#define ST7735_DRIVER //No workee... you have to set it in the TFT_eSPI user_setup_select.h file
245 | #define TFT_WIDTH 128
246 | #define TFT_HEIGHT 128
247 | #endif
248 |
249 | #ifdef TFT_DISPLAY
250 | #include // Graphics and font library for ST7735 driver chip
251 | #define TFT_SPI_OVERLAP
252 | //#define TFT_CS PIN_D3 // GPIO 0
253 | //#define TFT_DC PIN_D5 // GPIO 14 Data Command control pin
254 |
255 | #define LOAD_GLCD // Font 1. Original Adafruit 8 pixel font needs ~1820 bytes in FLASH
256 | #define LOAD_FONT2 // Font 2. Small 16 pixel high font, needs ~3534 bytes in FLASH, 96 characters
257 | #define LOAD_FONT4 // Font 4. Medium 26 pixel high font, needs ~5848 bytes in FLASH, 96 characters
258 | #define LOAD_FONT6 // Font 6. Large 48 pixel font, needs ~2666 bytes in FLASH, only characters 1234567890:-.apm
259 |
260 | /*
261 | https://github.com/Bodmer/TFT_eSPI Supports using the SPI0 bus:
262 | https://github.com/Bodmer/TFT_eSPI/issues/74
263 |
264 | The exact type of display must be set in \Arduino\libraries\TFT_eSPI-master by updating the
265 | User_Setup_Select.h files and then the file selected there.
266 |
267 | Requires SPI.pins which came in core 2.4.0, but can be added to 2.3.0 by updating the SPI core library
268 | https://github.com/esp8266/Arduino/tree/af0f5ed956b85e41da647d51d1799db469d6e697/libraries/SPI and also:
269 | https://github.com/esp8266/Arduino/blob/af0f5ed956b85e41da647d51d1799db469d6e697/cores/esp8266/esp8266_peri.h
270 | These files live in
271 | C:\Users\JamesN2\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0 and libraries\SPI under that
272 | to recompile the core library, you must fine the spi.o file in the temp folder used for output and delete it
273 |
274 | https://www.adafruit.com/product/2088
275 | http://www.displayfuture.com/Display/datasheet/controller/ST7735.pdf
276 | https://learn.adafruit.com/adafruit-gfx-graphics-library?view=all
277 | */
278 | #endif
279 |
280 | #ifdef PIXELS
281 | //#include
282 | //#include
283 | #include
284 | NeoPixelBus strip(PIXELS, 2); //number of pixels, pin must be GPIO2, TX1
285 | #endif
286 |
287 | #include "base64.h"
288 | extern "C" {
289 | #include //Required for getResetInfoPtr()
290 | }
291 |
292 | #ifdef DEBUGGING
293 | String debugbuf = "";
294 | #ifdef TFT_DISPLAY
295 | int debug_y;
296 | int debug_x;
297 | #define TFT_DEBUG_START 22
298 | #define TFT_DEBUG_END TFT_HEIGHT-16
299 | #endif
300 | #endif
301 |
302 | #include "helpers.h"
303 | #include "global.h"
304 |
305 |
306 | /* Include the HTML, STYLE and Script "Pages" */
307 | #include "Page_Root.h"
308 | #include "Pages.h"
309 | #include "Page_Style.css.h"
310 | #include "Page_Script.js.h"
311 | #include "example.h"
312 |
313 | #define STREAM_BUF_LINES 5
314 | #define STREAM_MAX_CONFIDENCE 10
315 |
316 | //extern "C" int __get_rf_mode(void); causes "unknown function error"
317 | #define MICROSECONDS 1000000
318 | //ADC_MODE(ADC_VCC); //include to measure 3.3 volt rail. comment out to use ADC pin.
319 |
320 | /****** Global Variables *****/
321 |
322 | //anything defined inside this struct will be saved to RTC memory on DeepSleep and should survive the restart
323 | //these variables can change constantly and will not wear out the eeprom.
324 | struct {
325 | float count; //TODO: why is this a float?
326 | bool RFon;
327 | } rtcmem;
328 | static_assert (sizeof(rtcmem) < 512, "RTC can't hold more than 512 bytes");
329 | rst_info *reset;
330 |
331 | String DeviceID = "????????"; //compressed unique id for logging to server.
332 | //Will be made from MAC ID Base64 Encoded with URL safe character set
333 |
334 | byte streaming=0;
335 | String streamURL = "";
336 | int streamLine = 1;
337 | String streamBuf[STREAM_BUF_LINES];
338 | int streamBufLine = 0;
339 |
340 | boolean xoff=false; //flag to see if we need to hold off xmit until device is ready
341 | boolean havedata = false; //flag to indicate data in rxbuf so we don't have to check length each loop.
342 | String rxbuf = ""; //buffer for data recieved from device.
343 | String txbuf = ""; //buffer for data to send to the device.
344 | #define RFBUF_MAX 128
345 |
346 | int reading1,reading2,reading3; //extracted value from datastream for local display.
347 | short readingcount = 0;
348 |
349 | byte pwrondelay = 0; //countdown to send power on string to device
350 |
351 | //If Xoff, recieve bytes until Xon before sending byte.
352 | void putc_x(byte b) {
353 | while (Serial.available() || xoff) {
354 | byte c = Serial.read();
355 | //can't peek, because xoff could be behind next char
356 | if (c == 0x13) { xoff=true; } // XOFF
357 | else if (c == 0x11) { xoff=false; } // XON
358 | else if (c > 0 && c < 0xFF) { //rx data
359 | rxbuf += c; //buffer it
360 | //TODO: may need to check rxbuf.length() and send an xoff if too big.
361 | havedata=true;
362 | }
363 | delay(1); //should this be more?
364 | //TODO: timeout?
365 | }
366 | Serial.write(b);
367 | }
368 |
369 |
370 | //If Xoff, recieve bytes until Xon before sending string.
371 | void writeStr_x(String msg) {
372 | for(int i=0;i0 && c<0xFF) { rxbuf += c; havedata=true;} //filter out nulls and FF's.
383 | if (!Serial.available() && timout) { delay(timout); } //wait a tich if there isn't already more data available. Otherwise, timeout.
384 | }
385 | // regexp.Target(rxbuf);
386 | // if (REGEXP_MATCHED == regexp.Match(config.regexp) {
387 | // reading1 = hex2int(regexp.GetMatch(rxbuf,0); //extract it.
388 | // }
389 | // int i = rxbuf.length();
390 | // if ( ('+' == rxbuf[i-8]) || ('-' == rxbuf[i-8]) ) { //detected a reading?
391 | // reading1 = hex2int(rxbuf.substring(i-8)); //extract it.
392 | // //debug("hexvalue:",reading1);
393 | // rxbuf = ""; //TODO: only dump it if valid data and user setting allows.
394 | // }
395 |
396 | }
397 |
398 | #ifdef TFT_DISPLAY
399 | TFT_eSPI tft = TFT_eSPI(); // Invoke library, pins defined in User_Setup.h
400 | #define TFT_BACKGROUND TFT_BLUE
401 | #define TFT_RBG_COLOR(r,g,b) (((((r)/8)&31) << 11) | ((((g)/4)&63) << 5) | (((b)/8)&31))
402 |
403 | void showreading(String reading, int x, int y, int fontno) {
404 | tft.setTextColor(TFT_YELLOW,TFT_BACKGROUND);
405 | tft.setTextFont(fontno); tft.setTextSize(1);
406 | if (x<0) {
407 | x = -x - tft.textWidth(reading,fontno) - 2;
408 | if (x<0) x = 0;
409 | }
410 | tft.fillRect(0,y,TFT_WIDTH,tft.fontHeight(fontno),TFT_BACKGROUND);
411 | tft.setCursor(x, y);
412 | tft.print(reading);
413 | }
414 |
415 | #endif
416 |
417 | void setup ( void ) {
418 | EEPROM.begin(512); //EEPROM actually uses SPI_FLASH_SEC_SIZE which appears to be 4096
419 | Serial.begin(BAUD_RATE); //take a guess, so we can see debug messages from ReadConfig
420 | Serial.swap(); //change to TX GPIO15, RX GPIO13
421 | //pinMode(TX2, OUTPUT); //TX line to device should always be an output
422 | //digitalWrite(TX2, HIGH); //when not used as serial, keep TX high or device will see nulls or FF's
423 | //pinMode(RX2,INPUT_PULLUP); // when not used as serial, keep RX high or we may see nulls or FF's
424 | pinMode(SERIAL_ENABLE_PIN, OUTPUT);
425 | digitalWrite(SERIAL_ENABLE_PIN, LOW);
426 | pinMode(WAS_BLINK, INPUT);
427 | digitalWrite(CLEAR_BLINK, HIGH);
428 | pinMode(CLEAR_BLINK, OUTPUT);
429 |
430 | debug("\r","Start ES8266 reason:");
431 |
432 | reset = ESP.getResetInfoPtr();
433 | debugln(reset->reason,ESP.getResetReason());
434 | switch (reset->reason) {
435 | case REASON_EXT_SYS_RST: //6
436 | case REASON_DEFAULT_RST: //0
437 | //standard power up or reset
438 | rtcmem.count=0;
439 | rtcmem.RFon=true; //TODO: Is this right? Will the radio always come on by default?
440 | break;
441 | case REASON_DEEP_SLEEP_AWAKE: // 5
442 | //wake up from RTC
443 | ESP.rtcUserMemoryRead(0, (uint32_t*) &rtcmem, sizeof(rtcmem));
444 | rtcmem.count++;
445 | debugln(" for RTC Tick ",rtcmem.count);
446 | break;
447 | }
448 |
449 | ReadConfig(); //returns false and sets up default config if none found. See global.h
450 | config.Interval = 0; //Temporary: Use to break out of sleep loop.
451 | debugln(config.baud," baud");
452 | config.baud = 9600; //temporary
453 | Serial.swap(); //change back
454 | Serial.begin(config.baud);
455 | Serial.swap(); //change to TX GPIO15, RX GPIO13
456 |
457 | if (config.Interval > 0) config.sleepy=true; else config.sleepy=false;
458 | if (rtcmem.count >= config.WakeCount) {
459 | havedata = true; //fake having data so we will connect.
460 | debugln("Check in",config.WakeCount);
461 | }
462 | // Check if we really need to wake up, and if we don't, just go back to sleep
463 | if ( !digitalRead(WAS_BLINK) //havent see a blink
464 | && config.Logging //and we are logging, but
465 | && config.sleepy //we are setup to go to sleep //config.Interval>0 causes webserver issues here
466 | && !havedata //not waiting on data to be logged to the server //rxbuf.length()==0 causes webserver issues here
467 | ) { //then lets go to sleep
468 | debugln("Sleep for ",config.Interval);
469 | rtcmem.RFon = false;
470 | ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcmem, sizeof(rtcmem)); //write data to RTC memory so we don't loose it.
471 | ESP.deepSleep(config.Interval * MICROSECONDS, WAKE_RF_DISABLED);
472 | //WAKE_NO_RFCAL); //deep sleep, shut off RF, wake back up in setup.
473 | //https://github.com/esp8266/Arduino/issues/3072
474 | }
475 | //If we get to here, we want to wake up and talk, but the radio might not be on. Only way to turn it on is to set a flag and go back to sleep.
476 | if (!rtcmem.RFon) {
477 | debugln("Reset for RF","");
478 | rtcmem.RFon = true;
479 | ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcmem, sizeof(rtcmem)); //write data to RTC memory so we don't loose it.
480 | ESP.deepSleep(1, WAKE_NO_RFCAL); //deep sleep, wake right away with RF on, assume calibration not needed
481 | }
482 | //we are up and radio should be on.
483 |
484 | #ifdef TFT_DISPLAY
485 | tft.init();
486 | tft.setRotation(1);
487 | tft.fillScreen(TFT_BACKGROUND);
488 | tft.setCursor(0, 0);
489 | tft.setTextColor(TFT_WHITE,TFT_BACKGROUND); tft.setTextFont(1); tft.setTextSize(1);
490 | #ifdef DEBUGGING
491 | debug_x=1; debug_y=TFT_DEBUG_START;
492 | #endif
493 | #endif
494 | #ifdef PIXELS
495 | strip.Begin();
496 | strip.Show();
497 | #endif
498 | pwrondelay = config.pwrondelay;
499 | if (config.Connect) {
500 | digitalWrite(SERIAL_ENABLE_PIN, HIGH);
501 | debugln("Device port enabled","");
502 | }
503 | else {
504 | debugln("Device port disabled","");
505 | pwrondelay = 0; //no point in doing pwr on string if no device.
506 | }
507 | readingcount = config.datacount;
508 |
509 | //uncomment the next line if you need the mac address for your router.
510 | debugln("MAC:",GetMacAddress());
511 | uint8_t mac[6];
512 | WiFi.macAddress(mac);
513 | DeviceID = base64::encode(mac,6);
514 | DeviceID.replace("+","-");
515 | DeviceID.replace("/","_");
516 | debugln("DeviceID:",DeviceID);
517 | #ifdef TFT_DISPLAY
518 | tft.print("MAC:");
519 | tft.println(GetMacAddress());
520 | tft.print("Device:");
521 | tft.print(DeviceID);
522 | #endif
523 |
524 |
525 | if (AdminEnabled) {
526 | //WiFi.mode(WIFI_AP_STA);
527 | WiFi.mode(WIFI_AP);
528 | WiFi.softAP( ACCESS_POINT_NAME , ACCESS_POINT_PASSWORD);
529 | IPAddress myIP = WiFi.softAPIP();
530 | debugln("Connect to SSID:",ACCESS_POINT_NAME);
531 | debugln("Password:",ACCESS_POINT_PASSWORD);
532 | debugln("http://",myIP);
533 | }
534 | else {
535 | WiFi.mode(WIFI_STA);
536 | }
537 |
538 | ConfigureWifi();
539 | SPIFFS.begin();
540 | server.on ( "/root", HTTP_GET, handle_root ); //main web page in Page_Root.h
541 | server.on ( "/admin.html", HTTP_GET, [](AsyncWebServerRequest *request) { //settings menu
542 | #ifdef DEBUGGING
543 | debugbuf += "admin.html";
544 | #endif
545 | AsyncWebServerResponse *response = request->beginResponse(200, "text/html", PAGE_AdminMainPage); //in Pages.h
546 | response->addHeader ( "Cache-Control", "max-age=86400" ); //doesn't change, let the browser know
547 | //response->addHeader ( "Last-Modified", "Wed, 25 Feb 2015 12:00:00 GMT" ); //doesn't appear to work
548 | request->send ( response );
549 | } );
550 | server.on ( "/general.html", HTTP_GET, send_general_html ); //in Pages.h
551 | server.on ( "/general.html", HTTP_POST, send_general_html ); //ESPAsyncWebServer needs separate GET and POST handlers
552 | server.on ( "/device.html", HTTP_GET, send_device_html ); //in Pages.h
553 | server.on ( "/device.html", HTTP_POST, send_device_html ); //in Pages.h
554 | server.on ( "/update", HTTP_GET, send_fs_html ); //in Pages.h
555 | server.on ( "/update", HTTP_POST, [](AsyncWebServerRequest *request){
556 | request->send(200);
557 | }, handle_fs_upload ); //in Pages.h
558 | server.on ( "/config.html", HTTP_GET, send_network_configuration_html );
559 | server.on ( "/config.html", HTTP_POST, send_network_configuration_html );
560 | server.on ( "/info.html", HTTP_GET, [](AsyncWebServerRequest *request) {
561 | #ifdef DEBUGGING
562 | debugbuf += "/info.html";
563 | #endif
564 | request->send ( 200, "text/html", PAGE_Information );
565 | } );
566 | server.on ( "/ntp.html", HTTP_GET, send_NTP_configuration_html );
567 | server.on ( "/ntp.html", HTTP_POST, send_NTP_configuration_html );
568 |
569 | server.on ( "/example.html", HTTP_GET, [](AsyncWebServerRequest *request) { request->send ( 200, "text/html", PAGE_example ); } );
570 | server.on ( "/admin/filldynamicdata", HTTP_GET, filldynamicdata );
571 |
572 | server.on ( "/favicon.ico", HTTP_GET, send_favicon_ico ); //in Page_Root.h
573 | server.on ( "/style.css", HTTP_GET, [](AsyncWebServerRequest *request) {
574 | #ifdef DEBUGGING
575 | debugbuf += "/style.css";
576 | #endif
577 | AsyncWebServerResponse *response = request->beginResponse( 200, "text/css", PAGE_Style_css );
578 | response->addHeader ( "Cache-Control", "max-age=86400" );
579 | request->send ( response );
580 | } );
581 | server.on ( "/microajax.js", HTTP_GET, [](AsyncWebServerRequest *request) {
582 | #ifdef DEBUGGING
583 | debugbuf+="/microajax.js";
584 | #endif
585 | AsyncWebServerResponse *response = request->beginResponse( 200, "text/plain", PAGE_microajax_js );
586 | response->addHeader ( "Cache-Control", "max-age=86400" );
587 | request->send ( response );
588 | } );
589 | server.on ( "/admin/values", HTTP_GET, send_network_configuration_values_html );
590 | server.on ( "/admin/connectionstate", HTTP_GET, send_connection_state_values_html );
591 | server.on ( "/admin/infovalues", HTTP_GET, send_information_values_html );
592 | server.on ( "/admin/ntpvalues", HTTP_GET, send_NTP_configuration_values_html );
593 | server.on ( "/admin/generalvalues", HTTP_GET, send_general_configuration_values_html);
594 | server.on ( "/admin/devicename", HTTP_GET, send_devicename_value_html);
595 | server.on("/data", HTTP_GET, [](AsyncWebServerRequest *request){
596 | if (request->hasArg("text")) {
597 | txbuf = parseServer(request->arg("text"));
598 | writeStr_x(txbuf); //pass on what was sent less server msgs
599 | Serial.flush(); //complete the send before going on TODO: Can we wait that long?
600 | debugq("<"+txbuf);
601 | txbuf="";
602 | rxbuf=""; havedata=false; //done with that data. TODO: Why are we doing this here?
603 | //delay(10); //give the device time to respond //nope, can't 'cause AsyncWebServer, get it next browser request
604 | checkSerial(0); // get any text that comes back now //parameter is delay, must be 0 with AsyncWebServer
605 | }
606 | request->send(200, "text/html", rxbuf); //should be text/plain but for testing...
607 | #ifdef DEBUGGING
608 | if (rxbuf.length()>0) debugbuf+=">"+rxbuf;
609 | #endif
610 | if (!config.Logging) {rxbuf=""; havedata=false;} //don't clear if logging so the server gets a copy
611 | });
612 | server.on("/file", HTTP_GET, [](AsyncWebServerRequest *request){
613 | if (request->hasArg("start")) { //have to specify a starting line to begin streaming.
614 | if (WL_CONNECTED != WiFi.status()) {
615 | #ifdef DEBUGGING
616 | debugbuf+="file requested, but no net\n";
617 | debugbuf+=get_wifi_status();
618 | #endif
619 | request->send(400, "text/html", "No internet access, check network config");
620 | }
621 | else { //connected, start new file
622 | streamLine = request->arg("start").toInt(); // || 1; //the logical or 1 doesn't work for some reason!!!
623 | if (streamLine < 1) streamLine = 1;
624 | streamURL = config.streamServerURL + request->arg("name"); //include file name if specified
625 | http.begin(streamURL + "&line=" + streamLine);
626 | #ifdef DEBUGGING
627 | debugbuf+="Streaming from \n";
628 | debugbuf+=streamURL;
629 | debugbuf+="&line=";
630 | debugbuf+=streamLine;
631 | debugbuf+="\n";
632 | #endif
633 | //TODO: Make the argument name for the line number configurable
634 | //maybe it should be post data?
635 | int httpCode = http.GET();
636 | if (HTTP_CODE_OK==httpCode) {
637 | if (streaming < STREAM_MAX_CONFIDENCE) streaming++; //flag it so the loop will keep running
638 | streamBuf[streamBufLine] = http.getString(); //first line returned on open
639 | request->send(200, "text/html", (String)"Streaming:"+streamBuf[streamBufLine]+"StopStatus");
640 | streamBufLine++;
641 | streamLine++;
642 | }
643 | else {
644 | request->send(400, "text/html", http.errorToString(httpCode)+"\nBad response from file stream server, check network config.");
645 | }
646 | http.end();
647 | }
648 | } //done with new stream
649 | else if (request->hasArg("stop")) {
650 | streaming = 0; //stop the cha loop a
651 | request->send(200, "text/html", (String)"Streaming halted at line:" + streamLine + " Continue");
652 | }
653 | else { //got a request but no start
654 | if (streaming) { //already streaming, just provide a status update.
655 | AsyncWebServerResponse *response = request->beginResponse(200, "text/html", (String)"Streaming:" + streamLine + +"\n Stop");
656 | response->addHeader ( "Refresh", "5" ); // short version of
657 | request->send(response);
658 | }
659 | }
660 | });
661 | server.onNotFound ( [](AsyncWebServerRequest *request) { //TODO: serve root if no
662 | #ifdef DEBUGGING
663 | debugbuf+="404:";
664 | debugbuf+=request->url();
665 | debugbuf+="\n";
666 | #endif
667 | request->send ( 404, "text/html", "Page not Found" );
668 | } );
669 | server.serveStatic("/", SPIFFS, "/").setTemplateProcessor(send_tag_values);
670 | server.begin();
671 | debugln("HTTP server started on port:","80" );
672 | debugln("Response Length:", strlen(PAGE_AdminMainPage));
673 | tkSecond.attach(1,Second_Tick);
674 | UDPNTPClient.begin(2390); // Port for NTP receive
675 | #ifdef TFT_DISPLAY
676 | tft.println(" up");
677 | #endif
678 |
679 | } //Setup
680 |
681 |
682 |
683 | void loop ( void ) {
684 | if (AdminEnabled && (AdminTimeOut>0)) {
685 | if (AdminTimeOutCounter > AdminTimeOut) {
686 | AdminEnabled = false;
687 | debugln("Admin Mode disabled!","");
688 | WiFi.mode(WIFI_STA);
689 | //WiFi.disconnect();
690 | //WiFi.softAPdisconnect(true);
691 | }
692 | }
693 |
694 | if(DateTime.minute != Minute_Old) { //only check once a minute
695 | Minute_Old = DateTime.minute;
696 | #ifdef DEBUGGING
697 | //Serial.printf("FreeMem:%d %d:%d:%d %d.%d.%d \n",ESP.getFreeHeap() , DateTime.hour,DateTime.minute, DateTime.second, DateTime.year, DateTime.month, DateTime.day);
698 | debug("mem:",ESP.getFreeHeap());
699 | debug(" ",DateTime.year);
700 | debug("/",DateTime.month);
701 | debug("/",DateTime.day);
702 | debug(" ",DateTime.hour);
703 | debug(":",DateTime.minute);
704 | debug(":",DateTime.second);
705 | if (AdminEnabled) {debug(" admin ","")};
706 | if (config.Logging) {debug(" log ","")};
707 | if (config.sleepy) {
708 | debug(" sleep for:",config.Interval)
709 | debug(" checkin every:",config.WakeCount)
710 | };
711 | if (havedata) {debug(" data:",rxbuf)};
712 | debugln("","");
713 | #endif
714 | #ifdef TFT_DISPLAY
715 | if (WL_CONNECTED == WiFi.status()) {
716 | tft.setCursor(2, 2);//leave room for power status
717 | tft.setTextColor(TFT_YELLOW,TFT_BACKGROUND); tft.setTextFont(2); tft.setTextSize(1);
718 | IPAddress ip = WiFi.localIP();
719 | tft.print(String(ip[0]) + "." + String(ip[1]) + "." + String(ip[2]) + ".");
720 | tft.setTextFont(1); tft.setTextSize(2);
721 | tft.println(String(ip[3]));
722 | }
723 | else if (AdminEnabled) {
724 | tft.setCursor(1, 2);//leave room for power status
725 | tft.setTextColor(TFT_WHITE,TFT_BACKGROUND); tft.setTextFont(1); tft.setTextSize(1);
726 | tft.print("MAC:");
727 | tft.println(GetMacAddress());
728 | tft.setTextColor(TFT_YELLOW,TFT_BACKGROUND); tft.setTextFont(1); tft.setTextSize(1);
729 | tft.print("SSID:");
730 | tft.println(ACCESS_POINT_NAME);
731 | tft.print("PASS:");
732 | tft.println(ACCESS_POINT_PASSWORD);
733 | };
734 | #endif
735 | if (config.Update_Time_Via_NTP_Every > 0 ) {
736 | if (cNTP_Update > 5 && firstStart) {
737 | NTPRefresh();
738 | cNTP_Update =0;
739 | firstStart = false;
740 | }
741 | else if ( cNTP_Update > (config.Update_Time_Via_NTP_Every * 60) ) {
742 | NTPRefresh();
743 | cNTP_Update =0;
744 | }
745 | }
746 | }
747 |
748 | if (streaming) {
749 | if (streamBufLine>0 && !xoff) {
750 | streamBufLine--;
751 | debugln("<",streamBuf[streamBufLine]);
752 | writeStr_x(streamBuf[streamBufLine]);
753 | }
754 | if (STREAM_BUF_LINES>streamBufLine) { //we have room to buffer more lines.
755 | if (WL_CONNECTED != WiFi.status()) {
756 | debugln("net lost while streaming:", get_wifi_status());
757 | streaming = 0; //stop the cha loop a
758 | }
759 | else {
760 | //streamURL = config.streamServerURL + server.arg("name"); //already set in server.on("/file"
761 | //http.begin(streamURL + "&line=" + streamLine + "&lines=" + (STREAM_BUF_LINES-streamBufLine));
762 | //TODO: Deal with multiple line returns.
763 | http.begin(streamURL + "&line=" + streamLine + "&data=" + rxbuf );
764 | //TODO: Make the argument name for the line number configurable
765 | //maybe it should be post data?
766 | int httpCode = http.GET(); //blocking TODO: Timeout?
767 | if (HTTP_CODE_OK==httpCode) {
768 | //debugln(">",streamBuf[streamBufLine]);
769 | streamBuf[">",streamBufLine] = http.getString();
770 | streamBufLine++;
771 | streamLine++;
772 | if (streaming < STREAM_MAX_CONFIDENCE) streaming++;
773 | debugln(">",rxbuf);
774 | rxbuf="";
775 | havedata=false;
776 | }
777 | else { //TODO: Stop instantly on 404.
778 | debug(http.errorToString(httpCode),httpCode);
779 | debugln(" at line:",streamLine);
780 | streaming--; //loosen grip on the cha loop a
781 | }
782 | http.end();
783 | }
784 | }
785 | }
786 |
787 | checkSerial(1);
788 | //http://www.cplusplus.com/reference/cstdio/scanf/
789 | if (00 ) {
813 | havedata=true; //correct
814 | rxbuf = parseServer(rxbuf); //get out any settings and make those changes, leaving just the text to send to the device.
815 | debugln("send:",rxbuf);
816 | if ( rxbuf.length()>0 ) {
817 | digitalWrite(SERIAL_ENABLE_PIN, HIGH);
818 | delay(5); //give the RS232 transceiver / level converter time to respond
819 | writeStr_x(rxbuf); //pass on the servers response
820 | Serial.flush(); //complete the send before going on
821 | rxbuf=""; havedata=false; //done with that data.
822 | delay(10); //give the device time to respond
823 | checkSerial(10); // get any text that comes back now
824 | }
825 | }
826 | if (rtcmem.count >= config.WakeCount) {rtcmem.count = 0;} //reset checkin count.
827 | digitalWrite(CLEAR_BLINK, LOW); //disable any further blinks while we are awake.
828 | pinMode(CLEAR_BLINK, OUTPUT); //incase it was overwritten by Serial1 NeoPixel cmdString
829 | //TODO: Don't we want to see additional blinks?
830 | }
831 | else {
832 | debug("Logging failed to ",streamURL);
833 | debug("id=", DeviceID);
834 | debug("&data=", urlencode(rxbuf.c_str()));
835 | debug("error:",http.errorToString(httpCode));
836 | debugln(" errorcode:",httpCode);
837 | debugln(" log:",http.getString());
838 | delay(1000);
839 | // if we aren't connected to a browser, rxbuf will overflow
840 | // TODO: try to log rxbuf to SPIFFs if a server isn't reachable.
841 | // TODO: At least just dump all but the last x characters.
842 | // HACK: For now, just dump
843 | rxbuf="";
844 | }
845 | http.end();
846 | }
847 | }
848 |
849 | if (havecmd) {
850 | havecmd = false;
851 |
852 | debug(cmdStr.length(),"chars");
853 | debugln(" cmd:", cmdStr);
854 | #ifdef PIXELS
855 | //https://github.com/Makuna/NeoPixelBus/blob/master/src/internal/NeoEsp8266UartMethod.cpp
856 | uint16_t pixno;
857 | uint8_t redness,greenness,blueness;
858 | debug(" pixels",cmdStr.length()>>2);
859 | //http://192.168.0.127/data?text={cmd:aF84bF84cF84dF84eF84fF84gF84hF84iF84jF84kF84lF84mF84nF84oF84pF84qF84rF84sF84tF84uF84vF84wF84xF84yF84}
860 | //http://192.168.0.127/data?text={cmd:yF84xF84wF84vF84uF84tF84sF84rF84qF84pF84oF84nF84mF84lF84kF84jF84iF84hF84gF84fF84eF84dF84cF84bF84aF84}
861 | //http://192.168.0.127/data?text={cmd:a48Fb48Fc48Fd48Fe48Ff48Fg48Fh48Fi48Fj48Fk48Fl48Fm48Fn48Fo48Fp48Fq48Fr48Fs48Ft48Fu48Fv48Fw48Fx48Fy48F}
862 | while( cmdStr.length()>=4) {
863 | pixno = cmdStr[0]-'a';
864 | redness = h2int(cmdStr[1])<<4;
865 | greenness = h2int(cmdStr[2])<<4;
866 | blueness = h2int(cmdStr[3])<<4;
867 | debug(" #",pixno);
868 | debug(" R",redness);
869 | debug(" G",greenness);
870 | debugln(" B",blueness);
871 | strip.SetPixelColor(pixno, RgbColor(redness, greenness, blueness) );
872 | //strip.SetPixelColor(h2int(cmdStr[0]), RgbColor(h2int(cmdStr[1]),h2int(cmdStr[2]),h2int(cmdStr[3])) );
873 | cmdStr = cmdStr.substring(4);
874 | } //done with pixels
875 | strip.Show();
876 | #endif
877 | cmdStr="";
878 | } //done with cmd
879 |
880 | if (Refresh) { //Refresh gets set once a second by Second_Tick() in global.h
881 | Refresh = false; //service it here when we get a round toit.
882 | if (!AdminEnabled //not in admin mode
883 | && config.Logging //and we are logging, but
884 | && config.sleepy //we are setup to go to sleep //config.Interval>0 causes webserver issues here
885 | && !havedata //not waiting on data to be logged to the server //rxbuf.length()==0 causes old webserver issues here
886 | ) { //then lets go to sleep
887 | debugln("Sleep for ",config.Interval);
888 | digitalWrite(CLEAR_BLINK, HIGH); //allow new blinks to be detected
889 | pinMode(CLEAR_BLINK, OUTPUT); //incase it was overwritten by Serial1 NeoPixel cmdString
890 |
891 | //TODO: Drop the connection to the device.
892 | ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcmem, sizeof(rtcmem)); //write data to RTC memory so we don't loose it.
893 | //TODO: Compensate for how long we have already been awake. e.g. (Interval - DateTime.Seconds)
894 | ESP.deepSleep(config.Interval * MICROSECONDS, WAKE_NO_RFCAL); //deep sleep, assume RF ok, wake back up in setup.
895 | }
896 | else {
897 | // debugln(config.sleepy?"1":"0",havedata?"1":"0");
898 | #ifdef TFT_DISPLAY
899 | if (config.datacount && !readingcount--) {
900 | readingcount = config.datacount;
901 | writeStr_x(config.datatrigger);
902 | }
903 | #endif
904 | }
905 |
906 | if (pwrondelay) { //waiting to send power on string
907 | debugq(String(pwrondelay--));
908 | if (!pwrondelay) {
909 | writeStr_x(config.pwronstr);
910 | debugq("<"+String(config.pwronstr));
911 | }
912 | }
913 |
914 | #ifdef DEBUGGING
915 | if (debugbuf.length()>0) {
916 | debugln(debugbuf,"");
917 | #ifdef TFT_DISPLAY
918 | #if DEBUGGING == 2
919 | tft.setCursor(debug_x, debug_y);
920 | tft.setTextColor(TFT_WHITE,TFT_BLUE); tft.setTextFont(1); tft.setTextSize(1);
921 | tft.println(debugbuf);
922 | debug_x = tft.getCursorX();
923 | debug_y = tft.getCursorY();
924 | if (debug_y > TFT_DEBUG_END) {
925 | debug_x=1; debug_y=TFT_DEBUG_START;
926 | }
927 | #endif
928 | #endif
929 | debugbuf="";
930 | }
931 | #endif
932 | #ifdef TFT_DISPLAY
933 | if (config.datacount) { //don't mess with this if we aren't updating the local display.
934 | tft.drawLine(0, 0, 128, 0, TFT_BLACK); //erase the prior reading
935 | //tft.drawLine(0, 0, (int)(ESP.getVcc()/50), 0, TFT_RBG_COLOR(0,0,255)); //read power rail. Needs ADC_MODE(ADC_VCC);
936 | tft.drawLine(0, 0, (int)(analogRead(A0)*TFT_WIDTH/1024), 0, TFT_RBG_COLOR(0,0,255)); //Read analog input. 0-1.0 volts
937 | tft.drawLine(0, 1, TFT_WIDTH, 1, TFT_BLACK); //erase the prior reading
938 | tft.drawLine(0, 1, (int)random(80), 1, TFT_RBG_COLOR(255,0,0)); //TODO: Replace with something useful
939 | showreading(String(config.dataslope1*(float)reading1+config.dataoffset1)+config.dataname1,-TFT_WIDTH,TFT_HEIGHT/3,4);
940 | showreading(String(config.dataslope2*(float)reading2+config.dataoffset2)+config.dataname2,-TFT_WIDTH,TFT_HEIGHT/2,4);
941 | showreading(String(config.dataslope3*(float)reading3+config.dataoffset3)+config.dataname3,-TFT_WIDTH,TFT_HEIGHT/1.5,4);
942 | }
943 | #endif
944 |
945 | } // End 1 second Refresh tick
946 |
947 |
948 | } // main loop
949 |
950 |
951 |
--------------------------------------------------------------------------------
/example.h:
--------------------------------------------------------------------------------
1 | #ifndef PAGE_EXAMPLE_H
2 | #define PAGE_EXAMPLE_H
3 | //
4 | // The EXAMPLE PAGE
5 | //
6 | const char PAGE_example[] PROGMEM = R"=====(
7 |
8 |
9 |
My Example goes here
10 |
11 |
Here comes the Dynamic Data in
12 |
30 |
31 | )=====";
32 | #endif
33 |
34 |
35 | void filldynamicdata(AsyncWebServerRequest *request)
36 | {
37 | String values ="";
38 | values += "mydynamicdata|" + (String) + "This is filled by AJAX. Millis since start: " + (String) millis() + "|div\n"; // Build a string, like this: ID|VALUE|TYPE
39 | request->send ( 200, "text/plain", values);
40 | }
41 |
42 | void processExample(AsyncWebServerRequest *request)
43 | {
44 | if (request->args() > 0 ) // Are there any POST/GET Fields ?
45 | {
46 | for ( uint8_t i = 0; i < request->args(); i++ ) { // Iterate through the fields
47 | if (request->argName(i) == "firstname")
48 | {
49 | // Your processing for the transmitted form-variable
50 | String fName = request->arg(i);
51 | }
52 | }
53 | }
54 | request->send ( 200, "text/html", PAGE_example );
55 | }
56 |
--------------------------------------------------------------------------------
/global.h:
--------------------------------------------------------------------------------
1 | #ifndef GLOBAL_H
2 | #define GLOBAL_H
3 |
4 | //ESP8266WebServer server(80); // The Webserver
5 | AsyncWebServer server(80);
6 |
7 | boolean firstStart = true; // On firststart = true, NTP will try to get a valid time
8 | int AdminTimeOutCounter = 0; // Counter for Disabling the AdminMode
9 | strDateTime DateTime; // Global DateTime structure, will be refreshed every Second
10 | WiFiUDP UDPNTPClient; // NTP Client
11 | unsigned long UnixTimestamp = 0; // GLOBALTIME ( Will be set by NTP)
12 | boolean Refresh = false; // For Main Loop, to refresh things like GPIO / WS2812
13 | int cNTP_Update = 0; // Counter for Updating the time via NTP
14 | Ticker tkSecond; // Second - Timer for Updating Datetime Structure
15 | boolean AdminEnabled = true; // Enable Admin Mode for a given Time
16 | byte Minute_Old = 100; // Helpvariable for checking, when a new Minute comes up (for Auto Turn On / Off)
17 | HTTPClient http;
18 | //http.setReuse(true); //if server allows it
19 |
20 | String cmdStr = ""; //holds incomming IO commands.
21 | boolean havecmd = false; //flag to indicate we have an IO command to process.
22 |
23 | /* CONFIGURATION */
24 | #define CONFIG_VER 1
25 |
26 | struct strConfig {
27 | boolean dhcp = true;
28 | boolean daylight = true;
29 | long Update_Time_Via_NTP_Every = 60;
30 | long timezone = -8;
31 | // byte LED_R;
32 | // byte LED_G;
33 | // byte LED_B;
34 | byte IP[4]={192,168,1,100};
35 | byte Netmask[4]={255,255,255,0};
36 | byte Gateway[4]={192,168,1,1};
37 | char ssid[32] = "attwifi";
38 | char password[32]="";
39 | char ntpServerName[64] = "0.pool.ntp.org";
40 | char streamServerURL[64] = "http://www.massmind.org/techref/getline.asp?";
41 |
42 | boolean Logging = false;
43 | byte WakeCount = 10;
44 | long baud = 9600;
45 | boolean Connect = true; //should we enable (optional) RS232 level converter?
46 | //byte TurnOnHour;
47 | //byte TurnOnMinute;
48 | //byte TurnOffHour;
49 | //byte TurnOffMinute;
50 | long Interval = 0; //Time to stay asleep. Zero means stay on.
51 | boolean sleepy = false; //flag to set if Interval > 0. doesn't actually need to be saved!
52 |
53 | char DeviceName[32] = "Not Named";
54 | char datatrigger[10] = "r%0D";
55 | char dataregexp1[32] = "r%*1crr_%4x0_%4x1_%4x2";
56 | float dataslope1 = 1;
57 | float dataoffset1 = 0;
58 | float dataslope2 = 1;
59 | float dataoffset2 = 0;
60 | float dataslope3 = 1;
61 | float dataoffset3 = 0;
62 | byte datacount = 0;
63 | char dataname1[5] = "????"; //5 because terminating null.
64 | char dataname2[5] = "????";
65 | char dataname3[5] = "????";
66 | char pwronstr[10] = "";
67 | byte pwrondelay = 0;
68 | } config;
69 |
70 | void WriteConfig() {
71 | //EEPROM actually uses SPI_FLASH_SEC_SIZE which appears to be 4096, but we were only allocating 512 bytes on startup
72 | //because of the way we write the next bit of data past the end of the last here, this is what limited the size of
73 | //the values. Oh, and ReadStringFromEEPROM only allows 65 characters. TODO: Yike.
74 | debugln(" Writing Config v", CONFIG_VER);
75 | EEPROM.write(0, 'C');
76 | EEPROM.write(1, 'F');
77 | EEPROM.write(2, CONFIG_VER);
78 | EEPROM.put(3,config);
79 | EEPROM.commit();
80 | }
81 |
82 | boolean ReadConfig() {
83 | debug("Reading Config. Found v", EEPROM.read(2));
84 | if (EEPROM.read(0) == 'C' && EEPROM.read(1) == 'F' && EEPROM.read(2) == CONFIG_VER ) {
85 | EEPROM.get(3,config);
86 | debugln(" loaded v", CONFIG_VER);
87 | return true;
88 | }
89 | else { // DEFAULT CONFIG
90 | debug(". Replaced w/ default v", CONFIG_VER);
91 | WriteConfig();
92 | return false;
93 | }
94 | }
95 |
96 |
97 |
98 | String get_wifi_status() {
99 | String state = "N/A";
100 | String Networks = "";
101 | if (WiFi.status() == 0) state = "Idle";
102 | else if (WiFi.status() == 1) state = "NO SSIDs";
103 | else if (WiFi.status() == 2) state = "SCANNING"; //was SCAN COMPLETE?
104 | else if (WiFi.status() == 3) state = "CONNECTED: " + WiFi.localIP().toString();
105 | else if (WiFi.status() == 4) state = "FAILED";
106 | else if (WiFi.status() == 5) state = "DROPPED";
107 | else if (WiFi.status() == 6) state = "TRY"; //Was DISCONNECTED
108 | return state;
109 | }
110 |
111 | void ConfigureWifi() {
112 | //https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/readme.md#enable-wi-fi-diagnostic
113 |
114 | debugln("Begin Wifi to point:", config.ssid);
115 | //debugln("Password:",config.password);
116 | WiFi.begin (config.ssid, config.password);
117 | if (!config.dhcp) {
118 | debugln(" hardcoded", "");
119 | WiFi.config(
120 | IPAddress(config.IP[0], config.IP[1], config.IP[2], config.IP[3] ),
121 | IPAddress(config.Gateway[0], config.Gateway[1], config.Gateway[2], config.Gateway[3] ),
122 | IPAddress(config.Netmask[0], config.Netmask[1], config.Netmask[2], config.Netmask[3] )
123 | );
124 | }
125 | for (char i = 0; ( ( i < 5) && WiFi.status() != WL_CONNECTED ); i++) {
126 | delay(1000 * i);
127 | debug(get_wifi_status(), " "); //this will print our IP if we have one.
128 | }
129 | if (WL_CONNECTED == WiFi.status()) {
130 | AdminEnabled = false; //no need for admin if we are online}
131 | WiFi.mode(WIFI_STA); //TODO: Re-enable
132 | debugln("\nAdmin closed. Connect to: ", WiFi.localIP().toString());
133 | }
134 | //debugln(" Gateway:",WiFi.gatewayIP());
135 | //debugln(" localIP:",WiFi.localIP());
136 | }
137 |
138 |
139 |
140 | /*
141 | **
142 | ** NTP
143 | **
144 | */
145 |
146 | const int NTP_PACKET_SIZE = 48;
147 | byte packetBuffer[ NTP_PACKET_SIZE];
148 |
149 | void NTPRefresh() {
150 | if (WiFi.status() == WL_CONNECTED) {
151 | IPAddress timeServerIP;
152 | WiFi.hostByName(config.ntpServerName, timeServerIP);
153 | //sendNTPpacket(timeServerIP); // send an NTP packet to a time server
154 |
155 | debugln("sending NTP packet...","");
156 | memset(packetBuffer, 0, NTP_PACKET_SIZE);
157 | packetBuffer[0] = 0b11100011; // LI, Version, Mode
158 | packetBuffer[1] = 0; // Stratum, or type of clock
159 | packetBuffer[2] = 6; // Polling Interval
160 | packetBuffer[3] = 0xEC; // Peer Clock Precision
161 | packetBuffer[12] = 49;
162 | packetBuffer[13] = 0x4E;
163 | packetBuffer[14] = 49;
164 | packetBuffer[15] = 52;
165 | UDPNTPClient.beginPacket(timeServerIP, 123);
166 | UDPNTPClient.write(packetBuffer, NTP_PACKET_SIZE);
167 | UDPNTPClient.endPacket();
168 |
169 | delay(1000);
170 |
171 | int cb = UDPNTPClient.parsePacket();
172 | if (!cb) {
173 | debugln("NTP no packet yet", cb);
174 | }
175 | else {
176 | debugln("NTP packet received, length=", cb);
177 | UDPNTPClient.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
178 | unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
179 | unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
180 | unsigned long secsSince1900 = highWord << 16 | lowWord;
181 | const unsigned long seventyYears = 2208988800UL;
182 | unsigned long epoch = secsSince1900 - seventyYears;
183 | UnixTimestamp = epoch;
184 | }
185 | }
186 | }
187 |
188 | void Second_Tick() {
189 | strDateTime tempDateTime;
190 | AdminTimeOutCounter++;
191 | cNTP_Update++;
192 | UnixTimestamp++;
193 | ConvertUnixTimeStamp(UnixTimestamp + (config.timezone * 360) , &tempDateTime);
194 | if (config.daylight) // Sommerzeit beachten
195 | if (summertime(tempDateTime.year, tempDateTime.month, tempDateTime.day, tempDateTime.hour, 0)) {
196 | ConvertUnixTimeStamp(UnixTimestamp + (config.timezone * 360) + 3600, &DateTime);
197 | }
198 | else {
199 | DateTime = tempDateTime;
200 | }
201 | else {
202 | DateTime = tempDateTime;
203 | }
204 | Refresh = true;
205 | }
206 |
207 | String parseServer(String response) { //get out any settings and make those changes, leaving just the text to send to the device.
208 | char c;
209 | int p1=0,p2=0;
210 | String text;
211 | for (int i =0; i < response.length(); i++){
212 | c=response.charAt(i);
213 | switch(c) {
214 | case '\\':
215 | i++; //don't look at escaped characters
216 | loop;
217 | case '{':
218 | text = response.substring(1,i);
219 | p1 = i+1; //start of first parameter
220 | break;
221 | case ':':
222 | p2 = i; //end of paramter, start of value
223 | #ifdef DEBUGGING
224 | debugbuf+=" param:"+response.substring(p1,p2);
225 | #endif
226 | break;
227 | case ',':
228 | case '}':
229 | #ifdef DEBUGGING
230 | debugbuf+=", val:"+response.substring(p2+1,i);
231 | #endif
232 | if ( response.substring(p1,p2) == "interval" ) {
233 | config.Interval = response.substring(p2+1,i).toInt();
234 | if (config.Interval>0) config.sleepy=true; else config.sleepy=false;
235 | #ifdef DEBUGGING
236 | debugbuf+="\n interval="+String(config.Interval);
237 | #endif
238 | }
239 | if ( response.substring(p1,p2) == "cmd" ) {
240 | cmdStr=response.substring(p2+1,i);
241 | #ifdef DEBUGGING
242 | debugbuf+="\n cmd";//="+cmdStr;
243 | #endif
244 | havecmd=true;
245 | }
246 | p1 = i+1; //start of next parameter if it was ','
247 | break;
248 | }
249 | }
250 | if (0==p1) {text = response;} //if no JASON, entire string is text for device.
251 | return text;
252 | }
253 |
254 | #endif
255 |
256 |
--------------------------------------------------------------------------------
/helpers.h:
--------------------------------------------------------------------------------
1 | #ifndef HELPERS_H
2 | #define HELPERS_H
3 |
4 |
5 | #ifdef DEBUGGING
6 | void swapin() {
7 | Serial.flush();
8 | delay(5);//can't be used with ESPAsyncWebServer
9 | Serial.swap();
10 | // Serial.begin(DEBUG_BAUD_RATE);
11 | Serial.flush();
12 | //when not used as serial, keep TX high or device will see nulls or FF's
13 | //pinMode(TX2, OUTPUT);
14 | //digitalWrite(TX2, HIGH);
15 | //NOPE! This actually causes garbage!
16 | //pinMode(RX2,INPUT_PULLUP); // when not used as serial, keep RX high or we may see nulls or FF's
17 | }
18 |
19 | void swapout() {
20 | Serial.flush();
21 | delay(5);//can't be used with ESPAsyncWebServer
22 | Serial.swap();
23 | // Serial.begin(BAUD_RATE);
24 | Serial.flush();
25 | }
26 |
27 | #define debug(dir,msg) swapin();Serial.print(dir);Serial.print(msg);swapout();
28 | #define debugln(dir,msg) swapin();Serial.print(dir);Serial.println(msg);swapout();
29 | //adding Serial.print(0); seems to compensate for the loss of the last crlf when using ESPAsyncWebServer
30 | #define debughex(msg) swapin();Serial.print(">");for(int i=0;i0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )
44 |
45 |
46 | struct strDateTime
47 | {
48 | byte hour;
49 | byte minute;
50 | byte second;
51 | int year;
52 | byte month;
53 | byte day;
54 | byte wday;
55 |
56 | } ;
57 |
58 |
59 |
60 | //
61 | // Summertime calculates the daylight saving for a given date.
62 | //
63 | boolean summertime(int year, byte month, byte day, byte hour, byte tzHours)
64 | // input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ)
65 | {
66 | if (month<3 || month>10) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez
67 | if (month>3 && month<10) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep
68 | if (month==3 && (hour + 24 * day)>=(1 + tzHours + 24*(31 - (5 * year /4 + 4) % 7)) || month==10 && (hour + 24 * day)<(1 + tzHours + 24*(31 - (5 * year /4 + 1) % 7)))
69 | return true;
70 | else
71 | return false;
72 | }
73 |
74 | //
75 | // Check the Values is between 0-255
76 | //
77 | boolean checkRange(String Value)
78 | {
79 | if (Value.toInt() < 0 || Value.toInt() > 255)
80 | {
81 | return false;
82 | }
83 | else
84 | {
85 | return true;
86 | }
87 | }
88 |
89 |
90 | void WriteStringToEEPROM(int beginaddress, String string)
91 | {
92 | char charBuf[string.length()+1];
93 | string.toCharArray(charBuf, string.length()+1);
94 | for (int t= 0; t 65) break;
109 | counter++;
110 | retString.concat(rChar);
111 |
112 | }
113 | return retString;
114 | }
115 | void EEPROMWritelong(int address, long value)
116 | {
117 | byte four = (value & 0xFF);
118 | byte three = ((value >> 8) & 0xFF);
119 | byte two = ((value >> 16) & 0xFF);
120 | byte one = ((value >> 24) & 0xFF);
121 |
122 | //Write the 4 bytes into the eeprom memory.
123 | EEPROM.write(address, four);
124 | EEPROM.write(address + 1, three);
125 | EEPROM.write(address + 2, two);
126 | EEPROM.write(address + 3, one);
127 | }
128 | long EEPROMReadlong(long address)
129 | {
130 | //Read the 4 bytes from the eeprom memory.
131 | long four = EEPROM.read(address);
132 | long three = EEPROM.read(address + 1);
133 | long two = EEPROM.read(address + 2);
134 | long one = EEPROM.read(address + 3);
135 |
136 | //Return the recomposed long by using bitshift.
137 | return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
138 | }
139 |
140 | void ConvertUnixTimeStamp( unsigned long TimeStamp, struct strDateTime* DateTime)
141 | {
142 | uint8_t year;
143 | uint8_t month, monthLength;
144 | uint32_t time;
145 | unsigned long days;
146 | time = (uint32_t)TimeStamp;
147 | DateTime->second = time % 60;
148 | time /= 60; // now it is minutes
149 | DateTime->minute = time % 60;
150 | time /= 60; // now it is hours
151 | DateTime->hour = time % 24;
152 | time /= 24; // now it is days
153 | DateTime->wday = ((time + 4) % 7) + 1; // Sunday is day 1
154 |
155 | year = 0;
156 | days = 0;
157 | while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
158 | year++;
159 | }
160 | DateTime->year = year; // year is offset from 1970
161 |
162 | days -= LEAP_YEAR(year) ? 366 : 365;
163 | time -= days; // now it is days in this year, starting at 0
164 |
165 | days=0;
166 | month=0;
167 | monthLength=0;
168 | for (month=0; month<12; month++) {
169 | if (month==1) { // february
170 | if (LEAP_YEAR(year)) {
171 | monthLength=29;
172 | } else {
173 | monthLength=28;
174 | }
175 | } else {
176 | monthLength = monthDays[month];
177 | }
178 |
179 | if (time >= monthLength) {
180 | time -= monthLength;
181 | } else {
182 | break;
183 | }
184 | }
185 | DateTime->month = month + 1; // jan is month 1
186 | DateTime->day = time + 1; // day of month
187 | DateTime->year += 1970;
188 |
189 |
190 | }
191 |
192 |
193 |
194 | String GetMacAddress() {
195 | uint8_t mac[6];
196 | char macStr[18] = {0};
197 | WiFi.macAddress(mac);
198 | sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
199 | //TODO: Rewrite using nibble2hex as sprintf is expensive.
200 | return String(macStr);
201 | }
202 |
203 | char nibble2hex(char c) {
204 | return "0123456789ABCDEF"[c&0xf];
205 | }
206 |
207 | // convert a single hex digit character to its integer value (from https://code.google.com/p/avr-netino/)
208 | unsigned char h2int(char c) {
209 | if (c >= '0' && c <='9') { return((unsigned char)c - '0'); }
210 | if (c >= 'a' && c <='f') { return((unsigned char)c - 'a' + 10); }
211 | if (c >= 'A' && c <='F') { return((unsigned char)c - 'A' + 10); }
212 | return(0);
213 | }
214 |
215 | int hex2int(String s) {
216 | int v=0;
217 | for (int i = s.length(); i>0; i--) { //index s from right (msb) to left (lsb)
218 | v |= h2int(s[i]);
219 | v *= 16;
220 | }
221 | if ('-'==s[0]) v=-v;
222 | return v;
223 | }
224 |
225 | int urldecode(String input, char *output, int len) {// (based on https://code.google.com/p/avr-netino/)
226 | char c;
227 | len--; //leave room for the terminating zero.
228 | for(byte t=0;t= --len) break;
239 | }
240 | *output='\0';
241 | return len;
242 | }
243 |
244 | String urlencode(const char *str) {
245 | String encoded = String();
246 | encoded.reserve(strlen(str)*2); // what is generally enough
247 | char c;
248 | while (c = *str++){
249 | if (' ' == c){
250 | encoded+= '+';
251 | }
252 | else if (isalnum(c)){
253 | encoded+=c;
254 | }
255 | else{
256 | encoded+='%';
257 | encoded+=nibble2hex(c>>4);
258 | encoded+=nibble2hex(c);
259 | }
260 | }
261 | return encoded;
262 | }
263 |
264 | String HTMLencode(const char *str) {
265 | String encoded = String();
266 | encoded.reserve(strlen(str)*2);
267 | char c;
268 | while (c = *str++){
269 | switch(c) {
270 | case '&': encoded+="&"; break;
271 | case '\"': encoded+="""; break;
272 | case '\'': encoded+="'"; break;
273 | case '<': encoded+="<"; break;
274 | case '>': encoded+=">"; break;
275 | default: encoded+=c; break;
276 | }
277 | }
278 | return encoded;
279 | }
280 |
281 | #endif
282 |
--------------------------------------------------------------------------------