diff --git a/watering/.vscode/settings.json b/watering/.vscode/settings.json index 023a4c3..fd4c047 100644 --- a/watering/.vscode/settings.json +++ b/watering/.vscode/settings.json @@ -9,6 +9,12 @@ "vector": "cpp", "string_view": "cpp", "initializer_list": "cpp", - "regex": "cpp" + "regex": "cpp", + "new": "cpp", + "*.tcc": "cpp", + "optional": "cpp", + "system_error": "cpp", + "sstream": "cpp", + "memory": "cpp" } } \ No newline at end of file diff --git a/watering/data/index.html b/watering/data/index.html new file mode 100644 index 0000000..d8c5346 --- /dev/null +++ b/watering/data/index.html @@ -0,0 +1,164 @@ + + + + + + + Simple.css Test Page + + + + +
+

Gartenbewässerung

+

%HOSTNAME% Connecting...

+
+
+
+

%NAME_VALVE1%

+ Unbekannt +
+

+ + + + + +
+

--

Std. +
+

--

Min. +
+

--

Sek. +
+ +

+ +
+ + + +

Timer

+
+

Garten vorn:

+

Minuten

+ + +
+
+ +

Timer

+
+

Tröge:

+

Minuten

+ + +
+
+ + + + + \ No newline at end of file diff --git a/watering/data/simple.css b/watering/data/simple.css new file mode 100644 index 0000000..35e9e24 --- /dev/null +++ b/watering/data/simple.css @@ -0,0 +1,762 @@ +/* Global variables. */ +:root { + /* Set sans-serif & mono fonts */ + --sans-font: -apple-system, BlinkMacSystemFont, "Avenir Next", Avenir, + "Nimbus Sans L", Roboto, "Noto Sans", "Segoe UI", Arial, Helvetica, + "Helvetica Neue", sans-serif; + --mono-font: Consolas, Menlo, Monaco, "Andale Mono", "Ubuntu Mono", monospace; + --standard-border-radius: 8px; + + /* Default (light) theme */ + --bg: #fff; + --accent-bg: #f5f7ff; + --text: #212121; + --text-light: #585858; + --border: #898EA4; + --accent: #0d47a1; + --ok: #279c1c; + --warn: #f1d323; + --fail: #d12e2e; + --accent-hover: #1266e2; + --accent-text: var(--bg); + --code: #d81b60; + --preformatted: #444; + --marked: #e9c92b; + --disabled: #efefef; +} + +/* Dark theme */ +@media (prefers-color-scheme: dark) { + :root { + color-scheme: dark; + --bg: #212121; + --accent-bg: #2b2b2b; + --text: #dcdcdc; + --text-light: #ababab; + --accent: #113b1e; + --ok: #279c1c; + --warn: #ddd125; + --fail: #ce3030; + --accent-hover: #1b5a2f; + --accent-text: var(--bg); + --code: #f06292; + --preformatted: #ccc; + --disabled: #111; + } + /* Add a bit of transparency so light media isn't so glaring in dark mode */ + img, + video { + opacity: 0.8; + } +} + +/* Reset box-sizing */ +*, *::before, *::after { + box-sizing: border-box; +} + +/* Reset default appearance */ +textarea, +select, +input, +progress { + appearance: none; + -webkit-appearance: none; + -moz-appearance: none; +} + +html { + /* Set the font globally */ + font-family: var(--sans-font); + scroll-behavior: smooth; +} + +/* Make the body a nice central block */ +body { + color: var(--text); + background-color: var(--bg); + font-size: 1.15rem; + line-height: 1.5; + display: grid; + grid-template-columns: 1fr min(45rem, 90%) 1fr; + margin: 0; +} +body > * { + grid-column: 2; +} + +/* Make the header bg full width, but the content inline with body */ +body > header { + background-color: var(--accent-bg); + border-bottom: 1px solid var(--border); + text-align: center; + padding: 0 0.5rem 0.5rem 0.5rem; + grid-column: 1 / -1; +} + +body > header > *:only-child { + margin-block-start: 2rem; +} + +body > header h1 { + max-width: 1200px; + margin: 1rem auto; +} + +body > header p { + max-width: 40rem; + margin: 1rem auto; +} +/* Add a little padding to ensure spacing is correct between content and header nav */ +main { + padding-top: 1.5rem; +} +body > footer { + margin-top: 1rem; + padding: 0rem 1rem 1.5rem 1rem; + color: var(--text-light); + font-size: 0.9rem; + text-align: center; + border-top: 1px solid var(--border); +} + +/* Format headers */ +h1 { + font-size: 3rem; + margin-top: 0.5rem; + padding-bottom: 0.5rem; +} + +h2 { + font-size: 2.6rem; + margin-top: 1rem; +} + +h3 { + font-size: 2rem; + margin-top: 1rem; +} + +h4 { + font-size: 1.44rem; +} + +h5 { + font-size: 1.15rem; +} + +h6 { + font-size: 0.96rem; +} + +p { + margin: 1.5rem 0; +} + +/* Prevent long strings from overflowing container */ +p, h1, h2, h3, h4, h5, h6 { + overflow-wrap: break-word; +} + +/* Fix line height when title wraps */ +h1, +h2, +h3 { + line-height: 1; +} + +/* Reduce header size on mobile */ +@media only screen and (max-width: 720px) { + h1 { + font-size: 2.5rem; + } + + h2 { + font-size: 2.1rem; + } + + h3 { + font-size: 1.75rem; + } + + h4 { + font-size: 1.25rem; + } +} + +/* Format links & buttons */ +a, +a:visited { + color: var(--accent); +} + +a:hover { + text-decoration: none; +} + +button, +.button, +a.button, /* extra specificity to override a */ +input[type="submit"], +input[type="reset"], +input[type="button"] { + border: 1px solid var(--accent); + background-color: var(--accent); + color: var(--text); + padding: 0.5rem 0.9rem; + text-decoration: none; + line-height: normal; +} + +.button[aria-disabled="true"], +input:disabled, +textarea:disabled, +select:disabled, +button[disabled] { + cursor: not-allowed; + background-color: var(--disabled); + border-color: var(--disabled); + color: var(--text-light); +} + +input[type="range"] { + padding: 0; +} + +/* Set the cursor to '?' on an abbreviation and style the abbreviation to show that there is more information underneath */ +abbr[title] { + cursor: help; + text-decoration-line: underline; + text-decoration-style: dotted; +} + +button:enabled:hover, +.button:not([aria-disabled="true"]):hover, +input[type="submit"]:enabled:hover, +input[type="reset"]:enabled:hover, +input[type="button"]:enabled:hover { + background-color: var(--accent-hover); + border-color: var(--accent-hover); + cursor: pointer; +} + +.button:focus-visible, +button:focus-visible:where(:enabled), +input:enabled:focus-visible:where( + [type="submit"], + [type="reset"], + [type="button"] +) { + outline: 2px solid var(--accent); + outline-offset: 1px; +} + +/* Format navigation */ +header nav { + font-size: 1rem; + line-height: 2; + padding: 1rem 0 0 0; +} + +/* Use flexbox to allow items to wrap, as needed */ +header nav ul, +header nav ol { + align-content: space-around; + align-items: center; + display: flex; + flex-direction: row; + flex-wrap: wrap; + justify-content: center; + list-style-type: none; + margin: 0; + padding: 0; +} + +/* List items are inline elements, make them behave more like blocks */ +header nav ul li, +header nav ol li { + display: inline-block; +} + +header nav a, +header nav a:visited { + margin: 0 0.5rem 1rem 0.5rem; + border: 1px solid var(--border); + border-radius: var(--standard-border-radius); + color: var(--text); + display: inline-block; + padding: 0.1rem 1rem; + text-decoration: none; +} + +header nav a:hover, +header nav a.current, +header nav a[aria-current="page"], +header nav a[aria-current="true"] { + border-color: var(--accent); + color: var(--accent); + cursor: pointer; +} + +/* Reduce nav side on mobile */ +@media only screen and (max-width: 720px) { + header nav a { + border: none; + padding: 0; + text-decoration: underline; + line-height: 1; + } +} + +/* Consolidate box styling */ +aside, details, pre, progress { + background-color: var(--accent-bg); + border: 1px solid var(--border); + border-radius: var(--standard-border-radius); + margin-bottom: 1rem; +} + +aside { + font-size: 1rem; + width: 30%; + padding: 0 15px; + margin-inline-start: 15px; + float: left; +} +*[dir="rtl"] aside { + float: left; +} + +/* Make aside full-width on mobile */ +@media only screen and (max-width: 720px) { + aside { + width: 100%; + float: none; + margin-inline-start: 0; + } +} + +article, fieldset, dialog { + border: 1px solid var(--border); + padding: 1rem; + border-radius: var(--standard-border-radius); + margin-bottom: 1rem; +} + +article h2:first-child, +section h2:first-child, +article h3:first-child, +section h3:first-child { + margin-top: 0.2rem; +} + +section { + border-top: 1px solid var(--border); + border-bottom: 1px solid var(--border); + padding: 0rem 1rem; + margin: 1rem 0; +} + +/* Don't double separators when chaining sections */ +section + section, +section:first-child { + border-top: 0; + padding-top: 0; +} + +section + section { + margin-top: 0; +} + +section:last-child { + border-bottom: 0; + padding-bottom: 0; +} + +details { + padding: 0.7rem 1rem; +} + +summary { + cursor: pointer; + font-weight: bold; + padding: 0.7rem 1rem; + margin: -0.7rem -1rem; + word-break: break-all; +} + +details[open] > summary + * { + margin-top: 0; +} + +details[open] > summary { + margin-bottom: 0.5rem; +} + +details[open] > :last-child { + margin-bottom: 0; +} + +/* Format tables */ +table { + margin: 1.5rem 0; + border-spacing: 20px 0px; +} + +figure > table { + width: max-content; + margin: 0; +} + +td, +th { + border: 1px solid var(--border); + border-radius: var(--standard-border-radius); + text-align: center; + padding: 0.5rem; +} + +th { + background-color: var(--accent-bg); + font-weight: bold; +} + +tr:nth-child(even) { + /* Set every other cell slightly darker. Improves readability. */ + background-color: var(--accent-bg); +} + +table caption { + font-weight: bold; + margin-bottom: 0.5rem; +} + +/* Format forms */ +textarea, +select, +input, +button, +.button { + font-size: inherit; + font-family: inherit; + padding: 0.5rem; + margin: 0 0.5rem 0 0.5rem; + border-radius: var(--standard-border-radius); + box-shadow: none; + max-width: 100%; + display: inline-block; +} +textarea, +select, +input { + color: var(--text); + background-color: var(--bg); + border: 1px solid var(--border); +} +label { + display: block; +} +textarea:not([cols]) { + width: 100%; +} + +/* Add arrow to drop-down */ +select:not([multiple]) { + background-image: linear-gradient(45deg, transparent 49%, var(--text) 51%), + linear-gradient(135deg, var(--text) 51%, transparent 49%); + background-position: calc(100% - 15px), calc(100% - 10px); + background-size: 5px 5px, 5px 5px; + background-repeat: no-repeat; + padding-inline-end: 25px; +} +*[dir="rtl"] select:not([multiple]) { + background-position: 10px, 15px; +} + +/* checkbox and radio button style */ +input[type="checkbox"], +input[type="radio"] { + vertical-align: middle; + position: relative; + width: min-content; +} + +input[type="checkbox"] + label, +input[type="radio"] + label { + display: inline-block; +} + +input[type="radio"] { + border-radius: 100%; +} + +input[type="checkbox"]:checked, +input[type="radio"]:checked { + background-color: var(--accent); +} + +input[type="checkbox"]:checked::after { + /* Creates a rectangle with colored right and bottom borders which is rotated to look like a check mark */ + content: " "; + width: 0.18em; + height: 0.32em; + border-radius: 0; + position: absolute; + top: 0.05em; + left: 0.17em; + background-color: transparent; + border-right: solid var(--bg) 0.08em; + border-bottom: solid var(--bg) 0.08em; + font-size: 1.8em; + transform: rotate(45deg); +} +input[type="radio"]:checked::after { + /* creates a colored circle for the checked radio button */ + content: " "; + width: 0.25em; + height: 0.25em; + border-radius: 100%; + position: absolute; + top: 0.125em; + background-color: var(--bg); + left: 0.125em; + font-size: 32px; +} + +/* Makes input fields wider on smaller screens */ +@media only screen and (max-width: 720px) { + textarea, + select, + input { + width: 100%; + } +} + +/* Set a height for color input */ +input[type="color"] { + height: 2.5rem; + padding: 0.2rem; +} + +/* do not show border around file selector button */ +input[type="file"] { + border: 0; +} + +/* Misc body elements */ +hr { + border: none; + height: 1px; + background: var(--border); + margin: 1rem auto; +} + +mark { + padding: 2px 5px; + border-radius: var(--standard-border-radius); + border: 2px solid var(--marked); + background-color: var(--bg); + color: var(--text); +} + +mark a { + color: #0d47a1; +} + +img, +video { + max-width: 100%; + height: auto; + border-radius: var(--standard-border-radius); +} + +figure { + margin: 0; + display: block; + overflow-x: auto; +} + +figure > img, +figure > picture > img { + display: block; + margin-inline: auto; +} + +figcaption { + text-align: center; + font-size: 0.9rem; + color: var(--text-light); + margin-block: 1rem; +} + +blockquote { + margin-inline-start: 2rem; + margin-inline-end: 0; + margin-block: 2rem; + padding: 0.4rem 0.8rem; + border-inline-start: 0.35rem solid var(--accent); + color: var(--text-light); + font-style: italic; +} + +cite { + font-size: 0.9rem; + color: var(--text-light); + font-style: normal; +} + +dt { + color: var(--text-light); +} + +/* Use mono font for code elements */ +code, +pre, +pre span, +kbd, +samp { + font-family: var(--mono-font); + color: var(--code); +} + +kbd { + color: var(--preformatted); + border: 1px solid var(--preformatted); + border-bottom: 3px solid var(--preformatted); + border-radius: var(--standard-border-radius); + padding: 0.1rem 0.4rem; +} + +pre { + padding: 1rem 1.4rem; + max-width: 100%; + overflow: auto; + color: var(--preformatted); +} + +/* Fix embedded code within pre */ +pre code { + color: var(--preformatted); + background: none; + margin: 0; + padding: 0; +} + +/* Progress bars */ +/* Declarations are repeated because you */ +/* cannot combine vendor-specific selectors */ +progress { + width: 100%; +} + +progress:indeterminate { + background-color: var(--accent-bg); +} + +progress::-webkit-progress-bar { + border-radius: var(--standard-border-radius); + background-color: var(--accent-bg); +} + +progress::-webkit-progress-value { + border-radius: var(--standard-border-radius); + background-color: var(--accent); +} + +progress::-moz-progress-bar { + border-radius: var(--standard-border-radius); + background-color: var(--accent); + transition-property: width; + transition-duration: 0.3s; +} + +progress:indeterminate::-moz-progress-bar { + background-color: var(--accent-bg); +} + +dialog { + background-color: var(--bg); + max-width: 40rem; + margin: auto; +} + +dialog::backdrop { + background-color: var(--bg); + opacity: 0.8; +} + +@media only screen and (max-width: 720px) { + dialog { + max-width: calc(100vw - 2rem); + } +} + +/* Superscript & Subscript */ +/* Prevent scripts from affecting line-height. */ +sup, sub { + vertical-align: baseline; + position: relative; +} + +sup { + top: -0.4em; +} + +sub { + top: 0.3em; +} + +/* Classes for notices */ +.notice { + background: var(--accent-bg); + border: 2px solid var(--border); + border-radius: var(--standard-border-radius); + padding: 1.5rem; + margin: 2rem 0; +} + +/* Print */ +@media print { + @page { + margin: 1cm; + } + body { + display: block; + } + body > header { + background-color: unset; + } + body > header nav, + body > footer { + display: none; + } + article { + border: none; + padding: 0; + } + a[href^="http"]::after { + content: " <" attr(href) ">"; + } + abbr[title]:after { + content: " (" attr(title) ")"; + } + a { + text-decoration: none; + } + p { + widows: 3; + orphans: 3; + } + hr { + border-top: 1px solid var(--border); + } + mark { + border: 1px solid var(--border); + } + pre, table, figure, img, svg { + break-inside: avoid; + } + pre code { + white-space: pre-wrap; + } +} diff --git a/watering/lib/2024-08-21_1456_V-Markt Immenstadt.pdf b/watering/lib/2024-08-21_1456_V-Markt Immenstadt.pdf new file mode 100644 index 0000000..05effb8 Binary files /dev/null and b/watering/lib/2024-08-21_1456_V-Markt Immenstadt.pdf differ diff --git a/watering/lib/ArduinoJson/.devcontainer/clang10/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang10/devcontainer.json deleted file mode 100644 index 7fa6130..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang10/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "Clang 10", - "image": "conanio/clang10", - "runArgs": [ - "--name=ArduinoJson-clang10" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang11/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang11/devcontainer.json deleted file mode 100644 index 572533e..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang11/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "Clang 11", - "image": "conanio/clang11", - "runArgs": [ - "--name=ArduinoJson-clang11" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang13/Dockerfile b/watering/lib/ArduinoJson/.devcontainer/clang13/Dockerfile deleted file mode 100644 index 74f4c5f..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang13/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM ubuntu:22.04 - -RUN apt-get update -RUN apt-get install -y cmake git clang-13 libc++-13-dev libc++abi-13-dev -ENV CC=clang-13 CXX=clang++-13 diff --git a/watering/lib/ArduinoJson/.devcontainer/clang13/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang13/devcontainer.json deleted file mode 100644 index fc747d5..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang13/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "Clang 13", - "build": { - "dockerfile": "Dockerfile" - }, - "runArgs": [ - "--name=ArduinoJson-clang13" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang14/Dockerfile b/watering/lib/ArduinoJson/.devcontainer/clang14/Dockerfile deleted file mode 100644 index 0e7d67f..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang14/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM ubuntu:22.04 - -RUN apt-get update -RUN apt-get install -y cmake git clang-14 libc++-14-dev libc++abi-14-dev -ENV CC=clang-14 CXX=clang++-14 diff --git a/watering/lib/ArduinoJson/.devcontainer/clang14/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang14/devcontainer.json deleted file mode 100644 index 716e824..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang14/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "Clang 14", - "build": { - "dockerfile": "Dockerfile" - }, - "runArgs": [ - "--name=ArduinoJson-clang14" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang15/Dockerfile b/watering/lib/ArduinoJson/.devcontainer/clang15/Dockerfile deleted file mode 100644 index 21abe15..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang15/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM ubuntu:22.04 - -RUN apt-get update -RUN apt-get install -y cmake git clang-15 libc++-15-dev libc++abi-15-dev -ENV CC=clang-15 CXX=clang++-15 diff --git a/watering/lib/ArduinoJson/.devcontainer/clang15/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang15/devcontainer.json deleted file mode 100644 index b802f2f..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang15/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "Clang 15", - "build": { - "dockerfile": "Dockerfile" - }, - "runArgs": [ - "--name=ArduinoJson-clang15" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang16/Dockerfile b/watering/lib/ArduinoJson/.devcontainer/clang16/Dockerfile deleted file mode 100644 index 206efc1..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang16/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM ubuntu:22.04 - -RUN apt-get update -RUN apt-get install -y cmake git clang-16 libc++-16-dev libc++abi-16-dev -ENV CC=clang-16 CXX=clang++-16 diff --git a/watering/lib/ArduinoJson/.devcontainer/clang16/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang16/devcontainer.json deleted file mode 100644 index 650cf79..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang16/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "Clang 16", - "build": { - "dockerfile": "Dockerfile" - }, - "runArgs": [ - "--name=ArduinoJson-clang16" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang17/Dockerfile b/watering/lib/ArduinoJson/.devcontainer/clang17/Dockerfile deleted file mode 100644 index 1b4501a..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang17/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM ubuntu:24.04 - -RUN apt-get update -RUN apt-get install -y cmake git clang-17 libc++-17-dev libc++abi-17-dev -ENV CC=clang-17 CXX=clang++-17 diff --git a/watering/lib/ArduinoJson/.devcontainer/clang17/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang17/devcontainer.json deleted file mode 100644 index 6980f1c..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang17/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "Clang 17", - "build": { - "dockerfile": "Dockerfile" - }, - "runArgs": [ - "--name=ArduinoJson-clang17" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang5/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang5/devcontainer.json deleted file mode 100644 index 8844d13..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang5/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "Clang 5", - "image": "conanio/clang50", - "runArgs": [ - "--name=ArduinoJson-clang5" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang6/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang6/devcontainer.json deleted file mode 100644 index e4a35f4..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang6/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "Clang 6", - "image": "conanio/clang60", - "runArgs": [ - "--name=ArduinoJson-clang6" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang7/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang7/devcontainer.json deleted file mode 100644 index 1a8b558..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang7/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "Clang 7", - "image": "conanio/clang7", - "runArgs": [ - "--name=ArduinoJson-clang7" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang8/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang8/devcontainer.json deleted file mode 100644 index 7be7680..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang8/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "Clang 8", - "image": "conanio/clang8", - "runArgs": [ - "--name=ArduinoJson-clang8" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/clang9/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/clang9/devcontainer.json deleted file mode 100644 index 46f07fc..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/clang9/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "Clang 9", - "image": "conanio/clang9", - "runArgs": [ - "--name=ArduinoJson-clang9" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc10/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc10/devcontainer.json deleted file mode 100644 index d6dfba0..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc10/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "GCC 10", - "image": "conanio/gcc10", - "runArgs": [ - "--name=ArduinoJson-gcc10" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc11/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc11/devcontainer.json deleted file mode 100644 index 1edc308..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc11/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "GCC 11", - "image": "conanio/gcc11", - "runArgs": [ - "--name=ArduinoJson-gcc11" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc12/Dockerfile b/watering/lib/ArduinoJson/.devcontainer/gcc12/Dockerfile deleted file mode 100644 index a6275d4..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc12/Dockerfile +++ /dev/null @@ -1,4 +0,0 @@ -FROM ubuntu:22.04 - -RUN apt-get update -RUN apt-get install -y cmake git g++-12 diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc12/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc12/devcontainer.json deleted file mode 100644 index 8c744c8..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc12/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "GCC 12", - "build": { - "dockerfile": "Dockerfile", - }, - "runArgs": [ - "--name=ArduinoJson-gcc12" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc48/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc48/devcontainer.json deleted file mode 100644 index 660eac4..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc48/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "GCC 4.8", - "image": "conanio/gcc48", - "runArgs": [ - "--name=ArduinoJson-gcc48" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools", - "josetr.cmake-language-support-vscode", - "ms-vscode.cpptools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc5/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc5/devcontainer.json deleted file mode 100644 index 20ce7c1..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc5/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "GCC 5", - "image": "conanio/gcc5", - "runArgs": [ - "--name=ArduinoJson-gcc5" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc6/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc6/devcontainer.json deleted file mode 100644 index 35fb5fa..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc6/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "GCC 6", - "image": "conanio/gcc6", - "runArgs": [ - "--name=ArduinoJson-gcc6" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc7/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc7/devcontainer.json deleted file mode 100644 index 28bab20..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc7/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "GCC 7", - "image": "conanio/gcc7", - "runArgs": [ - "--name=ArduinoJson-gcc7" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc8/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc8/devcontainer.json deleted file mode 100644 index 622d472..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc8/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "GCC 8", - "image": "conanio/gcc8", - "runArgs": [ - "--name=ArduinoJson-gcc8" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.devcontainer/gcc9/devcontainer.json b/watering/lib/ArduinoJson/.devcontainer/gcc9/devcontainer.json deleted file mode 100644 index f946d9f..0000000 --- a/watering/lib/ArduinoJson/.devcontainer/gcc9/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "GCC 9", - "image": "conanio/gcc9", - "runArgs": [ - "--name=ArduinoJson-gcc9" - ], - "customizations": { - "vscode": { - "extensions": [ - "ms-vscode.cmake-tools" - ], - "settings": { - "cmake.generator": "Unix Makefiles", - "cmake.buildDirectory": "/tmp/build" - } - } - } -} diff --git a/watering/lib/ArduinoJson/.github/FUNDING.yml b/watering/lib/ArduinoJson/.github/FUNDING.yml deleted file mode 100644 index 0ec57d0..0000000 --- a/watering/lib/ArduinoJson/.github/FUNDING.yml +++ /dev/null @@ -1,4 +0,0 @@ -github: bblanchon -custom: - - https://arduinojson.org/book/ - - https://donate.benoitblanchon.fr/ diff --git a/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/bug_report.md b/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 57ee851..0000000 --- a/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -name: 🐛 Bug report -about: Report a bug in ArduinoJson -title: '' -labels: 'bug' -assignees: '' ---- - - - -**Describe the bug** -A clear and concise description of what the bug is. - -**Troubleshooter report** -Here is the report generated by the [ArduinoJson Troubleshooter](https://arduinojson.org/v7/troubleshooter/): -[Paste the report here] - -**Environment** -Here is the environment that I used: -* Microcontroller: [e.g. ESP8266] -* Core/runtime: [e.g. ESP8266 core for Arduino v3.0.2] -* IDE: [e.g. Arduino IDE 1.8.16] - -**Reproduction** -Here is a small snippet that reproduces the issue. - -```c++ -JsonDocument doc; - -DeserializationError error = deserializeJson(doc, "{\"hello\":\"world\"}"); - -[insert repro code here] -``` - -**Compiler output** -If relevant, include the complete compiler output (i.e. not just the line that contains the error.) - - -**Program output** -If relevant, include the repro program output. - -Expected output: - -``` -[insert expected output here] -``` - -Actual output: - -``` -[insert actual output here] -``` diff --git a/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/config.yml b/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 5f69e8e..0000000 --- a/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,8 +0,0 @@ -blank_issues_enabled: true -contact_links: - - name: 👨‍🏫 ArduinoJson Assistant - url: https://arduinojson.org/v7/assistant/ - about: An online tool that computes memory requirements and generates scaffolding code for your project. - - name: 👨‍⚕️ ArduinoJson Troubleshooter - url: https://arduinojson.org/v7/troubleshooter/ - about: An online tool that helps you diagnose the most common issues with ArduinoJson. diff --git a/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/feature_request.md b/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 889baaf..0000000 --- a/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: 💡 Feature request -about: Suggest an idea for ArduinoJson -title: '' -labels: enhancement -assignees: '' ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/help.md b/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/help.md deleted file mode 100644 index 4440b86..0000000 --- a/watering/lib/ArduinoJson/.github/ISSUE_TEMPLATE/help.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -name: 😭 Help! -about: Ask for help -title: '' -labels: 'question' -assignees: '' ---- - - - -**Describe the issue** -A clear and concise description of what you're trying to do. -You don't need to explain every aspect of your project: focus on the problem you're having. - -**Troubleshooter report** -Here is the report generated by the [ArduinoJson Troubleshooter](https://arduinojson.org/v7/troubleshooter/): -[Paste the report here] - -**Environment** -Here is the environment that I'm using': -* Microconroller: [e.g. ESP8266] -* Core/runtime: [e.g. ESP8266 core for Arduino v3.0.2] -* IDE: [e.g. Arduino IDE 1.8.16] - -**Reproduction** -Here is a small snippet that demonstrate the problem. - -```c++ -JsonDocument doc; - -DeserializationError error = deserializeJson(doc, "{\"hello\":\"world\"}"); - -// insert code here -``` - -**Program output** -If relevant, include the program output. - -Expected output: - -``` -[insert expected output here] -``` - -Actual output: - -``` -[insert actual output here] -``` diff --git a/watering/lib/ArduinoJson/.github/workflows/ci.yml b/watering/lib/ArduinoJson/.github/workflows/ci.yml deleted file mode 100644 index e605cc2..0000000 --- a/watering/lib/ArduinoJson/.github/workflows/ci.yml +++ /dev/null @@ -1,606 +0,0 @@ -name: Continuous Integration - -on: [push, pull_request] - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - lint: - name: Lint - runs-on: ubuntu-22.04 - steps: - - name: Install - run: sudo apt-get install -y clang-format - - name: Checkout - uses: actions/checkout@v4 - - name: Symlinks - run: find * -type l -printf "::error::%p is a symlink. This is forbidden by the Arduino Library Specification." -exec false {} + - - name: Clang-format - run: | - find src/ extras/ -name '*.[ch]pp' | xargs clang-format -i --verbose --style=file - git diff --exit-code - - name: Check URLs - run: | - grep -hREo "(http|https)://[a-zA-Z0-9./?=_%:-]*" src/ | sort -u | while read -r URL - do - STATUS=$(curl -s -o /dev/null -I -w "%{http_code}" "$URL") - [ "$STATUS" -ge 400 ] && echo "::warning title=HTTP $STATUS::$URL returned $STATUS" - done || true - - gcc: - name: GCC - needs: lint - runs-on: ubuntu-22.04 - strategy: - fail-fast: false - matrix: - include: - - gcc: "4.8" - - gcc: "5" - - gcc: "6" - - gcc: "7" - cxxflags: -fsanitize=leak -fno-sanitize-recover=all - - gcc: "8" - cxxflags: -fsanitize=undefined -fno-sanitize-recover=all - - gcc: "9" - cxxflags: -fsanitize=address -fno-sanitize-recover=all - - gcc: "10" - cxxflags: -funsigned-char # Issue #1715 - - gcc: "11" - - gcc: "12" - steps: - - name: Workaround for actions/runner-images#9491 - run: sudo sysctl vm.mmap_rnd_bits=28 - - - name: Install - run: | - sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 40976EAF437D05B5 3B4FE6ACC0B21F32 - sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ xenial main universe' - sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ bionic main universe' - sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ focal main universe' - sudo apt-get update - sudo apt-get install -y gcc-${{ matrix.gcc }} g++-${{ matrix.gcc }} - timeout-minutes: 5 - - - name: Checkout - uses: actions/checkout@v4 - timeout-minutes: 1 - - - name: Configure - run: cmake -DCMAKE_BUILD_TYPE=Debug . - env: - CC: gcc-${{ matrix.gcc }} - CXX: g++-${{ matrix.gcc }} - CXXFLAGS: ${{ matrix.cxxflags }} - timeout-minutes: 1 - - - name: Build - run: cmake --build . - timeout-minutes: 10 - - - name: Test - run: ctest --output-on-failure -C Debug . - env: - UBSAN_OPTIONS: print_stacktrace=1 - timeout-minutes: 2 - - clang: - name: Clang - needs: lint - strategy: - fail-fast: false - matrix: - include: - - clang: "3.9" - runner: ubuntu-20.04 - archive: bionic - - clang: "4.0" - runner: ubuntu-20.04 - archive: bionic - - clang: "5.0" - runner: ubuntu-20.04 - archive: bionic - - clang: "6.0" - runner: ubuntu-20.04 - archive: bionic - - clang: "7" - runner: ubuntu-20.04 - - clang: "8" - cxxflags: -fsanitize=leak -fno-sanitize-recover=all - runner: ubuntu-20.04 - - clang: "9" - cxxflags: -fsanitize=undefined -fno-sanitize-recover=all - runner: ubuntu-20.04 - - clang: "10" - cxxflags: -fsanitize=address -fno-sanitize-recover=all - runner: ubuntu-20.04 - - clang: "11" - runner: ubuntu-22.04 - - clang: "12" - runner: ubuntu-22.04 - - clang: "13" - runner: ubuntu-22.04 - - clang: "14" - runner: ubuntu-22.04 - - clang: "15" - runner: ubuntu-22.04 - runs-on: ${{ matrix.runner }} - steps: - - name: Add archive repositories - if: matrix.archive - run: | - sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ ${{ matrix.archive }} main' - sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ ${{ matrix.archive }} universe' - - name: Install Clang ${{ matrix.clang }} - run: | - sudo apt-get update - sudo apt-get install -y clang-${{ matrix.clang }} - - name: Install libc++ ${{ matrix.clang }} - if: matrix.clang >= 11 - run: sudo apt-get install -y libc++-${{ matrix.clang }}-dev libc++abi-${{ matrix.clang }}-dev - - name: Install libunwind ${{ matrix.clang }} - if: matrix.clang == 12 # dependency is missing in Ubuntu 22.04 - run: sudo apt-get install -y libunwind-${{ matrix.clang }}-dev - - name: Checkout - uses: actions/checkout@v4 - - name: Configure - run: cmake -DCMAKE_BUILD_TYPE=Debug . - env: - CC: clang-${{ matrix.clang }} - CXX: clang++-${{ matrix.clang }} - CXXFLAGS: >- - ${{ matrix.cxxflags }} - ${{ matrix.clang < 11 && '-I/usr/lib/llvm-10/include/c++/v1/' || '' }} - - name: Build - run: cmake --build . - - name: Test - run: ctest --output-on-failure -C Debug . - env: - UBSAN_OPTIONS: print_stacktrace=1 - - conf_test: - name: Test configuration on Linux - needs: [gcc, clang] - runs-on: ubuntu-20.04 - steps: - - name: Install - run: | - sudo apt-get update - sudo apt-get install -y g++-multilib gcc-avr avr-libc - - name: Checkout - uses: actions/checkout@v4 - - name: AVR - run: avr-g++ -std=c++11 -Isrc extras/conf_test/avr.cpp - - name: GCC 32-bit - run: g++ -std=c++11 -m32 -Isrc extras/conf_test/x86.cpp - - name: GCC 64-bit - run: g++ -std=c++11 -m64 -Isrc extras/conf_test/x64.cpp - - name: Clang 32-bit - run: clang++ -std=c++11 -m32 -Isrc extras/conf_test/x86.cpp - - name: Clang 64-bit - run: clang++ -std=c++11 -m64 -Isrc extras/conf_test/x64.cpp - - conf_test_windows: - name: Test configuration on Windows - runs-on: windows-2019 - needs: [gcc, clang] - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: 32-bit - run: | - call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvars32.bat" - cl /Isrc extras/conf_test/x86.cpp - shell: cmd - - name: 64-bit - run: | - call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvars64.bat" - cl /Isrc extras/conf_test/x64.cpp - shell: cmd - - xcode: - name: XCode - needs: clang - runs-on: macos-13 - strategy: - fail-fast: false - matrix: - include: - - xcode: "14.1" - - xcode: "14.2" - - xcode: "14.3.1" - - xcode: "15.0.1" - - xcode: "15.1" - - xcode: "15.2" - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Select XCode version - run: sudo xcode-select --switch /Applications/Xcode_${{ matrix.xcode }}.app - - name: Configure - run: cmake -DCMAKE_BUILD_TYPE=Debug . - - name: Build - run: cmake --build . - - name: Test - run: ctest --output-on-failure -C Debug . - - # DISABLED: Running on AppVeyor instead because it supports older versions of the compiler - # msvc: - # name: Visual Studio - # strategy: - # fail-fast: false - # matrix: - # include: - # - os: windows-2016 - # - os: windows-2019 - # runs-on: ${{ matrix.os }} - # steps: - # - name: Checkout - # uses: actions/checkout@v4 - # - name: Configure - # run: cmake -DCMAKE_BUILD_TYPE=Debug . - # - name: Build - # run: cmake --build . - # - name: Test - # run: ctest --output-on-failure -C Debug . - - arduino: - name: Arduino - needs: gcc - strategy: - fail-fast: false - matrix: - include: - - core: arduino:avr - board: arduino:avr:uno - - core: arduino:samd - board: arduino:samd:mkr1000 - runs-on: ubuntu-20.04 - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Install arduino-cli - run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh - - name: Install core - run: arduino-cli core install ${{ matrix.core }} - - name: Install libraries - run: arduino-cli lib install SD Ethernet - - name: Build JsonConfigFile - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonConfigFile/JsonConfigFile.ino" - - name: Build JsonFilterExample - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonFilterExample/JsonFilterExample.ino" - - name: Build JsonGeneratorExample - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonGeneratorExample/JsonGeneratorExample.ino" - - name: Build JsonHttpClient - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonHttpClient/JsonHttpClient.ino" - - name: Build JsonParserExample - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonParserExample/JsonParserExample.ino" - - name: Build JsonServer - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonServer/JsonServer.ino" - - name: Build JsonUdpBeacon - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonUdpBeacon/JsonUdpBeacon.ino" - - name: Build MsgPackParser - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/MsgPackParser/MsgPackParser.ino" - - name: Build ProgmemExample - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/ProgmemExample/ProgmemExample.ino" - - name: Build StringExample - run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/StringExample/StringExample.ino" - - platformio: - name: PlatformIO - needs: gcc - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - include: - - platform: atmelavr - board: leonardo - libraries: - - SD - - Ethernet - conf_test: avr - - platform: espressif8266 - board: huzzah - conf_test: esp8266 - - platform: espressif32 - board: esp32dev - libraries: - - Ethernet - conf_test: esp8266 - - platform: atmelsam - board: mkr1000USB - libraries: - - SD - - Ethernet - conf_test: esp8266 - - platform: teensy - board: teensy31 - conf_test: esp8266 - - platform: ststm32 - board: adafruit_feather_f405 - libraries: - - SD - - Ethernet - conf_test: esp8266 - - platform: nordicnrf52 - board: adafruit_feather_nrf52840 - libraries: - - SD - - Ethernet - conf_test: esp8266 - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Set up cache for pip - uses: actions/cache@v4 - with: - path: ~/.cache/pip - key: ${{ runner.os }}-pip - - name: Set up Python 3.x - uses: actions/setup-python@v5 - with: - python-version: "3.x" - - name: Install PlatformIO - run: pip install platformio - - name: Install adafruit-nrfutil - if: ${{ matrix.platform == 'nordicnrf52' }} - run: pip install adafruit-nrfutil - - name: Include Adafruit_TinyUSB.h # https://github.com/adafruit/Adafruit_nRF52_Arduino/issues/653 - if: ${{ matrix.platform == 'nordicnrf52' }} - run: find examples/ -name '*.ino' -exec sed -i 's/\(#include \)/\1\n#include /' {} + - - name: Set up cache for platformio - uses: actions/cache@v4 - with: - path: ~/.platformio - key: ${{ runner.os }}-platformio-${{ matrix.platform }} - - name: Install platform "${{ matrix.platform }}" - run: platformio platform install ${{ matrix.platform }} - - name: Install libraries - if: ${{ matrix.libraries }} - run: platformio lib install arduino-libraries/${{ join(matrix.libraries, ' arduino-libraries/') }} - - name: Test configuration - run: platformio ci "extras/conf_test/${{ matrix.conf_test }}.cpp" -l '.' -b ${{ matrix.board }} - if: ${{ matrix.conf_test }} - - name: Build JsonConfigFile - run: platformio ci "examples/JsonConfigFile/JsonConfigFile.ino" -l '.' -b ${{ matrix.board }} - - name: Build JsonFilterExample - run: platformio ci "examples/JsonFilterExample/JsonFilterExample.ino" -l '.' -b ${{ matrix.board }} - - name: Build JsonGeneratorExample - run: platformio ci "examples/JsonGeneratorExample/JsonGeneratorExample.ino" -l '.' -b ${{ matrix.board }} - - name: Build JsonHttpClient - run: platformio ci "examples/JsonHttpClient/JsonHttpClient.ino" -l '.' -b ${{ matrix.board }} - - name: Build JsonParserExample - run: platformio ci "examples/JsonParserExample/JsonParserExample.ino" -l '.' -b ${{ matrix.board }} - - name: Build JsonServer - if: ${{ matrix.platform != 'espressif32' }} - run: platformio ci "examples/JsonServer/JsonServer.ino" -l '.' -b ${{ matrix.board }} - - name: Build JsonUdpBeacon - run: platformio ci "examples/JsonUdpBeacon/JsonUdpBeacon.ino" -l '.' -b ${{ matrix.board }} - - name: Build MsgPackParser - run: platformio ci "examples/MsgPackParser/MsgPackParser.ino" -l '.' -b ${{ matrix.board }} - - name: Build ProgmemExample - run: platformio ci "examples/ProgmemExample/ProgmemExample.ino" -l '.' -b ${{ matrix.board }} - - name: Build StringExample - run: platformio ci "examples/StringExample/StringExample.ino" -l '.' -b ${{ matrix.board }} - - name: PlatformIO prune - if: ${{ always() }} - run: platformio system prune -f - - particle: - name: Particle - needs: gcc - runs-on: ubuntu-latest - if: github.event_name == 'push' - strategy: - fail-fast: false - matrix: - include: - - board: argon - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Install Particle CLI - run: sudo npm install -g particle-cli - - name: Login to Particle - run: particle login -t "${{ secrets.PARTICLE_TOKEN }}" - - name: Compile - run: extras/ci/particle.sh ${{ matrix.board }} - - arm: - name: GCC for ARM processor - needs: gcc - runs-on: ubuntu-20.04 - steps: - - name: Install - run: | - sudo apt-get update - sudo apt-get install -y g++-arm-linux-gnueabihf - - name: Checkout - uses: actions/checkout@v4 - - name: Configure - run: cmake . - env: - CC: arm-linux-gnueabihf-gcc - CXX: arm-linux-gnueabihf-g++ - - name: Build - run: cmake --build . - - coverage: - needs: gcc - name: Coverage - runs-on: ubuntu-20.04 - steps: - - name: Install - run: sudo apt-get install -y lcov ninja-build - - name: Checkout - uses: actions/checkout@v4 - - name: Configure - run: cmake -G Ninja -DCOVERAGE=true . - - name: Build - run: ninja - - name: Test - run: ctest --output-on-failure -LE 'WillFail|Fuzzing' -T test - - name: lcov --capture - run: lcov --capture --no-external --directory . --output-file coverage.info - - name: lcov --remove - run: lcov --remove coverage.info "$(pwd)/extras/*" --output-file coverage_filtered.info - - name: genhtml - run: mkdir coverage && genhtml coverage_filtered.info -o coverage -t ArduinoJson - - name: Upload HTML report - uses: actions/upload-artifact@v4 - with: - name: Coverage report - path: coverage - - name: Upload to Coveralls - uses: coverallsapp/github-action@v2 - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - path-to-lcov: coverage_filtered.info - - valgrind: - needs: gcc - name: Valgrind - runs-on: ubuntu-20.04 - steps: - - name: Install - run: | - sudo apt-get update - sudo apt-get install -y valgrind ninja-build - - name: Checkout - uses: actions/checkout@v4 - - name: Configure - run: cmake -G Ninja -D MEMORYCHECK_COMMAND_OPTIONS="--error-exitcode=1 --leak-check=full" . - - name: Build - run: ninja - - name: Memcheck - run: ctest --output-on-failure -LE WillFail -T memcheck - id: memcheck - - name: MemoryChecker.*.log - run: cat Testing/Temporary/MemoryChecker.*.log > $GITHUB_STEP_SUMMARY - if: failure() - - clang-tidy: - needs: clang - name: Clang-Tidy - runs-on: ubuntu-20.04 - steps: - - name: Install - run: sudo apt-get install -y clang-tidy cmake ninja-build - - name: Checkout - uses: actions/checkout@v4 - - name: Configure - run: cmake -G Ninja -DCMAKE_CXX_CLANG_TIDY="clang-tidy-10;--warnings-as-errors=*" -DCMAKE_BUILD_TYPE=Debug . - env: - CC: clang-10 - CXX: clang++-10 - - name: Check - run: cmake --build . -- -k 0 - - amalgamate: - needs: gcc - name: Amalgamate ArduinoJson.h - runs-on: ubuntu-20.04 - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Setup - run: | - if [[ $GITHUB_REF == refs/tags/* ]]; then - VERSION=${GITHUB_REF#refs/tags/} - else - VERSION=${GITHUB_SHA::7} - fi - echo "ARDUINOJSON_H=ArduinoJson-$VERSION.h" >> $GITHUB_ENV - echo "ARDUINOJSON_HPP=ArduinoJson-$VERSION.hpp" >> $GITHUB_ENV - - name: Amalgamate ArduinoJson.h - run: extras/scripts/build-single-header.sh "src/ArduinoJson.h" "$ARDUINOJSON_H" - - name: Amalgamate ArduinoJson.hpp - run: extras/scripts/build-single-header.sh "src/ArduinoJson.hpp" "$ARDUINOJSON_HPP" - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: Single headers - path: | - ${{ env.ARDUINOJSON_H }} - ${{ env.ARDUINOJSON_HPP }} - - name: Smoke test ArduinoJson.h - run: | - g++ -x c++ - <> $GITHUB_OUTPUT - echo "version=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT - - name: Checkout - uses: actions/checkout@v4 - - name: Write release body - id: body - run: | - FILENAME=RELEASE.md - tee $FILENAME <> $GITHUB_OUTPUT - - name: Amalgamate ArduinoJson.h - id: amalgamate_h - run: | - FILENAME=ArduinoJson-${{ steps.init.outputs.tag }}.h - extras/scripts/build-single-header.sh src/ArduinoJson.h "$FILENAME" - echo "filename=$FILENAME" >> $GITHUB_OUTPUT - - name: Amalgamate ArduinoJson.hpp - id: amalgamate_hpp - run: | - FILENAME=ArduinoJson-${{ steps.init.outputs.tag }}.hpp - extras/scripts/build-single-header.sh src/ArduinoJson.hpp "$FILENAME" - echo "filename=$FILENAME" >> $GITHUB_OUTPUT - - name: Create release - uses: ncipollo/release-action@v1 - with: - bodyFile: ${{ steps.body.outputs.filename }} - name: ArduinoJson ${{ steps.init.outputs.version }} - artifacts: ${{ steps.amalgamate_h.outputs.filename }},${{ steps.amalgamate_hpp.outputs.filename }} - token: ${{ secrets.GITHUB_TOKEN }} - - idf: - name: IDF Component Registry - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Upload component to the component registry - uses: espressif/upload-components-ci-action@v1 - with: - name: ArduinoJson - namespace: bblanchon - api_token: ${{ secrets.IDF_COMPONENT_API_TOKEN }} - - particle: - name: Particle - runs-on: ubuntu-latest - steps: - - name: Install - run: npm install -g particle-cli - - name: Checkout - uses: actions/checkout@v4 - - name: Login - run: particle login --token ${{ secrets.PARTICLE_TOKEN }} - - name: Publish - run: bash -eux extras/scripts/publish-particle-library.sh - - platformio: - name: PlatformIO - runs-on: ubuntu-latest - steps: - - name: Set up Python 3.x - uses: actions/setup-python@v5 - with: - python-version: "3.x" - - name: Install PlatformIO - run: pip install platformio - - name: Checkout - uses: actions/checkout@v4 - - name: Publish - run: pio pkg publish --no-interactive --no-notify - env: - PLATFORMIO_AUTH_TOKEN: ${{ secrets.PLATFORMIO_AUTH_TOKEN }} diff --git a/watering/lib/AsyncTCP/.clang-format b/watering/lib/AsyncTCP/.clang-format new file mode 100644 index 0000000..8f47348 --- /dev/null +++ b/watering/lib/AsyncTCP/.clang-format @@ -0,0 +1,246 @@ +# Clang format version: 18.1.3 +--- +BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: BlockIndent +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: true +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: true + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Always +BreakAfterJavaFieldAnnotations: false +BreakArrays: false +BreakBeforeBinaryOperators: NonAssignment +BreakBeforeBraces: Custom +BreakBeforeConceptDeclarations: Always +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +ColumnLimit: 160 +CommentPragmas: "" +CompactNamespaces: false +ConstructorInitializerIndentWidth: 2 +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: ^"(llvm|llvm-c|clang|clang-c)/ + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: ^(<|"(gtest|gmock|isl|json)/) + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: .* + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: "" +IncludeIsMainSourceRegex: "" +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: NoIndent +IndentGotoLabels: false +IndentPPDirectives: None +IndentRequiresClause: false +IndentWidth: 2 +IndentWrappedFunctionNames: true +InsertBraces: true +InsertNewlineAtEOF: true +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtEOF: false +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: Signature +Language: Cpp +LineEnding: LF +MacroBlockBegin: "" +MacroBlockEnd: "" +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PPIndentWidth: -1 +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: false +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: Never +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDeclarationName: false + AfterFunctionDefinitionName: false + AfterIfMacros: true + AfterOverloadedOperator: true + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: Never +SpacesInContainerLiterals: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InConditionalStatements: false + InCStyleCasts: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Auto +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 2 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +BracedInitializerIndentWidth: 2 diff --git a/watering/lib/AsyncTCP/.codespellrc b/watering/lib/AsyncTCP/.codespellrc new file mode 100644 index 0000000..46c1122 --- /dev/null +++ b/watering/lib/AsyncTCP/.codespellrc @@ -0,0 +1,8 @@ +[codespell] +# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/spell-check/.codespellrc +# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here: +ignore-words-list = ba,licence +skip = ./.git,./.licenses,__pycache__,.clang-format,.codespellrc,.editorconfig,.flake8,.prettierignore,.yamllint.yml,.gitignore +builtin = clear,informal,en-GB_to_en-US +check-filenames = +check-hidden = diff --git a/watering/lib/AsyncTCP/.editorconfig b/watering/lib/AsyncTCP/.editorconfig new file mode 100644 index 0000000..e22936c --- /dev/null +++ b/watering/lib/AsyncTCP/.editorconfig @@ -0,0 +1,60 @@ +# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/general/.editorconfig +# See: https://editorconfig.org/ +# The formatting style defined in this file is the official standardized style to be used in all Arduino Tooling +# projects and should not be modified. +# Note: indent style for each file type is defined even when it matches the universal config in order to make it clear +# that this type has an official style. + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 2 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{adoc,asc,asciidoc}] +indent_size = 2 +indent_style = space + +[*.{bash,sh}] +indent_size = 4 +indent_style = space + +[*.{c,cc,cp,cpp,cxx,h,hh,hpp,hxx,ii,inl,ino,ixx,pde,tpl,tpp,txx}] +indent_size = 2 +indent_style = space + +[*.{go,mod}] +indent_style = tab + +[*.java] +indent_size = 2 +indent_style = space + +[*.{js,jsx,json,jsonc,json5,ts,tsx}] +indent_size = 2 +indent_style = space + +[*.{md,mdx,mkdn,mdown,markdown}] +indent_size = unset +indent_style = space + +[*.proto] +indent_size = 2 +indent_style = space + +[*.py] +indent_size = 4 +indent_style = space + +[*.svg] +indent_size = 2 +indent_style = space + +[*.{yaml,yml}] +indent_size = 2 +indent_style = space + +[{.gitconfig,.gitmodules}] +indent_style = tab diff --git a/watering/lib/AsyncTCP/.gitignore b/watering/lib/AsyncTCP/.gitignore new file mode 100644 index 0000000..18584e8 --- /dev/null +++ b/watering/lib/AsyncTCP/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +.lh +/.pio +/.vscode + +/logs diff --git a/watering/lib/AsyncTCP/.gitpod.Dockerfile b/watering/lib/AsyncTCP/.gitpod.Dockerfile new file mode 100644 index 0000000..29eeb43 --- /dev/null +++ b/watering/lib/AsyncTCP/.gitpod.Dockerfile @@ -0,0 +1,2 @@ +FROM gitpod/workspace-python-3.11 +USER gitpod diff --git a/watering/lib/AsyncTCP/.gitpod.yml b/watering/lib/AsyncTCP/.gitpod.yml new file mode 100644 index 0000000..2f8a443 --- /dev/null +++ b/watering/lib/AsyncTCP/.gitpod.yml @@ -0,0 +1,9 @@ +tasks: + - command: pip install --upgrade pip && pip install -U platformio && platformio run + +image: + file: .gitpod.Dockerfile + +vscode: + extensions: + - shardulm94.trailing-spaces diff --git a/watering/lib/AsyncTCP/.pre-commit-config.yaml b/watering/lib/AsyncTCP/.pre-commit-config.yaml new file mode 100644 index 0000000..660d000 --- /dev/null +++ b/watering/lib/AsyncTCP/.pre-commit-config.yaml @@ -0,0 +1,42 @@ +exclude: | + (?x)( + ^\.github\/| + LICENSE\.md$ + ) + +default_language_version: + # force all unspecified python hooks to run python3 + python: python3 + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: "v5.0.0" + hooks: + # Generic checks + - id: check-case-conflict + - id: check-symlinks + - id: debug-statements + - id: destroyed-symlinks + - id: detect-private-key + - id: end-of-file-fixer + exclude: ^.*\.(bin|BIN)$ + - id: mixed-line-ending + args: [--fix=lf] + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + exclude: ^platformio\.ini$ + + - repo: https://github.com/codespell-project/codespell + rev: "v2.3.0" + hooks: + # Spell checking + - id: codespell + exclude: ^.*\.(svd|SVD)$ + + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: "v18.1.3" + hooks: + # C/C++ formatting + - id: clang-format + types_or: [c, c++] + exclude: ^.*\/build_opt\.h$ diff --git a/watering/lib/AsyncTCP/CMakeLists.txt b/watering/lib/AsyncTCP/CMakeLists.txt new file mode 100644 index 0000000..f52e1c9 --- /dev/null +++ b/watering/lib/AsyncTCP/CMakeLists.txt @@ -0,0 +1,15 @@ +set(COMPONENT_SRCDIRS + "src" +) + +set(COMPONENT_ADD_INCLUDEDIRS + "src" +) + +set(COMPONENT_REQUIRES + "arduino-esp32" +) + +register_component() + +target_compile_options(${COMPONENT_TARGET} PRIVATE -fno-rtti) diff --git a/watering/lib/AsyncTCP/CODE_OF_CONDUCT.md b/watering/lib/AsyncTCP/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..4fcdc2f --- /dev/null +++ b/watering/lib/AsyncTCP/CODE_OF_CONDUCT.md @@ -0,0 +1,129 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socioeconomic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +https://sidweb.nl/cms3/en/contact. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/watering/lib/AsyncTCP/Kconfig.projbuild b/watering/lib/AsyncTCP/Kconfig.projbuild new file mode 100644 index 0000000..1774926 --- /dev/null +++ b/watering/lib/AsyncTCP/Kconfig.projbuild @@ -0,0 +1,30 @@ +menu "AsyncTCP Configuration" + +choice ASYNC_TCP_RUNNING_CORE + bool "Core on which AsyncTCP's thread is running" + default ASYNC_TCP_RUN_CORE1 + help + Select on which core AsyncTCP is running + + config ASYNC_TCP_RUN_CORE0 + bool "CORE 0" + config ASYNC_TCP_RUN_CORE1 + bool "CORE 1" + config ASYNC_TCP_RUN_NO_AFFINITY + bool "BOTH" + +endchoice + +config ASYNC_TCP_RUNNING_CORE + int + default 0 if ASYNC_TCP_RUN_CORE0 + default 1 if ASYNC_TCP_RUN_CORE1 + default -1 if ASYNC_TCP_RUN_NO_AFFINITY + +config ASYNC_TCP_USE_WDT + bool "Enable WDT for the AsyncTCP task" + default "y" + help + Enable WDT for the AsyncTCP task, so it will trigger if a handler is locking the thread. + +endmenu diff --git a/watering/lib/AsyncTCP/LICENSE b/watering/lib/AsyncTCP/LICENSE new file mode 100644 index 0000000..65c5ca8 --- /dev/null +++ b/watering/lib/AsyncTCP/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/watering/lib/AsyncTCP/README.md b/watering/lib/AsyncTCP/README.md new file mode 100644 index 0000000..edda626 --- /dev/null +++ b/watering/lib/AsyncTCP/README.md @@ -0,0 +1,55 @@ +![https://avatars.githubusercontent.com/u/195753706?s=96&v=4](https://avatars.githubusercontent.com/u/195753706?s=96&v=4) + +# AsyncTCP + +[![License: LGPL 3.0](https://img.shields.io/badge/License-LGPL%203.0-yellow.svg)](https://opensource.org/license/lgpl-3-0/) +[![Continuous Integration](https://github.com/ESP32Async/AsyncTCP/actions/workflows/ci.yml/badge.svg)](https://github.com/ESP32Async/AsyncTCP/actions/workflows/ci.yml) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/ESP32Async/library/AsyncTCP.svg)](https://registry.platformio.org/libraries/ESP32Async/AsyncTCP) + +Discord Server: [https://discord.gg/X7zpGdyUcY](https://discord.gg/X7zpGdyUcY) + +## Async TCP Library for ESP32 Arduino + +This is a fully asynchronous TCP library, aimed at enabling trouble-free, multi-connection network environment for Espressif's ESP32 MCUs. + +This library is the base for [ESPAsyncWebServer](https://github.com/ESP32Async/ESPAsyncWebServer) + +## How to install + +The library can be downloaded from the releases page at [https://github.com/ESP32Async/AsyncTCP/releases](https://github.com/ESP32Async/AsyncTCP/releases). + +It is also deployed in these registries: + +- Arduino Library Registry: [https://github.com/arduino/library-registry](https://github.com/arduino/library-registry) + +- ESP Component Registry [https://components.espressif.com/components/esp32async/asynctcp/](https://components.espressif.com/components/esp32async/asynctcp/) + +- PlatformIO Registry: [https://registry.platformio.org/libraries/esp32async/AsyncTCP](https://registry.platformio.org/libraries/esp32async/AsyncTCP) + + - Use: `lib_deps=ESP32Async/AsyncTCP` to point to latest version + - Use: `lib_deps=ESP32Async/AsyncTCP @ ^` to point to latest version with the same major version + - Use: `lib_deps=ESP32Async/AsyncTCP @ ` to always point to the same version (reproductible build) + +## AsyncClient and AsyncServer + +The base classes on which everything else is built. They expose all possible scenarios, but are really raw and require more skills to use. + +## Important recommendations + +Most of the crashes are caused by improper configuration of the library for the project. +Here are some recommendations to avoid them. + +I personally use the following configuration in my projects: + +```c++ + -D CONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 // (keep default) + -D CONFIG_ASYNC_TCP_PRIORITY=10 // (keep default) + -D CONFIG_ASYNC_TCP_QUEUE_SIZE=64 // (keep default) + -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 // force async_tcp task to be on same core as the app (default is core 0) + -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 // reduce the stack size (default is 16K) +``` + +## Compatibility + +- ESP32 +- Arduino Core 2.x and 3.x diff --git a/watering/lib/AsyncTCP/arduino-cli-dev.yaml b/watering/lib/AsyncTCP/arduino-cli-dev.yaml new file mode 100644 index 0000000..174df7a --- /dev/null +++ b/watering/lib/AsyncTCP/arduino-cli-dev.yaml @@ -0,0 +1,25 @@ +board_manager: + additional_urls: + - https://espressif.github.io/arduino-esp32/package_esp32_dev_index.json +directories: + builtin.libraries: ./src/ +build_cache: + compilations_before_purge: 10 + ttl: 720h0m0s +daemon: + port: "50051" +library: + enable_unsafe_install: false +logging: + file: "" + format: text + level: info +metrics: + addr: :9090 + enabled: true +output: + no_color: false +sketch: + always_export_binaries: false +updater: + enable_notification: true diff --git a/watering/lib/AsyncTCP/arduino-cli.yaml b/watering/lib/AsyncTCP/arduino-cli.yaml new file mode 100644 index 0000000..42365f4 --- /dev/null +++ b/watering/lib/AsyncTCP/arduino-cli.yaml @@ -0,0 +1,25 @@ +board_manager: + additional_urls: + - https://espressif.github.io/arduino-esp32/package_esp32_index.json +directories: + builtin.libraries: ./src/ +build_cache: + compilations_before_purge: 10 + ttl: 720h0m0s +daemon: + port: "50051" +library: + enable_unsafe_install: false +logging: + file: "" + format: text + level: info +metrics: + addr: :9090 + enabled: true +output: + no_color: false +sketch: + always_export_binaries: false +updater: + enable_notification: true diff --git a/watering/lib/AsyncTCP/component.mk b/watering/lib/AsyncTCP/component.mk new file mode 100644 index 0000000..bb5bb16 --- /dev/null +++ b/watering/lib/AsyncTCP/component.mk @@ -0,0 +1,3 @@ +COMPONENT_ADD_INCLUDEDIRS := src +COMPONENT_SRCDIRS := src +CXXFLAGS += -fno-rtti diff --git a/watering/lib/AsyncTCP/examples/AsyncSend/AsyncSend.ino b/watering/lib/AsyncTCP/examples/AsyncSend/AsyncSend.ino new file mode 100644 index 0000000..3e9cb4e --- /dev/null +++ b/watering/lib/AsyncTCP/examples/AsyncSend/AsyncSend.ino @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +/* + This example demonstrates how to send data to a remote server asynchronously. + Run on the remote computer: nc -l -p 1234 + + You should see in the logs: + +Connected! +Will send 5760 bytes... +Acked 1436 bytes in 19 ms +Will send 1436 bytes... +Acked 1436 bytes in 2 ms +Will send 996 bytes... +Waiting for acks... +Acked 1436 bytes in 1 ms +Acked 1436 bytes in 5 ms +Acked 1452 bytes in 17 ms +Acked 996 bytes in 28 ms +Buffer received - next send in 2 sec +Will send 5760 bytes... +Acked 1436 bytes in 14 ms +Will send 1436 bytes... +Acked 1436 bytes in 2 ms +Acked 1436 bytes in 0 ms +Acked 1452 bytes in 1 ms +Will send 996 bytes... +Waiting for acks... +Acked 1436 bytes in 3 ms +Acked 996 bytes in 18 ms +Buffer received - next send in 2 sec + + And in the remote terminal 3072 characters sent [......... ...........] and so on. +*/ + +#include +#include +#include +#include + +#include +#include + +#define WIFI_SSID "IoT" +#define WIFI_PASSWORD "" + +#define REMOTE_IP "192.168.125.116" +#define REMOTE_PORT 1234 + +#define BUFFER_SIZE 8 * 1024 + +static char buffer[BUFFER_SIZE] = {0}; +static size_t bufferPos = 0; + +// 0 == disconnected +// 1 == connecting +// 2 == connected +static uint8_t state = 0; + +// number of bytes waiting for a ack +static size_t waitingAck = 0; + +static AsyncClient client; + +void setup() { + Serial.begin(115200); + while (!Serial) { + continue; + } + + // connect to WiFi + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + } + Serial.println("Connected to WiFi!"); + Serial.println(WiFi.localIP()); + + // fill buffer + buffer[0] = '['; + for (size_t i = 1; i < BUFFER_SIZE - 1; i++) { + buffer[i] = '.'; + } + buffer[BUFFER_SIZE - 1] = ']'; + + // register a callback when the client disconnects + client.onDisconnect([](void *arg, AsyncClient *client) { + Serial.printf("Disconnected.\n"); + state = 0; + }); + + // register a callback when an error occurs + client.onError([](void *arg, AsyncClient *client, int8_t error) { + Serial.printf("Error: %s\n", client->errorToString(error)); + }); + + // register a callback when data arrives, to accumulate it + client.onData([](void *arg, AsyncClient *client, void *data, size_t len) { + Serial.printf("Received %u bytes...\n", len); + Serial.write((uint8_t *)data, len); + }); + + // register a callback when we are connected + client.onConnect([](void *arg, AsyncClient *client) { + Serial.printf("Connected!\n"); + state = 2; + }); + + client.onAck([](void *arg, AsyncClient *client, size_t len, uint32_t time) { + Serial.printf("Acked %u bytes in %" PRIu32 " ms\n", len, time); + assert(waitingAck >= len); + waitingAck -= len; + }); + + client.setRxTimeout(20000); + client.setNoDelay(true); +} + +void loop() { + switch (state) { + case 0: + { + Serial.printf("Connecting...\n"); + if (!client.connect(REMOTE_IP, REMOTE_PORT)) { + Serial.printf("Failed to connect!\n"); + delay(1000); // to not flood logs + } else { + state = 1; + } + break; + } + + case 1: + { + Serial.printf("Still connecting...\n"); + delay(500); // to not flood logs + break; + } + + case 2: + { + // fill PCB space until we can + size_t willSend; + while (bufferPos < BUFFER_SIZE && (willSend = client.write(buffer + bufferPos, BUFFER_SIZE - bufferPos))) { + Serial.printf("Will send %u bytes...\n", willSend); + bufferPos += willSend; + waitingAck += willSend; + } + + // we have sent the whole buffer ? + if (bufferPos >= BUFFER_SIZE) { + // wait for acks, or send again after 2 sec + if (waitingAck) { + Serial.printf("Waiting for acks...\n"); + delay(100); + } else { + Serial.printf("Buffer received - next send in 2 sec\n"); + delay(2000); + bufferPos = 0; + } + } + break; + } + + default: break; + } +} diff --git a/watering/lib/AsyncTCP/examples/Client/Client.ino b/watering/lib/AsyncTCP/examples/Client/Client.ino new file mode 100644 index 0000000..abdfba8 --- /dev/null +++ b/watering/lib/AsyncTCP/examples/Client/Client.ino @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include +#include +#include + +// Run a server at the root of the project with: +// > python3 -m http.server 3333 +// Now you can open a browser and test it works by visiting http://192.168.125.122:3333/ or http://192.168.125.122:3333/README.md +#define HOST "192.168.125.122" +#define PORT 3333 + +// WiFi SSID to connect to +#define WIFI_SSID "IoT" + +// 16 slots on esp32 (CONFIG_LWIP_MAX_ACTIVE_TCP) +#define MAX_CLIENTS CONFIG_LWIP_MAX_ACTIVE_TCP +// #define MAX_CLIENTS 1 + +size_t permits = MAX_CLIENTS; + +void makeRequest() { + if (!permits) { + return; + } + + Serial.printf("** permits: %d\n", permits); + + AsyncClient *client = new AsyncClient; + + client->onError([](void *arg, AsyncClient *client, int8_t error) { + Serial.printf("** error occurred %s \n", client->errorToString(error)); + client->close(true); + delete client; + }); + + client->onConnect([](void *arg, AsyncClient *client) { + permits--; + Serial.printf("** client has been connected: %" PRIu16 "\n", client->localPort()); + + client->onDisconnect([](void *arg, AsyncClient *client) { + Serial.printf("** client has been disconnected: %" PRIu16 "\n", client->localPort()); + client->close(true); + delete client; + + permits++; + makeRequest(); + }); + + client->onData([](void *arg, AsyncClient *client, void *data, size_t len) { + Serial.printf("** data received by client: %" PRIu16 ": len=%u\n", client->localPort(), len); + }); + + client->write("GET /README.md HTTP/1.1\r\nHost: " HOST "\r\nUser-Agent: ESP\r\nConnection: close\r\n\r\n"); + }); + + if (client->connect(HOST, PORT)) { + } else { + Serial.println("** connection failed"); + } +} + +void setup() { + Serial.begin(115200); + while (!Serial) { + continue; + } + + WiFi.mode(WIFI_STA); + WiFi.begin(WIFI_SSID); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println("** connected to WiFi"); + Serial.println(WiFi.localIP()); + + for (size_t i = 0; i < MAX_CLIENTS; i++) { + makeRequest(); + } +} + +void loop() { + delay(1000); + Serial.printf("** free heap: %" PRIu32 "\n", ESP.getFreeHeap()); +} diff --git a/watering/lib/AsyncTCP/examples/FetchWebsite/FetchWebsite.ino b/watering/lib/AsyncTCP/examples/FetchWebsite/FetchWebsite.ino new file mode 100644 index 0000000..3d5948b --- /dev/null +++ b/watering/lib/AsyncTCP/examples/FetchWebsite/FetchWebsite.ino @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include +#include +#include +#include + +#include +#include + +#define WIFI_SSID "IoT" +#define WIFI_PASSWORD "" + +void fetchAsync(const char *host, std::function onDone) { + Serial.printf("[%s] Fetching: http://%s...\n", host, host); + + // buffer where we will accumulate the received data + StreamString *content = new StreamString(); + + // reserve enough space to avoid reallocations + content->reserve(32 * 1024); + + // create a new client + AsyncClient *client = new AsyncClient(); + + // register a callback when the client disconnects + client->onDisconnect([content, host, onDone](void *arg, AsyncClient *client) { + Serial.printf("[%s] Disconnected.\n", host); + onDone(content); + delete client; + delete content; + }); + + // register a callback when an error occurs + client->onError([host, onDone](void *arg, AsyncClient *client, int8_t error) { + Serial.printf("[%s] Error: %s\n", host, client->errorToString(error)); + }); + + // register a callback when data arrives, to accumulate it + client->onData([host, content](void *arg, AsyncClient *client, void *data, size_t len) { + Serial.printf("[%s] Received %u bytes...\n", host, len); + content->write((const uint8_t *)data, len); + }); + + // register a callback when we are connected + client->onConnect([host](void *arg, AsyncClient *client) { + Serial.printf("[%s] Connected!\n", host); + + // send request + client->write("GET / HTTP/1.1\r\n"); + client->write("Host: "); + client->write(host); + client->write("\r\n"); + client->write("User-Agent: ESP32\r\n"); + client->write("Connection: close\r\n"); + client->write("\r\n"); + }); + + Serial.printf("[%s] Connecting...\n", host); + + client->setRxTimeout(20000); + // client->setAckTimeout(10000); + client->setNoDelay(true); + + if (!client->connect(host, 80)) { + Serial.printf("[%s] Failed to connect!\n", host); + delete client; + delete content; + onDone(nullptr); + } +} + +void setup() { + Serial.begin(115200); + while (!Serial) { + continue; + } + + // connect to WiFi + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + } + Serial.println("Connected to WiFi!"); + Serial.println(WiFi.localIP()); + + // fetch asynchronously 2 websites: + + // equivalent to curl -v --raw http://www.google.com/ + fetchAsync("www.google.com", [](const StreamString *content) { + if (content) { + Serial.printf("[www.google.com] Fetched website:\n%s\n", content->c_str()); + } else { + Serial.println("[www.google.com] Failed to fetch website!"); + } + }); + + // equivalent to curl -v --raw http://www.time.org/ + fetchAsync("www.time.org", [](const StreamString *content) { + if (content) { + Serial.printf("[www.time.org] Fetched website:\n%s\n", content->c_str()); + } else { + Serial.println("[www.time.org] Failed to fetch website!"); + } + }); +} + +void loop() { + delay(500); +} diff --git a/watering/lib/AsyncTCP/idf_component.yml b/watering/lib/AsyncTCP/idf_component.yml new file mode 100644 index 0000000..10c0478 --- /dev/null +++ b/watering/lib/AsyncTCP/idf_component.yml @@ -0,0 +1,32 @@ +description: "Async TCP Library for ESP32 Arduino" +url: "https://github.com/ESP32Async/AsyncTCP" +license: "LGPL-3.0-or-later" +tags: + - arduino +files: + exclude: + - "idf_component_examples/" + - "idf_component_examples/**/*" + - "examples/" + - "examples/**/*" + - ".gitignore" + - ".clang-format" + - ".gitpod.Dockerfile" + - ".gitpod.yml" + - ".codespellrc" + - ".editorconfig" + - ".pre-commit-config.yaml" + - "arduino-cli.yaml" + - "arduino-cli-dev.yaml" + - "CODE_OF_CONDUCT.md" + - "component.mk" + - "library.json" + - "library.properties" + - "platformio.ini" + - "pre-commit.requirements.txt" +dependencies: + espressif/arduino-esp32: + version: "^3.1.1" + require: public +examples: + - path: ./idf_component_examples/client diff --git a/watering/lib/AsyncTCP/idf_component_examples/client/CMakeLists.txt b/watering/lib/AsyncTCP/idf_component_examples/client/CMakeLists.txt new file mode 100644 index 0000000..664d458 --- /dev/null +++ b/watering/lib/AsyncTCP/idf_component_examples/client/CMakeLists.txt @@ -0,0 +1,8 @@ +# For more information about build system see +# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(main) diff --git a/watering/lib/AsyncTCP/idf_component_examples/client/README.md b/watering/lib/AsyncTCP/idf_component_examples/client/README.md new file mode 100644 index 0000000..e409b28 --- /dev/null +++ b/watering/lib/AsyncTCP/idf_component_examples/client/README.md @@ -0,0 +1 @@ +### Basic example to show how AsyncTCP client works diff --git a/watering/lib/AsyncTCP/idf_component_examples/client/main/CMakeLists.txt b/watering/lib/AsyncTCP/idf_component_examples/client/main/CMakeLists.txt new file mode 100644 index 0000000..9eb7ec4 --- /dev/null +++ b/watering/lib/AsyncTCP/idf_component_examples/client/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "main.cpp" + INCLUDE_DIRS ".") diff --git a/watering/lib/AsyncTCP/idf_component_examples/client/main/idf_component.yml b/watering/lib/AsyncTCP/idf_component_examples/client/main/idf_component.yml new file mode 100644 index 0000000..5a8dff8 --- /dev/null +++ b/watering/lib/AsyncTCP/idf_component_examples/client/main/idf_component.yml @@ -0,0 +1,6 @@ +## IDF Component Manager Manifest File +dependencies: + esp32async/asynctcp: + version: "*" + override_path: "../../../" + pre_release: true diff --git a/watering/lib/AsyncTCP/idf_component_examples/client/main/main.cpp b/watering/lib/AsyncTCP/idf_component_examples/client/main/main.cpp new file mode 100644 index 0000000..7bbbf4c --- /dev/null +++ b/watering/lib/AsyncTCP/idf_component_examples/client/main/main.cpp @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "Arduino.h" +#include "AsyncTCP.h" +#include "WiFi.h" + +// Run a server at the root of the project with: +// > python3 -m http.server 3333 +// Now you can open a browser and test it works by visiting http://192.168.125.122:3333/ or http://192.168.125.122:3333/README.md +#define HOST "192.168.125.122" +#define PORT 3333 + +// WiFi SSID to connect to +#define WIFI_SSID "*********" +#define WIFI_PASS "*********" + +bool client_running = false; + +void makeRequest() { + client_running = true; + AsyncClient *client = new AsyncClient; + if (client == nullptr) { + Serial.println("** could not allocate client"); + client_running = false; + return; + } + + client->onError([](void *arg, AsyncClient *client, int8_t error) { + Serial.printf("** error occurred %s \n", client->errorToString(error)); + client->close(true); + delete client; + client_running = false; + }); + + client->onConnect([](void *arg, AsyncClient *client) { + Serial.printf("** client has been connected: %" PRIu16 "\n", client->localPort()); + + client->onDisconnect([](void *arg, AsyncClient *client) { + Serial.printf("** client has been disconnected: %" PRIu16 "\n", client->localPort()); + client->close(true); + delete client; + client_running = false; + }); + + client->onData([](void *arg, AsyncClient *client, void *data, size_t len) { + Serial.printf("** data received by client: %" PRIu16 ": len=%u\n", client->localPort(), len); + }); + + client->write("GET /README.md HTTP/1.1\r\nHost: " HOST "\r\nUser-Agent: ESP\r\nConnection: close\r\n\r\n"); + }); + + if (!client->connect(HOST, PORT)) { + Serial.println("** connection failed"); + client_running = false; + } +} + +void setup() { + Serial.begin(115200); + + Serial.print("Connecting to "); + Serial.print(WIFI_SSID); + WiFi.begin(WIFI_SSID, WIFI_PASS); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(); + Serial.print("Connected to WiFi. IP: "); + Serial.println(WiFi.localIP()); +} + +void loop() { + if (!client_running) { + makeRequest(); + } + delay(1000); + Serial.printf("** free heap: %" PRIu32 "\n", ESP.getFreeHeap()); +} diff --git a/watering/lib/AsyncTCP/idf_component_examples/client/sdkconfig.defaults b/watering/lib/AsyncTCP/idf_component_examples/client/sdkconfig.defaults new file mode 100644 index 0000000..bb72365 --- /dev/null +++ b/watering/lib/AsyncTCP/idf_component_examples/client/sdkconfig.defaults @@ -0,0 +1,12 @@ +# +# Arduino ESP32 +# +CONFIG_AUTOSTART_ARDUINO=y +# end of Arduino ESP32 + +# +# FREERTOS +# +CONFIG_FREERTOS_HZ=1000 +# end of FREERTOS +# end of Component config diff --git a/watering/lib/AsyncTCP/library.json b/watering/lib/AsyncTCP/library.json new file mode 100644 index 0000000..3252141 --- /dev/null +++ b/watering/lib/AsyncTCP/library.json @@ -0,0 +1,31 @@ +{ + "name": "AsyncTCP", + "version": "3.3.8", + "description": "Asynchronous TCP Library for ESP32", + "keywords": "async,tcp", + "repository": { + "type": "git", + "url": "https://github.com/ESP32Async/AsyncTCP.git" + }, + "authors": + { + "name": "ESP32Async", + "maintainer": true + }, + "license": "LGPL-3.0", + "frameworks": "arduino", + "platforms": [ + "espressif32", + "libretiny" + ], + "export": { + "include": [ + "examples", + "src", + "library.json", + "library.properties", + "LICENSE", + "README.md" + ] + } +} diff --git a/watering/lib/AsyncTCP/library.properties b/watering/lib/AsyncTCP/library.properties new file mode 100644 index 0000000..edb5760 --- /dev/null +++ b/watering/lib/AsyncTCP/library.properties @@ -0,0 +1,11 @@ +name=Async TCP +includes=AsyncTCP.h +version=3.3.8 +author=ESP32Async +maintainer=ESP32Async +sentence=Async TCP Library for ESP32 +paragraph=Async TCP Library for ESP32 +category=Other +url=https://github.com/ESP32Async/AsyncTCP.git +architectures=* +license=LGPL-3.0 diff --git a/watering/lib/AsyncTCP/platformio.ini b/watering/lib/AsyncTCP/platformio.ini new file mode 100644 index 0000000..5ae31c8 --- /dev/null +++ b/watering/lib/AsyncTCP/platformio.ini @@ -0,0 +1,45 @@ +[platformio] +default_envs = arduino-2, arduino-3 +lib_dir = . +; src_dir = examples/Client +; src_dir = examples/FetchWebsite +src_dir = examples/AsyncSend + +[env] +framework = arduino +build_flags = + -Wall -Wextra + -D CONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 + -D CONFIG_ASYNC_TCP_PRIORITY=10 + -D CONFIG_ASYNC_TCP_QUEUE_SIZE=64 + -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 + -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 + -D CONFIG_ARDUHAL_LOG_COLORS + -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG +upload_protocol = esptool +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder, log2file +board = esp32dev + +[env:arduino-2] +platform = espressif32@6.10.0 + +[env:arduino-3] +platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20/platform-espressif32.zip + +[env:arduino-3-latest] +platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20-rc2/platform-espressif32.zip + +; CI + +[env:ci-arduino-2] +platform = espressif32@6.10.0 +board = ${sysenv.PIO_BOARD} + +[env:ci-arduino-3] +platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20/platform-espressif32.zip +board = ${sysenv.PIO_BOARD} + +[env:ci-arduino-3-latest] +platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20-rc2/platform-espressif32.zip +board = ${sysenv.PIO_BOARD} diff --git a/watering/lib/AsyncTCP/pre-commit.requirements.txt b/watering/lib/AsyncTCP/pre-commit.requirements.txt new file mode 100644 index 0000000..40a16fa --- /dev/null +++ b/watering/lib/AsyncTCP/pre-commit.requirements.txt @@ -0,0 +1 @@ +pre-commit==4.1.0 diff --git a/watering/lib/AsyncTCP/src/AsyncTCP.cpp b/watering/lib/AsyncTCP/src/AsyncTCP.cpp new file mode 100644 index 0000000..fe1efc4 --- /dev/null +++ b/watering/lib/AsyncTCP/src/AsyncTCP.cpp @@ -0,0 +1,1682 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "Arduino.h" + +#include "AsyncTCP.h" + +extern "C" { +#include "lwip/dns.h" +#include "lwip/err.h" +#include "lwip/inet.h" +#include "lwip/opt.h" +#include "lwip/tcp.h" +} + +#if CONFIG_ASYNC_TCP_USE_WDT +#include "esp_task_wdt.h" +#endif + +// Required for: +// https://github.com/espressif/arduino-esp32/blob/3.0.3/libraries/Network/src/NetworkInterface.cpp#L37-L47 +#if ESP_IDF_VERSION_MAJOR >= 5 +#include +#endif + +// https://github.com/espressif/arduino-esp32/issues/10526 +#ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING +#define TCP_MUTEX_LOCK() \ + if (!sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) { \ + LOCK_TCPIP_CORE(); \ + } + +#define TCP_MUTEX_UNLOCK() \ + if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) { \ + UNLOCK_TCPIP_CORE(); \ + } +#else // CONFIG_LWIP_TCPIP_CORE_LOCKING +#define TCP_MUTEX_LOCK() +#define TCP_MUTEX_UNLOCK() +#endif // CONFIG_LWIP_TCPIP_CORE_LOCKING + +#define INVALID_CLOSED_SLOT -1 + +/* + TCP poll interval is specified in terms of the TCP coarse timer interval, which is called twice a second + https://github.com/espressif/esp-lwip/blob/2acf959a2bb559313cd2bf9306c24612ba3d0e19/src/core/tcp.c#L1895 +*/ +#define CONFIG_ASYNC_TCP_POLL_TIMER 1 + +/* + * TCP/IP Event Task + * */ + +typedef enum { + LWIP_TCP_SENT, + LWIP_TCP_RECV, + LWIP_TCP_FIN, + LWIP_TCP_ERROR, + LWIP_TCP_POLL, + LWIP_TCP_CLEAR, + LWIP_TCP_ACCEPT, + LWIP_TCP_CONNECTED, + LWIP_TCP_DNS +} lwip_tcp_event_t; + +typedef struct { + lwip_tcp_event_t event; + void *arg; + union { + struct { + tcp_pcb *pcb; + int8_t err; + } connected; + struct { + int8_t err; + } error; + struct { + tcp_pcb *pcb; + uint16_t len; + } sent; + struct { + tcp_pcb *pcb; + pbuf *pb; + int8_t err; + } recv; + struct { + tcp_pcb *pcb; + int8_t err; + } fin; + struct { + tcp_pcb *pcb; + } poll; + struct { + AsyncClient *client; + } accept; + struct { + const char *name; + ip_addr_t addr; + } dns; + }; +} lwip_tcp_event_packet_t; + +static QueueHandle_t _async_queue = NULL; +static TaskHandle_t _async_service_task_handle = NULL; + +static SemaphoreHandle_t _slots_lock = NULL; +static const int _number_of_closed_slots = CONFIG_LWIP_MAX_ACTIVE_TCP; +static uint32_t _closed_slots[_number_of_closed_slots]; +static uint32_t _closed_index = []() { + _slots_lock = xSemaphoreCreateBinary(); + configASSERT(_slots_lock); // Add sanity check + xSemaphoreGive(_slots_lock); + for (int i = 0; i < _number_of_closed_slots; ++i) { + _closed_slots[i] = 1; + } + return 1; +}(); + +static inline bool _init_async_event_queue() { + if (!_async_queue) { + _async_queue = xQueueCreate(CONFIG_ASYNC_TCP_QUEUE_SIZE, sizeof(lwip_tcp_event_packet_t *)); + if (!_async_queue) { + return false; + } + } + return true; +} + +static inline bool _send_async_event(lwip_tcp_event_packet_t **e, TickType_t wait = portMAX_DELAY) { + return _async_queue && xQueueSend(_async_queue, e, wait) == pdPASS; +} + +static inline bool _prepend_async_event(lwip_tcp_event_packet_t **e, TickType_t wait = portMAX_DELAY) { + return _async_queue && xQueueSendToFront(_async_queue, e, wait) == pdPASS; +} + +static inline bool _get_async_event(lwip_tcp_event_packet_t **e) { + while (true) { + if (!_async_queue) { + break; + } + +#if CONFIG_ASYNC_TCP_USE_WDT + // need to return periodically to feed the dog + if (xQueueReceive(_async_queue, e, pdMS_TO_TICKS(1000)) != pdPASS) { + break; + } +#else + if (xQueueReceive(_async_queue, e, portMAX_DELAY) != pdPASS) { + break; + } +#endif + + if ((*e)->event != LWIP_TCP_POLL) { + return true; + } + + /* + Let's try to coalesce two (or more) consecutive poll events into one + this usually happens with poor implemented user-callbacks that are runs too long and makes poll events to stack in the queue + if consecutive user callback for a same connection runs longer that poll time then it will fill the queue with events until it deadlocks. + This is a workaround to mitigate such poor designs and won't let other events/connections to starve the task time. + It won't be effective if user would run multiple simultaneous long running callbacks due to message interleaving. + todo: implement some kind of fair dequeuing or (better) simply punish user for a bad designed callbacks by resetting hog connections + */ + lwip_tcp_event_packet_t *next_pkt = NULL; + while (xQueuePeek(_async_queue, &next_pkt, 0) == pdPASS) { + // if the next event that will come is a poll event for the same connection, we can discard it and continue + if (next_pkt->arg == (*e)->arg && next_pkt->event == LWIP_TCP_POLL) { + if (xQueueReceive(_async_queue, &next_pkt, 0) == pdPASS) { + free(next_pkt); + next_pkt = NULL; + log_d("coalescing polls, network congestion or async callbacks might be too slow!"); + continue; + } + } + + // quit while loop if next incoming event can't be discarded (not a poll event) + break; + } + + /* + now we have to decide if to proceed with poll callback handler or discard it? + poor designed apps using asynctcp without proper dataflow control could flood the queue with interleaved pool/ack events. + I.e. on each poll app would try to generate more data to send, which in turn results in additional ack event triggering chain effect + for long connections. Or poll callback could take long time starving other connections. Anyway our goal is to keep the queue length + grows under control (if possible) and poll events are the safest to discard. + Let's discard poll events processing using linear-increasing probability curve when queue size grows over 3/4 + Poll events are periodic and connection could get another chance next time + */ + if (uxQueueMessagesWaiting(_async_queue) > (rand() % CONFIG_ASYNC_TCP_QUEUE_SIZE / 4 + CONFIG_ASYNC_TCP_QUEUE_SIZE * 3 / 4)) { + free(*e); + *e = NULL; + log_d("discarding poll due to queue congestion"); + continue; // continue main loop to dequeue next event which we know is not a poll event + } + return true; // queue not nearly full, caller can process the poll event + } + return false; +} + +static bool _remove_events_with_arg(void *arg) { + if (!_async_queue) { + return false; + } + + lwip_tcp_event_packet_t *first_packet = NULL; + lwip_tcp_event_packet_t *packet = NULL; + + // figure out which is the first non-matching packet so we can keep the order + while (!first_packet) { + if (xQueueReceive(_async_queue, &first_packet, 0) != pdPASS) { + return false; + } + // discard packet if matching + if ((uintptr_t)first_packet->arg == (uintptr_t)arg) { + free(first_packet); + first_packet = NULL; + } else if (xQueueSend(_async_queue, &first_packet, 0) != pdPASS) { + // try to return first packet to the back of the queue + // we can't wait here if queue is full, because this call has been done from the only consumer task of this queue + // otherwise it would deadlock, we have to discard the event + free(first_packet); + first_packet = NULL; + return false; + } + } + + while (xQueuePeek(_async_queue, &packet, 0) == pdPASS && packet != first_packet) { + if (xQueueReceive(_async_queue, &packet, 0) != pdPASS) { + return false; + } + if ((uintptr_t)packet->arg == (uintptr_t)arg) { + // remove matching event + free(packet); + packet = NULL; + // otherwise try to requeue it + } else if (xQueueSend(_async_queue, &packet, 0) != pdPASS) { + // we can't wait here if queue is full, because this call has been done from the only consumer task of this queue + // otherwise it would deadlock, we have to discard the event + free(packet); + packet = NULL; + return false; + } + } + return true; +} + +static void _handle_async_event(lwip_tcp_event_packet_t *e) { + if (e->arg == NULL) { + // do nothing when arg is NULL + // ets_printf("event arg == NULL: 0x%08x\n", e->recv.pcb); + } else if (e->event == LWIP_TCP_CLEAR) { + _remove_events_with_arg(e->arg); + } else if (e->event == LWIP_TCP_RECV) { + // ets_printf("-R: 0x%08x\n", e->recv.pcb); + AsyncClient::_s_recv(e->arg, e->recv.pcb, e->recv.pb, e->recv.err); + } else if (e->event == LWIP_TCP_FIN) { + // ets_printf("-F: 0x%08x\n", e->fin.pcb); + AsyncClient::_s_fin(e->arg, e->fin.pcb, e->fin.err); + } else if (e->event == LWIP_TCP_SENT) { + // ets_printf("-S: 0x%08x\n", e->sent.pcb); + AsyncClient::_s_sent(e->arg, e->sent.pcb, e->sent.len); + } else if (e->event == LWIP_TCP_POLL) { + // ets_printf("-P: 0x%08x\n", e->poll.pcb); + AsyncClient::_s_poll(e->arg, e->poll.pcb); + } else if (e->event == LWIP_TCP_ERROR) { + // ets_printf("-E: 0x%08x %d\n", e->arg, e->error.err); + AsyncClient::_s_error(e->arg, e->error.err); + } else if (e->event == LWIP_TCP_CONNECTED) { + // ets_printf("C: 0x%08x 0x%08x %d\n", e->arg, e->connected.pcb, e->connected.err); + AsyncClient::_s_connected(e->arg, e->connected.pcb, e->connected.err); + } else if (e->event == LWIP_TCP_ACCEPT) { + // ets_printf("A: 0x%08x 0x%08x\n", e->arg, e->accept.client); + AsyncServer::_s_accepted(e->arg, e->accept.client); + } else if (e->event == LWIP_TCP_DNS) { + // ets_printf("D: 0x%08x %s = %s\n", e->arg, e->dns.name, ipaddr_ntoa(&e->dns.addr)); + AsyncClient::_s_dns_found(e->dns.name, &e->dns.addr, e->arg); + } + free((void *)(e)); +} + +static void _async_service_task(void *pvParameters) { +#if CONFIG_ASYNC_TCP_USE_WDT + if (esp_task_wdt_add(NULL) != ESP_OK) { + log_w("Failed to add async task to WDT"); + } +#endif + lwip_tcp_event_packet_t *packet = NULL; + for (;;) { + if (_get_async_event(&packet)) { + _handle_async_event(packet); + } +#if CONFIG_ASYNC_TCP_USE_WDT + esp_task_wdt_reset(); +#endif + } +#if CONFIG_ASYNC_TCP_USE_WDT + esp_task_wdt_delete(NULL); +#endif + vTaskDelete(NULL); + _async_service_task_handle = NULL; +} +/* +static void _stop_async_task(){ + if(_async_service_task_handle){ + vTaskDelete(_async_service_task_handle); + _async_service_task_handle = NULL; + } +} +*/ + +static bool customTaskCreateUniversal( + TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t usStackDepth, void *const pvParameters, UBaseType_t uxPriority, + TaskHandle_t *const pxCreatedTask, const BaseType_t xCoreID +) { +#ifndef CONFIG_FREERTOS_UNICORE + if (xCoreID >= 0 && xCoreID < 2) { + return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID); + } else { +#endif + return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); +#ifndef CONFIG_FREERTOS_UNICORE + } +#endif +} + +static bool _start_async_task() { + if (!_init_async_event_queue()) { + return false; + } + if (!_async_service_task_handle) { + customTaskCreateUniversal( + _async_service_task, "async_tcp", CONFIG_ASYNC_TCP_STACK_SIZE, NULL, CONFIG_ASYNC_TCP_PRIORITY, &_async_service_task_handle, CONFIG_ASYNC_TCP_RUNNING_CORE + ); + if (!_async_service_task_handle) { + return false; + } + } + return true; +} + +/* + * LwIP Callbacks + * */ + +static int8_t _tcp_clear_events(void *arg) { + lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t)); + if (!e) { + log_e("Failed to allocate event packet"); + return ERR_MEM; + } + e->event = LWIP_TCP_CLEAR; + e->arg = arg; + if (!_prepend_async_event(&e)) { + free((void *)(e)); + return ERR_TIMEOUT; + } + return ERR_OK; +} + +static int8_t _tcp_connected(void *arg, tcp_pcb *pcb, int8_t err) { + // ets_printf("+C: 0x%08x\n", pcb); + lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t)); + if (!e) { + log_e("Failed to allocate event packet"); + return ERR_MEM; + } + e->event = LWIP_TCP_CONNECTED; + e->arg = arg; + e->connected.pcb = pcb; + e->connected.err = err; + if (!_prepend_async_event(&e)) { + free((void *)(e)); + return ERR_TIMEOUT; + } + return ERR_OK; +} + +static int8_t _tcp_poll(void *arg, struct tcp_pcb *pcb) { + // throttle polling events queueing when event queue is getting filled up, let it handle _onack's + // log_d("qs:%u", uxQueueMessagesWaiting(_async_queue)); + if (uxQueueMessagesWaiting(_async_queue) > (rand() % CONFIG_ASYNC_TCP_QUEUE_SIZE / 2 + CONFIG_ASYNC_TCP_QUEUE_SIZE / 4)) { + log_d("throttling"); + return ERR_OK; + } + + // ets_printf("+P: 0x%08x\n", pcb); + lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t)); + if (!e) { + log_e("Failed to allocate event packet"); + return ERR_MEM; + } + e->event = LWIP_TCP_POLL; + e->arg = arg; + e->poll.pcb = pcb; + // poll events are not critical 'cause those are repetitive, so we may not wait the queue in any case + if (!_send_async_event(&e, 0)) { + free((void *)(e)); + return ERR_TIMEOUT; + } + return ERR_OK; +} + +static int8_t _tcp_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *pb, int8_t err) { + lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t)); + if (!e) { + log_e("Failed to allocate event packet"); + return ERR_MEM; + } + e->arg = arg; + if (pb) { + // ets_printf("+R: 0x%08x\n", pcb); + e->event = LWIP_TCP_RECV; + e->recv.pcb = pcb; + e->recv.pb = pb; + e->recv.err = err; + } else { + // ets_printf("+F: 0x%08x\n", pcb); + e->event = LWIP_TCP_FIN; + e->fin.pcb = pcb; + e->fin.err = err; + // close the PCB in LwIP thread + AsyncClient::_s_lwip_fin(e->arg, e->fin.pcb, e->fin.err); + } + if (!_send_async_event(&e)) { + free((void *)(e)); + return ERR_TIMEOUT; + } + return ERR_OK; +} + +static int8_t _tcp_sent(void *arg, struct tcp_pcb *pcb, uint16_t len) { + // ets_printf("+S: 0x%08x\n", pcb); + lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t)); + if (!e) { + log_e("Failed to allocate event packet"); + return ERR_MEM; + } + e->event = LWIP_TCP_SENT; + e->arg = arg; + e->sent.pcb = pcb; + e->sent.len = len; + if (!_send_async_event(&e)) { + free((void *)(e)); + return ERR_TIMEOUT; + } + return ERR_OK; +} + +void AsyncClient::_tcp_error(void *arg, int8_t err) { + // ets_printf("+E: 0x%08x\n", arg); + AsyncClient *client = reinterpret_cast(arg); + if (client && client->_pcb) { + tcp_arg(client->_pcb, NULL); + if (client->_pcb->state == LISTEN) { + tcp_sent(client->_pcb, NULL); + tcp_recv(client->_pcb, NULL); + tcp_err(client->_pcb, NULL); + tcp_poll(client->_pcb, NULL, 0); + } + client->_pcb = nullptr; + client->_free_closed_slot(); + } + + // enqueue event to be processed in the async task for the user callback + lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t)); + if (!e) { + log_e("Failed to allocate event packet"); + return; + } + e->event = LWIP_TCP_ERROR; + e->arg = arg; + e->error.err = err; + if (!_send_async_event(&e)) { + ::free((void *)(e)); + } +} + +static void _tcp_dns_found(const char *name, struct ip_addr *ipaddr, void *arg) { + lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t)); + if (!e) { + log_e("Failed to allocate event packet"); + return; + } + // ets_printf("+DNS: name=%s ipaddr=0x%08x arg=%x\n", name, ipaddr, arg); + e->event = LWIP_TCP_DNS; + e->arg = arg; + e->dns.name = name; + if (ipaddr) { + memcpy(&e->dns.addr, ipaddr, sizeof(struct ip_addr)); + } else { + memset(&e->dns.addr, 0, sizeof(e->dns.addr)); + } + if (!_send_async_event(&e)) { + free((void *)(e)); + } +} + +// Used to switch out from LwIP thread +static int8_t _tcp_accept(void *arg, AsyncClient *client) { + lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t)); + if (!e) { + log_e("Failed to allocate event packet"); + return ERR_MEM; + } + e->event = LWIP_TCP_ACCEPT; + e->arg = arg; + e->accept.client = client; + if (!_prepend_async_event(&e)) { + free((void *)(e)); + return ERR_TIMEOUT; + } + return ERR_OK; +} + +/* + * TCP/IP API Calls + * */ + +#include "lwip/priv/tcpip_priv.h" + +typedef struct { + struct tcpip_api_call_data call; + tcp_pcb *pcb; + int8_t closed_slot; + int8_t err; + union { + struct { + const char *data; + size_t size; + uint8_t apiflags; + } write; + size_t received; + struct { + ip_addr_t *addr; + uint16_t port; + tcp_connected_fn cb; + } connect; + struct { + ip_addr_t *addr; + uint16_t port; + } bind; + uint8_t backlog; + }; +} tcp_api_call_t; + +static err_t _tcp_output_api(struct tcpip_api_call_data *api_call_msg) { + tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg; + msg->err = ERR_CONN; + if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) { + msg->err = tcp_output(msg->pcb); + } + return msg->err; +} + +static esp_err_t _tcp_output(tcp_pcb *pcb, int8_t closed_slot) { + if (!pcb) { + return ERR_CONN; + } + tcp_api_call_t msg; + msg.pcb = pcb; + msg.closed_slot = closed_slot; + tcpip_api_call(_tcp_output_api, (struct tcpip_api_call_data *)&msg); + return msg.err; +} + +static err_t _tcp_write_api(struct tcpip_api_call_data *api_call_msg) { + tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg; + msg->err = ERR_CONN; + if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) { + msg->err = tcp_write(msg->pcb, msg->write.data, msg->write.size, msg->write.apiflags); + } + return msg->err; +} + +static esp_err_t _tcp_write(tcp_pcb *pcb, int8_t closed_slot, const char *data, size_t size, uint8_t apiflags) { + if (!pcb) { + return ERR_CONN; + } + tcp_api_call_t msg; + msg.pcb = pcb; + msg.closed_slot = closed_slot; + msg.write.data = data; + msg.write.size = size; + msg.write.apiflags = apiflags; + tcpip_api_call(_tcp_write_api, (struct tcpip_api_call_data *)&msg); + return msg.err; +} + +static err_t _tcp_recved_api(struct tcpip_api_call_data *api_call_msg) { + tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg; + msg->err = ERR_CONN; + if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) { + // if(msg->closed_slot != INVALID_CLOSED_SLOT && !_closed_slots[msg->closed_slot]) { + // if(msg->closed_slot != INVALID_CLOSED_SLOT) { + msg->err = 0; + tcp_recved(msg->pcb, msg->received); + } + return msg->err; +} + +static esp_err_t _tcp_recved(tcp_pcb *pcb, int8_t closed_slot, size_t len) { + if (!pcb) { + return ERR_CONN; + } + tcp_api_call_t msg; + msg.pcb = pcb; + msg.closed_slot = closed_slot; + msg.received = len; + tcpip_api_call(_tcp_recved_api, (struct tcpip_api_call_data *)&msg); + return msg.err; +} + +static err_t _tcp_close_api(struct tcpip_api_call_data *api_call_msg) { + tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg; + msg->err = ERR_CONN; + if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) { + msg->err = tcp_close(msg->pcb); + } + return msg->err; +} + +static esp_err_t _tcp_close(tcp_pcb *pcb, int8_t closed_slot) { + if (!pcb) { + return ERR_CONN; + } + tcp_api_call_t msg; + msg.pcb = pcb; + msg.closed_slot = closed_slot; + tcpip_api_call(_tcp_close_api, (struct tcpip_api_call_data *)&msg); + return msg.err; +} + +static err_t _tcp_abort_api(struct tcpip_api_call_data *api_call_msg) { + tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg; + msg->err = ERR_CONN; + if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) { + tcp_abort(msg->pcb); + } + return msg->err; +} + +static esp_err_t _tcp_abort(tcp_pcb *pcb, int8_t closed_slot) { + if (!pcb) { + return ERR_CONN; + } + tcp_api_call_t msg; + msg.pcb = pcb; + msg.closed_slot = closed_slot; + tcpip_api_call(_tcp_abort_api, (struct tcpip_api_call_data *)&msg); + return msg.err; +} + +static err_t _tcp_connect_api(struct tcpip_api_call_data *api_call_msg) { + tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg; + msg->err = tcp_connect(msg->pcb, msg->connect.addr, msg->connect.port, msg->connect.cb); + return msg->err; +} + +static esp_err_t _tcp_connect(tcp_pcb *pcb, int8_t closed_slot, ip_addr_t *addr, uint16_t port, tcp_connected_fn cb) { + if (!pcb) { + return ESP_FAIL; + } + tcp_api_call_t msg; + msg.pcb = pcb; + msg.closed_slot = closed_slot; + msg.connect.addr = addr; + msg.connect.port = port; + msg.connect.cb = cb; + tcpip_api_call(_tcp_connect_api, (struct tcpip_api_call_data *)&msg); + return msg.err; +} + +static err_t _tcp_bind_api(struct tcpip_api_call_data *api_call_msg) { + tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg; + msg->err = tcp_bind(msg->pcb, msg->bind.addr, msg->bind.port); + return msg->err; +} + +static esp_err_t _tcp_bind(tcp_pcb *pcb, ip_addr_t *addr, uint16_t port) { + if (!pcb) { + return ESP_FAIL; + } + tcp_api_call_t msg; + msg.pcb = pcb; + msg.closed_slot = -1; + msg.bind.addr = addr; + msg.bind.port = port; + tcpip_api_call(_tcp_bind_api, (struct tcpip_api_call_data *)&msg); + return msg.err; +} + +static err_t _tcp_listen_api(struct tcpip_api_call_data *api_call_msg) { + tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg; + msg->err = 0; + msg->pcb = tcp_listen_with_backlog(msg->pcb, msg->backlog); + return msg->err; +} + +static tcp_pcb *_tcp_listen_with_backlog(tcp_pcb *pcb, uint8_t backlog) { + if (!pcb) { + return NULL; + } + tcp_api_call_t msg; + msg.pcb = pcb; + msg.closed_slot = -1; + msg.backlog = backlog ? backlog : 0xFF; + tcpip_api_call(_tcp_listen_api, (struct tcpip_api_call_data *)&msg); + return msg.pcb; +} + +/* + Async TCP Client + */ + +AsyncClient::AsyncClient(tcp_pcb *pcb) + : _connect_cb(0), _connect_cb_arg(0), _discard_cb(0), _discard_cb_arg(0), _sent_cb(0), _sent_cb_arg(0), _error_cb(0), _error_cb_arg(0), _recv_cb(0), + _recv_cb_arg(0), _pb_cb(0), _pb_cb_arg(0), _timeout_cb(0), _timeout_cb_arg(0), _poll_cb(0), _poll_cb_arg(0), _ack_pcb(true), _tx_last_packet(0), + _rx_timeout(0), _rx_last_ack(0), _ack_timeout(CONFIG_ASYNC_TCP_MAX_ACK_TIME), _connect_port(0), prev(NULL), next(NULL) { + _pcb = pcb; + _closed_slot = INVALID_CLOSED_SLOT; + if (_pcb) { + _rx_last_packet = millis(); + tcp_arg(_pcb, this); + tcp_recv(_pcb, &_tcp_recv); + tcp_sent(_pcb, &_tcp_sent); + tcp_err(_pcb, &_tcp_error); + tcp_poll(_pcb, &_tcp_poll, CONFIG_ASYNC_TCP_POLL_TIMER); + if (!_allocate_closed_slot()) { + _close(); + } + } +} + +AsyncClient::~AsyncClient() { + if (_pcb) { + _close(); + } + _free_closed_slot(); +} + +/* + * Operators + * */ + +AsyncClient &AsyncClient::operator=(const AsyncClient &other) { + if (_pcb) { + _close(); + } + + _pcb = other._pcb; + _closed_slot = other._closed_slot; + if (_pcb) { + _rx_last_packet = millis(); + tcp_arg(_pcb, this); + tcp_recv(_pcb, &_tcp_recv); + tcp_sent(_pcb, &_tcp_sent); + tcp_err(_pcb, &_tcp_error); + tcp_poll(_pcb, &_tcp_poll, CONFIG_ASYNC_TCP_POLL_TIMER); + } + return *this; +} + +bool AsyncClient::operator==(const AsyncClient &other) const { + return _pcb == other._pcb; +} + +AsyncClient &AsyncClient::operator+=(const AsyncClient &other) { + if (next == NULL) { + next = (AsyncClient *)(&other); + next->prev = this; + } else { + AsyncClient *c = next; + while (c->next != NULL) { + c = c->next; + } + c->next = (AsyncClient *)(&other); + c->next->prev = c; + } + return *this; +} + +/* + * Callback Setters + * */ + +void AsyncClient::onConnect(AcConnectHandler cb, void *arg) { + _connect_cb = cb; + _connect_cb_arg = arg; +} + +void AsyncClient::onDisconnect(AcConnectHandler cb, void *arg) { + _discard_cb = cb; + _discard_cb_arg = arg; +} + +void AsyncClient::onAck(AcAckHandler cb, void *arg) { + _sent_cb = cb; + _sent_cb_arg = arg; +} + +void AsyncClient::onError(AcErrorHandler cb, void *arg) { + _error_cb = cb; + _error_cb_arg = arg; +} + +void AsyncClient::onData(AcDataHandler cb, void *arg) { + _recv_cb = cb; + _recv_cb_arg = arg; +} + +void AsyncClient::onPacket(AcPacketHandler cb, void *arg) { + _pb_cb = cb; + _pb_cb_arg = arg; +} + +void AsyncClient::onTimeout(AcTimeoutHandler cb, void *arg) { + _timeout_cb = cb; + _timeout_cb_arg = arg; +} + +void AsyncClient::onPoll(AcConnectHandler cb, void *arg) { + _poll_cb = cb; + _poll_cb_arg = arg; +} + +/* + * Main Public Methods + * */ + +bool AsyncClient::_connect(ip_addr_t addr, uint16_t port) { + if (_pcb) { + log_d("already connected, state %d", _pcb->state); + return false; + } + if (!_start_async_task()) { + log_e("failed to start task"); + return false; + } + + if (!_allocate_closed_slot()) { + log_e("failed to allocate: closed slot full"); + return false; + } + + TCP_MUTEX_LOCK(); + tcp_pcb *pcb = tcp_new_ip_type(addr.type); + if (!pcb) { + TCP_MUTEX_UNLOCK(); + log_e("pcb == NULL"); + return false; + } + tcp_arg(pcb, this); + tcp_err(pcb, &_tcp_error); + tcp_recv(pcb, &_tcp_recv); + tcp_sent(pcb, &_tcp_sent); + tcp_poll(pcb, &_tcp_poll, CONFIG_ASYNC_TCP_POLL_TIMER); + TCP_MUTEX_UNLOCK(); + + esp_err_t err = _tcp_connect(pcb, _closed_slot, &addr, port, (tcp_connected_fn)&_tcp_connected); + return err == ESP_OK; +} + +bool AsyncClient::connect(const IPAddress &ip, uint16_t port) { + ip_addr_t addr; +#if ESP_IDF_VERSION_MAJOR < 5 + addr.u_addr.ip4.addr = ip; + addr.type = IPADDR_TYPE_V4; +#else + ip.to_ip_addr_t(&addr); +#endif + + return _connect(addr, port); +} + +#if LWIP_IPV6 && ESP_IDF_VERSION_MAJOR < 5 +bool AsyncClient::connect(const IPv6Address &ip, uint16_t port) { + auto ipaddr = static_cast(ip); + ip_addr_t addr = IPADDR6_INIT(ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]); + + return _connect(addr, port); +} +#endif + +bool AsyncClient::connect(const char *host, uint16_t port) { + ip_addr_t addr; + + if (!_start_async_task()) { + log_e("failed to start task"); + return false; + } + + TCP_MUTEX_LOCK(); + err_t err = dns_gethostbyname(host, &addr, (dns_found_callback)&_tcp_dns_found, this); + TCP_MUTEX_UNLOCK(); + if (err == ERR_OK) { +#if ESP_IDF_VERSION_MAJOR < 5 +#if LWIP_IPV6 + if (addr.type == IPADDR_TYPE_V6) { + return connect(IPv6Address(addr.u_addr.ip6.addr), port); + } + return connect(IPAddress(addr.u_addr.ip4.addr), port); +#else + return connect(IPAddress(addr.addr), port); +#endif +#else + return _connect(addr, port); +#endif + } else if (err == ERR_INPROGRESS) { + _connect_port = port; + return true; + } + log_d("error: %d", err); + return false; +} + +void AsyncClient::close(bool now) { + if (_pcb) { + _tcp_recved(_pcb, _closed_slot, _rx_ack_len); + } + _close(); +} + +int8_t AsyncClient::abort() { + if (_pcb) { + _tcp_abort(_pcb, _closed_slot); + _pcb = NULL; + } + return ERR_ABRT; +} + +size_t AsyncClient::space() const { + if ((_pcb != NULL) && (_pcb->state == ESTABLISHED)) { + return tcp_sndbuf(_pcb); + } + return 0; +} + +size_t AsyncClient::add(const char *data, size_t size, uint8_t apiflags) { + if (!_pcb || size == 0 || data == NULL) { + return 0; + } + size_t room = space(); + if (!room) { + return 0; + } + size_t will_send = (room < size) ? room : size; + int8_t err = ERR_OK; + err = _tcp_write(_pcb, _closed_slot, data, will_send, apiflags); + if (err != ERR_OK) { + return 0; + } + return will_send; +} + +bool AsyncClient::send() { + auto backup = _tx_last_packet; + _tx_last_packet = millis(); + if (_tcp_output(_pcb, _closed_slot) == ERR_OK) { + return true; + } + _tx_last_packet = backup; + return false; +} + +size_t AsyncClient::ack(size_t len) { + if (len > _rx_ack_len) { + len = _rx_ack_len; + } + if (len) { + _tcp_recved(_pcb, _closed_slot, len); + } + _rx_ack_len -= len; + return len; +} + +void AsyncClient::ackPacket(struct pbuf *pb) { + if (!pb) { + return; + } + _tcp_recved(_pcb, _closed_slot, pb->len); + pbuf_free(pb); +} + +/* + * Main Private Methods + * */ + +int8_t AsyncClient::_close() { + // ets_printf("X: 0x%08x\n", (uint32_t)this); + int8_t err = ERR_OK; + if (_pcb) { + TCP_MUTEX_LOCK(); + tcp_arg(_pcb, NULL); + tcp_sent(_pcb, NULL); + tcp_recv(_pcb, NULL); + tcp_err(_pcb, NULL); + tcp_poll(_pcb, NULL, 0); + TCP_MUTEX_UNLOCK(); + _tcp_clear_events(this); + err = _tcp_close(_pcb, _closed_slot); + if (err != ERR_OK) { + err = abort(); + } + _free_closed_slot(); + _pcb = NULL; + if (_discard_cb) { + _discard_cb(_discard_cb_arg, this); + } + } + return err; +} + +bool AsyncClient::_allocate_closed_slot() { + bool allocated = false; + if (xSemaphoreTake(_slots_lock, portMAX_DELAY) == pdTRUE) { + uint32_t closed_slot_min_index = 0; + allocated = _closed_slot != INVALID_CLOSED_SLOT; + if (!allocated) { + for (int i = 0; i < _number_of_closed_slots; ++i) { + if ((_closed_slot == INVALID_CLOSED_SLOT || _closed_slots[i] <= closed_slot_min_index) && _closed_slots[i] != 0) { + closed_slot_min_index = _closed_slots[i]; + _closed_slot = i; + } + } + allocated = _closed_slot != INVALID_CLOSED_SLOT; + if (allocated) { + _closed_slots[_closed_slot] = 0; + } + } + xSemaphoreGive(_slots_lock); + } + return allocated; +} + +void AsyncClient::_free_closed_slot() { + xSemaphoreTake(_slots_lock, portMAX_DELAY); + if (_closed_slot != INVALID_CLOSED_SLOT) { + _closed_slots[_closed_slot] = _closed_index; + _closed_slot = INVALID_CLOSED_SLOT; + ++_closed_index; + } + xSemaphoreGive(_slots_lock); +} + +/* + * Private Callbacks + * */ + +int8_t AsyncClient::_connected(tcp_pcb *pcb, int8_t err) { + _pcb = reinterpret_cast(pcb); + if (_pcb) { + _rx_last_packet = millis(); + } + _tx_last_packet = 0; + _rx_last_ack = 0; + if (_connect_cb) { + _connect_cb(_connect_cb_arg, this); + } + return ERR_OK; +} + +void AsyncClient::_error(int8_t err) { + if (_error_cb) { + _error_cb(_error_cb_arg, this, err); + } + if (_discard_cb) { + _discard_cb(_discard_cb_arg, this); + } +} + +// In LwIP Thread +int8_t AsyncClient::_lwip_fin(tcp_pcb *pcb, int8_t err) { + if (!_pcb || pcb != _pcb) { + log_d("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); + return ERR_OK; + } + tcp_arg(_pcb, NULL); + if (_pcb->state == LISTEN) { + tcp_sent(_pcb, NULL); + tcp_recv(_pcb, NULL); + tcp_err(_pcb, NULL); + tcp_poll(_pcb, NULL, 0); + } + if (tcp_close(_pcb) != ERR_OK) { + tcp_abort(_pcb); + } + _free_closed_slot(); + _pcb = NULL; + return ERR_OK; +} + +// In Async Thread +int8_t AsyncClient::_fin(tcp_pcb *pcb, int8_t err) { + _tcp_clear_events(this); + if (_discard_cb) { + _discard_cb(_discard_cb_arg, this); + } + return ERR_OK; +} + +int8_t AsyncClient::_sent(tcp_pcb *pcb, uint16_t len) { + _rx_last_ack = _rx_last_packet = millis(); + if (_sent_cb) { + _sent_cb(_sent_cb_arg, this, len, (_rx_last_packet - _tx_last_packet)); + } + return ERR_OK; +} + +int8_t AsyncClient::_recv(tcp_pcb *pcb, pbuf *pb, int8_t err) { + while (pb != NULL) { + _rx_last_packet = millis(); + // we should not ack before we assimilate the data + _ack_pcb = true; + pbuf *b = pb; + pb = b->next; + b->next = NULL; + if (_pb_cb) { + _pb_cb(_pb_cb_arg, this, b); + } else { + if (_recv_cb) { + _recv_cb(_recv_cb_arg, this, b->payload, b->len); + } + if (!_ack_pcb) { + _rx_ack_len += b->len; + } else if (_pcb) { + _tcp_recved(_pcb, _closed_slot, b->len); + } + } + pbuf_free(b); + } + return ERR_OK; +} + +int8_t AsyncClient::_poll(tcp_pcb *pcb) { + if (!_pcb) { + // log_d("pcb is NULL"); + return ERR_OK; + } + if (pcb != _pcb) { + log_d("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); + return ERR_OK; + } + + uint32_t now = millis(); + + // ACK Timeout + if (_ack_timeout) { + const uint32_t one_day = 86400000; + bool last_tx_is_after_last_ack = (_rx_last_ack - _tx_last_packet + one_day) < one_day; + if (last_tx_is_after_last_ack && (now - _tx_last_packet) >= _ack_timeout) { + log_d("ack timeout %d", pcb->state); + if (_timeout_cb) { + _timeout_cb(_timeout_cb_arg, this, (now - _tx_last_packet)); + } + return ERR_OK; + } + } + // RX Timeout + if (_rx_timeout && (now - _rx_last_packet) >= (_rx_timeout * 1000)) { + log_d("rx timeout %d", pcb->state); + _close(); + return ERR_OK; + } + // Everything is fine + if (_poll_cb) { + _poll_cb(_poll_cb_arg, this); + } + return ERR_OK; +} + +void AsyncClient::_dns_found(struct ip_addr *ipaddr) { +#if ESP_IDF_VERSION_MAJOR < 5 + if (ipaddr && IP_IS_V4(ipaddr)) { + connect(IPAddress(ip_addr_get_ip4_u32(ipaddr)), _connect_port); +#if LWIP_IPV6 + } else if (ipaddr && ipaddr->u_addr.ip6.addr) { + connect(IPv6Address(ipaddr->u_addr.ip6.addr), _connect_port); +#endif +#else + if (ipaddr) { + IPAddress ip; + ip.from_ip_addr_t(ipaddr); + connect(ip, _connect_port); +#endif + } else { + if (_error_cb) { + _error_cb(_error_cb_arg, this, -55); + } + if (_discard_cb) { + _discard_cb(_discard_cb_arg, this); + } + } +} + +/* + * Public Helper Methods + * */ + +bool AsyncClient::free() { + if (!_pcb) { + return true; + } + if (_pcb->state == CLOSED || _pcb->state > ESTABLISHED) { + return true; + } + return false; +} + +size_t AsyncClient::write(const char *data, size_t size, uint8_t apiflags) { + size_t will_send = add(data, size, apiflags); + if (!will_send || !send()) { + return 0; + } + return will_send; +} + +void AsyncClient::setRxTimeout(uint32_t timeout) { + _rx_timeout = timeout; +} + +uint32_t AsyncClient::getRxTimeout() const { + return _rx_timeout; +} + +uint32_t AsyncClient::getAckTimeout() const { + return _ack_timeout; +} + +void AsyncClient::setAckTimeout(uint32_t timeout) { + _ack_timeout = timeout; +} + +void AsyncClient::setNoDelay(bool nodelay) const { + if (!_pcb) { + return; + } + if (nodelay) { + tcp_nagle_disable(_pcb); + } else { + tcp_nagle_enable(_pcb); + } +} + +bool AsyncClient::getNoDelay() { + if (!_pcb) { + return false; + } + return tcp_nagle_disabled(_pcb); +} + +void AsyncClient::setKeepAlive(uint32_t ms, uint8_t cnt) { + if (ms != 0) { + _pcb->so_options |= SOF_KEEPALIVE; // Turn on TCP Keepalive for the given pcb + // Set the time between keepalive messages in milli-seconds + _pcb->keep_idle = ms; + _pcb->keep_intvl = ms; + _pcb->keep_cnt = cnt; // The number of unanswered probes required to force closure of the socket + } else { + _pcb->so_options &= ~SOF_KEEPALIVE; // Turn off TCP Keepalive for the given pcb + } +} + +uint16_t AsyncClient::getMss() const { + if (!_pcb) { + return 0; + } + return tcp_mss(_pcb); +} + +uint32_t AsyncClient::getRemoteAddress() const { + if (!_pcb) { + return 0; + } +#if LWIP_IPV4 && LWIP_IPV6 + return _pcb->remote_ip.u_addr.ip4.addr; +#else + return _pcb->remote_ip.addr; +#endif +} + +#if LWIP_IPV6 +ip6_addr_t AsyncClient::getRemoteAddress6() const { + if (!_pcb) { + ip6_addr_t nulladdr; + ip6_addr_set_zero(&nulladdr); + return nulladdr; + } + return _pcb->remote_ip.u_addr.ip6; +} + +ip6_addr_t AsyncClient::getLocalAddress6() const { + if (!_pcb) { + ip6_addr_t nulladdr; + ip6_addr_set_zero(&nulladdr); + return nulladdr; + } + return _pcb->local_ip.u_addr.ip6; +} +#if ESP_IDF_VERSION_MAJOR < 5 +IPv6Address AsyncClient::remoteIP6() const { + return IPv6Address(getRemoteAddress6().addr); +} + +IPv6Address AsyncClient::localIP6() const { + return IPv6Address(getLocalAddress6().addr); +} +#else +IPAddress AsyncClient::remoteIP6() const { + if (!_pcb) { + return IPAddress(IPType::IPv6); + } + IPAddress ip; + ip.from_ip_addr_t(&(_pcb->remote_ip)); + return ip; +} + +IPAddress AsyncClient::localIP6() const { + if (!_pcb) { + return IPAddress(IPType::IPv6); + } + IPAddress ip; + ip.from_ip_addr_t(&(_pcb->local_ip)); + return ip; +} +#endif +#endif + +uint16_t AsyncClient::getRemotePort() const { + if (!_pcb) { + return 0; + } + return _pcb->remote_port; +} + +uint32_t AsyncClient::getLocalAddress() const { + if (!_pcb) { + return 0; + } +#if LWIP_IPV4 && LWIP_IPV6 + return _pcb->local_ip.u_addr.ip4.addr; +#else + return _pcb->local_ip.addr; +#endif +} + +uint16_t AsyncClient::getLocalPort() const { + if (!_pcb) { + return 0; + } + return _pcb->local_port; +} + +IPAddress AsyncClient::remoteIP() const { +#if ESP_IDF_VERSION_MAJOR < 5 + return IPAddress(getRemoteAddress()); +#else + if (!_pcb) { + return IPAddress(); + } + IPAddress ip; + ip.from_ip_addr_t(&(_pcb->remote_ip)); + return ip; +#endif +} + +uint16_t AsyncClient::remotePort() const { + return getRemotePort(); +} + +IPAddress AsyncClient::localIP() const { +#if ESP_IDF_VERSION_MAJOR < 5 + return IPAddress(getLocalAddress()); +#else + if (!_pcb) { + return IPAddress(); + } + IPAddress ip; + ip.from_ip_addr_t(&(_pcb->local_ip)); + return ip; +#endif +} + +uint16_t AsyncClient::localPort() const { + return getLocalPort(); +} + +uint8_t AsyncClient::state() const { + if (!_pcb) { + return 0; + } + return _pcb->state; +} + +bool AsyncClient::connected() const { + if (!_pcb) { + return false; + } + return _pcb->state == ESTABLISHED; +} + +bool AsyncClient::connecting() const { + if (!_pcb) { + return false; + } + return _pcb->state > CLOSED && _pcb->state < ESTABLISHED; +} + +bool AsyncClient::disconnecting() const { + if (!_pcb) { + return false; + } + return _pcb->state > ESTABLISHED && _pcb->state < TIME_WAIT; +} + +bool AsyncClient::disconnected() const { + if (!_pcb) { + return true; + } + return _pcb->state == CLOSED || _pcb->state == TIME_WAIT; +} + +bool AsyncClient::freeable() const { + if (!_pcb) { + return true; + } + return _pcb->state == CLOSED || _pcb->state > ESTABLISHED; +} + +bool AsyncClient::canSend() const { + return space() > 0; +} + +const char *AsyncClient::errorToString(int8_t error) { + switch (error) { + case ERR_OK: return "OK"; + case ERR_MEM: return "Out of memory error"; + case ERR_BUF: return "Buffer error"; + case ERR_TIMEOUT: return "Timeout"; + case ERR_RTE: return "Routing problem"; + case ERR_INPROGRESS: return "Operation in progress"; + case ERR_VAL: return "Illegal value"; + case ERR_WOULDBLOCK: return "Operation would block"; + case ERR_USE: return "Address in use"; + case ERR_ALREADY: return "Already connected"; + case ERR_CONN: return "Not connected"; + case ERR_IF: return "Low-level netif error"; + case ERR_ABRT: return "Connection aborted"; + case ERR_RST: return "Connection reset"; + case ERR_CLSD: return "Connection closed"; + case ERR_ARG: return "Illegal argument"; + case -55: return "DNS failed"; + default: return "UNKNOWN"; + } +} + +const char *AsyncClient::stateToString() const { + switch (state()) { + case 0: return "Closed"; + case 1: return "Listen"; + case 2: return "SYN Sent"; + case 3: return "SYN Received"; + case 4: return "Established"; + case 5: return "FIN Wait 1"; + case 6: return "FIN Wait 2"; + case 7: return "Close Wait"; + case 8: return "Closing"; + case 9: return "Last ACK"; + case 10: return "Time Wait"; + default: return "UNKNOWN"; + } +} + +/* + * Static Callbacks (LwIP C2C++ interconnect) + * */ + +void AsyncClient::_s_dns_found(const char *name, struct ip_addr *ipaddr, void *arg) { + reinterpret_cast(arg)->_dns_found(ipaddr); +} + +int8_t AsyncClient::_s_poll(void *arg, struct tcp_pcb *pcb) { + return reinterpret_cast(arg)->_poll(pcb); +} + +int8_t AsyncClient::_s_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *pb, int8_t err) { + return reinterpret_cast(arg)->_recv(pcb, pb, err); +} + +int8_t AsyncClient::_s_fin(void *arg, struct tcp_pcb *pcb, int8_t err) { + return reinterpret_cast(arg)->_fin(pcb, err); +} + +int8_t AsyncClient::_s_lwip_fin(void *arg, struct tcp_pcb *pcb, int8_t err) { + return reinterpret_cast(arg)->_lwip_fin(pcb, err); +} + +int8_t AsyncClient::_s_sent(void *arg, struct tcp_pcb *pcb, uint16_t len) { + return reinterpret_cast(arg)->_sent(pcb, len); +} + +void AsyncClient::_s_error(void *arg, int8_t err) { + reinterpret_cast(arg)->_error(err); +} + +int8_t AsyncClient::_s_connected(void *arg, struct tcp_pcb *pcb, int8_t err) { + return reinterpret_cast(arg)->_connected(pcb, err); +} + +/* + Async TCP Server + */ + +AsyncServer::AsyncServer(IPAddress addr, uint16_t port) + : _port(port) +#if ESP_IDF_VERSION_MAJOR < 5 + , + _bind4(true), _bind6(false) +#else + , + _bind4(addr.type() != IPType::IPv6), _bind6(addr.type() == IPType::IPv6) +#endif + , + _addr(addr), _noDelay(false), _pcb(0), _connect_cb(0), _connect_cb_arg(0) { +} + +#if ESP_IDF_VERSION_MAJOR < 5 +AsyncServer::AsyncServer(IPv6Address addr, uint16_t port) + : _port(port), _bind4(false), _bind6(true), _addr6(addr), _noDelay(false), _pcb(0), _connect_cb(0), _connect_cb_arg(0) {} +#endif + +AsyncServer::AsyncServer(uint16_t port) + : _port(port), _bind4(true), _bind6(false), _addr((uint32_t)IPADDR_ANY) +#if ESP_IDF_VERSION_MAJOR < 5 + , + _addr6() +#endif + , + _noDelay(false), _pcb(0), _connect_cb(0), _connect_cb_arg(0) { +} + +AsyncServer::~AsyncServer() { + end(); +} + +void AsyncServer::onClient(AcConnectHandler cb, void *arg) { + _connect_cb = cb; + _connect_cb_arg = arg; +} + +void AsyncServer::begin() { + if (_pcb) { + return; + } + + if (!_start_async_task()) { + log_e("failed to start task"); + return; + } + int8_t err; + TCP_MUTEX_LOCK(); + _pcb = tcp_new_ip_type(_bind4 && _bind6 ? IPADDR_TYPE_ANY : (_bind6 ? IPADDR_TYPE_V6 : IPADDR_TYPE_V4)); + TCP_MUTEX_UNLOCK(); + if (!_pcb) { + log_e("_pcb == NULL"); + return; + } + + ip_addr_t local_addr; +#if ESP_IDF_VERSION_MAJOR < 5 + if (_bind6) { // _bind6 && _bind4 both at the same time is not supported on Arduino 2 in this lib API + local_addr.type = IPADDR_TYPE_V6; + memcpy(local_addr.u_addr.ip6.addr, static_cast(_addr6), sizeof(uint32_t) * 4); + } else { + local_addr.type = IPADDR_TYPE_V4; + local_addr.u_addr.ip4.addr = _addr; + } +#else + _addr.to_ip_addr_t(&local_addr); +#endif + err = _tcp_bind(_pcb, &local_addr, _port); + + if (err != ERR_OK) { + _tcp_close(_pcb, -1); + _pcb = NULL; + log_e("bind error: %d", err); + return; + } + + static uint8_t backlog = 5; + _pcb = _tcp_listen_with_backlog(_pcb, backlog); + if (!_pcb) { + log_e("listen_pcb == NULL"); + return; + } + TCP_MUTEX_LOCK(); + tcp_arg(_pcb, (void *)this); + tcp_accept(_pcb, &_s_accept); + TCP_MUTEX_UNLOCK(); +} + +void AsyncServer::end() { + if (_pcb) { + TCP_MUTEX_LOCK(); + tcp_arg(_pcb, NULL); + tcp_accept(_pcb, NULL); + if (tcp_close(_pcb) != ERR_OK) { + TCP_MUTEX_UNLOCK(); + _tcp_abort(_pcb, -1); + } else { + TCP_MUTEX_UNLOCK(); + } + _pcb = NULL; + } +} + +// runs on LwIP thread +int8_t AsyncServer::_accept(tcp_pcb *pcb, int8_t err) { + if (!pcb) { + log_e("_accept failed: pcb is NULL"); + return ERR_ABRT; + } + if (_connect_cb) { + AsyncClient *c = new (std::nothrow) AsyncClient(pcb); + if (c && c->pcb()) { + c->setNoDelay(_noDelay); + if (_tcp_accept(this, c) == ERR_OK) { + return ERR_OK; // success + } + // Couldn't allocate accept event + // We can't let the client object call in to close, as we're on the LWIP thread; it could deadlock trying to RPC to itself + c->_pcb = nullptr; + tcp_abort(pcb); + log_e("_accept failed: couldn't accept client"); + return ERR_ABRT; + } + if (c) { + // Couldn't complete setup + // pcb has already been aborted + delete c; + pcb = nullptr; + log_e("_accept failed: couldn't complete setup"); + return ERR_ABRT; + } + log_e("_accept failed: couldn't allocate client"); + } else { + log_e("_accept failed: no onConnect callback"); + } + tcp_abort(pcb); + return ERR_OK; +} + +int8_t AsyncServer::_accepted(AsyncClient *client) { + if (_connect_cb) { + _connect_cb(_connect_cb_arg, client); + } + return ERR_OK; +} + +void AsyncServer::setNoDelay(bool nodelay) { + _noDelay = nodelay; +} + +bool AsyncServer::getNoDelay() const { + return _noDelay; +} + +uint8_t AsyncServer::status() const { + if (!_pcb) { + return 0; + } + return _pcb->state; +} + +int8_t AsyncServer::_s_accept(void *arg, tcp_pcb *pcb, int8_t err) { + return reinterpret_cast(arg)->_accept(pcb, err); +} + +int8_t AsyncServer::_s_accepted(void *arg, AsyncClient *client) { + return reinterpret_cast(arg)->_accepted(client); +} diff --git a/watering/lib/AsyncTCP/src/AsyncTCP.h b/watering/lib/AsyncTCP/src/AsyncTCP.h new file mode 100644 index 0000000..7715ec3 --- /dev/null +++ b/watering/lib/AsyncTCP/src/AsyncTCP.h @@ -0,0 +1,335 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef ASYNCTCP_H_ +#define ASYNCTCP_H_ + +#include "AsyncTCPVersion.h" +#define ASYNCTCP_FORK_ESP32Async + +#include "IPAddress.h" +#if ESP_IDF_VERSION_MAJOR < 5 +#include "IPv6Address.h" +#endif +#include "lwip/ip6_addr.h" +#include "lwip/ip_addr.h" +#include + +#ifndef LIBRETINY +#include "sdkconfig.h" +extern "C" { +#include "freertos/semphr.h" +#include "lwip/pbuf.h" +} +#else +extern "C" { +#include +#include +} +#define CONFIG_ASYNC_TCP_RUNNING_CORE -1 // any available core +#endif + +// If core is not defined, then we are running in Arduino or PIO +#ifndef CONFIG_ASYNC_TCP_RUNNING_CORE +#define CONFIG_ASYNC_TCP_RUNNING_CORE -1 // any available core +#endif + +// guard AsyncTCP task with watchdog +#ifndef CONFIG_ASYNC_TCP_USE_WDT +#define CONFIG_ASYNC_TCP_USE_WDT 1 +#endif + +#ifndef CONFIG_ASYNC_TCP_STACK_SIZE +#define CONFIG_ASYNC_TCP_STACK_SIZE 8192 * 2 +#endif + +#ifndef CONFIG_ASYNC_TCP_PRIORITY +#define CONFIG_ASYNC_TCP_PRIORITY 10 +#endif + +#ifndef CONFIG_ASYNC_TCP_QUEUE_SIZE +#define CONFIG_ASYNC_TCP_QUEUE_SIZE 64 +#endif + +#ifndef CONFIG_ASYNC_TCP_MAX_ACK_TIME +#define CONFIG_ASYNC_TCP_MAX_ACK_TIME 5000 +#endif + +class AsyncClient; + +#define ASYNC_WRITE_FLAG_COPY 0x01 // will allocate new buffer to hold the data while sending (else will hold reference to the data given) +#define ASYNC_WRITE_FLAG_MORE 0x02 // will not send PSH flag, meaning that there should be more data to be sent before the application should react. + +typedef std::function AcConnectHandler; +typedef std::function AcAckHandler; +typedef std::function AcErrorHandler; +typedef std::function AcDataHandler; +typedef std::function AcPacketHandler; +typedef std::function AcTimeoutHandler; + +struct tcp_pcb; +struct ip_addr; + +class AsyncClient { +public: + AsyncClient(tcp_pcb *pcb = 0); + ~AsyncClient(); + + AsyncClient &operator=(const AsyncClient &other); + AsyncClient &operator+=(const AsyncClient &other); + + bool operator==(const AsyncClient &other) const; + + bool operator!=(const AsyncClient &other) const { + return !(*this == other); + } + bool connect(const IPAddress &ip, uint16_t port); +#if ESP_IDF_VERSION_MAJOR < 5 + bool connect(const IPv6Address &ip, uint16_t port); +#endif + bool connect(const char *host, uint16_t port); + /** + * @brief close connection + * + * @param now - ignored + */ + void close(bool now = false); + // same as close() + void stop() { + close(false); + }; + int8_t abort(); + bool free(); + + // ack is not pending + bool canSend() const; + // TCP buffer space available + size_t space() const; + + /** + * @brief add data to be send (but do not send yet) + * @note add() would call lwip's tcp_write() + By default apiflags=ASYNC_WRITE_FLAG_COPY + You could try to use apiflags with this flag unset to pass data by reference and avoid copy to socket buffer, + but looks like it does not work for Arduino's lwip in ESP32/IDF at least + it is enforced in https://github.com/espressif/esp-lwip/blob/0606eed9d8b98a797514fdf6eabb4daf1c8c8cd9/src/core/tcp_out.c#L422C5-L422C30 + if LWIP_NETIF_TX_SINGLE_PBUF is set, and it is set indeed in IDF + https://github.com/espressif/esp-idf/blob/a0f798cfc4bbd624aab52b2c194d219e242d80c1/components/lwip/port/include/lwipopts.h#L744 + * + * @param data + * @param size + * @param apiflags + * @return size_t amount of data that has been copied + */ + size_t add(const char *data, size_t size, uint8_t apiflags = ASYNC_WRITE_FLAG_COPY); + + /** + * @brief send data previously add()'ed + * + * @return true on success + * @return false on error + */ + bool send(); + + /** + * @brief add and enqueue data for sending + * @note it is same as add() + send() + * @note only make sense when canSend() == true + * + * @param data + * @param size + * @param apiflags + * @return size_t + */ + size_t write(const char *data, size_t size, uint8_t apiflags = ASYNC_WRITE_FLAG_COPY); + + /** + * @brief add and enqueue data for sending + * @note treats data as null-terminated string + * + * @param data + * @return size_t + */ + size_t write(const char *data) { + return data == NULL ? 0 : write(data, strlen(data)); + }; + + uint8_t state() const; + bool connecting() const; + bool connected() const; + bool disconnecting() const; + bool disconnected() const; + + // disconnected or disconnecting + bool freeable() const; + + uint16_t getMss() const; + + uint32_t getRxTimeout() const; + // no RX data timeout for the connection in seconds + void setRxTimeout(uint32_t timeout); + + uint32_t getAckTimeout() const; + // no ACK timeout for the last sent packet in milliseconds + void setAckTimeout(uint32_t timeout); + + void setNoDelay(bool nodelay) const; + bool getNoDelay(); + + void setKeepAlive(uint32_t ms, uint8_t cnt); + + uint32_t getRemoteAddress() const; + uint16_t getRemotePort() const; + uint32_t getLocalAddress() const; + uint16_t getLocalPort() const; +#if LWIP_IPV6 + ip6_addr_t getRemoteAddress6() const; + ip6_addr_t getLocalAddress6() const; +#if ESP_IDF_VERSION_MAJOR < 5 + IPv6Address remoteIP6() const; + IPv6Address localIP6() const; +#else + IPAddress remoteIP6() const; + IPAddress localIP6() const; +#endif +#endif + + // compatibility + IPAddress remoteIP() const; + uint16_t remotePort() const; + IPAddress localIP() const; + uint16_t localPort() const; + + // set callback - on successful connect + void onConnect(AcConnectHandler cb, void *arg = 0); + // set callback - disconnected + void onDisconnect(AcConnectHandler cb, void *arg = 0); + // set callback - ack received + void onAck(AcAckHandler cb, void *arg = 0); + // set callback - unsuccessful connect or error + void onError(AcErrorHandler cb, void *arg = 0); + // set callback - data received (called if onPacket is not used) + void onData(AcDataHandler cb, void *arg = 0); + // set callback - data received + // !!! You MUST call ackPacket() or free the pbuf yourself to prevent memory leaks + void onPacket(AcPacketHandler cb, void *arg = 0); + // set callback - ack timeout + void onTimeout(AcTimeoutHandler cb, void *arg = 0); + // set callback - every 125ms when connected + void onPoll(AcConnectHandler cb, void *arg = 0); + + // ack pbuf from onPacket + void ackPacket(struct pbuf *pb); + // ack data that you have not acked using the method below + size_t ack(size_t len); + // will not ack the current packet. Call from onData + void ackLater() { + _ack_pcb = false; + } + + static const char *errorToString(int8_t error); + const char *stateToString() const; + + // internal callbacks - Do NOT call any of the functions below in user code! + static int8_t _s_poll(void *arg, struct tcp_pcb *tpcb); + static int8_t _s_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *pb, int8_t err); + static int8_t _s_fin(void *arg, struct tcp_pcb *tpcb, int8_t err); + static int8_t _s_lwip_fin(void *arg, struct tcp_pcb *tpcb, int8_t err); + static void _s_error(void *arg, int8_t err); + static int8_t _s_sent(void *arg, struct tcp_pcb *tpcb, uint16_t len); + static int8_t _s_connected(void *arg, struct tcp_pcb *tpcb, int8_t err); + static void _s_dns_found(const char *name, struct ip_addr *ipaddr, void *arg); + static void _tcp_error(void *arg, int8_t err); + + int8_t _recv(tcp_pcb *pcb, pbuf *pb, int8_t err); + tcp_pcb *pcb() { + return _pcb; + } + +protected: + friend class AsyncServer; + + bool _connect(ip_addr_t addr, uint16_t port); + + tcp_pcb *_pcb; + int8_t _closed_slot; + + AcConnectHandler _connect_cb; + void *_connect_cb_arg; + AcConnectHandler _discard_cb; + void *_discard_cb_arg; + AcAckHandler _sent_cb; + void *_sent_cb_arg; + AcErrorHandler _error_cb; + void *_error_cb_arg; + AcDataHandler _recv_cb; + void *_recv_cb_arg; + AcPacketHandler _pb_cb; + void *_pb_cb_arg; + AcTimeoutHandler _timeout_cb; + void *_timeout_cb_arg; + AcConnectHandler _poll_cb; + void *_poll_cb_arg; + + bool _ack_pcb; + uint32_t _tx_last_packet; + uint32_t _rx_ack_len; + uint32_t _rx_last_packet; + uint32_t _rx_timeout; + uint32_t _rx_last_ack; + uint32_t _ack_timeout; + uint16_t _connect_port; + + int8_t _close(); + void _free_closed_slot(); + bool _allocate_closed_slot(); + int8_t _connected(tcp_pcb *pcb, int8_t err); + void _error(int8_t err); + int8_t _poll(tcp_pcb *pcb); + int8_t _sent(tcp_pcb *pcb, uint16_t len); + int8_t _fin(tcp_pcb *pcb, int8_t err); + int8_t _lwip_fin(tcp_pcb *pcb, int8_t err); + void _dns_found(struct ip_addr *ipaddr); + +public: + AsyncClient *prev; + AsyncClient *next; +}; + +class AsyncServer { +public: + AsyncServer(IPAddress addr, uint16_t port); +#if ESP_IDF_VERSION_MAJOR < 5 + AsyncServer(IPv6Address addr, uint16_t port); +#endif + AsyncServer(uint16_t port); + ~AsyncServer(); + void onClient(AcConnectHandler cb, void *arg); + void begin(); + void end(); + void setNoDelay(bool nodelay); + bool getNoDelay() const; + uint8_t status() const; + + // Do not use any of the functions below! + static int8_t _s_accept(void *arg, tcp_pcb *newpcb, int8_t err); + static int8_t _s_accepted(void *arg, AsyncClient *client); + +protected: + uint16_t _port; + bool _bind4 = false; + bool _bind6 = false; + IPAddress _addr; +#if ESP_IDF_VERSION_MAJOR < 5 + IPv6Address _addr6; +#endif + bool _noDelay; + tcp_pcb *_pcb; + AcConnectHandler _connect_cb; + void *_connect_cb_arg; + + int8_t _accept(tcp_pcb *newpcb, int8_t err); + int8_t _accepted(AsyncClient *client); +}; + +#endif /* ASYNCTCP_H_ */ diff --git a/watering/lib/AsyncTCP/src/AsyncTCPVersion.h b/watering/lib/AsyncTCP/src/AsyncTCPVersion.h new file mode 100644 index 0000000..cb5a691 --- /dev/null +++ b/watering/lib/AsyncTCP/src/AsyncTCPVersion.h @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/** Major version number (X.x.x) */ +#define ASYNCTCP_VERSION_MAJOR 3 +/** Minor version number (x.X.x) */ +#define ASYNCTCP_VERSION_MINOR 3 +/** Patch version number (x.x.X) */ +#define ASYNCTCP_VERSION_PATCH 8 + +/** + * Macro to convert version number into an integer + * + * To be used in comparisons, such as ASYNCTCP_VERSION >= ASYNCTCP_VERSION_VAL(2, 0, 0) + */ +#define ASYNCTCP_VERSION_VAL(major, minor, patch) ((major << 16) | (minor << 8) | (patch)) + +/** + * Current version, as an integer + * + * To be used in comparisons, such as ASYNCTCP_VERSION_NUM >= ASYNCTCP_VERSION_VAL(2, 0, 0) + */ +#define ASYNCTCP_VERSION_NUM ASYNCTCP_VERSION_VAL(ASYNCTCP_VERSION_MAJOR, ASYNCTCP_VERSION_MINOR, ASYNCTCP_VERSION_PATCH) + +/** + * Current version, as string + */ +#define df2xstr(s) #s +#define df2str(s) df2xstr(s) +#define ASYNCTCP_VERSION df2str(ASYNCTCP_VERSION_MAJOR) "." df2str(ASYNCTCP_VERSION_MINOR) "." df2str(ASYNCTCP_VERSION_PATCH) + +#ifdef __cplusplus +} +#endif diff --git a/watering/lib/ESPAsyncWebServer/.clang-format b/watering/lib/ESPAsyncWebServer/.clang-format new file mode 100644 index 0000000..8f47348 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/.clang-format @@ -0,0 +1,246 @@ +# Clang format version: 18.1.3 +--- +BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: BlockIndent +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: true +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: true + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Always +BreakAfterJavaFieldAnnotations: false +BreakArrays: false +BreakBeforeBinaryOperators: NonAssignment +BreakBeforeBraces: Custom +BreakBeforeConceptDeclarations: Always +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +ColumnLimit: 160 +CommentPragmas: "" +CompactNamespaces: false +ConstructorInitializerIndentWidth: 2 +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: ^"(llvm|llvm-c|clang|clang-c)/ + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: ^(<|"(gtest|gmock|isl|json)/) + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: .* + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: "" +IncludeIsMainSourceRegex: "" +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: NoIndent +IndentGotoLabels: false +IndentPPDirectives: None +IndentRequiresClause: false +IndentWidth: 2 +IndentWrappedFunctionNames: true +InsertBraces: true +InsertNewlineAtEOF: true +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtEOF: false +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: Signature +Language: Cpp +LineEnding: LF +MacroBlockBegin: "" +MacroBlockEnd: "" +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PPIndentWidth: -1 +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: false +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: Never +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDeclarationName: false + AfterFunctionDefinitionName: false + AfterIfMacros: true + AfterOverloadedOperator: true + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: Never +SpacesInContainerLiterals: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InConditionalStatements: false + InCStyleCasts: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Auto +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 2 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +BracedInitializerIndentWidth: 2 diff --git a/watering/lib/ESPAsyncWebServer/.codespellrc b/watering/lib/ESPAsyncWebServer/.codespellrc new file mode 100644 index 0000000..d26ee41 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/.codespellrc @@ -0,0 +1,8 @@ +[codespell] +# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/spell-check/.codespellrc +# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here: +ignore-words-list = ba,licence,varius +skip = ./.git,./.licenses,__pycache__,.clang-format,.codespellrc,.editorconfig,.flake8,.prettierignore,.yamllint.yml,.gitignore +builtin = clear,informal,en-GB_to_en-US +check-filenames = +check-hidden = diff --git a/watering/lib/ESPAsyncWebServer/.editorconfig b/watering/lib/ESPAsyncWebServer/.editorconfig new file mode 100644 index 0000000..e22936c --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/.editorconfig @@ -0,0 +1,60 @@ +# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/general/.editorconfig +# See: https://editorconfig.org/ +# The formatting style defined in this file is the official standardized style to be used in all Arduino Tooling +# projects and should not be modified. +# Note: indent style for each file type is defined even when it matches the universal config in order to make it clear +# that this type has an official style. + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 2 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{adoc,asc,asciidoc}] +indent_size = 2 +indent_style = space + +[*.{bash,sh}] +indent_size = 4 +indent_style = space + +[*.{c,cc,cp,cpp,cxx,h,hh,hpp,hxx,ii,inl,ino,ixx,pde,tpl,tpp,txx}] +indent_size = 2 +indent_style = space + +[*.{go,mod}] +indent_style = tab + +[*.java] +indent_size = 2 +indent_style = space + +[*.{js,jsx,json,jsonc,json5,ts,tsx}] +indent_size = 2 +indent_style = space + +[*.{md,mdx,mkdn,mdown,markdown}] +indent_size = unset +indent_style = space + +[*.proto] +indent_size = 2 +indent_style = space + +[*.py] +indent_size = 4 +indent_style = space + +[*.svg] +indent_size = 2 +indent_style = space + +[*.{yaml,yml}] +indent_size = 2 +indent_style = space + +[{.gitconfig,.gitmodules}] +indent_style = tab diff --git a/watering/lib/ESPAsyncWebServer/.gitignore b/watering/lib/ESPAsyncWebServer/.gitignore new file mode 100644 index 0000000..1efbc8e --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +.lh +/.pio +/.vscode +/logs diff --git a/watering/lib/ESPAsyncWebServer/.gitpod.Dockerfile b/watering/lib/ESPAsyncWebServer/.gitpod.Dockerfile new file mode 100644 index 0000000..29eeb43 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/.gitpod.Dockerfile @@ -0,0 +1,2 @@ +FROM gitpod/workspace-python-3.11 +USER gitpod diff --git a/watering/lib/ESPAsyncWebServer/.gitpod.yml b/watering/lib/ESPAsyncWebServer/.gitpod.yml new file mode 100644 index 0000000..2f8a443 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/.gitpod.yml @@ -0,0 +1,9 @@ +tasks: + - command: pip install --upgrade pip && pip install -U platformio && platformio run + +image: + file: .gitpod.Dockerfile + +vscode: + extensions: + - shardulm94.trailing-spaces diff --git a/watering/lib/ESPAsyncWebServer/.pre-commit-config.yaml b/watering/lib/ESPAsyncWebServer/.pre-commit-config.yaml new file mode 100644 index 0000000..eb2d62e --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/.pre-commit-config.yaml @@ -0,0 +1,42 @@ +exclude: | + (?x)( + ^\.github\/| + LICENSE$ + ) + +default_language_version: + # force all unspecified python hooks to run python3 + python: python3 + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: "v5.0.0" + hooks: + # Generic checks + - id: check-case-conflict + - id: check-symlinks + - id: debug-statements + - id: destroyed-symlinks + - id: detect-private-key + - id: end-of-file-fixer + exclude: ^.*\.(bin|BIN)$ + - id: mixed-line-ending + args: [--fix=lf] + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + exclude: ^platformio\.ini$ + + - repo: https://github.com/codespell-project/codespell + rev: "v2.3.0" + hooks: + # Spell checking + - id: codespell + exclude: ^.*\.(svd|SVD)$ + + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: "v18.1.3" + hooks: + # C/C++ formatting + - id: clang-format + types_or: [c, c++] + exclude: ^.*\/build_opt\.h$ diff --git a/watering/lib/ESPAsyncWebServer/CMakeLists.txt b/watering/lib/ESPAsyncWebServer/CMakeLists.txt new file mode 100644 index 0000000..ea7be08 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/CMakeLists.txt @@ -0,0 +1,9 @@ +set(COMPONENT_SRCDIRS + "src" +) + +set(COMPONENT_ADD_INCLUDEDIRS + "src" +) + +register_component() diff --git a/watering/lib/ESPAsyncWebServer/CODE_OF_CONDUCT.md b/watering/lib/ESPAsyncWebServer/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..4fcdc2f --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/CODE_OF_CONDUCT.md @@ -0,0 +1,129 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socioeconomic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +https://sidweb.nl/cms3/en/contact. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/watering/lib/ESPAsyncWebServer/LICENSE b/watering/lib/ESPAsyncWebServer/LICENSE new file mode 100644 index 0000000..153d416 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/watering/lib/ESPAsyncWebServer/README.md b/watering/lib/ESPAsyncWebServer/README.md new file mode 100644 index 0000000..9bb7575 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/README.md @@ -0,0 +1,141 @@ +![https://avatars.githubusercontent.com/u/195753706?s=96&v=4](https://avatars.githubusercontent.com/u/195753706?s=96&v=4) + +# ESPAsyncWebServer + +[![Latest Release](https://img.shields.io/github/release/ESP32Async/ESPAsyncWebServer.svg)](https://GitHub.com/ESP32Async/ESPAsyncWebServer/releases/) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/ESP32Async/library/ESPAsyncWebServer.svg)](https://registry.platformio.org/libraries/ESP32Async/ESPAsyncWebServer) + +[![License: LGPL 3.0](https://img.shields.io/badge/License-LGPL%203.0-yellow.svg)](https://opensource.org/license/lgpl-3-0/) +[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](code_of_conduct.md) + +[![GitHub latest commit](https://badgen.net/github/last-commit/ESP32Async/ESPAsyncWebServer)](https://GitHub.com/ESP32Async/ESPAsyncWebServer/commit/) +[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/ESP32Async/ESPAsyncWebServer) + +[![ESP32Async Discord Server](https://img.shields.io/badge/Discord-ESP32Async-blue?logo=discord)](https://discord.gg/X7zpGdyUcY) + +[![Documentation](https://img.shields.io/badge/Wiki-ESPAsyncWebServer-blue?logo=github)](https://github.com/ESP32Async/ESPAsyncWebServer/wiki) + +## Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266, RP2040 and RP2350 + +Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc. + +- [Documentation](#documentation) +- [How to install](#how-to-install) +- [Dependencies](#dependencies) + - [ESP32 / pioarduino](#esp32--pioarduino) + - [ESP8266 / pioarduino](#esp8266--pioarduino) + - [Unofficial dependencies](#unofficial-dependencies) + +## Documentation + +The complete [project documentation](https://github.com/ESP32Async/ESPAsyncWebServer/wiki) is available in the Wiki section. + +## How to install + +The library can be downloaded from the releases page at [https://github.com/ESP32Async/ESPAsyncWebServer/releases](https://github.com/ESP32Async/ESPAsyncWebServer/releases). + +It is also deployed in these registries: + +- Arduino Library Registry: [https://github.com/arduino/library-registry](https://github.com/arduino/library-registry) + +- ESP Component Registry [https://components.espressif.com/components/esp32async/espasyncwebserver](https://components.espressif.com/components/esp32async/espasyncwebserver) + +- PlatformIO Registry: [https://registry.platformio.org/libraries/esp32async/ESPAsyncWebServer](https://registry.platformio.org/libraries/esp32async/ESPAsyncWebServer) + + - Use: `lib_deps=ESP32Async/ESPAsyncWebServer` to point to latest version + - Use: `lib_deps=ESP32Async/ESPAsyncWebServer @ ^` to point to latest version with the same major version + - Use: `lib_deps=ESP32Async/ESPAsyncWebServer @ ` to always point to the same version (reproductible build) + +## Dependencies + +### ESP32 / pioarduino + +```ini +[env:stable] +platform = https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip +lib_compat_mode = strict +lib_ldf_mode = chain +lib_deps = + ESP32Async/AsyncTCP + ESP32Async/ESPAsyncWebServer +``` + +### ESP8266 / pioarduino + +```ini +[env:stable] +platform = espressif8266 +lib_compat_mode = strict +lib_ldf_mode = chain +lib_deps = + ESP32Async/ESPAsyncTCP + ESP32Async/ESPAsyncWebServer +``` + +### Unofficial dependencies + +**AsyncTCPSock** + +AsyncTCPSock can be used instead of AsyncTCP by excluding AsyncTCP from the library dependencies and adding AsyncTCPSock instead: + +```ini +lib_compat_mode = strict +lib_ldf_mode = chain +lib_deps = + https://github.com/ESP32Async/AsyncTCPSock/archive/refs/tags/v1.0.3-dev.zip + ESP32Async/ESPAsyncWebServer +lib_ignore = + AsyncTCP + ESP32Async/AsyncTCP +``` + +**RPAsyncTCP** + +RPAsyncTCP replaces AsyncTCP to provide support for RP2040(+WiFi) and RP2350(+WiFi) boards. For example - Raspberry Pi Pico W and Raspberry Pi Pico 2W. + +```ini +lib_compat_mode = strict +lib_ldf_mode = chain +platform = https://github.com/maxgerhardt/platform-raspberrypi.git +board = rpipicow +board_build.core = earlephilhower +lib_deps = + ayushsharma82/RPAsyncTCP@^1.3.2 + ESP32Async/ESPAsyncWebServer +lib_ignore = + lwIP_ESPHost +build_flags = ${env.build_flags} + -Wno-missing-field-initializers +``` + +## Important recommendations for build options + +Most of the crashes are caused by improper use or configuration of the AsyncTCP library used for the project. +Here are some recommendations to avoid them and build-time flags you can change. + +`CONFIG_ASYNC_TCP_MAX_ACK_TIME` - defines a timeout for TCP connection to be considered alive when waiting for data. +In some bad network conditions you might consider increasing it. + +`CONFIG_ASYNC_TCP_QUEUE_SIZE` - defines the length of the queue for events related to connections handling. +Both the server and AsyncTCP library were optimized to control the queue automatically. Do NOT try blindly increasing the queue size, it does not help you in a way you might think it is. If you receive debug messages about queue throttling, try to optimize your server callbacks code to execute as fast as possible. +Read #165 thread, it might give you some hints. + +`CONFIG_ASYNC_TCP_RUNNING_CORE` - CPU core thread affinity that runs the queue events handling and executes server callbacks. Default is ANY core, so it means that for dualcore SoCs both cores could handle server activities. If your server's code is too heavy and unoptimized or you see that sometimes +server might affect other network activities, you might consider to bind it to the same core that runs Arduino code (1) to minimize affect on radio part. Otherwise you can leave the default to let RTOS decide where to run the thread based on priority + +`CONFIG_ASYNC_TCP_STACK_SIZE` - stack size for the thread that runs sever events and callbacks. Default is 16k that is a way too much waste for well-defined short async code or simple static file handling. You might want to cosider reducing it to 4-8k to same RAM usage. If you do not know what this is or not sure about your callback code demands - leave it as default, should be enough even for very hungry callbacks in most cases. + +> [!NOTE] +> This relates to ESP32 only, ESP8266 uses different ESPAsyncTCP lib that does not has this build options + +I personally use the following configuration in my projects: + +```c++ + -D CONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 // (keep default) + -D CONFIG_ASYNC_TCP_PRIORITY=10 // (keep default) + -D CONFIG_ASYNC_TCP_QUEUE_SIZE=64 // (keep default) + -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 // force async_tcp task to be on same core as Arduino app (default is any core) + -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 // reduce the stack size (default is 16K) +``` + +If you need to serve chunk requests with a really low buffer (which should be avoided), you can set `-D ASYNCWEBSERVER_USE_CHUNK_INFLIGHT=0` to disable the in-flight control. diff --git a/watering/lib/ESPAsyncWebServer/data/README.md b/watering/lib/ESPAsyncWebServer/data/README.md new file mode 100644 index 0000000..96a2ee4 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/data/README.md @@ -0,0 +1,48 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod +rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper +arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit +accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. +Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo +dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod +rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper +arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit +accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. +Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo +dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod +rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper +arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit +accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. +Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo +dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod +rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper +arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit +accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. +Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo +dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod +rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper +arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit +accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. +Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo +dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod +rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper +arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit +accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. +Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo +dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod +rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper +arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit +accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. +Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo +dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod +rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper +arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit +accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. +Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo +dapibus elit, id varius sem dui id lacus. diff --git a/watering/lib/ESPAsyncWebServer/docs/logo.png b/watering/lib/ESPAsyncWebServer/docs/logo.png new file mode 100644 index 0000000..1995c88 Binary files /dev/null and b/watering/lib/ESPAsyncWebServer/docs/logo.png differ diff --git a/watering/lib/ESPAsyncWebServer/docs/logo.webp b/watering/lib/ESPAsyncWebServer/docs/logo.webp new file mode 100644 index 0000000..c70b842 Binary files /dev/null and b/watering/lib/ESPAsyncWebServer/docs/logo.webp differ diff --git a/watering/lib/ESPAsyncWebServer/docs/perf-c10-asynctcpsock.png b/watering/lib/ESPAsyncWebServer/docs/perf-c10-asynctcpsock.png new file mode 100644 index 0000000..b1d4d7a Binary files /dev/null and b/watering/lib/ESPAsyncWebServer/docs/perf-c10-asynctcpsock.png differ diff --git a/watering/lib/ESPAsyncWebServer/docs/perf-c10.png b/watering/lib/ESPAsyncWebServer/docs/perf-c10.png new file mode 100644 index 0000000..e63e71a Binary files /dev/null and b/watering/lib/ESPAsyncWebServer/docs/perf-c10.png differ diff --git a/watering/lib/ESPAsyncWebServer/examples/AsyncResponseStream/AsyncResponseStream.ino b/watering/lib/ESPAsyncWebServer/examples/AsyncResponseStream/AsyncResponseStream.ino new file mode 100644 index 0000000..62fa799 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/AsyncResponseStream/AsyncResponseStream.ino @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // Shows how to use AsyncResponseStream. + // The internal buffer will be allocated and data appended to it, + // until the response is sent, then this buffer is read and committed on the network. + // + // curl -v http://192.168.4.1/ + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + AsyncResponseStream *response = request->beginResponseStream("plain/text", 40 * 1024); + for (int i = 0; i < 32 * 1024; i++) { + response->write('a'); + } + request->send(response); + }); + + server.begin(); +} + +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Auth/Auth.ino b/watering/lib/ESPAsyncWebServer/examples/Auth/Auth.ino new file mode 100644 index 0000000..c3751e0 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Auth/Auth.ino @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Authentication and authorization middlewares +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +// basicAuth +static AsyncAuthenticationMiddleware basicAuth; +static AsyncAuthenticationMiddleware basicAuthHash; + +// simple digest authentication +static AsyncAuthenticationMiddleware digestAuth; +static AsyncAuthenticationMiddleware digestAuthHash; + +// complex authentication which adds request attributes for the next middlewares and handler +static AsyncMiddlewareFunction complexAuth([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + if (!request->authenticate("user", "password")) { + return request->requestAuthentication(); + } + + // add attributes to the request for the next middlewares and handler + request->setAttribute("user", "Mathieu"); + request->setAttribute("role", "staff"); + if (request->hasParam("token")) { + request->setAttribute("token", request->getParam("token")->value().c_str()); + } + + next(); +}); + +static AsyncAuthorizationMiddleware authz([](AsyncWebServerRequest *request) { + return request->getAttribute("token") == "123"; +}); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // basic authentication + basicAuth.setUsername("admin"); + basicAuth.setPassword("admin"); + basicAuth.setRealm("MyApp"); + basicAuth.setAuthFailureMessage("Authentication failed"); + basicAuth.setAuthType(AsyncAuthType::AUTH_BASIC); + basicAuth.generateHash(); // precompute hash (optional but recommended) + + // basic authentication with hash + basicAuthHash.setUsername("admin"); + basicAuthHash.setPasswordHash("YWRtaW46YWRtaW4="); // BASE64(admin:admin) + basicAuthHash.setRealm("MyApp"); + basicAuthHash.setAuthFailureMessage("Authentication failed"); + basicAuthHash.setAuthType(AsyncAuthType::AUTH_BASIC); + + // digest authentication + digestAuth.setUsername("admin"); + digestAuth.setPassword("admin"); + digestAuth.setRealm("MyApp"); + digestAuth.setAuthFailureMessage("Authentication failed"); + digestAuth.setAuthType(AsyncAuthType::AUTH_DIGEST); + digestAuth.generateHash(); // precompute hash (optional but recommended) + + // digest authentication with hash + digestAuthHash.setUsername("admin"); + digestAuthHash.setPasswordHash("f499b71f9a36d838b79268e145e132f7"); // MD5(user:realm:pass) + digestAuthHash.setRealm("MyApp"); + digestAuthHash.setAuthFailureMessage("Authentication failed"); + digestAuthHash.setAuthType(AsyncAuthType::AUTH_DIGEST); + + // basic authentication method + // curl -v -u admin:admin http://192.168.4.1/auth-basic + server + .on( + "/auth-basic", HTTP_GET, + [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + } + ) + .addMiddleware(&basicAuth); + + // basic authentication method with hash + // curl -v -u admin:admin http://192.168.4.1/auth-basic-hash + server + .on( + "/auth-basic-hash", HTTP_GET, + [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + } + ) + .addMiddleware(&basicAuthHash); + + // digest authentication + // curl -v -u admin:admin --digest http://192.168.4.1/auth-digest + server + .on( + "/auth-digest", HTTP_GET, + [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + } + ) + .addMiddleware(&digestAuth); + + // digest authentication with hash + // curl -v -u admin:admin --digest http://192.168.4.1/auth-digest-hash + server + .on( + "/auth-digest-hash", HTTP_GET, + [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + } + ) + .addMiddleware(&digestAuthHash); + + // test digest auth custom authorization middleware + // curl -v --digest -u user:password http://192.168.4.1/auth-custom?token=123 => OK + // curl -v --digest -u user:password http://192.168.4.1/auth-custom?token=456 => 403 + // curl -v --digest -u user:FAILED http://192.168.4.1/auth-custom?token=456 => 401 + server + .on( + "/auth-custom", HTTP_GET, + [](AsyncWebServerRequest *request) { + String buffer = "Hello "; + buffer.concat(request->getAttribute("user")); + buffer.concat(" with role: "); + buffer.concat(request->getAttribute("role")); + request->send(200, "text/plain", buffer); + } + ) + .addMiddlewares({&complexAuth, &authz}); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/CORS/CORS.ino b/watering/lib/ESPAsyncWebServer/examples/CORS/CORS.ino new file mode 100644 index 0000000..3be46fd --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/CORS/CORS.ino @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// How to use CORS middleware +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); +static AsyncCorsMiddleware cors; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + cors.setOrigin("http://192.168.4.1"); + cors.setMethods("POST, GET, OPTIONS, DELETE"); + cors.setHeaders("X-Custom-Header"); + cors.setAllowCredentials(false); + cors.setMaxAge(600); + + server.addMiddleware(&cors); + + // Test CORS preflight request + // curl -v -X OPTIONS -H "origin: http://192.168.4.1" http://192.168.4.1/cors + // + // Test CORS request + // curl -v -H "origin: http://192.168.4.1" http://192.168.4.1/cors + // + // Test non-CORS request + // curl -v http://192.168.4.1/cors + // + server.on("/cors", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino b/watering/lib/ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino new file mode 100644 index 0000000..a872a9b --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif +#include "ESPAsyncWebServer.h" + +static DNSServer dnsServer; +static AsyncWebServer server(80); + +class CaptiveRequestHandler : public AsyncWebHandler { +public: + bool canHandle(__unused AsyncWebServerRequest *request) const override { + return true; + } + + void handleRequest(AsyncWebServerRequest *request) { + AsyncResponseStream *response = request->beginResponseStream("text/html"); + response->print("Captive Portal"); + response->print("

This is our captive portal front page.

"); + response->printf("

You were trying to reach: http://%s%s

", request->host().c_str(), request->url().c_str()); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + response->printf("

Try opening this link instead

", WiFi.softAPIP().toString().c_str()); +#endif + response->print(""); + request->send(response); + } +}; + +void setup() { + Serial.begin(115200); + Serial.println(); + Serial.println("Configuring access point..."); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + if (!WiFi.softAP("esp-captive")) { + Serial.println("Soft AP creation failed."); + while (1); + } + + dnsServer.start(53, "*", WiFi.softAPIP()); +#endif + + server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER); // only when requested from AP + // more handlers... + server.begin(); +} + +void loop() { + dnsServer.processNextRequest(); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/CatchAllHandler/CatchAllHandler.ino b/watering/lib/ESPAsyncWebServer/examples/CatchAllHandler/CatchAllHandler.ino new file mode 100644 index 0000000..42a3698 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/CatchAllHandler/CatchAllHandler.ino @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to catch all requests and send a 404 Not Found response +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + // catch any request, and send a 404 Not Found response + // except for /game_log which is handled by onRequestBody + // + // curl -v http://192.168.4.1/foo + // + server.onNotFound([](AsyncWebServerRequest *request) { + if (request->url() == "/game_log") { + return; // response object already created by onRequestBody + } + + request->send(404, "text/plain", "Not found"); + }); + + // See: https://github.com/ESP32Async/ESPAsyncWebServer/issues/6 + // catch any POST request and send a 200 OK response + // + // curl -v -X POST http://192.168.4.1/game_log -H "Content-Type: application/json" -d '{"game": "test"}' + // + server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { + if (request->url() == "/game_log") { + request->send(200, "application/json", "{\"status\":\"OK\"}"); + } + // note that there is no else here: the goal is only to prepare a response based on some body content + // onNotFound will always be called after this, and will not override the response object if `/game_log` is requested + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/ChunkResponse/ChunkResponse.ino b/watering/lib/ESPAsyncWebServer/examples/ChunkResponse/ChunkResponse.ino new file mode 100644 index 0000000..e7d4838 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/ChunkResponse/ChunkResponse.ino @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Chunk response with caching example +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // first time: serves the file and cache headers + // curl -N -v http://192.168.4.1/ --output - + // + // secodn time: serves 304 + // curl -N -v -H "if-none-match: 4272" http://192.168.4.1/ --output - + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + String etag = String(htmlContentLength); + + if (request->header(asyncsrv::T_INM) == etag) { + request->send(304); + return; + } + + AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t { + Serial.printf("%u / %u\n", index, htmlContentLength); + + // finished ? + if (htmlContentLength <= index) { + Serial.println("finished"); + return 0; + } + + // serve a maximum of 256 or maxLen bytes of the remaining content + // this small number is specifically chosen to demonstrate the chunking + // DO NOT USE SUCH SMALL NUMBER IN PRODUCTION + // Reducing the chunk size will increase the response time, thus reducing the server's capacity in processing concurrent requests + const int chunkSize = min((size_t)256, min(maxLen, htmlContentLength - index)); + Serial.printf("sending: %u\n", chunkSize); + + memcpy(buffer, htmlContent + index, chunkSize); + + return chunkSize; + }); + + response->addHeader(asyncsrv::T_Cache_Control, "public,max-age=60"); + response->addHeader(asyncsrv::T_ETag, etag); + + request->send(response); + }); + + server.begin(); +} + +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/ChunkRetryResponse/ChunkRetryResponse.ino b/watering/lib/ESPAsyncWebServer/examples/ChunkRetryResponse/ChunkRetryResponse.ino new file mode 100644 index 0000000..48772cc --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/ChunkRetryResponse/ChunkRetryResponse.ino @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to wait in a chunk response for incoming data +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +#if __has_include("ArduinoJson.h") +#include +#include +#include +#endif + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +static AsyncWebServer server(80); +static AsyncLoggingMiddleware requestLogger; + +static String triggerUART; +static int key = -1; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // adds some internal request logging for debugging + requestLogger.setEnabled(true); + requestLogger.setOutput(Serial); + + server.addMiddleware(&requestLogger); + +#if __has_include("ArduinoJson.h") + + // + // HOW TO RUN THIS EXAMPLE: + // + // 1. Trigger a request that will be blocked for a long time: + // > time curl -v -X POST http://192.168.4.1/api -H "Content-Type: application/json" -d '{"input": "Please type a key to continue in Serial console..."}' --output - + // + // 2. While waiting, in another terminal, run some concurrent requests: + // > time curl -v http://192.168.4.1/ + // + // 3. Type a key in the Serial console to continue the processing within 30 seconds. + // This should unblock the first request. + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + server.on( + "/api", HTTP_POST, + [](AsyncWebServerRequest *request) { + // request parsing has finished + + // no data ? + if (!((String *)request->_tempObject)->length()) { + request->send(400); + return; + } + + JsonDocument doc; + + // deserialize and check for errors + if (deserializeJson(doc, *(String *)request->_tempObject)) { + request->send(400); + return; + } + + // start UART com: UART will send the data to the Serial console and wait for the key press + triggerUART = doc["input"].as(); + key = -1; + + AsyncWebServerResponse *response = request->beginChunkedResponse("text/plain", [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t { + // still waiting for UARY ? + if (triggerUART.length() && key == -1) { + return RESPONSE_TRY_AGAIN; + } + + // finished ? + if (!triggerUART.length() && key == -1) { + return 0; // 0 means we are done + } + + // log_d("UART answered!"); + + String answer = "You typed: "; + answer.concat((char)key); + + // note: I did not check for maxLen, but you should (see ChunkResponse.ino) + memcpy(buffer, answer.c_str(), answer.length()); + + // finish! + triggerUART = emptyString; + key = -1; + + return answer.length(); + }); + + request->send(response); + }, + NULL, // upload handler is not used so it should be NULL + [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { + // log_d("Body: index: %u, len: %u, total: %u", index, len, total); + + if (!index) { + // log_d("Start body parsing"); + request->_tempObject = new String(); + // cast request->_tempObject pointer to String and reserve total size + ((String *)request->_tempObject)->reserve(total); + // set timeout 30s + request->client()->setRxTimeout(30); + } + + // log_d("Append body data"); + ((String *)request->_tempObject)->concat((const char *)data, len); + } + ); + +#endif + + server.begin(); +} + +void loop() { + if (triggerUART.length() && key == -1) { + Serial.println(triggerUART); + // log_d("Waiting for UART input..."); + while (!Serial.available()) { + delay(100); + } + key = Serial.read(); + Serial.flush(); + // log_d("UART input: %c", key); + triggerUART = emptyString; + } +} diff --git a/watering/lib/ESPAsyncWebServer/examples/EndBegin/EndBegin.ino b/watering/lib/ESPAsyncWebServer/examples/EndBegin/EndBegin.ino new file mode 100644 index 0000000..acfc6ff --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/EndBegin/EndBegin.ino @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// https://github.com/ESP32Async/ESPAsyncWebServer/discussions/23 +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world"); + }); + + server.begin(); + Serial.println("begin() - run: curl -v http://192.168.4.1/ => should succeed"); + delay(10000); + + Serial.println("end()"); + server.end(); + server.begin(); + Serial.println("begin() - run: curl -v http://192.168.4.1/ => should succeed"); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Filters/Filters.ino b/watering/lib/ESPAsyncWebServer/examples/Filters/Filters.ino new file mode 100644 index 0000000..519478c --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Filters/Filters.ino @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to use setFilter to route requests to different handlers based on WiFi mode +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif +#include "ESPAsyncWebServer.h" + +static DNSServer dnsServer; +static AsyncWebServer server(80); + +class CaptiveRequestHandler : public AsyncWebHandler { +public: + bool canHandle(__unused AsyncWebServerRequest *request) const override { + return true; + } + + void handleRequest(AsyncWebServerRequest *request) override { + AsyncResponseStream *response = request->beginResponseStream("text/html"); + response->print("Captive Portal"); + response->print("

This is out captive portal front page.

"); + response->printf("

You were trying to reach: http://%s%s

", request->host().c_str(), request->url().c_str()); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + response->printf("

Try opening this link instead

", WiFi.softAPIP().toString().c_str()); +#endif + response->print(""); + request->send(response); + } +}; + +bool hit1 = false; +bool hit2 = false; + +void setup() { + Serial.begin(115200); + + server + .on( + "/", HTTP_GET, + [](AsyncWebServerRequest *request) { + Serial.println("Captive portal request..."); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + Serial.println("WiFi.localIP(): " + WiFi.localIP().toString()); +#endif + Serial.println("request->client()->localIP(): " + request->client()->localIP().toString()); +#if ESP_IDF_VERSION_MAJOR >= 5 +#ifndef CONFIG_IDF_TARGET_ESP32H2 + Serial.println("WiFi.type(): " + String((int)WiFi.localIP().type())); +#endif + Serial.println("request->client()->type(): " + String((int)request->client()->localIP().type())); +#endif +#ifndef CONFIG_IDF_TARGET_ESP32H2 + Serial.println(WiFi.localIP() == request->client()->localIP() ? "should be: ON_STA_FILTER" : "should be: ON_AP_FILTER"); + Serial.println(WiFi.localIP() == request->client()->localIP()); + Serial.println(WiFi.localIP().toString() == request->client()->localIP().toString()); +#endif + request->send(200, "text/plain", "This is the captive portal"); + hit1 = true; + } + ) + .setFilter(ON_AP_FILTER); + + server + .on( + "/", HTTP_GET, + [](AsyncWebServerRequest *request) { + Serial.println("Website request..."); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + Serial.println("WiFi.localIP(): " + WiFi.localIP().toString()); +#endif + Serial.println("request->client()->localIP(): " + request->client()->localIP().toString()); +#if ESP_IDF_VERSION_MAJOR >= 5 +#ifndef CONFIG_IDF_TARGET_ESP32H2 + Serial.println("WiFi.type(): " + String((int)WiFi.localIP().type())); +#endif + Serial.println("request->client()->type(): " + String((int)request->client()->localIP().type())); +#endif +#ifndef CONFIG_IDF_TARGET_ESP32H2 + Serial.println(WiFi.localIP() == request->client()->localIP() ? "should be: ON_STA_FILTER" : "should be: ON_AP_FILTER"); + Serial.println(WiFi.localIP() == request->client()->localIP()); + Serial.println(WiFi.localIP().toString() == request->client()->localIP().toString()); +#endif + request->send(200, "text/plain", "This is the website"); + hit2 = true; + } + ) + .setFilter(ON_STA_FILTER); + + // assert(WiFi.softAP("esp-captive-portal")); + // dnsServer.start(53, "*", WiFi.softAPIP()); + // server.begin(); + // Serial.println("Captive portal started!"); + + // while (!hit1) { + // dnsServer.processNextRequest(); + // yield(); + // } + // delay(1000); // Wait for the client to process the response + + // Serial.println("Captive portal opened, stopping it and connecting to WiFi..."); + // dnsServer.stop(); + // WiFi.softAPdisconnect(); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.persistent(false); + WiFi.begin("IoT"); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + } + Serial.println("Connected to WiFi with IP address: " + WiFi.localIP().toString()); +#endif + + server.begin(); + + // while (!hit2) { + // delay(10); + // } + // delay(1000); // Wait for the client to process the response + // ESP.restart(); +} + +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/FlashResponse/FlashResponse.ino b/watering/lib/ESPAsyncWebServer/examples/FlashResponse/FlashResponse.ino new file mode 100644 index 0000000..6948cd2 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/FlashResponse/FlashResponse.ino @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to serve a large HTML page from flash memory without copying it to heap in a temporary buffer +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/HeaderManipulation/HeaderManipulation.ino b/watering/lib/ESPAsyncWebServer/examples/HeaderManipulation/HeaderManipulation.ino new file mode 100644 index 0000000..4fe34dc --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/HeaderManipulation/HeaderManipulation.ino @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Show how to manipulate headers in the request / response +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +// request logger +static AsyncLoggingMiddleware requestLogger; + +// filter out specific headers from the incoming request +static AsyncHeaderFilterMiddleware headerFilter; + +// remove all headers from the incoming request except the ones provided in the constructor +AsyncHeaderFreeMiddleware headerFree; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + requestLogger.setEnabled(true); + requestLogger.setOutput(Serial); + + headerFilter.filter("X-Remove-Me"); + + headerFree.keep("X-Keep-Me"); + headerFree.keep("host"); + + server.addMiddlewares({&requestLogger, &headerFilter}); + + // x-remove-me header will be removed + // + // curl -v -H "X-Header: Foo" -H "x-remove-me: value" http://192.168.4.1/remove + // + server.on("/remove", HTTP_GET, [](AsyncWebServerRequest *request) { + // print all headers + for (size_t i = 0; i < request->headers(); i++) { + const AsyncWebHeader *h = request->getHeader(i); + Serial.printf("Header[%s]: %s\n", h->name().c_str(), h->value().c_str()); + } + request->send(200, "text/plain", "Hello, world!"); + }); + + // Only headers x-keep-me and host will be kept + // + // curl -v -H "x-keep-me: value" -H "x-remove-me: value" http://192.168.4.1/keep + // + server + .on( + "/keep", HTTP_GET, + [](AsyncWebServerRequest *request) { + // print all headers + for (size_t i = 0; i < request->headers(); i++) { + const AsyncWebHeader *h = request->getHeader(i); + Serial.printf("Header[%s]: %s\n", h->name().c_str(), h->value().c_str()); + } + request->send(200, "text/plain", "Hello, world!"); + } + ) + .addMiddleware(&headerFree); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Headers/Headers.ino b/watering/lib/ESPAsyncWebServer/examples/Headers/Headers.ino new file mode 100644 index 0000000..e07c515 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Headers/Headers.ino @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Query and send headers +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // + // curl -v http://192.168.4.1 + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + //List all collected headers + int headers = request->headers(); + int i; + for (i = 0; i < headers; i++) { + const AsyncWebHeader *h = request->getHeader(i); + Serial.printf("HEADER[%s]: %s\n", h->name().c_str(), h->value().c_str()); + } + + AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "Hello World!"); + + //Add header to the response + response->addHeader("Server", "ESP Async Web Server"); + + //Add multiple headers with the same name + response->addHeader("Set-Cookie", "sessionId=38afes7a8", false); + response->addHeader("Set-Cookie", "id=a3fWa; Max-Age=2592000", false); + response->addHeader("Set-Cookie", "qwerty=219ffwef9w0f; Domain=example.com", false); + + //Remove specific header + response->removeHeader("Set-Cookie", "sessionId=38afes7a8"); + + //Remove all headers with the same name + response->removeHeader("Set-Cookie"); + + request->send(response); + }); + + server.begin(); +} + +void loop() { + //Sleep in the loop task to not keep the CPU busy + delay(1000); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Json/Json.ino b/watering/lib/ESPAsyncWebServer/examples/Json/Json.ino new file mode 100644 index 0000000..0ea8892 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Json/Json.ino @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to send and receive Json data +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +#if __has_include("ArduinoJson.h") +#include +#include +#include +#endif + +static AsyncWebServer server(80); + +#if __has_include("ArduinoJson.h") +static AsyncCallbackJsonWebHandler *handler = new AsyncCallbackJsonWebHandler("/json2"); +#endif + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + +#if __has_include("ArduinoJson.h") + // + // sends JSON using AsyncJsonResponse + // + // curl -v http://192.168.4.1/json1 + // + server.on("/json1", HTTP_GET, [](AsyncWebServerRequest *request) { + AsyncJsonResponse *response = new AsyncJsonResponse(); + JsonObject root = response->getRoot().to(); + root["hello"] = "world"; + response->setLength(); + request->send(response); + }); + + // Send JSON using AsyncResponseStream + // + // curl -v http://192.168.4.1/json2 + // + server.on("/json2", HTTP_GET, [](AsyncWebServerRequest *request) { + AsyncResponseStream *response = request->beginResponseStream("application/json"); + JsonDocument doc; + JsonObject root = doc.to(); + root["foo"] = "bar"; + serializeJson(root, *response); + request->send(response); + }); + + // curl -v -X POST -H 'Content-Type: application/json' -d '{"name":"You"}' http://192.168.4.1/json2 + // curl -v -X PUT -H 'Content-Type: application/json' -d '{"name":"You"}' http://192.168.4.1/json2 + handler->setMethod(HTTP_POST | HTTP_PUT); + handler->onRequest([](AsyncWebServerRequest *request, JsonVariant &json) { + serializeJson(json, Serial); + AsyncJsonResponse *response = new AsyncJsonResponse(); + JsonObject root = response->getRoot().to(); + root["hello"] = json.as()["name"]; + response->setLength(); + request->send(response); + }); + + server.addHandler(handler); +#endif + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Logging/Logging.ino b/watering/lib/ESPAsyncWebServer/examples/Logging/Logging.ino new file mode 100644 index 0000000..6485185 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Logging/Logging.ino @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Show how to log the incoming request and response as a curl-like syntax +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); +static AsyncLoggingMiddleware requestLogger; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + requestLogger.setEnabled(true); + requestLogger.setOutput(Serial); + + server.addMiddleware(&requestLogger); + + // curl -v -H "X-Header:Foo" http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/MessagePack/MessagePack.ino b/watering/lib/ESPAsyncWebServer/examples/MessagePack/MessagePack.ino new file mode 100644 index 0000000..4fea247 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/MessagePack/MessagePack.ino @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to send and receive Message Pack data +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +#if __has_include("ArduinoJson.h") +#include +#include +#include +#endif + +static AsyncWebServer server(80); + +#if __has_include("ArduinoJson.h") +static AsyncCallbackMessagePackWebHandler *handler = new AsyncCallbackMessagePackWebHandler("/msgpack2"); +#endif + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + +#if __has_include("ArduinoJson.h") + // + // sends MessagePack using AsyncMessagePackResponse + // + // curl -v http://192.168.4.1/msgpack1 + // + server.on("/msgpack1", HTTP_GET, [](AsyncWebServerRequest *request) { + AsyncMessagePackResponse *response = new AsyncMessagePackResponse(); + JsonObject root = response->getRoot().to(); + root["hello"] = "world"; + response->setLength(); + request->send(response); + }); + + // Send MessagePack using AsyncResponseStream + // + // curl -v http://192.168.4.1/msgpack2 + // + server.on("/msgpack2", HTTP_GET, [](AsyncWebServerRequest *request) { + AsyncResponseStream *response = request->beginResponseStream("application/msgpack"); + JsonDocument doc; + JsonObject root = doc.to(); + root["foo"] = "bar"; + serializeMsgPack(root, *response); + request->send(response); + }); + + handler->setMethod(HTTP_POST | HTTP_PUT); + handler->onRequest([](AsyncWebServerRequest *request, JsonVariant &json) { + serializeJson(json, Serial); + AsyncMessagePackResponse *response = new AsyncMessagePackResponse(); + JsonObject root = response->getRoot().to(); + root["hello"] = json.as()["name"]; + response->setLength(); + request->send(response); + }); + + server.addHandler(handler); +#endif + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Middleware/Middleware.ino b/watering/lib/ESPAsyncWebServer/examples/Middleware/Middleware.ino new file mode 100644 index 0000000..c52f949 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Middleware/Middleware.ino @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Show how to sue Middleware +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +// New middleware classes can be created! +class MyMiddleware : public AsyncMiddleware { +public: + void run(AsyncWebServerRequest *request, ArMiddlewareNext next) override { + Serial.printf("Before handler: %s %s\n", request->methodToString(), request->url().c_str()); + next(); // continue middleware chain + Serial.printf("After handler: response code=%d\n", request->getResponse()->code()); + } +}; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // add a global middleware to the server + server.addMiddleware(new MyMiddleware()); + + // Test with: + // + // - curl -v http://192.168.4.1/ => 200 OK + // - curl -v http://192.168.4.1/?user=anon => 403 Forbidden + // - curl -v http://192.168.4.1/?user=foo => 200 OK + // - curl -v http://192.168.4.1/?user=error => 400 ERROR + // + AsyncCallbackWebHandler &handler = server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + Serial.printf("In Handler: %s %s\n", request->methodToString(), request->url().c_str()); + request->send(200, "text/plain", "Hello, world!"); + }); + + // add a middleware to this handler only to send 403 if the user is anon + handler.addMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + Serial.println("Checking user=anon"); + if (request->hasParam("user") && request->getParam("user")->value() == "anon") { + request->send(403, "text/plain", "Forbidden"); + } else { + next(); + } + }); + + // add a middleware to this handler that will replace the previously created response by another one + handler.addMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + next(); + Serial.println("Checking user=error"); + if (request->hasParam("user") && request->getParam("user")->value() == "error") { + request->send(400, "text/plain", "ERROR"); + } + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Params/Params.ino b/watering/lib/ESPAsyncWebServer/examples/Params/Params.ino new file mode 100644 index 0000000..2c438a5 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Params/Params.ino @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Query parameters and body parameters +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +static const char *htmlContent PROGMEM = R"( + + + + POST Request with Multiple Parameters + + +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // Get query parameters + // + // curl -v http://192.168.4.1/?who=Bob + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + if (request->hasParam("who")) { + Serial.printf("Who? %s\n", request->getParam("who")->value().c_str()); + } + + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + // Get form body parameters + // + // curl -v -H "Content-Type: application/x-www-form-urlencoded" -d "who=Carl" -d "param=value" http://192.168.4.1/ + // + server.on("/", HTTP_POST, [](AsyncWebServerRequest *request) { + // display params + size_t count = request->params(); + for (size_t i = 0; i < count; i++) { + const AsyncWebParameter *p = request->getParam(i); + Serial.printf("PARAM[%u]: %s = %s\n", i, p->name().c_str(), p->value().c_str()); + } + + // get who param + String who; + if (request->hasParam("who", true)) { + who = request->getParam("who", true)->value(); + } else { + who = "No message sent"; + } + request->send(200, "text/plain", "Hello " + who + "!"); + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/PartitionDownloader/PartitionDownloader.ino b/watering/lib/ESPAsyncWebServer/examples/PartitionDownloader/PartitionDownloader.ino new file mode 100644 index 0000000..3c76366 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/PartitionDownloader/PartitionDownloader.ino @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// - Download ESP32 partition by name and/or type and/or subtype +// - Support encrypted and non-encrypted partitions +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include +#include + +#ifndef ESP32 +// this example is only for the ESP32 +void setup() {} +void loop() {} +#else + +#include + +static AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + LittleFS.begin(true); + + // To upload the FS partition, run: + // > pio run -e arduino-3 -t buildfs + // > pio run -e arduino-3 -t uploadfs + // + // Examples: + // + // - Download the partition named "spiffs": http://192.168.4.1/partition?label=spiffs + // - Download the partition named "spiffs" with type "data": http://192.168.4.1/partition?label=spiffs&type=1 + // - Download the partition named "spiffs" with type "data" and subtype "spiffs": http://192.168.4.1/partition?label=spiffs&type=1&subtype=130 + // - Download the partition with subtype "nvs": http://192.168.4.1/partition?type=1&subtype=2 + // + // "type" and "subtype" IDs can be found in esp_partition.h header file. + // + // Add "&raw=false" parameter to download the partition unencrypted (for encrypted partitions). + // By default, the raw partition is downloaded, so if a partition is encrypted, the encrypted data will be downloaded. + // + // To browse a downloaded LittleFS partition, you can use https://tniessen.github.io/littlefs-disk-img-viewer/ (block size is 4096) + // + server.on("/partition", HTTP_GET, [](AsyncWebServerRequest *request) { + const AsyncWebParameter *pLabel = request->getParam("label"); + const AsyncWebParameter *pType = request->getParam("type"); + const AsyncWebParameter *pSubtype = request->getParam("subtype"); + const AsyncWebParameter *pRaw = request->getParam("raw"); + + if (!pLabel && !pType && !pSubtype) { + request->send(400, "text/plain", "Bad request: missing parameter"); + return; + } + + esp_partition_type_t type = ESP_PARTITION_TYPE_ANY; + esp_partition_subtype_t subtype = ESP_PARTITION_SUBTYPE_ANY; + const char *label = nullptr; + bool raw = true; + + if (pLabel) { + label = pLabel->value().c_str(); + } + + if (pType) { + type = (esp_partition_type_t)pType->value().toInt(); + } + + if (pSubtype) { + subtype = (esp_partition_subtype_t)pSubtype->value().toInt(); + } + + if (pRaw && pRaw->value() == "false") { + raw = false; + } + + const esp_partition_t *partition = esp_partition_find_first(type, subtype, label); + + if (!partition) { + request->send(404, "text/plain", "Partition not found"); + return; + } + + AsyncWebServerResponse *response = + request->beginChunkedResponse("application/octet-stream", [partition, raw](uint8_t *buffer, size_t maxLen, size_t index) -> size_t { + const size_t remaining = partition->size - index; + if (!remaining) { + return 0; + } + const size_t len = std::min(maxLen, remaining); + if (raw && esp_partition_read_raw(partition, index, buffer, len) == ESP_OK) { + return len; + } + if (!raw && esp_partition_read(partition, index, buffer, len) == ESP_OK) { + return len; + } + return 0; + }); + + response->addHeader("Content-Disposition", "attachment; filename=" + String(partition->label) + ".bin"); + response->setContentLength(partition->size); + + request->send(response); + }); + + server.begin(); +} + +void loop() { + delay(100); +} + +#endif diff --git a/watering/lib/ESPAsyncWebServer/examples/PerfTests/PerfTests.ino b/watering/lib/ESPAsyncWebServer/examples/PerfTests/PerfTests.ino new file mode 100644 index 0000000..6467d2c --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/PerfTests/PerfTests.ino @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Perf tests +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); +static constexpr char characters[] = "0123456789ABCDEF"; +static size_t charactersIndex = 0; + +static AsyncWebServer server(80); +static AsyncEventSource events("/events"); + +static volatile size_t requests = 0; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // Pauses in the request parsing phase + // + // autocannon -c 32 -w 32 -a 96 -t 30 --renderStatusCodes -m POST -H "Content-Type: application/json" -b '{"foo": "bar"}' http://192.168.4.1/delay + // + // curl -v -X POST -H "Content-Type: application/json" -d '{"game": "test"}' http://192.168.4.1/delay + // + server.onNotFound([](AsyncWebServerRequest *request) { + requests = requests + 1; + if (request->url() == "/delay") { + request->send(200, "application/json", "{\"status\":\"OK\"}"); + } else { + request->send(404, "text/plain", "Not found"); + } + }); + server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { + if (request->url() == "/delay") { + delay(3000); + } + }); + + // HTTP endpoint + // + // > brew install autocannon + // > autocannon -c 10 -w 10 -d 20 http://192.168.4.1 + // > autocannon -c 16 -w 16 -d 20 http://192.168.4.1 + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + requests = requests + 1; + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + // IMPORTANT - DO NOT WRITE SUCH CODE IN PRODUCTON ! + // + // This example simulates the slowdown that can happen when: + // - downloading a huge file from sdcard + // - doing some file listing on SDCard because it is horribly slow to get a file listing with file stats on SDCard. + // So in both cases, ESP would deadlock or TWDT would trigger. + // + // This example simulats that by slowing down the chunk callback: + // - d=2000 is the delay in ms in the callback + // - l=10000 is the length of the response + // + // time curl -N -v -G -d 'd=2000' -d 'l=10000' http://192.168.4.1/slow.html --output - + // + server.on("/slow.html", HTTP_GET, [](AsyncWebServerRequest *request) { + requests = requests + 1; + uint32_t d = request->getParam("d")->value().toInt(); + uint32_t l = request->getParam("l")->value().toInt(); + Serial.printf("d = %" PRIu32 ", l = %" PRIu32 "\n", d, l); + AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [d, l](uint8_t *buffer, size_t maxLen, size_t index) -> size_t { + Serial.printf("%u\n", index); + // finished ? + if (index >= l) { + return 0; + } + + // slow down the task to simulate some heavy processing, like SD card reading + delay(d); + + memset(buffer, characters[charactersIndex], 256); + charactersIndex = (charactersIndex + 1) % sizeof(characters); + return 256; + }); + + request->send(response); + }); + + // SSS endpoint + // + // launch 16 concurrent workers for 30 seconds + // > for i in {1..10}; do ( count=$(gtimeout 30 curl -s -N -H "Accept: text/event-stream" http://192.168.4.1/events 2>&1 | grep -c "^data:"); echo "Total: $count events, $(echo "$count / 4" | bc -l) events / second" ) & done; + // > for i in {1..16}; do ( count=$(gtimeout 30 curl -s -N -H "Accept: text/event-stream" http://192.168.4.1/events 2>&1 | grep -c "^data:"); echo "Total: $count events, $(echo "$count / 4" | bc -l) events / second" ) & done; + // + // With AsyncTCP, with 16 workers: a lot of "Event message queue overflow: discard message", no crash + // + // Total: 1711 events, 427.75 events / second + // Total: 1711 events, 427.75 events / second + // Total: 1626 events, 406.50 events / second + // Total: 1562 events, 390.50 events / second + // Total: 1706 events, 426.50 events / second + // Total: 1659 events, 414.75 events / second + // Total: 1624 events, 406.00 events / second + // Total: 1706 events, 426.50 events / second + // Total: 1487 events, 371.75 events / second + // Total: 1573 events, 393.25 events / second + // Total: 1569 events, 392.25 events / second + // Total: 1559 events, 389.75 events / second + // Total: 1560 events, 390.00 events / second + // Total: 1562 events, 390.50 events / second + // Total: 1626 events, 406.50 events / second + // + // With AsyncTCP, with 10 workers: + // + // Total: 2038 events, 509.50 events / second + // Total: 2120 events, 530.00 events / second + // Total: 2119 events, 529.75 events / second + // Total: 2038 events, 509.50 events / second + // Total: 2037 events, 509.25 events / second + // Total: 2119 events, 529.75 events / second + // Total: 2119 events, 529.75 events / second + // Total: 2120 events, 530.00 events / second + // Total: 2038 events, 509.50 events / second + // Total: 2038 events, 509.50 events / second + // + // With AsyncTCPSock, with 16 workers: ESP32 CRASH !!! + // + // With AsyncTCPSock, with 10 workers: + // + // Total: 1242 events, 310.50 events / second + // Total: 1242 events, 310.50 events / second + // Total: 1242 events, 310.50 events / second + // Total: 1242 events, 310.50 events / second + // Total: 1181 events, 295.25 events / second + // Total: 1182 events, 295.50 events / second + // Total: 1240 events, 310.00 events / second + // Total: 1181 events, 295.25 events / second + // Total: 1181 events, 295.25 events / second + // Total: 1183 events, 295.75 events / second + // + server.addHandler(&events); + + server.begin(); +} + +static uint32_t lastSSE = 0; +static uint32_t deltaSSE = 10; + +static uint32_t lastHeap = 0; + +void loop() { + uint32_t now = millis(); + if (now - lastSSE >= deltaSSE) { + events.send(String("ping-") + now, "heartbeat", now); + lastSSE = millis(); + } + +#ifdef ESP32 + if (now - lastHeap >= 2000) { + Serial.printf("Uptime: %3lu s, requests: %3u, Free heap: %" PRIu32 "\n", millis() / 1000, requests, ESP.getFreeHeap()); + lastHeap = now; + } +#endif +} diff --git a/watering/lib/ESPAsyncWebServer/examples/RateLimit/RateLimit.ino b/watering/lib/ESPAsyncWebServer/examples/RateLimit/RateLimit.ino new file mode 100644 index 0000000..89d6090 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/RateLimit/RateLimit.ino @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Show how to rate limit the server or some endpoints +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); +static AsyncRateLimitMiddleware rateLimit; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // maximum 5 requests per 10 seconds + rateLimit.setMaxRequests(5); + rateLimit.setWindowSize(10); + + // run quickly several times: + // + // curl -v http://192.168.4.1/ + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + }); + + // run quickly several times: + // + // curl -v http://192.168.4.1/rate-limited + // + server + .on( + "/rate-limited", HTTP_GET, + [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + } + ) + .addMiddleware(&rateLimit); // only rate limit this endpoint, but could be applied globally to the server + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Redirect/Redirect.ino b/watering/lib/ESPAsyncWebServer/examples/Redirect/Redirect.ino new file mode 100644 index 0000000..ce1b9fb --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Redirect/Redirect.ino @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to redirect +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->redirect("/index.txt"); + }); + + // curl -v http://192.168.4.1/index.txt + server.on("/index.txt", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/RequestContinuation/RequestContinuation.ino b/watering/lib/ESPAsyncWebServer/examples/RequestContinuation/RequestContinuation.ino new file mode 100644 index 0000000..0584cf1 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/RequestContinuation/RequestContinuation.ino @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to use request continuation to pause a request for a long processing task, and be able to resume it later. +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include +#include +#include + +static AsyncWebServer server(80); + +// request handler that is saved from the paused request to communicate with Serial +static String message; +static AsyncWebServerRequestPtr serialRequest; + +// request handler that is saved from the paused request to communicate with GPIO +static uint8_t pin = 35; +static AsyncWebServerRequestPtr gpioRequest; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // Post a message that will be sent to the Serial console, and pause the request until the user types a key + // + // curl -v -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "question=Name%3F%20" http://192.168.4.1/serial + // + // curl output should show "Answer: [y/n]" as the response + server.on("/serial", HTTP_POST, [](AsyncWebServerRequest *request) { + message = request->getParam("question", true)->value(); + serialRequest = request->pause(); + }); + + // Wait for a GPIO to be high + // + // curl -v http://192.168.4.1/gpio + // + // curl output should show "GPIO is high!" as the response + server.on("/gpio", HTTP_GET, [](AsyncWebServerRequest *request) { + gpioRequest = request->pause(); + }); + + pinMode(pin, INPUT); + + server.begin(); +} + +void loop() { + delay(500); + + // Check for a high voltage on the RX1 pin + if (digitalRead(pin) == HIGH) { + if (auto request = gpioRequest.lock()) { + request->send(200, "text/plain", "GPIO is high!"); + } + } + + // check for an incoming message from the Serial console + if (message.length()) { + Serial.printf("%s", message.c_str()); + // drops buffer + while (Serial.available()) { + Serial.read(); + } + Serial.setTimeout(10000); + String response = Serial.readStringUntil('\n'); // waits for a key to be pressed + Serial.println(); + message = emptyString; + if (auto request = serialRequest.lock()) { + request->send(200, "text/plain", "Answer: " + response); + } + } +} diff --git a/watering/lib/ESPAsyncWebServer/examples/RequestContinuationComplete/RequestContinuationComplete.ino b/watering/lib/ESPAsyncWebServer/examples/RequestContinuationComplete/RequestContinuationComplete.ino new file mode 100644 index 0000000..ccd16fd --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/RequestContinuationComplete/RequestContinuationComplete.ino @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to use request continuation to pause a request for a long processing task, and be able to resume it later. +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +#include +#include +#include + +static AsyncWebServer server(80); + +// =============================================================== +// The code below is used to simulate some long running operations +// =============================================================== + +typedef struct { + size_t id; + AsyncWebServerRequestPtr requestPtr; + uint8_t data; +} LongRunningOperation; + +static std::list> longRunningOperations; +static size_t longRunningOperationsCount = 0; +#ifdef ESP32 +static std::mutex longRunningOperationsMutex; +#endif + +static void startLongRunningOperation(AsyncWebServerRequestPtr &&requestPtr) { +#ifdef ESP32 + std::lock_guard lock(longRunningOperationsMutex); +#endif + + // LongRunningOperation *op = new LongRunningOperation(); + std::unique_ptr op(new LongRunningOperation()); + op->id = ++longRunningOperationsCount; + op->data = 10; + + // you need to hold the AsyncWebServerRequestPtr returned by pause(); + // This object is authorized to leave the scope of the request handler. + op->requestPtr = std::move(requestPtr); + + Serial.printf("[%u] Start long running operation for %" PRIu8 " seconds...\n", op->id, op->data); + longRunningOperations.push_back(std::move(op)); +} + +static bool processLongRunningOperation(LongRunningOperation *op) { + // request was deleted ? + if (op->requestPtr.expired()) { + Serial.printf("[%u] Request was deleted - stopping long running operation\n", op->id); + return true; // operation finished + } + + // processing the operation + Serial.printf("[%u] Long running operation processing... %" PRIu8 " seconds left\n", op->id, op->data); + + // check if we have finished ? + op->data--; + if (op->data) { + // not finished yet + return false; + } + + // Try to get access to the request pointer if it is still exist. + // If there has been a disconnection during that time, the pointer won't be valid anymore + if (auto request = op->requestPtr.lock()) { + Serial.printf("[%u] Long running operation finished! Sending back response...\n", op->id); + request->send(200, "text/plain", String(op->id) + " "); + + } else { + Serial.printf("[%u] Long running operation finished, but request was deleted!\n", op->id); + } + + return true; // operation finished +} + +/// ========================================================== + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // Add a middleware to see how pausing a request affects the middleware chain + server.addMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + Serial.printf("Middleware chain start\n"); + + // continue to the next middleware, and at the end the request handler + next(); + + // we can check the request pause state after the handler was executed + if (request->isPaused()) { + Serial.printf("Request was paused!\n"); + } + + Serial.printf("Middleware chain ends\n"); + }); + + // HOW TO RUN THIS EXAMPLE: + // + // 1. Open several terminals to trigger some requests concurrently that will be paused with: + // > time curl -v http://192.168.4.1/ + // + // 2. Look at the output of the Serial console to see how the middleware chain is executed + // and to see the long running operations being processed and resume the requests. + // + // 3. You can try close your curl command to cancel the request and check that the request is deleted. + // Note: in case the network is disconnected, the request will be deleted. + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // Print a message in case the request is disconnected (network disconnection, client close, etc.) + request->onDisconnect([]() { + Serial.printf("Request was disconnected!\n"); + }); + + // Instruct ESPAsyncWebServer to pause the request and get a AsyncWebServerRequestPtr to be able to access the request later. + // The AsyncWebServerRequestPtr is the ONLY object authorized to leave the scope of the request handler. + // The Middleware chain will continue to run until the end after this handler exit, but the request will be paused and will not + // be sent to the client until send() is called later. + Serial.printf("Pausing request...\n"); + AsyncWebServerRequestPtr requestPtr = request->pause(); + + // start our long operation... + startLongRunningOperation(std::move(requestPtr)); + }); + + server.begin(); +} + +static uint32_t lastTime = 0; + +void loop() { + if (millis() - lastTime >= 1000) { + +#ifdef ESP32 + Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + std::lock_guard lock(longRunningOperationsMutex); +#endif + + // process all long running operations + longRunningOperations.remove_if([](const std::unique_ptr &op) { + return processLongRunningOperation(op.get()); + }); + + lastTime = millis(); + } +} diff --git a/watering/lib/ESPAsyncWebServer/examples/ResumableDownload/ResumableDownload.ino b/watering/lib/ESPAsyncWebServer/examples/ResumableDownload/ResumableDownload.ino new file mode 100644 index 0000000..373ca24 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/ResumableDownload/ResumableDownload.ino @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Make sure resumable downloads can be implemented (HEAD request / response and Range header) +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + /* + ❯ curl -I -X HEAD http://192.168.4.1/download + HTTP/1.1 200 OK + Content-Length: 1024 + Content-Type: application/octet-stream + Connection: close + Accept-Ranges: bytes + */ + // Ref: https://github.com/mathieucarbou/ESPAsyncWebServer/pull/80 + server.on("/download", HTTP_HEAD | HTTP_GET, [](AsyncWebServerRequest *request) { + if (request->method() == HTTP_HEAD) { + AsyncWebServerResponse *response = request->beginResponse(200, "application/octet-stream"); + response->addHeader(asyncsrv::T_Accept_Ranges, "bytes"); + response->addHeader(asyncsrv::T_Content_Length, 10); + response->setContentLength(1024); // make sure we can overrides previously set content length + response->addHeader(asyncsrv::T_Content_Type, "foo"); + response->setContentType("application/octet-stream"); // make sure we can overrides previously set content type + // ... + request->send(response); + } else { + // ... + } + }); + + server.begin(); +} + +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Rewrite/Rewrite.ino b/watering/lib/ESPAsyncWebServer/examples/Rewrite/Rewrite.ino new file mode 100644 index 0000000..6981b11 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Rewrite/Rewrite.ino @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to rewrite URLs +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/index.txt + server.on("/index.txt", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + }); + + // curl -v http://192.168.4.1/index.txt + server.on("/index.html", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/html", "

Hello, world!

"); + }); + + // curl -v http://192.168.4.1/ + server.rewrite("/", "/index.html"); + server.rewrite("/index.txt", "/index.html"); // will hide the .txt file + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/ServerSentEvents/ServerSentEvents.ino b/watering/lib/ESPAsyncWebServer/examples/ServerSentEvents/ServerSentEvents.ino new file mode 100644 index 0000000..91e2c1d --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/ServerSentEvents/ServerSentEvents.ino @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// SSE example +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static const char *htmlContent PROGMEM = R"( + + + + Server-Sent Events + + + +

Open your browser console!

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +static AsyncWebServer server(80); +static AsyncEventSource events("/events"); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + events.onConnect([](AsyncEventSourceClient *client) { + Serial.printf("SSE Client connected! ID: %" PRIu32 "\n", client->lastId()); + client->send("hello!", NULL, millis(), 1000); + }); + + events.onDisconnect([](AsyncEventSourceClient *client) { + Serial.printf("SSE Client disconnected! ID: %" PRIu32 "\n", client->lastId()); + }); + + server.addHandler(&events); + + server.begin(); +} + +static uint32_t lastSSE = 0; +static uint32_t deltaSSE = 3000; + +static uint32_t lastHeap = 0; + +void loop() { + uint32_t now = millis(); + if (now - lastSSE >= deltaSSE) { + events.send(String("ping-") + now, "heartbeat", now); + lastSSE = millis(); + } + +#ifdef ESP32 + if (now - lastHeap >= 2000) { + Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + lastHeap = now; + } +#endif +} diff --git a/watering/lib/ESPAsyncWebServer/examples/ServerSentEvents_PR156/ServerSentEvents_PR156.ino b/watering/lib/ESPAsyncWebServer/examples/ServerSentEvents_PR156/ServerSentEvents_PR156.ino new file mode 100644 index 0000000..928c9ad --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/ServerSentEvents_PR156/ServerSentEvents_PR156.ino @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// SSE example +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static const char *htmlContent PROGMEM = R"( + + + + Server-Sent Events + + + +

Open your browser console!

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +static AsyncWebServer server(80); +static AsyncEventSource events("/events"); + +static volatile size_t connectionCount = 0; +static volatile uint32_t timestampConnected = 0; +static constexpr uint32_t timeoutClose = 15000; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + events.onConnect([](AsyncEventSourceClient *client) { + /** + * @brief: Purpose for a test case: count() function + * Task watchdog shall be triggered due to a self-deadlock by mutex handling of the AsyncEventSource. + * + * E (61642) task_wdt: Task watchdog got triggered. The following tasks did not reset the watchdog in time: + * E (61642) task_wdt: - async_tcp (CPU 0/1) + * + * Resolve: using recursive_mutex insteads of mutex. + */ + connectionCount = events.count(); + + timestampConnected = millis(); + Serial.printf("SSE Client connected! ID: %" PRIu32 "\n", client->lastId()); + client->send("hello!", NULL, millis(), 1000); + Serial.printf("Number of connected clients: %u\n", connectionCount); + }); + + events.onDisconnect([](AsyncEventSourceClient *client) { + connectionCount = events.count(); + Serial.printf("SSE Client disconnected! ID: %" PRIu32 "\n", client->lastId()); + Serial.printf("Number of connected clients: %u\n", connectionCount); + }); + + server.addHandler(&events); + + server.begin(); +} + +static constexpr uint32_t deltaSSE = 3000; +static uint32_t lastSSE = 0; +static uint32_t lastHeap = 0; + +void loop() { + uint32_t now = millis(); + if (connectionCount > 0) { + if (now - lastSSE >= deltaSSE) { + events.send(String("ping-") + now, "heartbeat", now); + lastSSE = millis(); + } + + /** + * @brief: Purpose for a test case: close() function + * Task watchdog shall be triggered due to a self-deadlock by mutex handling of the AsyncEventSource. + * + * E (61642) task_wdt: Task watchdog got triggered. The following tasks did not reset the watchdog in time: + * E (61642) task_wdt: - async_tcp (CPU 0/1) + * + * Resolve: using recursive_mutex insteads of mutex. + */ + if (now - timestampConnected >= timeoutClose) { + Serial.printf("SSE Clients close\n"); + events.close(); + } + } + +#ifdef ESP32 + if (now - lastHeap >= 2000) { + Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + lastHeap = now; + } +#endif +} diff --git a/watering/lib/ESPAsyncWebServer/examples/ServerState/ServerState.ino b/watering/lib/ESPAsyncWebServer/examples/ServerState/ServerState.ino new file mode 100644 index 0000000..8501758 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/ServerState/ServerState.ino @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Server state example +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server1(80); +static AsyncWebServer server2(80); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // server state returns one of the tcp_state enum values: + // enum tcp_state { + // CLOSED = 0, + // LISTEN = 1, + // SYN_SENT = 2, + // SYN_RCVD = 3, + // ESTABLISHED = 4, + // FIN_WAIT_1 = 5, + // FIN_WAIT_2 = 6, + // CLOSE_WAIT = 7, + // CLOSING = 8, + // LAST_ACK = 9, + // TIME_WAIT = 10 + // }; + + assert(server1.state() == tcp_state::CLOSED); + assert(server2.state() == tcp_state::CLOSED); + + server1.begin(); + + assert(server1.state() == tcp_state::LISTEN); + assert(server2.state() == tcp_state::CLOSED); + + server2.begin(); + + assert(server1.state() == tcp_state::LISTEN); + assert(server2.state() == tcp_state::CLOSED); + + Serial.println("Done!"); +} + +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/SkipServerMiddleware/SkipServerMiddleware.ino b/watering/lib/ESPAsyncWebServer/examples/SkipServerMiddleware/SkipServerMiddleware.ino new file mode 100644 index 0000000..d232c71 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/SkipServerMiddleware/SkipServerMiddleware.ino @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Authentication and authorization middlewares +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +static AsyncAuthenticationMiddleware basicAuth; +static AsyncLoggingMiddleware logging; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // basic authentication + basicAuth.setUsername("admin"); + basicAuth.setPassword("admin"); + basicAuth.setRealm("MyApp"); + basicAuth.setAuthFailureMessage("Authentication failed"); + basicAuth.setAuthType(AsyncAuthType::AUTH_BASIC); + basicAuth.generateHash(); // precompute hash (optional but recommended) + + // logging middleware + logging.setEnabled(true); + logging.setOutput(Serial); + + // we apply auth middleware to the server globally + server.addMiddleware(&basicAuth); + + // protected endpoint: requires basic authentication + // curl -v -u admin:admin http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world!"); + }); + + // we skip all global middleware from the catchall handler + server.catchAllHandler().skipServerMiddlewares(); + // we apply a specific middleware to the catchall handler only to log requests without a handler defined + server.catchAllHandler().addMiddleware(&logging); + + // standard 404 handler: will display the request in the console i na curl-like style + // curl -v -H "Foo: Bar" http://192.168.4.1/foo + server.onNotFound([](AsyncWebServerRequest *request) { + request->send(404, "text/plain", "Not found"); + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/SlowChunkResponse/SlowChunkResponse.ino b/watering/lib/ESPAsyncWebServer/examples/SlowChunkResponse/SlowChunkResponse.ino new file mode 100644 index 0000000..bbf70b6 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/SlowChunkResponse/SlowChunkResponse.ino @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Simulate a slow response in a chunk response (like file download from SD Card) +// poll events will be throttled. +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); +static constexpr char characters[] = "0123456789ABCDEF"; +static size_t charactersIndex = 0; + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + // IMPORTANT - DO NOT WRITE SUCH CODE IN PRODUCTON ! + // + // This example simulates the slowdown that can happen when: + // - downloading a huge file from sdcard + // - doing some file listing on SDCard because it is horribly slow to get a file listing with file stats on SDCard. + // So in both cases, ESP would deadlock or TWDT would trigger. + // + // This example simulats that by slowing down the chunk callback: + // - d=2000 is the delay in ms in the callback + // - l=10000 is the length of the response + // + // time curl -N -v -G -d 'd=2000' -d 'l=10000' http://192.168.4.1/slow.html --output - + // + server.on("/slow.html", HTTP_GET, [](AsyncWebServerRequest *request) { + uint32_t d = request->getParam("d")->value().toInt(); + uint32_t l = request->getParam("l")->value().toInt(); + Serial.printf("d = %" PRIu32 ", l = %" PRIu32 "\n", d, l); + AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [d, l](uint8_t *buffer, size_t maxLen, size_t index) -> size_t { + Serial.printf("%u\n", index); + // finished ? + if (index >= l) { + return 0; + } + + // slow down the task to simulate some heavy processing, like SD card reading + delay(d); + + memset(buffer, characters[charactersIndex], 256); + charactersIndex = (charactersIndex + 1) % sizeof(characters); + return 256; + }); + + request->send(response); + }); + + server.begin(); +} + +static uint32_t lastHeap = 0; + +void loop() { +#ifdef ESP32 + uint32_t now = millis(); + if (now - lastHeap >= 2000) { + Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + lastHeap = now; + } +#endif +} diff --git a/watering/lib/ESPAsyncWebServer/examples/StaticFile/StaticFile.ino b/watering/lib/ESPAsyncWebServer/examples/StaticFile/StaticFile.ino new file mode 100644 index 0000000..331f287 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/StaticFile/StaticFile.ino @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to serve a static file +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include +#include + +static AsyncWebServer server(80); + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + +#ifdef ESP32 + LittleFS.begin(true); +#else + LittleFS.begin(); +#endif + + { + File f = LittleFS.open("/index.html", "w"); + assert(f); + f.print(htmlContent); + f.close(); + } + + LittleFS.mkdir("/files"); + + { + File f = LittleFS.open("/files/a.txt", "w"); + assert(f); + f.print("Hello from a.txt"); + f.close(); + } + + { + File f = LittleFS.open("/files/b.txt", "w"); + assert(f); + f.print("Hello from b.txt"); + f.close(); + } + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->redirect("/index.html"); + }); + + // curl -v http://192.168.4.1/index.html + server.serveStatic("/index.html", LittleFS, "/index.html"); + + // Example to serve a directory content + // curl -v http://192.168.4.1/base/ => serves a.txt + // curl -v http://192.168.4.1/base/a.txt => serves a.txt + // curl -v http://192.168.4.1/base/b.txt => serves b.txt + server.serveStatic("/base", LittleFS, "/files").setDefaultFile("a.txt"); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Templates/Templates.ino b/watering/lib/ESPAsyncWebServer/examples/Templates/Templates.ino new file mode 100644 index 0000000..edc02c2 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Templates/Templates.ino @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to serve a static and dynamic template +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include +#include + +static AsyncWebServer server(80); + +static const char *htmlContent PROGMEM = R"( + + + +

Hello, %USER%

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + +#ifdef ESP32 + LittleFS.begin(true); +#else + LittleFS.begin(); +#endif + + { + File f = LittleFS.open("/template.html", "w"); + assert(f); + f.print(htmlContent); + f.close(); + } + + // Serve the static template file + // + // curl -v http://192.168.4.1/template.html + server.serveStatic("/template.html", LittleFS, "/template.html"); + + // Serve the static template with a template processor + // + // ServeStatic static is used to serve static output which never changes over time. + // This special endpoints automatically adds caching headers. + // If a template processor is used, it must ensure that the outputted content will always be the same over time and never changes. + // Otherwise, do not use serveStatic. + // Example below: IP never changes. + // + // curl -v http://192.168.4.1/index.html + server.serveStatic("/index.html", LittleFS, "/template.html").setTemplateProcessor([](const String &var) -> String { + if (var == "USER") { + return "Bob"; + } + return emptyString; + }); + + // Serve a template with dynamic content + // + // to serve a template with dynamic content (output changes over time), use normal + // Example below: content changes over tinme do not use serveStatic. + // + // curl -v http://192.168.4.1/dynamic.html + server.on("/dynamic.html", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(LittleFS, "/template.html", "text/html", false, [](const String &var) -> String { + if (var == "USER") { + return String("Bob ") + millis(); + } + return emptyString; + }); + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/Upload/Upload.ino b/watering/lib/ESPAsyncWebServer/examples/Upload/Upload.ino new file mode 100644 index 0000000..ceac47d --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/Upload/Upload.ino @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Demo text, binary and file upload +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include +#include +#include + +static AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + + if (!LittleFS.begin()) { + LittleFS.format(); + LittleFS.begin(); + } + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // 1. Generate a Lorem_ipsum.txt file of about 20KB of text + // + // 3. Run: curl -v -F "data=@Lorem_ipsum.txt" http://192.168.4.1/upload/text + // + server.on( + "/upload/text", HTTP_POST, + [](AsyncWebServerRequest *request) { + if (!request->_tempObject) { + return request->send(400, "text/plain", "Nothing uploaded"); + } + StreamString *buffer = reinterpret_cast(request->_tempObject); + Serial.printf("Text uploaded:\n%s\n", buffer->c_str()); + delete buffer; + request->_tempObject = nullptr; + request->send(200, "text/plain", "OK"); + }, + [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) { + Serial.printf("Upload[%s]: start=%u, len=%u, final=%d\n", filename.c_str(), index, len, final); + + if (!index) { + // first pass + StreamString *buffer = new StreamString(); + size_t size = std::max(4094l, request->header("Content-Length").toInt()); + Serial.printf("Allocating string buffer of %u bytes\n", size); + if (!buffer->reserve(size)) { + delete buffer; + request->abort(); + } + request->_tempObject = buffer; + } + + if (len) { + reinterpret_cast(request->_tempObject)->write(data, len); + } + } + ); + + // 1. Generate a Lorem_ipsum.txt file of about 20KB of text + // + // 3. Run: curl -v -F "data=@Lorem_ipsum.txt" http://192.168.4.1/upload/file + // + server.on( + "/upload/file", HTTP_POST, + [](AsyncWebServerRequest *request) { + if (request->getResponse()) { + // 400 File not available for writing + return; + } + + if (!LittleFS.exists("/my_file.txt")) { + return request->send(400, "text/plain", "Nothing uploaded"); + } + + // sends back the uploaded file + request->send(LittleFS, "/my_file.txt", "text/plain"); + }, + [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) { + Serial.printf("Upload[%s]: start=%u, len=%u, final=%d\n", filename.c_str(), index, len, final); + + if (!index) { + request->_tempFile = LittleFS.open("/my_file.txt", "w"); + + if (!request->_tempFile) { + request->send(400, "text/plain", "File not available for writing"); + } + } + if (len) { + request->_tempFile.write(data, len); + } + if (final) { + request->_tempFile.close(); + } + } + ); + + // + // Upload a binary file: curl -v -F "data=@file.mp3" http://192.168.4.1/upload/binary + // + server.on( + "/upload/binary", HTTP_POST, + [](AsyncWebServerRequest *request) { + // response already set ? + if (request->getResponse()) { + // 400 No Content-Length + return; + } + + // nothing uploaded ? + if (!request->_tempObject) { + return request->send(400, "text/plain", "Nothing uploaded"); + } + + uint8_t *buffer = reinterpret_cast(request->_tempObject); + // process the buffer + + delete buffer; + request->_tempObject = nullptr; + + request->send(200, "text/plain", "OK"); + }, + [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) { + Serial.printf("Upload[%s]: start=%u, len=%u, final=%d\n", filename.c_str(), index, len, final); + + // first pass ? + if (!index) { + size_t size = request->header("Content-Length").toInt(); + if (!size) { + request->send(400, "text/plain", "No Content-Length"); + } else { + Serial.printf("Allocating buffer of %u bytes\n", size); + uint8_t *buffer = new (std::nothrow) uint8_t[size]; + if (!buffer) { + // not enough memory + request->abort(); + } else { + request->_tempObject = buffer; + } + } + } + + if (len) { + memcpy(reinterpret_cast(request->_tempObject) + index, data, len); + } + } + ); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/examples/WebSocket/WebSocket.ino b/watering/lib/ESPAsyncWebServer/examples/WebSocket/WebSocket.ino new file mode 100644 index 0000000..8c5e5a5 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/WebSocket/WebSocket.ino @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// WebSocket example +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); +static AsyncWebSocket ws("/ws"); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // + // Run in terminal 1: websocat ws://192.168.4.1/ws => should stream data + // Run in terminal 2: websocat ws://192.168.4.1/ws => should stream data + // Run in terminal 3: websocat ws://192.168.4.1/ws => should fail: + // + // To send a message to the WebSocket server: + // + // echo "Hello!" | websocat ws://192.168.4.1/ws + // + ws.onEvent([](AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { + (void)len; + + if (type == WS_EVT_CONNECT) { + ws.textAll("new client connected"); + Serial.println("ws connect"); + client->setCloseClientOnQueueFull(false); + client->ping(); + + } else if (type == WS_EVT_DISCONNECT) { + ws.textAll("client disconnected"); + Serial.println("ws disconnect"); + + } else if (type == WS_EVT_ERROR) { + Serial.println("ws error"); + + } else if (type == WS_EVT_PONG) { + Serial.println("ws pong"); + + } else if (type == WS_EVT_DATA) { + AwsFrameInfo *info = (AwsFrameInfo *)arg; + Serial.printf("index: %" PRIu64 ", len: %" PRIu64 ", final: %" PRIu8 ", opcode: %" PRIu8 "\n", info->index, info->len, info->final, info->opcode); + String msg = ""; + if (info->final && info->index == 0 && info->len == len) { + if (info->opcode == WS_TEXT) { + data[len] = 0; + Serial.printf("ws text: %s\n", (char *)data); + } + } + } + }); + + // shows how to prevent a third WS client to connect + server.addHandler(&ws).addMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + // ws.count() is the current count of WS clients: this one is trying to upgrade its HTTP connection + if (ws.count() > 1) { + // if we have 2 clients or more, prevent the next one to connect + request->send(503, "text/plain", "Server is busy"); + } else { + // process next middleware and at the end the handler + next(); + } + }); + + server.addHandler(&ws); + + server.begin(); +} + +static uint32_t lastWS = 0; +static uint32_t deltaWS = 100; + +static uint32_t lastHeap = 0; + +void loop() { + uint32_t now = millis(); + + if (now - lastWS >= deltaWS) { + ws.printfAll("kp%.4f", (10.0 / 3.0)); + lastWS = millis(); + } + + if (now - lastHeap >= 2000) { + Serial.printf("Connected clients: %u / %u total\n", ws.count(), ws.getClients().size()); + + // this can be called to also set a soft limit on the number of connected clients + ws.cleanupClients(2); // no more than 2 clients + +#ifdef ESP32 + Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); +#endif + lastHeap = now; + } +} diff --git a/watering/lib/ESPAsyncWebServer/examples/WebSocketEasy/WebSocketEasy.ino b/watering/lib/ESPAsyncWebServer/examples/WebSocketEasy/WebSocketEasy.ino new file mode 100644 index 0000000..12b03ce --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/examples/WebSocketEasy/WebSocketEasy.ino @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// WebSocket example using the easy to use AsyncWebSocketMessageHandler handler that only supports unfragmented messages +// + +#include +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#endif + +#include + +static AsyncWebServer server(80); + +// create an easy-to-use handler +static AsyncWebSocketMessageHandler wsHandler; + +// add it to the websocket server +static AsyncWebSocket ws("/ws", wsHandler.eventHandler()); + +// alternatively you can do as usual: +// +// static AsyncWebSocket ws("/ws"); +// ws.onEvent(wsHandler.eventHandler()); + +static const char *htmlContent PROGMEM = R"( + + + + WebSocket + + +

WebSocket Example

+ <>Open your browser console!

+ + + + + + )"; +static const size_t htmlContentLength = strlen_P(htmlContent); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // serves root html page + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/html", (const uint8_t *)htmlContent, htmlContentLength); + }); + + wsHandler.onConnect([](AsyncWebSocket *server, AsyncWebSocketClient *client) { + Serial.printf("Client %" PRIu32 " connected\n", client->id()); + server->textAll("New client: " + String(client->id())); + }); + + wsHandler.onDisconnect([](AsyncWebSocket *server, uint32_t clientId) { + Serial.printf("Client %" PRIu32 " disconnected\n", clientId); + server->textAll("Client " + String(clientId) + " disconnected"); + }); + + wsHandler.onError([](AsyncWebSocket *server, AsyncWebSocketClient *client, uint16_t errorCode, const char *reason, size_t len) { + Serial.printf("Client %" PRIu32 " error: %" PRIu16 ": %s\n", client->id(), errorCode, reason); + }); + + wsHandler.onMessage([](AsyncWebSocket *server, AsyncWebSocketClient *client, const uint8_t *data, size_t len) { + Serial.printf("Client %" PRIu32 " data: %s\n", client->id(), (const char *)data); + }); + + wsHandler.onFragment([](AsyncWebSocket *server, AsyncWebSocketClient *client, const AwsFrameInfo *frameInfo, const uint8_t *data, size_t len) { + Serial.printf("Client %" PRIu32 " fragment %" PRIu32 ": %s\n", client->id(), frameInfo->num, (const char *)data); + }); + + server.addHandler(&ws); + server.begin(); +} + +static uint32_t lastWS = 0; +static uint32_t deltaWS = 2000; + +void loop() { + uint32_t now = millis(); + + if (now - lastWS >= deltaWS) { + ws.cleanupClients(); + ws.printfAll("now: %" PRIu32 "\n", now); + lastWS = millis(); +#ifdef ESP32 + Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); +#endif + } +} diff --git a/watering/lib/ESPAsyncWebServer/idf_component.yml b/watering/lib/ESPAsyncWebServer/idf_component.yml new file mode 100644 index 0000000..c52a097 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component.yml @@ -0,0 +1,37 @@ +description: "Async Web Server for ESP32 Arduino" +url: "https://github.com/ESP32Async/ESPAsyncWebServer" +license: "LGPL-3.0-or-later" +tags: + - arduino +files: + exclude: + - "idf_component_examples/" + - "idf_component_examples/**/*" + - "docs/" + - "docs/*" + - "examples/" + - "examples/**/*" + - ".gitignore" + - ".clang-format" + - ".gitpod.Dockerfile" + - ".gitpod.yml" + - ".codespellrc" + - ".editorconfig" + - ".pre-commit-config.yaml" + - "CODE_OF_CONDUCT.md" + - "library.json" + - "library.properties" + - "partitions-4MB.csv" + - "platformio.ini" + - "pre-commit.requirements.txt" +dependencies: + esp32async/asynctcp: + version: "^3.3.8" + require: public + bblanchon/arduinojson: + version: "^7.4.1" + require: public +examples: + - path: ./idf_component_examples/catchall + - path: ./idf_component_examples/serversentevents + - path: ./idf_component_examples/websocket diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/CMakeLists.txt b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/CMakeLists.txt new file mode 100644 index 0000000..664d458 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/CMakeLists.txt @@ -0,0 +1,8 @@ +# For more information about build system see +# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(main) diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/README.md b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/README.md new file mode 100644 index 0000000..1e09f91 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/README.md @@ -0,0 +1 @@ +### Basic example to show how to catch all requests and send a 404 Not Found response diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/CMakeLists.txt b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/CMakeLists.txt new file mode 100644 index 0000000..9eb7ec4 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "main.cpp" + INCLUDE_DIRS ".") diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/idf_component.yml b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/idf_component.yml new file mode 100644 index 0000000..e2d1c65 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/idf_component.yml @@ -0,0 +1,6 @@ +## IDF Component Manager Manifest File +dependencies: + esp32async/espasyncwebserver: + version: "*" + override_path: "../../../" + pre_release: true diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/main.cpp b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/main.cpp new file mode 100644 index 0000000..c491588 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/main/main.cpp @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// Shows how to catch all requests and send a 404 Not Found response +// + +#include +#include +#include + +#include + +static AsyncWebServer server(80); + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + // catch any request, and send a 404 Not Found response + // except for /game_log which is handled by onRequestBody + // + // curl -v http://192.168.4.1/foo + // + server.onNotFound([](AsyncWebServerRequest *request) { + if (request->url() == "/game_log") { + return; // response object already created by onRequestBody + } + + request->send(404, "text/plain", "Not found"); + }); + + // See: https://github.com/ESP32Async/ESPAsyncWebServer/issues/6 + // catch any POST request and send a 200 OK response + // + // curl -v -X POST http://192.168.4.1/game_log -H "Content-Type: application/json" -d '{"game": "test"}' + // + server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { + if (request->url() == "/game_log") { + request->send(200, "application/json", "{\"status\":\"OK\"}"); + } + // note that there is no else here: the goal is only to prepare a response based on some body content + // onNotFound will always be called after this, and will not override the response object if `/game_log` is requested + }); + + server.begin(); +} + +// not needed +void loop() { + delay(100); +} diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/sdkconfig.defaults b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/sdkconfig.defaults new file mode 100644 index 0000000..bb72365 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/catchall/sdkconfig.defaults @@ -0,0 +1,12 @@ +# +# Arduino ESP32 +# +CONFIG_AUTOSTART_ARDUINO=y +# end of Arduino ESP32 + +# +# FREERTOS +# +CONFIG_FREERTOS_HZ=1000 +# end of FREERTOS +# end of Component config diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/CMakeLists.txt b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/CMakeLists.txt new file mode 100644 index 0000000..664d458 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/CMakeLists.txt @@ -0,0 +1,8 @@ +# For more information about build system see +# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(main) diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/README.md b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/README.md new file mode 100644 index 0000000..ea21ac9 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/README.md @@ -0,0 +1 @@ +### Basic example to show how to use ServerSentEvents diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/CMakeLists.txt b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/CMakeLists.txt new file mode 100644 index 0000000..9eb7ec4 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "main.cpp" + INCLUDE_DIRS ".") diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/idf_component.yml b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/idf_component.yml new file mode 100644 index 0000000..e2d1c65 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/idf_component.yml @@ -0,0 +1,6 @@ +## IDF Component Manager Manifest File +dependencies: + esp32async/espasyncwebserver: + version: "*" + override_path: "../../../" + pre_release: true diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/main.cpp b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/main.cpp new file mode 100644 index 0000000..59a1f59 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/main/main.cpp @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// SSE example +// + +#include +#include +#include + +#include + +static const char *htmlContent PROGMEM = R"( + + + + Server-Sent Events + + + +

Open your browser console!

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +static AsyncWebServer server(80); +static AsyncEventSource events("/events"); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // curl -v http://192.168.4.1/ + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + // need to cast to uint8_t* + // if you do not, the const char* will be copied in a temporary String buffer + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + events.onConnect([](AsyncEventSourceClient *client) { + Serial.printf("SSE Client connected! ID: %" PRIu32 "\n", client->lastId()); + client->send("hello!", NULL, millis(), 1000); + }); + + events.onDisconnect([](AsyncEventSourceClient *client) { + Serial.printf("SSE Client disconnected! ID: %" PRIu32 "\n", client->lastId()); + }); + + server.addHandler(&events); + + server.begin(); +} + +static uint32_t lastSSE = 0; +static uint32_t deltaSSE = 3000; + +static uint32_t lastHeap = 0; + +void loop() { + uint32_t now = millis(); + if (now - lastSSE >= deltaSSE) { + events.send(String("ping-") + now, "heartbeat", now); + lastSSE = millis(); + } + + if (now - lastHeap >= 2000) { + Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + lastHeap = now; + } +} diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/sdkconfig.defaults b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/sdkconfig.defaults new file mode 100644 index 0000000..bb72365 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/serversentevents/sdkconfig.defaults @@ -0,0 +1,12 @@ +# +# Arduino ESP32 +# +CONFIG_AUTOSTART_ARDUINO=y +# end of Arduino ESP32 + +# +# FREERTOS +# +CONFIG_FREERTOS_HZ=1000 +# end of FREERTOS +# end of Component config diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/CMakeLists.txt b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/CMakeLists.txt new file mode 100644 index 0000000..664d458 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/CMakeLists.txt @@ -0,0 +1,8 @@ +# For more information about build system see +# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(main) diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/README.md b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/README.md new file mode 100644 index 0000000..3741fc3 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/README.md @@ -0,0 +1 @@ +### Basic example to show how to use WebSockets diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/CMakeLists.txt b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/CMakeLists.txt new file mode 100644 index 0000000..9eb7ec4 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "main.cpp" + INCLUDE_DIRS ".") diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/idf_component.yml b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/idf_component.yml new file mode 100644 index 0000000..e2d1c65 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/idf_component.yml @@ -0,0 +1,6 @@ +## IDF Component Manager Manifest File +dependencies: + esp32async/espasyncwebserver: + version: "*" + override_path: "../../../" + pre_release: true diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/main.cpp b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/main.cpp new file mode 100644 index 0000000..843d1a4 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/main/main.cpp @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// WebSocket example +// + +#include +#include +#include + +#include + +static AsyncWebServer server(80); +static AsyncWebSocket ws("/ws"); + +void setup() { + Serial.begin(115200); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); +#endif + + // + // Run in terminal 1: websocat ws://192.168.4.1/ws => should stream data + // Run in terminal 2: websocat ws://192.168.4.1/ws => should stream data + // Run in terminal 3: websocat ws://192.168.4.1/ws => should fail: + // + // To send a message to the WebSocket server: + // + // echo "Hello!" | websocat ws://192.168.4.1/ws + // + ws.onEvent([](AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { + (void)len; + + if (type == WS_EVT_CONNECT) { + ws.textAll("new client connected"); + Serial.println("ws connect"); + client->setCloseClientOnQueueFull(false); + client->ping(); + + } else if (type == WS_EVT_DISCONNECT) { + ws.textAll("client disconnected"); + Serial.println("ws disconnect"); + + } else if (type == WS_EVT_ERROR) { + Serial.println("ws error"); + + } else if (type == WS_EVT_PONG) { + Serial.println("ws pong"); + + } else if (type == WS_EVT_DATA) { + AwsFrameInfo *info = (AwsFrameInfo *)arg; + String msg = ""; + if (info->final && info->index == 0 && info->len == len) { + if (info->opcode == WS_TEXT) { + data[len] = 0; + Serial.printf("ws text: %s\n", (char *)data); + } + } + } + }); + + // shows how to prevent a third WS client to connect + server.addHandler(&ws).addMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + // ws.count() is the current count of WS clients: this one is trying to upgrade its HTTP connection + if (ws.count() > 1) { + // if we have 2 clients or more, prevent the next one to connect + request->send(503, "text/plain", "Server is busy"); + } else { + // process next middleware and at the end the handler + next(); + } + }); + + server.addHandler(&ws); + + server.begin(); +} + +static uint32_t lastWS = 0; +static uint32_t deltaWS = 100; + +static uint32_t lastHeap = 0; + +void loop() { + uint32_t now = millis(); + + if (now - lastWS >= deltaWS) { + ws.printfAll("kp%.4f", (10.0 / 3.0)); + lastWS = millis(); + } + + if (now - lastHeap >= 2000) { + // cleanup disconnected clients or too many clients + ws.cleanupClients(); + + Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + lastHeap = now; + } +} diff --git a/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/sdkconfig.defaults b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/sdkconfig.defaults new file mode 100644 index 0000000..bb72365 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/idf_component_examples/websocket/sdkconfig.defaults @@ -0,0 +1,12 @@ +# +# Arduino ESP32 +# +CONFIG_AUTOSTART_ARDUINO=y +# end of Arduino ESP32 + +# +# FREERTOS +# +CONFIG_FREERTOS_HZ=1000 +# end of FREERTOS +# end of Component config diff --git a/watering/lib/ESPAsyncWebServer/library.json b/watering/lib/ESPAsyncWebServer/library.json new file mode 100644 index 0000000..e7ca989 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/library.json @@ -0,0 +1,33 @@ +{ + "name": "ESPAsyncWebServer", + "version": "3.7.6", + "description": "Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040. Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc.", + "keywords": "http,async,websocket,webserver", + "homepage": "https://github.com/ESP32Async/ESPAsyncWebServer", + "repository": { + "type": "git", + "url": "https://github.com/ESP32Async/ESPAsyncWebServer.git" + }, + "authors": + { + "name": "ESP32Async", + "maintainer": true + }, + "license": "LGPL-3.0", + "frameworks": "arduino", + "platforms": [ + "espressif32", + "espressif8266", + "raspberrypi" + ], + "export": { + "include": [ + "examples", + "src", + "library.json", + "library.properties", + "LICENSE", + "README.md" + ] + } +} diff --git a/watering/lib/ESPAsyncWebServer/library.properties b/watering/lib/ESPAsyncWebServer/library.properties new file mode 100644 index 0000000..ab8dea4 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/library.properties @@ -0,0 +1,11 @@ +name=ESP Async WebServer +includes=ESPAsyncWebServer.h +version=3.7.6 +author=ESP32Async +maintainer=ESP32Async +sentence=Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040 +paragraph=Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc +category=Other +url=https://github.com/ESP32Async/ESPAsyncWebServer +architectures=* +license=LGPL-3.0 diff --git a/watering/lib/ESPAsyncWebServer/partitions-4MB.csv b/watering/lib/ESPAsyncWebServer/partitions-4MB.csv new file mode 100644 index 0000000..75efc35 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/partitions-4MB.csv @@ -0,0 +1,7 @@ +# Name ,Type ,SubType ,Offset ,Size ,Flags +nvs ,data ,nvs ,36K ,20K , +otadata ,data ,ota ,56K ,8K , +app0 ,app ,ota_0 ,64K ,1856K , +app1 ,app ,ota_1 ,1920K ,1856K , +spiffs ,data ,spiffs ,3776K ,256K , +coredump ,data ,coredump ,4032K ,64K , diff --git a/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/.gitignore b/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/.gitignore new file mode 100644 index 0000000..6c42fe0 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/.gitignore @@ -0,0 +1,11 @@ +.DS_Store +.lh +/.pio +/.vscode +/logs + +/sdkconfig.* +/CMakeLists.txt +/dependencies.lock +/.dummy +/managed_components diff --git a/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/platformio.ini b/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/platformio.ini new file mode 100644 index 0000000..08d7a50 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/platformio.ini @@ -0,0 +1,26 @@ +[env] +framework = arduino +platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20/platform-espressif32.zip +build_flags = + -Og + -Wall -Wextra + -Wno-unused-parameter + -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_VERBOSE + ; -D CONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 + ; -D CONFIG_ASYNC_TCP_PRIORITY=10 + -D CONFIG_ASYNC_TCP_QUEUE_SIZE=128 + -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 + -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 +upload_protocol = esptool +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder, log2file +lib_compat_mode = strict +lib_ldf_mode = chain +lib_deps = + ESP32Async/AsyncTCP @ 3.3.8 + ESP32Async/ESpAsyncWebServer @ 3.7.0 + +custom_sdkconfig = CONFIG_LWIP_MAX_ACTIVE_TCP=32 + +[env:esp32dev] +board = esp32dev diff --git a/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/src/main.cpp b/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/src/main.cpp new file mode 100644 index 0000000..752c402 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/pioarduino_examples/IncreaseMaxSockets/src/main.cpp @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +// +// This example demonstrates how to increase the maximum number of active TCP connections +// +// in platformo.ini: +// +// Use hybrid compilation to set the maximum number of active TCP connections +// +// custom_sdkconfig = CONFIG_LWIP_MAX_ACTIVE_TCP=32 +// +// and increase the queue stack size +// +// -D CONFIG_ASYNC_TCP_QUEUE_SIZE=128 +// + +#include +#include +#include +#include + +static const char *htmlContent PROGMEM = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +static const size_t htmlContentLength = strlen_P(htmlContent); + +static AsyncWebServer server(80); +static AsyncEventSource events("/events"); + +static volatile size_t requests = 0; + +void setup() { + Serial.begin(115200); + + Serial.println("============================"); + Serial.printf("CONFIG_LWIP_MAX_ACTIVE_TCP %d\n", CONFIG_LWIP_MAX_ACTIVE_TCP); + Serial.println("============================"); + + WiFi.mode(WIFI_STA); + WiFi.begin("IoT", ""); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.println("Connecting to WiFi..."); + } + + // HTTP endpoint + // + // > autocannon -c 32 -d 20 -t 30 --renderStatusCodes http://192.168.125.146/ + // + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + requests++; + request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength); + }); + + // SSS endpoint + // + // launch 32 concurrent workers for 30 seconds + // > for i in {1..32}; do ( count=$(gtimeout 30 curl -s -N -H "Accept: text/event-stream" http://192.168.125.146/events 2>&1 | grep -c "^data:"); echo "Total: $count events, $(echo "$count / 4" | bc -l) events / second" ) & done; + // + server.addHandler(&events); + + server.begin(); +} + +static uint32_t lastSSE = 0; +static uint32_t deltaSSE = 10; + +static uint32_t lastHeap = 0; + +void loop() { + uint32_t now = millis(); + if (now - lastSSE >= deltaSSE) { + events.send(String("ping-") + now, "heartbeat", now); + lastSSE = millis(); + } + +#ifdef ESP32 + if (now - lastHeap >= 2000) { + Serial.printf("Uptime: %3lu s, requests: %3u, Free heap: %" PRIu32 "\n", millis() / 1000, requests, ESP.getFreeHeap()); + lastHeap = now; + } +#endif +} diff --git a/watering/lib/ESPAsyncWebServer/platformio.ini b/watering/lib/ESPAsyncWebServer/platformio.ini new file mode 100644 index 0000000..757b371 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/platformio.ini @@ -0,0 +1,155 @@ +[platformio] +default_envs = arduino-2, arduino-3, esp8266, raspberrypi +lib_dir = . +; src_dir = examples/AsyncResponseStream +; src_dir = examples/Auth +; src_dir = examples/CaptivePortal +; src_dir = examples/CatchAllHandler +; src_dir = examples/ChunkResponse +; src_dir = examples/ChunkRetryResponse +; src_dir = examples/CORS +; src_dir = examples/EndBegin +; src_dir = examples/Filters +; src_dir = examples/FlashResponse +; src_dir = examples/HeaderManipulation +; src_dir = examples/Json +; src_dir = examples/Logging +; src_dir = examples/MessagePack +; src_dir = examples/Middleware +; src_dir = examples/Params +; src_dir = examples/PartitionDownloader +src_dir = examples/PerfTests +; src_dir = examples/RateLimit +; src_dir = examples/Redirect +; src_dir = examples/RequestContinuation +; src_dir = examples/RequestContinuationComplete +; src_dir = examples/ResumableDownload +; src_dir = examples/Rewrite +; src_dir = examples/ServerSentEvents +; src_dir = examples/ServerState +; src_dir = examples/SkipServerMiddleware +; src_dir = examples/SlowChunkResponse +; src_dir = examples/StaticFile +; src_dir = examples/Templates +; src_dir = examples/Upload +; src_dir = examples/WebSocket +; src_dir = examples/WebSocketEasy + +[env] +framework = arduino +platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20/platform-espressif32.zip +board = esp32dev +build_flags = + -Og + -Wall -Wextra + -Wno-unused-parameter + ; -D CONFIG_ARDUHAL_LOG_COLORS + -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_VERBOSE + -D CONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 + -D CONFIG_ASYNC_TCP_PRIORITY=10 + -D CONFIG_ASYNC_TCP_QUEUE_SIZE=64 + -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 + -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 + ; -D CONFIG_ASYNC_TCP_USE_WDT=0 +upload_protocol = esptool +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder, log2file +; monitor_filters = esp8266_exception_decoder, log2file +lib_compat_mode = strict +lib_ldf_mode = chain +lib_deps = + bblanchon/ArduinoJson @ 7.4.1 + ESP32Async/AsyncTCP @ 3.3.8 +board_build.partitions = partitions-4MB.csv +board_build.filesystem = littlefs + +[env:arduino-2] +platform = espressif32@6.10.0 + +[env:arduino-3] + +[env:arduino-3-latest] +platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20-rc2/platform-espressif32.zip + +[env:arduino-3-no-json] +lib_deps = + ESP32Async/AsyncTCP @ 3.3.8 + +[env:arduino-3-latest-asynctcp] +lib_deps = + https://github.com/ESP32Async/AsyncTCP + +[env:arduino-3-no-chunk-inflight] +build_flags = ${env.build_flags} + -D ASYNCWEBSERVER_USE_CHUNK_INFLIGHT=0 + +[env:AsyncTCPSock] +lib_deps = + https://github.com/ESP32Async/AsyncTCPSock/archive/refs/tags/v1.0.3-dev.zip +build_flags = ${env.build_flags} + +[env:esp8266] +platform = espressif8266 +; board = huzzah +board = d1_mini +lib_deps = + bblanchon/ArduinoJson @ 7.4.1 + ESP32Async/ESPAsyncTCP @ 2.0.0 + +[env:raspberrypi] +platform = https://github.com/maxgerhardt/platform-raspberrypi.git#c7502925e3b08af70e9f924d54ab9d00a7e64781 +board = rpipicow +board_build.core = earlephilhower +lib_deps = + bblanchon/ArduinoJson @ 7.3.0 + ayushsharma82/RPAsyncTCP@^1.3.2 +lib_ignore = + lwIP_ESPHost +build_flags = ${env.build_flags} + -Wno-missing-field-initializers + +; CI + +[env:ci-arduino-2] +platform = espressif32@6.10.0 +board = ${sysenv.PIO_BOARD} + +[env:ci-arduino-3] +board = ${sysenv.PIO_BOARD} + +[env:ci-arduino-3-latest] +platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20-rc2/platform-espressif32.zip +board = ${sysenv.PIO_BOARD} + +[env:ci-arduino-3-no-json] +board = ${sysenv.PIO_BOARD} +lib_deps = + ESP32Async/AsyncTCP @ 3.3.8 + +[env:ci-arduino-3-latest-asynctcp] +lib_deps = + https://github.com/ESP32Async/AsyncTCP + +[env:ci-arduino-3-no-chunk-inflight] +board = ${sysenv.PIO_BOARD} +build_flags = ${env.build_flags} + -D ASYNCWEBSERVER_USE_CHUNK_INFLIGHT=1 + +[env:ci-esp8266] +platform = espressif8266 +board = ${sysenv.PIO_BOARD} +lib_deps = + bblanchon/ArduinoJson @ 7.4.1 + ESP32Async/ESPAsyncTCP @ 2.0.0 + +[env:ci-raspberrypi] +platform = https://github.com/maxgerhardt/platform-raspberrypi.git#c7502925e3b08af70e9f924d54ab9d00a7e64781 +board = ${sysenv.PIO_BOARD} +board_build.core = earlephilhower +lib_deps = + bblanchon/ArduinoJson @ 7.3.0 + ayushsharma82/RPAsyncTCP@^1.3.2 +lib_ignore = + lwIP_ESPHost +build_flags = ${env.build_flags} + -Wno-missing-field-initializers diff --git a/watering/lib/ESPAsyncWebServer/pre-commit.requirements.txt b/watering/lib/ESPAsyncWebServer/pre-commit.requirements.txt new file mode 100644 index 0000000..40a16fa --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/pre-commit.requirements.txt @@ -0,0 +1 @@ +pre-commit==4.1.0 diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncEventSource.cpp b/watering/lib/ESPAsyncWebServer/src/AsyncEventSource.cpp new file mode 100644 index 0000000..2ebfa2d --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncEventSource.cpp @@ -0,0 +1,507 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "Arduino.h" +#if defined(ESP32) +#include +#endif +#include "AsyncEventSource.h" + +#define ASYNC_SSE_NEW_LINE_CHAR (char)0xa + +using namespace asyncsrv; + +static String generateEventMessage(const char *message, const char *event, uint32_t id, uint32_t reconnect) { + String str; + size_t len{0}; + if (message) { + len += strlen(message); + } + + if (event) { + len += strlen(event); + } + + len += 42; // give it some overhead + + if (!str.reserve(len)) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + return emptyString; + } + + if (reconnect) { + str += T_retry_; + str += reconnect; + str += ASYNC_SSE_NEW_LINE_CHAR; // '\n' + } + + if (id) { + str += T_id__; + str += id; + str += ASYNC_SSE_NEW_LINE_CHAR; // '\n' + } + + if (event != NULL) { + str += T_event_; + str += event; + str += ASYNC_SSE_NEW_LINE_CHAR; // '\n' + } + + if (!message) { + return str; + } + + size_t messageLen = strlen(message); + char *lineStart = (char *)message; + char *lineEnd; + do { + char *nextN = strchr(lineStart, '\n'); + char *nextR = strchr(lineStart, '\r'); + if (nextN == NULL && nextR == NULL) { + // a message is a single-line string + str += T_data_; + str += message; + str += T_nn; + return str; + } + + // a message is a multi-line string + char *nextLine = NULL; + if (nextN != NULL && nextR != NULL) { // windows line-ending \r\n + if (nextR + 1 == nextN) { + // normal \r\n sequence + lineEnd = nextR; + nextLine = nextN + 1; + } else { + // some abnormal \n \r mixed sequence + lineEnd = std::min(nextR, nextN); + nextLine = lineEnd + 1; + } + } else if (nextN != NULL) { // Unix/Mac OS X LF + lineEnd = nextN; + nextLine = nextN + 1; + } else { // some ancient garbage + lineEnd = nextR; + nextLine = nextR + 1; + } + + str += T_data_; + str.concat(lineStart, lineEnd - lineStart); + str += ASYNC_SSE_NEW_LINE_CHAR; // \n + + lineStart = nextLine; + } while (lineStart < ((char *)message + messageLen)); + + // append another \n to terminate message + str += ASYNC_SSE_NEW_LINE_CHAR; // '\n' + + return str; +} + +// Message + +size_t AsyncEventSourceMessage::ack(size_t len, __attribute__((unused)) uint32_t time) { + // If the whole message is now acked... + if (_acked + len > _data->length()) { + // Return the number of extra bytes acked (they will be carried on to the next message) + const size_t extra = _acked + len - _data->length(); + _acked = _data->length(); + return extra; + } + // Return that no extra bytes left. + _acked += len; + return 0; +} + +size_t AsyncEventSourceMessage::write(AsyncClient *client) { + if (!client) { + return 0; + } + + if (_sent >= _data->length() || !client->canSend()) { + return 0; + } + + size_t len = std::min(_data->length() - _sent, client->space()); + /* + add() would call lwip's tcp_write() under the AsyncTCP hood with apiflags argument. + By default apiflags=ASYNC_WRITE_FLAG_COPY + we could have used apiflags with this flag unset to pass data by reference and avoid copy to socket buffer, + but looks like it does not work for Arduino's lwip in ESP32/IDF + it is enforced in https://github.com/espressif/esp-lwip/blob/0606eed9d8b98a797514fdf6eabb4daf1c8c8cd9/src/core/tcp_out.c#L422C5-L422C30 + if LWIP_NETIF_TX_SINGLE_PBUF is set, and it is set indeed in IDF + https://github.com/espressif/esp-idf/blob/a0f798cfc4bbd624aab52b2c194d219e242d80c1/components/lwip/port/include/lwipopts.h#L744 + + So let's just keep it enforced ASYNC_WRITE_FLAG_COPY and keep in mind that there is no zero-copy + */ + size_t written = client->add(_data->c_str() + _sent, len, ASYNC_WRITE_FLAG_COPY); // ASYNC_WRITE_FLAG_MORE + _sent += written; + return written; +} + +size_t AsyncEventSourceMessage::send(AsyncClient *client) { + size_t sent = write(client); + return sent && client->send() ? sent : 0; +} + +// Client + +AsyncEventSourceClient::AsyncEventSourceClient(AsyncWebServerRequest *request, AsyncEventSource *server) : _client(request->client()), _server(server) { + + if (request->hasHeader(T_Last_Event_ID)) { + _lastId = atoi(request->getHeader(T_Last_Event_ID)->value().c_str()); + } + + _client->setRxTimeout(0); + _client->onError(NULL, NULL); + _client->onAck( + [](void *r, AsyncClient *c, size_t len, uint32_t time) { + (void)c; + static_cast(r)->_onAck(len, time); + }, + this + ); + _client->onPoll( + [](void *r, AsyncClient *c) { + (void)c; + static_cast(r)->_onPoll(); + }, + this + ); + _client->onData(NULL, NULL); + _client->onTimeout( + [this](void *r, AsyncClient *c __attribute__((unused)), uint32_t time) { + static_cast(r)->_onTimeout(time); + }, + this + ); + _client->onDisconnect( + [this](void *r, AsyncClient *c) { + static_cast(r)->_onDisconnect(); + delete c; + }, + this + ); + + _server->_addClient(this); + delete request; + + _client->setNoDelay(true); +} + +AsyncEventSourceClient::~AsyncEventSourceClient() { +#ifdef ESP32 + std::lock_guard lock(_lockmq); +#endif + _messageQueue.clear(); + close(); +} + +bool AsyncEventSourceClient::_queueMessage(const char *message, size_t len) { + if (_messageQueue.size() >= SSE_MAX_QUEUED_MESSAGES) { +#ifdef ESP8266 + ets_printf(String(F("ERROR: Too many messages queued\n")).c_str()); +#elif defined(ESP32) + log_e("Event message queue overflow: discard message"); +#endif + return false; + } + +#ifdef ESP32 + // length() is not thread-safe, thus acquiring the lock before this call.. + std::lock_guard lock(_lockmq); +#endif + + _messageQueue.emplace_back(message, len); + + /* + throttle queue run + if Q is filled for >25% then network/CPU is congested, since there is no zero-copy mode for socket buff + forcing Q run will only eat more heap ram and blow the buffer, let's just keep data in our own queue + the queue will be processed at least on each onAck()/onPoll() call from AsyncTCP + */ + if (_messageQueue.size() < SSE_MAX_QUEUED_MESSAGES >> 2 && _client->canSend()) { + _runQueue(); + } + + return true; +} + +bool AsyncEventSourceClient::_queueMessage(AsyncEvent_SharedData_t &&msg) { + if (_messageQueue.size() >= SSE_MAX_QUEUED_MESSAGES) { +#ifdef ESP8266 + ets_printf(String(F("ERROR: Too many messages queued\n")).c_str()); +#elif defined(ESP32) + log_e("Event message queue overflow: discard message"); +#endif + return false; + } + +#ifdef ESP32 + // length() is not thread-safe, thus acquiring the lock before this call.. + std::lock_guard lock(_lockmq); +#endif + + _messageQueue.emplace_back(std::move(msg)); + + /* + throttle queue run + if Q is filled for >25% then network/CPU is congested, since there is no zero-copy mode for socket buff + forcing Q run will only eat more heap ram and blow the buffer, let's just keep data in our own queue + the queue will be processed at least on each onAck()/onPoll() call from AsyncTCP + */ + if (_messageQueue.size() < SSE_MAX_QUEUED_MESSAGES >> 2 && _client->canSend()) { + _runQueue(); + } + return true; +} + +void AsyncEventSourceClient::_onAck(size_t len __attribute__((unused)), uint32_t time __attribute__((unused))) { +#ifdef ESP32 + // Same here, acquiring the lock early + std::lock_guard lock(_lockmq); +#endif + + // adjust in-flight len + if (len < _inflight) { + _inflight -= len; + } else { + _inflight = 0; + } + + // acknowledge as much messages's data as we got confirmed len from a AsyncTCP + while (len && _messageQueue.size()) { + len = _messageQueue.front().ack(len); + if (_messageQueue.front().finished()) { + // now we could release full ack'ed messages, we were keeping it unless send confirmed from AsyncTCP + _messageQueue.pop_front(); + } + } + + // try to send another batch of data + if (_messageQueue.size()) { + _runQueue(); + } +} + +void AsyncEventSourceClient::_onPoll() { + if (_messageQueue.size()) { +#ifdef ESP32 + // Same here, acquiring the lock early + std::lock_guard lock(_lockmq); +#endif + _runQueue(); + } +} + +void AsyncEventSourceClient::_onTimeout(uint32_t time __attribute__((unused))) { + if (_client) { + _client->close(true); + } +} + +void AsyncEventSourceClient::_onDisconnect() { + if (!_client) { + return; + } + _client = nullptr; + _server->_handleDisconnect(this); +} + +void AsyncEventSourceClient::close() { + if (_client) { + _client->close(); + } +} + +bool AsyncEventSourceClient::send(const char *message, const char *event, uint32_t id, uint32_t reconnect) { + if (!connected()) { + return false; + } + return _queueMessage(std::make_shared(generateEventMessage(message, event, id, reconnect))); +} + +void AsyncEventSourceClient::_runQueue() { + if (!_client) { + return; + } + + // there is no need to lock the mutex here, 'cause all the calls to this method must be already lock'ed + size_t total_bytes_written = 0; + for (auto i = _messageQueue.begin(); i != _messageQueue.end(); ++i) { + if (!i->sent()) { + const size_t bytes_written = i->write(_client); + total_bytes_written += bytes_written; + _inflight += bytes_written; + if (bytes_written == 0 || _inflight > _max_inflight) { + // Serial.print("_"); + break; + } + } + } + + // flush socket + if (total_bytes_written) { + _client->send(); + } +} + +void AsyncEventSourceClient::set_max_inflight_bytes(size_t value) { + if (value >= SSE_MIN_INFLIGH && value <= SSE_MAX_INFLIGH) { + _max_inflight = value; + } +} + +/* AsyncEventSource */ + +void AsyncEventSource::authorizeConnect(ArAuthorizeConnectHandler cb) { + AsyncAuthorizationMiddleware *m = new AsyncAuthorizationMiddleware(401, cb); + m->_freeOnRemoval = true; + addMiddleware(m); +} + +void AsyncEventSource::_addClient(AsyncEventSourceClient *client) { + if (!client) { + return; + } +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + _clients.emplace_back(client); + if (_connectcb) { + _connectcb(client); + } + + _adjust_inflight_window(); +} + +void AsyncEventSource::_handleDisconnect(AsyncEventSourceClient *client) { + if (_disconnectcb) { + _disconnectcb(client); + } +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + for (auto i = _clients.begin(); i != _clients.end(); ++i) { + if (i->get() == client) { + _clients.erase(i); + break; + } + } + _adjust_inflight_window(); +} + +void AsyncEventSource::close() { + // While the whole loop is not done, the linked list is locked and so the + // iterator should remain valid even when AsyncEventSource::_handleDisconnect() + // is called very early +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + for (const auto &c : _clients) { + if (c->connected()) { + /** + * @brief: Fix self-deadlock by using recursive_mutex instead. + * Due to c->close() shall call the callback function _onDisconnect() + * The calling flow _onDisconnect() --> _handleDisconnect() --> deadlock + */ + c->close(); + } + } +} + +// pmb fix +size_t AsyncEventSource::avgPacketsWaiting() const { + size_t aql = 0; + uint32_t nConnectedClients = 0; +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + if (!_clients.size()) { + return 0; + } + + for (const auto &c : _clients) { + if (c->connected()) { + aql += c->packetsWaiting(); + ++nConnectedClients; + } + } + return ((aql) + (nConnectedClients / 2)) / (nConnectedClients); // round up +} + +AsyncEventSource::SendStatus AsyncEventSource::send(const char *message, const char *event, uint32_t id, uint32_t reconnect) { + AsyncEvent_SharedData_t shared_msg = std::make_shared(generateEventMessage(message, event, id, reconnect)); +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + size_t hits = 0; + size_t miss = 0; + for (const auto &c : _clients) { + if (c->write(shared_msg)) { + ++hits; + } else { + ++miss; + } + } + return hits == 0 ? DISCARDED : (miss == 0 ? ENQUEUED : PARTIALLY_ENQUEUED); +} + +size_t AsyncEventSource::count() const { +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + size_t n_clients{0}; + for (const auto &i : _clients) { + if (i->connected()) { + ++n_clients; + } + } + + return n_clients; +} + +bool AsyncEventSource::canHandle(AsyncWebServerRequest *request) const { + return request->isSSE() && request->url().equals(_url); +} + +void AsyncEventSource::handleRequest(AsyncWebServerRequest *request) { + request->send(new AsyncEventSourceResponse(this)); +} + +void AsyncEventSource::_adjust_inflight_window() { + if (_clients.size()) { + size_t inflight = SSE_MAX_INFLIGH / _clients.size(); + for (const auto &c : _clients) { + c->set_max_inflight_bytes(inflight); + } + // Serial.printf("adjusted inflight to: %u\n", inflight); + } +} + +/* Response */ + +AsyncEventSourceResponse::AsyncEventSourceResponse(AsyncEventSource *server) { + _server = server; + _code = 200; + _contentType = T_text_event_stream; + _sendContentLength = false; + addHeader(T_Cache_Control, T_no_cache); + addHeader(T_Connection, T_keep_alive); +} + +void AsyncEventSourceResponse::_respond(AsyncWebServerRequest *request) { + String out; + _assembleHead(out, request->version()); + request->client()->write(out.c_str(), _headLength); + _state = RESPONSE_WAIT_ACK; +} + +size_t AsyncEventSourceResponse::_ack(AsyncWebServerRequest *request, size_t len, uint32_t time __attribute__((unused))) { + if (len) { + new AsyncEventSourceClient(request, _server); + } + return 0; +} diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncEventSource.h b/watering/lib/ESPAsyncWebServer/src/AsyncEventSource.h new file mode 100644 index 0000000..96f0a89 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncEventSource.h @@ -0,0 +1,320 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef ASYNCEVENTSOURCE_H_ +#define ASYNCEVENTSOURCE_H_ + +#include + +#ifdef ESP32 +#include +#include +#ifndef SSE_MAX_QUEUED_MESSAGES +#define SSE_MAX_QUEUED_MESSAGES 32 +#endif +#define SSE_MIN_INFLIGH 2 * 1460 // allow 2 MSS packets +#define SSE_MAX_INFLIGH 16 * 1024 // but no more than 16k, no need to blow it, since same data is kept in local Q +#elif defined(ESP8266) +#include +#ifndef SSE_MAX_QUEUED_MESSAGES +#define SSE_MAX_QUEUED_MESSAGES 8 +#endif +#define SSE_MIN_INFLIGH 2 * 1460 // allow 2 MSS packets +#define SSE_MAX_INFLIGH 8 * 1024 // but no more than 8k, no need to blow it, since same data is kept in local Q +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#ifndef SSE_MAX_QUEUED_MESSAGES +#define SSE_MAX_QUEUED_MESSAGES 32 +#endif +#define SSE_MIN_INFLIGH 2 * 1460 // allow 2 MSS packets +#define SSE_MAX_INFLIGH 16 * 1024 // but no more than 16k, no need to blow it, since same data is kept in local Q +#endif + +#include + +#ifdef ESP8266 +#include +#ifdef CRYPTO_HASH_h // include Hash.h from espressif framework if the first include was from the crypto library +#include <../src/Hash.h> +#endif +#endif + +class AsyncEventSource; +class AsyncEventSourceResponse; +class AsyncEventSourceClient; +using ArEventHandlerFunction = std::function; +using ArAuthorizeConnectHandler = ArAuthorizeFunction; +// shared message object container +using AsyncEvent_SharedData_t = std::shared_ptr; + +/** + * @brief Async Event Message container with shared message content data + * + */ +class AsyncEventSourceMessage { + +private: + const AsyncEvent_SharedData_t _data; + size_t _sent{0}; // num of bytes already sent + size_t _acked{0}; // num of bytes acked + +public: + AsyncEventSourceMessage(AsyncEvent_SharedData_t data) : _data(data){}; +#if defined(ESP32) + AsyncEventSourceMessage(const char *data, size_t len) : _data(std::make_shared(data, len)){}; +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) + AsyncEventSourceMessage(const char *data, size_t len) : _data(std::make_shared()) { + if (data && len > 0) { + _data->concat(data, len); + } + }; +#else + // esp8266's String does not have constructor with data/length arguments. Use a concat method here + AsyncEventSourceMessage(const char *data, size_t len) { + _data->concat(data, len); + }; +#endif + + /** + * @brief acknowledge sending len bytes of data + * @note if num of bytes to ack is larger then the unacknowledged message length the number of carried over bytes are returned + * + * @param len bytes to acknowledge + * @param time + * @return size_t number of extra bytes carried over + */ + size_t ack(size_t len, uint32_t time = 0); + + /** + * @brief write message data to client's buffer + * @note this method does NOT call client's send + * + * @param client + * @return size_t number of bytes written + */ + size_t write(AsyncClient *client); + + /** + * @brief writes message data to client's buffer and calls client's send method + * + * @param client + * @return size_t returns num of bytes the clien was able to send() + */ + size_t send(AsyncClient *client); + + // returns true if full message's length were acked + bool finished() { + return _acked == _data->length(); + } + + /** + * @brief returns true if all data has been sent already + * + */ + bool sent() { + return _sent == _data->length(); + } +}; + +/** + * @brief class holds a sse messages queue for a particular client's connection + * + */ +class AsyncEventSourceClient { +private: + AsyncClient *_client; + AsyncEventSource *_server; + uint32_t _lastId{0}; + size_t _inflight{0}; // num of unacknowledged bytes that has been written to socket buffer + size_t _max_inflight{SSE_MAX_INFLIGH}; // max num of unacknowledged bytes that could be written to socket buffer + std::list _messageQueue; +#ifdef ESP32 + mutable std::recursive_mutex _lockmq; +#endif + bool _queueMessage(const char *message, size_t len); + bool _queueMessage(AsyncEvent_SharedData_t &&msg); + void _runQueue(); + +public: + AsyncEventSourceClient(AsyncWebServerRequest *request, AsyncEventSource *server); + ~AsyncEventSourceClient(); + + /** + * @brief Send an SSE message to client + * it will craft an SSE message and place it to client's message queue + * + * @param message body string, could be single or multi-line string sepprated by \n, \r, \r\n + * @param event body string, a sinle line string + * @param id sequence id + * @param reconnect client's reconnect timeout + * @return true if message was placed in a queue + * @return false if queue is full + */ + bool send(const char *message, const char *event = NULL, uint32_t id = 0, uint32_t reconnect = 0); + bool send(const String &message, const String &event, uint32_t id = 0, uint32_t reconnect = 0) { + return send(message.c_str(), event.c_str(), id, reconnect); + } + bool send(const String &message, const char *event, uint32_t id = 0, uint32_t reconnect = 0) { + return send(message.c_str(), event, id, reconnect); + } + + /** + * @brief place supplied preformatted SSE message to the message queue + * @note message must a properly formatted SSE string according to https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events + * + * @param message data + * @return true on success + * @return false on queue overflow or no client connected + */ + bool write(AsyncEvent_SharedData_t message) { + return connected() && _queueMessage(std::move(message)); + }; + + [[deprecated("Use _write(AsyncEvent_SharedData_t message) instead to share same data with multiple SSE clients")]] + bool write(const char *message, size_t len) { + return connected() && _queueMessage(message, len); + }; + + // close client's connection + void close(); + + // getters + + AsyncClient *client() { + return _client; + } + bool connected() const { + return _client && _client->connected(); + } + uint32_t lastId() const { + return _lastId; + } + size_t packetsWaiting() const { + return _messageQueue.size(); + }; + + /** + * @brief Sets max amount of bytes that could be written to client's socket while awaiting delivery acknowledge + * used to throttle message delivery length to tradeoff memory consumption + * @note actual amount of data written could possible be a bit larger but no more than available socket buff space + * + * @param value + */ + void set_max_inflight_bytes(size_t value); + + /** + * @brief Get current max inflight bytes value + * + * @return size_t + */ + size_t get_max_inflight_bytes() const { + return _max_inflight; + } + + // system callbacks (do not call if from user code!) + void _onAck(size_t len, uint32_t time); + void _onPoll(); + void _onTimeout(uint32_t time); + void _onDisconnect(); +}; + +/** + * @brief a class that maintains all connected HTTP clients subscribed to SSE delivery + * dispatches supplied messages to the client's queues + * + */ +class AsyncEventSource : public AsyncWebHandler { +private: + String _url; + std::list> _clients; +#ifdef ESP32 + // Same as for individual messages, protect mutations of _clients list + // since simultaneous access from different tasks is possible + mutable std::recursive_mutex _client_queue_lock; +#endif + ArEventHandlerFunction _connectcb = nullptr; + ArEventHandlerFunction _disconnectcb = nullptr; + + // this method manipulates in-fligh data size for connected client depending on number of active connections + void _adjust_inflight_window(); + +public: + typedef enum { + DISCARDED = 0, + ENQUEUED = 1, + PARTIALLY_ENQUEUED = 2, + } SendStatus; + + AsyncEventSource(const char *url) : _url(url){}; + AsyncEventSource(const String &url) : _url(url){}; + ~AsyncEventSource() { + close(); + }; + + const char *url() const { + return _url.c_str(); + } + // close all connected clients + void close(); + + /** + * @brief set on-connect callback for the client + * used to deliver messages to client on first connect + * + * @param cb + */ + void onConnect(ArEventHandlerFunction cb) { + _connectcb = cb; + } + + /** + * @brief Send an SSE message to client + * it will craft an SSE message and place it to all connected client's message queues + * + * @param message body string, could be single or multi-line string sepprated by \n, \r, \r\n + * @param event body string, a sinle line string + * @param id sequence id + * @param reconnect client's reconnect timeout + * @return SendStatus if message was placed in any/all/part of the client's queues + */ + SendStatus send(const char *message, const char *event = NULL, uint32_t id = 0, uint32_t reconnect = 0); + SendStatus send(const String &message, const String &event, uint32_t id = 0, uint32_t reconnect = 0) { + return send(message.c_str(), event.c_str(), id, reconnect); + } + SendStatus send(const String &message, const char *event, uint32_t id = 0, uint32_t reconnect = 0) { + return send(message.c_str(), event, id, reconnect); + } + + // The client pointer sent to the callback is only for reference purposes. DO NOT CALL ANY METHOD ON IT ! + void onDisconnect(ArEventHandlerFunction cb) { + _disconnectcb = cb; + } + void authorizeConnect(ArAuthorizeConnectHandler cb); + + // returns number of connected clients + size_t count() const; + + // returns average number of messages pending in all client's queues + size_t avgPacketsWaiting() const; + + // system callbacks (do not call from user code!) + void _addClient(AsyncEventSourceClient *client); + void _handleDisconnect(AsyncEventSourceClient *client); + bool canHandle(AsyncWebServerRequest *request) const override final; + void handleRequest(AsyncWebServerRequest *request) override final; +}; + +class AsyncEventSourceResponse : public AsyncWebServerResponse { +private: + AsyncEventSource *_server; + +public: + AsyncEventSourceResponse(AsyncEventSource *server); + void _respond(AsyncWebServerRequest *request); + size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time); + bool _sourceValid() const { + return true; + } +}; + +#endif /* ASYNCEVENTSOURCE_H_ */ diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncJson.cpp b/watering/lib/ESPAsyncWebServer/src/AsyncJson.cpp new file mode 100644 index 0000000..b8d014b --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncJson.cpp @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "AsyncJson.h" + +#if ASYNC_JSON_SUPPORT == 1 + +#if ARDUINOJSON_VERSION_MAJOR == 5 +AsyncJsonResponse::AsyncJsonResponse(bool isArray) : _isValid{false} { + _code = 200; + _contentType = asyncsrv::T_application_json; + if (isArray) { + _root = _jsonBuffer.createArray(); + } else { + _root = _jsonBuffer.createObject(); + } +} +#elif ARDUINOJSON_VERSION_MAJOR == 6 +AsyncJsonResponse::AsyncJsonResponse(bool isArray, size_t maxJsonBufferSize) : _jsonBuffer(maxJsonBufferSize), _isValid{false} { + _code = 200; + _contentType = asyncsrv::T_application_json; + if (isArray) { + _root = _jsonBuffer.createNestedArray(); + } else { + _root = _jsonBuffer.createNestedObject(); + } +} +#else +AsyncJsonResponse::AsyncJsonResponse(bool isArray) : _isValid{false} { + _code = 200; + _contentType = asyncsrv::T_application_json; + if (isArray) { + _root = _jsonBuffer.add(); + } else { + _root = _jsonBuffer.add(); + } +} +#endif + +size_t AsyncJsonResponse::setLength() { +#if ARDUINOJSON_VERSION_MAJOR == 5 + _contentLength = _root.measureLength(); +#else + _contentLength = measureJson(_root); +#endif + if (_contentLength) { + _isValid = true; + } + return _contentLength; +} + +size_t AsyncJsonResponse::_fillBuffer(uint8_t *data, size_t len) { + ChunkPrint dest(data, _sentLength, len); +#if ARDUINOJSON_VERSION_MAJOR == 5 + _root.printTo(dest); +#else + serializeJson(_root, dest); +#endif + return len; +} + +#if ARDUINOJSON_VERSION_MAJOR == 6 +PrettyAsyncJsonResponse::PrettyAsyncJsonResponse(bool isArray, size_t maxJsonBufferSize) : AsyncJsonResponse{isArray, maxJsonBufferSize} {} +#else +PrettyAsyncJsonResponse::PrettyAsyncJsonResponse(bool isArray) : AsyncJsonResponse{isArray} {} +#endif + +size_t PrettyAsyncJsonResponse::setLength() { +#if ARDUINOJSON_VERSION_MAJOR == 5 + _contentLength = _root.measurePrettyLength(); +#else + _contentLength = measureJsonPretty(_root); +#endif + if (_contentLength) { + _isValid = true; + } + return _contentLength; +} + +size_t PrettyAsyncJsonResponse::_fillBuffer(uint8_t *data, size_t len) { + ChunkPrint dest(data, _sentLength, len); +#if ARDUINOJSON_VERSION_MAJOR == 5 + _root.prettyPrintTo(dest); +#else + serializeJsonPretty(_root, dest); +#endif + return len; +} + +#if ARDUINOJSON_VERSION_MAJOR == 6 +AsyncCallbackJsonWebHandler::AsyncCallbackJsonWebHandler(const String &uri, ArJsonRequestHandlerFunction onRequest, size_t maxJsonBufferSize) + : _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), maxJsonBufferSize(maxJsonBufferSize), _maxContentLength(16384) {} +#else +AsyncCallbackJsonWebHandler::AsyncCallbackJsonWebHandler(const String &uri, ArJsonRequestHandlerFunction onRequest) + : _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), _maxContentLength(16384) {} +#endif + +bool AsyncCallbackJsonWebHandler::canHandle(AsyncWebServerRequest *request) const { + if (!_onRequest || !request->isHTTP() || !(_method & request->method())) { + return false; + } + + if (_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri + "/"))) { + return false; + } + + if (request->method() != HTTP_GET && !request->contentType().equalsIgnoreCase(asyncsrv::T_application_json)) { + return false; + } + + return true; +} + +void AsyncCallbackJsonWebHandler::handleRequest(AsyncWebServerRequest *request) { + if (_onRequest) { + if (request->method() == HTTP_GET) { + JsonVariant json; + _onRequest(request, json); + return; + } else if (request->_tempObject != NULL) { + +#if ARDUINOJSON_VERSION_MAJOR == 5 + DynamicJsonBuffer jsonBuffer; + JsonVariant json = jsonBuffer.parse((uint8_t *)(request->_tempObject)); + if (json.success()) { +#elif ARDUINOJSON_VERSION_MAJOR == 6 + DynamicJsonDocument jsonBuffer(this->maxJsonBufferSize); + DeserializationError error = deserializeJson(jsonBuffer, (uint8_t *)(request->_tempObject)); + if (!error) { + JsonVariant json = jsonBuffer.as(); +#else + JsonDocument jsonBuffer; + DeserializationError error = deserializeJson(jsonBuffer, (uint8_t *)(request->_tempObject)); + if (!error) { + JsonVariant json = jsonBuffer.as(); +#endif + + _onRequest(request, json); + return; + } + } + request->send(_contentLength > _maxContentLength ? 413 : 400); + } else { + request->send(500); + } +} + +void AsyncCallbackJsonWebHandler::handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { + if (_onRequest) { + _contentLength = total; + if (total > 0 && request->_tempObject == NULL && total < _maxContentLength) { + request->_tempObject = malloc(total); + if (request->_tempObject == NULL) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + request->abort(); + return; + } + } + if (request->_tempObject != NULL) { + memcpy((uint8_t *)(request->_tempObject) + index, data, len); + } + } +} + +#endif // ASYNC_JSON_SUPPORT diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncJson.h b/watering/lib/ESPAsyncWebServer/src/AsyncJson.h new file mode 100644 index 0000000..b5777d6 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncJson.h @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef ASYNC_JSON_H_ +#define ASYNC_JSON_H_ + +#if __has_include("ArduinoJson.h") +#include +#if ARDUINOJSON_VERSION_MAJOR >= 5 +#define ASYNC_JSON_SUPPORT 1 +#else +#define ASYNC_JSON_SUPPORT 0 +#endif // ARDUINOJSON_VERSION_MAJOR >= 5 +#endif // __has_include("ArduinoJson.h") + +#if ASYNC_JSON_SUPPORT == 1 +#include + +#include "ChunkPrint.h" + +#if ARDUINOJSON_VERSION_MAJOR == 6 +#ifndef DYNAMIC_JSON_DOCUMENT_SIZE +#define DYNAMIC_JSON_DOCUMENT_SIZE 1024 +#endif +#endif + +class AsyncJsonResponse : public AsyncAbstractResponse { +protected: +#if ARDUINOJSON_VERSION_MAJOR == 5 + DynamicJsonBuffer _jsonBuffer; +#elif ARDUINOJSON_VERSION_MAJOR == 6 + DynamicJsonDocument _jsonBuffer; +#else + JsonDocument _jsonBuffer; +#endif + + JsonVariant _root; + bool _isValid; + +public: +#if ARDUINOJSON_VERSION_MAJOR == 6 + AsyncJsonResponse(bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); +#else + AsyncJsonResponse(bool isArray = false); +#endif + JsonVariant &getRoot() { + return _root; + } + bool _sourceValid() const { + return _isValid; + } + size_t setLength(); + size_t getSize() const { + return _jsonBuffer.size(); + } + size_t _fillBuffer(uint8_t *data, size_t len); +#if ARDUINOJSON_VERSION_MAJOR >= 6 + bool overflowed() const { + return _jsonBuffer.overflowed(); + } +#endif +}; + +class PrettyAsyncJsonResponse : public AsyncJsonResponse { +public: +#if ARDUINOJSON_VERSION_MAJOR == 6 + PrettyAsyncJsonResponse(bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); +#else + PrettyAsyncJsonResponse(bool isArray = false); +#endif + size_t setLength(); + size_t _fillBuffer(uint8_t *data, size_t len); +}; + +typedef std::function ArJsonRequestHandlerFunction; + +class AsyncCallbackJsonWebHandler : public AsyncWebHandler { +protected: + String _uri; + WebRequestMethodComposite _method; + ArJsonRequestHandlerFunction _onRequest; + size_t _contentLength; +#if ARDUINOJSON_VERSION_MAJOR == 6 + size_t maxJsonBufferSize; +#endif + size_t _maxContentLength; + +public: +#if ARDUINOJSON_VERSION_MAJOR == 6 + AsyncCallbackJsonWebHandler(const String &uri, ArJsonRequestHandlerFunction onRequest = nullptr, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); +#else + AsyncCallbackJsonWebHandler(const String &uri, ArJsonRequestHandlerFunction onRequest = nullptr); +#endif + + void setMethod(WebRequestMethodComposite method) { + _method = method; + } + void setMaxContentLength(int maxContentLength) { + _maxContentLength = maxContentLength; + } + void onRequest(ArJsonRequestHandlerFunction fn) { + _onRequest = fn; + } + + bool canHandle(AsyncWebServerRequest *request) const override final; + void handleRequest(AsyncWebServerRequest *request) override final; + void handleUpload( + __unused AsyncWebServerRequest *request, __unused const String &filename, __unused size_t index, __unused uint8_t *data, __unused size_t len, + __unused bool final + ) override final {} + void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) override final; + bool isRequestHandlerTrivial() const override final { + return !_onRequest; + } +}; + +#endif // ASYNC_JSON_SUPPORT == 1 + +#endif // ASYNC_JSON_H_ diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncMessagePack.cpp b/watering/lib/ESPAsyncWebServer/src/AsyncMessagePack.cpp new file mode 100644 index 0000000..0c6faa1 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncMessagePack.cpp @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "AsyncMessagePack.h" + +#if ASYNC_MSG_PACK_SUPPORT == 1 + +#if ARDUINOJSON_VERSION_MAJOR == 6 +AsyncMessagePackResponse::AsyncMessagePackResponse(bool isArray, size_t maxJsonBufferSize) : _jsonBuffer(maxJsonBufferSize), _isValid{false} { + _code = 200; + _contentType = asyncsrv::T_application_msgpack; + if (isArray) { + _root = _jsonBuffer.createNestedArray(); + } else { + _root = _jsonBuffer.createNestedObject(); + } +} +#else +AsyncMessagePackResponse::AsyncMessagePackResponse(bool isArray) : _isValid{false} { + _code = 200; + _contentType = asyncsrv::T_application_msgpack; + if (isArray) { + _root = _jsonBuffer.add(); + } else { + _root = _jsonBuffer.add(); + } +} +#endif + +size_t AsyncMessagePackResponse::setLength() { + _contentLength = measureMsgPack(_root); + if (_contentLength) { + _isValid = true; + } + return _contentLength; +} + +size_t AsyncMessagePackResponse::_fillBuffer(uint8_t *data, size_t len) { + ChunkPrint dest(data, _sentLength, len); + serializeMsgPack(_root, dest); + return len; +} + +#if ARDUINOJSON_VERSION_MAJOR == 6 +AsyncCallbackMessagePackWebHandler::AsyncCallbackMessagePackWebHandler( + const String &uri, ArMessagePackRequestHandlerFunction onRequest, size_t maxJsonBufferSize +) + : _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), maxJsonBufferSize(maxJsonBufferSize), _maxContentLength(16384) {} +#else +AsyncCallbackMessagePackWebHandler::AsyncCallbackMessagePackWebHandler(const String &uri, ArMessagePackRequestHandlerFunction onRequest) + : _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), _maxContentLength(16384) {} +#endif + +bool AsyncCallbackMessagePackWebHandler::canHandle(AsyncWebServerRequest *request) const { + if (!_onRequest || !request->isHTTP() || !(_method & request->method())) { + return false; + } + + if (_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri + "/"))) { + return false; + } + + if (request->method() != HTTP_GET && !request->contentType().equalsIgnoreCase(asyncsrv::T_application_msgpack)) { + return false; + } + + return true; +} + +void AsyncCallbackMessagePackWebHandler::handleRequest(AsyncWebServerRequest *request) { + if (_onRequest) { + if (request->method() == HTTP_GET) { + JsonVariant json; + _onRequest(request, json); + return; + } else if (request->_tempObject != NULL) { + +#if ARDUINOJSON_VERSION_MAJOR == 6 + DynamicJsonDocument jsonBuffer(this->maxJsonBufferSize); + DeserializationError error = deserializeMsgPack(jsonBuffer, (uint8_t *)(request->_tempObject)); + if (!error) { + JsonVariant json = jsonBuffer.as(); +#else + JsonDocument jsonBuffer; + DeserializationError error = deserializeMsgPack(jsonBuffer, (uint8_t *)(request->_tempObject)); + if (!error) { + JsonVariant json = jsonBuffer.as(); +#endif + + _onRequest(request, json); + return; + } + } + request->send(_contentLength > _maxContentLength ? 413 : 400); + } else { + request->send(500); + } +} + +void AsyncCallbackMessagePackWebHandler::handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { + if (_onRequest) { + _contentLength = total; + if (total > 0 && request->_tempObject == NULL && total < _maxContentLength) { + request->_tempObject = malloc(total); + if (request->_tempObject == NULL) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + request->abort(); + return; + } + } + if (request->_tempObject != NULL) { + memcpy((uint8_t *)(request->_tempObject) + index, data, len); + } + } +} + +#endif // ASYNC_MSG_PACK_SUPPORT diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncMessagePack.h b/watering/lib/ESPAsyncWebServer/src/AsyncMessagePack.h new file mode 100644 index 0000000..7488b5c --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncMessagePack.h @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#pragma once + +/* + server.on("/msg_pack", HTTP_ANY, [](AsyncWebServerRequest * request) { + AsyncMessagePackResponse * response = new AsyncMessagePackResponse(); + JsonObject& root = response->getRoot(); + root["key1"] = "key number one"; + JsonObject& nested = root.createNestedObject("nested"); + nested["key1"] = "key number one"; + response->setLength(); + request->send(response); + }); + + -------------------- + + AsyncCallbackMessagePackWebHandler* handler = new AsyncCallbackMessagePackWebHandler("/msg_pack/endpoint"); + handler->onRequest([](AsyncWebServerRequest *request, JsonVariant &json) { + JsonObject jsonObj = json.as(); + // ... + }); + server.addHandler(handler); +*/ + +#if __has_include("ArduinoJson.h") +#include +#if ARDUINOJSON_VERSION_MAJOR >= 6 +#define ASYNC_MSG_PACK_SUPPORT 1 +#else +#define ASYNC_MSG_PACK_SUPPORT 0 +#endif // ARDUINOJSON_VERSION_MAJOR >= 6 +#endif // __has_include("ArduinoJson.h") + +#if ASYNC_MSG_PACK_SUPPORT == 1 +#include + +#include "ChunkPrint.h" + +#if ARDUINOJSON_VERSION_MAJOR == 6 +#ifndef DYNAMIC_JSON_DOCUMENT_SIZE +#define DYNAMIC_JSON_DOCUMENT_SIZE 1024 +#endif +#endif + +class AsyncMessagePackResponse : public AsyncAbstractResponse { +protected: +#if ARDUINOJSON_VERSION_MAJOR == 6 + DynamicJsonDocument _jsonBuffer; +#else + JsonDocument _jsonBuffer; +#endif + + JsonVariant _root; + bool _isValid; + +public: +#if ARDUINOJSON_VERSION_MAJOR == 6 + AsyncMessagePackResponse(bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); +#else + AsyncMessagePackResponse(bool isArray = false); +#endif + JsonVariant &getRoot() { + return _root; + } + bool _sourceValid() const { + return _isValid; + } + size_t setLength(); + size_t getSize() const { + return _jsonBuffer.size(); + } + size_t _fillBuffer(uint8_t *data, size_t len); +#if ARDUINOJSON_VERSION_MAJOR >= 6 + bool overflowed() const { + return _jsonBuffer.overflowed(); + } +#endif +}; + +typedef std::function ArMessagePackRequestHandlerFunction; + +class AsyncCallbackMessagePackWebHandler : public AsyncWebHandler { +protected: + String _uri; + WebRequestMethodComposite _method; + ArMessagePackRequestHandlerFunction _onRequest; + size_t _contentLength; +#if ARDUINOJSON_VERSION_MAJOR == 6 + size_t maxJsonBufferSize; +#endif + size_t _maxContentLength; + +public: +#if ARDUINOJSON_VERSION_MAJOR == 6 + AsyncCallbackMessagePackWebHandler( + const String &uri, ArMessagePackRequestHandlerFunction onRequest = nullptr, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE + ); +#else + AsyncCallbackMessagePackWebHandler(const String &uri, ArMessagePackRequestHandlerFunction onRequest = nullptr); +#endif + + void setMethod(WebRequestMethodComposite method) { + _method = method; + } + void setMaxContentLength(int maxContentLength) { + _maxContentLength = maxContentLength; + } + void onRequest(ArMessagePackRequestHandlerFunction fn) { + _onRequest = fn; + } + + bool canHandle(AsyncWebServerRequest *request) const override final; + void handleRequest(AsyncWebServerRequest *request) override final; + void handleUpload( + __unused AsyncWebServerRequest *request, __unused const String &filename, __unused size_t index, __unused uint8_t *data, __unused size_t len, + __unused bool final + ) override final {} + void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) override final; + bool isRequestHandlerTrivial() const override final { + return !_onRequest; + } +}; + +#endif // ASYNC_MSG_PACK_SUPPORT == 1 diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncWebHeader.cpp b/watering/lib/ESPAsyncWebServer/src/AsyncWebHeader.cpp new file mode 100644 index 0000000..6d82f74 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncWebHeader.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include + +AsyncWebHeader::AsyncWebHeader(const String &data) { + if (!data) { + return; + } + int index = data.indexOf(':'); + if (index < 0) { + return; + } + _name = data.substring(0, index); + _value = data.substring(index + 2); +} + +String AsyncWebHeader::toString() const { + String str; + if (str.reserve(_name.length() + _value.length() + 2)) { + str.concat(_name); + str.concat((char)0x3a); + str.concat((char)0x20); + str.concat(_value); + str.concat(asyncsrv::T_rn); + } else { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + } + return str; +} diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncWebServerVersion.h b/watering/lib/ESPAsyncWebServer/src/AsyncWebServerVersion.h new file mode 100644 index 0000000..46b4ef9 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncWebServerVersion.h @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/** Major version number (X.x.x) */ +#define ASYNCWEBSERVER_VERSION_MAJOR 3 +/** Minor version number (x.X.x) */ +#define ASYNCWEBSERVER_VERSION_MINOR 7 +/** Patch version number (x.x.X) */ +#define ASYNCWEBSERVER_VERSION_PATCH 6 + +/** + * Macro to convert version number into an integer + * + * To be used in comparisons, such as ASYNCWEBSERVER_VERSION >= ASYNCWEBSERVER_VERSION_VAL(2, 0, 0) + */ +#define ASYNCWEBSERVER_VERSION_VAL(major, minor, patch) ((major << 16) | (minor << 8) | (patch)) + +/** + * Current version, as an integer + * + * To be used in comparisons, such as ASYNCWEBSERVER_VERSION_NUM >= ASYNCWEBSERVER_VERSION_VAL(2, 0, 0) + */ +#define ASYNCWEBSERVER_VERSION_NUM ASYNCWEBSERVER_VERSION_VAL(ASYNCWEBSERVER_VERSION_MAJOR, ASYNCWEBSERVER_VERSION_MINOR, ASYNCWEBSERVER_VERSION_PATCH) + +/** + * Current version, as string + */ +#define df2xstr(s) #s +#define df2str(s) df2xstr(s) +#define ASYNCWEBSERVER_VERSION df2str(ASYNCWEBSERVER_VERSION_MAJOR) "." df2str(ASYNCWEBSERVER_VERSION_MINOR) "." df2str(ASYNCWEBSERVER_VERSION_PATCH) + +#ifdef __cplusplus +} +#endif diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncWebSocket.cpp b/watering/lib/ESPAsyncWebServer/src/AsyncWebSocket.cpp new file mode 100644 index 0000000..f86d616 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncWebSocket.cpp @@ -0,0 +1,1364 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "AsyncWebSocket.h" +#include "Arduino.h" + +#include + +#include + +#if defined(ESP32) +#if ESP_IDF_VERSION_MAJOR < 5 +#include "BackPort_SHA1Builder.h" +#else +#include +#endif +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) || defined(ESP8266) +#include +#endif + +using namespace asyncsrv; + +size_t webSocketSendFrameWindow(AsyncClient *client) { + if (!client || !client->canSend()) { + return 0; + } + size_t space = client->space(); + if (space < 9) { + return 0; + } + return space - 8; +} + +size_t webSocketSendFrame(AsyncClient *client, bool final, uint8_t opcode, bool mask, uint8_t *data, size_t len) { + if (!client || !client->canSend()) { + // Serial.println("SF 1"); + return 0; + } + size_t space = client->space(); + if (space < 2) { + // Serial.println("SF 2"); + return 0; + } + uint8_t mbuf[4] = {0, 0, 0, 0}; + uint8_t headLen = 2; + if (len && mask) { + headLen += 4; + mbuf[0] = rand() % 0xFF; + mbuf[1] = rand() % 0xFF; + mbuf[2] = rand() % 0xFF; + mbuf[3] = rand() % 0xFF; + } + if (len > 125) { + headLen += 2; + } + if (space < headLen) { + // Serial.println("SF 2"); + return 0; + } + space -= headLen; + + if (len > space) { + len = space; + } + + uint8_t *buf = (uint8_t *)malloc(headLen); + if (buf == NULL) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + client->abort(); + return 0; + } + + buf[0] = opcode & 0x0F; + if (final) { + buf[0] |= 0x80; + } + if (len < 126) { + buf[1] = len & 0x7F; + } else { + buf[1] = 126; + buf[2] = (uint8_t)((len >> 8) & 0xFF); + buf[3] = (uint8_t)(len & 0xFF); + } + if (len && mask) { + buf[1] |= 0x80; + memcpy(buf + (headLen - 4), mbuf, 4); + } + if (client->add((const char *)buf, headLen) != headLen) { + // os_printf("error adding %lu header bytes\n", headLen); + free(buf); + // Serial.println("SF 4"); + return 0; + } + free(buf); + + if (len) { + if (len && mask) { + size_t i; + for (i = 0; i < len; i++) { + data[i] = data[i] ^ mbuf[i % 4]; + } + } + if (client->add((const char *)data, len) != len) { + // os_printf("error adding %lu data bytes\n", len); + // Serial.println("SF 5"); + return 0; + } + } + if (!client->send()) { + // os_printf("error sending frame: %lu\n", headLen+len); + // Serial.println("SF 6"); + return 0; + } + // Serial.println("SF"); + return len; +} + +/* + * AsyncWebSocketMessageBuffer + */ + +AsyncWebSocketMessageBuffer::AsyncWebSocketMessageBuffer(const uint8_t *data, size_t size) : _buffer(std::make_shared>(size)) { + if (_buffer->capacity() < size) { + _buffer->reserve(size); + } else { + std::memcpy(_buffer->data(), data, size); + } +} + +AsyncWebSocketMessageBuffer::AsyncWebSocketMessageBuffer(size_t size) : _buffer(std::make_shared>(size)) { + if (_buffer->capacity() < size) { + _buffer->reserve(size); + } +} + +bool AsyncWebSocketMessageBuffer::reserve(size_t size) { + if (_buffer->capacity() >= size) { + return true; + } + _buffer->reserve(size); + return _buffer->capacity() >= size; +} + +/* + * Control Frame + */ + +class AsyncWebSocketControl { +private: + uint8_t _opcode; + uint8_t *_data; + size_t _len; + bool _mask; + bool _finished; + +public: + AsyncWebSocketControl(uint8_t opcode, const uint8_t *data = NULL, size_t len = 0, bool mask = false) + : _opcode(opcode), _len(len), _mask(len && mask), _finished(false) { + if (data == NULL) { + _len = 0; + } + if (_len) { + if (_len > 125) { + _len = 125; + } + + _data = (uint8_t *)malloc(_len); + + if (_data == NULL) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + _len = 0; + } else { + memcpy(_data, data, len); + } + } else { + _data = NULL; + } + } + + ~AsyncWebSocketControl() { + if (_data != NULL) { + free(_data); + } + } + + bool finished() const { + return _finished; + } + uint8_t opcode() { + return _opcode; + } + uint8_t len() { + return _len + 2; + } + size_t send(AsyncClient *client) { + _finished = true; + return webSocketSendFrame(client, true, _opcode & 0x0F, _mask, _data, _len); + } +}; + +/* + * AsyncWebSocketMessage Message + */ + +AsyncWebSocketMessage::AsyncWebSocketMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode, bool mask) + : _WSbuffer{buffer}, _opcode(opcode & 0x07), _mask{mask}, _status{_WSbuffer ? WS_MSG_SENDING : WS_MSG_ERROR} {} + +void AsyncWebSocketMessage::ack(size_t len, uint32_t time) { + (void)time; + _acked += len; + if (_sent >= _WSbuffer->size() && _acked >= _ack) { + _status = WS_MSG_SENT; + } + // ets_printf("A: %u\n", len); +} + +size_t AsyncWebSocketMessage::send(AsyncClient *client) { + if (!client) { + return 0; + } + + if (_status != WS_MSG_SENDING) { + return 0; + } + if (_acked < _ack) { + return 0; + } + if (_sent == _WSbuffer->size()) { + if (_acked == _ack) { + _status = WS_MSG_SENT; + } + return 0; + } + if (_sent > _WSbuffer->size()) { + _status = WS_MSG_ERROR; + // ets_printf("E: %u > %u\n", _sent, _WSbuffer->length()); + return 0; + } + + size_t toSend = _WSbuffer->size() - _sent; + size_t window = webSocketSendFrameWindow(client); + + if (window < toSend) { + toSend = window; + } + + _sent += toSend; + _ack += toSend + ((toSend < 126) ? 2 : 4) + (_mask * 4); + + // ets_printf("W: %u %u\n", _sent - toSend, toSend); + + bool final = (_sent == _WSbuffer->size()); + uint8_t *dPtr = (uint8_t *)(_WSbuffer->data() + (_sent - toSend)); + uint8_t opCode = (toSend && _sent == toSend) ? _opcode : (uint8_t)WS_CONTINUATION; + + size_t sent = webSocketSendFrame(client, final, opCode, _mask, dPtr, toSend); + _status = WS_MSG_SENDING; + if (toSend && sent != toSend) { + // ets_printf("E: %u != %u\n", toSend, sent); + _sent -= (toSend - sent); + _ack -= (toSend - sent); + } + // ets_printf("S: %u %u\n", _sent, sent); + return sent; +} + +/* + * Async WebSocket Client + */ +const char *AWSC_PING_PAYLOAD = "ESPAsyncWebServer-PING"; +const size_t AWSC_PING_PAYLOAD_LEN = 22; + +AsyncWebSocketClient::AsyncWebSocketClient(AsyncWebServerRequest *request, AsyncWebSocket *server) : _tempObject(NULL) { + _client = request->client(); + _server = server; + _clientId = _server->_getNextId(); + _status = WS_CONNECTED; + _pstate = 0; + _lastMessageTime = millis(); + _keepAlivePeriod = 0; + _client->setRxTimeout(0); + _client->onError( + [](void *r, AsyncClient *c, int8_t error) { + (void)c; + ((AsyncWebSocketClient *)(r))->_onError(error); + }, + this + ); + _client->onAck( + [](void *r, AsyncClient *c, size_t len, uint32_t time) { + (void)c; + ((AsyncWebSocketClient *)(r))->_onAck(len, time); + }, + this + ); + _client->onDisconnect( + [](void *r, AsyncClient *c) { + ((AsyncWebSocketClient *)(r))->_onDisconnect(); + delete c; + }, + this + ); + _client->onTimeout( + [](void *r, AsyncClient *c, uint32_t time) { + (void)c; + ((AsyncWebSocketClient *)(r))->_onTimeout(time); + }, + this + ); + _client->onData( + [](void *r, AsyncClient *c, void *buf, size_t len) { + (void)c; + ((AsyncWebSocketClient *)(r))->_onData(buf, len); + }, + this + ); + _client->onPoll( + [](void *r, AsyncClient *c) { + (void)c; + ((AsyncWebSocketClient *)(r))->_onPoll(); + }, + this + ); + delete request; + memset(&_pinfo, 0, sizeof(_pinfo)); +} + +AsyncWebSocketClient::~AsyncWebSocketClient() { + { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + _messageQueue.clear(); + _controlQueue.clear(); + } + _server->_handleEvent(this, WS_EVT_DISCONNECT, NULL, NULL, 0); +} + +void AsyncWebSocketClient::_clearQueue() { + while (!_messageQueue.empty() && _messageQueue.front().finished()) { + _messageQueue.pop_front(); + } +} + +void AsyncWebSocketClient::_onAck(size_t len, uint32_t time) { + _lastMessageTime = millis(); + +#ifdef ESP32 + std::unique_lock lock(_lock); +#endif + + if (!_controlQueue.empty()) { + auto &head = _controlQueue.front(); + if (head.finished()) { + len -= head.len(); + if (_status == WS_DISCONNECTING && head.opcode() == WS_DISCONNECT) { + _controlQueue.pop_front(); + _status = WS_DISCONNECTED; + if (_client) { +#ifdef ESP32 + /* + Unlocking has to be called before return execution otherwise std::unique_lock ::~unique_lock() will get an exception pthread_mutex_unlock. + Due to _client->close(true) shall call the callback function _onDisconnect() + The calling flow _onDisconnect() --> _handleDisconnect() --> ~AsyncWebSocketClient() + */ + lock.unlock(); +#endif + _client->close(true); + } + return; + } + _controlQueue.pop_front(); + } + } + + if (len && !_messageQueue.empty()) { + _messageQueue.front().ack(len, time); + } + + _clearQueue(); + + _runQueue(); +} + +void AsyncWebSocketClient::_onPoll() { + if (!_client) { + return; + } + +#ifdef ESP32 + std::unique_lock lock(_lock); +#endif + if (_client && _client->canSend() && (!_controlQueue.empty() || !_messageQueue.empty())) { + _runQueue(); + } else if (_keepAlivePeriod > 0 && (millis() - _lastMessageTime) >= _keepAlivePeriod && (_controlQueue.empty() && _messageQueue.empty())) { +#ifdef ESP32 + lock.unlock(); +#endif + ping((uint8_t *)AWSC_PING_PAYLOAD, AWSC_PING_PAYLOAD_LEN); + } +} + +void AsyncWebSocketClient::_runQueue() { + // all calls to this method MUST be protected by a mutex lock! + if (!_client) { + return; + } + + _clearQueue(); + + if (!_controlQueue.empty() && (_messageQueue.empty() || _messageQueue.front().betweenFrames()) + && webSocketSendFrameWindow(_client) > (size_t)(_controlQueue.front().len() - 1)) { + _controlQueue.front().send(_client); + } else if (!_messageQueue.empty() && _messageQueue.front().betweenFrames() && webSocketSendFrameWindow(_client)) { + _messageQueue.front().send(_client); + } +} + +bool AsyncWebSocketClient::queueIsFull() const { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + return (_messageQueue.size() >= WS_MAX_QUEUED_MESSAGES) || (_status != WS_CONNECTED); +} + +size_t AsyncWebSocketClient::queueLen() const { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + return _messageQueue.size(); +} + +bool AsyncWebSocketClient::canSend() const { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + return _messageQueue.size() < WS_MAX_QUEUED_MESSAGES; +} + +bool AsyncWebSocketClient::_queueControl(uint8_t opcode, const uint8_t *data, size_t len, bool mask) { + if (!_client) { + return false; + } + +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + + _controlQueue.emplace_back(opcode, data, len, mask); + + if (_client && _client->canSend()) { + _runQueue(); + } + + return true; +} + +bool AsyncWebSocketClient::_queueMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode, bool mask) { + if (!_client || buffer->size() == 0 || _status != WS_CONNECTED) { + return false; + } + +#ifdef ESP32 + std::unique_lock lock(_lock); +#endif + + if (_messageQueue.size() >= WS_MAX_QUEUED_MESSAGES) { + if (closeWhenFull) { + _status = WS_DISCONNECTED; + + if (_client) { +#ifdef ESP32 + /* + Unlocking has to be called before return execution otherwise std::unique_lock ::~unique_lock() will get an exception pthread_mutex_unlock. + Due to _client->close(true) shall call the callback function _onDisconnect() + The calling flow _onDisconnect() --> _handleDisconnect() --> ~AsyncWebSocketClient() + */ + lock.unlock(); +#endif + _client->close(true); + } + +#ifdef ESP8266 + ets_printf("AsyncWebSocketClient::_queueMessage: Too many messages queued: closing connection\n"); +#elif defined(ESP32) + log_e("Too many messages queued: closing connection"); +#endif + + } else { +#ifdef ESP8266 + ets_printf("AsyncWebSocketClient::_queueMessage: Too many messages queued: discarding new message\n"); +#elif defined(ESP32) + log_e("Too many messages queued: discarding new message"); +#endif + } + + return false; + } + + _messageQueue.emplace_back(buffer, opcode, mask); + + if (_client && _client->canSend()) { + _runQueue(); + } + + return true; +} + +void AsyncWebSocketClient::close(uint16_t code, const char *message) { + if (_status != WS_CONNECTED) { + return; + } + + _status = WS_DISCONNECTING; + + if (code) { + uint8_t packetLen = 2; + if (message != NULL) { + size_t mlen = strlen(message); + if (mlen > 123) { + mlen = 123; + } + packetLen += mlen; + } + char *buf = (char *)malloc(packetLen); + if (buf != NULL) { + buf[0] = (uint8_t)(code >> 8); + buf[1] = (uint8_t)(code & 0xFF); + if (message != NULL) { + memcpy(buf + 2, message, packetLen - 2); + } + _queueControl(WS_DISCONNECT, (uint8_t *)buf, packetLen); + free(buf); + return; + } else { +#ifdef ESP32 + log_e("Failed to allocate"); + _client->abort(); +#endif + } + } + _queueControl(WS_DISCONNECT); +} + +bool AsyncWebSocketClient::ping(const uint8_t *data, size_t len) { + return _status == WS_CONNECTED && _queueControl(WS_PING, data, len); +} + +void AsyncWebSocketClient::_onError(int8_t) { + // Serial.println("onErr"); +} + +void AsyncWebSocketClient::_onTimeout(uint32_t time) { + if (!_client) { + return; + } + // Serial.println("onTime"); + (void)time; + _client->close(true); +} + +void AsyncWebSocketClient::_onDisconnect() { + // Serial.println("onDis"); + _client = nullptr; + _server->_handleDisconnect(this); +} + +void AsyncWebSocketClient::_onData(void *pbuf, size_t plen) { + _lastMessageTime = millis(); + uint8_t *data = (uint8_t *)pbuf; + while (plen > 0) { + if (!_pstate) { + const uint8_t *fdata = data; + + _pinfo.index = 0; + _pinfo.final = (fdata[0] & 0x80) != 0; + _pinfo.opcode = fdata[0] & 0x0F; + _pinfo.masked = (fdata[1] & 0x80) != 0; + _pinfo.len = fdata[1] & 0x7F; + + // log_d("WS[%" PRIu32 "]: _onData: %" PRIu32, _clientId, plen); + // log_d("WS[%" PRIu32 "]: _status = %" PRIu32, _clientId, _status); + // log_d("WS[%" PRIu32 "]: _pinfo: index: %" PRIu64 ", final: %" PRIu8 ", opcode: %" PRIu8 ", masked: %" PRIu8 ", len: %" PRIu64, _clientId, _pinfo.index, _pinfo.final, _pinfo.opcode, _pinfo.masked, _pinfo.len); + + data += 2; + plen -= 2; + + if (_pinfo.len == 126 && plen >= 2) { + _pinfo.len = fdata[3] | (uint16_t)(fdata[2]) << 8; + data += 2; + plen -= 2; + + } else if (_pinfo.len == 127 && plen >= 8) { + _pinfo.len = fdata[9] | (uint16_t)(fdata[8]) << 8 | (uint32_t)(fdata[7]) << 16 | (uint32_t)(fdata[6]) << 24 | (uint64_t)(fdata[5]) << 32 + | (uint64_t)(fdata[4]) << 40 | (uint64_t)(fdata[3]) << 48 | (uint64_t)(fdata[2]) << 56; + data += 8; + plen -= 8; + } + + if (_pinfo.masked + && plen >= 4) { // if ws.close() is called, Safari sends a close frame with plen 2 and masked bit set. We must not decrement plen which is already 0. + memcpy(_pinfo.mask, data, 4); + data += 4; + plen -= 4; + } + } + + const size_t datalen = std::min((size_t)(_pinfo.len - _pinfo.index), plen); + const auto datalast = data[datalen]; + + if (_pinfo.masked) { + for (size_t i = 0; i < datalen; i++) { + data[i] ^= _pinfo.mask[(_pinfo.index + i) % 4]; + } + } + + if ((datalen + _pinfo.index) < _pinfo.len) { + _pstate = 1; + + if (_pinfo.index == 0) { + if (_pinfo.opcode) { + _pinfo.message_opcode = _pinfo.opcode; + _pinfo.num = 0; + } + } + if (datalen > 0) { + _server->_handleEvent(this, WS_EVT_DATA, (void *)&_pinfo, data, datalen); + } + + _pinfo.index += datalen; + } else if ((datalen + _pinfo.index) == _pinfo.len) { + _pstate = 0; + if (_pinfo.opcode == WS_DISCONNECT) { + if (datalen) { + uint16_t reasonCode = (uint16_t)(data[0] << 8) + data[1]; + char *reasonString = (char *)(data + 2); + if (reasonCode > 1001) { + _server->_handleEvent(this, WS_EVT_ERROR, (void *)&reasonCode, (uint8_t *)reasonString, strlen(reasonString)); + } + } + if (_status == WS_DISCONNECTING) { + _status = WS_DISCONNECTED; + if (_client) { + _client->close(true); + } + } else { + _status = WS_DISCONNECTING; + if (_client) { + _client->ackLater(); + } + _queueControl(WS_DISCONNECT, data, datalen); + } + } else if (_pinfo.opcode == WS_PING) { + _server->_handleEvent(this, WS_EVT_PING, NULL, NULL, 0); + _queueControl(WS_PONG, data, datalen); + } else if (_pinfo.opcode == WS_PONG) { + if (datalen != AWSC_PING_PAYLOAD_LEN || memcmp(AWSC_PING_PAYLOAD, data, AWSC_PING_PAYLOAD_LEN) != 0) { + _server->_handleEvent(this, WS_EVT_PONG, NULL, NULL, 0); + } + } else if (_pinfo.opcode < WS_DISCONNECT) { // continuation or text/binary frame + _server->_handleEvent(this, WS_EVT_DATA, (void *)&_pinfo, data, datalen); + if (_pinfo.final) { + _pinfo.num = 0; + } else { + _pinfo.num += 1; + } + } + } else { + // os_printf("frame error: len: %u, index: %llu, total: %llu\n", datalen, _pinfo.index, _pinfo.len); + // what should we do? + break; + } + + // restore byte as _handleEvent may have added a null terminator i.e., data[len] = 0; + if (datalen) { + data[datalen] = datalast; + } + + data += datalen; + plen -= datalen; + } +} + +size_t AsyncWebSocketClient::printf(const char *format, ...) { + va_list arg; + va_start(arg, format); + size_t len = vsnprintf(nullptr, 0, format, arg); + va_end(arg); + + if (len == 0) { + return 0; + } + + char *buffer = new char[len + 1]; + + if (!buffer) { + return 0; + } + + va_start(arg, format); + len = vsnprintf(buffer, len + 1, format, arg); + va_end(arg); + + bool enqueued = text(buffer, len); + delete[] buffer; + return enqueued ? len : 0; +} + +#ifdef ESP8266 +size_t AsyncWebSocketClient::printf_P(PGM_P formatP, ...) { + va_list arg; + va_start(arg, formatP); + size_t len = vsnprintf_P(nullptr, 0, formatP, arg); + va_end(arg); + + if (len == 0) { + return 0; + } + + char *buffer = new char[len + 1]; + + if (!buffer) { + return 0; + } + + va_start(arg, formatP); + len = vsnprintf_P(buffer, len + 1, formatP, arg); + va_end(arg); + + bool enqueued = text(buffer, len); + delete[] buffer; + return enqueued ? len : 0; +} +#endif + +namespace { +AsyncWebSocketSharedBuffer makeSharedBuffer(const uint8_t *message, size_t len) { + auto buffer = std::make_shared>(len); + std::memcpy(buffer->data(), message, len); + return buffer; +} +} // namespace + +bool AsyncWebSocketClient::text(AsyncWebSocketMessageBuffer *buffer) { + bool enqueued = false; + if (buffer) { + enqueued = text(std::move(buffer->_buffer)); + delete buffer; + } + return enqueued; +} + +bool AsyncWebSocketClient::text(AsyncWebSocketSharedBuffer buffer) { + return _queueMessage(buffer); +} + +bool AsyncWebSocketClient::text(const uint8_t *message, size_t len) { + return text(makeSharedBuffer(message, len)); +} + +bool AsyncWebSocketClient::text(const char *message, size_t len) { + return text((const uint8_t *)message, len); +} + +bool AsyncWebSocketClient::text(const char *message) { + return text(message, strlen(message)); +} + +bool AsyncWebSocketClient::text(const String &message) { + return text(message.c_str(), message.length()); +} + +#ifdef ESP8266 +bool AsyncWebSocketClient::text(const __FlashStringHelper *data) { + PGM_P p = reinterpret_cast(data); + + size_t n = 0; + while (1) { + if (pgm_read_byte(p + n) == 0) { + break; + } + n += 1; + } + + char *message = (char *)malloc(n + 1); + bool enqueued = false; + if (message) { + memcpy_P(message, p, n); + message[n] = 0; + enqueued = text(message, n); + free(message); + } + return enqueued; +} +#endif // ESP8266 + +bool AsyncWebSocketClient::binary(AsyncWebSocketMessageBuffer *buffer) { + bool enqueued = false; + if (buffer) { + enqueued = binary(std::move(buffer->_buffer)); + delete buffer; + } + return enqueued; +} + +bool AsyncWebSocketClient::binary(AsyncWebSocketSharedBuffer buffer) { + return _queueMessage(buffer, WS_BINARY); +} + +bool AsyncWebSocketClient::binary(const uint8_t *message, size_t len) { + return binary(makeSharedBuffer(message, len)); +} + +bool AsyncWebSocketClient::binary(const char *message, size_t len) { + return binary((const uint8_t *)message, len); +} + +bool AsyncWebSocketClient::binary(const char *message) { + return binary(message, strlen(message)); +} + +bool AsyncWebSocketClient::binary(const String &message) { + return binary(message.c_str(), message.length()); +} + +#ifdef ESP8266 +bool AsyncWebSocketClient::binary(const __FlashStringHelper *data, size_t len) { + PGM_P p = reinterpret_cast(data); + char *message = (char *)malloc(len); + bool enqueued = false; + if (message) { + memcpy_P(message, p, len); + enqueued = binary(message, len); + free(message); + } + return enqueued; +} +#endif + +IPAddress AsyncWebSocketClient::remoteIP() const { + if (!_client) { + return IPAddress((uint32_t)0U); + } + + return _client->remoteIP(); +} + +uint16_t AsyncWebSocketClient::remotePort() const { + if (!_client) { + return 0; + } + + return _client->remotePort(); +} + +/* + * Async Web Socket - Each separate socket location + */ + +void AsyncWebSocket::_handleEvent(AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { + if (_eventHandler != NULL) { + _eventHandler(this, client, type, arg, data, len); + } +} + +AsyncWebSocketClient *AsyncWebSocket::_newClient(AsyncWebServerRequest *request) { + _clients.emplace_back(request, this); + _handleEvent(&_clients.back(), WS_EVT_CONNECT, request, NULL, 0); + return &_clients.back(); +} + +void AsyncWebSocket::_handleDisconnect(AsyncWebSocketClient *client) { + const auto client_id = client->id(); + const auto iter = std::find_if(std::begin(_clients), std::end(_clients), [client_id](const AsyncWebSocketClient &c) { + return c.id() == client_id; + }); + if (iter != std::end(_clients)) { + _clients.erase(iter); + } +} + +bool AsyncWebSocket::availableForWriteAll() { + return std::none_of(std::begin(_clients), std::end(_clients), [](const AsyncWebSocketClient &c) { + return c.queueIsFull(); + }); +} + +bool AsyncWebSocket::availableForWrite(uint32_t id) { + const auto iter = std::find_if(std::begin(_clients), std::end(_clients), [id](const AsyncWebSocketClient &c) { + return c.id() == id; + }); + if (iter == std::end(_clients)) { + return true; + } + return !iter->queueIsFull(); +} + +size_t AsyncWebSocket::count() const { + return std::count_if(std::begin(_clients), std::end(_clients), [](const AsyncWebSocketClient &c) { + return c.status() == WS_CONNECTED; + }); +} + +AsyncWebSocketClient *AsyncWebSocket::client(uint32_t id) { + const auto iter = std::find_if(_clients.begin(), _clients.end(), [id](const AsyncWebSocketClient &c) { + return c.id() == id && c.status() == WS_CONNECTED; + }); + if (iter == std::end(_clients)) { + return nullptr; + } + + return &(*iter); +} + +void AsyncWebSocket::close(uint32_t id, uint16_t code, const char *message) { + if (AsyncWebSocketClient *c = client(id)) { + c->close(code, message); + } +} + +void AsyncWebSocket::closeAll(uint16_t code, const char *message) { + for (auto &c : _clients) { + if (c.status() == WS_CONNECTED) { + c.close(code, message); + } + } +} + +void AsyncWebSocket::cleanupClients(uint16_t maxClients) { + if (count() > maxClients) { + _clients.front().close(); + } + + for (auto i = _clients.begin(); i != _clients.end(); ++i) { + if (i->shouldBeDeleted()) { + _clients.erase(i); + break; + } + } +} + +bool AsyncWebSocket::ping(uint32_t id, const uint8_t *data, size_t len) { + AsyncWebSocketClient *c = client(id); + return c && c->ping(data, len); +} + +AsyncWebSocket::SendStatus AsyncWebSocket::pingAll(const uint8_t *data, size_t len) { + size_t hit = 0; + size_t miss = 0; + for (auto &c : _clients) { + if (c.status() == WS_CONNECTED && c.ping(data, len)) { + hit++; + } else { + miss++; + } + } + return hit == 0 ? DISCARDED : (miss == 0 ? ENQUEUED : PARTIALLY_ENQUEUED); +} + +bool AsyncWebSocket::text(uint32_t id, const uint8_t *message, size_t len) { + AsyncWebSocketClient *c = client(id); + return c && c->text(makeSharedBuffer(message, len)); +} +bool AsyncWebSocket::text(uint32_t id, const char *message, size_t len) { + return text(id, (const uint8_t *)message, len); +} +bool AsyncWebSocket::text(uint32_t id, const char *message) { + return text(id, message, strlen(message)); +} +bool AsyncWebSocket::text(uint32_t id, const String &message) { + return text(id, message.c_str(), message.length()); +} + +#ifdef ESP8266 +bool AsyncWebSocket::text(uint32_t id, const __FlashStringHelper *data) { + PGM_P p = reinterpret_cast(data); + + size_t n = 0; + while (true) { + if (pgm_read_byte(p + n) == 0) { + break; + } + n += 1; + } + + char *message = (char *)malloc(n + 1); + bool enqueued = false; + if (message) { + memcpy_P(message, p, n); + message[n] = 0; + enqueued = text(id, message, n); + free(message); + } + return enqueued; +} +#endif // ESP8266 + +bool AsyncWebSocket::text(uint32_t id, AsyncWebSocketMessageBuffer *buffer) { + bool enqueued = false; + if (buffer) { + enqueued = text(id, std::move(buffer->_buffer)); + delete buffer; + } + return enqueued; +} +bool AsyncWebSocket::text(uint32_t id, AsyncWebSocketSharedBuffer buffer) { + AsyncWebSocketClient *c = client(id); + return c && c->text(buffer); +} + +AsyncWebSocket::SendStatus AsyncWebSocket::textAll(const uint8_t *message, size_t len) { + return textAll(makeSharedBuffer(message, len)); +} +AsyncWebSocket::SendStatus AsyncWebSocket::textAll(const char *message, size_t len) { + return textAll((const uint8_t *)message, len); +} +AsyncWebSocket::SendStatus AsyncWebSocket::textAll(const char *message) { + return textAll(message, strlen(message)); +} +AsyncWebSocket::SendStatus AsyncWebSocket::textAll(const String &message) { + return textAll(message.c_str(), message.length()); +} +#ifdef ESP8266 +AsyncWebSocket::SendStatus AsyncWebSocket::textAll(const __FlashStringHelper *data) { + PGM_P p = reinterpret_cast(data); + + size_t n = 0; + while (1) { + if (pgm_read_byte(p + n) == 0) { + break; + } + n += 1; + } + + char *message = (char *)malloc(n + 1); + AsyncWebSocket::SendStatus status = DISCARDED; + if (message) { + memcpy_P(message, p, n); + message[n] = 0; + status = textAll(message, n); + free(message); + } + return status; +} +#endif // ESP8266 +AsyncWebSocket::SendStatus AsyncWebSocket::textAll(AsyncWebSocketMessageBuffer *buffer) { + AsyncWebSocket::SendStatus status = DISCARDED; + if (buffer) { + status = textAll(std::move(buffer->_buffer)); + delete buffer; + } + return status; +} + +AsyncWebSocket::SendStatus AsyncWebSocket::textAll(AsyncWebSocketSharedBuffer buffer) { + size_t hit = 0; + size_t miss = 0; + for (auto &c : _clients) { + if (c.status() == WS_CONNECTED && c.text(buffer)) { + hit++; + } else { + miss++; + } + } + return hit == 0 ? DISCARDED : (miss == 0 ? ENQUEUED : PARTIALLY_ENQUEUED); +} + +bool AsyncWebSocket::binary(uint32_t id, const uint8_t *message, size_t len) { + AsyncWebSocketClient *c = client(id); + return c && c->binary(makeSharedBuffer(message, len)); +} +bool AsyncWebSocket::binary(uint32_t id, const char *message, size_t len) { + return binary(id, (const uint8_t *)message, len); +} +bool AsyncWebSocket::binary(uint32_t id, const char *message) { + return binary(id, message, strlen(message)); +} +bool AsyncWebSocket::binary(uint32_t id, const String &message) { + return binary(id, message.c_str(), message.length()); +} + +#ifdef ESP8266 +bool AsyncWebSocket::binary(uint32_t id, const __FlashStringHelper *data, size_t len) { + PGM_P p = reinterpret_cast(data); + char *message = (char *)malloc(len); + bool enqueued = false; + if (message) { + memcpy_P(message, p, len); + enqueued = binary(id, message, len); + free(message); + } + return enqueued; +} +#endif // ESP8266 + +bool AsyncWebSocket::binary(uint32_t id, AsyncWebSocketMessageBuffer *buffer) { + bool enqueued = false; + if (buffer) { + enqueued = binary(id, std::move(buffer->_buffer)); + delete buffer; + } + return enqueued; +} +bool AsyncWebSocket::binary(uint32_t id, AsyncWebSocketSharedBuffer buffer) { + AsyncWebSocketClient *c = client(id); + return c && c->binary(buffer); +} + +AsyncWebSocket::SendStatus AsyncWebSocket::binaryAll(const uint8_t *message, size_t len) { + return binaryAll(makeSharedBuffer(message, len)); +} +AsyncWebSocket::SendStatus AsyncWebSocket::binaryAll(const char *message, size_t len) { + return binaryAll((const uint8_t *)message, len); +} +AsyncWebSocket::SendStatus AsyncWebSocket::binaryAll(const char *message) { + return binaryAll(message, strlen(message)); +} +AsyncWebSocket::SendStatus AsyncWebSocket::binaryAll(const String &message) { + return binaryAll(message.c_str(), message.length()); +} + +#ifdef ESP8266 +AsyncWebSocket::SendStatus AsyncWebSocket::binaryAll(const __FlashStringHelper *data, size_t len) { + PGM_P p = reinterpret_cast(data); + char *message = (char *)malloc(len); + AsyncWebSocket::SendStatus status = DISCARDED; + if (message) { + memcpy_P(message, p, len); + status = binaryAll(message, len); + free(message); + } + return status; +} +#endif // ESP8266 + +AsyncWebSocket::SendStatus AsyncWebSocket::binaryAll(AsyncWebSocketMessageBuffer *buffer) { + AsyncWebSocket::SendStatus status = DISCARDED; + if (buffer) { + status = binaryAll(std::move(buffer->_buffer)); + delete buffer; + } + return status; +} +AsyncWebSocket::SendStatus AsyncWebSocket::binaryAll(AsyncWebSocketSharedBuffer buffer) { + size_t hit = 0; + size_t miss = 0; + for (auto &c : _clients) { + if (c.status() == WS_CONNECTED && c.binary(buffer)) { + hit++; + } else { + miss++; + } + } + return hit == 0 ? DISCARDED : (miss == 0 ? ENQUEUED : PARTIALLY_ENQUEUED); +} + +size_t AsyncWebSocket::printf(uint32_t id, const char *format, ...) { + AsyncWebSocketClient *c = client(id); + if (c) { + va_list arg; + va_start(arg, format); + size_t len = c->printf(format, arg); + va_end(arg); + return len; + } + return 0; +} + +size_t AsyncWebSocket::printfAll(const char *format, ...) { + va_list arg; + va_start(arg, format); + size_t len = vsnprintf(nullptr, 0, format, arg); + va_end(arg); + + if (len == 0) { + return 0; + } + + char *buffer = new char[len + 1]; + + if (!buffer) { + return 0; + } + + va_start(arg, format); + len = vsnprintf(buffer, len + 1, format, arg); + va_end(arg); + + AsyncWebSocket::SendStatus status = textAll(buffer, len); + delete[] buffer; + return status == DISCARDED ? 0 : len; +} + +#ifdef ESP8266 +size_t AsyncWebSocket::printf_P(uint32_t id, PGM_P formatP, ...) { + AsyncWebSocketClient *c = client(id); + if (c != NULL) { + va_list arg; + va_start(arg, formatP); + size_t len = c->printf_P(formatP, arg); + va_end(arg); + return len; + } + return 0; +} + +size_t AsyncWebSocket::printfAll_P(PGM_P formatP, ...) { + va_list arg; + va_start(arg, formatP); + size_t len = vsnprintf_P(nullptr, 0, formatP, arg); + va_end(arg); + + if (len == 0) { + return 0; + } + + char *buffer = new char[len + 1]; + + if (!buffer) { + return 0; + } + + va_start(arg, formatP); + len = vsnprintf_P(buffer, len + 1, formatP, arg); + va_end(arg); + + AsyncWebSocket::SendStatus status = textAll(buffer, len); + delete[] buffer; + return status == DISCARDED ? 0 : len; +} +#endif + +const char __WS_STR_CONNECTION[] PROGMEM = {"Connection"}; +const char __WS_STR_UPGRADE[] PROGMEM = {"Upgrade"}; +const char __WS_STR_ORIGIN[] PROGMEM = {"Origin"}; +const char __WS_STR_COOKIE[] PROGMEM = {"Cookie"}; +const char __WS_STR_VERSION[] PROGMEM = {"Sec-WebSocket-Version"}; +const char __WS_STR_KEY[] PROGMEM = {"Sec-WebSocket-Key"}; +const char __WS_STR_PROTOCOL[] PROGMEM = {"Sec-WebSocket-Protocol"}; +const char __WS_STR_ACCEPT[] PROGMEM = {"Sec-WebSocket-Accept"}; +const char __WS_STR_UUID[] PROGMEM = {"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"}; + +#define WS_STR_UUID_LEN 36 + +#define WS_STR_CONNECTION FPSTR(__WS_STR_CONNECTION) +#define WS_STR_UPGRADE FPSTR(__WS_STR_UPGRADE) +#define WS_STR_ORIGIN FPSTR(__WS_STR_ORIGIN) +#define WS_STR_COOKIE FPSTR(__WS_STR_COOKIE) +#define WS_STR_VERSION FPSTR(__WS_STR_VERSION) +#define WS_STR_KEY FPSTR(__WS_STR_KEY) +#define WS_STR_PROTOCOL FPSTR(__WS_STR_PROTOCOL) +#define WS_STR_ACCEPT FPSTR(__WS_STR_ACCEPT) +#define WS_STR_UUID FPSTR(__WS_STR_UUID) + +bool AsyncWebSocket::canHandle(AsyncWebServerRequest *request) const { + return _enabled && request->isWebSocketUpgrade() && request->url().equals(_url); +} + +void AsyncWebSocket::handleRequest(AsyncWebServerRequest *request) { + if (!request->hasHeader(WS_STR_VERSION) || !request->hasHeader(WS_STR_KEY)) { + request->send(400); + return; + } + if (_handshakeHandler != nullptr) { + if (!_handshakeHandler(request)) { + request->send(401); + return; + } + } + const AsyncWebHeader *version = request->getHeader(WS_STR_VERSION); + if (version->value().toInt() != 13) { + AsyncWebServerResponse *response = request->beginResponse(400); + response->addHeader(WS_STR_VERSION, T_13); + request->send(response); + return; + } + const AsyncWebHeader *key = request->getHeader(WS_STR_KEY); + AsyncWebServerResponse *response = new AsyncWebSocketResponse(key->value(), this); + if (response == NULL) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + request->abort(); + return; + } + if (request->hasHeader(WS_STR_PROTOCOL)) { + const AsyncWebHeader *protocol = request->getHeader(WS_STR_PROTOCOL); + // ToDo: check protocol + response->addHeader(WS_STR_PROTOCOL, protocol->value()); + } + request->send(response); +} + +AsyncWebSocketMessageBuffer *AsyncWebSocket::makeBuffer(size_t size) { + return new AsyncWebSocketMessageBuffer(size); +} + +AsyncWebSocketMessageBuffer *AsyncWebSocket::makeBuffer(const uint8_t *data, size_t size) { + return new AsyncWebSocketMessageBuffer(data, size); +} + +/* + * Response to Web Socket request - sends the authorization and detaches the TCP Client from the web server + * Authentication code from https://github.com/Links2004/arduinoWebSockets/blob/master/src/WebSockets.cpp#L480 + */ + +AsyncWebSocketResponse::AsyncWebSocketResponse(const String &key, AsyncWebSocket *server) { + _server = server; + _code = 101; + _sendContentLength = false; + + uint8_t hash[20]; + char buffer[33]; + +#if defined(ESP8266) || defined(TARGET_RP2040) || defined(PICO_RP2040) || defined(PICO_RP2350) || defined(TARGET_RP2350) + sha1(key + WS_STR_UUID, hash); +#else + String k; + if (!k.reserve(key.length() + WS_STR_UUID_LEN)) { + log_e("Failed to allocate"); + return; + } + k.concat(key); + k.concat(WS_STR_UUID); + SHA1Builder sha1; + sha1.begin(); + sha1.add((const uint8_t *)k.c_str(), k.length()); + sha1.calculate(); + sha1.getBytes(hash); +#endif + base64_encodestate _state; + base64_init_encodestate(&_state); + int len = base64_encode_block((const char *)hash, 20, buffer, &_state); + len = base64_encode_blockend((buffer + len), &_state); + addHeader(WS_STR_CONNECTION, WS_STR_UPGRADE); + addHeader(WS_STR_UPGRADE, T_WS); + addHeader(WS_STR_ACCEPT, buffer); +} + +void AsyncWebSocketResponse::_respond(AsyncWebServerRequest *request) { + if (_state == RESPONSE_FAILED) { + request->client()->close(true); + return; + } + String out; + _assembleHead(out, request->version()); + request->client()->write(out.c_str(), _headLength); + _state = RESPONSE_WAIT_ACK; +} + +size_t AsyncWebSocketResponse::_ack(AsyncWebServerRequest *request, size_t len, uint32_t time) { + (void)time; + + if (len) { + _server->_newClient(request); + } + + return 0; +} diff --git a/watering/lib/ESPAsyncWebServer/src/AsyncWebSocket.h b/watering/lib/ESPAsyncWebServer/src/AsyncWebSocket.h new file mode 100644 index 0000000..122aca9 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/AsyncWebSocket.h @@ -0,0 +1,499 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef ASYNCWEBSOCKET_H_ +#define ASYNCWEBSOCKET_H_ + +#include +#ifdef ESP32 +#include +#include +#ifndef WS_MAX_QUEUED_MESSAGES +#define WS_MAX_QUEUED_MESSAGES 32 +#endif +#elif defined(ESP8266) +#include +#ifndef WS_MAX_QUEUED_MESSAGES +#define WS_MAX_QUEUED_MESSAGES 8 +#endif +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#ifndef WS_MAX_QUEUED_MESSAGES +#define WS_MAX_QUEUED_MESSAGES 32 +#endif +#endif + +#include + +#include + +#ifdef ESP8266 +#include +#ifdef CRYPTO_HASH_h // include Hash.h from espressif framework if the first include was from the crypto library +#include <../src/Hash.h> +#endif +#endif + +#ifndef DEFAULT_MAX_WS_CLIENTS +#ifdef ESP32 +#define DEFAULT_MAX_WS_CLIENTS 8 +#else +#define DEFAULT_MAX_WS_CLIENTS 4 +#endif +#endif + +using AsyncWebSocketSharedBuffer = std::shared_ptr>; + +class AsyncWebSocket; +class AsyncWebSocketResponse; +class AsyncWebSocketClient; +class AsyncWebSocketControl; + +typedef struct { + /** Message type as defined by enum AwsFrameType. + * Note: Applications will only see WS_TEXT and WS_BINARY. + * All other types are handled by the library. */ + uint8_t message_opcode; + /** Frame number of a fragmented message. */ + uint32_t num; + /** Is this the last frame in a fragmented message ?*/ + uint8_t final; + /** Is this frame masked? */ + uint8_t masked; + /** Message type as defined by enum AwsFrameType. + * This value is the same as message_opcode for non-fragmented + * messages, but may also be WS_CONTINUATION in a fragmented message. */ + uint8_t opcode; + /** Length of the current frame. + * This equals the total length of the message if num == 0 && final == true */ + uint64_t len; + /** Mask key */ + uint8_t mask[4]; + /** Offset of the data inside the current frame. */ + uint64_t index; +} AwsFrameInfo; + +typedef enum { + WS_DISCONNECTED, + WS_CONNECTED, + WS_DISCONNECTING +} AwsClientStatus; +typedef enum { + WS_CONTINUATION, + WS_TEXT, + WS_BINARY, + WS_DISCONNECT = 0x08, + WS_PING, + WS_PONG +} AwsFrameType; +typedef enum { + WS_MSG_SENDING, + WS_MSG_SENT, + WS_MSG_ERROR +} AwsMessageStatus; +typedef enum { + WS_EVT_CONNECT, + WS_EVT_DISCONNECT, + WS_EVT_PING, + WS_EVT_PONG, + WS_EVT_ERROR, + WS_EVT_DATA +} AwsEventType; + +class AsyncWebSocketMessageBuffer { + friend AsyncWebSocket; + friend AsyncWebSocketClient; + +private: + AsyncWebSocketSharedBuffer _buffer; + +public: + AsyncWebSocketMessageBuffer() {} + explicit AsyncWebSocketMessageBuffer(size_t size); + AsyncWebSocketMessageBuffer(const uint8_t *data, size_t size); + //~AsyncWebSocketMessageBuffer(); + bool reserve(size_t size); + uint8_t *get() { + return _buffer->data(); + } + size_t length() const { + return _buffer->size(); + } +}; + +class AsyncWebSocketMessage { +private: + AsyncWebSocketSharedBuffer _WSbuffer; + uint8_t _opcode{WS_TEXT}; + bool _mask{false}; + AwsMessageStatus _status{WS_MSG_ERROR}; + size_t _sent{}; + size_t _ack{}; + size_t _acked{}; + +public: + AsyncWebSocketMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false); + + bool finished() const { + return _status != WS_MSG_SENDING; + } + bool betweenFrames() const { + return _acked == _ack; + } + + void ack(size_t len, uint32_t time); + size_t send(AsyncClient *client); +}; + +class AsyncWebSocketClient { +private: + AsyncClient *_client; + AsyncWebSocket *_server; + uint32_t _clientId; + AwsClientStatus _status; +#ifdef ESP32 + mutable std::recursive_mutex _lock; +#endif + std::deque _controlQueue; + std::deque _messageQueue; + bool closeWhenFull = true; + + uint8_t _pstate; + AwsFrameInfo _pinfo; + + uint32_t _lastMessageTime; + uint32_t _keepAlivePeriod; + + bool _queueControl(uint8_t opcode, const uint8_t *data = NULL, size_t len = 0, bool mask = false); + bool _queueMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false); + void _runQueue(); + void _clearQueue(); + +public: + void *_tempObject; + + AsyncWebSocketClient(AsyncWebServerRequest *request, AsyncWebSocket *server); + ~AsyncWebSocketClient(); + + // client id increments for the given server + uint32_t id() const { + return _clientId; + } + AwsClientStatus status() const { + return _status; + } + AsyncClient *client() { + return _client; + } + const AsyncClient *client() const { + return _client; + } + AsyncWebSocket *server() { + return _server; + } + const AsyncWebSocket *server() const { + return _server; + } + AwsFrameInfo const &pinfo() const { + return _pinfo; + } + + // - If "true" (default), the connection will be closed if the message queue is full. + // This is the default behavior in yubox-node-org, which is not silently discarding messages but instead closes the connection. + // The big issue with this behavior is that is can cause the UI to automatically re-create a new WS connection, which can be filled again, + // and so on, causing a resource exhaustion. + // + // - If "false", the incoming message will be discarded if the queue is full. + // This is the default behavior in the original ESPAsyncWebServer library from me-no-dev. + // This behavior allows the best performance at the expense of unreliable message delivery in case the queue is full (some messages may be lost). + // + // - In any case, when the queue is full, a message is logged. + // - IT is recommended to use the methods queueIsFull(), availableForWriteAll(), availableForWrite(clientId) to check if the queue is full before sending a message. + // + // Usage: + // - can be set in the onEvent listener when connecting (event type is: WS_EVT_CONNECT) + // + // Use cases:, + // - if using websocket to send logging messages, maybe some loss is acceptable. + // - But if using websocket to send UI update messages, maybe the connection should be closed and the UI redrawn. + void setCloseClientOnQueueFull(bool close) { + closeWhenFull = close; + } + bool willCloseClientOnQueueFull() const { + return closeWhenFull; + } + + IPAddress remoteIP() const; + uint16_t remotePort() const; + + bool shouldBeDeleted() const { + return !_client; + } + + // control frames + void close(uint16_t code = 0, const char *message = NULL); + bool ping(const uint8_t *data = NULL, size_t len = 0); + + // set auto-ping period in seconds. disabled if zero (default) + void keepAlivePeriod(uint16_t seconds) { + _keepAlivePeriod = seconds * 1000; + } + uint16_t keepAlivePeriod() { + return (uint16_t)(_keepAlivePeriod / 1000); + } + + // data packets + void message(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false) { + _queueMessage(buffer, opcode, mask); + } + bool queueIsFull() const; + size_t queueLen() const; + + size_t printf(const char *format, ...) __attribute__((format(printf, 2, 3))); + + bool text(AsyncWebSocketSharedBuffer buffer); + bool text(const uint8_t *message, size_t len); + bool text(const char *message, size_t len); + bool text(const char *message); + bool text(const String &message); + bool text(AsyncWebSocketMessageBuffer *buffer); + + bool binary(AsyncWebSocketSharedBuffer buffer); + bool binary(const uint8_t *message, size_t len); + bool binary(const char *message, size_t len); + bool binary(const char *message); + bool binary(const String &message); + bool binary(AsyncWebSocketMessageBuffer *buffer); + + bool canSend() const; + + // system callbacks (do not call) + void _onAck(size_t len, uint32_t time); + void _onError(int8_t); + void _onPoll(); + void _onTimeout(uint32_t time); + void _onDisconnect(); + void _onData(void *pbuf, size_t plen); + +#ifdef ESP8266 + size_t printf_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3))); + bool text(const __FlashStringHelper *message); + bool binary(const __FlashStringHelper *message, size_t len); +#endif +}; + +using AwsHandshakeHandler = std::function; +using AwsEventHandler = std::function; + +// WebServer Handler implementation that plays the role of a socket server +class AsyncWebSocket : public AsyncWebHandler { +private: + String _url; + std::list _clients; + uint32_t _cNextId; + AwsEventHandler _eventHandler; + AwsHandshakeHandler _handshakeHandler; + bool _enabled; +#ifdef ESP32 + mutable std::mutex _lock; +#endif + +public: + typedef enum { + DISCARDED = 0, + ENQUEUED = 1, + PARTIALLY_ENQUEUED = 2, + } SendStatus; + + explicit AsyncWebSocket(const char *url, AwsEventHandler handler = nullptr) : _url(url), _cNextId(1), _eventHandler(handler), _enabled(true) {} + AsyncWebSocket(const String &url, AwsEventHandler handler = nullptr) : _url(url), _cNextId(1), _eventHandler(handler), _enabled(true) {} + ~AsyncWebSocket(){}; + const char *url() const { + return _url.c_str(); + } + void enable(bool e) { + _enabled = e; + } + bool enabled() const { + return _enabled; + } + bool availableForWriteAll(); + bool availableForWrite(uint32_t id); + + size_t count() const; + AsyncWebSocketClient *client(uint32_t id); + bool hasClient(uint32_t id) { + return client(id) != nullptr; + } + + void close(uint32_t id, uint16_t code = 0, const char *message = NULL); + void closeAll(uint16_t code = 0, const char *message = NULL); + void cleanupClients(uint16_t maxClients = DEFAULT_MAX_WS_CLIENTS); + + bool ping(uint32_t id, const uint8_t *data = NULL, size_t len = 0); + SendStatus pingAll(const uint8_t *data = NULL, size_t len = 0); // done + + bool text(uint32_t id, const uint8_t *message, size_t len); + bool text(uint32_t id, const char *message, size_t len); + bool text(uint32_t id, const char *message); + bool text(uint32_t id, const String &message); + bool text(uint32_t id, AsyncWebSocketMessageBuffer *buffer); + bool text(uint32_t id, AsyncWebSocketSharedBuffer buffer); + + SendStatus textAll(const uint8_t *message, size_t len); + SendStatus textAll(const char *message, size_t len); + SendStatus textAll(const char *message); + SendStatus textAll(const String &message); + SendStatus textAll(AsyncWebSocketMessageBuffer *buffer); + SendStatus textAll(AsyncWebSocketSharedBuffer buffer); + + bool binary(uint32_t id, const uint8_t *message, size_t len); + bool binary(uint32_t id, const char *message, size_t len); + bool binary(uint32_t id, const char *message); + bool binary(uint32_t id, const String &message); + bool binary(uint32_t id, AsyncWebSocketMessageBuffer *buffer); + bool binary(uint32_t id, AsyncWebSocketSharedBuffer buffer); + + SendStatus binaryAll(const uint8_t *message, size_t len); + SendStatus binaryAll(const char *message, size_t len); + SendStatus binaryAll(const char *message); + SendStatus binaryAll(const String &message); + SendStatus binaryAll(AsyncWebSocketMessageBuffer *buffer); + SendStatus binaryAll(AsyncWebSocketSharedBuffer buffer); + + size_t printf(uint32_t id, const char *format, ...) __attribute__((format(printf, 3, 4))); + size_t printfAll(const char *format, ...) __attribute__((format(printf, 2, 3))); + +#ifdef ESP8266 + bool text(uint32_t id, const __FlashStringHelper *message); + SendStatus textAll(const __FlashStringHelper *message); + bool binary(uint32_t id, const __FlashStringHelper *message, size_t len); + SendStatus binaryAll(const __FlashStringHelper *message, size_t len); + size_t printf_P(uint32_t id, PGM_P formatP, ...) __attribute__((format(printf, 3, 4))); + size_t printfAll_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3))); +#endif + + void onEvent(AwsEventHandler handler) { + _eventHandler = handler; + } + void handleHandshake(AwsHandshakeHandler handler) { + _handshakeHandler = handler; + } + + // system callbacks (do not call) + uint32_t _getNextId() { + return _cNextId++; + } + AsyncWebSocketClient *_newClient(AsyncWebServerRequest *request); + void _handleDisconnect(AsyncWebSocketClient *client); + void _handleEvent(AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len); + bool canHandle(AsyncWebServerRequest *request) const override final; + void handleRequest(AsyncWebServerRequest *request) override final; + + // messagebuffer functions/objects. + AsyncWebSocketMessageBuffer *makeBuffer(size_t size = 0); + AsyncWebSocketMessageBuffer *makeBuffer(const uint8_t *data, size_t size); + + std::list &getClients() { + return _clients; + } +}; + +// WebServer response to authenticate the socket and detach the tcp client from the web server request +class AsyncWebSocketResponse : public AsyncWebServerResponse { +private: + String _content; + AsyncWebSocket *_server; + +public: + AsyncWebSocketResponse(const String &key, AsyncWebSocket *server); + void _respond(AsyncWebServerRequest *request); + size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time); + bool _sourceValid() const { + return true; + } +}; + +class AsyncWebSocketMessageHandler { +public: + AwsEventHandler eventHandler() const { + return _handler; + } + + void onConnect(std::function onConnect) { + _onConnect = onConnect; + } + + void onDisconnect(std::function onDisconnect) { + _onDisconnect = onDisconnect; + } + + /** + * Error callback + * @param reason null-terminated string + * @param len length of the string + */ + void onError(std::function onError) { + _onError = onError; + } + + /** + * Complete message callback + * @param data pointer to the data (binary or null-terminated string). This handler expects the user to know which data type he uses. + */ + void onMessage(std::function onMessage) { + _onMessage = onMessage; + } + + /** + * Fragmented message callback + * @param data pointer to the data (binary or null-terminated string), will be null-terminated. This handler expects the user to know which data type he uses. + */ + // clang-format off + void onFragment(std::function onFragment) { + _onFragment = onFragment; + } + // clang-format on + +private: + // clang-format off + std::function _onConnect; + std::function _onError; + std::function _onMessage; + std::function _onFragment; + std::function _onDisconnect; + // clang-format on + + // this handler is meant to only support 1-frame messages (== unfragmented messages) + AwsEventHandler _handler = [this](AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { + if (type == WS_EVT_CONNECT) { + if (_onConnect) { + _onConnect(server, client); + } + } else if (type == WS_EVT_DISCONNECT) { + if (_onDisconnect) { + _onDisconnect(server, client->id()); + } + } else if (type == WS_EVT_ERROR) { + if (_onError) { + _onError(server, client, *((uint16_t *)arg), (const char *)data, len); + } + } else if (type == WS_EVT_DATA) { + AwsFrameInfo *info = (AwsFrameInfo *)arg; + if (info->opcode == WS_TEXT) { + data[len] = 0; + } + if (info->final && info->index == 0 && info->len == len) { + if (_onMessage) { + _onMessage(server, client, data, len); + } + } else { + if (_onFragment) { + _onFragment(server, client, info, data, len); + } + } + } + }; +}; + +#endif /* ASYNCWEBSOCKET_H_ */ diff --git a/watering/lib/ESPAsyncWebServer/src/BackPort_SHA1Builder.cpp b/watering/lib/ESPAsyncWebServer/src/BackPort_SHA1Builder.cpp new file mode 100644 index 0000000..06a73a5 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/BackPort_SHA1Builder.cpp @@ -0,0 +1,284 @@ +/* + * FIPS-180-1 compliant SHA-1 implementation + * + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + * Modified for esp32 by Lucas Saavedra Vaz on 11 Jan 2024 + */ + +#include +#if ESP_IDF_VERSION_MAJOR < 5 + +#include "BackPort_SHA1Builder.h" + +// 32-bit integer manipulation macros (big endian) + +#ifndef GET_UINT32_BE +#define GET_UINT32_BE(n, b, i) \ + { (n) = ((uint32_t)(b)[(i)] << 24) | ((uint32_t)(b)[(i) + 1] << 16) | ((uint32_t)(b)[(i) + 2] << 8) | ((uint32_t)(b)[(i) + 3]); } +#endif + +#ifndef PUT_UINT32_BE +#define PUT_UINT32_BE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n) >> 24); \ + (b)[(i) + 1] = (uint8_t)((n) >> 16); \ + (b)[(i) + 2] = (uint8_t)((n) >> 8); \ + (b)[(i) + 3] = (uint8_t)((n)); \ + } +#endif + +// Constants + +static const uint8_t sha1_padding[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + +// Private methods + +void SHA1Builder::process(const uint8_t *data) { + uint32_t temp, W[16], A, B, C, D, E; + + GET_UINT32_BE(W[0], data, 0); + GET_UINT32_BE(W[1], data, 4); + GET_UINT32_BE(W[2], data, 8); + GET_UINT32_BE(W[3], data, 12); + GET_UINT32_BE(W[4], data, 16); + GET_UINT32_BE(W[5], data, 20); + GET_UINT32_BE(W[6], data, 24); + GET_UINT32_BE(W[7], data, 28); + GET_UINT32_BE(W[8], data, 32); + GET_UINT32_BE(W[9], data, 36); + GET_UINT32_BE(W[10], data, 40); + GET_UINT32_BE(W[11], data, 44); + GET_UINT32_BE(W[12], data, 48); + GET_UINT32_BE(W[13], data, 52); + GET_UINT32_BE(W[14], data, 56); + GET_UINT32_BE(W[15], data, 60); + +#define sha1_S(x, n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) + +#define sha1_R(t) (temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ W[(t - 14) & 0x0F] ^ W[t & 0x0F], (W[t & 0x0F] = sha1_S(temp, 1))) + +#define sha1_P(a, b, c, d, e, x) \ + { \ + e += sha1_S(a, 5) + sha1_F(b, c, d) + sha1_K + x; \ + b = sha1_S(b, 30); \ + } + + A = state[0]; + B = state[1]; + C = state[2]; + D = state[3]; + E = state[4]; + +#define sha1_F(x, y, z) (z ^ (x & (y ^ z))) +#define sha1_K 0x5A827999 + + sha1_P(A, B, C, D, E, W[0]); + sha1_P(E, A, B, C, D, W[1]); + sha1_P(D, E, A, B, C, W[2]); + sha1_P(C, D, E, A, B, W[3]); + sha1_P(B, C, D, E, A, W[4]); + sha1_P(A, B, C, D, E, W[5]); + sha1_P(E, A, B, C, D, W[6]); + sha1_P(D, E, A, B, C, W[7]); + sha1_P(C, D, E, A, B, W[8]); + sha1_P(B, C, D, E, A, W[9]); + sha1_P(A, B, C, D, E, W[10]); + sha1_P(E, A, B, C, D, W[11]); + sha1_P(D, E, A, B, C, W[12]); + sha1_P(C, D, E, A, B, W[13]); + sha1_P(B, C, D, E, A, W[14]); + sha1_P(A, B, C, D, E, W[15]); + sha1_P(E, A, B, C, D, sha1_R(16)); + sha1_P(D, E, A, B, C, sha1_R(17)); + sha1_P(C, D, E, A, B, sha1_R(18)); + sha1_P(B, C, D, E, A, sha1_R(19)); + +#undef sha1_K +#undef sha1_F + +#define sha1_F(x, y, z) (x ^ y ^ z) +#define sha1_K 0x6ED9EBA1 + + sha1_P(A, B, C, D, E, sha1_R(20)); + sha1_P(E, A, B, C, D, sha1_R(21)); + sha1_P(D, E, A, B, C, sha1_R(22)); + sha1_P(C, D, E, A, B, sha1_R(23)); + sha1_P(B, C, D, E, A, sha1_R(24)); + sha1_P(A, B, C, D, E, sha1_R(25)); + sha1_P(E, A, B, C, D, sha1_R(26)); + sha1_P(D, E, A, B, C, sha1_R(27)); + sha1_P(C, D, E, A, B, sha1_R(28)); + sha1_P(B, C, D, E, A, sha1_R(29)); + sha1_P(A, B, C, D, E, sha1_R(30)); + sha1_P(E, A, B, C, D, sha1_R(31)); + sha1_P(D, E, A, B, C, sha1_R(32)); + sha1_P(C, D, E, A, B, sha1_R(33)); + sha1_P(B, C, D, E, A, sha1_R(34)); + sha1_P(A, B, C, D, E, sha1_R(35)); + sha1_P(E, A, B, C, D, sha1_R(36)); + sha1_P(D, E, A, B, C, sha1_R(37)); + sha1_P(C, D, E, A, B, sha1_R(38)); + sha1_P(B, C, D, E, A, sha1_R(39)); + +#undef sha1_K +#undef sha1_F + +#define sha1_F(x, y, z) ((x & y) | (z & (x | y))) +#define sha1_K 0x8F1BBCDC + + sha1_P(A, B, C, D, E, sha1_R(40)); + sha1_P(E, A, B, C, D, sha1_R(41)); + sha1_P(D, E, A, B, C, sha1_R(42)); + sha1_P(C, D, E, A, B, sha1_R(43)); + sha1_P(B, C, D, E, A, sha1_R(44)); + sha1_P(A, B, C, D, E, sha1_R(45)); + sha1_P(E, A, B, C, D, sha1_R(46)); + sha1_P(D, E, A, B, C, sha1_R(47)); + sha1_P(C, D, E, A, B, sha1_R(48)); + sha1_P(B, C, D, E, A, sha1_R(49)); + sha1_P(A, B, C, D, E, sha1_R(50)); + sha1_P(E, A, B, C, D, sha1_R(51)); + sha1_P(D, E, A, B, C, sha1_R(52)); + sha1_P(C, D, E, A, B, sha1_R(53)); + sha1_P(B, C, D, E, A, sha1_R(54)); + sha1_P(A, B, C, D, E, sha1_R(55)); + sha1_P(E, A, B, C, D, sha1_R(56)); + sha1_P(D, E, A, B, C, sha1_R(57)); + sha1_P(C, D, E, A, B, sha1_R(58)); + sha1_P(B, C, D, E, A, sha1_R(59)); + +#undef sha1_K +#undef sha1_F + +#define sha1_F(x, y, z) (x ^ y ^ z) +#define sha1_K 0xCA62C1D6 + + sha1_P(A, B, C, D, E, sha1_R(60)); + sha1_P(E, A, B, C, D, sha1_R(61)); + sha1_P(D, E, A, B, C, sha1_R(62)); + sha1_P(C, D, E, A, B, sha1_R(63)); + sha1_P(B, C, D, E, A, sha1_R(64)); + sha1_P(A, B, C, D, E, sha1_R(65)); + sha1_P(E, A, B, C, D, sha1_R(66)); + sha1_P(D, E, A, B, C, sha1_R(67)); + sha1_P(C, D, E, A, B, sha1_R(68)); + sha1_P(B, C, D, E, A, sha1_R(69)); + sha1_P(A, B, C, D, E, sha1_R(70)); + sha1_P(E, A, B, C, D, sha1_R(71)); + sha1_P(D, E, A, B, C, sha1_R(72)); + sha1_P(C, D, E, A, B, sha1_R(73)); + sha1_P(B, C, D, E, A, sha1_R(74)); + sha1_P(A, B, C, D, E, sha1_R(75)); + sha1_P(E, A, B, C, D, sha1_R(76)); + sha1_P(D, E, A, B, C, sha1_R(77)); + sha1_P(C, D, E, A, B, sha1_R(78)); + sha1_P(B, C, D, E, A, sha1_R(79)); + +#undef sha1_K +#undef sha1_F + + state[0] += A; + state[1] += B; + state[2] += C; + state[3] += D; + state[4] += E; +} + +// Public methods + +void SHA1Builder::begin() { + total[0] = 0; + total[1] = 0; + + state[0] = 0x67452301; + state[1] = 0xEFCDAB89; + state[2] = 0x98BADCFE; + state[3] = 0x10325476; + state[4] = 0xC3D2E1F0; + + memset(buffer, 0x00, sizeof(buffer)); + memset(hash, 0x00, sizeof(hash)); +} + +void SHA1Builder::add(const uint8_t *data, size_t len) { + size_t fill; + uint32_t left; + + if (len == 0) { + return; + } + + left = total[0] & 0x3F; + fill = 64 - left; + + total[0] += (uint32_t)len; + total[0] &= 0xFFFFFFFF; + + if (total[0] < (uint32_t)len) { + total[1]++; + } + + if (left && len >= fill) { + memcpy((void *)(buffer + left), data, fill); + process(buffer); + data += fill; + len -= fill; + left = 0; + } + + while (len >= 64) { + process(data); + data += 64; + len -= 64; + } + + if (len > 0) { + memcpy((void *)(buffer + left), data, len); + } +} + +void SHA1Builder::calculate(void) { + uint32_t last, padn; + uint32_t high, low; + uint8_t msglen[8]; + + high = (total[0] >> 29) | (total[1] << 3); + low = (total[0] << 3); + + PUT_UINT32_BE(high, msglen, 0); + PUT_UINT32_BE(low, msglen, 4); + + last = total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); + + add((uint8_t *)sha1_padding, padn); + add(msglen, 8); + + PUT_UINT32_BE(state[0], hash, 0); + PUT_UINT32_BE(state[1], hash, 4); + PUT_UINT32_BE(state[2], hash, 8); + PUT_UINT32_BE(state[3], hash, 12); + PUT_UINT32_BE(state[4], hash, 16); +} + +void SHA1Builder::getBytes(uint8_t *output) { + memcpy(output, hash, SHA1_HASH_SIZE); +} + +#endif // ESP_IDF_VERSION_MAJOR < 5 diff --git a/watering/lib/ESPAsyncWebServer/src/BackPort_SHA1Builder.h b/watering/lib/ESPAsyncWebServer/src/BackPort_SHA1Builder.h new file mode 100644 index 0000000..e7eafbe --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/BackPort_SHA1Builder.h @@ -0,0 +1,44 @@ +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#if ESP_IDF_VERSION_MAJOR < 5 + +#ifndef SHA1Builder_h +#define SHA1Builder_h + +#include +#include + +#define SHA1_HASH_SIZE 20 + +class SHA1Builder { +private: + uint32_t total[2]; /* number of bytes processed */ + uint32_t state[5]; /* intermediate digest state */ + unsigned char buffer[64]; /* data block being processed */ + uint8_t hash[SHA1_HASH_SIZE]; /* SHA-1 result */ + + void process(const uint8_t *data); + +public: + void begin(); + void add(const uint8_t *data, size_t len); + void calculate(); + void getBytes(uint8_t *output); +}; + +#endif // SHA1Builder_h + +#endif // ESP_IDF_VERSION_MAJOR < 5 diff --git a/watering/lib/ESPAsyncWebServer/src/ChunkPrint.cpp b/watering/lib/ESPAsyncWebServer/src/ChunkPrint.cpp new file mode 100644 index 0000000..4617d34 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/ChunkPrint.cpp @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include + +ChunkPrint::ChunkPrint(uint8_t *destination, size_t from, size_t len) : _destination(destination), _to_skip(from), _to_write(len), _pos{0} {} + +size_t ChunkPrint::write(uint8_t c) { + if (_to_skip > 0) { + _to_skip--; + return 1; + } else if (_to_write > 0) { + _to_write--; + _destination[_pos++] = c; + return 1; + } + return 0; +} diff --git a/watering/lib/ESPAsyncWebServer/src/ChunkPrint.h b/watering/lib/ESPAsyncWebServer/src/ChunkPrint.h new file mode 100644 index 0000000..04938b3 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/ChunkPrint.h @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef CHUNKPRINT_H +#define CHUNKPRINT_H + +#include + +class ChunkPrint : public Print { +private: + uint8_t *_destination; + size_t _to_skip; + size_t _to_write; + size_t _pos; + +public: + ChunkPrint(uint8_t *destination, size_t from, size_t len); + size_t write(uint8_t c); + size_t write(const uint8_t *buffer, size_t size) { + return this->Print::write(buffer, size); + } +}; +#endif diff --git a/watering/lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h b/watering/lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h new file mode 100644 index 0000000..24233cd --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h @@ -0,0 +1,1217 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef _ESPAsyncWebServer_H_ +#define _ESPAsyncWebServer_H_ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#ifdef ESP32 +#include +#include +#elif defined(ESP8266) +#include +#include +#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#include +#include +#include +#else +#error Platform not supported +#endif + +#include "literals.h" + +#include "AsyncWebServerVersion.h" +#define ASYNCWEBSERVER_FORK_ESP32Async + +#ifdef ASYNCWEBSERVER_REGEX +#define ASYNCWEBSERVER_REGEX_ATTRIBUTE +#else +#define ASYNCWEBSERVER_REGEX_ATTRIBUTE __attribute__((warning("ASYNCWEBSERVER_REGEX not defined"))) +#endif + +// See https://github.com/ESP32Async/ESPAsyncWebServer/commit/3d3456e9e81502a477f6498c44d0691499dda8f9#diff-646b25b11691c11dce25529e3abce843f0ba4bd07ab75ec9eee7e72b06dbf13fR388-R392 +// This setting slowdown chunk serving but avoids crashing or deadlocks in the case where slow chunk responses are created, like file serving form SD Card +#ifndef ASYNCWEBSERVER_USE_CHUNK_INFLIGHT +#define ASYNCWEBSERVER_USE_CHUNK_INFLIGHT 1 +#endif + +class AsyncWebServer; +class AsyncWebServerRequest; +class AsyncWebServerResponse; +class AsyncWebHeader; +class AsyncWebParameter; +class AsyncWebRewrite; +class AsyncWebHandler; +class AsyncStaticWebHandler; +class AsyncCallbackWebHandler; +class AsyncResponseStream; +class AsyncMiddlewareChain; + +#if defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +typedef enum http_method WebRequestMethod; +#else +#ifndef WEBSERVER_H +typedef enum { + HTTP_GET = 0b00000001, + HTTP_POST = 0b00000010, + HTTP_DELETE = 0b00000100, + HTTP_PUT = 0b00001000, + HTTP_PATCH = 0b00010000, + HTTP_HEAD = 0b00100000, + HTTP_OPTIONS = 0b01000000, + HTTP_ANY = 0b01111111, +} WebRequestMethod; +#endif +#endif + +#ifndef HAVE_FS_FILE_OPEN_MODE +namespace fs { +class FileOpenMode { +public: + static const char *read; + static const char *write; + static const char *append; +}; +}; // namespace fs +#else +#include "FileOpenMode.h" +#endif + +// if this value is returned when asked for data, packet will not be sent and you will be asked for data again +#define RESPONSE_TRY_AGAIN 0xFFFFFFFF +#define RESPONSE_STREAM_BUFFER_SIZE 1460 + +typedef uint8_t WebRequestMethodComposite; +typedef std::function ArDisconnectHandler; + +/* + * PARAMETER :: Chainable object to hold GET/POST and FILE parameters + * */ + +class AsyncWebParameter { +private: + String _name; + String _value; + size_t _size; + bool _isForm; + bool _isFile; + +public: + AsyncWebParameter(const String &name, const String &value, bool form = false, bool file = false, size_t size = 0) + : _name(name), _value(value), _size(size), _isForm(form), _isFile(file) {} + const String &name() const { + return _name; + } + const String &value() const { + return _value; + } + size_t size() const { + return _size; + } + bool isPost() const { + return _isForm; + } + bool isFile() const { + return _isFile; + } +}; + +/* + * HEADER :: Chainable object to hold the headers + * */ + +class AsyncWebHeader { +private: + String _name; + String _value; + +public: + AsyncWebHeader(const AsyncWebHeader &) = default; + AsyncWebHeader(const char *name, const char *value) : _name(name), _value(value) {} + AsyncWebHeader(const String &name, const String &value) : _name(name), _value(value) {} + AsyncWebHeader(const String &data); + + AsyncWebHeader &operator=(const AsyncWebHeader &) = default; + + const String &name() const { + return _name; + } + const String &value() const { + return _value; + } + String toString() const; +}; + +/* + * REQUEST :: Each incoming Client is wrapped inside a Request and both live together until disconnect + * */ + +typedef enum { + RCT_NOT_USED = -1, + RCT_DEFAULT = 0, + RCT_HTTP, + RCT_WS, + RCT_EVENT, + RCT_MAX +} RequestedConnectionType; + +// this enum is similar to Arduino WebServer's AsyncAuthType and PsychicHttp +typedef enum { + AUTH_NONE = 0, // always allow + AUTH_BASIC = 1, + AUTH_DIGEST = 2, + AUTH_BEARER = 3, + AUTH_OTHER = 4, + AUTH_DENIED = 255, // always returns 401 +} AsyncAuthType; + +typedef std::function AwsResponseFiller; +typedef std::function AwsTemplateProcessor; + +using AsyncWebServerRequestPtr = std::weak_ptr; + +class AsyncWebServerRequest { + using File = fs::File; + using FS = fs::FS; + friend class AsyncWebServer; + friend class AsyncCallbackWebHandler; + +private: + AsyncClient *_client; + AsyncWebServer *_server; + AsyncWebHandler *_handler; + AsyncWebServerResponse *_response; + ArDisconnectHandler _onDisconnectfn; + + bool _sent = false; // response is sent + bool _paused = false; // request is paused (request continuation) + std::shared_ptr _this; // shared pointer to this request + + String _temp; + uint8_t _parseState; + + uint8_t _version; + WebRequestMethodComposite _method; + String _url; + String _host; + String _contentType; + String _boundary; + String _authorization; + RequestedConnectionType _reqconntype; + AsyncAuthType _authMethod = AsyncAuthType::AUTH_NONE; + bool _isMultipart; + bool _isPlainPost; + bool _expectingContinue; + size_t _contentLength; + size_t _parsedLength; + + std::list _headers; + std::list _params; + std::list _pathParams; + + std::unordered_map, std::equal_to> _attributes; + + uint8_t _multiParseState; + uint8_t _boundaryPosition; + size_t _itemStartIndex; + size_t _itemSize; + String _itemName; + String _itemFilename; + String _itemType; + String _itemValue; + uint8_t *_itemBuffer; + size_t _itemBufferIndex; + bool _itemIsFile; + + void _onPoll(); + void _onAck(size_t len, uint32_t time); + void _onError(int8_t error); + void _onTimeout(uint32_t time); + void _onDisconnect(); + void _onData(void *buf, size_t len); + + void _addPathParam(const char *param); + + bool _parseReqHead(); + bool _parseReqHeader(); + void _parseLine(); + void _parsePlainPostChar(uint8_t data); + void _parseMultipartPostByte(uint8_t data, bool last); + void _addGetParams(const String ¶ms); + + void _handleUploadStart(); + void _handleUploadByte(uint8_t data, bool last); + void _handleUploadEnd(); + + void _send(); + void _runMiddlewareChain(); + +public: + File _tempFile; + void *_tempObject; + + AsyncWebServerRequest(AsyncWebServer *, AsyncClient *); + ~AsyncWebServerRequest(); + + AsyncClient *client() { + return _client; + } + uint8_t version() const { + return _version; + } + WebRequestMethodComposite method() const { + return _method; + } + const String &url() const { + return _url; + } + const String &host() const { + return _host; + } + const String &contentType() const { + return _contentType; + } + size_t contentLength() const { + return _contentLength; + } + bool multipart() const { + return _isMultipart; + } + + const char *methodToString() const; + const char *requestedConnTypeToString() const; + + RequestedConnectionType requestedConnType() const { + return _reqconntype; + } + bool isExpectedRequestedConnType(RequestedConnectionType erct1, RequestedConnectionType erct2 = RCT_NOT_USED, RequestedConnectionType erct3 = RCT_NOT_USED) + const; + bool isWebSocketUpgrade() const { + return _method == HTTP_GET && isExpectedRequestedConnType(RCT_WS); + } + bool isSSE() const { + return _method == HTTP_GET && isExpectedRequestedConnType(RCT_EVENT); + } + bool isHTTP() const { + return isExpectedRequestedConnType(RCT_DEFAULT, RCT_HTTP); + } + void onDisconnect(ArDisconnectHandler fn); + + // hash is the string representation of: + // base64(user:pass) for basic or + // user:realm:md5(user:realm:pass) for digest + bool authenticate(const char *hash) const; + bool authenticate(const char *username, const char *credentials, const char *realm = NULL, bool isHash = false) const; + void requestAuthentication(const char *realm = nullptr, bool isDigest = true) { + requestAuthentication(isDigest ? AsyncAuthType::AUTH_DIGEST : AsyncAuthType::AUTH_BASIC, realm); + } + void requestAuthentication(AsyncAuthType method, const char *realm = nullptr, const char *_authFailMsg = nullptr); + + // IMPORTANT: this method is for internal use ONLY + // Please do not use it! + // It can be removed or modified at any time without notice + void setHandler(AsyncWebHandler *handler) { + _handler = handler; + } + +#ifndef ESP8266 + [[deprecated("All headers are now collected. Use removeHeader(name) or AsyncHeaderFreeMiddleware if you really need to free some headers.")]] +#endif + void addInterestingHeader(__unused const char *name) { + } +#ifndef ESP8266 + [[deprecated("All headers are now collected. Use removeHeader(name) or AsyncHeaderFreeMiddleware if you really need to free some headers.")]] +#endif + void addInterestingHeader(__unused const String &name) { + } + + /** + * @brief issue HTTP redirect response with Location header + * + * @param url - url to redirect to + * @param code - response code, default is 302 : temporary redirect + */ + void redirect(const char *url, int code = 302); + void redirect(const String &url, int code = 302) { + return redirect(url.c_str(), code); + }; + + void send(AsyncWebServerResponse *response); + AsyncWebServerResponse *getResponse() const { + return _response; + } + + void send(int code, const char *contentType = asyncsrv::empty, const char *content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr) { + send(beginResponse(code, contentType, content, callback)); + } + void send(int code, const String &contentType, const char *content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr) { + send(beginResponse(code, contentType.c_str(), content, callback)); + } + void send(int code, const String &contentType, const String &content, AwsTemplateProcessor callback = nullptr) { + send(beginResponse(code, contentType.c_str(), content.c_str(), callback)); + } + + void send(int code, const char *contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) { + send(beginResponse(code, contentType, content, len, callback)); + } + void send(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) { + send(beginResponse(code, contentType, content, len, callback)); + } + + void send(FS &fs, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr) { + if (fs.exists(path) || (!download && fs.exists(path + asyncsrv::T__gz))) { + send(beginResponse(fs, path, contentType, download, callback)); + } else { + send(404); + } + } + void send(FS &fs, const String &path, const String &contentType, bool download = false, AwsTemplateProcessor callback = nullptr) { + send(fs, path, contentType.c_str(), download, callback); + } + + void send(File content, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr) { + if (content) { + send(beginResponse(content, path, contentType, download, callback)); + } else { + send(404); + } + } + void send(File content, const String &path, const String &contentType, bool download = false, AwsTemplateProcessor callback = nullptr) { + send(content, path, contentType.c_str(), download, callback); + } + + void send(Stream &stream, const char *contentType, size_t len, AwsTemplateProcessor callback = nullptr) { + send(beginResponse(stream, contentType, len, callback)); + } + void send(Stream &stream, const String &contentType, size_t len, AwsTemplateProcessor callback = nullptr) { + send(beginResponse(stream, contentType, len, callback)); + } + + void send(const char *contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { + send(beginResponse(contentType, len, callback, templateCallback)); + } + void send(const String &contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { + send(beginResponse(contentType, len, callback, templateCallback)); + } + + void sendChunked(const char *contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { + send(beginChunkedResponse(contentType, callback, templateCallback)); + } + void sendChunked(const String &contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { + send(beginChunkedResponse(contentType, callback, templateCallback)); + } + +#ifndef ESP8266 + [[deprecated("Replaced by send(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr)")]] +#endif + void send_P(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) { + send(code, contentType, content, len, callback); + } +#ifndef ESP8266 + [[deprecated("Replaced by send(int code, const String& contentType, const char* content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr)")]] + void send_P(int code, const String &contentType, PGM_P content, AwsTemplateProcessor callback = nullptr) { + send(code, contentType, content, callback); + } +#else + void send_P(int code, const String &contentType, PGM_P content, AwsTemplateProcessor callback = nullptr) { + send(beginResponse_P(code, contentType, content, callback)); + } +#endif + + AsyncWebServerResponse * + beginResponse(int code, const char *contentType = asyncsrv::empty, const char *content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr); + AsyncWebServerResponse *beginResponse(int code, const String &contentType, const char *content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr) { + return beginResponse(code, contentType.c_str(), content, callback); + } + AsyncWebServerResponse *beginResponse(int code, const String &contentType, const String &content, AwsTemplateProcessor callback = nullptr) { + return beginResponse(code, contentType.c_str(), content.c_str(), callback); + } + + AsyncWebServerResponse *beginResponse(int code, const char *contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr); + AsyncWebServerResponse *beginResponse(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) { + return beginResponse(code, contentType.c_str(), content, len, callback); + } + + AsyncWebServerResponse * + beginResponse(FS &fs, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr); + AsyncWebServerResponse * + beginResponse(FS &fs, const String &path, const String &contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { + return beginResponse(fs, path, contentType.c_str(), download, callback); + } + + AsyncWebServerResponse * + beginResponse(File content, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr); + AsyncWebServerResponse * + beginResponse(File content, const String &path, const String &contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { + return beginResponse(content, path, contentType.c_str(), download, callback); + } + + AsyncWebServerResponse *beginResponse(Stream &stream, const char *contentType, size_t len, AwsTemplateProcessor callback = nullptr); + AsyncWebServerResponse *beginResponse(Stream &stream, const String &contentType, size_t len, AwsTemplateProcessor callback = nullptr) { + return beginResponse(stream, contentType.c_str(), len, callback); + } + + AsyncWebServerResponse *beginResponse(const char *contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); + AsyncWebServerResponse *beginResponse(const String &contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { + return beginResponse(contentType.c_str(), len, callback, templateCallback); + } + + AsyncWebServerResponse *beginChunkedResponse(const char *contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); + AsyncWebServerResponse *beginChunkedResponse(const String &contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { + return beginChunkedResponse(contentType.c_str(), callback, templateCallback); + } + + AsyncResponseStream *beginResponseStream(const char *contentType, size_t bufferSize = RESPONSE_STREAM_BUFFER_SIZE); + AsyncResponseStream *beginResponseStream(const String &contentType, size_t bufferSize = RESPONSE_STREAM_BUFFER_SIZE) { + return beginResponseStream(contentType.c_str(), bufferSize); + } + +#ifndef ESP8266 + [[deprecated("Replaced by beginResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr)")]] +#endif + AsyncWebServerResponse *beginResponse_P(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) { + return beginResponse(code, contentType.c_str(), content, len, callback); + } +#ifndef ESP8266 + [[deprecated("Replaced by beginResponse(int code, const String& contentType, const char* content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr)" + )]] +#endif + AsyncWebServerResponse *beginResponse_P(int code, const String &contentType, PGM_P content, AwsTemplateProcessor callback = nullptr); + + /** + * @brief Request Continuation: this function pauses the current request and returns a weak pointer (AsyncWebServerRequestPtr is a std::weak_ptr) to the request in order to reuse it later on. + * The middelware chain will continue to be processed until the end, but no response will be sent. + * To resume operations (send the request), the request must be retrieved from the weak pointer and a send() function must be called. + * AsyncWebServerRequestPtr is the only object allowed to exist the scope of the request handler. + * @warning This function should be called from within the context of a request (in a handler or middleware for example). + * @warning While the request is paused, if the client aborts the request, the latter will be disconnected and deleted. + * So it is the responsibility of the user to check the validity of the request pointer (AsyncWebServerRequestPtr) before using it by calling lock() and/or expired(). + */ + AsyncWebServerRequestPtr pause(); + + bool isPaused() const { + return _paused; + } + + /** + * @brief Aborts the request and close the client (RST). + * Mark the request as sent. + * If it was paused, it will be unpaused and it won't be possible to resume it. + */ + void abort(); + + bool isSent() const { + return _sent; + } + + /** + * @brief Get the Request parameter by name + * + * @param name + * @param post + * @param file + * @return const AsyncWebParameter* + */ + const AsyncWebParameter *getParam(const char *name, bool post = false, bool file = false) const; + + const AsyncWebParameter *getParam(const String &name, bool post = false, bool file = false) const { + return getParam(name.c_str(), post, file); + }; +#ifdef ESP8266 + const AsyncWebParameter *getParam(const __FlashStringHelper *data, bool post, bool file) const; +#endif + + /** + * @brief Get request parameter by number + * i.e., n-th parameter + * @param num + * @return const AsyncWebParameter* + */ + const AsyncWebParameter *getParam(size_t num) const; + const AsyncWebParameter *getParam(int num) const { + return num < 0 ? nullptr : getParam((size_t)num); + } + + size_t args() const { + return params(); + } // get arguments count + + // get request argument value by name + const String &arg(const char *name) const; + // get request argument value by name + const String &arg(const String &name) const { + return arg(name.c_str()); + }; +#ifdef ESP8266 + const String &arg(const __FlashStringHelper *data) const; // get request argument value by F(name) +#endif + const String &arg(size_t i) const; // get request argument value by number + const String &arg(int i) const { + return i < 0 ? emptyString : arg((size_t)i); + }; + const String &argName(size_t i) const; // get request argument name by number + const String &argName(int i) const { + return i < 0 ? emptyString : argName((size_t)i); + }; + bool hasArg(const char *name) const; // check if argument exists + bool hasArg(const String &name) const { + return hasArg(name.c_str()); + }; +#ifdef ESP8266 + bool hasArg(const __FlashStringHelper *data) const; // check if F(argument) exists +#endif + + const String &ASYNCWEBSERVER_REGEX_ATTRIBUTE pathArg(size_t i) const; + const String &ASYNCWEBSERVER_REGEX_ATTRIBUTE pathArg(int i) const { + return i < 0 ? emptyString : pathArg((size_t)i); + } + + // get request header value by name + const String &header(const char *name) const; + const String &header(const String &name) const { + return header(name.c_str()); + }; + +#ifdef ESP8266 + const String &header(const __FlashStringHelper *data) const; // get request header value by F(name) +#endif + + const String &header(size_t i) const; // get request header value by number + const String &header(int i) const { + return i < 0 ? emptyString : header((size_t)i); + }; + const String &headerName(size_t i) const; // get request header name by number + const String &headerName(int i) const { + return i < 0 ? emptyString : headerName((size_t)i); + }; + + size_t headers() const; // get header count + + // check if header exists + bool hasHeader(const char *name) const; + bool hasHeader(const String &name) const { + return hasHeader(name.c_str()); + }; +#ifdef ESP8266 + bool hasHeader(const __FlashStringHelper *data) const; // check if header exists +#endif + + const AsyncWebHeader *getHeader(const char *name) const; + const AsyncWebHeader *getHeader(const String &name) const { + return getHeader(name.c_str()); + }; +#ifdef ESP8266 + const AsyncWebHeader *getHeader(const __FlashStringHelper *data) const; +#endif + + const AsyncWebHeader *getHeader(size_t num) const; + const AsyncWebHeader *getHeader(int num) const { + return num < 0 ? nullptr : getHeader((size_t)num); + }; + + const std::list &getHeaders() const { + return _headers; + } + + size_t getHeaderNames(std::vector &names) const; + + // Remove a header from the request. + // It will free the memory and prevent the header to be seen during request processing. + bool removeHeader(const char *name); + // Remove all request headers. + void removeHeaders() { + _headers.clear(); + } + + size_t params() const; // get arguments count + bool hasParam(const char *name, bool post = false, bool file = false) const; + bool hasParam(const String &name, bool post = false, bool file = false) const { + return hasParam(name.c_str(), post, file); + }; +#ifdef ESP8266 + bool hasParam(const __FlashStringHelper *data, bool post = false, bool file = false) const { + return hasParam(String(data).c_str(), post, file); + }; +#endif + + // REQUEST ATTRIBUTES + + void setAttribute(const char *name, const char *value) { + _attributes[name] = value; + } + void setAttribute(const char *name, bool value) { + _attributes[name] = value ? "1" : emptyString; + } + void setAttribute(const char *name, long value) { + _attributes[name] = String(value); + } + void setAttribute(const char *name, float value, unsigned int decimalPlaces = 2) { + _attributes[name] = String(value, decimalPlaces); + } + void setAttribute(const char *name, double value, unsigned int decimalPlaces = 2) { + _attributes[name] = String(value, decimalPlaces); + } + + bool hasAttribute(const char *name) const { + return _attributes.find(name) != _attributes.end(); + } + + const String &getAttribute(const char *name, const String &defaultValue = emptyString) const; + bool getAttribute(const char *name, bool defaultValue) const; + long getAttribute(const char *name, long defaultValue) const; + float getAttribute(const char *name, float defaultValue) const; + double getAttribute(const char *name, double defaultValue) const; + + String urlDecode(const String &text) const; +}; + +/* + * FILTER :: Callback to filter AsyncWebRewrite and AsyncWebHandler (done by the Server) + * */ + +using ArRequestFilterFunction = std::function; + +bool ON_STA_FILTER(AsyncWebServerRequest *request); + +bool ON_AP_FILTER(AsyncWebServerRequest *request); + +/* + * MIDDLEWARE :: Request interceptor, assigned to a AsyncWebHandler (or the server), which can be used: + * 1. to run some code before the final handler is executed (e.g. check authentication) + * 2. decide whether to proceed or not with the next handler + * */ + +using ArMiddlewareNext = std::function; +using ArMiddlewareCallback = std::function; + +// Middleware is a base class for all middleware +class AsyncMiddleware { +public: + virtual ~AsyncMiddleware() {} + virtual void run(__unused AsyncWebServerRequest *request, __unused ArMiddlewareNext next) { + return next(); + }; + +private: + friend class AsyncWebHandler; + friend class AsyncEventSource; + friend class AsyncMiddlewareChain; + bool _freeOnRemoval = false; +}; + +// Create a custom middleware by providing an anonymous callback function +class AsyncMiddlewareFunction : public AsyncMiddleware { +public: + AsyncMiddlewareFunction(ArMiddlewareCallback fn) : _fn(fn) {} + void run(AsyncWebServerRequest *request, ArMiddlewareNext next) override { + return _fn(request, next); + }; + +private: + ArMiddlewareCallback _fn; +}; + +// For internal use only: super class to add/remove middleware to server or handlers +class AsyncMiddlewareChain { +public: + ~AsyncMiddlewareChain(); + + void addMiddleware(ArMiddlewareCallback fn); + void addMiddleware(AsyncMiddleware *middleware); + void addMiddlewares(std::vector middlewares); + bool removeMiddleware(AsyncMiddleware *middleware); + + // For internal use only + void _runChain(AsyncWebServerRequest *request, ArMiddlewareNext finalizer); + +protected: + std::list _middlewares; +}; + +// AsyncAuthenticationMiddleware is a middleware that checks if the request is authenticated +class AsyncAuthenticationMiddleware : public AsyncMiddleware { +public: + void setUsername(const char *username); + void setPassword(const char *password); + void setPasswordHash(const char *hash); + + void setRealm(const char *realm) { + _realm = realm; + } + void setAuthFailureMessage(const char *message) { + _authFailMsg = message; + } + + // set the authentication method to use + // default is AUTH_NONE: no authentication required + // AUTH_BASIC: basic authentication + // AUTH_DIGEST: digest authentication + // AUTH_BEARER: bearer token authentication + // AUTH_OTHER: other authentication method + // AUTH_DENIED: always return 401 Unauthorized + // if a method is set but no username or password is set, authentication will be ignored + void setAuthType(AsyncAuthType authMethod) { + _authMethod = authMethod; + } + + // precompute and store the hash value based on the username, password, realm. + // can be used for DIGEST and BASIC to avoid recomputing the hash for each request. + // returns true if the hash was successfully generated and replaced + bool generateHash(); + + // returns true if the username and password (or hash) are set + bool hasCredentials() const { + return _hasCreds; + } + + bool allowed(AsyncWebServerRequest *request) const; + + void run(AsyncWebServerRequest *request, ArMiddlewareNext next); + +private: + String _username; + String _credentials; + bool _hash = false; + + String _realm = asyncsrv::T_LOGIN_REQ; + AsyncAuthType _authMethod = AsyncAuthType::AUTH_NONE; + String _authFailMsg; + bool _hasCreds = false; +}; + +using ArAuthorizeFunction = std::function; +// AsyncAuthorizationMiddleware is a middleware that checks if the request is authorized +class AsyncAuthorizationMiddleware : public AsyncMiddleware { +public: + AsyncAuthorizationMiddleware(ArAuthorizeFunction authorizeConnectHandler) : _code(403), _authz(authorizeConnectHandler) {} + AsyncAuthorizationMiddleware(int code, ArAuthorizeFunction authorizeConnectHandler) : _code(code), _authz(authorizeConnectHandler) {} + + void run(AsyncWebServerRequest *request, ArMiddlewareNext next) { + return _authz && !_authz(request) ? request->send(_code) : next(); + } + +private: + int _code; + ArAuthorizeFunction _authz; +}; + +// remove all headers from the incoming request except the ones provided in the constructor +class AsyncHeaderFreeMiddleware : public AsyncMiddleware { +public: + void keep(const char *name) { + _toKeep.push_back(name); + } + void unKeep(const char *name) { + _toKeep.remove(name); + } + + void run(AsyncWebServerRequest *request, ArMiddlewareNext next); + +private: + std::list _toKeep; +}; + +// filter out specific headers from the incoming request +class AsyncHeaderFilterMiddleware : public AsyncMiddleware { +public: + void filter(const char *name) { + _toRemove.push_back(name); + } + void unFilter(const char *name) { + _toRemove.remove(name); + } + + void run(AsyncWebServerRequest *request, ArMiddlewareNext next); + +private: + std::list _toRemove; +}; + +// curl-like logging of incoming requests +class AsyncLoggingMiddleware : public AsyncMiddleware { +public: + void setOutput(Print &output) { + _out = &output; + } + void setEnabled(bool enabled) { + _enabled = enabled; + } + bool isEnabled() const { + return _enabled && _out; + } + + void run(AsyncWebServerRequest *request, ArMiddlewareNext next); + +private: + Print *_out = nullptr; + bool _enabled = true; +}; + +// CORS Middleware +class AsyncCorsMiddleware : public AsyncMiddleware { +public: + void setOrigin(const char *origin) { + _origin = origin; + } + void setMethods(const char *methods) { + _methods = methods; + } + void setHeaders(const char *headers) { + _headers = headers; + } + void setAllowCredentials(bool credentials) { + _credentials = credentials; + } + void setMaxAge(uint32_t seconds) { + _maxAge = seconds; + } + + void addCORSHeaders(AsyncWebServerResponse *response); + + void run(AsyncWebServerRequest *request, ArMiddlewareNext next); + +private: + String _origin = "*"; + String _methods = "*"; + String _headers = "*"; + bool _credentials = true; + uint32_t _maxAge = 86400; +}; + +// Rate limit Middleware +class AsyncRateLimitMiddleware : public AsyncMiddleware { +public: + void setMaxRequests(size_t maxRequests) { + _maxRequests = maxRequests; + } + void setWindowSize(uint32_t seconds) { + _windowSizeMillis = seconds * 1000; + } + + bool isRequestAllowed(uint32_t &retryAfterSeconds); + + void run(AsyncWebServerRequest *request, ArMiddlewareNext next); + +private: + size_t _maxRequests = 0; + uint32_t _windowSizeMillis = 0; + std::list _requestTimes; +}; + +/* + * REWRITE :: One instance can be handle any Request (done by the Server) + * */ + +class AsyncWebRewrite { +protected: + String _from; + String _toUrl; + String _params; + ArRequestFilterFunction _filter{nullptr}; + +public: + AsyncWebRewrite(const char *from, const char *to) : _from(from), _toUrl(to) { + int index = _toUrl.indexOf('?'); + if (index > 0) { + _params = _toUrl.substring(index + 1); + _toUrl = _toUrl.substring(0, index); + } + } + virtual ~AsyncWebRewrite() {} + AsyncWebRewrite &setFilter(ArRequestFilterFunction fn) { + _filter = fn; + return *this; + } + bool filter(AsyncWebServerRequest *request) const { + return _filter == NULL || _filter(request); + } + const String &from(void) const { + return _from; + } + const String &toUrl(void) const { + return _toUrl; + } + const String ¶ms(void) const { + return _params; + } + virtual bool match(AsyncWebServerRequest *request) { + return from() == request->url() && filter(request); + } +}; + +/* + * HANDLER :: One instance can be attached to any Request (done by the Server) + * */ + +class AsyncWebHandler : public AsyncMiddlewareChain { +protected: + ArRequestFilterFunction _filter = nullptr; + AsyncAuthenticationMiddleware *_authMiddleware = nullptr; + bool _skipServerMiddlewares = false; + +public: + AsyncWebHandler() {} + virtual ~AsyncWebHandler() {} + AsyncWebHandler &setFilter(ArRequestFilterFunction fn); + AsyncWebHandler &setAuthentication(const char *username, const char *password, AsyncAuthType authMethod = AsyncAuthType::AUTH_DIGEST); + AsyncWebHandler &setAuthentication(const String &username, const String &password, AsyncAuthType authMethod = AsyncAuthType::AUTH_DIGEST) { + return setAuthentication(username.c_str(), password.c_str(), authMethod); + }; + AsyncWebHandler &setSkipServerMiddlewares(bool state) { + _skipServerMiddlewares = state; + return *this; + } + // skip all globally defined server middlewares for this handler and only execute those defined for this handler specifically + AsyncWebHandler &skipServerMiddlewares() { + return setSkipServerMiddlewares(true); + } + bool mustSkipServerMiddlewares() const { + return _skipServerMiddlewares; + } + bool filter(AsyncWebServerRequest *request) { + return _filter == NULL || _filter(request); + } + virtual bool canHandle(AsyncWebServerRequest *request __attribute__((unused))) const { + return false; + } + virtual void handleRequest(__unused AsyncWebServerRequest *request) {} + virtual void handleUpload( + __unused AsyncWebServerRequest *request, __unused const String &filename, __unused size_t index, __unused uint8_t *data, __unused size_t len, + __unused bool final + ) {} + virtual void handleBody(__unused AsyncWebServerRequest *request, __unused uint8_t *data, __unused size_t len, __unused size_t index, __unused size_t total) {} + virtual bool isRequestHandlerTrivial() const { + return true; + } +}; + +/* + * RESPONSE :: One instance is created for each Request (attached by the Handler) + * */ + +typedef enum { + RESPONSE_SETUP, + RESPONSE_HEADERS, + RESPONSE_CONTENT, + RESPONSE_WAIT_ACK, + RESPONSE_END, + RESPONSE_FAILED +} WebResponseState; + +class AsyncWebServerResponse { +protected: + int _code; + std::list _headers; + String _contentType; + size_t _contentLength; + bool _sendContentLength; + bool _chunked; + size_t _headLength; + size_t _sentLength; + size_t _ackedLength; + size_t _writtenLength; + WebResponseState _state; + + static bool headerMustBePresentOnce(const String &name); + +public: + static const char *responseCodeToString(int code); + +public: + AsyncWebServerResponse(); + virtual ~AsyncWebServerResponse() {} + void setCode(int code); + int code() const { + return _code; + } + void setContentLength(size_t len); + void setContentType(const String &type) { + setContentType(type.c_str()); + } + void setContentType(const char *type); + bool addHeader(const char *name, const char *value, bool replaceExisting = true); + bool addHeader(const String &name, const String &value, bool replaceExisting = true) { + return addHeader(name.c_str(), value.c_str(), replaceExisting); + } + bool addHeader(const char *name, long value, bool replaceExisting = true) { + return addHeader(name, String(value), replaceExisting); + } + bool addHeader(const String &name, long value, bool replaceExisting = true) { + return addHeader(name.c_str(), value, replaceExisting); + } + bool removeHeader(const char *name); + bool removeHeader(const char *name, const char *value); + const AsyncWebHeader *getHeader(const char *name) const; + const std::list &getHeaders() const { + return _headers; + } + +#ifndef ESP8266 + [[deprecated("Use instead: _assembleHead(String& buffer, uint8_t version)")]] +#endif + String _assembleHead(uint8_t version) { + String buffer; + _assembleHead(buffer, version); + return buffer; + } + void _assembleHead(String &buffer, uint8_t version); + + virtual bool _started() const; + virtual bool _finished() const; + virtual bool _failed() const; + virtual bool _sourceValid() const; + virtual void _respond(AsyncWebServerRequest *request); + virtual size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time); +}; + +/* + * SERVER :: One instance + * */ + +typedef std::function ArRequestHandlerFunction; +typedef std::function + ArUploadHandlerFunction; +typedef std::function ArBodyHandlerFunction; + +class AsyncWebServer : public AsyncMiddlewareChain { +protected: + AsyncServer _server; + std::list> _rewrites; + std::list> _handlers; + AsyncCallbackWebHandler *_catchAllHandler; + +public: + AsyncWebServer(uint16_t port); + ~AsyncWebServer(); + + void begin(); + void end(); + + tcp_state state() const { +#ifdef ESP8266 + // ESPAsyncTCP and RPAsyncTCP methods are not corrected declared with const for immutable ones. + return static_cast(const_cast(this)->_server.status()); +#else + return static_cast(_server.status()); +#endif + } + +#if ASYNC_TCP_SSL_ENABLED + void onSslFileRequest(AcSSlFileHandler cb, void *arg); + void beginSecure(const char *cert, const char *private_key_file, const char *password); +#endif + + AsyncWebRewrite &addRewrite(AsyncWebRewrite *rewrite); + + /** + * @brief (compat) Add url rewrite rule by pointer + * a deep copy of the pointer object will be created, + * it is up to user to manage further lifetime of the object in argument + * + * @param rewrite pointer to rewrite object to copy setting from + * @return AsyncWebRewrite& reference to a newly created rewrite rule + */ + AsyncWebRewrite &addRewrite(std::shared_ptr rewrite); + + /** + * @brief add url rewrite rule + * + * @param from + * @param to + * @return AsyncWebRewrite& + */ + AsyncWebRewrite &rewrite(const char *from, const char *to); + + /** + * @brief (compat) remove rewrite rule via referenced object + * this will NOT deallocate pointed object itself, internal rule with same from/to urls will be removed if any + * it's a compat method, better use `removeRewrite(const char* from, const char* to)` + * @param rewrite + * @return true + * @return false + */ + bool removeRewrite(AsyncWebRewrite *rewrite); + + /** + * @brief remove rewrite rule + * + * @param from + * @param to + * @return true + * @return false + */ + bool removeRewrite(const char *from, const char *to); + + AsyncWebHandler &addHandler(AsyncWebHandler *handler); + bool removeHandler(AsyncWebHandler *handler); + + AsyncCallbackWebHandler &on(const char *uri, ArRequestHandlerFunction onRequest) { + return on(uri, HTTP_ANY, onRequest); + } + AsyncCallbackWebHandler &on( + const char *uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload = nullptr, + ArBodyHandlerFunction onBody = nullptr + ); + + AsyncStaticWebHandler &serveStatic(const char *uri, fs::FS &fs, const char *path, const char *cache_control = NULL); + + void onNotFound(ArRequestHandlerFunction fn); // called when handler is not assigned + void onFileUpload(ArUploadHandlerFunction fn); // handle file uploads + void onRequestBody(ArBodyHandlerFunction fn); // handle posts with plain body content (JSON often transmitted this way as a request) + // give access to the handler used to catch all requests, so that middleware can be added to it + AsyncWebHandler &catchAllHandler() const; + + void reset(); // remove all writers and handlers, with onNotFound/onFileUpload/onRequestBody + + void _handleDisconnect(AsyncWebServerRequest *request); + void _attachHandler(AsyncWebServerRequest *request); + void _rewriteRequest(AsyncWebServerRequest *request); +}; + +class DefaultHeaders { + using headers_t = std::list; + headers_t _headers; + +public: + DefaultHeaders() = default; + + using ConstIterator = headers_t::const_iterator; + + void addHeader(const String &name, const String &value) { + _headers.emplace_back(name, value); + } + + ConstIterator begin() const { + return _headers.begin(); + } + ConstIterator end() const { + return _headers.end(); + } + + DefaultHeaders(DefaultHeaders const &) = delete; + DefaultHeaders &operator=(DefaultHeaders const &) = delete; + + static DefaultHeaders &Instance() { + static DefaultHeaders instance; + return instance; + } +}; + +#include "AsyncEventSource.h" +#include "AsyncWebSocket.h" +#include "WebHandlerImpl.h" +#include "WebResponseImpl.h" + +#endif /* _AsyncWebServer_H_ */ diff --git a/watering/lib/ESPAsyncWebServer/src/Middleware.cpp b/watering/lib/ESPAsyncWebServer/src/Middleware.cpp new file mode 100644 index 0000000..890303d --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/Middleware.cpp @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "WebAuthentication.h" +#include + +AsyncMiddlewareChain::~AsyncMiddlewareChain() { + for (AsyncMiddleware *m : _middlewares) { + if (m->_freeOnRemoval) { + delete m; + } + } +} + +void AsyncMiddlewareChain::addMiddleware(ArMiddlewareCallback fn) { + AsyncMiddlewareFunction *m = new AsyncMiddlewareFunction(fn); + m->_freeOnRemoval = true; + _middlewares.emplace_back(m); +} + +void AsyncMiddlewareChain::addMiddleware(AsyncMiddleware *middleware) { + if (middleware) { + _middlewares.emplace_back(middleware); + } +} + +void AsyncMiddlewareChain::addMiddlewares(std::vector middlewares) { + for (AsyncMiddleware *m : middlewares) { + addMiddleware(m); + } +} + +bool AsyncMiddlewareChain::removeMiddleware(AsyncMiddleware *middleware) { + // remove all middlewares from _middlewares vector being equal to middleware, delete them having _freeOnRemoval flag to true and resize the vector. + const size_t size = _middlewares.size(); + _middlewares.erase( + std::remove_if( + _middlewares.begin(), _middlewares.end(), + [middleware](AsyncMiddleware *m) { + if (m == middleware) { + if (m->_freeOnRemoval) { + delete m; + } + return true; + } + return false; + } + ), + _middlewares.end() + ); + return size != _middlewares.size(); +} + +void AsyncMiddlewareChain::_runChain(AsyncWebServerRequest *request, ArMiddlewareNext finalizer) { + if (!_middlewares.size()) { + return finalizer(); + } + ArMiddlewareNext next; + std::list::iterator it = _middlewares.begin(); + next = [this, &next, &it, request, finalizer]() { + if (it == _middlewares.end()) { + return finalizer(); + } + AsyncMiddleware *m = *it; + it++; + return m->run(request, next); + }; + return next(); +} + +void AsyncAuthenticationMiddleware::setUsername(const char *username) { + _username = username; + _hasCreds = _username.length() && _credentials.length(); +} + +void AsyncAuthenticationMiddleware::setPassword(const char *password) { + _credentials = password; + _hash = false; + _hasCreds = _username.length() && _credentials.length(); +} + +void AsyncAuthenticationMiddleware::setPasswordHash(const char *hash) { + _credentials = hash; + _hash = _credentials.length(); + _hasCreds = _username.length() && _credentials.length(); +} + +bool AsyncAuthenticationMiddleware::generateHash() { + // ensure we have all the necessary data + if (!_hasCreds) { + return false; + } + + // if we already have a hash, do nothing + if (_hash) { + return false; + } + + switch (_authMethod) { + case AsyncAuthType::AUTH_DIGEST: + _credentials = generateDigestHash(_username.c_str(), _credentials.c_str(), _realm.c_str()); + if (_credentials.length()) { + _hash = true; + return true; + } else { + return false; + } + + case AsyncAuthType::AUTH_BASIC: + _credentials = generateBasicHash(_username.c_str(), _credentials.c_str()); + if (_credentials.length()) { + _hash = true; + return true; + } else { + return false; + } + + default: return false; + } +} + +bool AsyncAuthenticationMiddleware::allowed(AsyncWebServerRequest *request) const { + if (_authMethod == AsyncAuthType::AUTH_NONE) { + return true; + } + + if (_authMethod == AsyncAuthType::AUTH_DENIED) { + return false; + } + + if (!_hasCreds) { + return true; + } + + return request->authenticate(_username.c_str(), _credentials.c_str(), _realm.c_str(), _hash); +} + +void AsyncAuthenticationMiddleware::run(AsyncWebServerRequest *request, ArMiddlewareNext next) { + return allowed(request) ? next() : request->requestAuthentication(_authMethod, _realm.c_str(), _authFailMsg.c_str()); +} + +void AsyncHeaderFreeMiddleware::run(AsyncWebServerRequest *request, ArMiddlewareNext next) { + std::list toRemove; + for (auto &h : request->getHeaders()) { + bool keep = false; + for (const char *k : _toKeep) { + if (strcasecmp(h.name().c_str(), k) == 0) { + keep = true; + break; + } + } + if (!keep) { + toRemove.push_back(h.name().c_str()); + } + } + for (const char *h : toRemove) { + request->removeHeader(h); + } + next(); +} + +void AsyncHeaderFilterMiddleware::run(AsyncWebServerRequest *request, ArMiddlewareNext next) { + for (auto it = _toRemove.begin(); it != _toRemove.end(); ++it) { + request->removeHeader(*it); + } + next(); +} + +void AsyncLoggingMiddleware::run(AsyncWebServerRequest *request, ArMiddlewareNext next) { + if (!isEnabled()) { + next(); + return; + } + _out->print(F("* Connection from ")); + _out->print(request->client()->remoteIP().toString()); + _out->print(':'); + _out->println(request->client()->remotePort()); + _out->print('>'); + _out->print(' '); + _out->print(request->methodToString()); + _out->print(' '); + _out->print(request->url().c_str()); + _out->print(F(" HTTP/1.")); + _out->println(request->version()); + for (auto &h : request->getHeaders()) { + if (h.value().length()) { + _out->print('>'); + _out->print(' '); + _out->print(h.name()); + _out->print(':'); + _out->print(' '); + _out->println(h.value()); + } + } + _out->println(F(">")); + uint32_t elapsed = millis(); + next(); + elapsed = millis() - elapsed; + AsyncWebServerResponse *response = request->getResponse(); + if (response) { + _out->print(F("* Processed in ")); + _out->print(elapsed); + _out->println(F(" ms")); + _out->print('<'); + _out->print(F(" HTTP/1.")); + _out->print(request->version()); + _out->print(' '); + _out->print(response->code()); + _out->print(' '); + _out->println(AsyncWebServerResponse::responseCodeToString(response->code())); + for (auto &h : response->getHeaders()) { + if (h.value().length()) { + _out->print('<'); + _out->print(' '); + _out->print(h.name()); + _out->print(':'); + _out->print(' '); + _out->println(h.value()); + } + } + _out->println('<'); + } else { + _out->println(F("* Connection closed!")); + } +} + +void AsyncCorsMiddleware::addCORSHeaders(AsyncWebServerResponse *response) { + response->addHeader(asyncsrv::T_CORS_ACAO, _origin.c_str()); + response->addHeader(asyncsrv::T_CORS_ACAM, _methods.c_str()); + response->addHeader(asyncsrv::T_CORS_ACAH, _headers.c_str()); + response->addHeader(asyncsrv::T_CORS_ACAC, _credentials ? asyncsrv::T_TRUE : asyncsrv::T_FALSE); + response->addHeader(asyncsrv::T_CORS_ACMA, String(_maxAge).c_str()); +} + +void AsyncCorsMiddleware::run(AsyncWebServerRequest *request, ArMiddlewareNext next) { + // Origin header ? => CORS handling + if (request->hasHeader(asyncsrv::T_CORS_O)) { + // check if this is a preflight request => handle it and return + if (request->method() == HTTP_OPTIONS) { + AsyncWebServerResponse *response = request->beginResponse(200); + addCORSHeaders(response); + request->send(response); + return; + } + + // CORS request, no options => let the request pass and add CORS headers after + next(); + AsyncWebServerResponse *response = request->getResponse(); + if (response) { + addCORSHeaders(response); + } + + } else { + // NO Origin header => no CORS handling + next(); + } +} + +bool AsyncRateLimitMiddleware::isRequestAllowed(uint32_t &retryAfterSeconds) { + uint32_t now = millis(); + + while (!_requestTimes.empty() && _requestTimes.front() <= now - _windowSizeMillis) { + _requestTimes.pop_front(); + } + + _requestTimes.push_back(now); + + if (_requestTimes.size() > _maxRequests) { + _requestTimes.pop_front(); + retryAfterSeconds = (_windowSizeMillis - (now - _requestTimes.front())) / 1000 + 1; + return false; + } + + retryAfterSeconds = 0; + return true; +} + +void AsyncRateLimitMiddleware::run(AsyncWebServerRequest *request, ArMiddlewareNext next) { + uint32_t retryAfterSeconds; + if (isRequestAllowed(retryAfterSeconds)) { + next(); + } else { + AsyncWebServerResponse *response = request->beginResponse(429); + response->addHeader(asyncsrv::T_retry_after, retryAfterSeconds); + request->send(response); + } +} diff --git a/watering/lib/ESPAsyncWebServer/src/WebAuthentication.cpp b/watering/lib/ESPAsyncWebServer/src/WebAuthentication.cpp new file mode 100644 index 0000000..7ed7814 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/WebAuthentication.cpp @@ -0,0 +1,247 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "WebAuthentication.h" +#include +#if defined(ESP32) || defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) +#include +#else +#include "md5.h" +#endif +#include "literals.h" + +using namespace asyncsrv; + +// Basic Auth hash = base64("username:password") + +bool checkBasicAuthentication(const char *hash, const char *username, const char *password) { + if (username == NULL || password == NULL || hash == NULL) { + return false; + } + return generateBasicHash(username, password).equalsIgnoreCase(hash); +} + +String generateBasicHash(const char *username, const char *password) { + if (username == NULL || password == NULL) { + return emptyString; + } + + size_t toencodeLen = strlen(username) + strlen(password) + 1; + + char *toencode = new char[toencodeLen + 1]; + if (toencode == NULL) { + return emptyString; + } + char *encoded = new char[base64_encode_expected_len(toencodeLen) + 1]; + if (encoded == NULL) { + delete[] toencode; + return emptyString; + } + sprintf_P(toencode, PSTR("%s:%s"), username, password); + if (base64_encode_chars(toencode, toencodeLen, encoded) > 0) { + String res = String(encoded); + delete[] toencode; + delete[] encoded; + return res; + } + delete[] toencode; + delete[] encoded; + return emptyString; +} + +static bool getMD5(uint8_t *data, uint16_t len, char *output) { // 33 bytes or more +#if defined(ESP32) || defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) + MD5Builder md5; + md5.begin(); + md5.add(data, len); + md5.calculate(); + md5.getChars(output); +#else + md5_context_t _ctx; + + uint8_t *_buf = (uint8_t *)malloc(16); + if (_buf == NULL) { + return false; + } + memset(_buf, 0x00, 16); + + MD5Init(&_ctx); + MD5Update(&_ctx, data, len); + MD5Final(_buf, &_ctx); + + for (uint8_t i = 0; i < 16; i++) { + sprintf_P(output + (i * 2), PSTR("%02x"), _buf[i]); + } + + free(_buf); +#endif + return true; +} + +String genRandomMD5() { +#ifdef ESP8266 + uint32_t r = RANDOM_REG32; +#else + uint32_t r = rand(); +#endif + char *out = (char *)malloc(33); + if (out == NULL || !getMD5((uint8_t *)(&r), 4, out)) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + return emptyString; + } + String res = String(out); + free(out); + return res; +} + +static String stringMD5(const String &in) { + char *out = (char *)malloc(33); + if (out == NULL || !getMD5((uint8_t *)(in.c_str()), in.length(), out)) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + return emptyString; + } + String res = String(out); + free(out); + return res; +} + +String generateDigestHash(const char *username, const char *password, const char *realm) { + if (username == NULL || password == NULL || realm == NULL) { + return emptyString; + } + char *out = (char *)malloc(33); + if (out == NULL) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + return emptyString; + } + + String in; + if (!in.reserve(strlen(username) + strlen(realm) + strlen(password) + 2)) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + free(out); + return emptyString; + } + + in.concat(username); + in.concat(':'); + in.concat(realm); + in.concat(':'); + in.concat(password); + + if (!getMD5((uint8_t *)(in.c_str()), in.length(), out)) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + free(out); + return emptyString; + } + + in = String(out); + free(out); + return in; +} + +bool checkDigestAuthentication( + const char *header, const char *method, const char *username, const char *password, const char *realm, bool passwordIsHash, const char *nonce, + const char *opaque, const char *uri +) { + if (username == NULL || password == NULL || header == NULL || method == NULL) { + // os_printf("AUTH FAIL: missing required fields\n"); + return false; + } + + String myHeader(header); + int nextBreak = myHeader.indexOf(','); + if (nextBreak < 0) { + // os_printf("AUTH FAIL: no variables\n"); + return false; + } + + String myUsername; + String myRealm; + String myNonce; + String myUri; + String myResponse; + String myQop; + String myNc; + String myCnonce; + + myHeader += (char)0x2c; // ',' + myHeader += (char)0x20; // ' ' + do { + String avLine(myHeader.substring(0, nextBreak)); + avLine.trim(); + myHeader = myHeader.substring(nextBreak + 1); + nextBreak = myHeader.indexOf(','); + + int eqSign = avLine.indexOf('='); + if (eqSign < 0) { + // os_printf("AUTH FAIL: no = sign\n"); + return false; + } + String varName(avLine.substring(0, eqSign)); + avLine = avLine.substring(eqSign + 1); + if (avLine.startsWith(String('"'))) { + avLine = avLine.substring(1, avLine.length() - 1); + } + + if (varName.equals(T_username)) { + if (!avLine.equals(username)) { + // os_printf("AUTH FAIL: username\n"); + return false; + } + myUsername = avLine; + } else if (varName.equals(T_realm)) { + if (realm != NULL && !avLine.equals(realm)) { + // os_printf("AUTH FAIL: realm\n"); + return false; + } + myRealm = avLine; + } else if (varName.equals(T_nonce)) { + if (nonce != NULL && !avLine.equals(nonce)) { + // os_printf("AUTH FAIL: nonce\n"); + return false; + } + myNonce = avLine; + } else if (varName.equals(T_opaque)) { + if (opaque != NULL && !avLine.equals(opaque)) { + // os_printf("AUTH FAIL: opaque\n"); + return false; + } + } else if (varName.equals(T_uri)) { + if (uri != NULL && !avLine.equals(uri)) { + // os_printf("AUTH FAIL: uri\n"); + return false; + } + myUri = avLine; + } else if (varName.equals(T_response)) { + myResponse = avLine; + } else if (varName.equals(T_qop)) { + myQop = avLine; + } else if (varName.equals(T_nc)) { + myNc = avLine; + } else if (varName.equals(T_cnonce)) { + myCnonce = avLine; + } + } while (nextBreak > 0); + + String ha1 = passwordIsHash ? password : stringMD5(myUsername + ':' + myRealm + ':' + password).c_str(); + String ha2 = stringMD5(String(method) + ':' + myUri); + String response = ha1 + ':' + myNonce + ':' + myNc + ':' + myCnonce + ':' + myQop + ':' + ha2; + + if (myResponse.equals(stringMD5(response))) { + // os_printf("AUTH SUCCESS\n"); + return true; + } + + // os_printf("AUTH FAIL: password\n"); + return false; +} diff --git a/watering/lib/ESPAsyncWebServer/src/WebAuthentication.h b/watering/lib/ESPAsyncWebServer/src/WebAuthentication.h new file mode 100644 index 0000000..1711821 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/WebAuthentication.h @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef WEB_AUTHENTICATION_H_ +#define WEB_AUTHENTICATION_H_ + +#include "Arduino.h" + +bool checkBasicAuthentication(const char *header, const char *username, const char *password); + +bool checkDigestAuthentication( + const char *header, const char *method, const char *username, const char *password, const char *realm, bool passwordIsHash, const char *nonce, + const char *opaque, const char *uri +); + +// for storing hashed versions on the device that can be authenticated against +String generateDigestHash(const char *username, const char *password, const char *realm); + +String generateBasicHash(const char *username, const char *password); + +String genRandomMD5(); + +#endif diff --git a/watering/lib/ESPAsyncWebServer/src/WebHandlerImpl.h b/watering/lib/ESPAsyncWebServer/src/WebHandlerImpl.h new file mode 100644 index 0000000..1f68d62 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/WebHandlerImpl.h @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef ASYNCWEBSERVERHANDLERIMPL_H_ +#define ASYNCWEBSERVERHANDLERIMPL_H_ + +#include +#ifdef ASYNCWEBSERVER_REGEX +#include +#endif + +#include "stddef.h" +#include + +class AsyncStaticWebHandler : public AsyncWebHandler { + using File = fs::File; + using FS = fs::FS; + +private: + bool _getFile(AsyncWebServerRequest *request) const; + bool _searchFile(AsyncWebServerRequest *request, const String &path); + +protected: + FS _fs; + String _uri; + String _path; + String _default_file; + String _cache_control; + String _last_modified; + AwsTemplateProcessor _callback; + bool _isDir; + bool _tryGzipFirst = true; + +public: + AsyncStaticWebHandler(const char *uri, FS &fs, const char *path, const char *cache_control); + bool canHandle(AsyncWebServerRequest *request) const override final; + void handleRequest(AsyncWebServerRequest *request) override final; + AsyncStaticWebHandler &setTryGzipFirst(bool value); + AsyncStaticWebHandler &setIsDir(bool isDir); + AsyncStaticWebHandler &setDefaultFile(const char *filename); + AsyncStaticWebHandler &setCacheControl(const char *cache_control); + + /** + * @brief Set the Last-Modified time for the object + * + * @param last_modified + * @return AsyncStaticWebHandler& + */ + AsyncStaticWebHandler &setLastModified(const char *last_modified); + AsyncStaticWebHandler &setLastModified(struct tm *last_modified); + AsyncStaticWebHandler &setLastModified(time_t last_modified); + // sets to current time. Make sure sntp is running and time is updated + AsyncStaticWebHandler &setLastModified(); + + AsyncStaticWebHandler &setTemplateProcessor(AwsTemplateProcessor newCallback); +}; + +class AsyncCallbackWebHandler : public AsyncWebHandler { +private: +protected: + String _uri; + WebRequestMethodComposite _method; + ArRequestHandlerFunction _onRequest; + ArUploadHandlerFunction _onUpload; + ArBodyHandlerFunction _onBody; + bool _isRegex; + +public: + AsyncCallbackWebHandler() : _uri(), _method(HTTP_ANY), _onRequest(NULL), _onUpload(NULL), _onBody(NULL), _isRegex(false) {} + void setUri(const String &uri); + void setMethod(WebRequestMethodComposite method) { + _method = method; + } + void onRequest(ArRequestHandlerFunction fn) { + _onRequest = fn; + } + void onUpload(ArUploadHandlerFunction fn) { + _onUpload = fn; + } + void onBody(ArBodyHandlerFunction fn) { + _onBody = fn; + } + + bool canHandle(AsyncWebServerRequest *request) const override final; + void handleRequest(AsyncWebServerRequest *request) override final; + void handleUpload(AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) override final; + void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) override final; + bool isRequestHandlerTrivial() const override final { + return !_onRequest; + } +}; + +#endif /* ASYNCWEBSERVERHANDLERIMPL_H_ */ diff --git a/watering/lib/ESPAsyncWebServer/src/WebHandlers.cpp b/watering/lib/ESPAsyncWebServer/src/WebHandlers.cpp new file mode 100644 index 0000000..acfc7c0 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/WebHandlers.cpp @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "ESPAsyncWebServer.h" +#include "WebHandlerImpl.h" + +using namespace asyncsrv; + +AsyncWebHandler &AsyncWebHandler::setFilter(ArRequestFilterFunction fn) { + _filter = fn; + return *this; +} +AsyncWebHandler &AsyncWebHandler::setAuthentication(const char *username, const char *password, AsyncAuthType authMethod) { + if (!_authMiddleware) { + _authMiddleware = new AsyncAuthenticationMiddleware(); + _authMiddleware->_freeOnRemoval = true; + addMiddleware(_authMiddleware); + } + _authMiddleware->setUsername(username); + _authMiddleware->setPassword(password); + _authMiddleware->setAuthType(authMethod); + return *this; +}; + +AsyncStaticWebHandler::AsyncStaticWebHandler(const char *uri, FS &fs, const char *path, const char *cache_control) + : _fs(fs), _uri(uri), _path(path), _default_file(F("index.htm")), _cache_control(cache_control), _last_modified(), _callback(nullptr) { + // Ensure leading '/' + if (_uri.length() == 0 || _uri[0] != '/') { + _uri = String('/') + _uri; + } + if (_path.length() == 0 || _path[0] != '/') { + _path = String('/') + _path; + } + + // If path ends with '/' we assume a hint that this is a directory to improve performance. + // However - if it does not end with '/' we, can't assume a file, path can still be a directory. + _isDir = _path[_path.length() - 1] == '/'; + + // Remove the trailing '/' so we can handle default file + // Notice that root will be "" not "/" + if (_uri[_uri.length() - 1] == '/') { + _uri = _uri.substring(0, _uri.length() - 1); + } + if (_path[_path.length() - 1] == '/') { + _path = _path.substring(0, _path.length() - 1); + } +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setTryGzipFirst(bool value) { + _tryGzipFirst = value; + return *this; +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setIsDir(bool isDir) { + _isDir = isDir; + return *this; +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setDefaultFile(const char *filename) { + _default_file = filename; + return *this; +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setCacheControl(const char *cache_control) { + _cache_control = cache_control; + return *this; +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setLastModified(const char *last_modified) { + _last_modified = last_modified; + return *this; +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setLastModified(struct tm *last_modified) { + char result[30]; +#ifdef ESP8266 + auto formatP = PSTR("%a, %d %b %Y %H:%M:%S GMT"); + char format[strlen_P(formatP) + 1]; + strcpy_P(format, formatP); +#else + static constexpr const char *format = "%a, %d %b %Y %H:%M:%S GMT"; +#endif + + strftime(result, sizeof(result), format, last_modified); + _last_modified = result; + return *this; +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setLastModified(time_t last_modified) { + return setLastModified((struct tm *)gmtime(&last_modified)); +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setLastModified() { + time_t last_modified; + if (time(&last_modified) == 0) { // time is not yet set + return *this; + } + return setLastModified(last_modified); +} + +bool AsyncStaticWebHandler::canHandle(AsyncWebServerRequest *request) const { + return request->isHTTP() && request->method() == HTTP_GET && request->url().startsWith(_uri) && _getFile(request); +} + +bool AsyncStaticWebHandler::_getFile(AsyncWebServerRequest *request) const { + // Remove the found uri + String path = request->url().substring(_uri.length()); + + // We can skip the file check and look for default if request is to the root of a directory or that request path ends with '/' + bool canSkipFileCheck = (_isDir && path.length() == 0) || (path.length() && path[path.length() - 1] == '/'); + + path = _path + path; + + // Do we have a file or .gz file + if (!canSkipFileCheck && const_cast(this)->_searchFile(request, path)) { + return true; + } + + // Can't handle if not default file + if (_default_file.length() == 0) { + return false; + } + + // Try to add default file, ensure there is a trailing '/' to the path. + if (path.length() == 0 || path[path.length() - 1] != '/') { + path += String('/'); + } + path += _default_file; + + return const_cast(this)->_searchFile(request, path); +} + +#ifdef ESP32 +#define FILE_IS_REAL(f) (f == true && !f.isDirectory()) +#else +#define FILE_IS_REAL(f) (f == true) +#endif + +bool AsyncStaticWebHandler::_searchFile(AsyncWebServerRequest *request, const String &path) { + bool fileFound = false; + bool gzipFound = false; + + String gzip = path + T__gz; + + if (_tryGzipFirst) { + if (_fs.exists(gzip)) { + request->_tempFile = _fs.open(gzip, fs::FileOpenMode::read); + gzipFound = FILE_IS_REAL(request->_tempFile); + } + if (!gzipFound) { + if (_fs.exists(path)) { + request->_tempFile = _fs.open(path, fs::FileOpenMode::read); + fileFound = FILE_IS_REAL(request->_tempFile); + } + } + } else { + if (_fs.exists(path)) { + request->_tempFile = _fs.open(path, fs::FileOpenMode::read); + fileFound = FILE_IS_REAL(request->_tempFile); + } + if (!fileFound) { + if (_fs.exists(gzip)) { + request->_tempFile = _fs.open(gzip, fs::FileOpenMode::read); + gzipFound = FILE_IS_REAL(request->_tempFile); + } + } + } + + bool found = fileFound || gzipFound; + + if (found) { + // Extract the file name from the path and keep it in _tempObject + size_t pathLen = path.length(); + char *_tempPath = (char *)malloc(pathLen + 1); + if (_tempPath == NULL) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + request->abort(); + request->_tempFile.close(); + return false; + } + snprintf_P(_tempPath, pathLen + 1, PSTR("%s"), path.c_str()); + request->_tempObject = (void *)_tempPath; + } + + return found; +} + +void AsyncStaticWebHandler::handleRequest(AsyncWebServerRequest *request) { + // Get the filename from request->_tempObject and free it + String filename((char *)request->_tempObject); + free(request->_tempObject); + request->_tempObject = NULL; + + if (request->_tempFile != true) { + request->send(404); + return; + } + + time_t lw = request->_tempFile.getLastWrite(); // get last file mod time (if supported by FS) + // set etag to lastmod timestamp if available, otherwise to size + String etag; + if (lw) { + setLastModified(lw); +#if defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) + // time_t == long long int + constexpr size_t len = 1 + 8 * sizeof(time_t); + char buf[len]; + char *ret = lltoa(lw ^ request->_tempFile.size(), buf, len, 10); + etag = ret ? String(ret) : String(request->_tempFile.size()); +#else + etag = lw ^ request->_tempFile.size(); // etag combines file size and lastmod timestamp +#endif + } else { +#if defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) + etag = String(request->_tempFile.size()); +#else + etag = request->_tempFile.size(); +#endif + } + + bool not_modified = false; + + // if-none-match has precedence over if-modified-since + if (request->hasHeader(T_INM)) { + not_modified = request->header(T_INM).equals(etag); + } else if (_last_modified.length()) { + not_modified = request->header(T_IMS).equals(_last_modified); + } + + AsyncWebServerResponse *response; + + if (not_modified) { + request->_tempFile.close(); + response = new AsyncBasicResponse(304); // Not modified + } else { + response = new AsyncFileResponse(request->_tempFile, filename, emptyString, false, _callback); + } + + if (!response) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + request->abort(); + return; + } + + response->addHeader(T_ETag, etag.c_str()); + + if (_last_modified.length()) { + response->addHeader(T_Last_Modified, _last_modified.c_str()); + } + if (_cache_control.length()) { + response->addHeader(T_Cache_Control, _cache_control.c_str()); + } + + request->send(response); +} + +AsyncStaticWebHandler &AsyncStaticWebHandler::setTemplateProcessor(AwsTemplateProcessor newCallback) { + _callback = newCallback; + return *this; +} + +void AsyncCallbackWebHandler::setUri(const String &uri) { + _uri = uri; + _isRegex = uri.startsWith("^") && uri.endsWith("$"); +} + +bool AsyncCallbackWebHandler::canHandle(AsyncWebServerRequest *request) const { + if (!_onRequest || !request->isHTTP() || !(_method & request->method())) { + return false; + } + +#ifdef ASYNCWEBSERVER_REGEX + if (_isRegex) { + std::regex pattern(_uri.c_str()); + std::smatch matches; + std::string s(request->url().c_str()); + if (std::regex_search(s, matches, pattern)) { + for (size_t i = 1; i < matches.size(); ++i) { // start from 1 + request->_addPathParam(matches[i].str().c_str()); + } + } else { + return false; + } + } else +#endif + if (_uri.length() && _uri.startsWith("/*.")) { + String uriTemplate = String(_uri); + uriTemplate = uriTemplate.substring(uriTemplate.lastIndexOf(".")); + if (!request->url().endsWith(uriTemplate)) { + return false; + } + } else if (_uri.length() && _uri.endsWith("*")) { + String uriTemplate = String(_uri); + uriTemplate = uriTemplate.substring(0, uriTemplate.length() - 1); + if (!request->url().startsWith(uriTemplate)) { + return false; + } + } else if (_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri + "/"))) { + return false; + } + + return true; +} + +void AsyncCallbackWebHandler::handleRequest(AsyncWebServerRequest *request) { + if (_onRequest) { + _onRequest(request); + } else { + request->send(404, T_text_plain, "Not found"); + } +} +void AsyncCallbackWebHandler::handleUpload(AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) { + if (_onUpload) { + _onUpload(request, filename, index, data, len, final); + } +} +void AsyncCallbackWebHandler::handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { + // ESP_LOGD("AsyncWebServer", "AsyncCallbackWebHandler::handleBody"); + if (_onBody) { + _onBody(request, data, len, index, total); + } +} diff --git a/watering/lib/ESPAsyncWebServer/src/WebRequest.cpp b/watering/lib/ESPAsyncWebServer/src/WebRequest.cpp new file mode 100644 index 0000000..8b735af --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/WebRequest.cpp @@ -0,0 +1,1185 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "ESPAsyncWebServer.h" +#include "WebAuthentication.h" +#include "WebResponseImpl.h" +#include "literals.h" +#include + +#define __is_param_char(c) ((c) && ((c) != '{') && ((c) != '[') && ((c) != '&') && ((c) != '=')) + +static void doNotDelete(AsyncWebServerRequest *) {} + +using namespace asyncsrv; + +enum { + PARSE_REQ_START = 0, + PARSE_REQ_HEADERS = 1, + PARSE_REQ_BODY = 2, + PARSE_REQ_END = 3, + PARSE_REQ_FAIL = 4 +}; + +AsyncWebServerRequest::AsyncWebServerRequest(AsyncWebServer *s, AsyncClient *c) + : _client(c), _server(s), _handler(NULL), _response(NULL), _temp(), _parseState(PARSE_REQ_START), _version(0), _method(HTTP_ANY), _url(), _host(), + _contentType(), _boundary(), _authorization(), _reqconntype(RCT_HTTP), _authMethod(AsyncAuthType::AUTH_NONE), _isMultipart(false), _isPlainPost(false), + _expectingContinue(false), _contentLength(0), _parsedLength(0), _multiParseState(0), _boundaryPosition(0), _itemStartIndex(0), _itemSize(0), _itemName(), + _itemFilename(), _itemType(), _itemValue(), _itemBuffer(0), _itemBufferIndex(0), _itemIsFile(false), _tempObject(NULL) { + c->onError( + [](void *r, AsyncClient *c, int8_t error) { + (void)c; + // log_e("AsyncWebServerRequest::_onError"); + AsyncWebServerRequest *req = (AsyncWebServerRequest *)r; + req->_onError(error); + }, + this + ); + c->onAck( + [](void *r, AsyncClient *c, size_t len, uint32_t time) { + (void)c; + // log_e("AsyncWebServerRequest::_onAck"); + AsyncWebServerRequest *req = (AsyncWebServerRequest *)r; + req->_onAck(len, time); + }, + this + ); + c->onDisconnect( + [](void *r, AsyncClient *c) { + // log_e("AsyncWebServerRequest::_onDisconnect"); + AsyncWebServerRequest *req = (AsyncWebServerRequest *)r; + req->_onDisconnect(); + delete c; + }, + this + ); + c->onTimeout( + [](void *r, AsyncClient *c, uint32_t time) { + (void)c; + // log_e("AsyncWebServerRequest::_onTimeout"); + AsyncWebServerRequest *req = (AsyncWebServerRequest *)r; + req->_onTimeout(time); + }, + this + ); + c->onData( + [](void *r, AsyncClient *c, void *buf, size_t len) { + (void)c; + // log_e("AsyncWebServerRequest::_onData"); + AsyncWebServerRequest *req = (AsyncWebServerRequest *)r; + req->_onData(buf, len); + }, + this + ); + c->onPoll( + [](void *r, AsyncClient *c) { + (void)c; + // log_e("AsyncWebServerRequest::_onPoll"); + AsyncWebServerRequest *req = (AsyncWebServerRequest *)r; + req->_onPoll(); + }, + this + ); +} + +AsyncWebServerRequest::~AsyncWebServerRequest() { + // log_e("AsyncWebServerRequest::~AsyncWebServerRequest"); + + _this.reset(); + + _headers.clear(); + + _pathParams.clear(); + + AsyncWebServerResponse *r = _response; + _response = NULL; + delete r; + + if (_tempObject != NULL) { + free(_tempObject); + } + + if (_tempFile) { + _tempFile.close(); + } + + if (_itemBuffer) { + free(_itemBuffer); + } +} + +void AsyncWebServerRequest::_onData(void *buf, size_t len) { + // SSL/TLS handshake detection +#ifndef ASYNC_TCP_SSL_ENABLED + if (_parseState == PARSE_REQ_START && len && ((uint8_t *)buf)[0] == 0x16) { // 0x16 indicates a Handshake message (SSL/TLS). +#ifdef ESP32 + log_d("SSL/TLS handshake detected: resetting connection"); +#endif + _parseState = PARSE_REQ_FAIL; + abort(); + return; + } +#endif + + size_t i = 0; + while (true) { + + if (_parseState < PARSE_REQ_BODY) { + // Find new line in buf + char *str = (char *)buf; + for (i = 0; i < len; i++) { + // Check for null characters in header + if (!str[i]) { + _parseState = PARSE_REQ_FAIL; + abort(); + return; + } + if (str[i] == '\n') { + break; + } + } + if (i == len) { // No new line, just add the buffer in _temp + char ch = str[len - 1]; + str[len - 1] = 0; + if (!_temp.reserve(_temp.length() + len)) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + _parseState = PARSE_REQ_FAIL; + abort(); + return; + } + _temp.concat(str); + _temp.concat(ch); + } else { // Found new line - extract it and parse + str[i] = 0; // Terminate the string at the end of the line. + _temp.concat(str); + _temp.trim(); + _parseLine(); + if (++i < len) { + // Still have more buffer to process + buf = str + i; + len -= i; + continue; + } + } + } else if (_parseState == PARSE_REQ_BODY) { + // A handler should be already attached at this point in _parseLine function. + // If handler does nothing (_onRequest is NULL), we don't need to really parse the body. + const bool needParse = _handler && !_handler->isRequestHandlerTrivial(); + // Discard any bytes after content length; handlers may overrun their buffers + len = std::min(len, _contentLength - _parsedLength); + if (_isMultipart) { + if (needParse) { + size_t i; + for (i = 0; i < len; i++) { + _parseMultipartPostByte(((uint8_t *)buf)[i], i == len - 1); + _parsedLength++; + } + } else { + _parsedLength += len; + } + } else { + if (_parsedLength == 0) { + if (_contentType.startsWith(T_app_xform_urlencoded)) { + _isPlainPost = true; + } else if (_contentType == T_text_plain && __is_param_char(((char *)buf)[0])) { + size_t i = 0; + while (i < len && __is_param_char(((char *)buf)[i++])); + if (i < len && ((char *)buf)[i - 1] == '=') { + _isPlainPost = true; + } + } + } + if (!_isPlainPost) { + // ESP_LOGD("AsyncWebServer", "_isPlainPost: %d, _handler: %p", _isPlainPost, _handler); + if (_handler) { + _handler->handleBody(this, (uint8_t *)buf, len, _parsedLength, _contentLength); + } + _parsedLength += len; + } else if (needParse) { + size_t i; + for (i = 0; i < len; i++) { + _parsedLength++; + _parsePlainPostChar(((uint8_t *)buf)[i]); + } + } else { + _parsedLength += len; + } + } + if (_parsedLength == _contentLength) { + _parseState = PARSE_REQ_END; + _runMiddlewareChain(); + _send(); + } + } + break; + } +} + +void AsyncWebServerRequest::_onPoll() { + // os_printf("p\n"); + if (_response != NULL && _client != NULL && _client->canSend()) { + if (!_response->_finished()) { + _response->_ack(this, 0, 0); + } else { + AsyncWebServerResponse *r = _response; + _response = NULL; + delete r; + + _client->close(); + } + } +} + +void AsyncWebServerRequest::_onAck(size_t len, uint32_t time) { + // os_printf("a:%u:%u\n", len, time); + if (_response != NULL) { + if (!_response->_finished()) { + _response->_ack(this, len, time); + } else if (_response->_finished()) { + AsyncWebServerResponse *r = _response; + _response = NULL; + delete r; + + _client->close(); + } + } +} + +void AsyncWebServerRequest::_onError(int8_t error) { + (void)error; +} + +void AsyncWebServerRequest::_onTimeout(uint32_t time) { + (void)time; + // os_printf("TIMEOUT: %u, state: %s\n", time, _client->stateToString()); + _client->close(); +} + +void AsyncWebServerRequest::onDisconnect(ArDisconnectHandler fn) { + _onDisconnectfn = fn; +} + +void AsyncWebServerRequest::_onDisconnect() { + // os_printf("d\n"); + if (_onDisconnectfn) { + _onDisconnectfn(); + } + _server->_handleDisconnect(this); +} + +void AsyncWebServerRequest::_addPathParam(const char *p) { + _pathParams.emplace_back(p); +} + +void AsyncWebServerRequest::_addGetParams(const String ¶ms) { + size_t start = 0; + while (start < params.length()) { + int end = params.indexOf('&', start); + if (end < 0) { + end = params.length(); + } + int equal = params.indexOf('=', start); + if (equal < 0 || equal > end) { + equal = end; + } + String name = urlDecode(params.substring(start, equal)); + String value = urlDecode(equal + 1 < end ? params.substring(equal + 1, end) : emptyString); + if (name.length()) { + _params.emplace_back(name, value); + } + start = end + 1; + } +} + +bool AsyncWebServerRequest::_parseReqHead() { + // Split the head into method, url and version + int index = _temp.indexOf(' '); + String m = _temp.substring(0, index); + index = _temp.indexOf(' ', index + 1); + String u = _temp.substring(m.length() + 1, index); + _temp = _temp.substring(index + 1); + + if (m == T_GET) { + _method = HTTP_GET; + } else if (m == T_POST) { + _method = HTTP_POST; + } else if (m == T_DELETE) { + _method = HTTP_DELETE; + } else if (m == T_PUT) { + _method = HTTP_PUT; + } else if (m == T_PATCH) { + _method = HTTP_PATCH; + } else if (m == T_HEAD) { + _method = HTTP_HEAD; + } else if (m == T_OPTIONS) { + _method = HTTP_OPTIONS; + } else { + return false; + } + + String g; + index = u.indexOf('?'); + if (index > 0) { + g = u.substring(index + 1); + u = u.substring(0, index); + } + _url = urlDecode(u); + _addGetParams(g); + + if (!_url.length()) { + return false; + } + + if (!_temp.startsWith(T_HTTP_1_0)) { + _version = 1; + } + + _temp = emptyString; + return true; +} + +bool AsyncWebServerRequest::_parseReqHeader() { + int index = _temp.indexOf(':'); + if (index) { + String name(_temp.substring(0, index)); + String value(_temp.substring(index + 2)); + if (name.equalsIgnoreCase(T_Host)) { + _host = value; + } else if (name.equalsIgnoreCase(T_Content_Type)) { + _contentType = value.substring(0, value.indexOf(';')); + if (value.startsWith(T_MULTIPART_)) { + _boundary = value.substring(value.indexOf('=') + 1); + _boundary.replace(String('"'), String()); + _isMultipart = true; + } + } else if (name.equalsIgnoreCase(T_Content_Length)) { + _contentLength = atoi(value.c_str()); + } else if (name.equalsIgnoreCase(T_EXPECT) && value.equalsIgnoreCase(T_100_CONTINUE)) { + _expectingContinue = true; + } else if (name.equalsIgnoreCase(T_AUTH)) { + int space = value.indexOf(' '); + if (space == -1) { + _authorization = value; + _authMethod = AsyncAuthType::AUTH_OTHER; + } else { + String method = value.substring(0, space); + if (method.equalsIgnoreCase(T_BASIC)) { + _authMethod = AsyncAuthType::AUTH_BASIC; + } else if (method.equalsIgnoreCase(T_DIGEST)) { + _authMethod = AsyncAuthType::AUTH_DIGEST; + } else if (method.equalsIgnoreCase(T_BEARER)) { + _authMethod = AsyncAuthType::AUTH_BEARER; + } else { + _authMethod = AsyncAuthType::AUTH_OTHER; + } + _authorization = value.substring(space + 1); + } + } else if (name.equalsIgnoreCase(T_UPGRADE) && value.equalsIgnoreCase(T_WS)) { + // WebSocket request can be uniquely identified by header: [Upgrade: websocket] + _reqconntype = RCT_WS; + } else if (name.equalsIgnoreCase(T_ACCEPT)) { + String lowcase(value); + lowcase.toLowerCase(); +#ifndef ESP8266 + const char *substr = std::strstr(lowcase.c_str(), T_text_event_stream); +#else + const char *substr = std::strstr(lowcase.c_str(), String(T_text_event_stream).c_str()); +#endif + if (substr != NULL) { + // WebEvent request can be uniquely identified by header: [Accept: text/event-stream] + _reqconntype = RCT_EVENT; + } + } + _headers.emplace_back(name, value); + } +#if defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) + // Ancient PRI core does not have String::clear() method 8-() + _temp = emptyString; +#else + _temp.clear(); +#endif + return true; +} + +void AsyncWebServerRequest::_parsePlainPostChar(uint8_t data) { + if (data && (char)data != '&') { + _temp += (char)data; + } + if (!data || (char)data == '&' || _parsedLength == _contentLength) { + String name(T_BODY); + String value(_temp); + if (!(_temp.charAt(0) == '{') && !(_temp.charAt(0) == '[') && _temp.indexOf('=') > 0) { + name = _temp.substring(0, _temp.indexOf('=')); + value = _temp.substring(_temp.indexOf('=') + 1); + } + name = urlDecode(name); + if (name.length()) { + _params.emplace_back(name, urlDecode(value), true); + } + +#if defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) + // Ancient PRI core does not have String::clear() method 8-() + _temp = emptyString; +#else + _temp.clear(); +#endif + } +} + +void AsyncWebServerRequest::_handleUploadByte(uint8_t data, bool last) { + _itemBuffer[_itemBufferIndex++] = data; + + if (last || _itemBufferIndex == RESPONSE_STREAM_BUFFER_SIZE) { + // check if authenticated before calling the upload + if (_handler) { + _handler->handleUpload(this, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, false); + } + _itemBufferIndex = 0; + } +} + +enum { + EXPECT_BOUNDARY, + PARSE_HEADERS, + WAIT_FOR_RETURN1, + EXPECT_FEED1, + EXPECT_DASH1, + EXPECT_DASH2, + BOUNDARY_OR_DATA, + DASH3_OR_RETURN2, + EXPECT_FEED2, + PARSING_FINISHED, + PARSE_ERROR +}; + +void AsyncWebServerRequest::_parseMultipartPostByte(uint8_t data, bool last) { +#define itemWriteByte(b) \ + do { \ + _itemSize++; \ + if (_itemIsFile) \ + _handleUploadByte(b, last); \ + else \ + _itemValue += (char)(b); \ + } while (0) + + if (!_parsedLength) { + _multiParseState = EXPECT_BOUNDARY; + _temp = emptyString; + _itemName = emptyString; + _itemFilename = emptyString; + _itemType = emptyString; + } + + if (_multiParseState == WAIT_FOR_RETURN1) { + if (data != '\r') { + itemWriteByte(data); + } else { + _multiParseState = EXPECT_FEED1; + } + } else if (_multiParseState == EXPECT_BOUNDARY) { + if (_parsedLength < 2 && data != '-') { + _multiParseState = PARSE_ERROR; + return; + } else if (_parsedLength - 2 < _boundary.length() && _boundary.c_str()[_parsedLength - 2] != data) { + _multiParseState = PARSE_ERROR; + return; + } else if (_parsedLength - 2 == _boundary.length() && data != '\r') { + _multiParseState = PARSE_ERROR; + return; + } else if (_parsedLength - 3 == _boundary.length()) { + if (data != '\n') { + _multiParseState = PARSE_ERROR; + return; + } + _multiParseState = PARSE_HEADERS; + _itemIsFile = false; + } + } else if (_multiParseState == PARSE_HEADERS) { + if ((char)data != '\r' && (char)data != '\n') { + _temp += (char)data; + } + if ((char)data == '\n') { + if (_temp.length()) { + if (_temp.length() > 12 && _temp.substring(0, 12).equalsIgnoreCase(T_Content_Type)) { + _itemType = _temp.substring(14); + _itemIsFile = true; + } else if (_temp.length() > 19 && _temp.substring(0, 19).equalsIgnoreCase(T_Content_Disposition)) { + _temp = _temp.substring(_temp.indexOf(';') + 2); + while (_temp.indexOf(';') > 0) { + String name = _temp.substring(0, _temp.indexOf('=')); + String nameVal = _temp.substring(_temp.indexOf('=') + 2, _temp.indexOf(';') - 1); + if (name == T_name) { + _itemName = nameVal; + } else if (name == T_filename) { + _itemFilename = nameVal; + _itemIsFile = true; + } + _temp = _temp.substring(_temp.indexOf(';') + 2); + } + String name = _temp.substring(0, _temp.indexOf('=')); + String nameVal = _temp.substring(_temp.indexOf('=') + 2, _temp.length() - 1); + if (name == T_name) { + _itemName = nameVal; + } else if (name == T_filename) { + _itemFilename = nameVal; + _itemIsFile = true; + } + } + _temp = emptyString; + } else { + _multiParseState = WAIT_FOR_RETURN1; + // value starts from here + _itemSize = 0; + _itemStartIndex = _parsedLength; + _itemValue = emptyString; + if (_itemIsFile) { + if (_itemBuffer) { + free(_itemBuffer); + } + _itemBuffer = (uint8_t *)malloc(RESPONSE_STREAM_BUFFER_SIZE); + if (_itemBuffer == NULL) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + _multiParseState = PARSE_ERROR; + abort(); + return; + } + _itemBufferIndex = 0; + } + } + } + } else if (_multiParseState == EXPECT_FEED1) { + if (data != '\n') { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + _parseMultipartPostByte(data, last); + } else { + _multiParseState = EXPECT_DASH1; + } + } else if (_multiParseState == EXPECT_DASH1) { + if (data != '-') { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + _parseMultipartPostByte(data, last); + } else { + _multiParseState = EXPECT_DASH2; + } + } else if (_multiParseState == EXPECT_DASH2) { + if (data != '-') { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + itemWriteByte('-'); + _parseMultipartPostByte(data, last); + } else { + _multiParseState = BOUNDARY_OR_DATA; + _boundaryPosition = 0; + } + } else if (_multiParseState == BOUNDARY_OR_DATA) { + if (_boundaryPosition < _boundary.length() && _boundary.c_str()[_boundaryPosition] != data) { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + itemWriteByte('-'); + itemWriteByte('-'); + uint8_t i; + for (i = 0; i < _boundaryPosition; i++) { + itemWriteByte(_boundary.c_str()[i]); + } + _parseMultipartPostByte(data, last); + } else if (_boundaryPosition == _boundary.length() - 1) { + _multiParseState = DASH3_OR_RETURN2; + if (!_itemIsFile) { + _params.emplace_back(_itemName, _itemValue, true); + } else { + if (_itemSize) { + if (_handler) { + _handler->handleUpload(this, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, true); + } + _itemBufferIndex = 0; + _params.emplace_back(_itemName, _itemFilename, true, true, _itemSize); + } + free(_itemBuffer); + _itemBuffer = NULL; + } + + } else { + _boundaryPosition++; + } + } else if (_multiParseState == DASH3_OR_RETURN2) { + if (data == '-' && (_contentLength - _parsedLength - 4) != 0) { + // os_printf("ERROR: The parser got to the end of the POST but is expecting %u bytes more!\nDrop an issue so we can have more info on the matter!\n", _contentLength - _parsedLength - 4); + _contentLength = _parsedLength + 4; // lets close the request gracefully + } + if (data == '\r') { + _multiParseState = EXPECT_FEED2; + } else if (data == '-' && _contentLength == (_parsedLength + 4)) { + _multiParseState = PARSING_FINISHED; + } else { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + itemWriteByte('-'); + itemWriteByte('-'); + uint8_t i; + for (i = 0; i < _boundary.length(); i++) { + itemWriteByte(_boundary.c_str()[i]); + } + _parseMultipartPostByte(data, last); + } + } else if (_multiParseState == EXPECT_FEED2) { + if (data == '\n') { + _multiParseState = PARSE_HEADERS; + _itemIsFile = false; + } else { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + itemWriteByte('-'); + itemWriteByte('-'); + uint8_t i; + for (i = 0; i < _boundary.length(); i++) { + itemWriteByte(_boundary.c_str()[i]); + } + itemWriteByte('\r'); + _parseMultipartPostByte(data, last); + } + } +} + +void AsyncWebServerRequest::_parseLine() { + if (_parseState == PARSE_REQ_START) { + if (!_temp.length()) { + _parseState = PARSE_REQ_FAIL; + abort(); + } else { + if (_parseReqHead()) { + _parseState = PARSE_REQ_HEADERS; + } else { + _parseState = PARSE_REQ_FAIL; + abort(); + } + } + return; + } + + if (_parseState == PARSE_REQ_HEADERS) { + if (!_temp.length()) { + // end of headers + _server->_rewriteRequest(this); + _server->_attachHandler(this); + if (_expectingContinue) { + String response(T_HTTP_100_CONT); + _client->write(response.c_str(), response.length()); + } + if (_contentLength) { + _parseState = PARSE_REQ_BODY; + } else { + _parseState = PARSE_REQ_END; + _runMiddlewareChain(); + _send(); + } + } else { + _parseReqHeader(); + } + } +} + +void AsyncWebServerRequest::_runMiddlewareChain() { + if (_handler && _handler->mustSkipServerMiddlewares()) { + _handler->_runChain(this, [this]() { + _handler->handleRequest(this); + }); + } else { + _server->_runChain(this, [this]() { + if (_handler) { + _handler->_runChain(this, [this]() { + _handler->handleRequest(this); + }); + } + }); + } +} + +void AsyncWebServerRequest::_send() { + if (!_sent && !_paused) { + // log_d("AsyncWebServerRequest::_send()"); + + // user did not create a response ? + if (!_response) { + send(501, T_text_plain, "Handler did not handle the request"); + } + + // response is not valid ? + if (!_response->_sourceValid()) { + send(500, T_text_plain, "Invalid data in handler"); + } + + // here, we either have a response give nfrom user or one of the two above + _client->setRxTimeout(0); + _response->_respond(this); + _sent = true; + } +} + +AsyncWebServerRequestPtr AsyncWebServerRequest::pause() { + if (_paused) { + return _this; + } + client()->setRxTimeout(0); + // this shared ptr will hold the request pointer until it gets destroyed following a disconnect. + // this is just used as a holder providing weak observers, so the deleter is a no-op. + _this = std::shared_ptr(this, doNotDelete); + _paused = true; + return _this; +} + +void AsyncWebServerRequest::abort() { + if (!_sent) { + _sent = true; + _paused = false; + _this.reset(); + // log_e("AsyncWebServerRequest::abort"); + _client->abort(); + } +} + +size_t AsyncWebServerRequest::headers() const { + return _headers.size(); +} + +bool AsyncWebServerRequest::hasHeader(const char *name) const { + for (const auto &h : _headers) { + if (h.name().equalsIgnoreCase(name)) { + return true; + } + } + return false; +} + +#ifdef ESP8266 +bool AsyncWebServerRequest::hasHeader(const __FlashStringHelper *data) const { + return hasHeader(String(data)); +} +#endif + +const AsyncWebHeader *AsyncWebServerRequest::getHeader(const char *name) const { + auto iter = std::find_if(std::begin(_headers), std::end(_headers), [&name](const AsyncWebHeader &header) { + return header.name().equalsIgnoreCase(name); + }); + return (iter == std::end(_headers)) ? nullptr : &(*iter); +} + +#ifdef ESP8266 +const AsyncWebHeader *AsyncWebServerRequest::getHeader(const __FlashStringHelper *data) const { + PGM_P p = reinterpret_cast(data); + size_t n = strlen_P(p); + char *name = (char *)malloc(n + 1); + if (name) { + strcpy_P(name, p); + const AsyncWebHeader *result = getHeader(String(name)); + free(name); + return result; + } else { + return nullptr; + } +} +#endif + +const AsyncWebHeader *AsyncWebServerRequest::getHeader(size_t num) const { + if (num >= _headers.size()) { + return nullptr; + } + return &(*std::next(_headers.cbegin(), num)); +} + +size_t AsyncWebServerRequest::getHeaderNames(std::vector &names) const { + const size_t size = names.size(); + for (const auto &h : _headers) { + names.push_back(h.name().c_str()); + } + return names.size() - size; +} + +bool AsyncWebServerRequest::removeHeader(const char *name) { + const size_t size = _headers.size(); + _headers.remove_if([name](const AsyncWebHeader &header) { + return header.name().equalsIgnoreCase(name); + }); + return size != _headers.size(); +} + +size_t AsyncWebServerRequest::params() const { + return _params.size(); +} + +bool AsyncWebServerRequest::hasParam(const char *name, bool post, bool file) const { + for (const auto &p : _params) { + if (p.name().equals(name) && p.isPost() == post && p.isFile() == file) { + return true; + } + } + return false; +} + +const AsyncWebParameter *AsyncWebServerRequest::getParam(const char *name, bool post, bool file) const { + for (const auto &p : _params) { + if (p.name() == name && p.isPost() == post && p.isFile() == file) { + return &p; + } + } + return nullptr; +} + +#ifdef ESP8266 +const AsyncWebParameter *AsyncWebServerRequest::getParam(const __FlashStringHelper *data, bool post, bool file) const { + return getParam(String(data), post, file); +} +#endif + +const AsyncWebParameter *AsyncWebServerRequest::getParam(size_t num) const { + if (num >= _params.size()) { + return nullptr; + } + return &(*std::next(_params.cbegin(), num)); +} + +const String &AsyncWebServerRequest::getAttribute(const char *name, const String &defaultValue) const { + auto it = _attributes.find(name); + return it != _attributes.end() ? it->second : defaultValue; +} +bool AsyncWebServerRequest::getAttribute(const char *name, bool defaultValue) const { + auto it = _attributes.find(name); + return it != _attributes.end() ? it->second == "1" : defaultValue; +} +long AsyncWebServerRequest::getAttribute(const char *name, long defaultValue) const { + auto it = _attributes.find(name); + return it != _attributes.end() ? it->second.toInt() : defaultValue; +} +float AsyncWebServerRequest::getAttribute(const char *name, float defaultValue) const { + auto it = _attributes.find(name); + return it != _attributes.end() ? it->second.toFloat() : defaultValue; +} +double AsyncWebServerRequest::getAttribute(const char *name, double defaultValue) const { + auto it = _attributes.find(name); + return it != _attributes.end() ? it->second.toDouble() : defaultValue; +} + +AsyncWebServerResponse *AsyncWebServerRequest::beginResponse(int code, const char *contentType, const char *content, AwsTemplateProcessor callback) { + if (callback) { + return new AsyncProgmemResponse(code, contentType, (const uint8_t *)content, strlen(content), callback); + } + return new AsyncBasicResponse(code, contentType, content); +} + +AsyncWebServerResponse * + AsyncWebServerRequest::beginResponse(int code, const char *contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback) { + return new AsyncProgmemResponse(code, contentType, content, len, callback); +} + +AsyncWebServerResponse * + AsyncWebServerRequest::beginResponse(FS &fs, const String &path, const char *contentType, bool download, AwsTemplateProcessor callback) { + if (fs.exists(path) || (!download && fs.exists(path + T__gz))) { + return new AsyncFileResponse(fs, path, contentType, download, callback); + } + return NULL; +} + +AsyncWebServerResponse * + AsyncWebServerRequest::beginResponse(File content, const String &path, const char *contentType, bool download, AwsTemplateProcessor callback) { + if (content == true) { + return new AsyncFileResponse(content, path, contentType, download, callback); + } + return NULL; +} + +AsyncWebServerResponse *AsyncWebServerRequest::beginResponse(Stream &stream, const char *contentType, size_t len, AwsTemplateProcessor callback) { + return new AsyncStreamResponse(stream, contentType, len, callback); +} + +AsyncWebServerResponse * + AsyncWebServerRequest::beginResponse(const char *contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) { + return new AsyncCallbackResponse(contentType, len, callback, templateCallback); +} + +AsyncWebServerResponse * + AsyncWebServerRequest::beginChunkedResponse(const char *contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) { + if (_version) { + return new AsyncChunkedResponse(contentType, callback, templateCallback); + } + return new AsyncCallbackResponse(contentType, 0, callback, templateCallback); +} + +AsyncResponseStream *AsyncWebServerRequest::beginResponseStream(const char *contentType, size_t bufferSize) { + return new AsyncResponseStream(contentType, bufferSize); +} + +AsyncWebServerResponse *AsyncWebServerRequest::beginResponse_P(int code, const String &contentType, PGM_P content, AwsTemplateProcessor callback) { + return new AsyncProgmemResponse(code, contentType, (const uint8_t *)content, strlen_P(content), callback); +} + +void AsyncWebServerRequest::send(AsyncWebServerResponse *response) { + // request is already sent on the wire ? + if (_sent) { + return; + } + + // if we already had a response, delete it and replace it with the new one + if (_response) { + delete _response; + } + _response = response; + + // if request was paused, we need to send the response now + if (_paused) { + _paused = false; + _send(); + } +} + +void AsyncWebServerRequest::redirect(const char *url, int code) { + AsyncWebServerResponse *response = beginResponse(code); + response->addHeader(T_LOCATION, url); + send(response); +} + +bool AsyncWebServerRequest::authenticate(const char *username, const char *password, const char *realm, bool passwordIsHash) const { + if (_authorization.length()) { + if (_authMethod == AsyncAuthType::AUTH_DIGEST) { + return checkDigestAuthentication(_authorization.c_str(), methodToString(), username, password, realm, passwordIsHash, NULL, NULL, NULL); + } else if (!passwordIsHash) { + return checkBasicAuthentication(_authorization.c_str(), username, password); + } else { + return _authorization.equals(password); + } + } + return false; +} + +bool AsyncWebServerRequest::authenticate(const char *hash) const { + if (!_authorization.length() || hash == NULL) { + return false; + } + + if (_authMethod == AsyncAuthType::AUTH_DIGEST) { + String hStr = String(hash); + int separator = hStr.indexOf(':'); + if (separator <= 0) { + return false; + } + String username = hStr.substring(0, separator); + hStr = hStr.substring(separator + 1); + separator = hStr.indexOf(':'); + if (separator <= 0) { + return false; + } + String realm = hStr.substring(0, separator); + hStr = hStr.substring(separator + 1); + return checkDigestAuthentication(_authorization.c_str(), methodToString(), username.c_str(), hStr.c_str(), realm.c_str(), true, NULL, NULL, NULL); + } + + // Basic Auth, Bearer Auth, or other + return (_authorization.equals(hash)); +} + +void AsyncWebServerRequest::requestAuthentication(AsyncAuthType method, const char *realm, const char *_authFailMsg) { + if (!realm) { + realm = T_LOGIN_REQ; + } + + AsyncWebServerResponse *r = _authFailMsg ? beginResponse(401, T_text_html, _authFailMsg) : beginResponse(401); + + switch (method) { + case AsyncAuthType::AUTH_BASIC: + { + String header; + if (header.reserve(strlen(T_BASIC_REALM) + strlen(realm) + 1)) { + header.concat(T_BASIC_REALM); + header.concat(realm); + header.concat('"'); + r->addHeader(T_WWW_AUTH, header.c_str()); + } else { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + abort(); + } + + break; + } + case AsyncAuthType::AUTH_DIGEST: + { + size_t len = strlen(T_DIGEST_) + strlen(T_realm__) + strlen(T_auth_nonce) + 32 + strlen(T__opaque) + 32 + 1; + String header; + if (header.reserve(len + strlen(realm))) { + const String nonce = genRandomMD5(); + const String opaque = genRandomMD5(); + if (nonce.length() && opaque.length()) { + header.concat(T_DIGEST_); + header.concat(T_realm__); + header.concat(realm); + header.concat(T_auth_nonce); + header.concat(nonce); + header.concat(T__opaque); + header.concat(opaque); + header.concat((char)0x22); // '"' + r->addHeader(T_WWW_AUTH, header.c_str()); + } else { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + abort(); + } + } + break; + } + default: break; + } + + send(r); +} + +bool AsyncWebServerRequest::hasArg(const char *name) const { + for (const auto &arg : _params) { + if (arg.name() == name) { + return true; + } + } + return false; +} + +#ifdef ESP8266 +bool AsyncWebServerRequest::hasArg(const __FlashStringHelper *data) const { + return hasArg(String(data).c_str()); +} +#endif + +const String &AsyncWebServerRequest::arg(const char *name) const { + for (const auto &arg : _params) { + if (arg.name() == name) { + return arg.value(); + } + } + return emptyString; +} + +#ifdef ESP8266 +const String &AsyncWebServerRequest::arg(const __FlashStringHelper *data) const { + return arg(String(data).c_str()); +} +#endif + +const String &AsyncWebServerRequest::arg(size_t i) const { + return getParam(i)->value(); +} + +const String &AsyncWebServerRequest::argName(size_t i) const { + return getParam(i)->name(); +} + +const String &AsyncWebServerRequest::pathArg(size_t i) const { + if (i >= _pathParams.size()) { + return emptyString; + } + auto it = _pathParams.begin(); + std::advance(it, i); + return *it; +} + +const String &AsyncWebServerRequest::header(const char *name) const { + const AsyncWebHeader *h = getHeader(name); + return h ? h->value() : emptyString; +} + +#ifdef ESP8266 +const String &AsyncWebServerRequest::header(const __FlashStringHelper *data) const { + return header(String(data).c_str()); +}; +#endif + +const String &AsyncWebServerRequest::header(size_t i) const { + const AsyncWebHeader *h = getHeader(i); + return h ? h->value() : emptyString; +} + +const String &AsyncWebServerRequest::headerName(size_t i) const { + const AsyncWebHeader *h = getHeader(i); + return h ? h->name() : emptyString; +} + +String AsyncWebServerRequest::urlDecode(const String &text) const { + char temp[] = "0x00"; + unsigned int len = text.length(); + unsigned int i = 0; + String decoded; + // Allocate the string internal buffer - never longer from source text + if (!decoded.reserve(len)) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + return emptyString; + } + while (i < len) { + char decodedChar; + char encodedChar = text.charAt(i++); + if ((encodedChar == '%') && (i + 1 < len)) { + temp[2] = text.charAt(i++); + temp[3] = text.charAt(i++); + decodedChar = strtol(temp, NULL, 16); + } else if (encodedChar == '+') { + decodedChar = ' '; + } else { + decodedChar = encodedChar; // normal ascii char + } + decoded.concat(decodedChar); + } + return decoded; +} + +const char *AsyncWebServerRequest::methodToString() const { + if (_method == HTTP_ANY) { + return T_ANY; + } + if (_method & HTTP_GET) { + return T_GET; + } + if (_method & HTTP_POST) { + return T_POST; + } + if (_method & HTTP_DELETE) { + return T_DELETE; + } + if (_method & HTTP_PUT) { + return T_PUT; + } + if (_method & HTTP_PATCH) { + return T_PATCH; + } + if (_method & HTTP_HEAD) { + return T_HEAD; + } + if (_method & HTTP_OPTIONS) { + return T_OPTIONS; + } + return T_UNKNOWN; +} + +const char *AsyncWebServerRequest::requestedConnTypeToString() const { + switch (_reqconntype) { + case RCT_NOT_USED: return T_RCT_NOT_USED; + case RCT_DEFAULT: return T_RCT_DEFAULT; + case RCT_HTTP: return T_RCT_HTTP; + case RCT_WS: return T_RCT_WS; + case RCT_EVENT: return T_RCT_EVENT; + default: return T_ERROR; + } +} + +bool AsyncWebServerRequest::isExpectedRequestedConnType(RequestedConnectionType erct1, RequestedConnectionType erct2, RequestedConnectionType erct3) const { + return ((erct1 != RCT_NOT_USED) && (erct1 == _reqconntype)) || ((erct2 != RCT_NOT_USED) && (erct2 == _reqconntype)) + || ((erct3 != RCT_NOT_USED) && (erct3 == _reqconntype)); +} diff --git a/watering/lib/ESPAsyncWebServer/src/WebResponseImpl.h b/watering/lib/ESPAsyncWebServer/src/WebResponseImpl.h new file mode 100644 index 0000000..6408625 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/WebResponseImpl.h @@ -0,0 +1,180 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#ifndef ASYNCWEBSERVERRESPONSEIMPL_H_ +#define ASYNCWEBSERVERRESPONSEIMPL_H_ + +#ifdef Arduino_h +// arduino is not compatible with std::vector +#undef min +#undef max +#endif +#include "literals.h" +#include +#include +#include + +// It is possible to restore these defines, but one can use _min and _max instead. Or std::min, std::max. + +class AsyncBasicResponse : public AsyncWebServerResponse { +private: + String _content; + +public: + explicit AsyncBasicResponse(int code, const char *contentType = asyncsrv::empty, const char *content = asyncsrv::empty); + AsyncBasicResponse(int code, const String &contentType, const String &content = emptyString) + : AsyncBasicResponse(code, contentType.c_str(), content.c_str()) {} + void _respond(AsyncWebServerRequest *request) override final; + size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time) override final; + bool _sourceValid() const override final { + return true; + } +}; + +class AsyncAbstractResponse : public AsyncWebServerResponse { +private: +#if ASYNCWEBSERVER_USE_CHUNK_INFLIGHT + // amount of response data in-flight, i.e. sent, but not acked yet + size_t _in_flight{0}; + // in-flight queue credits + size_t _in_flight_credit{2}; +#endif + String _head; + // Data is inserted into cache at begin(). + // This is inefficient with vector, but if we use some other container, + // we won't be able to access it as contiguous array of bytes when reading from it, + // so by gaining performance in one place, we'll lose it in another. + std::vector _cache; + size_t _readDataFromCacheOrContent(uint8_t *data, const size_t len); + size_t _fillBufferAndProcessTemplates(uint8_t *buf, size_t maxLen); + +protected: + AwsTemplateProcessor _callback; + +public: + AsyncAbstractResponse(AwsTemplateProcessor callback = nullptr); + virtual ~AsyncAbstractResponse() {} + void _respond(AsyncWebServerRequest *request) override final; + size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time) override final; + virtual bool _sourceValid() const { + return false; + } + virtual size_t _fillBuffer(uint8_t *buf __attribute__((unused)), size_t maxLen __attribute__((unused))) { + return 0; + } +}; + +#ifndef TEMPLATE_PLACEHOLDER +#define TEMPLATE_PLACEHOLDER '%' +#endif + +#define TEMPLATE_PARAM_NAME_LENGTH 32 +class AsyncFileResponse : public AsyncAbstractResponse { + using File = fs::File; + using FS = fs::FS; + +private: + File _content; + String _path; + void _setContentTypeFromPath(const String &path); + +public: + AsyncFileResponse(FS &fs, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr); + AsyncFileResponse(FS &fs, const String &path, const String &contentType, bool download = false, AwsTemplateProcessor callback = nullptr) + : AsyncFileResponse(fs, path, contentType.c_str(), download, callback) {} + AsyncFileResponse( + File content, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr + ); + AsyncFileResponse(File content, const String &path, const String &contentType, bool download = false, AwsTemplateProcessor callback = nullptr) + : AsyncFileResponse(content, path, contentType.c_str(), download, callback) {} + ~AsyncFileResponse() { + _content.close(); + } + bool _sourceValid() const override final { + return !!(_content); + } + size_t _fillBuffer(uint8_t *buf, size_t maxLen) override final; +}; + +class AsyncStreamResponse : public AsyncAbstractResponse { +private: + Stream *_content; + +public: + AsyncStreamResponse(Stream &stream, const char *contentType, size_t len, AwsTemplateProcessor callback = nullptr); + AsyncStreamResponse(Stream &stream, const String &contentType, size_t len, AwsTemplateProcessor callback = nullptr) + : AsyncStreamResponse(stream, contentType.c_str(), len, callback) {} + bool _sourceValid() const override final { + return !!(_content); + } + size_t _fillBuffer(uint8_t *buf, size_t maxLen) override final; +}; + +class AsyncCallbackResponse : public AsyncAbstractResponse { +private: + AwsResponseFiller _content; + size_t _filledLength; + +public: + AsyncCallbackResponse(const char *contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); + AsyncCallbackResponse(const String &contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) + : AsyncCallbackResponse(contentType.c_str(), len, callback, templateCallback) {} + bool _sourceValid() const override final { + return !!(_content); + } + size_t _fillBuffer(uint8_t *buf, size_t maxLen) override final; +}; + +class AsyncChunkedResponse : public AsyncAbstractResponse { +private: + AwsResponseFiller _content; + size_t _filledLength; + +public: + AsyncChunkedResponse(const char *contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); + AsyncChunkedResponse(const String &contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) + : AsyncChunkedResponse(contentType.c_str(), callback, templateCallback) {} + bool _sourceValid() const override final { + return !!(_content); + } + size_t _fillBuffer(uint8_t *buf, size_t maxLen) override final; +}; + +class AsyncProgmemResponse : public AsyncAbstractResponse { +private: + const uint8_t *_content; + size_t _readLength; + +public: + AsyncProgmemResponse(int code, const char *contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr); + AsyncProgmemResponse(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) + : AsyncProgmemResponse(code, contentType.c_str(), content, len, callback) {} + bool _sourceValid() const override final { + return true; + } + size_t _fillBuffer(uint8_t *buf, size_t maxLen) override final; +}; + +class AsyncResponseStream : public AsyncAbstractResponse, public Print { +private: + std::unique_ptr _content; + +public: + AsyncResponseStream(const char *contentType, size_t bufferSize); + AsyncResponseStream(const String &contentType, size_t bufferSize) : AsyncResponseStream(contentType.c_str(), bufferSize) {} + bool _sourceValid() const override final { + return (_state < RESPONSE_END); + } + size_t _fillBuffer(uint8_t *buf, size_t maxLen) override final; + size_t write(const uint8_t *data, size_t len); + size_t write(uint8_t data); + /** + * @brief Returns the number of bytes available in the stream. + */ + size_t available() const { + return _content->available(); + } + using Print::write; +}; + +#endif /* ASYNCWEBSERVERRESPONSEIMPL_H_ */ diff --git a/watering/lib/ESPAsyncWebServer/src/WebResponses.cpp b/watering/lib/ESPAsyncWebServer/src/WebResponses.cpp new file mode 100644 index 0000000..3de8f32 --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/WebResponses.cpp @@ -0,0 +1,859 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "ESPAsyncWebServer.h" +#include "WebResponseImpl.h" + +using namespace asyncsrv; + +// Since ESP8266 does not link memchr by default, here's its implementation. +void *memchr(void *ptr, int ch, size_t count) { + unsigned char *p = static_cast(ptr); + while (count--) { + if (*p++ == static_cast(ch)) { + return --p; + } + } + return nullptr; +} + +/* + * Abstract Response + * + */ + +const char *AsyncWebServerResponse::responseCodeToString(int code) { + switch (code) { + case 100: return T_HTTP_CODE_100; + case 101: return T_HTTP_CODE_101; + case 200: return T_HTTP_CODE_200; + case 201: return T_HTTP_CODE_201; + case 202: return T_HTTP_CODE_202; + case 203: return T_HTTP_CODE_203; + case 204: return T_HTTP_CODE_204; + case 205: return T_HTTP_CODE_205; + case 206: return T_HTTP_CODE_206; + case 300: return T_HTTP_CODE_300; + case 301: return T_HTTP_CODE_301; + case 302: return T_HTTP_CODE_302; + case 303: return T_HTTP_CODE_303; + case 304: return T_HTTP_CODE_304; + case 305: return T_HTTP_CODE_305; + case 307: return T_HTTP_CODE_307; + case 400: return T_HTTP_CODE_400; + case 401: return T_HTTP_CODE_401; + case 402: return T_HTTP_CODE_402; + case 403: return T_HTTP_CODE_403; + case 404: return T_HTTP_CODE_404; + case 405: return T_HTTP_CODE_405; + case 406: return T_HTTP_CODE_406; + case 407: return T_HTTP_CODE_407; + case 408: return T_HTTP_CODE_408; + case 409: return T_HTTP_CODE_409; + case 410: return T_HTTP_CODE_410; + case 411: return T_HTTP_CODE_411; + case 412: return T_HTTP_CODE_412; + case 413: return T_HTTP_CODE_413; + case 414: return T_HTTP_CODE_414; + case 415: return T_HTTP_CODE_415; + case 416: return T_HTTP_CODE_416; + case 417: return T_HTTP_CODE_417; + case 429: return T_HTTP_CODE_429; + case 500: return T_HTTP_CODE_500; + case 501: return T_HTTP_CODE_501; + case 502: return T_HTTP_CODE_502; + case 503: return T_HTTP_CODE_503; + case 504: return T_HTTP_CODE_504; + case 505: return T_HTTP_CODE_505; + default: return T_HTTP_CODE_ANY; + } +} + +AsyncWebServerResponse::AsyncWebServerResponse() + : _code(0), _contentType(), _contentLength(0), _sendContentLength(true), _chunked(false), _headLength(0), _sentLength(0), _ackedLength(0), _writtenLength(0), + _state(RESPONSE_SETUP) { + for (const auto &header : DefaultHeaders::Instance()) { + _headers.emplace_back(header); + } +} + +void AsyncWebServerResponse::setCode(int code) { + if (_state == RESPONSE_SETUP) { + _code = code; + } +} + +void AsyncWebServerResponse::setContentLength(size_t len) { + if (_state == RESPONSE_SETUP && addHeader(T_Content_Length, len, true)) { + _contentLength = len; + } +} + +void AsyncWebServerResponse::setContentType(const char *type) { + if (_state == RESPONSE_SETUP && addHeader(T_Content_Type, type, true)) { + _contentType = type; + } +} + +bool AsyncWebServerResponse::removeHeader(const char *name) { + bool h_erased = false; + for (auto i = _headers.begin(); i != _headers.end();) { + if (i->name().equalsIgnoreCase(name)) { + _headers.erase(i); + h_erased = true; + } else { + ++i; + } + } + return h_erased; +} + +bool AsyncWebServerResponse::removeHeader(const char *name, const char *value) { + for (auto i = _headers.begin(); i != _headers.end(); ++i) { + if (i->name().equalsIgnoreCase(name) && i->value().equalsIgnoreCase(value)) { + _headers.erase(i); + return true; + } + } + return false; +} + +const AsyncWebHeader *AsyncWebServerResponse::getHeader(const char *name) const { + auto iter = std::find_if(std::begin(_headers), std::end(_headers), [&name](const AsyncWebHeader &header) { + return header.name().equalsIgnoreCase(name); + }); + return (iter == std::end(_headers)) ? nullptr : &(*iter); +} + +bool AsyncWebServerResponse::headerMustBePresentOnce(const String &name) { + for (uint8_t i = 0; i < T_only_once_headers_len; i++) { + if (name.equalsIgnoreCase(T_only_once_headers[i])) { + return true; + } + } + return false; +} + +bool AsyncWebServerResponse::addHeader(const char *name, const char *value, bool replaceExisting) { + for (auto i = _headers.begin(); i != _headers.end(); ++i) { + if (i->name().equalsIgnoreCase(name)) { + // header already set + if (replaceExisting) { + // remove, break and add the new one + _headers.erase(i); + break; + } else if (headerMustBePresentOnce(i->name())) { // we can have only one header with that name + // do not update + return false; + } else { + break; // accept multiple headers with the same name + } + } + } + // header was not found found, or existing one was removed + _headers.emplace_back(name, value); + return true; +} + +void AsyncWebServerResponse::_assembleHead(String &buffer, uint8_t version) { + if (version) { + addHeader(T_Accept_Ranges, T_none, false); + if (_chunked) { + addHeader(T_Transfer_Encoding, T_chunked, false); + } + } + + if (_sendContentLength) { + addHeader(T_Content_Length, String(_contentLength), false); + } + + if (_contentType.length()) { + addHeader(T_Content_Type, _contentType.c_str(), false); + } + + // precompute buffer size to avoid reallocations by String class + size_t len = 0; + len += 50; // HTTP/1.1 200 \r\n + for (const auto &header : _headers) { + len += header.name().length() + header.value().length() + 4; + } + + // prepare buffer + buffer.reserve(len); + + // HTTP header +#ifdef ESP8266 + buffer.concat(PSTR("HTTP/1.")); +#else + buffer.concat("HTTP/1."); +#endif + buffer.concat(version); + buffer.concat(' '); + buffer.concat(_code); + buffer.concat(' '); + buffer.concat(responseCodeToString(_code)); + buffer.concat(T_rn); + + // Add headers + for (const auto &header : _headers) { + buffer.concat(header.name()); +#ifdef ESP8266 + buffer.concat(PSTR(": ")); +#else + buffer.concat(": "); +#endif + buffer.concat(header.value()); + buffer.concat(T_rn); + } + + buffer.concat(T_rn); + _headLength = buffer.length(); +} + +bool AsyncWebServerResponse::_started() const { + return _state > RESPONSE_SETUP; +} +bool AsyncWebServerResponse::_finished() const { + return _state > RESPONSE_WAIT_ACK; +} +bool AsyncWebServerResponse::_failed() const { + return _state == RESPONSE_FAILED; +} +bool AsyncWebServerResponse::_sourceValid() const { + return false; +} +void AsyncWebServerResponse::_respond(AsyncWebServerRequest *request) { + _state = RESPONSE_END; + request->client()->close(); +} +size_t AsyncWebServerResponse::_ack(AsyncWebServerRequest *request, size_t len, uint32_t time) { + (void)request; + (void)len; + (void)time; + return 0; +} + +/* + * String/Code Response + * */ +AsyncBasicResponse::AsyncBasicResponse(int code, const char *contentType, const char *content) { + _code = code; + _content = content; + _contentType = contentType; + if (_content.length()) { + _contentLength = _content.length(); + if (!_contentType.length()) { + _contentType = T_text_plain; + } + } + addHeader(T_Connection, T_close, false); +} + +void AsyncBasicResponse::_respond(AsyncWebServerRequest *request) { + _state = RESPONSE_HEADERS; + String out; + _assembleHead(out, request->version()); + size_t outLen = out.length(); + size_t space = request->client()->space(); + if (!_contentLength && space >= outLen) { + _writtenLength += request->client()->write(out.c_str(), outLen); + _state = RESPONSE_WAIT_ACK; + } else if (_contentLength && space >= outLen + _contentLength) { + out += _content; + outLen += _contentLength; + _writtenLength += request->client()->write(out.c_str(), outLen); + _state = RESPONSE_WAIT_ACK; + } else if (space && space < outLen) { + String partial = out.substring(0, space); + _content = out.substring(space) + _content; + _contentLength += outLen - space; + _writtenLength += request->client()->write(partial.c_str(), partial.length()); + _state = RESPONSE_CONTENT; + } else if (space > outLen && space < (outLen + _contentLength)) { + size_t shift = space - outLen; + outLen += shift; + _sentLength += shift; + out += _content.substring(0, shift); + _content = _content.substring(shift); + _writtenLength += request->client()->write(out.c_str(), outLen); + _state = RESPONSE_CONTENT; + } else { + _content = out + _content; + _contentLength += outLen; + _state = RESPONSE_CONTENT; + } +} + +size_t AsyncBasicResponse::_ack(AsyncWebServerRequest *request, size_t len, uint32_t time) { + (void)time; + _ackedLength += len; + if (_state == RESPONSE_CONTENT) { + size_t available = _contentLength - _sentLength; + size_t space = request->client()->space(); + // we can fit in this packet + if (space > available) { + _writtenLength += request->client()->write(_content.c_str(), available); + _content = emptyString; + _state = RESPONSE_WAIT_ACK; + return available; + } + // send some data, the rest on ack + String out = _content.substring(0, space); + _content = _content.substring(space); + _sentLength += space; + _writtenLength += request->client()->write(out.c_str(), space); + return space; + } else if (_state == RESPONSE_WAIT_ACK) { + if (_ackedLength >= _writtenLength) { + _state = RESPONSE_END; + } + } + return 0; +} + +/* + * Abstract Response + * */ + +AsyncAbstractResponse::AsyncAbstractResponse(AwsTemplateProcessor callback) : _callback(callback) { + // In case of template processing, we're unable to determine real response size + if (callback) { + _contentLength = 0; + _sendContentLength = false; + _chunked = true; + } +} + +void AsyncAbstractResponse::_respond(AsyncWebServerRequest *request) { + addHeader(T_Connection, T_close, false); + _assembleHead(_head, request->version()); + _state = RESPONSE_HEADERS; + _ack(request, 0, 0); +} + +size_t AsyncAbstractResponse::_ack(AsyncWebServerRequest *request, size_t len, uint32_t time) { + (void)time; + if (!_sourceValid()) { + _state = RESPONSE_FAILED; + request->client()->close(); + return 0; + } + +#if ASYNCWEBSERVER_USE_CHUNK_INFLIGHT + // return a credit for each chunk of acked data (polls does not give any credits) + if (len) { + ++_in_flight_credit; + } + + // for chunked responses ignore acks if there are no _in_flight_credits left + if (_chunked && !_in_flight_credit) { +#ifdef ESP32 + log_d("(chunk) out of in-flight credits"); +#endif + return 0; + } + + _in_flight -= (_in_flight > len) ? len : _in_flight; + // get the size of available sock space +#endif + + _ackedLength += len; + size_t space = request->client()->space(); + + size_t headLen = _head.length(); + if (_state == RESPONSE_HEADERS) { + if (space >= headLen) { + _state = RESPONSE_CONTENT; + space -= headLen; + } else { + String out = _head.substring(0, space); + _head = _head.substring(space); + _writtenLength += request->client()->write(out.c_str(), out.length()); +#if ASYNCWEBSERVER_USE_CHUNK_INFLIGHT + _in_flight += out.length(); + --_in_flight_credit; // take a credit +#endif + return out.length(); + } + } + + if (_state == RESPONSE_CONTENT) { +#if ASYNCWEBSERVER_USE_CHUNK_INFLIGHT + // for response data we need to control the queue and in-flight fragmentation. Sending small chunks could give low latency, + // but flood asynctcp's queue and fragment socket buffer space for large responses. + // Let's ignore polled acks and acks in case when we have more in-flight data then the available socket buff space. + // That way we could balance on having half the buffer in-flight while another half is filling up, while minimizing events in asynctcp q + if (_in_flight > space) { + // log_d("defer user call %u/%u", _in_flight, space); + // take the credit back since we are ignoring this ack and rely on other inflight data + if (len) { + --_in_flight_credit; + } + return 0; + } +#endif + + size_t outLen; + if (_chunked) { + if (space <= 8) { + return 0; + } + + outLen = space; + } else if (!_sendContentLength) { + outLen = space; + } else { + outLen = ((_contentLength - _sentLength) > space) ? space : (_contentLength - _sentLength); + } + + uint8_t *buf = (uint8_t *)malloc(outLen + headLen); + if (!buf) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + request->abort(); + return 0; + } + + if (headLen) { + memcpy(buf, _head.c_str(), _head.length()); + } + + size_t readLen = 0; + + if (_chunked) { + // HTTP 1.1 allows leading zeros in chunk length. Or spaces may be added. + // See RFC2616 sections 2, 3.6.1. + readLen = _fillBufferAndProcessTemplates(buf + headLen + 6, outLen - 8); + if (readLen == RESPONSE_TRY_AGAIN) { + free(buf); + return 0; + } + outLen = sprintf((char *)buf + headLen, "%04x", readLen) + headLen; + buf[outLen++] = '\r'; + buf[outLen++] = '\n'; + outLen += readLen; + buf[outLen++] = '\r'; + buf[outLen++] = '\n'; + } else { + readLen = _fillBufferAndProcessTemplates(buf + headLen, outLen); + if (readLen == RESPONSE_TRY_AGAIN) { + free(buf); + return 0; + } + outLen = readLen + headLen; + } + + if (headLen) { + _head = emptyString; + } + + if (outLen) { + _writtenLength += request->client()->write((const char *)buf, outLen); +#if ASYNCWEBSERVER_USE_CHUNK_INFLIGHT + _in_flight += outLen; + --_in_flight_credit; // take a credit +#endif + } + + if (_chunked) { + _sentLength += readLen; + } else { + _sentLength += outLen - headLen; + } + + free(buf); + + if ((_chunked && readLen == 0) || (!_sendContentLength && outLen == 0) || (!_chunked && _sentLength == _contentLength)) { + _state = RESPONSE_WAIT_ACK; + } + return outLen; + + } else if (_state == RESPONSE_WAIT_ACK) { + if (!_sendContentLength || _ackedLength >= _writtenLength) { + _state = RESPONSE_END; + if (!_chunked && !_sendContentLength) { + request->client()->close(true); + } + } + } + return 0; +} + +size_t AsyncAbstractResponse::_readDataFromCacheOrContent(uint8_t *data, const size_t len) { + // If we have something in cache, copy it to buffer + const size_t readFromCache = std::min(len, _cache.size()); + if (readFromCache) { + memcpy(data, _cache.data(), readFromCache); + _cache.erase(_cache.begin(), _cache.begin() + readFromCache); + } + // If we need to read more... + const size_t needFromFile = len - readFromCache; + const size_t readFromContent = _fillBuffer(data + readFromCache, needFromFile); + return readFromCache + readFromContent; +} + +size_t AsyncAbstractResponse::_fillBufferAndProcessTemplates(uint8_t *data, size_t len) { + if (!_callback) { + return _fillBuffer(data, len); + } + + const size_t originalLen = len; + len = _readDataFromCacheOrContent(data, len); + // Now we've read 'len' bytes, either from cache or from file + // Search for template placeholders + uint8_t *pTemplateStart = data; + while ((pTemplateStart < &data[len]) && (pTemplateStart = (uint8_t *)memchr(pTemplateStart, TEMPLATE_PLACEHOLDER, &data[len - 1] - pTemplateStart + 1)) + ) { // data[0] ... data[len - 1] + uint8_t *pTemplateEnd = + (pTemplateStart < &data[len - 1]) ? (uint8_t *)memchr(pTemplateStart + 1, TEMPLATE_PLACEHOLDER, &data[len - 1] - pTemplateStart) : nullptr; + // temporary buffer to hold parameter name + uint8_t buf[TEMPLATE_PARAM_NAME_LENGTH + 1]; + String paramName; + // If closing placeholder is found: + if (pTemplateEnd) { + // prepare argument to callback + const size_t paramNameLength = std::min((size_t)sizeof(buf) - 1, (size_t)(pTemplateEnd - pTemplateStart - 1)); + if (paramNameLength) { + memcpy(buf, pTemplateStart + 1, paramNameLength); + buf[paramNameLength] = 0; + paramName = String(reinterpret_cast(buf)); + } else { // double percent sign encountered, this is single percent sign escaped. + // remove the 2nd percent sign + memmove(pTemplateEnd, pTemplateEnd + 1, &data[len] - pTemplateEnd - 1); + len += _readDataFromCacheOrContent(&data[len - 1], 1) - 1; + ++pTemplateStart; + } + } else if (&data[len - 1] - pTemplateStart + 1 + < TEMPLATE_PARAM_NAME_LENGTH + 2) { // closing placeholder not found, check if it's in the remaining file data + memcpy(buf, pTemplateStart + 1, &data[len - 1] - pTemplateStart); + const size_t readFromCacheOrContent = + _readDataFromCacheOrContent(buf + (&data[len - 1] - pTemplateStart), TEMPLATE_PARAM_NAME_LENGTH + 2 - (&data[len - 1] - pTemplateStart + 1)); + if (readFromCacheOrContent) { + pTemplateEnd = (uint8_t *)memchr(buf + (&data[len - 1] - pTemplateStart), TEMPLATE_PLACEHOLDER, readFromCacheOrContent); + if (pTemplateEnd) { + // prepare argument to callback + *pTemplateEnd = 0; + paramName = String(reinterpret_cast(buf)); + // Copy remaining read-ahead data into cache + _cache.insert(_cache.begin(), pTemplateEnd + 1, buf + (&data[len - 1] - pTemplateStart) + readFromCacheOrContent); + pTemplateEnd = &data[len - 1]; + } else // closing placeholder not found in file data, store found percent symbol as is and advance to the next position + { + // but first, store read file data in cache + _cache.insert(_cache.begin(), buf + (&data[len - 1] - pTemplateStart), buf + (&data[len - 1] - pTemplateStart) + readFromCacheOrContent); + ++pTemplateStart; + } + } else { // closing placeholder not found in content data, store found percent symbol as is and advance to the next position + ++pTemplateStart; + } + } else { // closing placeholder not found in content data, store found percent symbol as is and advance to the next position + ++pTemplateStart; + } + if (paramName.length()) { + // call callback and replace with result. + // Everything in range [pTemplateStart, pTemplateEnd] can be safely replaced with parameter value. + // Data after pTemplateEnd may need to be moved. + // The first byte of data after placeholder is located at pTemplateEnd + 1. + // It should be located at pTemplateStart + numBytesCopied (to begin right after inserted parameter value). + const String paramValue(_callback(paramName)); + const char *pvstr = paramValue.c_str(); + const unsigned int pvlen = paramValue.length(); + const size_t numBytesCopied = std::min(pvlen, static_cast(&data[originalLen - 1] - pTemplateStart + 1)); + // make room for param value + // 1. move extra data to cache if parameter value is longer than placeholder AND if there is no room to store + if ((pTemplateEnd + 1 < pTemplateStart + numBytesCopied) && (originalLen - (pTemplateStart + numBytesCopied - pTemplateEnd - 1) < len)) { + _cache.insert(_cache.begin(), &data[originalLen - (pTemplateStart + numBytesCopied - pTemplateEnd - 1)], &data[len]); + // 2. parameter value is longer than placeholder text, push the data after placeholder which not saved into cache further to the end + memmove(pTemplateStart + numBytesCopied, pTemplateEnd + 1, &data[originalLen] - pTemplateStart - numBytesCopied); + len = originalLen; // fix issue with truncated data, not sure if it has any side effects + } else if (pTemplateEnd + 1 != pTemplateStart + numBytesCopied) { + // 2. Either parameter value is shorter than placeholder text OR there is enough free space in buffer to fit. + // Move the entire data after the placeholder + memmove(pTemplateStart + numBytesCopied, pTemplateEnd + 1, &data[len] - pTemplateEnd - 1); + } + // 3. replace placeholder with actual value + memcpy(pTemplateStart, pvstr, numBytesCopied); + // If result is longer than buffer, copy the remainder into cache (this could happen only if placeholder text itself did not fit entirely in buffer) + if (numBytesCopied < pvlen) { + _cache.insert(_cache.begin(), pvstr + numBytesCopied, pvstr + pvlen); + } else if (pTemplateStart + numBytesCopied < pTemplateEnd + 1) { // result is copied fully; if result is shorter than placeholder text... + // there is some free room, fill it from cache + const size_t roomFreed = pTemplateEnd + 1 - pTemplateStart - numBytesCopied; + const size_t totalFreeRoom = originalLen - len + roomFreed; + len += _readDataFromCacheOrContent(&data[len - roomFreed], totalFreeRoom) - roomFreed; + } else { // result is copied fully; it is longer than placeholder text + const size_t roomTaken = pTemplateStart + numBytesCopied - pTemplateEnd - 1; + len = std::min(len + roomTaken, originalLen); + } + } + } // while(pTemplateStart) + return len; +} + +/* + * File Response + * */ + +void AsyncFileResponse::_setContentTypeFromPath(const String &path) { +#if HAVE_EXTERN_GET_Content_Type_FUNCTION +#ifndef ESP8266 + extern const char *getContentType(const String &path); +#else + extern const __FlashStringHelper *getContentType(const String &path); +#endif + _contentType = getContentType(path); +#else + if (path.endsWith(T__html)) { + _contentType = T_text_html; + } else if (path.endsWith(T__htm)) { + _contentType = T_text_html; + } else if (path.endsWith(T__css)) { + _contentType = T_text_css; + } else if (path.endsWith(T__json)) { + _contentType = T_application_json; + } else if (path.endsWith(T__js)) { + _contentType = T_application_javascript; + } else if (path.endsWith(T__png)) { + _contentType = T_image_png; + } else if (path.endsWith(T__gif)) { + _contentType = T_image_gif; + } else if (path.endsWith(T__jpg)) { + _contentType = T_image_jpeg; + } else if (path.endsWith(T__ico)) { + _contentType = T_image_x_icon; + } else if (path.endsWith(T__svg)) { + _contentType = T_image_svg_xml; + } else if (path.endsWith(T__eot)) { + _contentType = T_font_eot; + } else if (path.endsWith(T__woff)) { + _contentType = T_font_woff; + } else if (path.endsWith(T__woff2)) { + _contentType = T_font_woff2; + } else if (path.endsWith(T__ttf)) { + _contentType = T_font_ttf; + } else if (path.endsWith(T__xml)) { + _contentType = T_text_xml; + } else if (path.endsWith(T__pdf)) { + _contentType = T_application_pdf; + } else if (path.endsWith(T__zip)) { + _contentType = T_application_zip; + } else if (path.endsWith(T__gz)) { + _contentType = T_application_x_gzip; + } else { + _contentType = T_text_plain; + } +#endif +} + +AsyncFileResponse::AsyncFileResponse(FS &fs, const String &path, const char *contentType, bool download, AwsTemplateProcessor callback) + : AsyncAbstractResponse(callback) { + _code = 200; + _path = path; + + if (!download && !fs.exists(_path) && fs.exists(_path + T__gz)) { + _path = _path + T__gz; + addHeader(T_Content_Encoding, T_gzip, false); + _callback = nullptr; // Unable to process zipped templates + _sendContentLength = true; + _chunked = false; + } + + _content = fs.open(_path, fs::FileOpenMode::read); + _contentLength = _content.size(); + + if (strlen(contentType) == 0) { + _setContentTypeFromPath(path); + } else { + _contentType = contentType; + } + + int filenameStart = path.lastIndexOf('/') + 1; + char buf[26 + path.length() - filenameStart]; + char *filename = (char *)path.c_str() + filenameStart; + + if (download) { + // set filename and force download + snprintf_P(buf, sizeof(buf), PSTR("attachment; filename=\"%s\""), filename); + } else { + // set filename and force rendering + snprintf_P(buf, sizeof(buf), PSTR("inline")); + } + addHeader(T_Content_Disposition, buf, false); +} + +AsyncFileResponse::AsyncFileResponse(File content, const String &path, const char *contentType, bool download, AwsTemplateProcessor callback) + : AsyncAbstractResponse(callback) { + _code = 200; + _path = path; + + if (!download && String(content.name()).endsWith(T__gz) && !path.endsWith(T__gz)) { + addHeader(T_Content_Encoding, T_gzip, false); + _callback = nullptr; // Unable to process gzipped templates + _sendContentLength = true; + _chunked = false; + } + + _content = content; + _contentLength = _content.size(); + + if (strlen(contentType) == 0) { + _setContentTypeFromPath(path); + } else { + _contentType = contentType; + } + + int filenameStart = path.lastIndexOf('/') + 1; + char buf[26 + path.length() - filenameStart]; + char *filename = (char *)path.c_str() + filenameStart; + + if (download) { + snprintf_P(buf, sizeof(buf), PSTR("attachment; filename=\"%s\""), filename); + } else { + snprintf_P(buf, sizeof(buf), PSTR("inline")); + } + addHeader(T_Content_Disposition, buf, false); +} + +size_t AsyncFileResponse::_fillBuffer(uint8_t *data, size_t len) { + return _content.read(data, len); +} + +/* + * Stream Response + * */ + +AsyncStreamResponse::AsyncStreamResponse(Stream &stream, const char *contentType, size_t len, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) { + _code = 200; + _content = &stream; + _contentLength = len; + _contentType = contentType; +} + +size_t AsyncStreamResponse::_fillBuffer(uint8_t *data, size_t len) { + size_t available = _content->available(); + size_t outLen = (available > len) ? len : available; + size_t i; + for (i = 0; i < outLen; i++) { + data[i] = _content->read(); + } + return outLen; +} + +/* + * Callback Response + * */ + +AsyncCallbackResponse::AsyncCallbackResponse(const char *contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) + : AsyncAbstractResponse(templateCallback) { + _code = 200; + _content = callback; + _contentLength = len; + if (!len) { + _sendContentLength = false; + } + _contentType = contentType; + _filledLength = 0; +} + +size_t AsyncCallbackResponse::_fillBuffer(uint8_t *data, size_t len) { + size_t ret = _content(data, len, _filledLength); + if (ret != RESPONSE_TRY_AGAIN) { + _filledLength += ret; + } + return ret; +} + +/* + * Chunked Response + * */ + +AsyncChunkedResponse::AsyncChunkedResponse(const char *contentType, AwsResponseFiller callback, AwsTemplateProcessor processorCallback) + : AsyncAbstractResponse(processorCallback) { + _code = 200; + _content = callback; + _contentLength = 0; + _contentType = contentType; + _sendContentLength = false; + _chunked = true; + _filledLength = 0; +} + +size_t AsyncChunkedResponse::_fillBuffer(uint8_t *data, size_t len) { + size_t ret = _content(data, len, _filledLength); + if (ret != RESPONSE_TRY_AGAIN) { + _filledLength += ret; + } + return ret; +} + +/* + * Progmem Response + * */ + +AsyncProgmemResponse::AsyncProgmemResponse(int code, const char *contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback) + : AsyncAbstractResponse(callback) { + _code = code; + _content = content; + _contentType = contentType; + _contentLength = len; + _readLength = 0; +} + +size_t AsyncProgmemResponse::_fillBuffer(uint8_t *data, size_t len) { + size_t left = _contentLength - _readLength; + if (left > len) { + memcpy_P(data, _content + _readLength, len); + _readLength += len; + return len; + } + memcpy_P(data, _content + _readLength, left); + _readLength += left; + return left; +} + +/* + * Response Stream (You can print/write/printf to it, up to the contentLen bytes) + * */ + +AsyncResponseStream::AsyncResponseStream(const char *contentType, size_t bufferSize) { + _code = 200; + _contentLength = 0; + _contentType = contentType; + // internal buffer will be null on allocation failure + _content = std::unique_ptr(new cbuf(bufferSize)); + if (bufferSize && _content->size() < bufferSize) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + } +} + +size_t AsyncResponseStream::_fillBuffer(uint8_t *buf, size_t maxLen) { + return _content->read((char *)buf, maxLen); +} + +size_t AsyncResponseStream::write(const uint8_t *data, size_t len) { + if (_started()) { + return 0; + } + if (len > _content->room()) { + size_t needed = len - _content->room(); + _content->resizeAdd(needed); + // log a warning if allocation failed, but do not return: keep writing the bytes we can + // with _content->write: if len is more than the available size in the buffer, only + // the available size will be written + if (len > _content->room()) { +#ifdef ESP32 + log_e("Failed to allocate"); +#endif + } + } + size_t written = _content->write((const char *)data, len); + _contentLength += written; + return written; +} + +size_t AsyncResponseStream::write(uint8_t data) { + return write(&data, 1); +} diff --git a/watering/lib/ESPAsyncWebServer/src/WebServer.cpp b/watering/lib/ESPAsyncWebServer/src/WebServer.cpp new file mode 100644 index 0000000..7fc54bf --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/WebServer.cpp @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#include "ESPAsyncWebServer.h" +#include "WebHandlerImpl.h" + +using namespace asyncsrv; + +bool ON_STA_FILTER(AsyncWebServerRequest *request) { +#ifndef CONFIG_IDF_TARGET_ESP32H2 + return WiFi.localIP() == request->client()->localIP(); +#else + return false; +#endif +} + +bool ON_AP_FILTER(AsyncWebServerRequest *request) { +#ifndef CONFIG_IDF_TARGET_ESP32H2 + return WiFi.localIP() != request->client()->localIP(); +#else + return false; +#endif +} + +#ifndef HAVE_FS_FILE_OPEN_MODE +const char *fs::FileOpenMode::read = "r"; +const char *fs::FileOpenMode::write = "w"; +const char *fs::FileOpenMode::append = "a"; +#endif + +AsyncWebServer::AsyncWebServer(uint16_t port) : _server(port) { + _catchAllHandler = new AsyncCallbackWebHandler(); + _server.onClient( + [](void *s, AsyncClient *c) { + if (c == NULL) { + return; + } + c->setRxTimeout(3); + AsyncWebServerRequest *r = new AsyncWebServerRequest((AsyncWebServer *)s, c); + if (r == NULL) { + c->abort(); + delete c; + } + }, + this + ); +} + +AsyncWebServer::~AsyncWebServer() { + reset(); + end(); + delete _catchAllHandler; + _catchAllHandler = nullptr; // Prevent potential use-after-free +} + +AsyncWebRewrite &AsyncWebServer::addRewrite(std::shared_ptr rewrite) { + _rewrites.emplace_back(rewrite); + return *_rewrites.back().get(); +} + +AsyncWebRewrite &AsyncWebServer::addRewrite(AsyncWebRewrite *rewrite) { + _rewrites.emplace_back(rewrite); + return *_rewrites.back().get(); +} + +bool AsyncWebServer::removeRewrite(AsyncWebRewrite *rewrite) { + return removeRewrite(rewrite->from().c_str(), rewrite->toUrl().c_str()); +} + +bool AsyncWebServer::removeRewrite(const char *from, const char *to) { + for (auto r = _rewrites.begin(); r != _rewrites.end(); ++r) { + if (r->get()->from() == from && r->get()->toUrl() == to) { + _rewrites.erase(r); + return true; + } + } + return false; +} + +AsyncWebRewrite &AsyncWebServer::rewrite(const char *from, const char *to) { + _rewrites.emplace_back(std::make_shared(from, to)); + return *_rewrites.back().get(); +} + +AsyncWebHandler &AsyncWebServer::addHandler(AsyncWebHandler *handler) { + _handlers.emplace_back(handler); + return *(_handlers.back().get()); +} + +bool AsyncWebServer::removeHandler(AsyncWebHandler *handler) { + for (auto i = _handlers.begin(); i != _handlers.end(); ++i) { + if (i->get() == handler) { + _handlers.erase(i); + return true; + } + } + return false; +} + +void AsyncWebServer::begin() { + _server.setNoDelay(true); + _server.begin(); +} + +void AsyncWebServer::end() { + _server.end(); +} + +#if ASYNC_TCP_SSL_ENABLED +void AsyncWebServer::onSslFileRequest(AcSSlFileHandler cb, void *arg) { + _server.onSslFileRequest(cb, arg); +} + +void AsyncWebServer::beginSecure(const char *cert, const char *key, const char *password) { + _server.beginSecure(cert, key, password); +} +#endif + +void AsyncWebServer::_handleDisconnect(AsyncWebServerRequest *request) { + delete request; +} + +void AsyncWebServer::_rewriteRequest(AsyncWebServerRequest *request) { + // the last rewrite that matches the request will be used + // we do not break the loop to allow for multiple rewrites to be applied and only the last one to be used (allows overriding) + for (const auto &r : _rewrites) { + if (r->match(request)) { + request->_url = r->toUrl(); + request->_addGetParams(r->params()); + } + } +} + +void AsyncWebServer::_attachHandler(AsyncWebServerRequest *request) { + for (auto &h : _handlers) { + if (h->filter(request) && h->canHandle(request)) { + request->setHandler(h.get()); + return; + } + } + // ESP_LOGD("AsyncWebServer", "No handler found for %s, using _catchAllHandler pointer: %p", request->url().c_str(), _catchAllHandler); + request->setHandler(_catchAllHandler); +} + +AsyncCallbackWebHandler &AsyncWebServer::on( + const char *uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload, ArBodyHandlerFunction onBody +) { + AsyncCallbackWebHandler *handler = new AsyncCallbackWebHandler(); + handler->setUri(uri); + handler->setMethod(method); + handler->onRequest(onRequest); + handler->onUpload(onUpload); + handler->onBody(onBody); + addHandler(handler); + return *handler; +} + +AsyncStaticWebHandler &AsyncWebServer::serveStatic(const char *uri, fs::FS &fs, const char *path, const char *cache_control) { + AsyncStaticWebHandler *handler = new AsyncStaticWebHandler(uri, fs, path, cache_control); + addHandler(handler); + return *handler; +} + +void AsyncWebServer::onNotFound(ArRequestHandlerFunction fn) { + _catchAllHandler->onRequest(fn); +} + +void AsyncWebServer::onFileUpload(ArUploadHandlerFunction fn) { + _catchAllHandler->onUpload(fn); +} + +void AsyncWebServer::onRequestBody(ArBodyHandlerFunction fn) { + _catchAllHandler->onBody(fn); +} + +AsyncWebHandler &AsyncWebServer::catchAllHandler() const { + return *_catchAllHandler; +} + +void AsyncWebServer::reset() { + _rewrites.clear(); + _handlers.clear(); + + _catchAllHandler->onRequest(NULL); + _catchAllHandler->onUpload(NULL); + _catchAllHandler->onBody(NULL); +} diff --git a/watering/lib/ESPAsyncWebServer/src/literals.h b/watering/lib/ESPAsyncWebServer/src/literals.h new file mode 100644 index 0000000..a69f78b --- /dev/null +++ b/watering/lib/ESPAsyncWebServer/src/literals.h @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov + +#pragma once + +namespace asyncsrv { + +static constexpr const char *empty = ""; + +static constexpr const char *T__opaque = "\", opaque=\""; +static constexpr const char *T_100_CONTINUE = "100-continue"; +static constexpr const char *T_13 = "13"; +static constexpr const char *T_ACCEPT = "accept"; +static constexpr const char *T_Accept_Ranges = "accept-ranges"; +static constexpr const char *T_app_xform_urlencoded = "application/x-www-form-urlencoded"; +static constexpr const char *T_AUTH = "authorization"; +static constexpr const char *T_auth_nonce = "\", qop=\"auth\", nonce=\""; +static constexpr const char *T_BASIC = "basic"; +static constexpr const char *T_BASIC_REALM = "basic realm=\""; +static constexpr const char *T_BEARER = "bearer"; +static constexpr const char *T_BODY = "body"; +static constexpr const char *T_Cache_Control = "cache-control"; +static constexpr const char *T_chunked = "chunked"; +static constexpr const char *T_close = "close"; +static constexpr const char *T_cnonce = "cnonce"; +static constexpr const char *T_Connection = "connection"; +static constexpr const char *T_Content_Disposition = "content-disposition"; +static constexpr const char *T_Content_Encoding = "content-encoding"; +static constexpr const char *T_Content_Length = "content-length"; +static constexpr const char *T_Content_Type = "content-type"; +static constexpr const char *T_Content_Location = "content-location"; +static constexpr const char *T_Cookie = "cookie"; +static constexpr const char *T_CORS_ACAC = "access-control-allow-credentials"; +static constexpr const char *T_CORS_ACAH = "access-control-allow-headers"; +static constexpr const char *T_CORS_ACAM = "access-control-allow-methods"; +static constexpr const char *T_CORS_ACAO = "access-control-allow-origin"; +static constexpr const char *T_CORS_ACMA = "access-control-max-age"; +static constexpr const char *T_CORS_O = "origin"; +static constexpr const char *T_data_ = "data: "; +static constexpr const char *T_Date = "date"; +static constexpr const char *T_DIGEST = "digest"; +static constexpr const char *T_DIGEST_ = "digest "; +static constexpr const char *T_ETag = "etag"; +static constexpr const char *T_event_ = "event: "; +static constexpr const char *T_EXPECT = "expect"; +static constexpr const char *T_FALSE = "false"; +static constexpr const char *T_filename = "filename"; +static constexpr const char *T_gzip = "gzip"; +static constexpr const char *T_Host = "host"; +static constexpr const char *T_HTTP_1_0 = "HTTP/1.0"; +static constexpr const char *T_HTTP_100_CONT = "HTTP/1.1 100 Continue\r\n\r\n"; +static constexpr const char *T_id__ = "id: "; +static constexpr const char *T_IMS = "if-modified-since"; +static constexpr const char *T_INM = "if-none-match"; +static constexpr const char *T_keep_alive = "keep-alive"; +static constexpr const char *T_Last_Event_ID = "last-event-id"; +static constexpr const char *T_Last_Modified = "last-modified"; +static constexpr const char *T_LOCATION = "location"; +static constexpr const char *T_LOGIN_REQ = "Login Required"; +static constexpr const char *T_MULTIPART_ = "multipart/"; +static constexpr const char *T_name = "name"; +static constexpr const char *T_nc = "nc"; +static constexpr const char *T_no_cache = "no-cache"; +static constexpr const char *T_nonce = "nonce"; +static constexpr const char *T_none = "none"; +static constexpr const char *T_opaque = "opaque"; +static constexpr const char *T_qop = "qop"; +static constexpr const char *T_realm = "realm"; +static constexpr const char *T_realm__ = "realm=\""; +static constexpr const char *T_response = "response"; +static constexpr const char *T_retry_ = "retry: "; +static constexpr const char *T_retry_after = "retry-after"; +static constexpr const char *T_nn = "\n\n"; +static constexpr const char *T_rn = "\r\n"; +static constexpr const char *T_rnrn = "\r\n\r\n"; +static constexpr const char *T_Server = "server"; +static constexpr const char *T_Transfer_Encoding = "transfer-encoding"; +static constexpr const char *T_TRUE = "true"; +static constexpr const char *T_UPGRADE = "upgrade"; +static constexpr const char *T_uri = "uri"; +static constexpr const char *T_username = "username"; +static constexpr const char *T_WS = "websocket"; +static constexpr const char *T_WWW_AUTH = "www-authenticate"; + +// HTTP Methods + +static constexpr const char *T_ANY = "ANY"; +static constexpr const char *T_GET = "GET"; +static constexpr const char *T_POST = "POST"; +static constexpr const char *T_PUT = "PUT"; +static constexpr const char *T_DELETE = "DELETE"; +static constexpr const char *T_PATCH = "PATCH"; +static constexpr const char *T_HEAD = "HEAD"; +static constexpr const char *T_OPTIONS = "OPTIONS"; +static constexpr const char *T_UNKNOWN = "UNKNOWN"; + +// Req content types +static constexpr const char *T_RCT_NOT_USED = "RCT_NOT_USED"; +static constexpr const char *T_RCT_DEFAULT = "RCT_DEFAULT"; +static constexpr const char *T_RCT_HTTP = "RCT_HTTP"; +static constexpr const char *T_RCT_WS = "RCT_WS"; +static constexpr const char *T_RCT_EVENT = "RCT_EVENT"; +static constexpr const char *T_ERROR = "ERROR"; + +// extensions & MIME-Types +static constexpr const char *T__css = ".css"; +static constexpr const char *T__eot = ".eot"; +static constexpr const char *T__gif = ".gif"; +static constexpr const char *T__gz = ".gz"; +static constexpr const char *T__htm = ".htm"; +static constexpr const char *T__html = ".html"; +static constexpr const char *T__ico = ".ico"; +static constexpr const char *T__jpg = ".jpg"; +static constexpr const char *T__js = ".js"; +static constexpr const char *T__json = ".json"; +static constexpr const char *T__pdf = ".pdf"; +static constexpr const char *T__png = ".png"; +static constexpr const char *T__svg = ".svg"; +static constexpr const char *T__ttf = ".ttf"; +static constexpr const char *T__woff = ".woff"; +static constexpr const char *T__woff2 = ".woff2"; +static constexpr const char *T__xml = ".xml"; +static constexpr const char *T__zip = ".zip"; +static constexpr const char *T_application_javascript = "application/javascript"; +static constexpr const char *T_application_json = "application/json"; +static constexpr const char *T_application_msgpack = "application/msgpack"; +static constexpr const char *T_application_pdf = "application/pdf"; +static constexpr const char *T_application_x_gzip = "application/x-gzip"; +static constexpr const char *T_application_zip = "application/zip"; +static constexpr const char *T_font_eot = "font/eot"; +static constexpr const char *T_font_ttf = "font/ttf"; +static constexpr const char *T_font_woff = "font/woff"; +static constexpr const char *T_font_woff2 = "font/woff2"; +static constexpr const char *T_image_gif = "image/gif"; +static constexpr const char *T_image_jpeg = "image/jpeg"; +static constexpr const char *T_image_png = "image/png"; +static constexpr const char *T_image_svg_xml = "image/svg+xml"; +static constexpr const char *T_image_x_icon = "image/x-icon"; +static constexpr const char *T_text_css = "text/css"; +static constexpr const char *T_text_event_stream = "text/event-stream"; +static constexpr const char *T_text_html = "text/html"; +static constexpr const char *T_text_plain = "text/plain"; +static constexpr const char *T_text_xml = "text/xml"; + +// Response codes +static constexpr const char *T_HTTP_CODE_100 = "Continue"; +static constexpr const char *T_HTTP_CODE_101 = "Switching Protocols"; +static constexpr const char *T_HTTP_CODE_200 = "OK"; +static constexpr const char *T_HTTP_CODE_201 = "Created"; +static constexpr const char *T_HTTP_CODE_202 = "Accepted"; +static constexpr const char *T_HTTP_CODE_203 = "Non-Authoritative Information"; +static constexpr const char *T_HTTP_CODE_204 = "No Content"; +static constexpr const char *T_HTTP_CODE_205 = "Reset Content"; +static constexpr const char *T_HTTP_CODE_206 = "Partial Content"; +static constexpr const char *T_HTTP_CODE_300 = "Multiple Choices"; +static constexpr const char *T_HTTP_CODE_301 = "Moved Permanently"; +static constexpr const char *T_HTTP_CODE_302 = "Found"; +static constexpr const char *T_HTTP_CODE_303 = "See Other"; +static constexpr const char *T_HTTP_CODE_304 = "Not Modified"; +static constexpr const char *T_HTTP_CODE_305 = "Use Proxy"; +static constexpr const char *T_HTTP_CODE_307 = "Temporary Redirect"; +static constexpr const char *T_HTTP_CODE_400 = "Bad Request"; +static constexpr const char *T_HTTP_CODE_401 = "Unauthorized"; +static constexpr const char *T_HTTP_CODE_402 = "Payment Required"; +static constexpr const char *T_HTTP_CODE_403 = "Forbidden"; +static constexpr const char *T_HTTP_CODE_404 = "Not Found"; +static constexpr const char *T_HTTP_CODE_405 = "Method Not Allowed"; +static constexpr const char *T_HTTP_CODE_406 = "Not Acceptable"; +static constexpr const char *T_HTTP_CODE_407 = "Proxy Authentication Required"; +static constexpr const char *T_HTTP_CODE_408 = "Request Time-out"; +static constexpr const char *T_HTTP_CODE_409 = "Conflict"; +static constexpr const char *T_HTTP_CODE_410 = "Gone"; +static constexpr const char *T_HTTP_CODE_411 = "Length Required"; +static constexpr const char *T_HTTP_CODE_412 = "Precondition Failed"; +static constexpr const char *T_HTTP_CODE_413 = "Request Entity Too Large"; +static constexpr const char *T_HTTP_CODE_414 = "Request-URI Too Large"; +static constexpr const char *T_HTTP_CODE_415 = "Unsupported Media Type"; +static constexpr const char *T_HTTP_CODE_416 = "Requested range not satisfiable"; +static constexpr const char *T_HTTP_CODE_417 = "Expectation Failed"; +static constexpr const char *T_HTTP_CODE_429 = "Too Many Requests"; +static constexpr const char *T_HTTP_CODE_500 = "Internal Server Error"; +static constexpr const char *T_HTTP_CODE_501 = "Not Implemented"; +static constexpr const char *T_HTTP_CODE_502 = "Bad Gateway"; +static constexpr const char *T_HTTP_CODE_503 = "Service Unavailable"; +static constexpr const char *T_HTTP_CODE_504 = "Gateway Time-out"; +static constexpr const char *T_HTTP_CODE_505 = "HTTP Version not supported"; +static constexpr const char *T_HTTP_CODE_ANY = "Unknown code"; + +static constexpr const uint8_t T_only_once_headers_len = 11; +static constexpr const char *T_only_once_headers[] = {T_Content_Length, T_Content_Type, T_Date, T_ETag, T_Last_Modified, T_LOCATION, T_retry_after, + T_Transfer_Encoding, T_Content_Location, T_Server, T_WWW_AUTH}; + +} // namespace asyncsrv diff --git a/watering/lib/ESPUI/.clang-format b/watering/lib/ESPUI/.clang-format deleted file mode 100644 index 792a92e..0000000 --- a/watering/lib/ESPUI/.clang-format +++ /dev/null @@ -1,58 +0,0 @@ ---- -# Based on Webkit style -BasedOnStyle: Webkit -IndentWidth: 4 -ColumnLimit: 120 ---- -Language: Cpp -Standard: Cpp11 -# Pointers aligned to the left -DerivePointerAlignment: false -PointerAlignment: Left -AccessModifierOffset: -4 -AllowShortFunctionsOnASingleLine: Inline -AlwaysBreakTemplateDeclarations: true -BreakBeforeBraces: Custom -BraceWrapping: - AfterClass: true - AfterControlStatement: true - AfterEnum: true - AfterFunction: true - AfterNamespace: true - AfterStruct: true - AfterUnion: true - AfterExternBlock: true - BeforeCatch: true - BeforeElse: true - SplitEmptyFunction: false - SplitEmptyRecord: false - SplitEmptyNamespace: false -BreakConstructorInitializers: BeforeColon -CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: true -ConstructorInitializerIndentWidth: 4 -Cpp11BracedListStyle: true -FixNamespaceComments: true -IncludeBlocks: Regroup -IncludeCategories: - # C++ standard headers (no .h) - - Regex: '<[[:alnum:]_-]+>' - Priority: 1 - # Extenal libraries (with .h) - - Regex: '<[[:alnum:]_./-]+>' - Priority: 2 - # Headers from same folder - - Regex: '"[[:alnum:]_.-]+"' - Priority: 3 - # Headers from other folders - - Regex: '"[[:alnum:]_/.-]+"' - Priority: 4 -IndentCaseLabels: false -NamespaceIndentation: All -SortIncludes: true -SortUsingDeclarations: true -SpaceAfterTemplateKeyword: true -SpacesInAngles: false -SpacesInParentheses: false -SpacesInSquareBrackets: false -UseTab: Never \ No newline at end of file diff --git a/watering/lib/ESPUI/.github/ISSUE_TEMPLATE/bug_report.md b/watering/lib/ESPUI/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index b735373..0000000 --- a/watering/lib/ESPUI/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior: -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**Desktop (please complete the following information):** - - OS: [e.g. iOS] - - Browser [e.g. chrome, safari] - - Version [e.g. 22] - -**Smartphone (please complete the following information):** - - Device: [e.g. iPhone6] - - OS: [e.g. iOS8.1] - - Browser [e.g. stock browser, safari] - - Version [e.g. 22] - -**Additional context** -Add any other context about the problem here. diff --git a/watering/lib/ESPUI/.github/ISSUE_TEMPLATE/feature_request.md b/watering/lib/ESPUI/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 066b2d9..0000000 --- a/watering/lib/ESPUI/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/watering/lib/ESPUI/.gitignore b/watering/lib/ESPUI/.gitignore deleted file mode 100644 index 87b3c5f..0000000 --- a/watering/lib/ESPUI/.gitignore +++ /dev/null @@ -1,38 +0,0 @@ -# ========================= -# Operating System Files -# ========================= - -# OSX -# ========================= - -.DS_Store -.AppleDouble -.LSOverride - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# Linux -# ========================= - -# Backup files produced by some editors -*~ -*.bak - - -.vscode/ diff --git a/watering/lib/ESPUI/ESPUI_blocks.js b/watering/lib/ESPUI/ESPUI_blocks.js deleted file mode 100644 index 1813db3..0000000 --- a/watering/lib/ESPUI/ESPUI_blocks.js +++ /dev/null @@ -1,279 +0,0 @@ -// This is a block definition for projects like roboblocks -// -// Main Block -Facilino.LANG_COLOUR_HTML = '#BDBDBD'; -Facilino.LANG_COLOUR_ESPUI = '#B1B1B1'; - -Blockly.Blocks['espui'] = { - category: Facilino.locales.getKey('LANG_CATEGORY_HTML'), - subcategory: Facilino.locales.getKey('LANG_SUBCATERGORY_ESPUI'), - helpUrl: Facilino.getHelpUrl('espui'), - tags: ['webinterface'], - examples: ['lol.bly'], - category_colour: Facilino.LANG_COLOUR_HTML, - colour: Facilino.LANG_COLOUR_ESPUI, - init: function() { - var wifiOptions = [['No', false],['Yes', true]]; - this.appendDummyInput().appendField('UI Title:').appendField(new Blockly.FieldTextInput(Facilino.locales.getKey('LANG_ESPUI_ESPUI_TITLE')), 'ui_name'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_ESPUI_HOTSPOT')).appendField(new Blockly.FieldDropdown(wifiOptions), 'wifi_option'); - this.appendStatementInput('ui_elements').setCheck('ui_element'); - this.setColour(Facilino.LANG_COLOUR_ESPUI); - this.setTooltip(Facilino.locales.getKey('LANG_ESPUI_ESPUI_TOOLTIP')); - } -}; - -Blockly.Arduino['espui'] = function(block) { - var ui_name = block.getFieldValue('ui_name'); - var wifi_option = block.getFieldValue('wifi_option'); - var ui_elements = Blockly.Arduino.statementToCode(block, 'ui_elements'); - Blockly.Arduino.definitions_['define_wifi_h'] = '#include '; - Blockly.Arduino.definitions_['define_espui_h'] = '#include '; - Blockly.Arduino.setups_['setup_espui'] = '\n'; - if(wifi_option){ - Blockly.Arduino.setups_['setup_espui'] += - ' Serial.begin(115200);\n\n' + - ' WiFi.mode(WIFI_AP);\n' + - ' WiFi.softAP("' + ui_name + '");\n' + - ' Serial.print("IP address: ");\n' + - ' Serial.println(WiFi.softAPIP());\n\n'; - } - Blockly.Arduino.setups_['setup_espui'] += ui_elements; - Blockly.Arduino.setups_['setup_espui'] += ' ESPUI.begin("' + ui_name + '");\n'; - return null; -}; - -//Elements - -Blockly.Blocks['espui_button'] = { - category: Facilino.locales.getKey('LANG_CATEGORY_HTML'), - subcategory: Facilino.locales.getKey('LANG_SUBCATERGORY_ESPUI'), - helpUrl: Facilino.getHelpUrl('espui_button'), - tags: ['webinterface'], - examples: ['lol.bly'], - category_colour: Facilino.LANG_COLOUR_HTML, - colour: Facilino.LANG_COLOUR_ESPUI, - init: function() { - var colour = new Blockly.FieldColour('#000000'); - colour.setColours(['#000000','#40e0d0','#50c878','#3498dc','#687894','#e4d422','#eb8921','#e32636']).setColumns(2); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_BUTTON_BUTTON')).appendField(new Blockly.FieldTextInput(Facilino.locales.getKey('LANG_ESPUI_NAME')), 'ui_name'); - //this.appendDummyInput().appendField('UI Color').appendField(new Blockly.FieldDropdown(colorOptions), 'ui_color'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_COLOR')).appendField(colour, 'ui_color'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_TEXT')).appendField(new Blockly.FieldTextInput(Facilino.locales.getKey('LANG_ESPUI_TEXT')), 'button_text'); - this.setColour(Facilino.LANG_COLOUR_ESPUI); - this.setPreviousStatement(true, 'ui_element'); - this.setNextStatement(true, 'ui_element'); - this.setTooltip(Facilino.locales.getKey('LANG_ESPUI_BUTTON_TOOLTIP')); - this.appendStatementInput('on_down').appendField(new Blockly.FieldImage('img/blocks/button_pressed.svg', 24*options.zoom, 24*options.zoom)).setCheck(null); - this.appendStatementInput('on_up').appendField(new Blockly.FieldImage('img/blocks/button_released.svg', 24*options.zoom, 24*options.zoom)).setCheck(null); - } -}; - -Blockly.Arduino['espui_button'] = function(block) { - var ui_name = block.getFieldValue('ui_name'); - var color = block.getFieldValue('ui_color'); - var colorOptions = {"#000000": "COLOR_NONE", "#40e0d0": "COLOR_TURQUOISE", "#50c878": "COLOR_EMERALD", "#3498dc": "COLOR_PETERRIVER", "#687894": "COLOR_WETASPHALT", "#e4d422": "COLOR_SUNFLOWER", "#eb8921": "COLOR_CARROT", "#e32636": "COLOR_ALIZARIN"}; - var ui_color = colorOptions[color]; - var button_text = block.getFieldValue('button_text'); - var ui_name_clean = ui_name.replace(' ', '_'); - var on_down = Blockly.Arduino.statementToCode(block, 'on_down'); - var on_up = Blockly.Arduino.statementToCode(block, 'on_up'); - Blockly.Arduino.definitions_['define_ui_button_' + ui_name_clean] = - 'void button_' + ui_name_clean + '(Control c, int type) {\n' + - ' switch(type){\n' + - ' case B_DOWN:\n' + - on_down + '\n break;\n' + - ' case B_UP:\n' + - on_up + '\n break;\n' + - ' }\n' + - '}\n'; - var code = ' ESPUI.button("' + ui_name + '", &button_' + ui_name_clean + ', ' + ui_color + ', "' + button_text + '");\n'; - return code; -}; - -Blockly.Blocks['espui_label'] = { - category: Facilino.locales.getKey('LANG_CATEGORY_HTML'), - subcategory: Facilino.locales.getKey('LANG_SUBCATERGORY_ESPUI'), - helpUrl: Facilino.getHelpUrl('espui_label'), - tags: ['webinterface'], - examples: ['lol.bly'], - category_colour: Facilino.LANG_COLOUR_HTML, - colour: Facilino.LANG_COLOUR_ESPUI, - init: function() { - var colour = new Blockly.FieldColour('#000000'); - colour.setColours(['#000000','#40e0d0','#50c878','#3498dc','#687894','#e4d422','#eb8921','#e32636']).setColumns(2); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_LABEL_LABEL')).appendField(new Blockly.FieldTextInput(Facilino.locales.getKey('LANG_ESPUI_NAME')), 'ui_name'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_COLOR')).appendField(colour, 'ui_color'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_TEXT')).appendField(new Blockly.FieldTextInput('value'), 'start_value'); - this.setColour(Facilino.LANG_COLOUR_ESPUI); - this.setPreviousStatement(true, 'ui_element'); - this.setNextStatement(true, 'ui_element'); - this.setTooltip(Facilino.locales.getKey('LANG_ESPUI_LABEL_TOOLTIP')); - } -}; - -Blockly.Arduino['espui_label'] = function(block) { - var ui_name = block.getFieldValue('ui_name'); - var ui_color = block.getFieldValue('ui_color'); - var ui_name_clean = ui_name.replace(' ', '_'); - var start_value = block.getFieldValue('start_value'); - var code = ' ESPUI.label("' + ui_name + '", ' + ui_color + ', "' + start_value + '");\n'; - return code; -}; - -Blockly.Blocks['espui_switcher'] = { - category: Facilino.locales.getKey('LANG_CATEGORY_HTML'), - subcategory: Facilino.locales.getKey('LANG_SUBCATERGORY_ESPUI'), - helpUrl: Facilino.getHelpUrl('espui_switcher'), - tags: ['webinterface'], - examples: ['lol.bly'], - category_colour: Facilino.LANG_COLOUR_HTML, - colour: Facilino.LANG_COLOUR_ESPUI, - init: function() { - var colour = new Blockly.FieldColour('#000000'); - colour.setColours(['#000000','#40e0d0','#50c878','#3498dc','#687894','#e4d422','#eb8921','#e32636']).setColumns(2); - var stateOptions = [['Off', 'false'],['On', 'true']]; - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_SWITCH_SWITCH')).appendField(new Blockly.FieldTextInput(Facilino.locales.getKey('LANG_ESPUI_NAME')), 'ui_name'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_COLOR')).appendField(colour, 'ui_color'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_STATE')).appendField(new Blockly.FieldDropdown(stateOptions), 'switcher_state'); - this.setColour(Facilino.LANG_COLOUR_ESPUI); - this.setPreviousStatement(true, 'ui_element'); - this.setNextStatement(true, 'ui_element'); - this.setTooltip('A web interface button'); - this.appendStatementInput('on_on').appendField(new Blockly.FieldImage('img/blocks/switch_on.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_off').appendField(new Blockly.FieldImage('img/blocks/switch_off.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - } -}; - -Blockly.Arduino['espui_switcher'] = function(block) { - var ui_name = block.getFieldValue('ui_name'); - var color = block.getFieldValue('ui_color'); - var colorOptions = {"#000000": "COLOR_NONE", "#40e0d0": "COLOR_TURQUOISE", "#50c878": "COLOR_EMERALD", "#3498dc": "COLOR_PETERRIVER", "#687894": "COLOR_WETASPHALT", "#e4d422": "COLOR_SUNFLOWER", "#eb8921": "COLOR_CARROT", "#e32636": "COLOR_ALIZARIN"}; - var ui_color = colorOptions[color]; - var switcher_state = block.getFieldValue('switcher_state'); - var ui_name_clean = ui_name.replace(' ', '_'); - var on_on = Blockly.Arduino.statementToCode(block, 'on_down'); - var on_off = Blockly.Arduino.statementToCode(block, 'on_up'); - Blockly.Arduino.definitions_['define_ui_switcher_' + ui_name_clean] = - 'void switcher_' + ui_name_clean + '(Control c, int type) {\n' + - ' switch(type){\n' + - ' case S_ACTIVE:\n' + - on_on + '\n break;\n' + - ' case S_INACTIVE:\n' + - on_off + '\n break;\n' + - ' }\n' + - '}\n'; - var code = ' ESPUI.switcher("' + ui_name + '", ' + switcher_state + ', &switcher_' + ui_name_clean + ', ' + ui_color + ');\n'; - return code; -}; - -Blockly.Blocks['espui_pad'] = { - category: Facilino.locales.getKey('LANG_CATEGORY_HTML'), - subcategory: Facilino.locales.getKey('LANG_SUBCATERGORY_ESPUI'), - helpUrl: Facilino.getHelpUrl('espui_pad'), - tags: ['webinterface'], - examples: ['lol.bly'], - category_colour: Facilino.LANG_COLOUR_HTML, - colour: Facilino.LANG_COLOUR_ESPUI, - init: function() { - var colour = new Blockly.FieldColour('#000000'); - colour.setColours(['#000000','#40e0d0','#50c878','#3498dc','#687894','#e4d422','#eb8921','#e32636']).setColumns(2); - var centerOptions = [['Yes', 'false'],['No', 'true']]; - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_PAD_PAD')).appendField(new Blockly.FieldTextInput(Facilino.locales.getKey('LANG_ESPUI_NAME')), 'ui_name'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_COLOR')).appendField(colour, 'ui_color'); - this.appendDummyInput().appendField(Facilino.locales.getKey('LANG_ESPUI_PAD_CENTER')).appendField(new Blockly.FieldDropdown(centerOptions), 'pad_center'); - this.setColour(Facilino.LANG_COLOUR_ESPUI); - this.setPreviousStatement(true, 'ui_element'); - this.setNextStatement(true, 'ui_element'); - this.setTooltip('A web interface button'); - this.appendStatementInput('on_down_for').appendField(new Blockly.FieldImage('img/blocks/controller_up_pressed.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_up_for').appendField(new Blockly.FieldImage('img/blocks/controller_up_released.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_down_back').appendField(new Blockly.FieldImage('img/blocks/controller_down_pressed.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_up_back').appendField(new Blockly.FieldImage('img/blocks/controller_down_released.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_down_left').appendField(new Blockly.FieldImage('img/blocks/controller_right_pressed.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_up_left').appendField(new Blockly.FieldImage('img/blocks/controller_right_released.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_down_right').appendField(new Blockly.FieldImage('img/blocks/controller_left_pressed.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_up_right').appendField(new Blockly.FieldImage('img/blocks/controller_left_released.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_down_center').appendField(new Blockly.FieldImage('img/blocks/controller_center_pressed.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_up_center').appendField(new Blockly.FieldImage('img/blocks/controller_center_released.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.lastOption=this.getFieldValue('pad_center'); - }, - onchange() { - if (this.lastOption!==this.getFieldValue('pad_center')) - { - if (this.getFieldValue('pad_center')==='false') - { - try{ - - this.removeInput('on_down_center'); - this.removeInput('on_up_center'); - this.appendStatementInput('on_down_center').appendField(new Blockly.FieldImage('img/blocks/controller_center_pressed.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - this.appendStatementInput('on_up_center').appendField(new Blockly.FieldImage('img/blocks/controller_center_released.svg', 24*options.zoom, 24*options.zoom)).setCheck('code'); - } - catch(e) - { - } - } - else - { - try{ - this.removeInput('on_down_center'); - this.removeInput('on_up_center'); - } - catch(e) - { - } - } - this.lastOption=this.getFieldValue('pad_center'); - } - } -}; - -Blockly.Arduino['espui_pad'] = function(block) { - var ui_name = block.getFieldValue('ui_name'); - var color = block.getFieldValue('ui_color'); - var colorOptions = {"#000000": "COLOR_NONE", "#40e0d0": "COLOR_TURQUOISE", "#50c878": "COLOR_EMERALD", "#3498dc": "COLOR_PETERRIVER", "#687894": "COLOR_WETASPHALT", "#e4d422": "COLOR_SUNFLOWER", "#eb8921": "COLOR_CARROT", "#e32636": "COLOR_ALIZARIN"}; - var ui_color = colorOptions[color]; - var pad_center = block.getFieldValue('pad_center'); - var ui_name_clean = ui_name.replace(' ', '_'); - var on_down_for = Blockly.Arduino.statementToCode(block, 'on_down_for'); - var on_up_for = Blockly.Arduino.statementToCode(block, 'on_up_for'); - var on_down_back = Blockly.Arduino.statementToCode(block, 'on_down_back'); - var on_up_back = Blockly.Arduino.statementToCode(block, 'on_up_back'); - var on_down_left = Blockly.Arduino.statementToCode(block, 'on_down_left'); - var on_up_left = Blockly.Arduino.statementToCode(block, 'on_up_left'); - var on_down_right = Blockly.Arduino.statementToCode(block, 'on_down_right'); - var on_up_right = Blockly.Arduino.statementToCode(block, 'on_up_right'); - var on_down_center = Blockly.Arduino.statementToCode(block, 'on_down_center'); - var on_up_center = Blockly.Arduino.statementToCode(block, 'on_up_center'); - Blockly.Arduino.definitions_['define_ui_pad_' + ui_name_clean] = - 'void pad_' + ui_name_clean + '(Control c, int type) {\n' + - ' switch(type){\n' + - ' case P_FOR_DOWN:\n' + - on_down_for + '\n break;\n' + - ' case P_FOR_UP:\n' + - on_up_for + '\n break;\n' + - - ' case P_BACK_DOWN:\n' + - on_down_back + '\n break;\n' + - ' case P_BACK_UP:\n' + - on_up_back + '\n break;\n' + - - ' case P_RIGHT_DOWN:\n' + - on_down_left + '\n break;\n' + - ' case P_RIGHT_UP:\n' + - on_up_left + '\n break;\n' + - - ' case P_LEFT_DOWN:\n' + - on_down_right + '\n break;\n' + - ' case P_LEFT_UP:\n' + - on_up_right + '\n break;\n' + - - ' case P_CENTER_DOWN:\n' + - on_down_center + '\n break;\n' + - ' case P_CENTER_UP:\n' + - on_up_center + '\n break;\n' + - ' }\n' + - '}\n'; - var code = ' ESPUI.pad("' + ui_name + '", ' + pad_center + ', &pad_' + ui_name_clean + ', ' + ui_color + ');\n'; - return code; -}; \ No newline at end of file diff --git a/watering/lib/ESPUI/LICENSE b/watering/lib/ESPUI/LICENSE deleted file mode 100644 index e70f533..0000000 --- a/watering/lib/ESPUI/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Lukas Bachschwell (s00500) -Authors: Lukas Bachschwell - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/watering/lib/ESPUI/README.md b/watering/lib/ESPUI/README.md deleted file mode 100644 index 8108829..0000000 --- a/watering/lib/ESPUI/README.md +++ /dev/null @@ -1,723 +0,0 @@ -# ESPUI - -![ESPUI](docs/ui_complete.png) - -ESPUI is a simple library to make a web-based user interface for your projects using -the **ESP8266** or the **ESP32** It uses web sockets and lets you create, - -ol, and update elements on your GUI through multiple devices like phones -and tablets. - -ESPUI uses simple Arduino-style syntax for creating a solid, functioning user -interface without too much boilerplate code. - -So if you either don't know how or just don't want to waste time: this is your -simple solution user interface without the need of internet connectivity or any -additional servers. - -The Library runs on any kind of **ESP8266** and **ESP32** (NodeMCU, AI Thinker, etc.). - -- [Dependencies](#dependencies) -- [How to Install](#how-to-install) -- [Getting started](#getting-started) -- [UI Elements](#documentation) - * [Button](#button) - * [Switch](#switch) - * [Buttonpad](#buttonpad) - * [Labels](#labels) - * [Slider](#slider) - * [Number Input](#number-input) - * [Text Input](#text-input) - * [File Display](#filedisplay) - * [Date, Time, Colour and Password Input](#date-time-colour-and-password-input) - * [Select control](#select-control) - * [Getting the Time](#getting-the-time) - * [Separators](#separators) -- [Initialisation of the UI](#initialisation-of-the-ui) -- [Tabs](#tabs) -- [Log output](#log-output) -- [Colours](#colours) -- [Advanced Features](#advanced-features) - * [Dynamic Visibility](#dynamic-visibility) - * [Inline Styles](#inline-styles) - * [Disabling Controls](#disabling-controls) - * [Grouped controls](#grouped-controls) - * [Wide controls](#wide-controls) - * [Graph (Experimental)](#graph--experimental-) - * [Captive Portal](#captive-portal) -- [Notes for Development](#notes-for-development) -- [Contribute](#contribute) - - -### Contributed features - -- Tabs by @eringerli -- Generic API by @eringerli -- Min Max on slider by @eringerli -- OptionList by @eringerli -- Public Access to ESPAsyncServer -- Inline CSS styles by @iangray001 -- Separators by @iangray001 -- Grouped and wide controls by @iangray001 -- Transport layer rework by @iangray001 -- Time control by @iangray001 -- Vertical controls by @iangray001 -- Time/date/password/color input types by @pcbbc -- Delayed response support @MartinMueller2003 -- Fragmented control transfer @MartinMueller2003 -- Extended Callback @MartinMueller2003 -- Added a file display element @MartinMueller2003 - -## Roadmap - -- Fully implement graphs -- Expand number input features (floats etc.) -- Support for enabling and disabling controls - -## Dependencies - -This library is dependent on the following libraries. - -- [ESPAsyncWebserver](https://github.com/me-no-dev/ESPAsyncWebServer) -- [ArduinoJson](https://github.com/bblanchon/ArduinoJson) (Last tested with - version 6.10.0) - -- (_For ESP8266_) [ESPAsyncTCP](https://github.com/me-no-dev/ESPAsyncTCP) -- (_For ESP32_) [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) -- (_For ESP32_) [lorol/LittleFS_esp32](https://github.com/lorol/LITTLEFS) - -## How to Install - -Make sure all the dependencies are installed, then install like so: - -#### Using PlatformIO (_recommended_) - -Just include this library as a dependency in `lib_deps` like so: - -``` -lib_deps = - ESPUI - ESP Async WebServer - ESPAsyncTCP # (or AsyncTCP on ESP32) - LittleFS_esp32 # (ESP32 only) -``` - -#### Using the Arduino IDE (_recommended_) - -You can find this Library in the Arduino IDE library manager. Go to -`Sketch > Include Library > Library Manager` search for `ESPUI` and install. - -If you cannot use the Library Manager, you can download the [repository](https://github.com/s00500/ESPUI/archive/master.zip) and follow -the [instructions to manually install libraries](https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use/how-to-install-a-library). - -## Getting started - -ESPUI serves several files to the browser to build up its web interface. This -can be achieved in 2 ways: _PROGMEM_ or _LITTLEFS_ - -_When `ESPUI.begin()` is called the default is serving files from Memory and -ESPUI should work out of the box!_ - -**OPTIONAL:** But if this causes your program to _use too much memory_ you can -burn the files into the LITTLEFS filesystem on the ESP. There are now two ways to -do this: you can either use the ESP file upload tool or you use the library -function `ESPUI.prepareFileSystem()` - -#### Simple filesystem preparation (_recommended_) - -Just open the example sketch **prepareFileSystem** and run it on the ESP, (give -it up to 30 seconds, you can see the status on the Serial Monitor), The library -will create all needed files. Congratulations, you are done, from now on you -just need to do this again when there is a library update, or when you want to -use another chip :-) Now you can upload your normal sketch, when you do not call -the `ESPUI.prepareFileSystem()` function the compiler will strip out all the -unnecessary strings that are already saved in the chip's filesystem and you have -more program memory to work with. - -## User interface Elements - -- Label -- Button -- Switch -- Control pad -- Slider -- Text Input -- Date, Time, Colour and Password Input -- Numberinput -- Option select -- Separator -- Time -- Graph (partial implementation) -- File Display - - -## Documentation - -The heart of ESPUI is [ESPAsyncWebserver](https://github.com/me-no-dev/ESPAsyncWebServer). ESPUI's frontend is based on [Skeleton CSS](http://getskeleton.com/) and jQuery-like lightweight [zepto.js](https://zeptojs.com/) for handling events. The communication between the ESP and the client browser works using web sockets. ESPUI does not need network access and can be used in standalone access point mode, all resources are loaded directly from the ESPs memory. -

-This section will explain in detail how the Library is to be used from the Arduino code side. In the arduino `setup()` routine the interface can be customised by adding UI Elements. This is done by calling the corresponding library methods on the Library object `ESPUI`. Eg: `ESPUI.button("button", &myCallback);` creates a button in the interface that calls the `myCallback(Control *sender, int eventname)` function when changed. All buttons and items call their callback whenever there is a state change from them. This means the button will call the callback when it is pressed and also again when it is released. To separate different events, an integer number with the event name is passed to the callback function that can be handled in a `switch(){}case{}` statement. -

-Alternativly you may use the extended callback funtion which provides three parameters to the callback function `myCallback(Control *sender, int eventname, void * UserParameter)`. The `UserParameter` is provided as part of the `ESPUI.addControl` method set and allows the user to define contextual information that is to be presented to the callback function in an unmodified form. -

-It also possible to use a lambda function in the callback parameter. It also allows the user to define, in a more C++ way, contextual information in any form. This is shown by the [completeLambda](examples/completeLambda/completeLambda.ino) example. -

-The below example creates a button and defines a lambda function to invoke a more specialized button callback handler: -``` -void YourClassName::setup() -{ - ButtonElementId = ESPUI.addControl( - ControlType::Button, - ButtonLabel.c_str(), - " Button Face Text ", - ControlColor::None, - ParentElementId, - [&](Control *sender, int eventname) - { - myButtonCallback(sender, eventname); // class method - }); - - // or - ButtonElementId = ESPUI.button( - " Button Face Text ", - [&](Control *sender, int eventname) - { - myButtonCallback(sender, eventname); // class method - }); -} -``` -``` -void YourClassName::myButtonCallback(Control* sender, int eventname) -{ - if (eventname == B_DOWN) - { - // Handle the button down event - } - else if (eventname == B_UP) - { - // Handle the button up event - } -} -``` -
-
-#### Button - -![Buttons](docs/ui_button.png) - -Buttons have a name and a callback value. Their text can be changed at runtime using `ESPUI.updateButton()`. - -Events: -- `B_DOWN` - Fired when button is pressed. -- `B_UP` - Fired when button is released. - -#### Switch - -![Switches](docs/ui_switches.png) - -Switches sync their state on all connected devices. This means when you change -their value (either by pressing them, or programmatically using `ESPUI.updateSwitcher()`) they change visibly -on all tablets or computers that currently display the interface. - -Events: -- `S_ACTIVE` - Fired when turning on. -- `S_INACTIVE` - Fired when turning off. - -#### Buttonpad - -![control pads](docs/ui_controlpad.png) - -Button pads come in two flavours: with or without a center button. They are -useful for controlling movements of vehicles/cameras etc. They use a single -callback per pad and have 8 or 10 different event types to differentiate the -button actions. - -- `P_LEFT_DOWN` -- `P_LEFT_UP` -- `P_RIGHT_DOWN` -- `P_RIGHT_UP` -- `P_FOR_DOWN` -- `P_FOR_UP` -- `P_BACK_DOWN` -- `P_BACK_UP` -- `P_CENTER_DOWN` -- `P_CENTER_UP` - -#### Labels - -![labels](docs/ui_labels.png) - -Labels are used to display textual information (i.e. states, values of sensors, -configuration parameters etc.). To send data from the code use `ESP.updateLabel()` . -Labels get a name on creation and a initial value. - -Labels automatically wrap your text. If you want them to have multiple lines use -the normal `
` tag in the string you print to the label. - -In fact, because HTML can be used in the label's value, you can make a label display -images by including an `` tag. - -``` - ESPUI.label("An Image Label", ControlColor::Peterriver, ""); -``` - -This requires that the client has access to the image in question, either from the internet or a local web server. - - -#### Slider - -![slider](docs/ui_slider.png) - -Sliders can be used to select (or display) a numerical value. Sliders provide -realtime data and are touch compatible. Note that like all ESPUI functions, the callback does not return an `int` -but a `String` so should be converted with the `.toInt()` function. See the examples for more details. Sliders can -be updated from code using `ESP.updateSlider()`. - -A slider usually only sends a new value when it is released to save network bandwidth. -This behaviour can be changed globally by setting `sliderContinuous` before `begin()`: - -``` -ESPUI.sliderContinuous = true; -ESPUI.begin("ESPUI Control"); -``` - -Events: - - `SL_VALUE` - Fired when a slider value changes. - -#### Number Input - -![number](docs/ui_number.png) - -The number input can be used to receive numbers from the user. You can -enter a value into it and when you are done with your change it is sent to the -ESP. A number box needs to have a min and a max value. To set it up just use: - -`ESPUI.number("Numbertest", &numberCall, ControlColor::Alizarin, 5, 0, 10);` - -Number inputs can be updated from code using `ESP.updateNumber()`. - -Note that HTML number boxes will respect their min and max when the user -clicks the up and down arrows, but it is possible on most clients to simply type -any number in. As with all user input, numbers should be validated in callback code -because all client side checks can be skipped. If any value from the UI might -cause a problem, validate it. - -Events: - - `N_VALUE` - Fired when a number value changes. - - -#### Text Input - -![text](docs/ui_text.png) - -The text input works very similar like the number input but allows any string to be entered. -If you attach a Max control to the text input then a max length will be applied -to the control. - -``` -text = ESPUI.text("Label", callback, ControlColor::Dark, "Initial value"); -ESPUI.addControl(ControlType::Max, "", "32", ControlColor::None, text); -``` - -Text inputs can be updated from code using `ESP.updateText()`. - -However even with a set maximum length, user input should still be validated -because it is easy to bypass client-side checks. Never trust user input. - -Events: - - `T_VALUE` - Fired when a text value changes. - - -#### Date, Time, Colour and Password Input - -![text](docs/ui_inputtypes.png) - -As an extension to the text input control, you can also specify the type attribute to be used for the HTML input element. -This allows you to easily create input controls for Date, Time, Colour and Passwords, or indeed any other -[HTML Input Types](https://www.w3schools.com/html/html_form_input_types.asp) supported by your browser. - -``` -text_date = ESPUI.text("Date", callback, ControlColor::Dark, "2022-05-24"); -ESPUI.setInputType(text_date, "date"); - -text_time = ESPUI.text("Time", callback, ControlColor::Dark, "13:00"); -ESPUI.setInputType(text_time, "time"); - -text_colour = ESPUI.text("Colour", callback, ControlColor::Dark, "#FF0000"); -ESPUI.setInputType(text_colour, "color"); - -text_password = ESPUI.text("Password", callback, ControlColor::Dark, "tiddles123"); -ESPUI.setInputType(text_password, "password"); -``` - -*Important!* This function should be called _before_ `ESPUI.begin` or results will be unreliable. - -Note that not all browsers support all input types, and that the control displayed to edit the input is browser dependent. - -However even with a type set, user input should still be validated -because it is easy to bypass client-side checks. Never trust user input. - - -#### File Display - -![filedisplay](docs/ui_fileDisplay.png) - -The File Display control is used to upload a file from the ESP file system and display the contents on the UI. The content is Auto Scrolled -to the last line in the file. Syntax: - -`fileDisplayId = ESPUI.fileDisplay("Filetest", ControlColor::Turquoise, FullyQualified FilePath);` - -After updating the contents of the file, trigger a display update using: -`ESPUI.updateControl(fileDisplayId);` - - -#### Select control - -![option1](docs/ui_select1.png) -![option2](docs/ui_select2.png) - -The Select control lets the user select from a predefined list of options. First create a select widget like so - -``` -uint16_t select1 = ESPUI.addControl( ControlType::Select, "Select Title", "Initial Value", ControlColor::Alizarin, tab1, &selectExample ); -``` - -Then add Options to it, specifying the Select as the parent: - -``` -ESPUI.addControl( ControlType::Option, "Option1", "Opt1", ControlColor::Alizarin, select1); -ESPUI.addControl( ControlType::Option, "Option2", "Opt2", ControlColor::Alizarin, select1); -ESPUI.addControl( ControlType::Option, "Option3", "Opt3", ControlColor::Alizarin, select1); -``` - -Check the **tabbedGui** example for a working demo. Selectors can be updated from code using `ESP.updateSelect()`. - -Events: - - `S_VALUE` - Fired when a select value changes. - -#### Getting the Time - -ESPUI can create an invisible control that can be used to fetch the current time from the client -when they are connected to the UI. This could be used to intermittently provide an accurate time -source to your ESP. Remember that clients cannot be relied upon to be correct or truthful. - -Create a Time control with the following: - -``` -//Add the invisible "Time" control -auto timeId = ESPUI.addControl(Time, "", "", None, 0, timeCallback); -``` - -After creating the UI, sending an update to the Time control will cause it to fetch the current -time from the client and then fire its callback with the result. - -``` -//Request an update to the time -ESPUI.updateTime(timeId); -//Will trigger timeCallback -``` - -In `timeCallback` you can then print the control's value as normal: - -``` -void timeCallback(Control *sender, int type) { - if(type == TM_VALUE) { - Serial.println(sender->value); - } -} -``` - -The returned string will be an [ISO string](https://www.w3schools.com/jsref/jsref_toisostring.asp) as returned by the Javascript `new Date().toISOString()`. The format is `YYYY-MM-DDTHH:mm:ss.sssZ` so for example: `2022-01-20T21:44:22.913Z`. - -Events: - - `TM_VALUE` - Fires when the control is updated with `updateTime()` - -#### Separators - -![separators](docs/ui_separators.png) - -You can use separators to break up the UI and better organise your controls. Adding a separator will force any following controls onto the subsequent line. Add separators as follows: - -``` -ESPUI.separator("Separator name"); -//or -ESPUI.addControl(ControlType::Separator, "Separator name", "", ControlColor::None, maintab); -``` - -Separators fire no events. - -### Initialisation of the UI - -After all the elements are configured, call `ESPUI.begin("Some Title");` -to start the UI interface. (Or `ESPUI.beginLITTLEFS("Some Title");` respectively) -Make sure you setup a working network connection or AccessPoint **before** (see -the `gui.ino` example). The web interface can then be used from multiple devices at once and -also shows connection status in the top bar. - - - -### Tabs - -![tabs](docs/ui_tabs.png) - -Tabs can be used to organize your controls into pages. Check the **tabbedGui** example to see -how this is done. Tabs can be created as follows: - -``` -ESPUI.addControl(ControlType::Tab, "Settings 1", "Settings 1"); -``` - -Then all widgets for the tab need to be added to it by specifying the tab as the parent. Widgets not -added to a tab will be shown above the tab selctor. - -``` -ESPUI.addControl(ControlType::Text, "Text Title", "a Text Field", ControlColor::Alizarin, tab1, &textCall); -``` - -Note that the basic functions to add controls like `ESPUI.button()` or `ESPUI.slider()` do not add to any tab, -so they are good for building small UIs. However if you need to use tabs then you will have to add all your -controls using the full `ESPUI.addControl()` function. - - - -### Log output - -ESPUI has several different log levels. You can set them using the -`ESPUI.setVerbosity(Verbosity::VerboseJSON)` function. - -Loglevels are: - -- `Verbosity::Quiet` (default) -- `Verbosity::Verbose` -- `Verbosity::VerboseJSON` - -VerboseJSON outputs the most debug information. - -### Colours - -A selection of basic colours are available to use: - -![Colours](docs/ui_colours.png) - -If you want more control over the UI design, see the Inline Styles section below. - - -## Advanced Features - -ESPUI includes a range of advanced features that can customise your UIs. - - -### Dynamic Visibility - -Controls can be made visible or invisible at runtime with the `updateVisibility()` function. - -``` -ESPUI.updateVisibility(controlId, false); -``` - -Note that you cannot hide individual controls from a [control group](#grouped-controls), you have to hide the entire group. - - -### Inline Styles - -You can add custom CSS styles to controls. This allows you to style the UI with custom colors, drop shadows, -or other CSS effects. Add styles with the following functions: - -``` -setPanelStyle(uint16_t id, String style); -setElementStyle(uint16_t id, String style) -``` - -A panel style is applied to the panel on which the UI element is placed, an element style is applied to the element itself. -Because CSS inline styles can only style one specific DOM element, for controls made up of multiple elements (like the pad) -this is limited. Element styles can be applied to all controls, but will only work correctly for the Button, Label, Slider, -Switcher, Number, Text, and Selector. - -Dynamic update of styles is supported. When either of the above functions are called, the control is updated live. This could -be used to refect a warning state by changing the color of a button, or for similar effects. - -For example, this code will set a control's panel to a random background color: - -``` -char stylecol[30]; -sprintf(stylecol, "background-color: #%06X;", (unsigned int) random(0x0, 0xFFFFFF)); -ESPUI.setPanelStyle(switch1, stylecol); -``` - -You can get quite creative with this. - -![Inline Styles](docs/inlinestyles.gif) - -The [completeExample](examples/completeExample/completeExample.cpp) example includes a range of things that you can do with inline styles. - -![More Inline Styles](docs/ui_inlinestyles2.png) - - -### Disabling Controls - -It is possible to dynamically enable and disable controls to, for example, provide feedback to the user that a particular feature is -temporarily unavailable. To do this use the following function call: - -``` -ESPUI.setEnabled(controlId, enabled); -``` - -Setting `enabled` to false will make the control noninteractive and it will visually change to illustrate this to the user. The control -will stop firing any events. Note that whilst the widget will change appearance, the panel of the control will remain whatever colour -it was set to. If you wish to also change the colour of the panel then you should use inline styles to show the noninteractive state. For example: - -``` -ESPUI.setEnabled(mainButton, false); -const String disabledstyle = "background-color: #bbb; border-bottom: #999 3px solid;"; -ESPUI.setPanelStyle(mainButton, disabledstyle); -``` - -This CSS style sets the panel background and its border to grey. To put the control back to enabled use the following: - -``` -ESPUI.setEnabled(mainButton, true); -ESPUI.setPanelStyle(mainButton, ";"); -``` - -Note that we have to set the inline style to `";"` (i.e. an empty CSS rule) because if we just try to set it to `""` this will be -interpreted as "do not change the style". - -Controls can also be set to disabled before the UI is started. - -### Grouped controls - -Normally, whenever a control is added to the UI, a new panel is generated with a title. However, you can instead -set the "parent" of a new control to be an existing control. This allows you to add multiple widgets into the same -panel. For example: - -``` -panel1 = ESPUI.addControl(ControlType::Button, "Button Set", "Button A", ControlColor::Turquoise, Control::noParent, btncallback); -ESPUI.addControl(ControlType::Button, "", "Button B", ControlColor::None, panel1, btncallback); -ESPUI.addControl(ControlType::Button, "", "Button C", ControlColor::None, panel1, btncallback); -``` - -The first call to `addControl` has no parent (or it could be set to a tab if you are using a tabbed UI), so therefore a new panel is added containing one button -with the value `Button A`. The two subsequent calls have their parent set to the first control we added, so instead of creating -a new panel, the result is the following: - -![Grouped buttons](docs/ui_groupedbuttons.png) - -The grouped controls operate entirely independently, and can be assigned different callbacks, or updated separately. The grouping -is purely visual. - -Most controls can be grouped this way, but the result is not always visually pleasant. This works best with labels, sliders, switchers, -and buttons. - -![Other grouped controls](docs/ui_groupedbuttons2.png) - -For sliders and switchers, you can also set the controls to be displayed vertically. - -``` -auto vertswitcher = ESPUI.addControl(Switcher, "Vertical Switcher", "0", Dark, tab1); -ESPUI.setVertical(vertswitcher); -``` - -This must be done before `ESPUI.begin()` is called. Vertical layouts are currently only supported for sliders and switchers, and it -is a purely visual change. Behaviour is identical. Mixing horizontal and vertical controls can result in some unpredictable layouts. - -When you add multiple buttons to a single panel, the buttons have a title so they can be differentiated. For sliders and switchers this is -not the case. Therefore you might want to add additional labels so that the controls can be distinguished. There is not yet automatic -support for doing this, so the approach is to add labels that have been styled using [inline styles](#inline-styles). By doing this -you can acheieve effects such as this: - -![Labelling grouped controls](docs/ui_groupedbuttons3.png) - -The code to do this is in the [completeExample](examples/completeExample/completeExample.cpp) example. - -### Wide controls - -Controls can be set to be displayed "wide" with the function: - -``` -ESPUI.setPanelWide(controlid, true); -``` - -*Important!* This function should be called _before_ `ESPUI.begin` or results will be unreliable. - -Setting a control to wide tells ESPUI to lay out that control as if there was only a single column, even on wide displays. -This can be applied to every element to force a single column layout, or to individual elements to customise the display. - -![Wide controls](docs/ui_widecontrols.png) - -Note that this will have no effect on small screens. - - -### Graph (Experimental) - -![graph](docs/ui_graph.png) - -The graph widget can display graph points with timestamp at wich they arrive - -Use `ESPUI.addGraphPoint(graphId, random(1, 50));` to add a new value at the current time, use `ESPUI.clearGraph(graphId)` to clear the entire graph. -Graph points are saved in the browser in **localstorage** to be persistant, clear local storageto remove the points or use clearGraph() from a bbutton callback to provide a clear button. - -_There are many issues with the graph component currently and work is ongoing. Consider helping us out with development!_ - -### Captive Portal - -ESPUI will redirect all unknown URLs it is asked for to the 'root' of the local HTTP server instead of responding with an HTTP code 404. This makes it act as a simple 'captive portal'. Note you must also set up the ESP to be a DNS server that responds to all DNS requests with the IP address of the ESP. This only effective when the ESP is acting as a WiFi hotspot in AP mode and assigning itself as the DNS server to connected clients. - -All the example sketches include the DNS related code and will work as captive portals when used as a hotspot. In the event you wish to disable this feature you can do so by removing the DNS server code and adding the code below. - -``` -ESPUI.captivePortal = false; -``` - - -# Notes for Development - -If you want to work on the HTML/CSS/JS files, do make changes in the _data_ -directory. When you need to transfer that code to the ESP, run -`tools/prepare_static_ui_sources.py -a` (this script needs **python3** with the -modules **htmlmin**, **jsmin** and **csscompressor**). This will generate a) minified files -next to the original files and b) the C header files in `src` that contain the minified and -gzipped HTML/CSS/JS data. Alternatively, you can specify the `--source` and `--target` arguments to the -`prepare_static_ui_sources.py` script (run the script without arguments for -help) if you want to use different locations. - -If you don't have a python environment, you need to minify and gzip the -HTML/CSS/JS files manually. I wrote a little useful jsfiddle for this, -[see here](https://jsfiddle.net/s00500/yvLbhuuv/). - -If you change something in HTML/CSS/JS and want to create a pull request, please -do include the minified versions and corresponding C header files in your -commits. (Do **NOT** commit all the minified versions for the non changed files) - -# Experimental debugging environment using emulation on host - -It is possible to run or debug this library on a unix-like computer (Linux, -macOS, WSL) without flashing on hardware, and with your favourite debugging -tools (gdb, valgrind, ...). This is accomplished through the -esp8266/Arduino "emulation on host" environment. - -A fake AsyncWebserver library is needed because lwIP is not yet ported to -the emulation environment. Full instructions can be found in this project's -[readme page](https://github.com/d-a-v/emuAsync). - -## Changelog for 2.1: - - - Adds the ability to have inline styles for widgets and panels - - Adds LittleFS on the ESP32 - - Cleans up examples - - Adds Button Animation - - Adds chunking for the widgets so you can add even more of them - - Fixes lots of bugs related to invisible UI elements and sliders - - Adds the ability to change port - -## Changelog for 2.0: - -- ArduinoJSON 6.10.0 Support -- Split pad into pad and padWithCenter -- Cleaned order of parameters on switch and pad -- Changes all numbers to actually be numbers (slider value, number value, min and max) - -# Contribute - -Liked this Library? You can **support** me by sending me a :coffee: -[Coffee](https://paypal.me/lukasbachschwell/5). - -Otherwise I really welcome **Pull Requests**. diff --git a/watering/lib/ESPUI/data/css/normalize.css b/watering/lib/ESPUI/data/css/normalize.css deleted file mode 100644 index 3b301cb..0000000 --- a/watering/lib/ESPUI/data/css/normalize.css +++ /dev/null @@ -1,246 +0,0 @@ - html { - font-family: sans-serif; /* 1 */ - -ms-text-size-adjust: 100%; /* 2 */ - -webkit-text-size-adjust: 100%; /* 2 */ - } - - body { - margin: 0; - } - - /* HTML5 display definitions - ========================================================================== */ - - article, - aside, - details, - figcaption, - figure, - footer, - header, - hgroup, - main, - menu, - nav, - section, - summary { - display: block; - } - - audio, - canvas, - progress, - video { - display: inline-block; /* 1 */ - vertical-align: baseline; /* 2 */ - } - - audio:not([controls]) { - display: none; - height: 0; - } - - [hidden], - template { - display: none; - } - - /* Links - ========================================================================== */ - - a { - background-color: transparent; - } - - a:active, - a:hover { - outline: 0; - } - - /* Text-level semantics - ========================================================================== */ - - abbr[title] { - border-bottom: 1px dotted; - } - - b, - strong { - font-weight: bold; - } - - dfn { - font-style: italic; - } - - h1 { - font-size: 2em; - margin: 0.67em 0; - } - - mark { - background: #ff0; - color: #000; - } - - small { - font-size: 80%; - } - - sub, - sup { - font-size: 75%; - line-height: 0; - position: relative; - vertical-align: baseline; - } - - sup { - top: -0.5em; - } - - sub { - bottom: -0.25em; - } - - /* Embedded content - ========================================================================== */ - - img { - border: 0; - } - - svg:not(:root) { - overflow: visible; - } - - /* Grouping content - ========================================================================== */ - - figure { - margin: 1em 40px; - } - - hr { - -moz-box-sizing: content-box; - box-sizing: content-box; - height: 0; - } - - pre { - overflow: auto; - } - - code, - kbd, - pre, - samp { - font-family: monospace, monospace; - font-size: 1em; - } - - button, - input, - optgroup, - select, - textarea { - color: inherit; /* 1 */ - font: inherit; /* 2 */ - margin: 0; /* 3 */ - } - - button { - overflow: visible; - } - - button, - select { - text-transform: none; - } - - button, - html input[type="button"], /* 1 */ - input[type="reset"], - input[type="submit"] { - -webkit-appearance: button; /* 2 */ - cursor: pointer; /* 3 */ - } - - button[disabled], - html input[disabled] { - cursor: default; - } - - button::-moz-focus-inner, - input::-moz-focus-inner { - border: 0; - padding: 0; - } - - input { - line-height: normal; - } - - input[type="checkbox"], - input[type="radio"] { - box-sizing: border-box; /* 1 */ - padding: 0; /* 2 */ - } - - input[type="number"]::-webkit-inner-spin-button, - input[type="number"]::-webkit-outer-spin-button { - height: auto; - } - - input[type="search"] { - -webkit-appearance: textfield; /* 1 */ - -moz-box-sizing: content-box; - -webkit-box-sizing: content-box; /* 2 */ - box-sizing: content-box; - } - - input[type="search"]::-webkit-search-cancel-button, - input[type="search"]::-webkit-search-decoration { - -webkit-appearance: none; - } - - fieldset { - border: 1px solid #c0c0c0; - margin: 0 2px; - padding: 0.35em 0.625em 0.75em; - } - - /** - * 1. Correct `color` not being inherited in IE 8/9/10/11. - * 2. Remove padding so people aren't caught out if they zero out fieldsets. - */ - - legend { - border: 0; /* 1 */ - padding: 0; /* 2 */ - } - - textarea { - overflow: auto; - } - - /** - * Don't inherit the `font-weight` (applied by a rule above). - * NOTE: the default cannot safely be changed in Chrome and Safari on OS X. - */ - - optgroup { - font-weight: bold; - } - - /* Tables - ========================================================================== */ - table { - border-collapse: collapse; - border-spacing: 0; - } - - td, - th { - padding: 0; - } diff --git a/watering/lib/ESPUI/data/css/normalize.min.css b/watering/lib/ESPUI/data/css/normalize.min.css deleted file mode 100644 index 344cf9c..0000000 --- a/watering/lib/ESPUI/data/css/normalize.min.css +++ /dev/null @@ -1 +0,0 @@ -html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:visible}figure{margin:1em 40px}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:bold}table{border-collapse:collapse;border-spacing:0}td,th{padding:0} \ No newline at end of file diff --git a/watering/lib/ESPUI/data/css/style.css b/watering/lib/ESPUI/data/css/style.css deleted file mode 100644 index f5d46f7..0000000 --- a/watering/lib/ESPUI/data/css/style.css +++ /dev/null @@ -1,1200 +0,0 @@ -.container { - position: relative; - width: 79%; - margin: 20px; - box-sizing: border-box; -} - -.column, -.columns { - width: 100%; - float: left; -} - -.card { - min-height: 100px; - border-radius: 6px; - box-shadow: 0 4px 4px rgba(204, 197, 185, 0.5); - padding-left: 20px; - padding-right: 20px; - margin-bottom: 40px; - min-width: 500px; - color: #fff; -} - - -@media (min-width: 1205px) { - .wide.card { - min-width: 1075px; - } -} - -@media (min-width: 1790px) { - .wide.card { - min-width: 1650px; - } -} - -@media (max-width: 630px) { - .card { - min-width: 98%; - } -} - -.sectionbreak.columns { - color: black; -} - -.sectionbreak.columns hr { - border: none; - height: 2px; - background-color: #666 -} - -.card-slider {} - -.turquoise { - background: #1abc9c; - border-bottom: #16a085 3px solid; -} - -.emerald { - background: #2ecc71; - border-bottom: #27ae60 3px solid; -} - -.peterriver { - background: #3498db; - border-bottom: #2980b9 3px solid; -} - -.wetasphalt { - background: #34495e; - border-bottom: #2c3e50 3px solid; -} - -.sunflower { - background: #f1c40f; - border-bottom: #e6bb0f 3px solid; -} - -.carrot { - background: #e67e22; - border-bottom: #d35400 3px solid; -} - -.alizarin { - background: #e74c3c; - border-bottom: #c0392b 3px solid; -} - -.dark { - background: #444857; - border-bottom: #444857 3px solid; -} - -.label { - box-sizing: border-box; - white-space: nowrap; - border-radius: 0.2em; - padding: 0.12em 0.4em 0.14em; - text-align: center; - color: #ffffff; - font-weight: 700; - line-height: 1.3; - margin-bottom: 5px; - display: inline-block; - white-space: nowrap; - vertical-align: baseline; - position: relative; - top: -0.15em; - background-color: #999999; - margin-bottom: 10px; -} - -.label-wrap { - width: 90%; - white-space: pre-wrap; - word-wrap: break-word; -} - -.label.color-blue { - background-color: #6f9ad1; -} - -.label.color-red { - background-color: #d37c7c; -} - -.label.color-green { - background-color: #9bc268; -} - -.label.color-orange { - background-color: #dea154; -} - -.label.color-yellow { - background-color: #e9d641; -} - -.label.color-purple { - background-color: #9f83d1; -} - -/* For devices larger than 400px */ - -@media (min-width: 400px) { - .container { - width: 84%; - } -} - -/* For devices larger than 550px */ - -@media (min-width: 630px) { - .container { - width: 98%; - } - - .column, - .columns { - margin-right: 35px; - } - - .column:first-child, - .columns:first-child { - margin-left: 0; - } - - .one.column, - .one.columns { - width: 4.66666666667%; - } - - .two.columns { - width: 13.3333333333%; - } - - .three.columns { - width: 22%; - } - - .four.columns { - width: 30.6666666667%; - } - - .five.columns { - width: 39.3333333333%; - } - - .six.columns { - width: 48%; - } - - .seven.columns { - width: 56.6666666667%; - } - - .eight.columns { - width: 65.3333333333%; - } - - .nine.columns { - width: 74%; - } - - .ten.columns { - width: 82.6666666667%; - } - - .eleven.columns { - width: 91.3333333333%; - } - - .twelve.columns { - width: 100%; - margin-left: 0; - } - - .one-third.column { - width: 30.6666666667%; - } - - .two-thirds.column { - width: 65.3333333333%; - } - - .one-half.column { - width: 48%; - } - - /* Offsets */ - .offset-by-one.column, - .offset-by-one.columns { - margin-left: 8.66666666667%; - } - - .offset-by-two.column, - .offset-by-two.columns { - margin-left: 17.3333333333%; - } - - .offset-by-three.column, - .offset-by-three.columns { - margin-left: 26%; - } - - .offset-by-four.column, - .offset-by-four.columns { - margin-left: 34.6666666667%; - } - - .offset-by-five.column, - .offset-by-five.columns { - margin-left: 43.3333333333%; - } - - .offset-by-six.column, - .offset-by-six.columns { - margin-left: 52%; - } - - .offset-by-seven.column, - .offset-by-seven.columns { - margin-left: 60.6666666667%; - } - - .offset-by-eight.column, - .offset-by-eight.columns { - margin-left: 69.3333333333%; - } - - .offset-by-nine.column, - .offset-by-nine.columns { - margin-left: 78%; - } - - .offset-by-ten.column, - .offset-by-ten.columns { - margin-left: 86.6666666667%; - } - - .offset-by-eleven.column, - .offset-by-eleven.columns { - margin-left: 95.3333333333%; - } - - .offset-by-one-third.column, - .offset-by-one-third.columns { - margin-left: 34.6666666667%; - } - - .offset-by-two-thirds.column, - .offset-by-two-thirds.columns { - margin-left: 69.3333333333%; - } - - .offset-by-one-half.column, - .offset-by-one-half.columns { - margin-left: 52%; - } -} - -/* Base Styles - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -html { - font-size: 62.5%; -} - -body { - margin: 0; - font-size: 1.5em; - line-height: 1; - font-weight: 400; - font-family: "Open Sans", sans-serif; - color: #222; - background-color: #ecf0f1; -} - -/* Typography - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -h1, -h2, -h3, -h4, -h5, -h6 { - margin-top: 0; - margin-bottom: 0.5rem; - font-weight: 300; -} - -h1 { - font-size: 4rem; - line-height: 1.2; - letter-spacing: -0.1rem; -} - -h2 { - font-size: 3.6rem; - line-height: 1.25; - letter-spacing: -0.1rem; -} - -h3 { - font-size: 3rem; - line-height: 1.3; - letter-spacing: -0.1rem; -} - -h4 { - font-size: 2.4rem; - line-height: 1.35; - letter-spacing: -0.08rem; -} - -h5 { - font-size: 1.8rem; - line-height: 1.5; - letter-spacing: -0.05rem; -} - -h6 { - font-size: 1.5rem; - line-height: 1.6; - letter-spacing: 0; -} - -/* Larger than phablet */ - -@media (min-width: 630px) { - h1 { - font-size: 5rem; - } - - h2 { - font-size: 4.2rem; - } - - h3 { - font-size: 3.6rem; - } - - h4 { - font-size: 3rem; - } - - h5 { - font-size: 2rem; - } - - h6 { - font-size: 1.5rem; - } -} - -p { - margin-top: 0; -} - -/* Links - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -a { - color: #1eaedb; -} - -a:hover { - color: #0fa0ce; -} - -/* Buttons - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -button { - display: inline-block; - padding: 10px; - border-radius: 3px; - color: #fff; - background-color: #999999; -} - -button:enabled:active { - background-color: #666666; - transform: translateX(4px) translateY(4px); -} - -/* Main Head Part - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -#mainHeader { - display: inline-block; -} - -#conStatus { - position: inherit; - font-size: 0.75em; -} - -/* Spacing - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -button, -.button { - margin-bottom: 1rem; - margin-left: 0.3rem; - margin-right: 0.3rem; -} - -/* Utilities - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -.u-full-width { - width: 100%; - box-sizing: border-box; -} - -.u-max-full-width { - max-width: 100%; - box-sizing: border-box; -} - -.u-pull-right { - float: right; -} - -.u-pull-left { - float: left; -} - -.tcenter { - text-align: center; -} - -/* Misc - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -hr { - margin-top: 0.5rem; - margin-bottom: 1.2rem; - border-width: 0; - border-top: 1px solid #e1e1e1; -} - -/* Clearing - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -/* Self Clearing Goodness */ - -.container:after, -.row:after, -.u-cf { - content: ""; - display: table; - clear: both; -} - -/* ButtonPad - –––––––––––––––––––––––––––––––––––––––––––––––––– */ - -.control { - background-color: #ddd; - background-image: linear-gradient(hsla(0, 0%, 0%, 0.1), - hsla(0, 0%, 100%, 0.1)); - border-radius: 50%; - box-shadow: inset 0 1px 1px 1px hsla(0, 0%, 100%, 0.5), - 0 0 1px 1px hsla(0, 0%, 100%, 0.75), 0 0 1px 2px hsla(0, 0%, 100%, 0.25), - 0 0 1px 3px hsla(0, 0%, 100%, 0.25), 0 0 1px 4px hsla(0, 0%, 100%, 0.25), - 0 0 1px 6px hsla(0, 0%, 0%, 0.75); - height: 9em; - margin: 3em auto; - position: relative; - width: 9em; -} - -.control ul { - height: 100%; - padding: 0; - transform: rotate(45deg); -} - -.control li { - border-radius: 100% 0 0 0; - box-shadow: inset -1px -1px 1px hsla(0, 0%, 100%, 0.5), - 0 0 1px hsla(0, 0%, 0%, 0.75); - display: inline-block; - height: 50%; - overflow: hidden; - width: 50%; -} - -.control ul li:nth-child(2) { - transform: rotate(90deg); -} - -.control ul li:nth-child(3) { - transform: rotate(-90deg); -} - -.control ul li:nth-child(4) { - transform: rotate(180deg); -} - -.control ul a { - height: 200%; - position: relative; - transform: rotate(-45deg); - width: 200%; -} - -.control a:hover, -.control a:focus { - background-color: hsla(0, 0%, 100%, 0.25); -} - -.control a { - border-radius: 50%; - color: #333; - display: block; - font: bold 1em/3 sans-serif; - text-align: center; - text-decoration: none; - text-shadow: 0 1px 1px hsla(0, 0%, 100%, 0.4); - transition: 0.15s; -} - -.control .confirm { - background-color: #ddd; - background-image: linear-gradient(hsla(0, 0%, 0%, 0.15), - hsla(0, 0%, 100%, 0.25)); - box-shadow: inset 0 1px 1px 1px hsla(0, 0%, 100%, 0.5), - 0 0 1px 1px hsla(0, 0%, 100%, 0.25), 0 0 1px 2px hsla(0, 0%, 100%, 0.25), - 0 0 1px 3px hsla(0, 0%, 100%, 0.25), 0 0 1px 4px hsla(0, 0%, 100%, 0.25), - 0 0 1px 6px hsla(0, 0%, 0%, 0.85); - left: 50%; - line-height: 3; - margin: -1.5em; - position: absolute; - top: 50%; - width: 3em; -} - -.control .confirm:hover, -.control .confirm:focus { - background-color: #eee; -} - -.control:not(.disabled) a.confirm:active { - background-color:#777 -} -.control:not(.disabled) li:active { - background-color:#777 -} - -/* Switch -–––––––––––––––––––––––––––––––––––––––––––––––––– */ - -.switch { - display: inline-block !important; - background-color: #bebebe; - border-radius: 4px; - box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); - color: #fff; - cursor: pointer; - display: block; - font-size: 14px; - height: 26px; - margin-left: 0.3rem; - margin-right: 0.3rem; - position: relative; - width: 60px; - -webkit-transition: background-color 0.2s ease-in-out; - -moz-transition: background-color 0.2s ease-in-out; - -o-transition: background-color 0.2s ease-in-out; - -ms-transition: background-color 0.2s ease-in-out; - transition: background-color 0.2s ease-in-out; -} - -.switch.checked { - background-color: #76d21d; -} - -.switch input[type="checkbox"] { - display: none; - cursor: pointer; - height: 10px; - left: 12px; - position: absolute; - top: 8px; - width: 10px; -} - -.in { - position: absolute; - top: 8px; - left: 12px; - -webkit-transition: left 0.08s ease-in-out; - -moz-transition: left 0.08s ease-in-out; - -o-transition: left 0.08s ease-in-out; - -ms-transition: left 0.08s ease-in-out; - transition: left 0.08s ease-in-out; -} - -.switch.checked div { - left: 38px; -} - -.switch .in:before { - background: #fff; - background: -moz-linear-gradient(top, #fff 0%, #f0f0f0 100%); - background: -webkit-gradient(linear, - left top, - left bottom, - color-stop(0%, #fff), - color-stop(100%, #f0f0f0)); - background: -webkit-linear-gradient(top, #fff 0%, #f0f0f0 100%); - background: -o-linear-gradient(top, #fff 0%, #f0f0f0 100%); - background: -ms-linear-gradient(top, #fff 0%, #f0f0f0 100%); - background: linear-gradient(to bottom, #fff 0%, #f0f0f0 100%); - border: 1px solid #fff; - border-radius: 2px; - box-shadow: 0 0 4px rgba(0, 0, 0, 0.3); - content: ""; - height: 18px; - position: absolute; - top: -5px; - left: -9px; - width: 26px; -} - -.switch .in:after { - background: #f0f0f0; - background: -moz-linear-gradient(top, #f0f0f0 0%, #fff 100%); - background: -webkit-gradient(linear, - left top, - left bottom, - color-stop(0%, #f0f0f0), - color-stop(100%, #fff)); - background: -webkit-linear-gradient(top, #f0f0f0 0%, #fff 100%); - background: -o-linear-gradient(top, #f0f0f0 0%, #fff 100%); - background: -ms-linear-gradient(top, #f0f0f0 0%, #fff 100%); - background: linear-gradient(to bottom, #f0f0f0 0%, #fff 100%); - border-radius: 10px; - content: ""; - height: 12px; - margin: -1px 0 0 -1px; - position: absolute; - width: 12px; -} - -/* ---------------------------------------------------------------------- - Material Design Range Slider - by Ravikumar Chauhan - ------------------------------------------------------------------------- */ -.rkmd-slider { - display: block; - position: relative; - font-size: 16px; - font-family: "Roboto", sans-serif; -} - -.rkmd-slider input[type="range"] { - overflow: hidden; - position: absolute; - width: 1px; - height: 1px; - opacity: 0; -} - -.rkmd-slider input[type="range"]+.slider { - display: block; - position: relative; - width: 100%; - height: 27px; - border-radius: 13px; - background-color: #bebebe; -} - -@media (pointer: fine) { - .rkmd-slider input[type="range"]+.slider { - height: 4px; - border-radius: 0px; - } -} - -.rkmd-slider input[type="range"]+.slider .slider-fill { - display: block; - position: absolute; - width: 0%; - height: 100%; - user-select: none; - z-index: 1; -} - -.rkmd-slider input[type="range"]+.slider .slider-handle { - cursor: pointer; - position: absolute; - top: 12px; - left: 0%; - width: 15px; - height: 15px; - margin-left: -8px; - border-radius: 50%; - transition: all 0.2s ease; - user-select: none; - z-index: 2; -} - -@media (pointer: fine) { - .rkmd-slider input[type="range"]+.slider .slider-handle { - top: -5.5px; - } -} - -.rkmd-slider input[type="range"]:disabled+.slider { - background-color: #b0b0b0 !important; -} - -.rkmd-slider input[type="range"]:disabled+.slider .slider-fill, -.rkmd-slider input[type="range"]:disabled+.slider .slider-handle { - cursor: default !important; - background-color: #b0b0b0 !important; -} - -.rkmd-slider input[type="range"]:disabled+.slider .slider-fill .slider-label, -.rkmd-slider input[type="range"]:disabled+.slider .slider-handle .slider-label { - display: none; - background-color: #b0b0b0 !important; -} - -.rkmd-slider input[type="range"]:disabled+.slider .slider-fill.is-active, -.rkmd-slider input[type="range"]:disabled+.slider .slider-handle.is-active { - top: -5.5px; - width: 15px; - height: 15px; - margin-left: -8px; -} - -.rkmd-slider input[type="range"]:disabled+.slider .slider-fill.is-active .slider-label, -.rkmd-slider input[type="range"]:disabled+.slider .slider-handle.is-active .slider-label { - display: none; - border-radius: 50%; - transform: none; -} - -.rkmd-slider input[type="range"]:disabled+.slider .slider-handle:active { - box-shadow: none !important; - transform: scale(1) !important; -} - -/* ---------------------------------------------------------------------- - Discrete Range Slider - by Ravikumar Chauhan - ------------------------------------------------------------------------- */ -.rkmd-slider.slider-discrete .slider .slider-handle { - position: relative; - z-index: 1; -} - -.rkmd-slider.slider-discrete .slider .slider-handle .slider-label { - position: absolute; - top: -17.5px; - left: 4px; - width: 30px; - height: 30px; - -webkit-transform-origin: 50% 100%; - transform-origin: 50% 100%; - border-radius: 50%; - -webkit-transform: scale(1) rotate(-45deg); - transform: scale(1) rotate(-45deg); - -webkit-transition: all 0.2s ease; - transition: all 0.2s ease; -} - -@media (pointer: fine) { - .rkmd-slider.slider-discrete .slider .slider-handle .slider-label { - left: -2px; - -webkit-transform: scale(0.5) rotate(-45deg); - transform: scale(0.5) rotate(-45deg); - } -} - -.rkmd-slider.slider-discrete .slider .slider-handle .slider-label span { - position: absolute; - top: 7px; - left: 0px; - width: 100%; - color: #fff; - font-size: 16px; - text-align: center; - -webkit-transform: rotate(45deg); - transform: rotate(45deg); - opacity: 0; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -@media (pointer: fine) { - .rkmd-slider.slider-discrete .slider .slider-handle .slider-label span { - font-size: 12px; - } -} - -.rkmd-slider.slider-discrete .slider .slider-handle.is-active { - top: 0px; - margin-left: -2px; - width: 4px; - height: 4px; -} - -.rkmd-slider.slider-discrete .slider .slider-handle.is-active .slider-label { - top: -15px; - left: -2px; - border-radius: 15px 15px 15px 0; - -webkit-transform: rotate(-45deg) translate(23px, -25px); - transform: rotate(-45deg) translate(23px, -25px); -} - -.rkmd-slider.slider-discrete .slider .slider-handle.is-active .slider-label span { - opacity: 1; -} - -.rkmd-slider.slider-discrete.slider-turquoise .slider-label { - background-color: #16a085; -} - -.rkmd-slider.slider-discrete.slider-emerald .slider-label { - background-color: #27ae60; -} - -.peterriver { - background: #3498db; - border-bottom: #2980b9 3px solid; -} - -.rkmd-slider.slider-discrete.slider-peterriver .slider-label { - background-color: #2980b9; -} - -.wetasphalt { - background: #34495e; - border-bottom: #2c3e50 3px solid; -} - -.rkmd-slider.slider-discrete.slider-wetasphalt .slider-label { - background-color: #2c3e50; -} - -.sunflower { - background: #f1c40f; - border-bottom: #e6bb0f 3px solid; -} - -.rkmd-slider.slider-discrete.slider-sunflower .slider-label { - background-color: #e6bb0f; -} - -.carrot { - background: #e67e22; - border-bottom: #d35400 3px solid; -} - -.rkmd-slider.slider-discrete.slider-carrot .slider-label { - background-color: #d35400; -} - -.alizarin { - background: #e74c3c; - border-bottom: #c0392b 3px solid; -} - -.rkmd-slider.slider-discrete.slider-alizarin .slider-label { - background-color: #c0392b; -} - -/* - .rkmd-slider.slider-light input[type="range"] + .slider { - background-color: #5c5c5c; - } - .rkmd-slider.slider-light input[type="range"]:disabled + .slider { - background-color: #5c5c5c !important; - } - .rkmd-slider.slider-light input[type="range"]:disabled + .slider .slider-fill, - .rkmd-slider.slider-light input[type="range"]:disabled + .slider .slider-handle { - background-color: #5c5c5c !important; - } - -*/ - -/* -------------------------------------------------------------- - * Text and number inputs - *--------------------------------------------------------------- */ - -input { - margin: 0 auto 1.2rem auto; - padding: 2px 5px; - width: 100%; - box-sizing: border-box; - border: none; - border-radius: 4px; - box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); - background: rgba(255, 255, 255, 0.8); -} - -select { - margin: 0 auto 1.2rem auto; - padding: 2px 5px; - width: 100%; - box-sizing: border-box; - border: none; - border-radius: 4px; - box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); - background: rgba(255, 255, 255, 0.8); -} - -input[id^="num"] { - max-width: 6em; - width: auto; - text-align: right; - font-weight: bold; - font-size: 115%; -} - -body div>ul.navigation { - margin: 0; - margin-bottom: 30px; - padding: 0; - border-bottom: 3px solid #666; - overflow: hidden; -} - -ul.navigation li { - list-style: none; - float: left; - margin-right: 4px; -} - -ul.navigation li.controls { - float: right; -} - -ul.navigation li a { - font-weight: bold; - display: inline-block; - padding: 6px 12px; - color: #888; - outline: 0; - text-decoration: none; - background: #f3f3f3; - background: -webkit-gradient(linear, 0 0, 0 bottom, from(#eee), to(#e4e4e4)); - background: -moz-linear-gradient(#eee, #e4e4e4); - background: linear-gradient(#eee, #e4e4e4); - -pie-background: linear-gradient(#eee, #e4e4e4); -} - -ul.navigation li.active a { - pointer-events: none; - color: white; - background: #666; - background: -webkit-gradient(linear, 0 0, 0 bottom, from(#888), to(#666)); - background: -moz-linear-gradient(#888, #666); - background: linear-gradient(#888, #666); - -pie-background: linear-gradient(#888, #666); -} - -div.tabscontent>div { - padding: 0 15px; -} - -#tabsnav:empty { - display: none; -} - -.range-slider { - margin: 0 0 0 0; -} - -.range-slider { - width: 100%; -} - -.range-slider__range { - -webkit-appearance: none; - width: calc(100% - (45px)); - height: 10px; - border-radius: 5px; - outline: 0; - padding: 0; - margin: 0; -} - -/* -.range-slider__range::-webkit-slider-thumb { - -webkit-appearance: none; - appearance: none; - width: 20px; - height: 20px; - border-radius: 50%; - cursor: pointer; - transition: background 0.15s ease-in-out; -} -.range-slider__range::-webkit-slider-thumb:hover { - background: #1abc9c; -} -.range-slider__range:active::-webkit-slider-thumb { - background: #1abc9c; -} -.range-slider__range::-moz-range-thumb { - width: 20px; - height: 20px; - border: 0; - border-radius: 50%; - cursor: pointer; - transition: background 0.15s ease-in-out; -} -.range-slider__range:focus::-webkit-slider-thumb { - box-shadow: 0 0 0 3px #fff, 0 0 0 6px #1abc9c; -} -*/ -.range-slider__value { - display: inline-block; - position: relative; - width: 30px; - color: #fff; - line-height: 20px; - text-align: center; - border-radius: 3px; - padding: 5px 5px; - margin-left: 2px; -} - -.range-slider__value:after { - position: absolute; - top: 8px; - left: -7px; - width: 0; - height: 0; - /*border-top:1px solid transparent; - border-right:1px solid #2c3e50; - border-bottom:1px solid transparent;*/ - content: ""; -} - -::-moz-range-track { - border: 0; -} - -input::-moz-focus-inner, -input::-moz-focus-outer { - border: 0; -} - -/* Styles for Graph widget */ - -svg { - display: block; - width: 100%; - height: 100%; -} - -.y-axis path, -.x-axis path { - stroke: gray; - stroke-width: 1; - fill: none; -} - -.series { - stroke: steelblue; - stroke-width: 3; - fill: none; -} - -.data-points circle { - stroke: steelblue; - stroke-width: 2; - fill: white; -} - -.data-points text { - display: none; -} - -.data-points circle:hover { - fill: steelblue; - stroke-width: 6; -} - -.data-points circle:hover+text { - display: inline-block; -} - -text { - text-anchor: end; -} - - -/* Styles to implement vertical orientations */ - -.vert-switcher { - transform: rotate(270deg); - margin-top: 15px; - margin-bottom: 25px; -} - -.vert-slider { - width: 150px; - transform: rotate(270deg); - display: inline-block; - margin: 50px -42px 70px -42px; -} - -.vert-slider span { - transform: rotate(90deg); -} - - -/* Styles to implement disabled controls */ - -button:disabled { - color: #333; - background-color: #999; -} - -select:disabled { - color: #333; - background-color: #999; -} - -input:disabled { - color: #333; - background-color: #999; -} - -.range-slider__range:disabled { - background-color: #999; -} - -.range-slider__range:disabled::-webkit-slider-thumb { - background-color: #aaa; -} - -.range-slider__range:disabled::-moz-range-thumb { - background-color: #aaa; -} - -.switch.disabled .in::before { - background:#bbb; - border: 1px solid #ddd; -} - -.switch.disabled .in::after { - background:#bbb; -} - -.switch.checked.disabled { - background: #b1d092; -} diff --git a/watering/lib/ESPUI/data/css/style.min.css b/watering/lib/ESPUI/data/css/style.min.css deleted file mode 100644 index 28cdbdb..0000000 --- a/watering/lib/ESPUI/data/css/style.min.css +++ /dev/null @@ -1 +0,0 @@ -.container{position:relative;width:79%;margin:20px;box-sizing:border-box}.column,.columns{width:100%;float:left}.card{min-height:100px;border-radius:6px;box-shadow:0 4px 4px rgba(204,197,185,0.5);padding-left:20px;padding-right:20px;margin-bottom:40px;min-width:500px;color:#fff}@media(min-width:1205px){.wide.card{min-width:1075px}}@media(min-width:1790px){.wide.card{min-width:1650px}}@media(max-width:630px){.card{min-width:98%}}.sectionbreak.columns{color:black}.sectionbreak.columns hr{border:0;height:2px;background-color:#666}.turquoise{background:#1abc9c;border-bottom:#16a085 3px solid}.emerald{background:#2ecc71;border-bottom:#27ae60 3px solid}.peterriver{background:#3498db;border-bottom:#2980b9 3px solid}.wetasphalt{background:#34495e;border-bottom:#2c3e50 3px solid}.sunflower{background:#f1c40f;border-bottom:#e6bb0f 3px solid}.carrot{background:#e67e22;border-bottom:#d35400 3px solid}.alizarin{background:#e74c3c;border-bottom:#c0392b 3px solid}.dark{background:#444857;border-bottom:#444857 3px solid}.label{box-sizing:border-box;white-space:nowrap;border-radius:.2em;padding:.12em .4em .14em;text-align:center;color:#fff;font-weight:700;line-height:1.3;margin-bottom:5px;display:inline-block;white-space:nowrap;vertical-align:baseline;position:relative;top:-.15em;background-color:#999;margin-bottom:10px}.label-wrap{width:90%;white-space:pre-wrap;word-wrap:break-word}.label.color-blue{background-color:#6f9ad1}.label.color-red{background-color:#d37c7c}.label.color-green{background-color:#9bc268}.label.color-orange{background-color:#dea154}.label.color-yellow{background-color:#e9d641}.label.color-purple{background-color:#9f83d1}@media(min-width:400px){.container{width:84%}}@media(min-width:630px){.container{width:98%}.column,.columns{margin-right:35px}.column:first-child,.columns:first-child{margin-left:0}.one.column,.one.columns{width:4.66666666667%}.two.columns{width:13.3333333333%}.three.columns{width:22%}.four.columns{width:30.6666666667%}.five.columns{width:39.3333333333%}.six.columns{width:48%}.seven.columns{width:56.6666666667%}.eight.columns{width:65.3333333333%}.nine.columns{width:74%}.ten.columns{width:82.6666666667%}.eleven.columns{width:91.3333333333%}.twelve.columns{width:100%;margin-left:0}.one-third.column{width:30.6666666667%}.two-thirds.column{width:65.3333333333%}.one-half.column{width:48%}.offset-by-one.column,.offset-by-one.columns{margin-left:8.66666666667%}.offset-by-two.column,.offset-by-two.columns{margin-left:17.3333333333%}.offset-by-three.column,.offset-by-three.columns{margin-left:26%}.offset-by-four.column,.offset-by-four.columns{margin-left:34.6666666667%}.offset-by-five.column,.offset-by-five.columns{margin-left:43.3333333333%}.offset-by-six.column,.offset-by-six.columns{margin-left:52%}.offset-by-seven.column,.offset-by-seven.columns{margin-left:60.6666666667%}.offset-by-eight.column,.offset-by-eight.columns{margin-left:69.3333333333%}.offset-by-nine.column,.offset-by-nine.columns{margin-left:78%}.offset-by-ten.column,.offset-by-ten.columns{margin-left:86.6666666667%}.offset-by-eleven.column,.offset-by-eleven.columns{margin-left:95.3333333333%}.offset-by-one-third.column,.offset-by-one-third.columns{margin-left:34.6666666667%}.offset-by-two-thirds.column,.offset-by-two-thirds.columns{margin-left:69.3333333333%}.offset-by-one-half.column,.offset-by-one-half.columns{margin-left:52%}}html{font-size:62.5%}body{margin:0;font-size:1.5em;line-height:1;font-weight:400;font-family:"Open Sans",sans-serif;color:#222;background-color:#ecf0f1}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:300}h1{font-size:4rem;line-height:1.2;letter-spacing:-.1rem}h2{font-size:3.6rem;line-height:1.25;letter-spacing:-.1rem}h3{font-size:3rem;line-height:1.3;letter-spacing:-.1rem}h4{font-size:2.4rem;line-height:1.35;letter-spacing:-.08rem}h5{font-size:1.8rem;line-height:1.5;letter-spacing:-.05rem}h6{font-size:1.5rem;line-height:1.6;letter-spacing:0}@media(min-width:630px){h1{font-size:5rem}h2{font-size:4.2rem}h3{font-size:3.6rem}h4{font-size:3rem}h5{font-size:2rem}h6{font-size:1.5rem}}p{margin-top:0}a{color:#1eaedb}a:hover{color:#0fa0ce}button{display:inline-block;padding:10px;border-radius:3px;color:#fff;background-color:#999}button:enabled:active{background-color:#666;transform:translateX(4px) translateY(4px)}#mainHeader{display:inline-block}#conStatus{position:inherit;font-size:.75em}button,.button{margin-bottom:1rem;margin-left:.3rem;margin-right:.3rem}.u-full-width{width:100%;box-sizing:border-box}.u-max-full-width{max-width:100%;box-sizing:border-box}.u-pull-right{float:right}.u-pull-left{float:left}.tcenter{text-align:center}hr{margin-top:.5rem;margin-bottom:1.2rem;border-width:0;border-top:1px solid #e1e1e1}.container:after,.row:after,.u-cf{content:"";display:table;clear:both}.control{background-color:#ddd;background-image:linear-gradient(hsla(0,0%,0%,0.1),hsla(0,0%,100%,0.1));border-radius:50%;box-shadow:inset 0 1px 1px 1px hsla(0,0%,100%,0.5),0 0 1px 1px hsla(0,0%,100%,0.75),0 0 1px 2px hsla(0,0%,100%,0.25),0 0 1px 3px hsla(0,0%,100%,0.25),0 0 1px 4px hsla(0,0%,100%,0.25),0 0 1px 6px hsla(0,0%,0%,0.75);height:9em;margin:3em auto;position:relative;width:9em}.control ul{height:100%;padding:0;transform:rotate(45deg)}.control li{border-radius:100% 0 0 0;box-shadow:inset -1px -1px 1px hsla(0,0%,100%,0.5),0 0 1px hsla(0,0%,0%,0.75);display:inline-block;height:50%;overflow:hidden;width:50%}.control ul li:nth-child(2){transform:rotate(90deg)}.control ul li:nth-child(3){transform:rotate(-90deg)}.control ul li:nth-child(4){transform:rotate(180deg)}.control ul a{height:200%;position:relative;transform:rotate(-45deg);width:200%}.control a:hover,.control a:focus{background-color:hsla(0,0%,100%,0.25)}.control a{border-radius:50%;color:#333;display:block;font:bold 1em/3 sans-serif;text-align:center;text-decoration:none;text-shadow:0 1px 1px hsla(0,0%,100%,0.4);transition:.15s}.control .confirm{background-color:#ddd;background-image:linear-gradient(hsla(0,0%,0%,0.15),hsla(0,0%,100%,0.25));box-shadow:inset 0 1px 1px 1px hsla(0,0%,100%,0.5),0 0 1px 1px hsla(0,0%,100%,0.25),0 0 1px 2px hsla(0,0%,100%,0.25),0 0 1px 3px hsla(0,0%,100%,0.25),0 0 1px 4px hsla(0,0%,100%,0.25),0 0 1px 6px hsla(0,0%,0%,0.85);left:50%;line-height:3;margin:-1.5em;position:absolute;top:50%;width:3em}.control .confirm:hover,.control .confirm:focus{background-color:#eee}.control:not(.disabled) a.confirm:active{background-color:#777}.control:not(.disabled) li:active{background-color:#777}.switch{display:inline-block !important;background-color:#bebebe;border-radius:4px;box-shadow:inset 0 0 6px rgba(0,0,0,0.3);color:#fff;cursor:pointer;display:block;font-size:14px;height:26px;margin-left:.3rem;margin-right:.3rem;position:relative;width:60px;-webkit-transition:background-color .2s ease-in-out;-moz-transition:background-color .2s ease-in-out;-o-transition:background-color .2s ease-in-out;-ms-transition:background-color .2s ease-in-out;transition:background-color .2s ease-in-out}.switch.checked{background-color:#76d21d}.switch input[type="checkbox"]{display:none;cursor:pointer;height:10px;left:12px;position:absolute;top:8px;width:10px}.in{position:absolute;top:8px;left:12px;-webkit-transition:left .08s ease-in-out;-moz-transition:left .08s ease-in-out;-o-transition:left .08s ease-in-out;-ms-transition:left .08s ease-in-out;transition:left .08s ease-in-out}.switch.checked div{left:38px}.switch .in:before{background:#fff;background:-moz-linear-gradient(top,#fff 0,#f0f0f0 100%);background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#fff),color-stop(100%,#f0f0f0));background:-webkit-linear-gradient(top,#fff 0,#f0f0f0 100%);background:-o-linear-gradient(top,#fff 0,#f0f0f0 100%);background:-ms-linear-gradient(top,#fff 0,#f0f0f0 100%);background:linear-gradient(to bottom,#fff 0,#f0f0f0 100%);border:1px solid #fff;border-radius:2px;box-shadow:0 0 4px rgba(0,0,0,0.3);content:"";height:18px;position:absolute;top:-5px;left:-9px;width:26px}.switch .in:after{background:#f0f0f0;background:-moz-linear-gradient(top,#f0f0f0 0,#fff 100%);background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#f0f0f0),color-stop(100%,#fff));background:-webkit-linear-gradient(top,#f0f0f0 0,#fff 100%);background:-o-linear-gradient(top,#f0f0f0 0,#fff 100%);background:-ms-linear-gradient(top,#f0f0f0 0,#fff 100%);background:linear-gradient(to bottom,#f0f0f0 0,#fff 100%);border-radius:10px;content:"";height:12px;margin:-1px 0 0 -1px;position:absolute;width:12px}.rkmd-slider{display:block;position:relative;font-size:16px;font-family:"Roboto",sans-serif}.rkmd-slider input[type="range"]{overflow:hidden;position:absolute;width:1px;height:1px;opacity:0}.rkmd-slider input[type="range"]+.slider{display:block;position:relative;width:100%;height:27px;border-radius:13px;background-color:#bebebe}@media(pointer:fine){.rkmd-slider input[type="range"]+.slider{height:4px;border-radius:0}}.rkmd-slider input[type="range"]+.slider .slider-fill{display:block;position:absolute;width:0;height:100%;user-select:none;z-index:1}.rkmd-slider input[type="range"]+.slider .slider-handle{cursor:pointer;position:absolute;top:12px;left:0;width:15px;height:15px;margin-left:-8px;border-radius:50%;transition:all .2s ease;user-select:none;z-index:2}@media(pointer:fine){.rkmd-slider input[type="range"]+.slider .slider-handle{top:-5.5px}}.rkmd-slider input[type="range"]:disabled+.slider{background-color:#b0b0b0 !important}.rkmd-slider input[type="range"]:disabled+.slider .slider-fill,.rkmd-slider input[type="range"]:disabled+.slider .slider-handle{cursor:default !important;background-color:#b0b0b0 !important}.rkmd-slider input[type="range"]:disabled+.slider .slider-fill .slider-label,.rkmd-slider input[type="range"]:disabled+.slider .slider-handle .slider-label{display:none;background-color:#b0b0b0 !important}.rkmd-slider input[type="range"]:disabled+.slider .slider-fill.is-active,.rkmd-slider input[type="range"]:disabled+.slider .slider-handle.is-active{top:-5.5px;width:15px;height:15px;margin-left:-8px}.rkmd-slider input[type="range"]:disabled+.slider .slider-fill.is-active .slider-label,.rkmd-slider input[type="range"]:disabled+.slider .slider-handle.is-active .slider-label{display:none;border-radius:50%;transform:none}.rkmd-slider input[type="range"]:disabled+.slider .slider-handle:active{box-shadow:none !important;transform:scale(1) !important}.rkmd-slider.slider-discrete .slider .slider-handle{position:relative;z-index:1}.rkmd-slider.slider-discrete .slider .slider-handle .slider-label{position:absolute;top:-17.5px;left:4px;width:30px;height:30px;-webkit-transform-origin:50% 100%;transform-origin:50% 100%;border-radius:50%;-webkit-transform:scale(1) rotate(-45deg);transform:scale(1) rotate(-45deg);-webkit-transition:all .2s ease;transition:all .2s ease}@media(pointer:fine){.rkmd-slider.slider-discrete .slider .slider-handle .slider-label{left:-2px;-webkit-transform:scale(0.5) rotate(-45deg);transform:scale(0.5) rotate(-45deg)}}.rkmd-slider.slider-discrete .slider .slider-handle .slider-label span{position:absolute;top:7px;left:0;width:100%;color:#fff;font-size:16px;text-align:center;-webkit-transform:rotate(45deg);transform:rotate(45deg);opacity:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}@media(pointer:fine){.rkmd-slider.slider-discrete .slider .slider-handle .slider-label span{font-size:12px}}.rkmd-slider.slider-discrete .slider .slider-handle.is-active{top:0;margin-left:-2px;width:4px;height:4px}.rkmd-slider.slider-discrete .slider .slider-handle.is-active .slider-label{top:-15px;left:-2px;border-radius:15px 15px 15px 0;-webkit-transform:rotate(-45deg) translate(23px,-25px);transform:rotate(-45deg) translate(23px,-25px)}.rkmd-slider.slider-discrete .slider .slider-handle.is-active .slider-label span{opacity:1}.rkmd-slider.slider-discrete.slider-turquoise .slider-label{background-color:#16a085}.rkmd-slider.slider-discrete.slider-emerald .slider-label{background-color:#27ae60}.peterriver{background:#3498db;border-bottom:#2980b9 3px solid}.rkmd-slider.slider-discrete.slider-peterriver .slider-label{background-color:#2980b9}.wetasphalt{background:#34495e;border-bottom:#2c3e50 3px solid}.rkmd-slider.slider-discrete.slider-wetasphalt .slider-label{background-color:#2c3e50}.sunflower{background:#f1c40f;border-bottom:#e6bb0f 3px solid}.rkmd-slider.slider-discrete.slider-sunflower .slider-label{background-color:#e6bb0f}.carrot{background:#e67e22;border-bottom:#d35400 3px solid}.rkmd-slider.slider-discrete.slider-carrot .slider-label{background-color:#d35400}.alizarin{background:#e74c3c;border-bottom:#c0392b 3px solid}.rkmd-slider.slider-discrete.slider-alizarin .slider-label{background-color:#c0392b}input{margin:0 auto 1.2rem auto;padding:2px 5px;width:100%;box-sizing:border-box;border:0;border-radius:4px;box-shadow:inset 0 0 6px rgba(0,0,0,0.3);background:rgba(255,255,255,0.8)}select{margin:0 auto 1.2rem auto;padding:2px 5px;width:100%;box-sizing:border-box;border:0;border-radius:4px;box-shadow:inset 0 0 6px rgba(0,0,0,0.3);background:rgba(255,255,255,0.8)}input[id^="num"]{max-width:6em;width:auto;text-align:right;font-weight:bold;font-size:115%}body div>ul.navigation{margin:0;margin-bottom:30px;padding:0;border-bottom:3px solid #666;overflow:hidden}ul.navigation li{list-style:none;float:left;margin-right:4px}ul.navigation li.controls{float:right}ul.navigation li a{font-weight:bold;display:inline-block;padding:6px 12px;color:#888;outline:0;text-decoration:none;background:#f3f3f3;background:-webkit-gradient(linear,0 0,0 bottom,from(#eee),to(#e4e4e4));background:-moz-linear-gradient(#eee,#e4e4e4);background:linear-gradient(#eee,#e4e4e4);-pie-background:linear-gradient(#eee,#e4e4e4)}ul.navigation li.active a{pointer-events:none;color:white;background:#666;background:-webkit-gradient(linear,0 0,0 bottom,from(#888),to(#666));background:-moz-linear-gradient(#888,#666);background:linear-gradient(#888,#666);-pie-background:linear-gradient(#888,#666)}div.tabscontent>div{padding:0 15px}#tabsnav:empty{display:none}.range-slider{margin:0}.range-slider{width:100%}.range-slider__range{-webkit-appearance:none;width:calc(100% - (45px));height:10px;border-radius:5px;outline:0;padding:0;margin:0}.range-slider__value{display:inline-block;position:relative;width:30px;color:#fff;line-height:20px;text-align:center;border-radius:3px;padding:5px 5px;margin-left:2px}.range-slider__value:after{position:absolute;top:8px;left:-7px;width:0;height:0;content:""}::-moz-range-track{border:0}input::-moz-focus-inner,input::-moz-focus-outer{border:0}svg{display:block;width:100%;height:100%}.y-axis path,.x-axis path{stroke:gray;stroke-width:1;fill:none}.series{stroke:steelblue;stroke-width:3;fill:none}.data-points circle{stroke:steelblue;stroke-width:2;fill:white}.data-points text{display:none}.data-points circle:hover{fill:steelblue;stroke-width:6}.data-points circle:hover+text{display:inline-block}text{text-anchor:end}.vert-switcher{transform:rotate(270deg);margin-top:15px;margin-bottom:25px}.vert-slider{width:150px;transform:rotate(270deg);display:inline-block;margin:50px -42px 70px -42px}.vert-slider span{transform:rotate(90deg)}button:disabled{color:#333;background-color:#999}select:disabled{color:#333;background-color:#999}input:disabled{color:#333;background-color:#999}.range-slider__range:disabled{background-color:#999}.range-slider__range:disabled::-webkit-slider-thumb{background-color:#aaa}.range-slider__range:disabled::-moz-range-thumb{background-color:#aaa}.switch.disabled .in::before{background:#bbb;border:1px solid #ddd}.switch.disabled .in::after{background:#bbb}.switch.checked.disabled{background:#b1d092} \ No newline at end of file diff --git a/watering/lib/ESPUI/data/index.htm b/watering/lib/ESPUI/data/index.htm deleted file mode 100644 index dbb5e84..0000000 --- a/watering/lib/ESPUI/data/index.htm +++ /dev/null @@ -1,35 +0,0 @@ - - - - - Control - - - - - - - - - - - - - -
-

-
Control
- Offline -

-
-
-
-
- -
-
- - diff --git a/watering/lib/ESPUI/data/index.min.htm b/watering/lib/ESPUI/data/index.min.htm deleted file mode 100644 index 9ae11a7..0000000 --- a/watering/lib/ESPUI/data/index.min.htm +++ /dev/null @@ -1 +0,0 @@ - Control

Control
Offline


\ No newline at end of file diff --git a/watering/lib/ESPUI/data/js/controls.js b/watering/lib/ESPUI/data/js/controls.js deleted file mode 100644 index 6d9fff0..0000000 --- a/watering/lib/ESPUI/data/js/controls.js +++ /dev/null @@ -1,1138 +0,0 @@ -const UI_INITIAL_GUI = 200; -const UI_RELOAD = 201; -const UPDATE_OFFSET = 100; - -const UI_EXTEND_GUI = 210; - -const UI_TITEL = 0; - -const UI_PAD = 1; -const UPDATE_PAD = 101; - -const UI_CPAD = 2; -const UPDATE_CPAD = 102; - -const UI_BUTTON = 3; -const UPDATE_BUTTON = 103; - -const UI_LABEL = 4; -const UPDATE_LABEL = 104; - -const UI_SWITCHER = 5; -const UPDATE_SWITCHER = 105; - -const UI_SLIDER = 6; -const UPDATE_SLIDER = 106; - -const UI_NUMBER = 7; -const UPDATE_NUMBER = 107; - -const UI_TEXT_INPUT = 8; -const UPDATE_TEXT_INPUT = 108; - -const UI_GRAPH = 9; -const ADD_GRAPH_POINT = 10; -const CLEAR_GRAPH = 109; - -const UI_TAB = 11; -const UPDATE_TAB = 111; - -const UI_SELECT = 12; -const UPDATE_SELECT = 112; - -const UI_OPTION = 13; -const UPDATE_OPTION = 113; -const UI_MIN = 14; -const UPDATE_MIN = 114; -const UI_MAX = 15; -const UPDATE_MAX = 115; -const UI_STEP = 16; -const UPDATE_STEP = 116; - -const UI_GAUGE = 17; -const UPDATE_GAUGE = 117; -const UI_ACCEL = 18; -const UPDATE_ACCEL = 118; - -const UI_SEPARATOR = 19; -const UPDATE_SEPARATOR = 119; - -const UI_TIME = 20; -const UPDATE_TIME = 120; - -const UI_FILEDISPLAY = 21; -const UPDATE_FILEDISPLAY = 121; - -const UI_FRAGMENT = 98; - -const UP = 0; -const DOWN = 1; -const LEFT = 2; -const RIGHT = 3; -const CENTER = 4; - -// Colors -const C_TURQUOISE = 0; -const C_EMERALD = 1; -const C_PETERRIVER = 2; -const C_WETASPHALT = 3; -const C_SUNFLOWER = 4; -const C_CARROT = 5; -const C_ALIZARIN = 6; -const C_DARK = 7; -const C_NONE = 255; - -var controlAssemblyArray = new Object(); -var FragmentAssemblyTimer = new Array(); -var graphData = new Array(); -var hasAccel = false; -var sliderContinuous = false; - -function colorClass(colorId) { - colorId = Number(colorId); - switch (colorId) { - case C_TURQUOISE: - return "turquoise"; - - case C_EMERALD: - return "emerald"; - - case C_PETERRIVER: - return "peterriver"; - - case C_WETASPHALT: - return "wetasphalt"; - - case C_SUNFLOWER: - return "sunflower"; - - case C_CARROT: - return "carrot"; - - case C_ALIZARIN: - return "alizarin"; - - case C_DARK: - case C_NONE: - return "dark"; - default: - return ""; - } -} - -var websock; -var websockConnected = false; -var WebSocketTimer = null; - -function requestOrientationPermission() { - /* - // Currently this fails, since it needs secure context on IOS safari - if (typeof DeviceMotionEvent.requestPermission === "function") { - DeviceOrientationEvent.requestPermission() - .then(response => { - if (response == "granted") { - window.addEventListener("deviceorientation", handleOrientation); - } - }) - .catch(console.error); - } else { - // Non IOS 13 - window.addEventListener("deviceorientation", handleOrientation); - } - */ -} -/* -function handleOrientation(event) { - var x = event.beta; // In degree in the range [-180,180] - var y = event.gamma; // In degree in the range [-90,90] - - var output = document.querySelector(".output"); - output.innerHTML = "beta : " + x + "\n"; - output.innerHTML += "gamma: " + y + "\n"; - - // Because we don't want to have the device upside down - // We constrain the x value to the range [-90,90] - if (x > 90) { - x = 90; - } - if (x < -90) { - x = -90; - } - - // To make computation easier we shift the range of - // x and y to [0,180] - x += 90; - y += 90; - - // 10 is half the size of the ball - // It center the positioning point to the center of the ball - var ball = document.querySelector(".ball"); - var garden = document.querySelector(".garden"); - var maxX = garden.clientWidth - ball.clientWidth; - var maxY = garden.clientHeight - ball.clientHeight; - ball.style.top = (maxY * y) / 180 - 10 + "px"; - ball.style.left = (maxX * x) / 180 - 10 + "px"; -} -*/ - -function saveGraphData() { - localStorage.setItem("espuigraphs", JSON.stringify(graphData)); -} - -function restoreGraphData(id) { - var savedData = localStorage.getItem("espuigraphs", graphData); - if (savedData != null) { - savedData = JSON.parse(savedData); - let idData = savedData[id]; - return Array.isArray(idData) ? idData : []; - } - return []; -} - -function restart() { - $(document).add("*").off(); - $("#row").html(""); - conStatusError(); - start(); -} - -function conStatusError() { - FragmentAssemblyTimer.forEach(element => { - clearInterval(element); - }); - FragmentAssemblyTimer = new Array(); - controlAssemblyArray = new Array(); - - if (true === websockConnected) { - websockConnected = false; - websock.close(); - $("#conStatus").removeClass("color-green"); - $("#conStatus").addClass("color-red"); - $("#conStatus").html("Error / No Connection ↻"); - $("#conStatus").off(); - $("#conStatus").on({ - click: restart, - }); - } -} - -function handleVisibilityChange() { - if (!websockConnected && !document.hidden) { - restart(); - } -} - -function start() { - let location = window.location.hostname; - let port = window.location.port; -// let location = "192.168.10.198"; -// let port = ""; - - document.addEventListener("visibilitychange", handleVisibilityChange, false); - if ( - port != "" || - port != 80 || - port != 443 - ) { - websock = new WebSocket( "ws://" + location + ":" + port + "/ws" ); - } else { - websock = new WebSocket("ws://" + location + "/ws"); - } - - // is the timer running? - if (null === WebSocketTimer) { - // timer runs forever - WebSocketTimer = setInterval(function () { - // console.info("Periodic Timer has expired"); - // is the socket closed? - if (websock.readyState === 3) { - // console.info("Web Socket Is Closed"); - restart(); - } - }, 5000); - } // end timer was not running - - websock.onopen = function (evt) { - console.log("websock open"); - $("#conStatus").addClass("color-green"); - $("#conStatus").text("Connected"); - websockConnected = true; - FragmentAssemblyTimer.forEach(element => { - clearInterval(element); - }); - FragmentAssemblyTimer = new Array(); - controlAssemblyArray = new Array(); - }; - - websock.onclose = function (evt) { - // console.log("Close evt: '" + evt + "'"); - // console.log("Close reason: '" + evt.reason + "'"); - // console.log("Close code: '" + evt.code + "'"); - console.log("websock close"); - conStatusError(); - FragmentAssemblyTimer.forEach(element => { - clearInterval(element); - }); - FragmentAssemblyTimer = new Array(); - controlAssemblyArray = new Array(); - }; - - websock.onerror = function (evt) { - console.log("websock Error"); - // console.log("Error evt: '" + evt + "'"); - // console.log("Error data: '" + evt.data + "'"); - - restart(); - FragmentAssemblyTimer.forEach(element => { - clearInterval(element); - }); - FragmentAssemblyTimer = new Array(); - controlAssemblyArray = new Array(); - }; - - var handleEvent = function (evt) { - // console.log("handleEvent:Data evt: '" + evt + "'"); - // console.log("handleEvent:Data data: '" + evt.data + "'"); - try { - var data = JSON.parse(evt.data); - } - catch (Event) { - console.error(Event); - // console.info("start the update over again"); - websock.send("uiok:" + 0); - return; - } - var e = document.body; - var center = ""; - // console.info("data.type: '" + data.type + "'"); - - switch (data.type) { - case UI_INITIAL_GUI: - // Clear current elements - $("#row").html(""); - $("#tabsnav").html(""); - $("#tabscontent").html(""); - - if (data.sliderContinuous) { - sliderContinuous = data.sliderContinuous; - } - // console.info("UI_INITIAL_GUI:data record: '" + data + "'"); - data.controls.forEach(element => { - // console.info("element: '" + JSON.stringify(element) + "'"); - var fauxEvent = { - data: JSON.stringify(element), - }; - handleEvent(fauxEvent); - }); - - //If there are more elements in the complete UI, then request them - //Note: we subtract 1 from data.controls.length because the controls always - //includes the title element - if (data.totalcontrols > (data.controls.length - 1)) { - websock.send("uiok:" + (data.controls.length - 1)); - } - break; - - case UI_EXTEND_GUI: - // console.info("UI_EXTEND_GUI data record: '" + data + "'"); - data.controls.forEach(element => { - // console.info("UI_EXTEND_GUI:element: '" + JSON.stringify(element) + "'"); - var fauxEvent = { - data: JSON.stringify(element), - }; - handleEvent(fauxEvent); - }); - - //Do we need to keep requesting more UI elements? - if (data.totalcontrols > data.startindex + (data.controls.length - 1)) { - websock.send("uiok:" + (data.startindex + (data.controls.length - 1))); - } - break; - - case UI_RELOAD: - window.location.reload(); - break; - - case UI_TITEL: - document.title = data.label; - $("#mainHeader").html(data.label); - break; - - /* - Most elements have the same behaviour when added. - */ - case UI_LABEL: - case UI_NUMBER: - case UI_TEXT_INPUT: - case UI_SELECT: - case UI_GAUGE: - case UI_SEPARATOR: - if (data.visible) addToHTML(data); - break; - - /* - These elements must call additional functions after being added to the DOM - */ - case UI_BUTTON: - if (data.visible) { - addToHTML(data); - $("#btn" + data.id).on({ - touchstart: function (e) { - e.preventDefault(); - buttonclick(data.id, true); - }, - touchend: function (e) { - e.preventDefault(); - buttonclick(data.id, false); - }, - }); - } - break; - - case UI_SWITCHER: - if (data.visible) { - addToHTML(data); - switcher(data.id, data.value); - } - break; - - case UI_CPAD: - case UI_PAD: - if (data.visible) { - addToHTML(data); - $("#pf" + data.id).on({ - touchstart: function (e) { - e.preventDefault(); - padclick(UP, data.id, true); - }, - touchend: function (e) { - e.preventDefault(); - padclick(UP, data.id, false); - }, - }); - $("#pl" + data.id).on({ - touchstart: function (e) { - e.preventDefault(); - padclick(LEFT, data.id, true); - }, - touchend: function (e) { - e.preventDefault(); - padclick(LEFT, data.id, false); - }, - }); - $("#pr" + data.id).on({ - touchstart: function (e) { - e.preventDefault(); - padclick(RIGHT, data.id, true); - }, - touchend: function (e) { - e.preventDefault(); - padclick(RIGHT, data.id, false); - }, - }); - $("#pb" + data.id).on({ - touchstart: function (e) { - e.preventDefault(); - padclick(DOWN, data.id, true); - }, - touchend: function (e) { - e.preventDefault(); - padclick(DOWN, data.id, false); - }, - }); - $("#pc" + data.id).on({ - touchstart: function (e) { - e.preventDefault(); - padclick(CENTER, data.id, true); - }, - touchend: function (e) { - e.preventDefault(); - padclick(CENTER, data.id, false); - }, - }); - } - break; - - case UI_SLIDER: - //https://codepen.io/seanstopnik/pen/CeLqA - if (data.visible) { - addToHTML(data); - rangeSlider(!sliderContinuous); - } - break; - - case UI_TAB: - if (data.visible) { - $("#tabsnav").append( - "
  • " + data.value + "
  • " - ); - $("#tabscontent").append("
    "); - - tabs = $(".tabscontent").tabbedContent({ loop: true }).data("api"); - // switch to tab... - $("a") - .filter(function () { - return $(this).attr("href") === "#click-to-switch"; - }) - .on("click", function (e) { - var tab = prompt("Tab to switch to (number or id)?"); - if (!tabs.switchTab(tab)) { - alert("That tab does not exist :\\"); - } - e.preventDefault(); - }); - } - break; - - case UI_OPTION: - if (data.parentControl) { - var parent = $("#select" + data.parentControl); - parent.append( - "" - ); - } - break; - - case UI_MIN: - if (data.parentControl) { - //Is it applied to a slider? - if ($('#sl' + data.parentControl).length) { - $('#sl' + data.parentControl).attr("min", data.value); - } else if ($('#num' + data.parentControl).length) { - //Or a number - $('#num' + data.parentControl).attr("min", data.value); - } - } - break; - - case UI_MAX: - if (data.parentControl) { - //Is it applied to a slider? - if ($('#sl' + data.parentControl).length) { - $('#sl' + data.parentControl).attr("max", data.value); - } else if ($('#text' + data.parentControl).length) { - //Is it a text element - $('#text' + data.parentControl).attr("maxlength", data.value); - } else if ($('#num' + data.parentControl).length) { - //Or a number - $('#num' + data.parentControl).attr("max", data.value); - } - } - break; - - case UI_STEP: - if (data.parentControl) { - //Is it applied to a slider? - if ($('#sl' + data.parentControl).length) { - $('#sl' + data.parentControl).attr("step", data.value); - } else if ($('#num' + data.parentControl).length) { - //Or a number - $('#num' + data.parentControl).attr("step", data.value); - } - } - break; - - case UI_GRAPH: - if (data.visible) { - addToHTML(data); - graphData[data.id] = restoreGraphData(data.id); - renderGraphSvg(graphData[data.id], "graph" + data.id); - } - break; - case ADD_GRAPH_POINT: - var ts = new Date().getTime(); - graphData[data.id].push({ x: ts, y: data.value }); - saveGraphData(); - renderGraphSvg(graphData[data.id], "graph" + data.id); - break; - case CLEAR_GRAPH: - graphData[data.id] = []; - saveGraphData(); - renderGraphSvg(graphData[data.id], "graph" + data.id); - break; - - case UI_ACCEL: - if (hasAccel) break; - hasAccel = true; - if (data.visible) { - addToHTML(data); - requestOrientationPermission(); - } - break; - - case UI_FILEDISPLAY: - if (data.visible) - { - addToHTML(data); - FileDisplayUploadFile(data); - } - break; - - /* - * Update messages change the value/style of a component without adding new HTML - */ - case UPDATE_LABEL: - $("#l" + data.id).html(data.value); - if (data.hasOwnProperty('elementStyle')) { - $("#l" + data.id).attr("style", data.elementStyle); - } - break; - - case UPDATE_SWITCHER: - switcher(data.id, data.value == "0" ? 0 : 1); - if (data.hasOwnProperty('elementStyle')) { - $("#sl" + data.id).attr("style", data.elementStyle); - } - break; - - case UPDATE_SLIDER: - $("#sl" + data.id).attr("value", data.value) - slider_move($("#sl" + data.id).parent().parent(), data.value, "100", false); - if (data.hasOwnProperty('elementStyle')) { - $("#sl" + data.id).attr("style", data.elementStyle); - } - break; - - case UPDATE_NUMBER: - $("#num" + data.id).val(data.value); - if (data.hasOwnProperty('elementStyle')) { - $("#num" + data.id).attr("style", data.elementStyle); - } - break; - - case UPDATE_TEXT_INPUT: - $("#text" + data.id).val(data.value); - if (data.hasOwnProperty('elementStyle')) { - $("#text" + data.id).attr("style", data.elementStyle); - } - if (data.hasOwnProperty('inputType')) { - $("#text" + data.id).attr("type", data.inputType); - } - break; - - case UPDATE_SELECT: - $("#select" + data.id).val(data.value); - if (data.hasOwnProperty('elementStyle')) { - $("#select" + data.id).attr("style", data.elementStyle); - } - break; - - case UPDATE_BUTTON: - $("#btn" + data.id).val(data.value); - $("#btn" + data.id).text(data.value); - if (data.hasOwnProperty('elementStyle')) { - $("#btn" + data.id).attr("style", data.elementStyle); - } - break; - - case UPDATE_PAD: - case UPDATE_CPAD: - break; - case UPDATE_GAUGE: - $("#gauge" + data.id).val(data.value); - if (data.hasOwnProperty('elementStyle')) { - $("#gauge" + data.id).attr("style", data.elementStyle); - } - break; - case UPDATE_ACCEL: - break; - - case UPDATE_TIME: - var rv = new Date().toISOString(); - websock.send("time:" + rv + ":" + data.id); - break; - - case UPDATE_FILEDISPLAY: - FileDisplayUploadFile(data); - break; - - case UI_FRAGMENT: - // console.info("Starting Fragment Processing"); - let FragmentLen = data.length; - let FragementOffset = data.offset; - let NextFragmentOffset = FragementOffset + FragmentLen; - let Total = data.total; - let Arrived = (FragmentLen + FragementOffset); - let FragmentFinal = Total === Arrived; - // console.info("UI_FRAGMENT:FragmentLen '" + FragmentLen + "'"); - // console.info("UI_FRAGMENT:FragementOffset '" + FragementOffset + "'"); - // console.info("UI_FRAGMENT:NextFragmentOffset '" + NextFragmentOffset + "'"); - // console.info("UI_FRAGMENT:Total '" + Total + "'"); - // console.info("UI_FRAGMENT:Arrived '" + Arrived + "'"); - // console.info("UI_FRAGMENT:FragmentFinal '" + FragmentFinal + "'"); - - if (!data.hasOwnProperty('control')) - { - console.error("UI_FRAGMENT:Missing control record, skipping control"); - // console.info("Done Fragment Processing"); - break; - } - let control = data.control; - StopFragmentAssemblyTimer(data.control.id); - - // is this the first fragment? - if(0 === FragementOffset) - { - // console.info("Found first fragment"); - controlAssemblyArray[control.id] = data; - // console.info("Value: " + controlAssemblyArray[control.id].control.value); - controlAssemblyArray[control.id].offset = NextFragmentOffset; - StartFragmentAssemblyTimer(control.id); - let TotalRequest = JSON.stringify({ 'id' : control.id, 'offset' : NextFragmentOffset }); - websock.send("uifragmentok:" + 0 + ": " + TotalRequest + ":"); - // console.info("asked for fragment " + TotalRequest); - // console.info("Done Fragment Processing"); - break; - } - - // not first fragment. are we assembling this control? - if("undefined" === typeof controlAssemblyArray[control.id]) - { - // it looks like we missed the first fragment. Start the control over - console.error("Missing first fragment for control: " + control.id); - StartFragmentAssemblyTimer(control.id); - let TotalRequest = JSON.stringify({ 'id' : control.id, 'offset' : 0 }); - websock.send("uifragmentok:" + 0 + ": " + TotalRequest + ":"); - // console.info("asked for fragment " + TotalRequest); - // console.info("Done Fragment Processing"); - break; - } - - // is this the expected next fragment - if(FragementOffset !== controlAssemblyArray[control.id].offset) - { - console.error("Wrong next fragment. Expected: " + controlAssemblyArray[control.id].offset + " Got: " + FragementOffset); - StartFragmentAssemblyTimer(control.id); - let TotalRequest = JSON.stringify({ 'id' : control.id, 'offset' : controlAssemblyArray[control.id].length + controlAssemblyArray[control.id].offset }); - websock.send("uifragmentok:" + 0 + ": " + TotalRequest + ":"); - // console.info("asked for the expected fragment: " + TotalRequest); - // console.info("Done Fragment Processing"); - break; - } - - // console.info("Add to existing fragment"); - controlAssemblyArray[control.id].control.value += control.value; - controlAssemblyArray[control.id].offset = NextFragmentOffset; - // console.info("Value: " + controlAssemblyArray[control.id].control.value); - - if(true === FragmentFinal) - { - var fauxEvent = { - data: JSON.stringify(controlAssemblyArray[control.id].control), - }; - handleEvent(fauxEvent); - controlAssemblyArray[control.id] = null; - // console.info("Found last fragment"); - } - else - { - // console.info("Ask for next fragment."); - StartFragmentAssemblyTimer(control.id); - let TotalRequest = JSON.stringify({ 'id' : control.id, 'offset' : NextFragmentOffset}); - websock.send("uifragmentok:" + 0 + ": " + TotalRequest + ":"); - // console.info("asked for the next fragment: " + TotalRequest); - } - // console.info("Done Fragment Processing"); - break; - - default: - console.error("Unknown type or event"); - break; - } - - if (data.type >= UI_TITEL && data.type < UPDATE_OFFSET) { - //A UI element was just added to the DOM - processEnabled(data); - } - - if (data.type >= UPDATE_OFFSET && data.type < UI_INITIAL_GUI) { - //An "update" message was just recieved and processed - var element = $("#id" + data.id); - - if (data.hasOwnProperty('panelStyle')) { - $("#id" + data.id).attr("style", data.panelStyle); - } - - if (data.hasOwnProperty('visible')) { - if (data['visible']) - $("#id" + data.id).show(); - else - $("#id" + data.id).hide(); - } - - if (data.type == UPDATE_SLIDER) { - element.removeClass( - "slider-turquoise slider-emerald slider-peterriver slider-wetasphalt slider-sunflower slider-carrot slider-alizarin" - ); - element.addClass("slider-" + colorClass(data.color)); - } else { - element.removeClass( - "turquoise emerald peterriver wetasphalt sunflower carrot alizarin" - ); - element.addClass(colorClass(data.color)); - } - - processEnabled(data); - } - - $(".range-slider__range").each(function () { - $(this)[0].value = $(this).attr("value"); - $(this).next().html($(this).attr("value")); - }); - }; - - websock.onmessage = handleEvent; -} - -async function FileDisplayUploadFile(data) -{ - let text = await downloadFile(data.value); - let ItemToUpdateId = "fd" + data.id; - // console.info("ItemToUpdateId: " + ItemToUpdateId); - // console.info(" text: " + text); - // populate the text object - $("#" + ItemToUpdateId).val(text); - $("#" + ItemToUpdateId).css("textAlign", "left"); - $("#" + ItemToUpdateId).css("white-space", "nowrap"); - $("#" + ItemToUpdateId).css("overflow", "scroll"); - $("#" + ItemToUpdateId).css("overflow-y", "scroll"); - $("#" + ItemToUpdateId).css("overflow-x", "scroll"); - $("#" + ItemToUpdateId).scrollTop($("#" + ItemToUpdateId).val().length); - - // scroll the page to the updated control - // $("#" + ItemToUpdateId).focus(); - -} // FileDisplayUploadFile - -async function downloadFile(filename) -{ - let response = await fetch(filename); - - if(response.status != 200) { - throw new Error("File Read Server Error: '" + response.status + "'"); - } - - // read response stream as text - let text_data = await response.text(); - - return text_data; -} // downloadFile - -function StartFragmentAssemblyTimer(Id) -{ - StopFragmentAssemblyTimer(Id); - FragmentAssemblyTimer[Id] = setInterval(function(_Id) - { - // does the fragment assembly still exist? - if("undefined" !== typeof controlAssemblyArray[_Id]) - { - if(null !== controlAssemblyArray[_Id]) - { - // we have a valid control that is being assembled - // ask for the next part - let TotalRequest = JSON.stringify({ 'id' : controlAssemblyArray[_Id].control.id, 'offset' : controlAssemblyArray[_Id].offset}); - websock.send("uifragmentok:" + 0 + ": " + TotalRequest + ":"); - } - } - }, 1000, Id); -} - -function StopFragmentAssemblyTimer(Id) -{ - if("undefined" !== typeof FragmentAssemblyTimer[Id]) - { - if(FragmentAssemblyTimer[Id]) - { - clearInterval(FragmentAssemblyTimer[Id]); - } - } -} - -function sliderchange(number) { - var val = $("#sl" + number).val(); - websock.send("slvalue:" + val + ":" + number); - - $(".range-slider__range").each(function () { - $(this).attr("value", $(this)[0].value); - }); -} - -function numberchange(number) { - var val = $("#num" + number).val(); - websock.send("nvalue:" + val + ":" + number); -} - -function textchange(number) { - var val = $("#text" + number).val(); - websock.send("tvalue:" + val + ":" + number); -} - -function tabclick(number) { - var val = $("#tab" + number).val(); - websock.send("tabvalue:" + val + ":" + number); -} - -function selectchange(number) { - var val = $("#select" + number).val(); - websock.send("svalue:" + val + ":" + number); -} - -function buttonclick(number, isdown) { - if (isdown) websock.send("bdown:" + number); - else websock.send("bup:" + number); -} - -function padclick(type, number, isdown) { - if ($("#id" + number + " nav").hasClass("disabled")) { - return; - } - switch (type) { - case CENTER: - if (isdown) websock.send("pcdown:" + number); - else websock.send("pcup:" + number); - break; - case UP: - if (isdown) websock.send("pfdown:" + number); - else websock.send("pfup:" + number); - break; - case DOWN: - if (isdown) websock.send("pbdown:" + number); - else websock.send("pbup:" + number); - break; - case LEFT: - if (isdown) websock.send("pldown:" + number); - else websock.send("plup:" + number); - break; - case RIGHT: - if (isdown) websock.send("prdown:" + number); - else websock.send("prup:" + number); - break; - } -} - -function switcher(number, state) { - if (state == null) { - if (!$("#sl" + number).hasClass("checked")) { - websock.send("sactive:" + number); - $("#sl" + number).addClass("checked"); - } else { - websock.send("sinactive:" + number); - $("#sl" + number).removeClass("checked"); - } - } else if (state == 1) { - $("#sl" + number).addClass("checked"); - $("#sl" + number).prop("checked", true); - } else if (state == 0) { - $("#sl" + number).removeClass("checked"); - $("#sl" + number).prop("checked", false); - } -} - -var rangeSlider = function (isDiscrete) { - var range = $(".range-slider__range"); - var slidercb = function () { - sliderchange($(this).attr("id").replace(/^\D+/g, "")); - }; - - range.on({ - input: function () { - $(this).next().html(this.value) - } - }); - - range.each(function () { - $(this).next().html(this.value); - if ($(this).attr("callbackSet") != "true") { - if (!isDiscrete) { - $(this).on({ input: slidercb }); //input fires when dragging - } else { - $(this).on({ change: slidercb }); //change fires only once released - } - $(this).attr("callbackSet", "true"); - } - }); -}; - - -var addToHTML = function (data) { - panelStyle = data.hasOwnProperty('panelStyle') ? " style='" + data.panelStyle + "' " : ""; - panelwide = data.hasOwnProperty('wide') ? "wide" : ""; - - if (!data.hasOwnProperty('parentControl') || $("#tab" + data.parentControl).length > 0) { - //We add the control with its own panel - var parent = data.hasOwnProperty('parentControl') ? - $("#tab" + data.parentControl) : - $("#row"); - - var html = ""; - switch (data.type) { - case UI_LABEL: - case UI_BUTTON: - case UI_SWITCHER: - case UI_CPAD: - case UI_PAD: - case UI_SLIDER: - case UI_NUMBER: - case UI_TEXT_INPUT: - case UI_SELECT: - case UI_GRAPH: - case UI_GAUGE: - case UI_ACCEL: - case UI_FILEDISPLAY: - html = "
    " + data.label + "

    " + - elementHTML(data) + - "
    "; - break; - - case UI_SEPARATOR: - html = "
    " + - "
    " + data.label + "

    "; - break; - case UI_TIME: - //Invisible element - break; - } - - parent.append(html); - - } else { - //We are adding to an existing panel so we only need the HTML for the element - var parent = $("#id" + data.parentControl); - parent.append(elementHTML(data)); - } -} - -var elementHTML = function (data) { - var id = data.id - var elementStyle = data.hasOwnProperty('elementStyle') ? " style='" + data.elementStyle + "' " : ""; - var inputType = data.hasOwnProperty('inputType') ? " type='" + data.inputType + "' " : ""; - switch (data.type) { - case UI_LABEL: - return "" + data.value + ""; - case UI_FILEDISPLAY: - return ""; - case UI_BUTTON: - return ""; - case UI_SWITCHER: - return ""; - case UI_CPAD: - case UI_PAD: - return ""; - case UI_SLIDER: - return "
    " + - "" + - data.value + "
    "; - case UI_NUMBER: - return ""; - case UI_TEXT_INPUT: - return ""; - case UI_SELECT: - return ""; - case UI_ACCEL: - return "ACCEL // Not implemented fully!
    ";
    -        default:
    -            return "";
    -    }
    -}
    -
    -var processEnabled = function (data) {
    -    //Handle the enabling and disabling of controls
    -    //Most controls can be disabled through the use of $("#").prop("disabled", true) and CSS will style it accordingly
    -    //The switcher and pads also require the addition of the "disabled" class
    -    switch (data.type) {
    -        case UI_SWITCHER:
    -        case UPDATE_SWITCHER:
    -            if (data.enabled) {
    -                $("#sl" + data.id).removeClass('disabled');
    -                $("#s" + data.id).prop("disabled", false);
    -            } else {
    -                $("#sl" + data.id).addClass('disabled');
    -                $("#s" + data.id).prop("disabled", true);
    -            }
    -            break;
    -
    -        case UI_SLIDER:
    -        case UPDATE_SLIDER:
    -            $("#sl" + data.id).prop("disabled", !data.enabled);
    -            break;
    -
    -        case UI_NUMBER:
    -        case UPDATE_NUMBER:
    -            $("#num" + data.id).prop("disabled", !data.enabled);
    -            break;
    -
    -        case UI_TEXT_INPUT:
    -        case UPDATE_TEXT_INPUT:
    -            $("#text" + data.id).prop("disabled", !data.enabled);
    -            break;
    -
    -        case UI_SELECT:
    -        case UPDATE_SELECT:
    -            $("#select" + data.id).prop("disabled", !data.enabled);
    -            break;
    -
    -        case UI_BUTTON:
    -        case UPDATE_BUTTON:
    -            $("#btn" + data.id).prop("disabled", !data.enabled);
    -            break;
    -
    -        case UI_PAD:
    -        case UI_CPAD:
    -        case UPDATE_PAD:
    -        case UPDATE_CPAD:
    -        case UI_FILEDISPLAY:
    -        case UPDATE_FILEDISPLAY:
    -            if (data.enabled) {
    -                $("#id" + data.id + " nav").removeClass('disabled');
    -            } else {
    -                $("#id" + data.id + " nav").addClass('disabled');
    -            }
    -            break;
    -    }
    -}
    diff --git a/watering/lib/ESPUI/data/js/controls.min.js b/watering/lib/ESPUI/data/js/controls.min.js
    deleted file mode 100644
    index 80d9035..0000000
    --- a/watering/lib/ESPUI/data/js/controls.min.js
    +++ /dev/null
    @@ -1,136 +0,0 @@
    -const UI_INITIAL_GUI=200;const UI_RELOAD=201;const UPDATE_OFFSET=100;const UI_EXTEND_GUI=210;const UI_TITEL=0;const UI_PAD=1;const UPDATE_PAD=101;const UI_CPAD=2;const UPDATE_CPAD=102;const UI_BUTTON=3;const UPDATE_BUTTON=103;const UI_LABEL=4;const UPDATE_LABEL=104;const UI_SWITCHER=5;const UPDATE_SWITCHER=105;const UI_SLIDER=6;const UPDATE_SLIDER=106;const UI_NUMBER=7;const UPDATE_NUMBER=107;const UI_TEXT_INPUT=8;const UPDATE_TEXT_INPUT=108;const UI_GRAPH=9;const ADD_GRAPH_POINT=10;const CLEAR_GRAPH=109;const UI_TAB=11;const UPDATE_TAB=111;const UI_SELECT=12;const UPDATE_SELECT=112;const UI_OPTION=13;const UPDATE_OPTION=113;const UI_MIN=14;const UPDATE_MIN=114;const UI_MAX=15;const UPDATE_MAX=115;const UI_STEP=16;const UPDATE_STEP=116;const UI_GAUGE=17;const UPDATE_GAUGE=117;const UI_ACCEL=18;const UPDATE_ACCEL=118;const UI_SEPARATOR=19;const UPDATE_SEPARATOR=119;const UI_TIME=20;const UPDATE_TIME=120;const UI_FILEDISPLAY=21;const UPDATE_FILEDISPLAY=121;const UI_FRAGMENT=98;const UP=0;const DOWN=1;const LEFT=2;const RIGHT=3;const CENTER=4;const C_TURQUOISE=0;const C_EMERALD=1;const C_PETERRIVER=2;const C_WETASPHALT=3;const C_SUNFLOWER=4;const C_CARROT=5;const C_ALIZARIN=6;const C_DARK=7;const C_NONE=255;var controlAssemblyArray=new Object();var FragmentAssemblyTimer=new Array();var graphData=new Array();var hasAccel=false;var sliderContinuous=false;function colorClass(colorId){colorId=Number(colorId);switch(colorId){case C_TURQUOISE:return"turquoise";case C_EMERALD:return"emerald";case C_PETERRIVER:return"peterriver";case C_WETASPHALT:return"wetasphalt";case C_SUNFLOWER:return"sunflower";case C_CARROT:return"carrot";case C_ALIZARIN:return"alizarin";case C_DARK:case C_NONE:return"dark";default:return"";}}
    -var websock;var websockConnected=false;var WebSocketTimer=null;function requestOrientationPermission(){}
    -function saveGraphData(){localStorage.setItem("espuigraphs",JSON.stringify(graphData));}
    -function restoreGraphData(id){var savedData=localStorage.getItem("espuigraphs",graphData);if(savedData!=null){savedData=JSON.parse(savedData);let idData=savedData[id];return Array.isArray(idData)?idData:[];}
    -return[];}
    -function restart(){$(document).add("*").off();$("#row").html("");conStatusError();start();}
    -function conStatusError(){FragmentAssemblyTimer.forEach(element=>{clearInterval(element);});FragmentAssemblyTimer=new Array();controlAssemblyArray=new Array();if(true===websockConnected){websockConnected=false;websock.close();$("#conStatus").removeClass("color-green");$("#conStatus").addClass("color-red");$("#conStatus").html("Error / No Connection ↻");$("#conStatus").off();$("#conStatus").on({click:restart,});}}
    -function handleVisibilityChange(){if(!websockConnected&&!document.hidden){restart();}}
    -function start(){let location=window.location.hostname;let port=window.location.port;document.addEventListener("visibilitychange",handleVisibilityChange,false);if(port!=""||port!=80||port!=443){websock=new WebSocket("ws://"+location+":"+port+"/ws");}else{websock=new WebSocket("ws://"+location+"/ws");}
    -if(null===WebSocketTimer){WebSocketTimer=setInterval(function(){if(websock.readyState===3){restart();}},5000);}
    -websock.onopen=function(evt){console.log("websock open");$("#conStatus").addClass("color-green");$("#conStatus").text("Connected");websockConnected=true;FragmentAssemblyTimer.forEach(element=>{clearInterval(element);});FragmentAssemblyTimer=new Array();controlAssemblyArray=new Array();};websock.onclose=function(evt){console.log("websock close");conStatusError();FragmentAssemblyTimer.forEach(element=>{clearInterval(element);});FragmentAssemblyTimer=new Array();controlAssemblyArray=new Array();};websock.onerror=function(evt){console.log("websock Error");restart();FragmentAssemblyTimer.forEach(element=>{clearInterval(element);});FragmentAssemblyTimer=new Array();controlAssemblyArray=new Array();};var handleEvent=function(evt){try{var data=JSON.parse(evt.data);}
    -catch(Event){console.error(Event);websock.send("uiok:"+0);return;}
    -var e=document.body;var center="";switch(data.type){case UI_INITIAL_GUI:$("#row").html("");$("#tabsnav").html("");$("#tabscontent").html("");if(data.sliderContinuous){sliderContinuous=data.sliderContinuous;}
    -data.controls.forEach(element=>{var fauxEvent={data:JSON.stringify(element),};handleEvent(fauxEvent);});if(data.totalcontrols>(data.controls.length-1)){websock.send("uiok:"+(data.controls.length-1));}
    -break;case UI_EXTEND_GUI:data.controls.forEach(element=>{var fauxEvent={data:JSON.stringify(element),};handleEvent(fauxEvent);});if(data.totalcontrols>data.startindex+(data.controls.length-1)){websock.send("uiok:"+(data.startindex+(data.controls.length-1)));}
    -break;case UI_RELOAD:window.location.reload();break;case UI_TITEL:document.title=data.label;$("#mainHeader").html(data.label);break;case UI_LABEL:case UI_NUMBER:case UI_TEXT_INPUT:case UI_SELECT:case UI_GAUGE:case UI_SEPARATOR:if(data.visible)addToHTML(data);break;case UI_BUTTON:if(data.visible){addToHTML(data);$("#btn"+data.id).on({touchstart:function(e){e.preventDefault();buttonclick(data.id,true);},touchend:function(e){e.preventDefault();buttonclick(data.id,false);},});}
    -break;case UI_SWITCHER:if(data.visible){addToHTML(data);switcher(data.id,data.value);}
    -break;case UI_CPAD:case UI_PAD:if(data.visible){addToHTML(data);$("#pf"+data.id).on({touchstart:function(e){e.preventDefault();padclick(UP,data.id,true);},touchend:function(e){e.preventDefault();padclick(UP,data.id,false);},});$("#pl"+data.id).on({touchstart:function(e){e.preventDefault();padclick(LEFT,data.id,true);},touchend:function(e){e.preventDefault();padclick(LEFT,data.id,false);},});$("#pr"+data.id).on({touchstart:function(e){e.preventDefault();padclick(RIGHT,data.id,true);},touchend:function(e){e.preventDefault();padclick(RIGHT,data.id,false);},});$("#pb"+data.id).on({touchstart:function(e){e.preventDefault();padclick(DOWN,data.id,true);},touchend:function(e){e.preventDefault();padclick(DOWN,data.id,false);},});$("#pc"+data.id).on({touchstart:function(e){e.preventDefault();padclick(CENTER,data.id,true);},touchend:function(e){e.preventDefault();padclick(CENTER,data.id,false);},});}
    -break;case UI_SLIDER:if(data.visible){addToHTML(data);rangeSlider(!sliderContinuous);}
    -break;case UI_TAB:if(data.visible){$("#tabsnav").append("
  • "+data.value+"
  • ");$("#tabscontent").append("
    ");tabs=$(".tabscontent").tabbedContent({loop:true}).data("api");$("a").filter(function(){return $(this).attr("href")==="#click-to-switch";}).on("click",function(e){var tab=prompt("Tab to switch to (number or id)?");if(!tabs.switchTab(tab)){alert("That tab does not exist :\\");} -e.preventDefault();});} -break;case UI_OPTION:if(data.parentControl){var parent=$("#select"+data.parentControl);parent.append("");} -break;case UI_MIN:if(data.parentControl){if($('#sl'+data.parentControl).length){$('#sl'+data.parentControl).attr("min",data.value);}else if($('#num'+data.parentControl).length){$('#num'+data.parentControl).attr("min",data.value);}} -break;case UI_MAX:if(data.parentControl){if($('#sl'+data.parentControl).length){$('#sl'+data.parentControl).attr("max",data.value);}else if($('#text'+data.parentControl).length){$('#text'+data.parentControl).attr("maxlength",data.value);}else if($('#num'+data.parentControl).length){$('#num'+data.parentControl).attr("max",data.value);}} -break;case UI_STEP:if(data.parentControl){if($('#sl'+data.parentControl).length){$('#sl'+data.parentControl).attr("step",data.value);}else if($('#num'+data.parentControl).length){$('#num'+data.parentControl).attr("step",data.value);}} -break;case UI_GRAPH:if(data.visible){addToHTML(data);graphData[data.id]=restoreGraphData(data.id);renderGraphSvg(graphData[data.id],"graph"+data.id);} -break;case ADD_GRAPH_POINT:var ts=new Date().getTime();graphData[data.id].push({x:ts,y:data.value});saveGraphData();renderGraphSvg(graphData[data.id],"graph"+data.id);break;case CLEAR_GRAPH:graphData[data.id]=[];saveGraphData();renderGraphSvg(graphData[data.id],"graph"+data.id);break;case UI_ACCEL:if(hasAccel)break;hasAccel=true;if(data.visible){addToHTML(data);requestOrientationPermission();} -break;case UI_FILEDISPLAY:if(data.visible) -{addToHTML(data);FileDisplayUploadFile(data);} -break;case UPDATE_LABEL:$("#l"+data.id).html(data.value);if(data.hasOwnProperty('elementStyle')){$("#l"+data.id).attr("style",data.elementStyle);} -break;case UPDATE_SWITCHER:switcher(data.id,data.value=="0"?0:1);if(data.hasOwnProperty('elementStyle')){$("#sl"+data.id).attr("style",data.elementStyle);} -break;case UPDATE_SLIDER:$("#sl"+data.id).attr("value",data.value) -slider_move($("#sl"+data.id).parent().parent(),data.value,"100",false);if(data.hasOwnProperty('elementStyle')){$("#sl"+data.id).attr("style",data.elementStyle);} -break;case UPDATE_NUMBER:$("#num"+data.id).val(data.value);if(data.hasOwnProperty('elementStyle')){$("#num"+data.id).attr("style",data.elementStyle);} -break;case UPDATE_TEXT_INPUT:$("#text"+data.id).val(data.value);if(data.hasOwnProperty('elementStyle')){$("#text"+data.id).attr("style",data.elementStyle);} -if(data.hasOwnProperty('inputType')){$("#text"+data.id).attr("type",data.inputType);} -break;case UPDATE_SELECT:$("#select"+data.id).val(data.value);if(data.hasOwnProperty('elementStyle')){$("#select"+data.id).attr("style",data.elementStyle);} -break;case UPDATE_BUTTON:$("#btn"+data.id).val(data.value);$("#btn"+data.id).text(data.value);if(data.hasOwnProperty('elementStyle')){$("#btn"+data.id).attr("style",data.elementStyle);} -break;case UPDATE_PAD:case UPDATE_CPAD:break;case UPDATE_GAUGE:$("#gauge"+data.id).val(data.value);if(data.hasOwnProperty('elementStyle')){$("#gauge"+data.id).attr("style",data.elementStyle);} -break;case UPDATE_ACCEL:break;case UPDATE_TIME:var rv=new Date().toISOString();websock.send("time:"+rv+":"+data.id);break;case UPDATE_FILEDISPLAY:FileDisplayUploadFile(data);break;case UI_FRAGMENT:let FragmentLen=data.length;let FragementOffset=data.offset;let NextFragmentOffset=FragementOffset+FragmentLen;let Total=data.total;let Arrived=(FragmentLen+FragementOffset);let FragmentFinal=Total===Arrived;if(!data.hasOwnProperty('control')) -{console.error("UI_FRAGMENT:Missing control record, skipping control");break;} -let control=data.control;StopFragmentAssemblyTimer(data.control.id);if(0===FragementOffset) -{controlAssemblyArray[control.id]=data;controlAssemblyArray[control.id].offset=NextFragmentOffset;StartFragmentAssemblyTimer(control.id);let TotalRequest=JSON.stringify({'id':control.id,'offset':NextFragmentOffset});websock.send("uifragmentok:"+0+": "+TotalRequest+":");break;} -if("undefined"===typeof controlAssemblyArray[control.id]) -{console.error("Missing first fragment for control: "+control.id);StartFragmentAssemblyTimer(control.id);let TotalRequest=JSON.stringify({'id':control.id,'offset':0});websock.send("uifragmentok:"+0+": "+TotalRequest+":");break;} -if(FragementOffset!==controlAssemblyArray[control.id].offset) -{console.error("Wrong next fragment. Expected: "+controlAssemblyArray[control.id].offset+" Got: "+FragementOffset);StartFragmentAssemblyTimer(control.id);let TotalRequest=JSON.stringify({'id':control.id,'offset':controlAssemblyArray[control.id].length+controlAssemblyArray[control.id].offset});websock.send("uifragmentok:"+0+": "+TotalRequest+":");break;} -controlAssemblyArray[control.id].control.value+=control.value;controlAssemblyArray[control.id].offset=NextFragmentOffset;if(true===FragmentFinal) -{var fauxEvent={data:JSON.stringify(controlAssemblyArray[control.id].control),};handleEvent(fauxEvent);controlAssemblyArray[control.id]=null;} -else -{StartFragmentAssemblyTimer(control.id);let TotalRequest=JSON.stringify({'id':control.id,'offset':NextFragmentOffset});websock.send("uifragmentok:"+0+": "+TotalRequest+":");} -break;default:console.error("Unknown type or event");break;} -if(data.type>=UI_TITEL&&data.type=UPDATE_OFFSET&&data.type0){var parent=data.hasOwnProperty('parentControl')?$("#tab"+data.parentControl):$("#row");var html="";switch(data.type){case UI_LABEL:case UI_BUTTON:case UI_SWITCHER:case UI_CPAD:case UI_PAD:case UI_SLIDER:case UI_NUMBER:case UI_TEXT_INPUT:case UI_SELECT:case UI_GRAPH:case UI_GAUGE:case UI_ACCEL:case UI_FILEDISPLAY:html="
    "+data.label+"

    "+ -elementHTML(data)+ -"
    ";break;case UI_SEPARATOR:html="
    "+ -"
    "+data.label+"

    ";break;case UI_TIME:break;} -parent.append(html);}else{var parent=$("#id"+data.parentControl);parent.append(elementHTML(data));}} -var elementHTML=function(data){var id=data.id -var elementStyle=data.hasOwnProperty('elementStyle')?" style='"+data.elementStyle+"' ":"";var inputType=data.hasOwnProperty('inputType')?" type='"+data.inputType+"' ":"";switch(data.type){case UI_LABEL:return""+data.value+"";case UI_FILEDISPLAY:return"";case UI_BUTTON:return"";case UI_SWITCHER:return"";case UI_CPAD:case UI_PAD:return"";case UI_SLIDER:return"
    "+ -""+ -data.value+"
    ";case UI_NUMBER:return"";case UI_TEXT_INPUT:return"";case UI_SELECT:return"";case UI_ACCEL:return"ACCEL // Not implemented fully!
    ";default:return"";}}
    -var processEnabled=function(data){switch(data.type){case UI_SWITCHER:case UPDATE_SWITCHER:if(data.enabled){$("#sl"+data.id).removeClass('disabled');$("#s"+data.id).prop("disabled",false);}else{$("#sl"+data.id).addClass('disabled');$("#s"+data.id).prop("disabled",true);}
    -break;case UI_SLIDER:case UPDATE_SLIDER:$("#sl"+data.id).prop("disabled",!data.enabled);break;case UI_NUMBER:case UPDATE_NUMBER:$("#num"+data.id).prop("disabled",!data.enabled);break;case UI_TEXT_INPUT:case UPDATE_TEXT_INPUT:$("#text"+data.id).prop("disabled",!data.enabled);break;case UI_SELECT:case UPDATE_SELECT:$("#select"+data.id).prop("disabled",!data.enabled);break;case UI_BUTTON:case UPDATE_BUTTON:$("#btn"+data.id).prop("disabled",!data.enabled);break;case UI_PAD:case UI_CPAD:case UPDATE_PAD:case UPDATE_CPAD:case UI_FILEDISPLAY:case UPDATE_FILEDISPLAY:if(data.enabled){$("#id"+data.id+" nav").removeClass('disabled');}else{$("#id"+data.id+" nav").addClass('disabled');}
    -break;}}
    \ No newline at end of file
    diff --git a/watering/lib/ESPUI/data/js/graph.js b/watering/lib/ESPUI/data/js/graph.js
    deleted file mode 100644
    index 4f470c9..0000000
    --- a/watering/lib/ESPUI/data/js/graph.js
    +++ /dev/null
    @@ -1,297 +0,0 @@
    -function lineGraph(parent, xAccessor, yAccessor) {
    -  // Constant size definitions TODO: this could well be improved and calculated...
    -  const width = 620;
    -  const height = 420;
    -  const gutter = 40;
    -  const pixelsPerTick = 30;
    -
    -  /**
    -   * Creates an object that contatins transform functions that:
    -   *   transforms numeric data into coordinate space, linearly
    -   *   transforms coordinates into numeric data, linearly
    -   */
    -  function numericTransformer(dataMin, dataMax, pxMin, pxMax) {
    -    var dataDiff = dataMax - dataMin,
    -      pxDiff = pxMax - pxMin,
    -      dataRatio = pxDiff / dataDiff,
    -      coordRatio = dataDiff / pxDiff;
    -
    -    return {
    -      // transforms a data point to a coordinate point
    -      toCoord: function(data) {
    -        return (data - dataMin) * dataRatio + pxMin;
    -      },
    -      // transforms a coord point to a data point
    -      toData: function(coord) {
    -        return (coord - pxMin) * coordRatio + dataMin;
    -      }
    -    };
    -  }
    -
    -  /**
    -   * Renders an axis.
    -   *   orientation = 'x' or 'y'
    -   *   transform = a function for transforming px into data for labeling/creating tick marks
    -   */
    -  function axisRenderer(orientation, transform) {
    -    var axisGroup = document.createElementNS("http://www.w3.org/2000/svg", "g");
    -    var axisPath = document.createElementNS(
    -      "http://www.w3.org/2000/svg",
    -      "path"
    -    );
    -
    -    axisGroup.setAttribute("class", orientation + "-axis");
    -
    -    var xMin = gutter;
    -    var xMax = width - gutter;
    -    var yMin = height - gutter;
    -    var yMax = gutter;
    -
    -    if (orientation === "x") {
    -      axisPath.setAttribute(
    -        "d",
    -        "M " + xMin + " " + yMin + " L " + xMax + " " + yMin
    -      );
    -
    -      // generate labels
    -      for (var i = xMin; i <= xMax; i++) {
    -        if ((i - xMin) % (pixelsPerTick*3) === 0 && i !== xMin) {
    -          var text = document.createElementNS(
    -            "http://www.w3.org/2000/svg",
    -            "text"
    -          );
    -          // primitive formatting
    -          text.innerHTML = new Date(Math.floor(transform(i))).toLocaleTimeString();
    -          text.setAttribute("x", i);
    -          text.setAttribute("y", yMin);
    -          // offset the text by 1 em
    -          text.setAttribute("dy", "1em");
    -          axisGroup.appendChild(text);
    -        }
    -      }
    -    } else {
    -      axisPath.setAttribute(
    -        "d",
    -        "M " + xMin + " " + yMin + " L " + xMin + " " + yMax
    -      );
    -
    -      // generate labels
    -      for (var i = yMax; i <= yMin; i++) {
    -        if ((i - yMin) % pixelsPerTick === 0 && i !== yMin) {
    -          var tickGroup = document.createElementNS(
    -            "http://www.w3.org/2000/svg",
    -            "g"
    -          );
    -          var gridLine = document.createElementNS(
    -            "http://www.w3.org/2000/svg",
    -            "path"
    -          );
    -          text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    -          // primitive formatting
    -          text.innerHTML = Math.floor(transform(i));
    -          text.setAttribute("x", xMin);
    -          text.setAttribute("y", i);
    -          // offset the text labels to align with grid line and keeping it to the left of the y-axis
    -          text.setAttribute("dx", "-.5em");
    -          text.setAttribute("dy", ".3em");
    -
    -          gridLine.setAttribute(
    -            "d",
    -            "M " + xMin + " " + i + " L " + xMax + " " + i
    -          );
    -
    -          tickGroup.appendChild(gridLine);
    -          tickGroup.appendChild(text);
    -          axisGroup.appendChild(tickGroup);
    -        }
    -      }
    -    }
    -
    -    axisGroup.appendChild(axisPath);
    -    parent.appendChild(axisGroup);
    -  }
    -
    -  /**
    -   * Renders a line
    -   */
    -  function lineRenderer(xAccessor, yAccessor, xTransform, yTransform) {
    -    var line = document.createElementNS("http://www.w3.org/2000/svg", "path");
    -
    -    xAccessor.reset();
    -    yAccessor.reset();
    -    if (!xAccessor.hasNext() || !yAccessor.hasNext()) {
    -      return;
    -    }
    -
    -    var pathString =
    -      "M " + xTransform(xAccessor.next()) + " " + yTransform(yAccessor.next());
    -    while (xAccessor.hasNext() && yAccessor.hasNext()) {
    -      pathString +=
    -        " L " +
    -        xTransform(xAccessor.next()) +
    -        " " +
    -        yTransform(yAccessor.next());
    -    }
    -
    -    line.setAttribute("class", "series");
    -    line.setAttribute("d", pathString);
    -
    -    parent.appendChild(line);
    -  }
    -
    -  /**
    -   * Renders data point circles + text labels
    -   */
    -  function pointRenderer(xAccessor, yAccessor, xTransform, yTransform) {
    -    var pointGroup = document.createElementNS(
    -      "http://www.w3.org/2000/svg",
    -      "g"
    -    );
    -
    -    pointGroup.setAttribute("class", "data-points");
    -
    -    xAccessor.reset();
    -    yAccessor.reset();
    -    if (!xAccessor.hasNext() || !yAccessor.hasNext()) {
    -      return;
    -    }
    -
    -    while (xAccessor.hasNext() && yAccessor.hasNext()) {
    -      var xDataValue = xAccessor.next();
    -      var x = xTransform(xDataValue);
    -      var yDataValue = yAccessor.next();
    -      var y = yTransform(yDataValue);
    -
    -      var circle = document.createElementNS(
    -        "http://www.w3.org/2000/svg",
    -        "circle"
    -      );
    -      circle.setAttribute("cx", x);
    -      circle.setAttribute("cy", y);
    -      circle.setAttribute("r", "4");
    -
    -      var text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    -      // primitive formatting
    -      text.innerHTML = Math.floor(xDataValue) + " / " + Math.floor(yDataValue);
    -      text.setAttribute("x", x);
    -      text.setAttribute("y", y);
    -
    -      text.setAttribute("dx", "1em");
    -      text.setAttribute("dy", "-.7em");
    -
    -      pointGroup.appendChild(circle);
    -      pointGroup.appendChild(text);
    -    }
    -
    -    parent.appendChild(pointGroup);
    -  }
    -
    -  // perform the rendering
    -  xTransform = numericTransformer(
    -    xAccessor.min(),
    -    xAccessor.max(),
    -    0 + gutter,
    -    width - gutter
    -  );
    -  // NOTE: for y... have to reverse coordinate space
    -  yTransform = numericTransformer(
    -    yAccessor.min(),
    -    yAccessor.max(),
    -    height - gutter,
    -    0 + gutter
    -  );
    -
    -  axisRenderer("x", xTransform.toData);
    -  axisRenderer("y", yTransform.toData);
    -
    -  lineRenderer(xAccessor, yAccessor, xTransform.toCoord, yTransform.toCoord);
    -  pointRenderer(xAccessor, yAccessor, xTransform.toCoord, yTransform.toCoord);
    -}
    -
    -// Final render function
    -function renderGraphSvg(dataArray, renderId) {
    -  var figure = document.getElementById(renderId);
    -  while (figure.hasChildNodes()) {
    -    figure.removeChild(figure.lastChild);
    -  }
    -  //console.log(dataArray);
    -  var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    -  svg.setAttribute("viewBox", "0 0 640 440");
    -  svg.setAttribute("preserveAspectRatio", "xMidYMid meet");
    -
    -  lineGraph(
    -    svg,
    -    // time accessor
    -    (function(data, min, max) {
    -      var i = 0;
    -      return {
    -        hasNext: function() {
    -          return i < data.length;
    -        },
    -        next: function() {
    -          return data[i++].x;
    -        },
    -        reset: function() {
    -          i = 0;
    -        },
    -        min: function() {
    -          return min;
    -        },
    -        max: function() {
    -          return max;
    -        }
    -      };
    -    })(
    -      dataArray,
    -      Math.min.apply(
    -        Math,
    -        dataArray.map(function(o) {
    -          return o.x;
    -        })
    -      ),
    -      Math.max.apply(
    -        Math,
    -        dataArray.map(function(o) {
    -          return o.x;
    -        })
    -      )
    -    ),
    -    // value accessor
    -    (function(data, min, max) {
    -      var i = 0;
    -      return {
    -        hasNext: function() {
    -          return i < data.length;
    -        },
    -        next: function() {
    -          return data[i++].y;
    -        },
    -        reset: function() {
    -          i = 0;
    -        },
    -        min: function() {
    -          return min;
    -        },
    -        max: function() {
    -          return max;
    -        }
    -      };
    -    })(
    -      dataArray,
    -      Math.min.apply(
    -        Math,
    -        dataArray.map(function(o) {
    -          return o.y;
    -        })
    -      ),
    -      Math.max.apply(
    -        Math,
    -        dataArray.map(function(o) {
    -          return o.y;
    -        })
    -      )
    -    )
    -  );
    -
    -  figure.appendChild(svg);
    -}
    diff --git a/watering/lib/ESPUI/data/js/graph.min.js b/watering/lib/ESPUI/data/js/graph.min.js
    deleted file mode 100644
    index fcc1846..0000000
    --- a/watering/lib/ESPUI/data/js/graph.min.js
    +++ /dev/null
    @@ -1,15 +0,0 @@
    -function lineGraph(parent,xAccessor,yAccessor){const width=620;const height=420;const gutter=40;const pixelsPerTick=30;function numericTransformer(dataMin,dataMax,pxMin,pxMax){var dataDiff=dataMax-dataMin,pxDiff=pxMax-pxMin,dataRatio=pxDiff/dataDiff,coordRatio=dataDiff/pxDiff;return{toCoord:function(data){return(data-dataMin)*dataRatio+pxMin;},toData:function(coord){return(coord-pxMin)*coordRatio+dataMin;}};}
    -function axisRenderer(orientation,transform){var axisGroup=document.createElementNS("http://www.w3.org/2000/svg","g");var axisPath=document.createElementNS("http://www.w3.org/2000/svg","path");axisGroup.setAttribute("class",orientation+"-axis");var xMin=gutter;var xMax=width-gutter;var yMin=height-gutter;var yMax=gutter;if(orientation==="x"){axisPath.setAttribute("d","M "+xMin+" "+yMin+" L "+xMax+" "+yMin);for(var i=xMin;i<=xMax;i++){if((i-xMin)%(pixelsPerTick*3)===0&&i!==xMin){var text=document.createElementNS("http://www.w3.org/2000/svg","text");text.innerHTML=new Date(Math.floor(transform(i))).toLocaleTimeString();text.setAttribute("x",i);text.setAttribute("y",yMin);text.setAttribute("dy","1em");axisGroup.appendChild(text);}}}else{axisPath.setAttribute("d","M "+xMin+" "+yMin+" L "+xMin+" "+yMax);for(var i=yMax;i<=yMin;i++){if((i-yMin)%pixelsPerTick===0&&i!==yMin){var tickGroup=document.createElementNS("http://www.w3.org/2000/svg","g");var gridLine=document.createElementNS("http://www.w3.org/2000/svg","path");text=document.createElementNS("http://www.w3.org/2000/svg","text");text.innerHTML=Math.floor(transform(i));text.setAttribute("x",xMin);text.setAttribute("y",i);text.setAttribute("dx","-.5em");text.setAttribute("dy",".3em");gridLine.setAttribute("d","M "+xMin+" "+i+" L "+xMax+" "+i);tickGroup.appendChild(gridLine);tickGroup.appendChild(text);axisGroup.appendChild(tickGroup);}}}
    -axisGroup.appendChild(axisPath);parent.appendChild(axisGroup);}
    -function lineRenderer(xAccessor,yAccessor,xTransform,yTransform){var line=document.createElementNS("http://www.w3.org/2000/svg","path");xAccessor.reset();yAccessor.reset();if(!xAccessor.hasNext()||!yAccessor.hasNext()){return;}
    -var pathString="M "+xTransform(xAccessor.next())+" "+yTransform(yAccessor.next());while(xAccessor.hasNext()&&yAccessor.hasNext()){pathString+=" L "+
    -xTransform(xAccessor.next())+
    -" "+
    -yTransform(yAccessor.next());}
    -line.setAttribute("class","series");line.setAttribute("d",pathString);parent.appendChild(line);}
    -function pointRenderer(xAccessor,yAccessor,xTransform,yTransform){var pointGroup=document.createElementNS("http://www.w3.org/2000/svg","g");pointGroup.setAttribute("class","data-points");xAccessor.reset();yAccessor.reset();if(!xAccessor.hasNext()||!yAccessor.hasNext()){return;}
    -while(xAccessor.hasNext()&&yAccessor.hasNext()){var xDataValue=xAccessor.next();var x=xTransform(xDataValue);var yDataValue=yAccessor.next();var y=yTransform(yDataValue);var circle=document.createElementNS("http://www.w3.org/2000/svg","circle");circle.setAttribute("cx",x);circle.setAttribute("cy",y);circle.setAttribute("r","4");var text=document.createElementNS("http://www.w3.org/2000/svg","text");text.innerHTML=Math.floor(xDataValue)+" / "+Math.floor(yDataValue);text.setAttribute("x",x);text.setAttribute("y",y);text.setAttribute("dx","1em");text.setAttribute("dy","-.7em");pointGroup.appendChild(circle);pointGroup.appendChild(text);}
    -parent.appendChild(pointGroup);}
    -xTransform=numericTransformer(xAccessor.min(),xAccessor.max(),0+gutter,width-gutter);yTransform=numericTransformer(yAccessor.min(),yAccessor.max(),height-gutter,0+gutter);axisRenderer("x",xTransform.toData);axisRenderer("y",yTransform.toData);lineRenderer(xAccessor,yAccessor,xTransform.toCoord,yTransform.toCoord);pointRenderer(xAccessor,yAccessor,xTransform.toCoord,yTransform.toCoord);}
    -function renderGraphSvg(dataArray,renderId){var figure=document.getElementById(renderId);while(figure.hasChildNodes()){figure.removeChild(figure.lastChild);}
    -var svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("viewBox","0 0 640 440");svg.setAttribute("preserveAspectRatio","xMidYMid meet");lineGraph(svg,(function(data,min,max){var i=0;return{hasNext:function(){return i' +
    -    '
    ' + - '
    0
    ' + - "
    "; - - return tmplt; -} - -function slider_move(parents, newW, sliderW, send) { - var slider_new_val = parseInt(Math.round((newW / sliderW) * 100)); - - var slider_fill = parents.find(".slider-fill"); - var slider_handle = parents.find(".slider-handle"); - var range = parents.find('input[type="range"]'); - range.next().html(newW); // update value - - slider_fill.css("width", slider_new_val + "%"); - slider_handle.css({ - left: slider_new_val + "%", - transition: "none", - "-webkit-transition": "none", - "-moz-transition": "none", - }); - - range.val(slider_new_val); - if (parents.find(".slider-handle span").text() != slider_new_val) { - parents.find(".slider-handle span").text(slider_new_val); - var number = parents.attr("id").substring(2); - if (send) websock.send("slvalue:" + slider_new_val + ":" + number); - } -} diff --git a/watering/lib/ESPUI/data/js/slider.min.js b/watering/lib/ESPUI/data/js/slider.min.js deleted file mode 100644 index 1e7e1b6..0000000 --- a/watering/lib/ESPUI/data/js/slider.min.js +++ /dev/null @@ -1,11 +0,0 @@ -function rkmd_rangeSlider(selector){var self,slider_width,slider_offset,curnt,sliderDiscrete,range,slider;self=$(selector);slider_width=self.width();slider_offset=self.offset().left;sliderDiscrete=self;sliderDiscrete.each(function(i,v){curnt=$(this);curnt.append(sliderDiscrete_tmplt());range=curnt.find('input[type="range"]');slider=curnt.find(".slider");slider_fill=slider.find(".slider-fill");slider_handle=slider.find(".slider-handle");slider_label=slider.find(".slider-label");var range_val=parseInt(range.val());slider_fill.css("width",range_val+"%");slider_handle.css("left",range_val+"%");slider_label.find("span").text(range_val);});self.on("mousedown touchstart",".slider-handle",function(e){if(e.button===2){return false;} -var parents=$(this).parents(".rkmd-slider");var slider_width=parents.width();var slider_offset=parents.offset().left;var check_range=parents.find('input[type="range"]').is(":disabled");if(check_range===true){return false;} -$(this).addClass("is-active");var moveFu=function(e){var pageX=e.pageX||e.changedTouches[0].pageX;var slider_new_width=pageX-slider_offset;if(slider_new_width<=slider_width&&!(slider_new_width<"0")){slider_move(parents,slider_new_width,slider_width,true);}};var upFu=function(e){$(this).off(handlers);parents.find(".is-active").removeClass("is-active");};var handlers={mousemove:moveFu,touchmove:moveFu,mouseup:upFu,touchend:upFu,};$(document).on(handlers);});self.on("mousedown touchstart",".slider",function(e){if(e.button===2){return false;} -var parents=$(this).parents(".rkmd-slider");var slider_width=parents.width();var slider_offset=parents.offset().left;var check_range=parents.find('input[type="range"]').is(":disabled");if(check_range===true){return false;} -var slider_new_width=e.pageX-slider_offset;if(slider_new_width<=slider_width&&!(slider_new_width<"0")){slider_move(parents,slider_new_width,slider_width,true);} -var upFu=function(e){$(this).off(handlers);};var handlers={mouseup:upFu,touchend:upFu,};$(document).on(handlers);});} -function sliderDiscrete_tmplt(){var tmplt='
    '+ -'
    '+ -'
    0
    '+ -"
    ";return tmplt;} -function slider_move(parents,newW,sliderW,send){var slider_new_val=parseInt(Math.round((newW/sliderW)*100));var slider_fill=parents.find(".slider-fill");var slider_handle=parents.find(".slider-handle");var range=parents.find('input[type="range"]');range.next().html(newW);slider_fill.css("width",slider_new_val+"%");slider_handle.css({left:slider_new_val+"%",transition:"none","-webkit-transition":"none","-moz-transition":"none",});range.val(slider_new_val);if(parents.find(".slider-handle span").text()!=slider_new_val){parents.find(".slider-handle span").text(slider_new_val);var number=parents.attr("id").substring(2);if(send)websock.send("slvalue:"+slider_new_val+":"+number);}} \ No newline at end of file diff --git a/watering/lib/ESPUI/data/js/tabbedcontent.js b/watering/lib/ESPUI/data/js/tabbedcontent.js deleted file mode 100644 index 2a97a0a..0000000 --- a/watering/lib/ESPUI/data/js/tabbedcontent.js +++ /dev/null @@ -1,351 +0,0 @@ -/** - * Tabs plugin for jQuery created by Òscar Casajuana < elboletaire at underave dot net > - * - * @copyright Copyright 2013-2016 Òscar Casajuana - * @license MIT - * @author Òscar Casajuana Alonso -*/ -;(function($, document, window, undefined) { - "use strict"; - - var Tabbedcontent = function(tabcontent, options) { - var defaults = { - links : tabcontent.prev().find('a').length ? tabcontent.prev().find('a') : '.tabs a', // the tabs itself. By default it selects the links contained in the previous wrapper or the links inside ".tabs a" if there's no previous item - errorSelector : '.error-message', // false to disable - speed : false, // speed of the show effect. Set to null or false to disable - onSwitch : false, // onSwitch callback - onInit : false, // onInit callback - currentClass : 'active', // current selected tab class (is set to the element) - tabErrorClass : 'has-errors', // a class to be added to the tab where errorSelector is detected - history : true, // set to false to disable HTML5 history - historyOnInit : true, // allows to deactivate the history for the intial autmatically tab switch on load - loop : false // if set to true will loop between tabs when using the next() and prev() api methods - }, - firstTime = false, - children = tabcontent.children(), - history = window.history, - loc = document.location, - current = null - ; - - options = $.extend(defaults, options); - - if (!(options.links instanceof $)) { - options.links = $(options.links); - } - - /** - * Checks if the specified tab id exists. - * - * @param string tab Tab #id - * @return bool - */ - function tabExists(tab) { - return Boolean(children.filter(tab).length); - } - /** - * Checks if the current tab is the - * first one in the tabs set. - * - * @return bool - */ - function isFirst() { - return current === 0; - } - /** - * Checks if the passed number is an integer. - * - * @param mixed num The value to be checked. - * @return bool - */ - function isInt(num) { - return num % 1 === 0; - } - /** - * Checks if the current tab is the - * last one in the tabs set. - * - * @return {Boolean} [description] - */ - function isLast() { - return current === children.length - 1; - } - /** - * Filters a tab based on current links href. - * - * Method for compatibility with Zepto.js - * - * @param string tab Tab #href - * @return bool - */ - function filterTab(tab) { - return $(this).attr('href').match(new RegExp(tab + '$')); - } - /** - * Returns an object containing two jQuery instances: - * one for the tab content and the other for its link. - * - * @param mixed tab A tab id, #id or index. - * @return object With thi - */ - function getTab(tab) { - if (tab instanceof $) { - return { - tab : tab, - link : options.links.eq(tab.index()) - }; - } - if (isInt(tab)) { - return { - tab : children.eq(tab), - link : options.links.eq(tab) - }; - } - if (children.filter(tab).length) { - return { - tab : children.filter(tab), - link : options.links.filter(function() { - return filterTab.apply(this, [tab]); - }) - }; - } - // assume it's an id without # - return { - tab : children.filter('#' + tab), - link : options.links.filter(function() { - return filterTab.apply(this, ['#' + tab]); - }) - }; - } - /** - * Returns the index of the current tab. - * - * @return int - */ - function getCurrent() { - return options.links.parent().filter('.' + options.currentClass).index(); - } - /** - * Go to the next tab in the tabs set. - * - * @param bool loop If defined will overwrite options.loop - * @return mixed - */ - function next(loop) { - ++current; - - if (loop === undefined) loop = options.loop; - - if (current < children.length) { - return switchTab(current, true); - } else if (loop && current >= children.length) { - return switchTab(0, true); - } - - return false; - } - /** - * Go to the previous tab in the tabs set. - * - * @param bool loop If defined will overwrite options.loop - * @return mixed - */ - function prev(loop) { - --current; - - if (loop === undefined) loop = options.loop; - - if (current >= 0) { - return switchTab(current, true); - } else if (loop && current < 0) { - return switchTab(children.length - 1, true); - } - - return false; - } - /** - * onSwitch callback for switchTab. - * - * @param string tab The tab #id - * @return void - */ - function onSwitch(tab) { - if (options.history && options.historyOnInit && firstTime && history !== undefined && ('pushState' in history)) { - firstTime = false; - window.setTimeout(function() { - history.replaceState(null, '', tab); - }, 100); - } - current = getCurrent(); - if (options.onSwitch && typeof options.onSwitch === 'function') { - options.onSwitch(tab, api()); - } - tabcontent.trigger('tabcontent.switch', [tab, api()]); - } - /** - * Switch to specified tab. - * - * @param mixed tab The tab to switch to. - * @param bool api Set to true to force history writing. - * @return bool Returns false if tab does not exist; true otherwise. - */ - function switchTab(tab, api) { - if (!tab.toString().match(/^#/)) { - tab = '#' + getTab(tab).tab.attr('id'); - } - - if (!tabExists(tab)) { - return false; - } - - // Toggle active class - options.links.attr('aria-selected','false').parent().removeClass(options.currentClass); - options.links.filter(function() { - return filterTab.apply(this, [tab]); - }).attr('aria-selected','true').parent().addClass(options.currentClass); - // Hide tabs - children.hide(); - - // We need to force the change of the hash if we're using the API - if (options.history && api) { - if (history !== undefined && ('pushState' in history)) { - history.pushState(null, '', tab); - } else { - // force hash change to add it to the history - window.location.hash = tab; - } - } - - // Show tabs - children.attr('aria-hidden','true').filter(tab).show(options.speed, function() { - if (options.speed) { - onSwitch(tab); - } - }).attr('aria-hidden','false'); - if (!options.speed) { - onSwitch(tab); - } - - return true; - } - /** - * Api method to switch tabs. - * - * @param mixed tab Tab to switch to. - * @return bool Returns false if tab does not exist; true otherwise. - */ - function apiSwitch(tab) { - return switchTab(tab, true); - } - /** - * Method used to switch tabs using the - * browser query hash. - * - * @param object e Event. - * @return void - */ - function hashSwitch(e) { - switchTab(loc.hash); - } - /** - * Initialization method. - * - * The tab checking preference is: - * - document.location.hash - * - options.errorSelector - * - first tab in the set of tabs - * - * The onInit method is called at the - * end of this method. - * - * @return void - */ - function init() { - // Switch to tab using location.hash - if (tabExists(loc.hash)) { - // Switch to current hash tab - switchTab(loc.hash); - } - // If there's a tab link with the options.currentClass set, - // switch to that tab. - else if (options.links.parent().filter('.' + options.currentClass).length) { - switchTab(options.links.parent().filter('.' + options.currentClass).index()); - } - // Switch to tab containing class options.errorSelector - else if (options.errorSelector && children.find(options.errorSelector).length) { - // Search for errors and show first tab containing one - children.each(function() { - if ($(this).find(options.errorSelector).length) { - switchTab("#" + $(this).attr("id")); - return false; - } - }); - } - // Open first tab - else { - switchTab("#" + children.filter(":first-child").attr("id")); - } - // Add a class to every tab containing errors - if (options.errorSelector) { - children.find(options.errorSelector).each(function() { - var tab = getTab($(this).parent()); - tab.link.parent().addClass(options.tabErrorClass); - }); - } - - // Binding - if ('onhashchange' in window) { - $(window).bind('hashchange', hashSwitch); - } else { // old browsers - var current_href = loc.href; - window.setInterval(function() { - if (current_href !== loc.href) { - hashSwitch.call(window.event); - current_href = loc.href; - } - }, 100); - } - // Bind click event on links, to ensure we don't rewrite the URI in - // case history is disabled - $(options.links).on('click', function(e) { - switchTab($(this).attr('href').replace(/^[^#]+/, ''), options.history); - e.preventDefault(); - }); - - // onInit callback - if (options.onInit && typeof options.onInit === 'function') { - options.onInit(api()); - } - tabcontent.trigger('tabcontent.init', [api()]); - } - /** - * Returns the methods exposed in the api. - * - * @return object Containing each api method. - */ - function api() { - return { - 'switch' : apiSwitch, - 'switchTab' : apiSwitch, // for old browsers - 'getCurrent' : getCurrent, - 'getTab' : getTab, - 'next' : next, - 'prev' : prev, - 'isFirst' : isFirst, - 'isLast' : isLast - }; - } - - init(); - - return api(); - }; - - $.fn.tabbedContent = function(options) { - return this.each(function() { - var tabs = new Tabbedcontent($(this), options); - $(this).data('api', tabs); - }); - }; - -})(window.jQuery || window.Zepto || window.$, document, window); diff --git a/watering/lib/ESPUI/data/js/tabbedcontent.min.js b/watering/lib/ESPUI/data/js/tabbedcontent.min.js deleted file mode 100644 index efbf454..0000000 --- a/watering/lib/ESPUI/data/js/tabbedcontent.min.js +++ /dev/null @@ -1,35 +0,0 @@ -;(function($,document,window,undefined){"use strict";var Tabbedcontent=function(tabcontent,options){var defaults={links:tabcontent.prev().find('a').length?tabcontent.prev().find('a'):'.tabs a',errorSelector:'.error-message',speed:false,onSwitch:false,onInit:false,currentClass:'active',tabErrorClass:'has-errors',history:true,historyOnInit:true,loop:false},firstTime=false,children=tabcontent.children(),history=window.history,loc=document.location,current=null;options=$.extend(defaults,options);if(!(options.links instanceof $)){options.links=$(options.links);} -function tabExists(tab){return Boolean(children.filter(tab).length);} -function isFirst(){return current===0;} -function isInt(num){return num%1===0;} -function isLast(){return current===children.length-1;} -function filterTab(tab){return $(this).attr('href').match(new RegExp(tab+'$'));} -function getTab(tab){if(tab instanceof $){return{tab:tab,link:options.links.eq(tab.index())};} -if(isInt(tab)){return{tab:children.eq(tab),link:options.links.eq(tab)};} -if(children.filter(tab).length){return{tab:children.filter(tab),link:options.links.filter(function(){return filterTab.apply(this,[tab]);})};} -return{tab:children.filter('#'+tab),link:options.links.filter(function(){return filterTab.apply(this,['#'+tab]);})};} -function getCurrent(){return options.links.parent().filter('.'+options.currentClass).index();} -function next(loop){++current;if(loop===undefined)loop=options.loop;if(current=children.length){return switchTab(0,true);} -return false;} -function prev(loop){--current;if(loop===undefined)loop=options.loop;if(current>=0){return switchTab(current,true);}else if(loop&¤t<0){return switchTab(children.length-1,true);} -return false;} -function onSwitch(tab){if(options.history&&options.historyOnInit&&firstTime&&history!==undefined&&('pushState'in history)){firstTime=false;window.setTimeout(function(){history.replaceState(null,'',tab);},100);} -current=getCurrent();if(options.onSwitch&&typeof options.onSwitch==='function'){options.onSwitch(tab,api());} -tabcontent.trigger('tabcontent.switch',[tab,api()]);} -function switchTab(tab,api){if(!tab.toString().match(/^#/)){tab='#'+getTab(tab).tab.attr('id');} -if(!tabExists(tab)){return false;} -options.links.attr('aria-selected','false').parent().removeClass(options.currentClass);options.links.filter(function(){return filterTab.apply(this,[tab]);}).attr('aria-selected','true').parent().addClass(options.currentClass);children.hide();if(options.history&&api){if(history!==undefined&&('pushState'in history)){history.pushState(null,'',tab);}else{window.location.hash=tab;}} -children.attr('aria-hidden','true').filter(tab).show(options.speed,function(){if(options.speed){onSwitch(tab);}}).attr('aria-hidden','false');if(!options.speed){onSwitch(tab);} -return true;} -function apiSwitch(tab){return switchTab(tab,true);} -function hashSwitch(e){switchTab(loc.hash);} -function init(){if(tabExists(loc.hash)){switchTab(loc.hash);} -else if(options.links.parent().filter('.'+options.currentClass).length){switchTab(options.links.parent().filter('.'+options.currentClass).index());} -else if(options.errorSelector&&children.find(options.errorSelector).length){children.each(function(){if($(this).find(options.errorSelector).length){switchTab("#"+$(this).attr("id"));return false;}});} -else{switchTab("#"+children.filter(":first-child").attr("id"));} -if(options.errorSelector){children.find(options.errorSelector).each(function(){var tab=getTab($(this).parent());tab.link.parent().addClass(options.tabErrorClass);});} -if('onhashchange'in window){$(window).bind('hashchange',hashSwitch);}else{var current_href=loc.href;window.setInterval(function(){if(current_href!==loc.href){hashSwitch.call(window.event);current_href=loc.href;}},100);} -$(options.links).on('click',function(e){switchTab($(this).attr('href').replace(/^[^#]+/,''),options.history);e.preventDefault();});if(options.onInit&&typeof options.onInit==='function'){options.onInit(api());} -tabcontent.trigger('tabcontent.init',[api()]);} -function api(){return{'switch':apiSwitch,'switchTab':apiSwitch,'getCurrent':getCurrent,'getTab':getTab,'next':next,'prev':prev,'isFirst':isFirst,'isLast':isLast};} -init();return api();};$.fn.tabbedContent=function(options){return this.each(function(){var tabs=new Tabbedcontent($(this),options);$(this).data('api',tabs);});};})(window.jQuery||window.Zepto||window.$,document,window); \ No newline at end of file diff --git a/watering/lib/ESPUI/data/js/zepto.min.js b/watering/lib/ESPUI/data/js/zepto.min.js deleted file mode 100644 index 1bd447f..0000000 --- a/watering/lib/ESPUI/data/js/zepto.min.js +++ /dev/null @@ -1,2 +0,0 @@ - /* Zepto v1.2.0 - zepto event ajax form ie - zeptojs.com/license */ - !function(t,e){"function"==typeof define&&define.amd?define(function(){return e(t)}):e(t)}(this,function(t){var e=function(){function $(t){return null==t?String(t):S[C.call(t)]||"object"}function F(t){return"function"==$(t)}function k(t){return null!=t&&t==t.window}function M(t){return null!=t&&t.nodeType==t.DOCUMENT_NODE}function R(t){return"object"==$(t)}function Z(t){return R(t)&&!k(t)&&Object.getPrototypeOf(t)==Object.prototype}function z(t){var e=!!t&&"length"in t&&t.length,n=r.type(t);return"function"!=n&&!k(t)&&("array"==n||0===e||"number"==typeof e&&e>0&&e-1 in t)}function q(t){return a.call(t,function(t){return null!=t})}function H(t){return t.length>0?r.fn.concat.apply([],t):t}function I(t){return t.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function V(t){return t in l?l[t]:l[t]=new RegExp("(^|\\s)"+t+"(\\s|$)")}function _(t,e){return"number"!=typeof e||h[I(t)]?e:e+"px"}function B(t){var e,n;return c[t]||(e=f.createElement(t),f.body.appendChild(e),n=getComputedStyle(e,"").getPropertyValue("display"),e.parentNode.removeChild(e),"none"==n&&(n="block"),c[t]=n),c[t]}function U(t){return"children"in t?u.call(t.children):r.map(t.childNodes,function(t){return 1==t.nodeType?t:void 0})}function X(t,e){var n,r=t?t.length:0;for(n=0;r>n;n++)this[n]=t[n];this.length=r,this.selector=e||""}function J(t,r,i){for(n in r)i&&(Z(r[n])||L(r[n]))?(Z(r[n])&&!Z(t[n])&&(t[n]={}),L(r[n])&&!L(t[n])&&(t[n]=[]),J(t[n],r[n],i)):r[n]!==e&&(t[n]=r[n])}function W(t,e){return null==e?r(t):r(t).filter(e)}function Y(t,e,n,r){return F(e)?e.call(t,n,r):e}function G(t,e,n){null==n?t.removeAttribute(e):t.setAttribute(e,n)}function K(t,n){var r=t.className||"",i=r&&r.baseVal!==e;return n===e?i?r.baseVal:r:void(i?r.baseVal=n:t.className=n)}function Q(t){try{return t?"true"==t||("false"==t?!1:"null"==t?null:+t+""==t?+t:/^[\[\{]/.test(t)?r.parseJSON(t):t):t}catch(e){return t}}function tt(t,e){e(t);for(var n=0,r=t.childNodes.length;r>n;n++)tt(t.childNodes[n],e)}var e,n,r,i,O,P,o=[],s=o.concat,a=o.filter,u=o.slice,f=t.document,c={},l={},h={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},p=/^\s*<(\w+|!)[^>]*>/,d=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,m=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,g=/^(?:body|html)$/i,v=/([A-Z])/g,y=["val","css","html","text","data","width","height","offset"],x=["after","prepend","before","append"],b=f.createElement("table"),E=f.createElement("tr"),j={tr:f.createElement("tbody"),tbody:b,thead:b,tfoot:b,td:E,th:E,"*":f.createElement("div")},w=/complete|loaded|interactive/,T=/^[\w-]*$/,S={},C=S.toString,N={},A=f.createElement("div"),D={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},L=Array.isArray||function(t){return t instanceof Array};return N.matches=function(t,e){if(!e||!t||1!==t.nodeType)return!1;var n=t.matches||t.webkitMatchesSelector||t.mozMatchesSelector||t.oMatchesSelector||t.matchesSelector;if(n)return n.call(t,e);var r,i=t.parentNode,o=!i;return o&&(i=A).appendChild(t),r=~N.qsa(i,e).indexOf(t),o&&A.removeChild(t),r},O=function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},P=function(t){return a.call(t,function(e,n){return t.indexOf(e)==n})},N.fragment=function(t,n,i){var o,s,a;return d.test(t)&&(o=r(f.createElement(RegExp.$1))),o||(t.replace&&(t=t.replace(m,"<$1>")),n===e&&(n=p.test(t)&&RegExp.$1),n in j||(n="*"),a=j[n],a.innerHTML=""+t,o=r.each(u.call(a.childNodes),function(){a.removeChild(this)})),Z(i)&&(s=r(o),r.each(i,function(t,e){y.indexOf(t)>-1?s[t](e):s.attr(t,e)})),o},N.Z=function(t,e){return new X(t,e)},N.isZ=function(t){return t instanceof N.Z},N.init=function(t,n){var i;if(!t)return N.Z();if("string"==typeof t)if(t=t.trim(),"<"==t[0]&&p.test(t))i=N.fragment(t,RegExp.$1,n),t=null;else{if(n!==e)return r(n).find(t);i=N.qsa(f,t)}else{if(F(t))return r(f).ready(t);if(N.isZ(t))return t;if(L(t))i=q(t);else if(R(t))i=[t],t=null;else if(p.test(t))i=N.fragment(t.trim(),RegExp.$1,n),t=null;else{if(n!==e)return r(n).find(t);i=N.qsa(f,t)}}return N.Z(i,t)},r=function(t,e){return N.init(t,e)},r.extend=function(t){var e,n=u.call(arguments,1);return"boolean"==typeof t&&(e=t,t=n.shift()),n.forEach(function(n){J(t,n,e)}),t},N.qsa=function(t,e){var n,r="#"==e[0],i=!r&&"."==e[0],o=r||i?e.slice(1):e,s=T.test(o);return t.getElementById&&s&&r?(n=t.getElementById(o))?[n]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:u.call(s&&!r&&t.getElementsByClassName?i?t.getElementsByClassName(o):t.getElementsByTagName(e):t.querySelectorAll(e))},r.contains=f.documentElement.contains?function(t,e){return t!==e&&t.contains(e)}:function(t,e){for(;e&&(e=e.parentNode);)if(e===t)return!0;return!1},r.type=$,r.isFunction=F,r.isWindow=k,r.isArray=L,r.isPlainObject=Z,r.isEmptyObject=function(t){var e;for(e in t)return!1;return!0},r.isNumeric=function(t){var e=Number(t),n=typeof t;return null!=t&&"boolean"!=n&&("string"!=n||t.length)&&!isNaN(e)&&isFinite(e)||!1},r.inArray=function(t,e,n){return o.indexOf.call(e,t,n)},r.camelCase=O,r.trim=function(t){return null==t?"":String.prototype.trim.call(t)},r.uuid=0,r.support={},r.expr={},r.noop=function(){},r.map=function(t,e){var n,i,o,r=[];if(z(t))for(i=0;i=0?t:t+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){null!=this.parentNode&&this.parentNode.removeChild(this)})},each:function(t){return o.every.call(this,function(e,n){return t.call(e,n,e)!==!1}),this},filter:function(t){return F(t)?this.not(this.not(t)):r(a.call(this,function(e){return N.matches(e,t)}))},add:function(t,e){return r(P(this.concat(r(t,e))))},is:function(t){return this.length>0&&N.matches(this[0],t)},not:function(t){var n=[];if(F(t)&&t.call!==e)this.each(function(e){t.call(this,e)||n.push(this)});else{var i="string"==typeof t?this.filter(t):z(t)&&F(t.item)?u.call(t):r(t);this.forEach(function(t){i.indexOf(t)<0&&n.push(t)})}return r(n)},has:function(t){return this.filter(function(){return R(t)?r.contains(this,t):r(this).find(t).size()})},eq:function(t){return-1===t?this.slice(t):this.slice(t,+t+1)},first:function(){var t=this[0];return t&&!R(t)?t:r(t)},last:function(){var t=this[this.length-1];return t&&!R(t)?t:r(t)},find:function(t){var e,n=this;return e=t?"object"==typeof t?r(t).filter(function(){var t=this;return o.some.call(n,function(e){return r.contains(e,t)})}):1==this.length?r(N.qsa(this[0],t)):this.map(function(){return N.qsa(this,t)}):r()},closest:function(t,e){var n=[],i="object"==typeof t&&r(t);return this.each(function(r,o){for(;o&&!(i?i.indexOf(o)>=0:N.matches(o,t));)o=o!==e&&!M(o)&&o.parentNode;o&&n.indexOf(o)<0&&n.push(o)}),r(n)},parents:function(t){for(var e=[],n=this;n.length>0;)n=r.map(n,function(t){return(t=t.parentNode)&&!M(t)&&e.indexOf(t)<0?(e.push(t),t):void 0});return W(e,t)},parent:function(t){return W(P(this.pluck("parentNode")),t)},children:function(t){return W(this.map(function(){return U(this)}),t)},contents:function(){return this.map(function(){return this.contentDocument||u.call(this.childNodes)})},siblings:function(t){return W(this.map(function(t,e){return a.call(U(e.parentNode),function(t){return t!==e})}),t)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(t){return r.map(this,function(e){return e[t]})},show:function(){return this.each(function(){"none"==this.style.display&&(this.style.display=""),"none"==getComputedStyle(this,"").getPropertyValue("display")&&(this.style.display=B(this.nodeName))})},replaceWith:function(t){return this.before(t).remove()},wrap:function(t){var e=F(t);if(this[0]&&!e)var n=r(t).get(0),i=n.parentNode||this.length>1;return this.each(function(o){r(this).wrapAll(e?t.call(this,o):i?n.cloneNode(!0):n)})},wrapAll:function(t){if(this[0]){r(this[0]).before(t=r(t));for(var e;(e=t.children()).length;)t=e.first();r(t).append(this)}return this},wrapInner:function(t){var e=F(t);return this.each(function(n){var i=r(this),o=i.contents(),s=e?t.call(this,n):t;o.length?o.wrapAll(s):i.append(s)})},unwrap:function(){return this.parent().each(function(){r(this).replaceWith(r(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(t){return this.each(function(){var n=r(this);(t===e?"none"==n.css("display"):t)?n.show():n.hide()})},prev:function(t){return r(this.pluck("previousElementSibling")).filter(t||"*")},next:function(t){return r(this.pluck("nextElementSibling")).filter(t||"*")},html:function(t){return 0 in arguments?this.each(function(e){var n=this.innerHTML;r(this).empty().append(Y(this,t,e,n))}):0 in this?this[0].innerHTML:null},text:function(t){return 0 in arguments?this.each(function(e){var n=Y(this,t,e,this.textContent);this.textContent=null==n?"":""+n}):0 in this?this.pluck("textContent").join(""):null},attr:function(t,r){var i;return"string"!=typeof t||1 in arguments?this.each(function(e){if(1===this.nodeType)if(R(t))for(n in t)G(this,n,t[n]);else G(this,t,Y(this,r,e,this.getAttribute(t)))}):0 in this&&1==this[0].nodeType&&null!=(i=this[0].getAttribute(t))?i:e},removeAttr:function(t){return this.each(function(){1===this.nodeType&&t.split(" ").forEach(function(t){G(this,t)},this)})},prop:function(t,e){return t=D[t]||t,1 in arguments?this.each(function(n){this[t]=Y(this,e,n,this[t])}):this[0]&&this[0][t]},removeProp:function(t){return t=D[t]||t,this.each(function(){delete this[t]})},data:function(t,n){var r="data-"+t.replace(v,"-$1").toLowerCase(),i=1 in arguments?this.attr(r,n):this.attr(r);return null!==i?Q(i):e},val:function(t){return 0 in arguments?(null==t&&(t=""),this.each(function(e){this.value=Y(this,t,e,this.value)})):this[0]&&(this[0].multiple?r(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value)},offset:function(e){if(e)return this.each(function(t){var n=r(this),i=Y(this,e,t,n.offset()),o=n.offsetParent().offset(),s={top:i.top-o.top,left:i.left-o.left};"static"==n.css("position")&&(s.position="relative"),n.css(s)});if(!this.length)return null;if(f.documentElement!==this[0]&&!r.contains(f.documentElement,this[0]))return{top:0,left:0};var n=this[0].getBoundingClientRect();return{left:n.left+t.pageXOffset,top:n.top+t.pageYOffset,width:Math.round(n.width),height:Math.round(n.height)}},css:function(t,e){if(arguments.length<2){var i=this[0];if("string"==typeof t){if(!i)return;return i.style[O(t)]||getComputedStyle(i,"").getPropertyValue(t)}if(L(t)){if(!i)return;var o={},s=getComputedStyle(i,"");return r.each(t,function(t,e){o[e]=i.style[O(e)]||s.getPropertyValue(e)}),o}}var a="";if("string"==$(t))e||0===e?a=I(t)+":"+_(t,e):this.each(function(){this.style.removeProperty(I(t))});else for(n in t)t[n]||0===t[n]?a+=I(n)+":"+_(n,t[n])+";":this.each(function(){this.style.removeProperty(I(n))});return this.each(function(){this.style.cssText+=";"+a})},index:function(t){return t?this.indexOf(r(t)[0]):this.parent().children().indexOf(this[0])},hasClass:function(t){return t?o.some.call(this,function(t){return this.test(K(t))},V(t)):!1},addClass:function(t){return t?this.each(function(e){if("className"in this){i=[];var n=K(this),o=Y(this,t,e,n);o.split(/\s+/g).forEach(function(t){r(this).hasClass(t)||i.push(t)},this),i.length&&K(this,n+(n?" ":"")+i.join(" "))}}):this},removeClass:function(t){return this.each(function(n){if("className"in this){if(t===e)return K(this,"");i=K(this),Y(this,t,n,i).split(/\s+/g).forEach(function(t){i=i.replace(V(t)," ")}),K(this,i.trim())}})},toggleClass:function(t,n){return t?this.each(function(i){var o=r(this),s=Y(this,t,i,K(this));s.split(/\s+/g).forEach(function(t){(n===e?!o.hasClass(t):n)?o.addClass(t):o.removeClass(t)})}):this},scrollTop:function(t){if(this.length){var n="scrollTop"in this[0];return t===e?n?this[0].scrollTop:this[0].pageYOffset:this.each(n?function(){this.scrollTop=t}:function(){this.scrollTo(this.scrollX,t)})}},scrollLeft:function(t){if(this.length){var n="scrollLeft"in this[0];return t===e?n?this[0].scrollLeft:this[0].pageXOffset:this.each(n?function(){this.scrollLeft=t}:function(){this.scrollTo(t,this.scrollY)})}},position:function(){if(this.length){var t=this[0],e=this.offsetParent(),n=this.offset(),i=g.test(e[0].nodeName)?{top:0,left:0}:e.offset();return n.top-=parseFloat(r(t).css("margin-top"))||0,n.left-=parseFloat(r(t).css("margin-left"))||0,i.top+=parseFloat(r(e[0]).css("border-top-width"))||0,i.left+=parseFloat(r(e[0]).css("border-left-width"))||0,{top:n.top-i.top,left:n.left-i.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||f.body;t&&!g.test(t.nodeName)&&"static"==r(t).css("position");)t=t.offsetParent;return t})}},r.fn.detach=r.fn.remove,["width","height"].forEach(function(t){var n=t.replace(/./,function(t){return t[0].toUpperCase()});r.fn[t]=function(i){var o,s=this[0];return i===e?k(s)?s["inner"+n]:M(s)?s.documentElement["scroll"+n]:(o=this.offset())&&o[t]:this.each(function(e){s=r(this),s.css(t,Y(this,i,e,s[t]()))})}}),x.forEach(function(n,i){var o=i%2;r.fn[n]=function(){var n,a,s=r.map(arguments,function(t){var i=[];return n=$(t),"array"==n?(t.forEach(function(t){return t.nodeType!==e?i.push(t):r.zepto.isZ(t)?i=i.concat(t.get()):void(i=i.concat(N.fragment(t)))}),i):"object"==n||null==t?t:N.fragment(t)}),u=this.length>1;return s.length<1?this:this.each(function(e,n){a=o?n:n.parentNode,n=0==i?n.nextSibling:1==i?n.firstChild:2==i?n:null;var c=r.contains(f.documentElement,a);s.forEach(function(e){if(u)e=e.cloneNode(!0);else if(!a)return r(e).remove();a.insertBefore(e,n),c&&tt(e,function(e){if(!(null==e.nodeName||"SCRIPT"!==e.nodeName.toUpperCase()||e.type&&"text/javascript"!==e.type||e.src)){var n=e.ownerDocument?e.ownerDocument.defaultView:t;n.eval.call(n,e.innerHTML)}})})})},r.fn[o?n+"To":"insert"+(i?"Before":"After")]=function(t){return r(t)[n](this),this}}),N.Z.prototype=X.prototype=r.fn,N.uniq=P,N.deserializeValue=Q,r.zepto=N,r}();return t.Zepto=e,void 0===t.$&&(t.$=e),function(e){function h(t){return t._zid||(t._zid=n++)}function p(t,e,n,r){if(e=d(e),e.ns)var i=m(e.ns);return(a[h(t)]||[]).filter(function(t){return t&&(!e.e||t.e==e.e)&&(!e.ns||i.test(t.ns))&&(!n||h(t.fn)===h(n))&&(!r||t.sel==r)})}function d(t){var e=(""+t).split(".");return{e:e[0],ns:e.slice(1).sort().join(" ")}}function m(t){return new RegExp("(?:^| )"+t.replace(" "," .* ?")+"(?: |$)")}function g(t,e){return t.del&&!f&&t.e in c||!!e}function v(t){return l[t]||f&&c[t]||t}function y(t,n,i,o,s,u,f){var c=h(t),p=a[c]||(a[c]=[]);n.split(/\s/).forEach(function(n){if("ready"==n)return e(document).ready(i);var a=d(n);a.fn=i,a.sel=s,a.e in l&&(i=function(t){var n=t.relatedTarget;return!n||n!==this&&!e.contains(this,n)?a.fn.apply(this,arguments):void 0}),a.del=u;var c=u||i;a.proxy=function(e){if(e=T(e),!e.isImmediatePropagationStopped()){e.data=o;var n=c.apply(t,e._args==r?[e]:[e].concat(e._args));return n===!1&&(e.preventDefault(),e.stopPropagation()),n}},a.i=p.length,p.push(a),"addEventListener"in t&&t.addEventListener(v(a.e),a.proxy,g(a,f))})}function x(t,e,n,r,i){var o=h(t);(e||"").split(/\s/).forEach(function(e){p(t,e,n,r).forEach(function(e){delete a[o][e.i],"removeEventListener"in t&&t.removeEventListener(v(e.e),e.proxy,g(e,i))})})}function T(t,n){return(n||!t.isDefaultPrevented)&&(n||(n=t),e.each(w,function(e,r){var i=n[e];t[e]=function(){return this[r]=b,i&&i.apply(n,arguments)},t[r]=E}),t.timeStamp||(t.timeStamp=Date.now()),(n.defaultPrevented!==r?n.defaultPrevented:"returnValue"in n?n.returnValue===!1:n.getPreventDefault&&n.getPreventDefault())&&(t.isDefaultPrevented=b)),t}function S(t){var e,n={originalEvent:t};for(e in t)j.test(e)||t[e]===r||(n[e]=t[e]);return T(n,t)}var r,n=1,i=Array.prototype.slice,o=e.isFunction,s=function(t){return"string"==typeof t},a={},u={},f="onfocusin"in t,c={focus:"focusin",blur:"focusout"},l={mouseenter:"mouseover",mouseleave:"mouseout"};u.click=u.mousedown=u.mouseup=u.mousemove="MouseEvents",e.event={add:y,remove:x},e.proxy=function(t,n){var r=2 in arguments&&i.call(arguments,2);if(o(t)){var a=function(){return t.apply(n,r?r.concat(i.call(arguments)):arguments)};return a._zid=h(t),a}if(s(n))return r?(r.unshift(t[n],t),e.proxy.apply(null,r)):e.proxy(t[n],t);throw new TypeError("expected function")},e.fn.bind=function(t,e,n){return this.on(t,e,n)},e.fn.unbind=function(t,e){return this.off(t,e)},e.fn.one=function(t,e,n,r){return this.on(t,e,n,r,1)};var b=function(){return!0},E=function(){return!1},j=/^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/,w={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};e.fn.delegate=function(t,e,n){return this.on(e,t,n)},e.fn.undelegate=function(t,e,n){return this.off(e,t,n)},e.fn.live=function(t,n){return e(document.body).delegate(this.selector,t,n),this},e.fn.die=function(t,n){return e(document.body).undelegate(this.selector,t,n),this},e.fn.on=function(t,n,a,u,f){var c,l,h=this;return t&&!s(t)?(e.each(t,function(t,e){h.on(t,n,a,e,f)}),h):(s(n)||o(u)||u===!1||(u=a,a=n,n=r),(u===r||a===!1)&&(u=a,a=r),u===!1&&(u=E),h.each(function(r,o){f&&(c=function(t){return x(o,t.type,u),u.apply(this,arguments)}),n&&(l=function(t){var r,s=e(t.target).closest(n,o).get(0);return s&&s!==o?(r=e.extend(S(t),{currentTarget:s,liveFired:o}),(c||u).apply(s,[r].concat(i.call(arguments,1)))):void 0}),y(o,t,u,a,n,l||c)}))},e.fn.off=function(t,n,i){var a=this;return t&&!s(t)?(e.each(t,function(t,e){a.off(t,n,e)}),a):(s(n)||o(i)||i===!1||(i=n,n=r),i===!1&&(i=E),a.each(function(){x(this,t,i,n)}))},e.fn.trigger=function(t,n){return t=s(t)||e.isPlainObject(t)?e.Event(t):T(t),t._args=n,this.each(function(){t.type in c&&"function"==typeof this[t.type]?this[t.type]():"dispatchEvent"in this?this.dispatchEvent(t):e(this).triggerHandler(t,n)})},e.fn.triggerHandler=function(t,n){var r,i;return this.each(function(o,a){r=S(s(t)?e.Event(t):t),r._args=n,r.target=a,e.each(p(a,t.type||t),function(t,e){return i=e.proxy(r),r.isImmediatePropagationStopped()?!1:void 0})}),i},"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(t){e.fn[t]=function(e){return 0 in arguments?this.bind(t,e):this.trigger(t)}}),e.Event=function(t,e){s(t)||(e=t,t=e.type);var n=document.createEvent(u[t]||"Events"),r=!0;if(e)for(var i in e)"bubbles"==i?r=!!e[i]:n[i]=e[i];return n.initEvent(t,r,!0),T(n)}}(e),function(e){function p(t,n,r){var i=e.Event(n);return e(t).trigger(i,r),!i.isDefaultPrevented()}function d(t,e,n,i){return t.global?p(e||r,n,i):void 0}function m(t){t.global&&0===e.active++&&d(t,null,"ajaxStart")}function g(t){t.global&&!--e.active&&d(t,null,"ajaxStop")}function v(t,e){var n=e.context;return e.beforeSend.call(n,t,e)===!1||d(e,n,"ajaxBeforeSend",[t,e])===!1?!1:void d(e,n,"ajaxSend",[t,e])}function y(t,e,n,r){var i=n.context,o="success";n.success.call(i,t,o,e),r&&r.resolveWith(i,[t,o,e]),d(n,i,"ajaxSuccess",[e,n,t]),b(o,e,n)}function x(t,e,n,r,i){var o=r.context;r.error.call(o,n,e,t),i&&i.rejectWith(o,[n,e,t]),d(r,o,"ajaxError",[n,r,t||e]),b(e,n,r)}function b(t,e,n){var r=n.context;n.complete.call(r,e,t),d(n,r,"ajaxComplete",[e,n]),g(n)}function E(t,e,n){if(n.dataFilter==j)return t;var r=n.context;return n.dataFilter.call(r,t,e)}function j(){}function w(t){return t&&(t=t.split(";",2)[0]),t&&(t==c?"html":t==f?"json":a.test(t)?"script":u.test(t)&&"xml")||"text"}function T(t,e){return""==e?t:(t+"&"+e).replace(/[&?]{1,2}/,"?")}function S(t){t.processData&&t.data&&"string"!=e.type(t.data)&&(t.data=e.param(t.data,t.traditional)),!t.data||t.type&&"GET"!=t.type.toUpperCase()&&"jsonp"!=t.dataType||(t.url=T(t.url,t.data),t.data=void 0)}function C(t,n,r,i){return e.isFunction(n)&&(i=r,r=n,n=void 0),e.isFunction(r)||(i=r,r=void 0),{url:t,data:n,success:r,dataType:i}}function O(t,n,r,i){var o,s=e.isArray(n),a=e.isPlainObject(n);e.each(n,function(n,u){o=e.type(u),i&&(n=r?i:i+"["+(a||"object"==o||"array"==o?n:"")+"]"),!i&&s?t.add(u.name,u.value):"array"==o||!r&&"object"==o?O(t,u,r,n):t.add(n,u)})}var i,o,n=+new Date,r=t.document,s=/)<[^<]*)*<\/script>/gi,a=/^(?:text|application)\/javascript/i,u=/^(?:text|application)\/xml/i,f="application/json",c="text/html",l=/^\s*$/,h=r.createElement("a");h.href=t.location.href,e.active=0,e.ajaxJSONP=function(i,o){if(!("type"in i))return e.ajax(i);var c,p,s=i.jsonpCallback,a=(e.isFunction(s)?s():s)||"Zepto"+n++,u=r.createElement("script"),f=t[a],l=function(t){e(u).triggerHandler("error",t||"abort")},h={abort:l};return o&&o.promise(h),e(u).on("load error",function(n,r){clearTimeout(p),e(u).off().remove(),"error"!=n.type&&c?y(c[0],h,i,o):x(null,r||"error",h,i,o),t[a]=f,c&&e.isFunction(f)&&f(c[0]),f=c=void 0}),v(h,i)===!1?(l("abort"),h):(t[a]=function(){c=arguments},u.src=i.url.replace(/\?(.+)=\?/,"?$1="+a),r.head.appendChild(u),i.timeout>0&&(p=setTimeout(function(){l("timeout")},i.timeout)),h)},e.ajaxSettings={type:"GET",beforeSend:j,success:j,error:j,complete:j,context:null,global:!0,xhr:function(){return new t.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:f,xml:"application/xml, text/xml",html:c,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0,dataFilter:j},e.ajax=function(n){var u,f,s=e.extend({},n||{}),a=e.Deferred&&e.Deferred();for(i in e.ajaxSettings)void 0===s[i]&&(s[i]=e.ajaxSettings[i]);m(s),s.crossDomain||(u=r.createElement("a"),u.href=s.url,u.href=u.href,s.crossDomain=h.protocol+"//"+h.host!=u.protocol+"//"+u.host),s.url||(s.url=t.location.toString()),(f=s.url.indexOf("#"))>-1&&(s.url=s.url.slice(0,f)),S(s);var c=s.dataType,p=/\?.+=\?/.test(s.url);if(p&&(c="jsonp"),s.cache!==!1&&(n&&n.cache===!0||"script"!=c&&"jsonp"!=c)||(s.url=T(s.url,"_="+Date.now())),"jsonp"==c)return p||(s.url=T(s.url,s.jsonp?s.jsonp+"=?":s.jsonp===!1?"":"callback=?")),e.ajaxJSONP(s,a);var P,d=s.accepts[c],g={},b=function(t,e){g[t.toLowerCase()]=[t,e]},C=/^([\w-]+:)\/\//.test(s.url)?RegExp.$1:t.location.protocol,N=s.xhr(),O=N.setRequestHeader;if(a&&a.promise(N),s.crossDomain||b("X-Requested-With","XMLHttpRequest"),b("Accept",d||"*/*"),(d=s.mimeType||d)&&(d.indexOf(",")>-1&&(d=d.split(",",2)[0]),N.overrideMimeType&&N.overrideMimeType(d)),(s.contentType||s.contentType!==!1&&s.data&&"GET"!=s.type.toUpperCase())&&b("Content-Type",s.contentType||"application/x-www-form-urlencoded"),s.headers)for(o in s.headers)b(o,s.headers[o]);if(N.setRequestHeader=b,N.onreadystatechange=function(){if(4==N.readyState){N.onreadystatechange=j,clearTimeout(P);var t,n=!1;if(N.status>=200&&N.status<300||304==N.status||0==N.status&&"file:"==C){if(c=c||w(s.mimeType||N.getResponseHeader("content-type")),"arraybuffer"==N.responseType||"blob"==N.responseType)t=N.response;else{t=N.responseText;try{t=E(t,c,s),"script"==c?(1,eval)(t):"xml"==c?t=N.responseXML:"json"==c&&(t=l.test(t)?null:e.parseJSON(t))}catch(r){n=r}if(n)return x(n,"parsererror",N,s,a)}y(t,N,s,a)}else x(N.statusText||null,N.status?"error":"abort",N,s,a)}},v(N,s)===!1)return N.abort(),x(null,"abort",N,s,a),N;var A="async"in s?s.async:!0;if(N.open(s.type,s.url,A,s.username,s.password),s.xhrFields)for(o in s.xhrFields)N[o]=s.xhrFields[o];for(o in g)O.apply(N,g[o]);return s.timeout>0&&(P=setTimeout(function(){N.onreadystatechange=j,N.abort(),x(null,"timeout",N,s,a)},s.timeout)),N.send(s.data?s.data:null),N},e.get=function(){return e.ajax(C.apply(null,arguments))},e.post=function(){var t=C.apply(null,arguments);return t.type="POST",e.ajax(t)},e.getJSON=function(){var t=C.apply(null,arguments);return t.dataType="json",e.ajax(t)},e.fn.load=function(t,n,r){if(!this.length)return this;var a,i=this,o=t.split(/\s/),u=C(t,n,r),f=u.success;return o.length>1&&(u.url=o[0],a=o[1]),u.success=function(t){i.html(a?e("
    ").html(t.replace(s,"")).find(a):t),f&&f.apply(i,arguments)},e.ajax(u),this};var N=encodeURIComponent;e.param=function(t,n){var r=[];return r.add=function(t,n){e.isFunction(n)&&(n=n()),null==n&&(n=""),this.push(N(t)+"="+N(n))},O(r,t,n),r.join("&").replace(/%20/g,"+")}}(e),function(t){t.fn.serializeArray=function(){var e,n,r=[],i=function(t){return t.forEach?t.forEach(i):void r.push({name:e,value:t})};return this[0]&&t.each(this[0].elements,function(r,o){n=o.type,e=o.name,e&&"fieldset"!=o.nodeName.toLowerCase()&&!o.disabled&&"submit"!=n&&"reset"!=n&&"button"!=n&&"file"!=n&&("radio"!=n&&"checkbox"!=n||o.checked)&&i(t(o).val())}),r},t.fn.serialize=function(){var t=[];return this.serializeArray().forEach(function(e){t.push(encodeURIComponent(e.name)+"="+encodeURIComponent(e.value))}),t.join("&")},t.fn.submit=function(e){if(0 in arguments)this.bind("submit",e);else if(this.length){var n=t.Event("submit");this.eq(0).trigger(n),n.isDefaultPrevented()||this.get(0).submit()}return this}}(e),function(){try{getComputedStyle(void 0)}catch(e){var n=getComputedStyle;t.getComputedStyle=function(t,e){try{return n(t,e)}catch(r){return null}}}}(),e}); diff --git a/watering/lib/ESPUI/docs/Memory ESP32.png b/watering/lib/ESPUI/docs/Memory ESP32.png deleted file mode 100644 index 6423125..0000000 Binary files a/watering/lib/ESPUI/docs/Memory ESP32.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/Memory ESP8266.png b/watering/lib/ESPUI/docs/Memory ESP8266.png deleted file mode 100644 index 6139c27..0000000 Binary files a/watering/lib/ESPUI/docs/Memory ESP8266.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/SPIFFS ESP32.png b/watering/lib/ESPUI/docs/SPIFFS ESP32.png deleted file mode 100644 index 5b43d0e..0000000 Binary files a/watering/lib/ESPUI/docs/SPIFFS ESP32.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/SPIFFS ESP8266.png b/watering/lib/ESPUI/docs/SPIFFS ESP8266.png deleted file mode 100644 index 454cc77..0000000 Binary files a/watering/lib/ESPUI/docs/SPIFFS ESP8266.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/inlinestyles.gif b/watering/lib/ESPUI/docs/inlinestyles.gif deleted file mode 100644 index d418fa3..0000000 Binary files a/watering/lib/ESPUI/docs/inlinestyles.gif and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_button.png b/watering/lib/ESPUI/docs/ui_button.png deleted file mode 100644 index f343c3a..0000000 Binary files a/watering/lib/ESPUI/docs/ui_button.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_colours.png b/watering/lib/ESPUI/docs/ui_colours.png deleted file mode 100644 index a9c4cc7..0000000 Binary files a/watering/lib/ESPUI/docs/ui_colours.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_complete.png b/watering/lib/ESPUI/docs/ui_complete.png deleted file mode 100644 index 0445fff..0000000 Binary files a/watering/lib/ESPUI/docs/ui_complete.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_controlpad.png b/watering/lib/ESPUI/docs/ui_controlpad.png deleted file mode 100644 index bdd16db..0000000 Binary files a/watering/lib/ESPUI/docs/ui_controlpad.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_fileDisplay.png b/watering/lib/ESPUI/docs/ui_fileDisplay.png deleted file mode 100644 index ce7ee8d..0000000 Binary files a/watering/lib/ESPUI/docs/ui_fileDisplay.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_graph.png b/watering/lib/ESPUI/docs/ui_graph.png deleted file mode 100644 index 2fac78c..0000000 Binary files a/watering/lib/ESPUI/docs/ui_graph.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_groupedbuttons.png b/watering/lib/ESPUI/docs/ui_groupedbuttons.png deleted file mode 100644 index 55a13c3..0000000 Binary files a/watering/lib/ESPUI/docs/ui_groupedbuttons.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_groupedbuttons2.png b/watering/lib/ESPUI/docs/ui_groupedbuttons2.png deleted file mode 100644 index 0e4ddd2..0000000 Binary files a/watering/lib/ESPUI/docs/ui_groupedbuttons2.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_groupedbuttons3.png b/watering/lib/ESPUI/docs/ui_groupedbuttons3.png deleted file mode 100644 index db6090e..0000000 Binary files a/watering/lib/ESPUI/docs/ui_groupedbuttons3.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_inlinestyles2.png b/watering/lib/ESPUI/docs/ui_inlinestyles2.png deleted file mode 100644 index 0ffa76a..0000000 Binary files a/watering/lib/ESPUI/docs/ui_inlinestyles2.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_inputtypes.png b/watering/lib/ESPUI/docs/ui_inputtypes.png deleted file mode 100644 index 3ed67b6..0000000 Binary files a/watering/lib/ESPUI/docs/ui_inputtypes.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_labels.png b/watering/lib/ESPUI/docs/ui_labels.png deleted file mode 100644 index cf9301e..0000000 Binary files a/watering/lib/ESPUI/docs/ui_labels.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_number.png b/watering/lib/ESPUI/docs/ui_number.png deleted file mode 100644 index ef1b797..0000000 Binary files a/watering/lib/ESPUI/docs/ui_number.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_select1.png b/watering/lib/ESPUI/docs/ui_select1.png deleted file mode 100644 index 6eb8001..0000000 Binary files a/watering/lib/ESPUI/docs/ui_select1.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_select2.png b/watering/lib/ESPUI/docs/ui_select2.png deleted file mode 100644 index 5e9ff7b..0000000 Binary files a/watering/lib/ESPUI/docs/ui_select2.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_separators.png b/watering/lib/ESPUI/docs/ui_separators.png deleted file mode 100644 index d355bac..0000000 Binary files a/watering/lib/ESPUI/docs/ui_separators.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_slider.png b/watering/lib/ESPUI/docs/ui_slider.png deleted file mode 100644 index 3de4707..0000000 Binary files a/watering/lib/ESPUI/docs/ui_slider.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_status.png b/watering/lib/ESPUI/docs/ui_status.png deleted file mode 100644 index c01199c..0000000 Binary files a/watering/lib/ESPUI/docs/ui_status.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_switches.png b/watering/lib/ESPUI/docs/ui_switches.png deleted file mode 100644 index 0ff4073..0000000 Binary files a/watering/lib/ESPUI/docs/ui_switches.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_tabs.png b/watering/lib/ESPUI/docs/ui_tabs.png deleted file mode 100644 index e034e2e..0000000 Binary files a/watering/lib/ESPUI/docs/ui_tabs.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_text.png b/watering/lib/ESPUI/docs/ui_text.png deleted file mode 100644 index f6e4930..0000000 Binary files a/watering/lib/ESPUI/docs/ui_text.png and /dev/null differ diff --git a/watering/lib/ESPUI/docs/ui_widecontrols.png b/watering/lib/ESPUI/docs/ui_widecontrols.png deleted file mode 100644 index 77119a5..0000000 Binary files a/watering/lib/ESPUI/docs/ui_widecontrols.png and /dev/null differ diff --git a/watering/lib/ESPUI/examples/completeExample/completeExample.cpp b/watering/lib/ESPUI/examples/completeExample/completeExample.cpp deleted file mode 100644 index 6833310..0000000 --- a/watering/lib/ESPUI/examples/completeExample/completeExample.cpp +++ /dev/null @@ -1,564 +0,0 @@ -/** - * @file completeExample.cpp - * @author Ian Gray @iangray1000 - * - * This is an example GUI to show off all of the features of ESPUI. - * This can be built using the Arduino IDE, or PlatformIO. - * - * --------------------------------------------------------------------------------------- - * If you just want to see examples of the ESPUI code, jump down to the setUpUI() function - * --------------------------------------------------------------------------------------- - * - * When this program boots, it will load an SSID and password from the EEPROM. - * The SSID is a null-terminated C string stored at EEPROM addresses 0-31 - * The password is a null-terminated C string stored at EEPROM addresses 32-95. - * If these credentials do not work for some reason, the ESP will create an Access - * Point wifi with the SSID HOSTNAME (defined below). You can then connect and use - * the controls on the "Wifi Credentials" tab to store credentials into the EEPROM. - * - */ - -#include -#include -#include - -#if defined(ESP32) -#include -#include -#else -// esp8266 -#include -#include -#include -#ifndef CORE_MOCK -#ifndef MMU_IRAM_HEAP -#warning Try MMU option '2nd heap shared' in 'tools' IDE menu (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#option-summary) -#warning use decorators: { HeapSelectIram doAllocationsInIRAM; ESPUI.addControl(...) ... } (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#how-to-select-heap) -#warning then check http:///heap -#endif // MMU_IRAM_HEAP -#ifndef DEBUG_ESP_OOM -#error on ESP8266 and ESPUI, you must define OOM debug option when developping -#endif -#endif -#endif - -//Settings -#define SLOW_BOOT 0 -#define HOSTNAME "ESPUITest" -#define FORCE_USE_HOTSPOT 0 - - -//Function Prototypes -void connectWifi(); -void setUpUI(); -void enterWifiDetailsCallback(Control *sender, int type); -void textCallback(Control *sender, int type); -void generalCallback(Control *sender, int type); -void scrambleCallback(Control *sender, int type); -void styleCallback(Control *sender, int type); -void updateCallback(Control *sender, int type); -void getTimeCallback(Control *sender, int type); -void graphAddCallback(Control *sender, int type); -void graphClearCallback(Control *sender, int type); -void randomString(char *buf, int len); -void extendedCallback(Control* sender, int type, void* param); - -//UI handles -uint16_t wifi_ssid_text, wifi_pass_text; -uint16_t mainLabel, mainSwitcher, mainSlider, mainText, mainNumber, mainScrambleButton, mainTime; -uint16_t styleButton, styleLabel, styleSwitcher, styleSlider, styleButton2, styleLabel2, styleSlider2; -uint16_t graph; -volatile bool updates = false; - - - -// This is the main function which builds our GUI -void setUpUI() { - -#ifdef ESP8266 - { HeapSelectIram doAllocationsInIRAM; -#endif - - //Turn off verbose debugging - ESPUI.setVerbosity(Verbosity::Quiet); - - //Make sliders continually report their position as they are being dragged. - ESPUI.sliderContinuous = true; - - //This GUI is going to be a tabbed GUI, so we are adding most controls using ESPUI.addControl - //which allows us to set a parent control. If we didn't need tabs we could use the simpler add - //functions like: - // ESPUI.button() - // ESPUI.label() - - - /* - * Tab: Basic Controls - * This tab contains all the basic ESPUI controls, and shows how to read and update them at runtime. - *-----------------------------------------------------------------------------------------------------------*/ - auto maintab = ESPUI.addControl(Tab, "", "Basic controls"); - - ESPUI.addControl(Separator, "General controls", "", None, maintab); - ESPUI.addControl(Button, "Button", "Button 1", Alizarin, maintab, extendedCallback, (void*)19); - mainLabel = ESPUI.addControl(Label, "Label", "Label text", Emerald, maintab, generalCallback); - mainSwitcher = ESPUI.addControl(Switcher, "Switcher", "", Sunflower, maintab, generalCallback); - - //Sliders default to being 0 to 100, but if you want different limits you can add a Min and Max control - mainSlider = ESPUI.addControl(Slider, "Slider", "200", Turquoise, maintab, generalCallback); - ESPUI.addControl(Min, "", "10", None, mainSlider); - ESPUI.addControl(Max, "", "400", None, mainSlider); - - //These are the values for the selector's options. (Note that they *must* be declared static - //so that the storage is allocated in global memory and not just on the stack of this function.) - static String optionValues[] {"Value 1", "Value 2", "Value 3", "Value 4", "Value 5"}; - auto mainselector = ESPUI.addControl(Select, "Selector", "Selector", Wetasphalt, maintab, generalCallback); - for(auto const& v : optionValues) { - ESPUI.addControl(Option, v.c_str(), v, None, mainselector); - } - - mainText = ESPUI.addControl(Text, "Text Input", "Initial value", Alizarin, maintab, generalCallback); - - //Number inputs also accept Min and Max components, but you should still validate the values. - mainNumber = ESPUI.addControl(Number, "Number Input", "42", Emerald, maintab, generalCallback); - ESPUI.addControl(Min, "", "10", None, mainNumber); - ESPUI.addControl(Max, "", "50", None, mainNumber); - - ESPUI.addControl(Separator, "Updates", "", None, maintab); - - //This button will update all the updatable controls on this tab to random values - mainScrambleButton = ESPUI.addControl(Button, "Scramble Values", "Scramble Values", Carrot, maintab, scrambleCallback); - ESPUI.addControl(Switcher, "Constant updates", "0", Carrot, maintab, updateCallback); - mainTime = ESPUI.addControl(Time, "", "", None, 0, generalCallback); - ESPUI.addControl(Button, "Get Time", "Get Time", Carrot, maintab, getTimeCallback); - - ESPUI.addControl(Separator, "Control Pads", "", None, maintab); - ESPUI.addControl(Pad, "Normal", "", Peterriver, maintab, generalCallback); - ESPUI.addControl(PadWithCenter, "With center", "", Peterriver, maintab, generalCallback); - - - /* - * Tab: Colours - * This tab shows all the basic colours - *-----------------------------------------------------------------------------------------------------------*/ - auto colourtab = ESPUI.addControl(Tab, "", "Colours"); - ESPUI.addControl(Button, "Alizarin", "Alizarin", Alizarin, colourtab, generalCallback); - ESPUI.addControl(Button, "Turquoise", "Turquoise", Turquoise, colourtab, generalCallback); - ESPUI.addControl(Button, "Emerald", "Emerald", Emerald, colourtab, generalCallback); - ESPUI.addControl(Button, "Peterriver", "Peterriver", Peterriver, colourtab, generalCallback); - ESPUI.addControl(Button, "Wetasphalt", "Wetasphalt", Wetasphalt, colourtab, generalCallback); - ESPUI.addControl(Button, "Sunflower", "Sunflower", Sunflower, colourtab, generalCallback); - ESPUI.addControl(Button, "Carrot", "Carrot", Carrot, colourtab, generalCallback); - ESPUI.addControl(Button, "Dark", "Dark", Dark, colourtab, generalCallback); - - - /* - * Tab: Styled controls - * This tab shows off how inline CSS styles can be applied to elements and panels in order - * to customise the look of the UI. - *-----------------------------------------------------------------------------------------------------------*/ - auto styletab = ESPUI.addControl(Tab, "", "Styled controls"); - styleButton = ESPUI.addControl(Button, "Styled Button", "Button", Alizarin, styletab, generalCallback); - styleLabel = ESPUI.addControl(Label, "Styled Label", "This is a label", Alizarin, styletab, generalCallback); - styleSwitcher = ESPUI.addControl(Switcher, "Styled Switcher", "1", Alizarin, styletab, generalCallback); - styleSlider = ESPUI.addControl(Slider, "Styled Slider", "0", Alizarin, styletab, generalCallback); - - //This button will randomise the colours of the above controls to show updating of inline styles - ESPUI.addControl(Button, "Randomise Colours", "Randomise Colours", Sunflower, styletab, styleCallback); - - ESPUI.addControl(Separator, "Other styling examples", "", None, styletab); - styleButton2 = ESPUI.addControl(Button, "Styled Button", "Button", Alizarin, styletab, generalCallback); - ESPUI.setPanelStyle(styleButton2, "background: linear-gradient(90deg, rgba(131,58,180,1) 0%, rgba(253,29,29,1) 50%, rgba(252,176,69,1) 100%); border-bottom: #555;"); - ESPUI.setElementStyle(styleButton2, "border-radius: 2em; border: 3px solid black; width: 30%; background-color: #8df;"); - - styleSlider2 = ESPUI.addControl(Slider, "Styled Slider", "0", Dark, styletab, generalCallback); - ESPUI.setElementStyle(styleSlider2, "background: linear-gradient(to right, red, orange, yellow, green, blue);"); - - styleLabel2 = ESPUI.addControl(Label, "Styled Label", "This is a label", Dark, styletab, generalCallback); - ESPUI.setElementStyle(styleLabel2, "text-shadow: 3px 3px #74b1ff, 6px 6px #c64ad7; font-size: 60px; font-variant-caps: small-caps; background-color: unset; color: #c4f0bb; -webkit-text-stroke: 1px black;"); - - - /* - * Tab: Grouped controls - * This tab shows how multiple control can be grouped into the same panel through the use of the - * parentControl value. This also shows how to add labels to grouped controls, and how to use vertical controls. - *-----------------------------------------------------------------------------------------------------------*/ - auto grouptab = ESPUI.addControl(Tab, "", "Grouped controls"); - - //The parent of this button is a tab, so it will create a new panel with one control. - auto groupbutton = ESPUI.addControl(Button, "Button Group", "Button A", Dark, grouptab, generalCallback); - //However the parent of this button is another control, so therefore no new panel is - //created and the button is added to the existing panel. - ESPUI.addControl(Button, "", "Button B", Alizarin, groupbutton, generalCallback); - ESPUI.addControl(Button, "", "Button C", Alizarin, groupbutton, generalCallback); - - - //Sliders can be grouped as well - //To label each slider in the group, we are going add additional labels and give them custom CSS styles - //We need this CSS style rule, which will remove the label's background and ensure that it takes up the entire width of the panel - String clearLabelStyle = "background-color: unset; width: 100%;"; - //First we add the main slider to create a panel - auto groupsliders = ESPUI.addControl(Slider, "Slider Group", "10", Dark, grouptab, generalCallback); - //Then we add a label and set its style to the clearLabelStyle. Here we've just given it the name "A" - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "A", None, groupsliders), clearLabelStyle); - //We can now continue to add additional sliders and labels - ESPUI.addControl(Slider, "", "20", None, groupsliders, generalCallback); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "B", None, groupsliders), clearLabelStyle); - ESPUI.addControl(Slider, "", "30", None, groupsliders, generalCallback); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "C", None, groupsliders), clearLabelStyle); - - //We can also usefully group switchers. - auto groupswitcher = ESPUI.addControl(Switcher, "Switcher Group", "0", Dark, grouptab, generalCallback); - ESPUI.addControl(Switcher, "", "1", Sunflower, groupswitcher, generalCallback); - ESPUI.addControl(Switcher, "", "0", Sunflower, groupswitcher, generalCallback); - ESPUI.addControl(Switcher, "", "1", Sunflower, groupswitcher, generalCallback); - //To label these switchers we need to first go onto a "new line" below the line of switchers - //To do this we add an empty label set to be clear and full width (with our clearLabelStyle) - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "", None, groupswitcher), clearLabelStyle); - //We will now need another label style. This one sets its width to the same as a switcher (and turns off the background) - String switcherLabelStyle = "width: 60px; margin-left: .3rem; margin-right: .3rem; background-color: unset;"; - //We can now just add the styled labels. - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "A", None, groupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "B", None, groupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "C", None, groupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "D", None, groupswitcher), switcherLabelStyle); - - //You can mix and match different control types, but the results might sometimes - //need additional styling to lay out nicely. - auto grouplabel = ESPUI.addControl(Label, "Mixed Group", "Main label", Dark, grouptab); - auto grouplabel2 = ESPUI.addControl(Label, "", "Secondary label", Emerald, grouplabel); - ESPUI.addControl(Button, "", "Button D", Alizarin, grouplabel, generalCallback); - ESPUI.addControl(Switcher, "", "1", Sunflower, grouplabel, generalCallback); - ESPUI.setElementStyle(grouplabel2, "font-size: x-large; font-family: serif;"); - - //Some controls can even support vertical orientation, currently Switchers and Sliders - ESPUI.addControl(Separator, "Vertical controls", "", None, grouptab); - auto vertgroupswitcher = ESPUI.addControl(Switcher, "Vertical Switcher Group", "0", Dark, grouptab, generalCallback); - ESPUI.setVertical(vertgroupswitcher); - //On the following lines we wrap the value returned from addControl and send it straight to setVertical - ESPUI.setVertical(ESPUI.addControl(Switcher, "", "0", None, vertgroupswitcher, generalCallback)); - ESPUI.setVertical(ESPUI.addControl(Switcher, "", "0", None, vertgroupswitcher, generalCallback)); - ESPUI.setVertical(ESPUI.addControl(Switcher, "", "0", None, vertgroupswitcher, generalCallback)); - //The mechanism for labelling vertical switchers is the same as we used above for horizontal ones - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "", None, vertgroupswitcher), clearLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "A", None, vertgroupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "B", None, vertgroupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "C", None, vertgroupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "D", None, vertgroupswitcher), switcherLabelStyle); - - auto vertgroupslider = ESPUI.addControl(Slider, "Vertical Slider Group", "15", Dark, grouptab, generalCallback); - ESPUI.setVertical(vertgroupslider); - ESPUI.setVertical(ESPUI.addControl(Slider, "", "25", None, vertgroupslider, generalCallback)); - ESPUI.setVertical(ESPUI.addControl(Slider, "", "35", None, vertgroupslider, generalCallback)); - ESPUI.setVertical(ESPUI.addControl(Slider, "", "45", None, vertgroupslider, generalCallback)); - //The mechanism for labelling vertical sliders is the same as we used above for switchers - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "", None, vertgroupslider), clearLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "A", None, vertgroupslider), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "B", None, vertgroupslider), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "C", None, vertgroupslider), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "D", None, vertgroupslider), switcherLabelStyle); - - //Note that combining vertical and horizontal sliders is going to result in very messy layout! - - /* - * Tab: Example UI - * An example UI for the documentation - *-----------------------------------------------------------------------------------------------------------*/ - auto exampletab = ESPUI.addControl(Tab, "Example", "Example"); - ESPUI.addControl(Separator, "Control and Status", "", None, exampletab); - ESPUI.addControl(Switcher, "Power", "1", Alizarin, exampletab, generalCallback); - ESPUI.addControl(Label, "Status", "System status: OK", Wetasphalt, exampletab, generalCallback); - - ESPUI.addControl(Separator, "Settings", "", None, exampletab); - ESPUI.addControl(PadWithCenter, "Attitude Control", "", Dark, exampletab, generalCallback); - auto examplegroup1 = ESPUI.addControl(Button, "Activate Features", "Feature A", Carrot, exampletab, generalCallback); - ESPUI.addControl(Button, "Activate Features", "Feature B", Carrot, examplegroup1, generalCallback); - ESPUI.addControl(Button, "Activate Features", "Feature C", Carrot, examplegroup1, generalCallback); - ESPUI.addControl(Slider, "Value control", "45", Peterriver, exampletab, generalCallback); - - /* - * Tab: WiFi Credentials - * You use this tab to enter the SSID and password of a wifi network to autoconnect to. - *-----------------------------------------------------------------------------------------------------------*/ - auto wifitab = ESPUI.addControl(Tab, "", "WiFi Credentials"); - wifi_ssid_text = ESPUI.addControl(Text, "SSID", "", Alizarin, wifitab, textCallback); - //Note that adding a "Max" control to a text control sets the max length - ESPUI.addControl(Max, "", "32", None, wifi_ssid_text); - wifi_pass_text = ESPUI.addControl(Text, "Password", "", Alizarin, wifitab, textCallback); - ESPUI.addControl(Max, "", "64", None, wifi_pass_text); - ESPUI.addControl(Button, "Save", "Save", Peterriver, wifitab, enterWifiDetailsCallback); - - - //Finally, start up the UI. - //This should only be called once we are connected to WiFi. - ESPUI.begin(HOSTNAME); - -#ifdef ESP8266 - } // HeapSelectIram -#endif - -} - -//This callback generates and applies inline styles to a bunch of controls to change their colour. -//The styles created are of the form: -// "border-bottom: #999 3px solid; background-color: #aabbcc;" -// "background-color: #aabbcc;" -void styleCallback(Control *sender, int type) { - //Declare space for style strings. These have to be static so that they are always available - //to the websocket layer. If we'd not made them static they'd be allocated on the heap and - //will be unavailable when we leave this function. - static char stylecol1[60], stylecol2[30]; - if(type == B_UP) { - //Generate two random HTML hex colour codes, and print them into CSS style rules - sprintf(stylecol1, "border-bottom: #999 3px solid; background-color: #%06X;", (unsigned int) random(0x0, 0xFFFFFF)); - sprintf(stylecol2, "background-color: #%06X;", (unsigned int) random(0x0, 0xFFFFFF)); - - //Apply those styles to various elements to show how controls react to styling - ESPUI.setPanelStyle(styleButton, stylecol1); - ESPUI.setElementStyle(styleButton, stylecol2); - ESPUI.setPanelStyle(styleLabel, stylecol1); - ESPUI.setElementStyle(styleLabel, stylecol2); - ESPUI.setPanelStyle(styleSwitcher, stylecol1); - ESPUI.setElementStyle(styleSwitcher, stylecol2); - ESPUI.setPanelStyle(styleSlider, stylecol1); - ESPUI.setElementStyle(styleSlider, stylecol2); - } -} - - -//This callback updates the "values" of a bunch of controls -void scrambleCallback(Control *sender, int type) { - static char rndString1[10]; - static char rndString2[20]; - static bool scText = false; - - if(type == B_UP) { //Button callbacks generate events for both UP and DOWN. - //Generate some random text - randomString(rndString1, 10); - randomString(rndString2, 20); - - //Set the various controls to random value to show how controls can be updated at runtime - ESPUI.updateLabel(mainLabel, String(rndString1)); - ESPUI.updateSwitcher(mainSwitcher, ESPUI.getControl(mainSwitcher)->value.toInt() ? false : true); - ESPUI.updateSlider(mainSlider, random(10, 400)); - ESPUI.updateText(mainText, String(rndString2)); - ESPUI.updateNumber(mainNumber, random(100000)); - ESPUI.updateButton(mainScrambleButton, scText ? "Scrambled!" : "Scrambled."); - scText = !scText; - } -} - -void updateCallback(Control *sender, int type) { - updates = (sender->value.toInt() > 0); -} - -void getTimeCallback(Control *sender, int type) { - if(type == B_UP) { - ESPUI.updateTime(mainTime); - } -} - -void graphAddCallback(Control *sender, int type) { - if(type == B_UP) { - ESPUI.addGraphPoint(graph, random(1, 50)); - } -} - -void graphClearCallback(Control *sender, int type) { - if(type == B_UP) { - ESPUI.clearGraph(graph); - } -} - - -//Most elements in this test UI are assigned this generic callback which prints some -//basic information. Event types are defined in ESPUI.h -void generalCallback(Control *sender, int type) { - Serial.print("CB: id("); - Serial.print(sender->id); - Serial.print(") Type("); - Serial.print(type); - Serial.print(") '"); - Serial.print(sender->label); - Serial.print("' = "); - Serial.println(sender->value); -} - -// Most elements in this test UI are assigned this generic callback which prints some -// basic information. Event types are defined in ESPUI.h -// The extended param can be used to hold a pointer to additional information -// or for C++ it can be used to return a this pointer for quick access -// using a lambda function -void extendedCallback(Control* sender, int type, void* param) -{ - Serial.print("CB: id("); - Serial.print(sender->id); - Serial.print(") Type("); - Serial.print(type); - Serial.print(") '"); - Serial.print(sender->label); - Serial.print("' = "); - Serial.println(sender->value); - Serial.print("param = "); - Serial.println((long)param); -} - -void setup() { - randomSeed(0); - Serial.begin(115200); - while(!Serial); - if(SLOW_BOOT) delay(5000); //Delay booting to give time to connect a serial monitor - connectWifi(); - #if defined(ESP32) - WiFi.setSleep(false); //For the ESP32: turn off sleeping to increase UI responsivness (at the cost of power use) - #endif - setUpUI(); -} - -void loop() { - static long unsigned lastTime = 0; - - //Send periodic updates if switcher is turned on - if(updates && millis() > lastTime + 500) { - static uint16_t sliderVal = 10; - - //Flick this switcher on and off - ESPUI.updateSwitcher(mainSwitcher, ESPUI.getControl(mainSwitcher)->value.toInt() ? false : true); - sliderVal += 10; - if(sliderVal > 400) sliderVal = 10; - - //Sliders, numbers, and labels can all be updated at will - ESPUI.updateSlider(mainSlider, sliderVal); - ESPUI.updateNumber(mainNumber, random(100000)); - ESPUI.updateLabel(mainLabel, String(sliderVal)); - lastTime = millis(); - } - - //Simple debug UART interface - if(Serial.available()) { - switch(Serial.read()) { - case 'w': //Print IP details - Serial.println(WiFi.localIP()); - break; - case 'W': //Reconnect wifi - connectWifi(); - break; - case 'C': //Force a crash (for testing exception decoder) - #if !defined(ESP32) - ((void (*)())0xf00fdead)(); - #endif - break; - default: - Serial.print('#'); - break; - } - } - - #if !defined(ESP32) - //We don't need to call this explicitly on ESP32 but we do on 8266 - MDNS.update(); - #endif - -} - - - - -//Utilities -// -//If you are here just to see examples of how to use ESPUI, you can ignore the following functions -//------------------------------------------------------------------------------------------------ -void readStringFromEEPROM(String& buf, int baseaddress, int size) { - buf.reserve(size); - for (int i = baseaddress; i < baseaddress+size; i++) { - char c = EEPROM.read(i); - buf += c; - if(!c) break; - } -} - -void connectWifi() { - int connect_timeout; - -#if defined(ESP32) - WiFi.setHostname(HOSTNAME); -#else - WiFi.hostname(HOSTNAME); -#endif - Serial.println("Begin wifi..."); - - //Load credentials from EEPROM - if(!(FORCE_USE_HOTSPOT)) { - yield(); - EEPROM.begin(100); - String stored_ssid, stored_pass; - readStringFromEEPROM(stored_ssid, 0, 32); - readStringFromEEPROM(stored_pass, 32, 96); - EEPROM.end(); - - //Try to connect with stored credentials, fire up an access point if they don't work. - #if defined(ESP32) - WiFi.begin(stored_ssid.c_str(), stored_pass.c_str()); - #else - WiFi.begin(stored_ssid, stored_pass); - #endif - connect_timeout = 28; //7 seconds - while (WiFi.status() != WL_CONNECTED && connect_timeout > 0) { - delay(250); - Serial.print("."); - connect_timeout--; - } - } - - if (WiFi.status() == WL_CONNECTED) { - Serial.println(WiFi.localIP()); - Serial.println("Wifi started"); - - if (!MDNS.begin(HOSTNAME)) { - Serial.println("Error setting up MDNS responder!"); - } - } else { - Serial.println("\nCreating access point..."); - WiFi.mode(WIFI_AP); - WiFi.softAPConfig(IPAddress(192, 168, 1, 1), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0)); - WiFi.softAP(HOSTNAME); - - connect_timeout = 20; - do { - delay(250); - Serial.print(","); - connect_timeout--; - } while(connect_timeout); - } -} - -void enterWifiDetailsCallback(Control *sender, int type) { - if(type == B_UP) { - Serial.println("Saving credentials to EPROM..."); - Serial.println(ESPUI.getControl(wifi_ssid_text)->value); - Serial.println(ESPUI.getControl(wifi_pass_text)->value); - unsigned int i; - EEPROM.begin(100); - for(i = 0; i < ESPUI.getControl(wifi_ssid_text)->value.length(); i++) { - EEPROM.write(i, ESPUI.getControl(wifi_ssid_text)->value.charAt(i)); - if(i==30) break; //Even though we provided a max length, user input should never be trusted - } - EEPROM.write(i, '\0'); - - for(i = 0; i < ESPUI.getControl(wifi_pass_text)->value.length(); i++) { - EEPROM.write(i + 32, ESPUI.getControl(wifi_pass_text)->value.charAt(i)); - if(i==94) break; //Even though we provided a max length, user input should never be trusted - } - EEPROM.write(i + 32, '\0'); - EEPROM.end(); - } -} - -void textCallback(Control *sender, int type) { - //This callback is needed to handle the changed values, even though it doesn't do anything itself. -} - -void randomString(char *buf, int len) { - for(auto i = 0; i < len-1; i++) - buf[i] = random(0, 26) + 'A'; - buf[len-1] = '\0'; -} diff --git a/watering/lib/ESPUI/examples/completeExample/completeExample.ino b/watering/lib/ESPUI/examples/completeExample/completeExample.ino deleted file mode 100644 index a4db808..0000000 --- a/watering/lib/ESPUI/examples/completeExample/completeExample.ino +++ /dev/null @@ -1,4 +0,0 @@ -// placeholder -#if CORE_MOCK -#include "completeExample.cpp" -#endif diff --git a/watering/lib/ESPUI/examples/completeLambda/completeLambda.ino b/watering/lib/ESPUI/examples/completeLambda/completeLambda.ino deleted file mode 100644 index a435d93..0000000 --- a/watering/lib/ESPUI/examples/completeLambda/completeLambda.ino +++ /dev/null @@ -1,544 +0,0 @@ -/** - * @file completeExample.cpp - * @author Ian Gray @iangray1000 - * - * This is an example GUI to show off all of the features of ESPUI. - * This can be built using the Arduino IDE, or PlatformIO. - * - * --------------------------------------------------------------------------------------- - * If you just want to see examples of the ESPUI code, jump down to the setUpUI() function - * --------------------------------------------------------------------------------------- - * - * When this program boots, it will load an SSID and password from the EEPROM. - * The SSID is a null-terminated C string stored at EEPROM addresses 0-31 - * The password is a null-terminated C string stored at EEPROM addresses 32-95. - * If these credentials do not work for some reason, the ESP will create an Access - * Point wifi with the SSID HOSTNAME (defined below). You can then connect and use - * the controls on the "Wifi Credentials" tab to store credentials into the EEPROM. - * - * Version with lambdas. Comparing to version with only callbacks: - * diff -u ../completeExample/completeExample.cpp completeLambda.ino|less - * - */ - -#include -#include -#include - -#if defined(ESP32) -#include -#include -#else -// esp8266 -#include -#include -#include -#ifndef CORE_MOCK -#ifndef MMU_IRAM_HEAP -#warning Try MMU option '2nd heap shared' in 'tools' IDE menu (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#option-summary) -#warning use decorators: { HeapSelectIram doAllocationsInIRAM; ESPUI.addControl(...) ... } (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#how-to-select-heap) -#warning then check http:///heap -#endif // MMU_IRAM_HEAP -#ifndef DEBUG_ESP_OOM -#error on ESP8266 and ESPUI, you must define OOM debug option when developping -#endif -#endif -#endif - -//Settings -#define SLOW_BOOT 0 -#define HOSTNAME "ESPUITest" -#define FORCE_USE_HOTSPOT 0 - - -//Function Prototypes -void connectWifi(); -void setUpUI(); -void textCallback(Control *sender, int type); -void generalCallback(Control *sender, int type); -void randomString(char *buf, int len); -void paramCallback(Control* sender, int type, int param); - -//UI handles -uint16_t wifi_ssid_text, wifi_pass_text; -uint16_t mainLabel, mainSwitcher, mainSlider, mainText, mainNumber, mainScrambleButton, mainTime; -uint16_t styleButton, styleLabel, styleSwitcher, styleSlider, styleButton2, styleLabel2, styleSlider2; -uint16_t graph; -volatile bool updates = false; - - - -// This is the main function which builds our GUI -void setUpUI() { - -#ifdef ESP8266 - { HeapSelectIram doAllocationsInIRAM; -#endif - - //Turn off verbose debugging - ESPUI.setVerbosity(Verbosity::Quiet); - - //Make sliders continually report their position as they are being dragged. - ESPUI.sliderContinuous = true; - - //This GUI is going to be a tabbed GUI, so we are adding most controls using ESPUI.addControl - //which allows us to set a parent control. If we didn't need tabs we could use the simpler add - //functions like: - // ESPUI.button() - // ESPUI.label() - - - /* - * Tab: Basic Controls - * This tab contains all the basic ESPUI controls, and shows how to read and update them at runtime. - *-----------------------------------------------------------------------------------------------------------*/ - auto maintab = ESPUI.addControl(Tab, "", "Basic controls"); - - ESPUI.addControl(Separator, "General controls", "", None, maintab); - ESPUI.addControl(Button, "Button", "Button 1", Alizarin, maintab, [](Control *sender, int type){ paramCallback(sender, type, 19); }); - mainLabel = ESPUI.addControl(Label, "Label", "Label text", Emerald, maintab, generalCallback); - mainSwitcher = ESPUI.addControl(Switcher, "Switcher", "", Sunflower, maintab, generalCallback); - - //Sliders default to being 0 to 100, but if you want different limits you can add a Min and Max control - mainSlider = ESPUI.addControl(Slider, "Slider", "200", Turquoise, maintab, generalCallback); - ESPUI.addControl(Min, "", "10", None, mainSlider); - ESPUI.addControl(Max, "", "400", None, mainSlider); - - //These are the values for the selector's options. (Note that they *must* be declared static - //so that the storage is allocated in global memory and not just on the stack of this function.) - static String optionValues[] {"Value 1", "Value 2", "Value 3", "Value 4", "Value 5"}; - auto mainselector = ESPUI.addControl(Select, "Selector", "Selector", Wetasphalt, maintab, generalCallback); - for(auto const& v : optionValues) { - ESPUI.addControl(Option, v.c_str(), v, None, mainselector); - } - - mainText = ESPUI.addControl(Text, "Text Input", "Initial value", Alizarin, maintab, generalCallback); - - //Number inputs also accept Min and Max components, but you should still validate the values. - mainNumber = ESPUI.addControl(Number, "Number Input", "42", Emerald, maintab, generalCallback); - ESPUI.addControl(Min, "", "10", None, mainNumber); - ESPUI.addControl(Max, "", "50", None, mainNumber); - - ESPUI.addControl(Separator, "Updates", "", None, maintab); - - //This button will update all the updatable controls on this tab to random values - mainScrambleButton = ESPUI.addControl(Button, "Scramble Values", "Scramble Values", Carrot, maintab, - //This callback updates the "values" of a bunch of controls - [](Control *sender, int type) { - static char rndString1[10]; - static char rndString2[20]; - static bool scText = false; - - if(type == B_UP) { //Button callbacks generate events for both UP and DOWN. - //Generate some random text - randomString(rndString1, 10); - randomString(rndString2, 20); - - //Set the various controls to random value to show how controls can be updated at runtime - ESPUI.updateLabel(mainLabel, String(rndString1)); - ESPUI.updateSwitcher(mainSwitcher, ESPUI.getControl(mainSwitcher)->value.toInt() ? false : true); - ESPUI.updateSlider(mainSlider, random(10, 400)); - ESPUI.updateText(mainText, String(rndString2)); - ESPUI.updateNumber(mainNumber, random(100000)); - ESPUI.updateButton(mainScrambleButton, scText ? "Scrambled!" : "Scrambled."); - scText = !scText; - } - }); - - ESPUI.addControl(Switcher, "Constant updates", "0", Carrot, maintab, - [](Control *sender, int type) { - updates = (sender->value.toInt() > 0); - }); - - mainTime = ESPUI.addControl(Time, "", "", None, 0, generalCallback); - - ESPUI.addControl(Button, "Get Time", "Get Time", Carrot, maintab, - [](Control *sender, int type) { - if(type == B_UP) { - ESPUI.updateTime(mainTime); - } - }); - - ESPUI.addControl(Separator, "Control Pads", "", None, maintab); - ESPUI.addControl(Pad, "Normal", "", Peterriver, maintab, generalCallback); - ESPUI.addControl(PadWithCenter, "With center", "", Peterriver, maintab, generalCallback); - - - /* - * Tab: Colours - * This tab shows all the basic colours - *-----------------------------------------------------------------------------------------------------------*/ - auto colourtab = ESPUI.addControl(Tab, "", "Colours"); - ESPUI.addControl(Button, "Alizarin", "Alizarin", Alizarin, colourtab, generalCallback); - ESPUI.addControl(Button, "Turquoise", "Turquoise", Turquoise, colourtab, generalCallback); - ESPUI.addControl(Button, "Emerald", "Emerald", Emerald, colourtab, generalCallback); - ESPUI.addControl(Button, "Peterriver", "Peterriver", Peterriver, colourtab, generalCallback); - ESPUI.addControl(Button, "Wetasphalt", "Wetasphalt", Wetasphalt, colourtab, generalCallback); - ESPUI.addControl(Button, "Sunflower", "Sunflower", Sunflower, colourtab, generalCallback); - ESPUI.addControl(Button, "Carrot", "Carrot", Carrot, colourtab, generalCallback); - ESPUI.addControl(Button, "Dark", "Dark", Dark, colourtab, generalCallback); - - - /* - * Tab: Styled controls - * This tab shows off how inline CSS styles can be applied to elements and panels in order - * to customise the look of the UI. - *-----------------------------------------------------------------------------------------------------------*/ - auto styletab = ESPUI.addControl(Tab, "", "Styled controls"); - styleButton = ESPUI.addControl(Button, "Styled Button", "Button", Alizarin, styletab, generalCallback); - styleLabel = ESPUI.addControl(Label, "Styled Label", "This is a label", Alizarin, styletab, generalCallback); - styleSwitcher = ESPUI.addControl(Switcher, "Styled Switcher", "1", Alizarin, styletab, generalCallback); - styleSlider = ESPUI.addControl(Slider, "Styled Slider", "0", Alizarin, styletab, generalCallback); - - //This button will randomise the colours of the above controls to show updating of inline styles - ESPUI.addControl(Button, "Randomise Colours", "Randomise Colours", Sunflower, styletab, - //This callback generates and applies inline styles to a bunch of controls to change their colour. - //The styles created are of the form: - // "border-bottom: #999 3px solid; background-color: #aabbcc;" - // "background-color: #aabbcc;" - [](Control *sender, int type) { - //Declare space for style strings. These have to be static so that they are always available - //to the websocket layer. If we'd not made them static they'd be allocated on the heap and - //will be unavailable when we leave this function. - static char stylecol1[60], stylecol2[30]; - if(type == B_UP) { - //Generate two random HTML hex colour codes, and print them into CSS style rules - sprintf(stylecol1, "border-bottom: #999 3px solid; background-color: #%06X;", (unsigned int) random(0x0, 0xFFFFFF)); - sprintf(stylecol2, "background-color: #%06X;", (unsigned int) random(0x0, 0xFFFFFF)); - - //Apply those styles to various elements to show how controls react to styling - ESPUI.setPanelStyle(styleButton, stylecol1); - ESPUI.setElementStyle(styleButton, stylecol2); - ESPUI.setPanelStyle(styleLabel, stylecol1); - ESPUI.setElementStyle(styleLabel, stylecol2); - ESPUI.setPanelStyle(styleSwitcher, stylecol1); - ESPUI.setElementStyle(styleSwitcher, stylecol2); - ESPUI.setPanelStyle(styleSlider, stylecol1); - ESPUI.setElementStyle(styleSlider, stylecol2); - } - }); - - ESPUI.addControl(Separator, "Other styling examples", "", None, styletab); - styleButton2 = ESPUI.addControl(Button, "Styled Button", "Button", Alizarin, styletab, generalCallback); - ESPUI.setPanelStyle(styleButton2, "background: linear-gradient(90deg, rgba(131,58,180,1) 0%, rgba(253,29,29,1) 50%, rgba(252,176,69,1) 100%); border-bottom: #555;"); - ESPUI.setElementStyle(styleButton2, "border-radius: 2em; border: 3px solid black; width: 30%; background-color: #8df;"); - - styleSlider2 = ESPUI.addControl(Slider, "Styled Slider", "0", Dark, styletab, generalCallback); - ESPUI.setElementStyle(styleSlider2, "background: linear-gradient(to right, red, orange, yellow, green, blue);"); - - styleLabel2 = ESPUI.addControl(Label, "Styled Label", "This is a label", Dark, styletab, generalCallback); - ESPUI.setElementStyle(styleLabel2, "text-shadow: 3px 3px #74b1ff, 6px 6px #c64ad7; font-size: 60px; font-variant-caps: small-caps; background-color: unset; color: #c4f0bb; -webkit-text-stroke: 1px black;"); - - - /* - * Tab: Grouped controls - * This tab shows how multiple control can be grouped into the same panel through the use of the - * parentControl value. This also shows how to add labels to grouped controls, and how to use vertical controls. - *-----------------------------------------------------------------------------------------------------------*/ - auto grouptab = ESPUI.addControl(Tab, "", "Grouped controls"); - - //The parent of this button is a tab, so it will create a new panel with one control. - auto groupbutton = ESPUI.addControl(Button, "Button Group", "Button A", Dark, grouptab, generalCallback); - //However the parent of this button is another control, so therefore no new panel is - //created and the button is added to the existing panel. - ESPUI.addControl(Button, "", "Button B", Alizarin, groupbutton, generalCallback); - ESPUI.addControl(Button, "", "Button C", Alizarin, groupbutton, generalCallback); - - - //Sliders can be grouped as well - //To label each slider in the group, we are going add additional labels and give them custom CSS styles - //We need this CSS style rule, which will remove the label's background and ensure that it takes up the entire width of the panel - String clearLabelStyle = "background-color: unset; width: 100%;"; - //First we add the main slider to create a panel - auto groupsliders = ESPUI.addControl(Slider, "Slider Group", "10", Dark, grouptab, generalCallback); - //Then we add a label and set its style to the clearLabelStyle. Here we've just given it the name "A" - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "A", None, groupsliders), clearLabelStyle); - //We can now continue to add additional sliders and labels - ESPUI.addControl(Slider, "", "20", None, groupsliders, generalCallback); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "B", None, groupsliders), clearLabelStyle); - ESPUI.addControl(Slider, "", "30", None, groupsliders, generalCallback); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "C", None, groupsliders), clearLabelStyle); - - //We can also usefully group switchers. - auto groupswitcher = ESPUI.addControl(Switcher, "Switcher Group", "0", Dark, grouptab, generalCallback); - ESPUI.addControl(Switcher, "", "1", Sunflower, groupswitcher, generalCallback); - ESPUI.addControl(Switcher, "", "0", Sunflower, groupswitcher, generalCallback); - ESPUI.addControl(Switcher, "", "1", Sunflower, groupswitcher, generalCallback); - //To label these switchers we need to first go onto a "new line" below the line of switchers - //To do this we add an empty label set to be clear and full width (with our clearLabelStyle) - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "", None, groupswitcher), clearLabelStyle); - //We will now need another label style. This one sets its width to the same as a switcher (and turns off the background) - String switcherLabelStyle = "width: 60px; margin-left: .3rem; margin-right: .3rem; background-color: unset;"; - //We can now just add the styled labels. - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "A", None, groupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "B", None, groupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "C", None, groupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "D", None, groupswitcher), switcherLabelStyle); - - //You can mix and match different control types, but the results might sometimes - //need additional styling to lay out nicely. - auto grouplabel = ESPUI.addControl(Label, "Mixed Group", "Main label", Dark, grouptab); - auto grouplabel2 = ESPUI.addControl(Label, "", "Secondary label", Emerald, grouplabel); - ESPUI.addControl(Button, "", "Button D", Alizarin, grouplabel, generalCallback); - ESPUI.addControl(Switcher, "", "1", Sunflower, grouplabel, generalCallback); - ESPUI.setElementStyle(grouplabel2, "font-size: x-large; font-family: serif;"); - - //Some controls can even support vertical orientation, currently Switchers and Sliders - ESPUI.addControl(Separator, "Vertical controls", "", None, grouptab); - auto vertgroupswitcher = ESPUI.addControl(Switcher, "Vertical Switcher Group", "0", Dark, grouptab, generalCallback); - ESPUI.setVertical(vertgroupswitcher); - //On the following lines we wrap the value returned from addControl and send it straight to setVertical - ESPUI.setVertical(ESPUI.addControl(Switcher, "", "0", None, vertgroupswitcher, generalCallback)); - ESPUI.setVertical(ESPUI.addControl(Switcher, "", "0", None, vertgroupswitcher, generalCallback)); - ESPUI.setVertical(ESPUI.addControl(Switcher, "", "0", None, vertgroupswitcher, generalCallback)); - //The mechanism for labelling vertical switchers is the same as we used above for horizontal ones - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "", None, vertgroupswitcher), clearLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "A", None, vertgroupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "B", None, vertgroupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "C", None, vertgroupswitcher), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "D", None, vertgroupswitcher), switcherLabelStyle); - - auto vertgroupslider = ESPUI.addControl(Slider, "Vertical Slider Group", "15", Dark, grouptab, generalCallback); - ESPUI.setVertical(vertgroupslider); - ESPUI.setVertical(ESPUI.addControl(Slider, "", "25", None, vertgroupslider, generalCallback)); - ESPUI.setVertical(ESPUI.addControl(Slider, "", "35", None, vertgroupslider, generalCallback)); - ESPUI.setVertical(ESPUI.addControl(Slider, "", "45", None, vertgroupslider, generalCallback)); - //The mechanism for labelling vertical sliders is the same as we used above for switchers - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "", None, vertgroupslider), clearLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "A", None, vertgroupslider), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "B", None, vertgroupslider), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "C", None, vertgroupslider), switcherLabelStyle); - ESPUI.setElementStyle(ESPUI.addControl(Label, "", "D", None, vertgroupslider), switcherLabelStyle); - - //Note that combining vertical and horizontal sliders is going to result in very messy layout! - - /* - * Tab: Example UI - * An example UI for the documentation - *-----------------------------------------------------------------------------------------------------------*/ - auto exampletab = ESPUI.addControl(Tab, "Example", "Example"); - ESPUI.addControl(Separator, "Control and Status", "", None, exampletab); - ESPUI.addControl(Switcher, "Power", "1", Alizarin, exampletab, generalCallback); - ESPUI.addControl(Label, "Status", "System status: OK", Wetasphalt, exampletab, generalCallback); - - ESPUI.addControl(Separator, "Settings", "", None, exampletab); - ESPUI.addControl(PadWithCenter, "Attitude Control", "", Dark, exampletab, generalCallback); - auto examplegroup1 = ESPUI.addControl(Button, "Activate Features", "Feature A", Carrot, exampletab, generalCallback); - ESPUI.addControl(Button, "Activate Features", "Feature B", Carrot, examplegroup1, generalCallback); - ESPUI.addControl(Button, "Activate Features", "Feature C", Carrot, examplegroup1, generalCallback); - ESPUI.addControl(Slider, "Value control", "45", Peterriver, exampletab, generalCallback); - - /* - * Tab: WiFi Credentials - * You use this tab to enter the SSID and password of a wifi network to autoconnect to. - *-----------------------------------------------------------------------------------------------------------*/ - auto wifitab = ESPUI.addControl(Tab, "", "WiFi Credentials"); - wifi_ssid_text = ESPUI.addControl(Text, "SSID", "", Alizarin, wifitab, textCallback); - //Note that adding a "Max" control to a text control sets the max length - ESPUI.addControl(Max, "", "32", None, wifi_ssid_text); - wifi_pass_text = ESPUI.addControl(Text, "Password", "", Alizarin, wifitab, textCallback); - ESPUI.addControl(Max, "", "64", None, wifi_pass_text); - ESPUI.addControl(Button, "Save", "Save", Peterriver, wifitab, - [](Control *sender, int type) { - if(type == B_UP) { - Serial.println("Saving credentials to EPROM..."); - Serial.println(ESPUI.getControl(wifi_ssid_text)->value); - Serial.println(ESPUI.getControl(wifi_pass_text)->value); - unsigned int i; - EEPROM.begin(100); - for(i = 0; i < ESPUI.getControl(wifi_ssid_text)->value.length(); i++) { - EEPROM.write(i, ESPUI.getControl(wifi_ssid_text)->value.charAt(i)); - if(i==30) break; //Even though we provided a max length, user input should never be trusted - } - EEPROM.write(i, '\0'); - - for(i = 0; i < ESPUI.getControl(wifi_pass_text)->value.length(); i++) { - EEPROM.write(i + 32, ESPUI.getControl(wifi_pass_text)->value.charAt(i)); - if(i==94) break; //Even though we provided a max length, user input should never be trusted - } - EEPROM.write(i + 32, '\0'); - EEPROM.end(); - } - }); - - - //Finally, start up the UI. - //This should only be called once we are connected to WiFi. - ESPUI.begin(HOSTNAME); - -#ifdef ESP8266 - } // HeapSelectIram -#endif - -} - - -//Most elements in this test UI are assigned this generic callback which prints some -//basic information. Event types are defined in ESPUI.h -void generalCallback(Control *sender, int type) { - Serial.print("CB: id("); - Serial.print(sender->id); - Serial.print(") Type("); - Serial.print(type); - Serial.print(") '"); - Serial.print(sender->label); - Serial.print("' = "); - Serial.println(sender->value); -} - -// Most elements in this test UI are assigned this generic callback which prints some -// basic information. Event types are defined in ESPUI.h -// The extended param can be used to pass additional information -void paramCallback(Control* sender, int type, int param) -{ - Serial.print("CB: id("); - Serial.print(sender->id); - Serial.print(") Type("); - Serial.print(type); - Serial.print(") '"); - Serial.print(sender->label); - Serial.print("' = "); - Serial.println(sender->value); - Serial.print("param = "); - Serial.println(param); -} - -void setup() { - randomSeed(0); - Serial.begin(115200); - while(!Serial); - if(SLOW_BOOT) delay(5000); //Delay booting to give time to connect a serial monitor - connectWifi(); - #if defined(ESP32) - WiFi.setSleep(false); //For the ESP32: turn off sleeping to increase UI responsivness (at the cost of power use) - #endif - setUpUI(); -} - -void loop() { - static long unsigned lastTime = 0; - - //Send periodic updates if switcher is turned on - if(updates && millis() > lastTime + 500) { - static uint16_t sliderVal = 10; - - //Flick this switcher on and off - ESPUI.updateSwitcher(mainSwitcher, ESPUI.getControl(mainSwitcher)->value.toInt() ? false : true); - sliderVal += 10; - if(sliderVal > 400) sliderVal = 10; - - //Sliders, numbers, and labels can all be updated at will - ESPUI.updateSlider(mainSlider, sliderVal); - ESPUI.updateNumber(mainNumber, random(100000)); - ESPUI.updateLabel(mainLabel, String(sliderVal)); - lastTime = millis(); - } - - //Simple debug UART interface - if(Serial.available()) { - switch(Serial.read()) { - case 'w': //Print IP details - Serial.println(WiFi.localIP()); - break; - case 'W': //Reconnect wifi - connectWifi(); - break; - case 'C': //Force a crash (for testing exception decoder) - #if !defined(ESP32) - ((void (*)())0xf00fdead)(); - #endif - break; - default: - Serial.print('#'); - break; - } - } - - #if !defined(ESP32) - //We don't need to call this explicitly on ESP32 but we do on 8266 - MDNS.update(); - #endif - -} - - - - -//Utilities -// -//If you are here just to see examples of how to use ESPUI, you can ignore the following functions -//------------------------------------------------------------------------------------------------ -void readStringFromEEPROM(String& buf, int baseaddress, int size) { - buf.reserve(size); - for (int i = baseaddress; i < baseaddress+size; i++) { - char c = EEPROM.read(i); - buf += c; - if(!c) break; - } -} - -void connectWifi() { - int connect_timeout; - -#if defined(ESP32) - WiFi.setHostname(HOSTNAME); -#else - WiFi.hostname(HOSTNAME); -#endif - Serial.println("Begin wifi..."); - - //Load credentials from EEPROM - if(!(FORCE_USE_HOTSPOT)) { - yield(); - EEPROM.begin(100); - String stored_ssid, stored_pass; - readStringFromEEPROM(stored_ssid, 0, 32); - readStringFromEEPROM(stored_pass, 32, 96); - EEPROM.end(); - - //Try to connect with stored credentials, fire up an access point if they don't work. - #if defined(ESP32) - WiFi.begin(stored_ssid.c_str(), stored_pass.c_str()); - #else - WiFi.begin(stored_ssid, stored_pass); - #endif - connect_timeout = 28; //7 seconds - while (WiFi.status() != WL_CONNECTED && connect_timeout > 0) { - delay(250); - Serial.print("."); - connect_timeout--; - } - } - - if (WiFi.status() == WL_CONNECTED) { - Serial.println(WiFi.localIP()); - Serial.println("Wifi started"); - - if (!MDNS.begin(HOSTNAME)) { - Serial.println("Error setting up MDNS responder!"); - } - } else { - Serial.println("\nCreating access point..."); - WiFi.mode(WIFI_AP); - WiFi.softAPConfig(IPAddress(192, 168, 1, 1), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0)); - WiFi.softAP(HOSTNAME); - - connect_timeout = 20; - do { - delay(250); - Serial.print(","); - connect_timeout--; - } while(connect_timeout); - } -} - - -void textCallback(Control *sender, int type) { - //This callback is needed to handle the changed values, even though it doesn't do anything itself. -} - -void randomString(char *buf, int len) { - for(auto i = 0; i < len-1; i++) - buf[i] = random(0, 26) + 'A'; - buf[len-1] = '\0'; -} diff --git a/watering/lib/ESPUI/examples/gui-generic-api/gui-generic-api.ino b/watering/lib/ESPUI/examples/gui-generic-api/gui-generic-api.ino deleted file mode 100644 index 556596b..0000000 --- a/watering/lib/ESPUI/examples/gui-generic-api/gui-generic-api.ino +++ /dev/null @@ -1,322 +0,0 @@ -#include -#include - -const byte DNS_PORT = 53; -IPAddress apIP(192, 168, 4, 1); -DNSServer dnsServer; - -#if defined(ESP32) -#include -#else -// esp8266 -#include -#include -#ifndef CORE_MOCK -#ifndef MMU_IRAM_HEAP -#warning Try MMU option '2nd heap shared' in 'tools' IDE menu (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#option-summary) -#warning use decorators: { HeapSelectIram doAllocationsInIRAM; ESPUI.addControl(...) ... } (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#how-to-select-heap) -#warning then check http:///heap -#endif // MMU_IRAM_HEAP -#if !defined(DEBUG_ESP_OOM) -#error on ESP8266 and ESPUI, you must define OOM debug option when developping -#endif -#endif -#endif - -const char* ssid = "ESPUI"; -const char* password = "espui"; -const char* hostname = "espui"; - -uint16_t status; -uint16_t button1; -uint16_t millisLabelId; -uint16_t switchOne; - -void numberCall(Control* sender, int type) -{ - Serial.println(sender->value); -} - -void textCall(Control* sender, int type) -{ - Serial.print("Text: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); -} - -void slider(Control* sender, int type) -{ - Serial.print("Slider: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); -} - -void buttonCallback(Control* sender, int type) -{ - switch (type) - { - case B_DOWN: - Serial.println("Button DOWN"); - break; - - case B_UP: - Serial.println("Button UP"); - break; - } -} - -void buttonExample(Control* sender, int type, void* param) -{ - Serial.print("param: "); - Serial.println((long)param); - switch (type) - { - case B_DOWN: - Serial.println("Status: Start"); - ESPUI.updateControlValue(status, "Start"); - - ESPUI.getControl(button1)->color = ControlColor::Carrot; - ESPUI.updateControl(button1); - break; - - case B_UP: - Serial.println("Status: Stop"); - ESPUI.updateControlValue(status, "Stop"); - - ESPUI.getControl(button1)->color = ControlColor::Peterriver; - ESPUI.updateControl(button1); - break; - } -} - -void padExample(Control* sender, int value) -{ - switch (value) - { - case P_LEFT_DOWN: - Serial.print("left down"); - break; - - case P_LEFT_UP: - Serial.print("left up"); - break; - - case P_RIGHT_DOWN: - Serial.print("right down"); - break; - - case P_RIGHT_UP: - Serial.print("right up"); - break; - - case P_FOR_DOWN: - Serial.print("for down"); - break; - - case P_FOR_UP: - Serial.print("for up"); - break; - - case P_BACK_DOWN: - Serial.print("back down"); - break; - - case P_BACK_UP: - Serial.print("back up"); - break; - - case P_CENTER_DOWN: - Serial.print("center down"); - break; - - case P_CENTER_UP: - Serial.print("center up"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void switchExample(Control* sender, int value) -{ - switch (value) - { - case S_ACTIVE: - Serial.print("Active:"); - break; - - case S_INACTIVE: - Serial.print("Inactive"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void selectExample(Control* sender, int value) -{ - Serial.print("Select: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); -} - -void otherSwitchExample(Control* sender, int value) -{ - switch (value) - { - case S_ACTIVE: - Serial.print("Active:"); - break; - - case S_INACTIVE: - Serial.print("Inactive"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void setup(void) -{ - ESPUI.setVerbosity(Verbosity::VerboseJSON); - Serial.begin(115200); - -#if defined(ESP32) - WiFi.setHostname(hostname); -#else - WiFi.hostname(hostname); -#endif - - // try to connect to existing network - WiFi.begin(ssid, password); - Serial.print("\n\nTry to connect to existing network"); - - { - uint8_t timeout = 10; - - // Wait for connection, 5s timeout - do - { - delay(500); - Serial.print("."); - timeout--; - } while (timeout && WiFi.status() != WL_CONNECTED); - - // not connected -> create hotspot - if (WiFi.status() != WL_CONNECTED) - { - Serial.print("\n\nCreating hotspot"); - - WiFi.mode(WIFI_AP); - delay(100); - WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); -#if defined(ESP32) - uint32_t chipid = 0; - for (int i = 0; i < 17; i = i + 8) - { - chipid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i; - } -#else - uint32_t chipid = ESP.getChipId(); -#endif - char ap_ssid[25]; - snprintf(ap_ssid, 26, "ESPUI-%08X", chipid); - WiFi.softAP(ap_ssid); - - timeout = 5; - - do - { - delay(500); - Serial.print("."); - timeout--; - } while (timeout); - } - } - - dnsServer.start(DNS_PORT, "*", apIP); - - Serial.println("\n\nWiFi parameters:"); - Serial.print("Mode: "); - Serial.println(WiFi.getMode() == WIFI_AP ? "Station" : "Client"); - Serial.print("IP address: "); - Serial.println(WiFi.getMode() == WIFI_AP ? WiFi.softAPIP() : WiFi.localIP()); - -#ifdef ESP8266 - { HeapSelectIram doAllocationsInIRAM; -#endif - - status = ESPUI.addControl(ControlType::Label, "Status:", "Stop", ControlColor::Turquoise); - - uint16_t select1 = ESPUI.addControl( - ControlType::Select, "Select:", "", ControlColor::Alizarin, Control::noParent, &selectExample); - - ESPUI.addControl(ControlType::Option, "Option1", "Opt1", ControlColor::Alizarin, select1); - ESPUI.addControl(ControlType::Option, "Option2", "Opt2", ControlColor::Alizarin, select1); - ESPUI.addControl(ControlType::Option, "Option3", "Opt3", ControlColor::Alizarin, select1); - - ESPUI.addControl( - ControlType::Text, "Text Test:", "a Text Field", ControlColor::Alizarin, Control::noParent, &textCall); - - millisLabelId = ESPUI.addControl(ControlType::Label, "Millis:", "0", ControlColor::Emerald, Control::noParent); - button1 = ESPUI.addControl( - ControlType::Button, "Push Button", "Press", ControlColor::Peterriver, Control::noParent, &buttonCallback); - ESPUI.addControl( - ControlType::Button, "Other Button", "Press", ControlColor::Wetasphalt, Control::noParent, &buttonExample, (void*)19); - ESPUI.addControl( - ControlType::PadWithCenter, "Pad with center", "", ControlColor::Sunflower, Control::noParent, &padExample); - ESPUI.addControl(ControlType::Pad, "Pad without center", "", ControlColor::Carrot, Control::noParent, &padExample); - switchOne = ESPUI.addControl( - ControlType::Switcher, "Switch one", "", ControlColor::Alizarin, Control::noParent, &switchExample); - ESPUI.addControl( - ControlType::Switcher, "Switch two", "", ControlColor::None, Control::noParent, &otherSwitchExample); - ESPUI.addControl(ControlType::Slider, "Slider one", "30", ControlColor::Alizarin, Control::noParent, &slider); - ESPUI.addControl(ControlType::Slider, "Slider two", "100", ControlColor::Alizarin, Control::noParent, &slider); - ESPUI.addControl(ControlType::Number, "Number:", "50", ControlColor::Alizarin, Control::noParent, &numberCall); - - /* - * .begin loads and serves all files from PROGMEM directly. - * If you want to serve the files from LITTLEFS use ESPUI.beginLITTLEFS - * (.prepareFileSystem has to be run in an empty sketch before) - */ - - // Enable this option if you want sliders to be continuous (update during move) and not discrete (update on stop) - // ESPUI.sliderContinuous = true; - - /* - * Optionally you can use HTTP BasicAuth. Keep in mind that this is NOT a - * SECURE way of limiting access. - * Anyone who is able to sniff traffic will be able to intercept your password - * since it is transmitted in cleartext. Just add a string as username and - * password, for example begin("ESPUI Control", "username", "password") - */ - - ESPUI.begin("ESPUI Control"); - -#ifdef ESP8266 - } // HeapSelectIram -#endif -} - -void loop(void) -{ - dnsServer.processNextRequest(); - - static long oldTime = 0; - static bool testSwitchState = false; - - if (millis() - oldTime > 5000) - { - ESPUI.updateControlValue(millisLabelId, String(millis())); - testSwitchState = !testSwitchState; - ESPUI.updateControlValue(switchOne, testSwitchState ? "1" : "0"); - - oldTime = millis(); - } -} diff --git a/watering/lib/ESPUI/examples/gui/gui.ino b/watering/lib/ESPUI/examples/gui/gui.ino deleted file mode 100644 index 71ab831..0000000 --- a/watering/lib/ESPUI/examples/gui/gui.ino +++ /dev/null @@ -1,301 +0,0 @@ -#include -#include - -const byte DNS_PORT = 53; -IPAddress apIP(192, 168, 4, 1); -DNSServer dnsServer; - -#if defined(ESP32) -#include -#else -// esp8266 -#include -#include -#ifndef CORE_MOCK -#ifndef MMU_IRAM_HEAP -#warning Try MMU option '2nd heap shared' in 'tools' IDE menu (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#option-summary) -#warning use decorators: { HeapSelectIram doAllocationsInIRAM; ESPUI.addControl(...) ... } (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#how-to-select-heap) -#warning then check http:///heap -#endif // MMU_IRAM_HEAP -#ifndef DEBUG_ESP_OOM -#error on ESP8266 and ESPUI, you must define OOM debug option when developping -#endif -#endif -#endif - -const char* ssid = "ESPUI"; -const char* password = "espui"; - -const char* hostname = "espui"; - -int statusLabelId; -int graphId; -int millisLabelId; -int testSwitchId; - -void numberCall(Control* sender, int type) -{ - Serial.println(sender->value); -} - -void textCall(Control* sender, int type) -{ - Serial.print("Text: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); -} - -void slider(Control* sender, int type) -{ - Serial.print("Slider: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); - // Like all Control Values in ESPUI slider values are Strings. To use them as int simply do this: - int sliderValueWithOffset = sender->value.toInt() + 100; - Serial.print("SliderValue with offset"); - Serial.println(sliderValueWithOffset); -} - -void buttonCallback(Control* sender, int type) -{ - switch (type) - { - case B_DOWN: - Serial.println("Button DOWN"); - break; - - case B_UP: - Serial.println("Button UP"); - break; - } -} - -void buttonExample(Control* sender, int type, void* param) -{ - Serial.print("param: "); - Serial.println((long)param); - switch (type) - { - case B_DOWN: - Serial.println("Status: Start"); - ESPUI.print(statusLabelId, "Start"); - break; - - case B_UP: - Serial.println("Status: Stop"); - ESPUI.print(statusLabelId, "Stop"); - break; - } -} -void padExample(Control* sender, int value) -{ - switch (value) - { - case P_LEFT_DOWN: - Serial.print("left down"); - break; - - case P_LEFT_UP: - Serial.print("left up"); - break; - - case P_RIGHT_DOWN: - Serial.print("right down"); - break; - - case P_RIGHT_UP: - Serial.print("right up"); - break; - - case P_FOR_DOWN: - Serial.print("for down"); - break; - - case P_FOR_UP: - Serial.print("for up"); - break; - - case P_BACK_DOWN: - Serial.print("back down"); - break; - - case P_BACK_UP: - Serial.print("back up"); - break; - - case P_CENTER_DOWN: - Serial.print("center down"); - break; - - case P_CENTER_UP: - Serial.print("center up"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void switchExample(Control* sender, int value) -{ - switch (value) - { - case S_ACTIVE: - Serial.print("Active:"); - break; - - case S_INACTIVE: - Serial.print("Inactive"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void otherSwitchExample(Control* sender, int value) -{ - switch (value) - { - case S_ACTIVE: - Serial.print("Active:"); - break; - - case S_INACTIVE: - Serial.print("Inactive"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void setup(void) -{ - ESPUI.setVerbosity(Verbosity::VerboseJSON); - Serial.begin(115200); - -#if defined(ESP32) - WiFi.setHostname(hostname); -#else - WiFi.hostname(hostname); -#endif - - // try to connect to existing network - WiFi.begin(ssid, password); - Serial.print("\n\nTry to connect to existing network"); - - { - uint8_t timeout = 10; - - // Wait for connection, 5s timeout - do - { - delay(500); - Serial.print("."); - timeout--; - } while (timeout && WiFi.status() != WL_CONNECTED); - - // not connected -> create hotspot - if (WiFi.status() != WL_CONNECTED) - { - Serial.print("\n\nCreating hotspot"); - - WiFi.mode(WIFI_AP); - delay(100); - WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); -#if defined(ESP32) - uint32_t chipid = 0; - for (int i = 0; i < 17; i = i + 8) - { - chipid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i; - } -#else - uint32_t chipid = ESP.getChipId(); -#endif - char ap_ssid[25]; - snprintf(ap_ssid, 26, "ESPUI-%08X", chipid); - WiFi.softAP(ap_ssid); - - timeout = 5; - - do - { - delay(500); - Serial.print("."); - timeout--; - } while (timeout); - } - } - - dnsServer.start(DNS_PORT, "*", apIP); - - Serial.println("\n\nWiFi parameters:"); - Serial.print("Mode: "); - Serial.println(WiFi.getMode() == WIFI_AP ? "Station" : "Client"); - Serial.print("IP address: "); - Serial.println(WiFi.getMode() == WIFI_AP ? WiFi.softAPIP() : WiFi.localIP()); - -#ifdef ESP8266 - { HeapSelectIram doAllocationsInIRAM; -#endif - - statusLabelId = ESPUI.label("Status:", ControlColor::Turquoise, "Stop"); - millisLabelId = ESPUI.label("Millis:", ControlColor::Emerald, "0"); - ESPUI.button("Push Button", &buttonCallback, ControlColor::Peterriver, "Press"); - ESPUI.button("Other Button", &buttonExample, ControlColor::Wetasphalt, "Press", (void*)19); - ESPUI.padWithCenter("Pad with center", &padExample, ControlColor::Sunflower); - ESPUI.pad("Pad without center", &padExample, ControlColor::Carrot); - testSwitchId = ESPUI.switcher("Switch one", &switchExample, ControlColor::Alizarin, false); - ESPUI.switcher("Switch two", &otherSwitchExample, ControlColor::None, true); - ESPUI.slider("Slider one", &slider, ControlColor::Alizarin, 30); - ESPUI.slider("Slider two", &slider, ControlColor::None, 100); - ESPUI.text("Text Test:", &textCall, ControlColor::Alizarin, "a Text Field"); - ESPUI.number("Numbertest", &numberCall, ControlColor::Alizarin, 5, 0, 10); - - graphId = ESPUI.graph("Graph Test", ControlColor::Wetasphalt); - - /* - * .begin loads and serves all files from PROGMEM directly. - * If you want to serve the files from LITTLEFS use ESPUI.beginLITTLEFS - * (.prepareFileSystem has to be run in an empty sketch before) - */ - - // Enable this option if you want sliders to be continuous (update during move) and not discrete (update on stop) - // ESPUI.sliderContinuous = true; - - /* - * Optionally you can use HTTP BasicAuth. Keep in mind that this is NOT a - * SECURE way of limiting access. - * Anyone who is able to sniff traffic will be able to intercept your password - * since it is transmitted in cleartext. Just add a string as username and - * password, for example begin("ESPUI Control", "username", "password") - */ - ESPUI.begin("ESPUI Control"); - -#ifdef ESP8266 - } // HeapSelectIram -#endif -} - -void loop(void) -{ - dnsServer.processNextRequest(); - - static long oldTime = 0; - static bool testSwitchState = false; - - if (millis() - oldTime > 5000) - { - ESPUI.print(millisLabelId, String(millis())); - - ESPUI.addGraphPoint(graphId, random(1, 50)); - - testSwitchState = !testSwitchState; - ESPUI.updateSwitcher(testSwitchId, testSwitchState); - - oldTime = millis(); - } -} diff --git a/watering/lib/ESPUI/examples/prepareFilesystem/prepareFilesystem.ino b/watering/lib/ESPUI/examples/prepareFilesystem/prepareFilesystem.ino deleted file mode 100644 index eae58d8..0000000 --- a/watering/lib/ESPUI/examples/prepareFilesystem/prepareFilesystem.ino +++ /dev/null @@ -1,16 +0,0 @@ -#include - -void setup(void) -{ - Serial.begin(115200); - ESPUI.setVerbosity(Verbosity::Verbose); //Enable verbose output so you see the files in LittleFS - delay(500); //Delay to allow Serial Monitor to start after a reset - Serial.println(F("\nPreparing filesystem with ESPUI resources")); - ESPUI.prepareFileSystem(); //Copy across current version of ESPUI resources - Serial.println(F("Done, files...")); - ESPUI.list(); //List all files on LittleFS, for info -} - -void loop() -{ -} diff --git a/watering/lib/ESPUI/examples/tabbedGui/tabbedGui.ino b/watering/lib/ESPUI/examples/tabbedGui/tabbedGui.ino deleted file mode 100644 index 4831a6b..0000000 --- a/watering/lib/ESPUI/examples/tabbedGui/tabbedGui.ino +++ /dev/null @@ -1,319 +0,0 @@ -#include -#include - -const byte DNS_PORT = 53; -IPAddress apIP(192, 168, 4, 1); -DNSServer dnsServer; - -#if defined(ESP32) -#include -#else -// esp8266 -#include -#include -#ifndef CORE_MOCK -#ifndef MMU_IRAM_HEAP -#warning Try MMU option '2nd heap shared' in 'tools' IDE menu (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#option-summary) -#warning use decorators: { HeapSelectIram doAllocationsInIRAM; ESPUI.addControl(...) ... } (cf. https://arduino-esp8266.readthedocs.io/en/latest/mmu.html#how-to-select-heap) -#warning then check http:///heap -#endif // MMU_IRAM_HEAP -#ifndef DEBUG_ESP_OOM -#error on ESP8266 and ESPUI, you must define OOM debug option when developping -#endif -#endif -#endif - -const char* ssid = "ESPUI"; -const char* password = "espui"; -const char* hostname = "espui"; - -uint16_t button1; -uint16_t switchOne; -uint16_t status; - -void numberCall(Control* sender, int type) -{ - Serial.println(sender->value); -} - -void textCall(Control* sender, int type) -{ - Serial.print("Text: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); -} - -void slider(Control* sender, int type) -{ - Serial.print("Slider: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); -} - -void buttonCallback(Control* sender, int type) -{ - switch (type) - { - case B_DOWN: - Serial.println("Button DOWN"); - break; - - case B_UP: - Serial.println("Button UP"); - break; - } -} - -void buttonExample(Control* sender, int type, void* param) -{ - Serial.print("param: "); - Serial.println((long)param); - switch (type) - { - case B_DOWN: - Serial.println("Status: Start"); - ESPUI.updateControlValue(status, "Start"); - - ESPUI.getControl(button1)->color = ControlColor::Carrot; - ESPUI.updateControl(button1); - break; - - case B_UP: - Serial.println("Status: Stop"); - ESPUI.updateControlValue(status, "Stop"); - - ESPUI.getControl(button1)->color = ControlColor::Peterriver; - ESPUI.updateControl(button1); - break; - } -} - -void padExample(Control* sender, int value) -{ - switch (value) - { - case P_LEFT_DOWN: - Serial.print("left down"); - break; - - case P_LEFT_UP: - Serial.print("left up"); - break; - - case P_RIGHT_DOWN: - Serial.print("right down"); - break; - - case P_RIGHT_UP: - Serial.print("right up"); - break; - - case P_FOR_DOWN: - Serial.print("for down"); - break; - - case P_FOR_UP: - Serial.print("for up"); - break; - - case P_BACK_DOWN: - Serial.print("back down"); - break; - - case P_BACK_UP: - Serial.print("back up"); - break; - - case P_CENTER_DOWN: - Serial.print("center down"); - break; - - case P_CENTER_UP: - Serial.print("center up"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void switchExample(Control* sender, int value) -{ - switch (value) - { - case S_ACTIVE: - Serial.print("Active:"); - break; - - case S_INACTIVE: - Serial.print("Inactive"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void selectExample(Control* sender, int value) -{ - Serial.print("Select: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); -} - -void otherSwitchExample(Control* sender, int value) -{ - switch (value) - { - case S_ACTIVE: - Serial.print("Active:"); - break; - - case S_INACTIVE: - Serial.print("Inactive"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void setup(void) -{ - Serial.begin(115200); - -#if defined(ESP32) - WiFi.setHostname(hostname); -#else - WiFi.hostname(hostname); -#endif - - // try to connect to existing network - WiFi.begin(ssid, password); - Serial.print("\n\nTry to connect to existing network"); - - { - uint8_t timeout = 10; - - // Wait for connection, 5s timeout - do - { - delay(500); - Serial.print("."); - timeout--; - } while (timeout && WiFi.status() != WL_CONNECTED); - - // not connected -> create hotspot - if (WiFi.status() != WL_CONNECTED) - { - Serial.print("\n\nCreating hotspot"); - - WiFi.mode(WIFI_AP); - delay(100); - WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); -#if defined(ESP32) - uint32_t chipid = 0; - for (int i = 0; i < 17; i = i + 8) - { - chipid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i; - } -#else - uint32_t chipid = ESP.getChipId(); -#endif - char ap_ssid[25]; - snprintf(ap_ssid, 26, "ESPUI-%08X", chipid); - WiFi.softAP(ap_ssid); - - timeout = 5; - - do - { - delay(500); - Serial.print("."); - timeout--; - } while (timeout); - } - } - - dnsServer.start(DNS_PORT, "*", apIP); - - Serial.println("\n\nWiFi parameters:"); - Serial.print("Mode: "); - Serial.println(WiFi.getMode() == WIFI_AP ? "Station" : "Client"); - Serial.print("IP address: "); - Serial.println(WiFi.getMode() == WIFI_AP ? WiFi.softAPIP() : WiFi.localIP()); - -#ifdef ESP8266 - { HeapSelectIram doAllocationsInIRAM; -#endif - - uint16_t tab1 = ESPUI.addControl(ControlType::Tab, "Settings 1", "Settings 1"); - uint16_t tab2 = ESPUI.addControl(ControlType::Tab, "Settings 2", "Settings 2"); - uint16_t tab3 = ESPUI.addControl(ControlType::Tab, "Settings 3", "Settings 3"); - - // shown above all tabs - status = ESPUI.addControl(ControlType::Label, "Status:", "Stop", ControlColor::Turquoise); - - uint16_t select1 - = ESPUI.addControl(ControlType::Select, "Select:", "", ControlColor::Alizarin, tab1, &selectExample); - ESPUI.addControl(ControlType::Option, "Option1", "Opt1", ControlColor::Alizarin, select1); - ESPUI.addControl(ControlType::Option, "Option2", "Opt2", ControlColor::Alizarin, select1); - ESPUI.addControl(ControlType::Option, "Option3", "Opt3", ControlColor::Alizarin, select1); - - ESPUI.addControl(ControlType::Text, "Text Test:", "a Text Field", ControlColor::Alizarin, tab1, &textCall); - - // tabbed controls - ESPUI.addControl(ControlType::Label, "Millis:", "0", ControlColor::Emerald, tab1); - button1 = ESPUI.addControl( - ControlType::Button, "Push Button", "Press", ControlColor::Peterriver, tab1, &buttonCallback); - ESPUI.addControl(ControlType::Button, "Other Button", "Press", ControlColor::Wetasphalt, tab1, &buttonExample, (void*)19); - ESPUI.addControl(ControlType::PadWithCenter, "Pad with center", "", ControlColor::Sunflower, tab2, &padExample); - ESPUI.addControl(ControlType::Pad, "Pad without center", "", ControlColor::Carrot, tab3, &padExample); - switchOne = ESPUI.addControl(ControlType::Switcher, "Switch one", "", ControlColor::Alizarin, tab3, &switchExample); - ESPUI.addControl(ControlType::Switcher, "Switch two", "", ControlColor::None, tab3, &otherSwitchExample); - ESPUI.addControl(ControlType::Slider, "Slider one", "30", ControlColor::Alizarin, tab1, &slider); - ESPUI.addControl(ControlType::Slider, "Slider two", "100", ControlColor::Alizarin, tab3, &slider); - ESPUI.addControl(ControlType::Number, "Number:", "50", ControlColor::Alizarin, tab3, &numberCall); - - /* - * .begin loads and serves all files from PROGMEM directly. - * If you want to serve the files from LITTLEFS use ESPUI.beginLITTLEFS - * (.prepareFileSystem has to be run in an empty sketch before) - */ - - // Enable this option if you want sliders to be continuous (update during move) and not discrete (update on stop) - // ESPUI.sliderContinuous = true; - - /* - * Optionally you can use HTTP BasicAuth. Keep in mind that this is NOT a - * SECURE way of limiting access. - * Anyone who is able to sniff traffic will be able to intercept your password - * since it is transmitted in cleartext. Just add a string as username and - * password, for example begin("ESPUI Control", "username", "password") - */ - - ESPUI.begin("ESPUI Control"); - -#ifdef ESP8266 - } // HeapSelectIram -#endif -} - -void loop(void) -{ - dnsServer.processNextRequest(); - - static long oldTime = 0; - static bool switchi = false; - - if (millis() - oldTime > 5000) - { - switchi = !switchi; - ESPUI.updateControlValue(switchOne, switchi ? "1" : "0"); - - oldTime = millis(); - } -} diff --git a/watering/lib/ESPUI/img/blocks/acknowledgements.html b/watering/lib/ESPUI/img/blocks/acknowledgements.html deleted file mode 100644 index c29dcbc..0000000 --- a/watering/lib/ESPUI/img/blocks/acknowledgements.html +++ /dev/null @@ -1,2 +0,0 @@ - -
    Icons made by Freepik from www.flaticon.com is licensed by CC 3.0 BY
    \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/button_pressed.svg b/watering/lib/ESPUI/img/blocks/button_pressed.svg deleted file mode 100644 index c7cf5a1..0000000 --- a/watering/lib/ESPUI/img/blocks/button_pressed.svg +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/watering/lib/ESPUI/img/blocks/button_released.svg b/watering/lib/ESPUI/img/blocks/button_released.svg deleted file mode 100644 index 7be0a56..0000000 --- a/watering/lib/ESPUI/img/blocks/button_released.svg +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/watering/lib/ESPUI/img/blocks/controller_center_pressed.svg b/watering/lib/ESPUI/img/blocks/controller_center_pressed.svg deleted file mode 100644 index 146e841..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_center_pressed.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_center_released.svg b/watering/lib/ESPUI/img/blocks/controller_center_released.svg deleted file mode 100644 index be2676b..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_center_released.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_down_pressed.svg b/watering/lib/ESPUI/img/blocks/controller_down_pressed.svg deleted file mode 100644 index be13e67..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_down_pressed.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_down_released.svg b/watering/lib/ESPUI/img/blocks/controller_down_released.svg deleted file mode 100644 index cd091f2..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_down_released.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_left_pressed.svg b/watering/lib/ESPUI/img/blocks/controller_left_pressed.svg deleted file mode 100644 index b2a800e..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_left_pressed.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_left_released.svg b/watering/lib/ESPUI/img/blocks/controller_left_released.svg deleted file mode 100644 index c66916c..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_left_released.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_right_pressed.svg b/watering/lib/ESPUI/img/blocks/controller_right_pressed.svg deleted file mode 100644 index 6e42679..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_right_pressed.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_right_released.svg b/watering/lib/ESPUI/img/blocks/controller_right_released.svg deleted file mode 100644 index 8946a5a..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_right_released.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_up_pressed.svg b/watering/lib/ESPUI/img/blocks/controller_up_pressed.svg deleted file mode 100644 index a67ea73..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_up_pressed.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/controller_up_released.svg b/watering/lib/ESPUI/img/blocks/controller_up_released.svg deleted file mode 100644 index ec66d54..0000000 --- a/watering/lib/ESPUI/img/blocks/controller_up_released.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/switch_off.svg b/watering/lib/ESPUI/img/blocks/switch_off.svg deleted file mode 100644 index a216630..0000000 --- a/watering/lib/ESPUI/img/blocks/switch_off.svg +++ /dev/null @@ -1,64 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/img/blocks/switch_on.svg b/watering/lib/ESPUI/img/blocks/switch_on.svg deleted file mode 100644 index 9b1539a..0000000 --- a/watering/lib/ESPUI/img/blocks/switch_on.svg +++ /dev/null @@ -1,61 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/watering/lib/ESPUI/keywords.txt b/watering/lib/ESPUI/keywords.txt deleted file mode 100644 index 84cd7eb..0000000 --- a/watering/lib/ESPUI/keywords.txt +++ /dev/null @@ -1,52 +0,0 @@ -####################################### -# Syntax Coloring Map For ESPUI -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -ESPUI KEYWORD1 - - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -label KEYWORD2 -button KEYWORD2 -switcher KEYWORD2 -pad KEYWORD2 -slider KEYWORD2 - -begin KEYWORD2 -beginSPIFFS KEYWORD2 -beginLITTLEFS KEYWORD2 -print KEYWORD2 -updateSwitcher KEYWORD2 -updateSlider KEYWORD2 -captivePortal LITERAL1 - -####################################### -# Instances (KEYWORD2) -####################################### - -####################################### -# Constants (LITERAL1) -####################################### - -B_DOWN LITERAL1 -B_UP LITERAL1 -P_LEFT_DOWN LITERAL1 -P_LEFT_UP LITERAL1 -P_RIGHT_DOWN LITERAL1 -P_RIGHT_UP LITERAL1 -P_FOR_DOWN LITERAL1 -P_FOR_UP LITERAL1 -P_BACK_DOWN LITERAL1 -P_BACK_UP LITERAL1 -P_CENTER_DOWN LITERAL1 -P_CENTER_UP LITERAL1 -S_ACTIVE LITERAL1 -S_INACTIVE LITERAL1 -SL_VALUE LITERAL1 diff --git a/watering/lib/ESPUI/lang/ESPUI.json b/watering/lib/ESPUI/lang/ESPUI.json deleted file mode 100644 index 4b3b853..0000000 --- a/watering/lib/ESPUI/lang/ESPUI.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "langs": { - "en-GB": { - "keys": { - "LANG_SUBCATERGORY_ESPUI": "User Interface", - "LANG_ESPUI_ESPUI_TITLE": "Title", - "LANG_ESPUI_ESPUI_HOTSPOT": "Enable Wifi Hotspot Code", - "LANG_ESPUI_ESPUI_TOOLTIP": "Creates a webinterface on the ESP32/ESP8266", - "LANG_ESPUI_BUTTON_BUTTON": "UI Button", - "LANG_ESPUI_NAME": "name", - "LANG_ESPUI_COLOR": "Color", - "LANG_ESPUI_TEXT": "Text", - "LANG_ESPUI_BUTTON_TOOLTIP": "A web interface button", - "LANG_ESPUI_LABEL_LABEL": "UI Label", - "LANG_ESPUI_LABEL": "Label", - "LANG_ESPUI_LABEL_TOOLTIP": "A web interface label you can update from your code", - "LANG_ESPUI_STATE": "State", - "LANG_ESPUI_SWITCH_SWITCH": "UI Switch", - "LANG_ESPUI_PAD_PAD": "UI Pad", - "LANG_ESPUI_PAD_CENTER": "Center button?" - } - }, - "zh-CN": { - "keys": { - "LANG_SUBCATERGORY_ESPUI": "用户接口", - "LANG_ESPUI_ESPUI_TITLE": "标题", - "LANG_ESPUI_ESPUI_HOTSPOT": "启用无线热点代码", - "LANG_ESPUI_ESPUI_TOOLTIP": "在ESP32/ESP8266创建一网络接口", - "LANG_ESPUI_BUTTON_BUTTON": "UI 按钮", - "LANG_ESPUI_NAME": "名称", - "LANG_ESPUI_COLOR": "颜色", - "LANG_ESPUI_TEXT": "文本", - "LANG_ESPUI_BUTTON_TOOLTIP": "一个网页接口的按钮", - "LANG_ESPUI_LABEL_LABEL": "UI 标签", - "LANG_ESPUI_LABEL": "标签", - "LANG_ESPUI_LABEL_TOOLTIP": "一个网页接口的标签,你可通过修改代码去更新它", - "LANG_ESPUI_STATE": "状态", - "LANG_ESPUI_SWITCH_SWITCH": "UI 开关", - "LANG_ESPUI_PAD_PAD": "UI 面板", - "LANG_ESPUI_PAD_CENTER": "中间按钮?" - }, - "tr-TR": { - "keys": { - "LANG_SUBCATERGORY_ESPUI": "Kullanıcı Arayüzü", - "LANG_ESPUI_ESPUI_TITLE": "Başlık", - "LANG_ESPUI_ESPUI_HOTSPOT": "Wifi Erişim Noktası Kodunu Etkinleştir", - "LANG_ESPUI_ESPUI_TOOLTIP": "ESP32/ESP8266'da bir web arayüzü oluşturur", - "LANG_ESPUI_BUTTON_BUTTON": "Kullanıcı Arayüzü Düğmesi", - "LANG_ESPUI_NAME": "ad", - "LANG_ESPUI_COLOR": "Renk", - "LANG_ESPUI_TEXT": "Metin", - "LANG_ESPUI_BUTTON_TOOLTIP": "Bir web arayüzü düğmesi", - "LANG_ESPUI_LABEL_LABEL": "Kullanıcı Arayüzü Etiketi", - "LANG_ESPUI_LABEL": "Etiket", - "LANG_ESPUI_LABEL_TOOLTIP": "Kodunuzdan güncelleyebileceğiniz bir web arayüzü etiketi", - "LANG_ESPUI_STATE": "Durum", - "LANG_ESPUI_SWITCH_SWITCH": "Kullanıcı Arayüzü Anahtarı", - "LANG_ESPUI_PAD_PAD": "UI Pad", - "LANG_ESPUI_PAD_CENTER": "Orta düğme?" - } - } - } -} diff --git a/watering/lib/ESPUI/library.json b/watering/lib/ESPUI/library.json deleted file mode 100644 index 8b3827a..0000000 --- a/watering/lib/ESPUI/library.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "ESPUI", - "keywords": "espressif web interface iot easy ui", - "description": "ESP32 and ESP8266 Web Interface Library", - "repository": { - "type": "git", - "url": "https://github.com/s00500/ESPUI.git" - }, - "authors": [ - { - "name": "Lukas Bachschwell", - "email": "lukas@lbsfilm.at", - "url": "https://lbsfilm.at", - "maintainer": true - } - ], - "dependencies": [ - { - "name": "ESP Async WebServer", - "authors": "Hristo Gochkov", - "frameworks": "arduino" - }, - { - "name": "ArduinoJson", - "authors": "Benoit Blanchon", - "frameworks": "arduino" - } - ], - "version": "2.2.4", - "frameworks": "arduino", - "platforms": "*" -} diff --git a/watering/lib/ESPUI/library.properties b/watering/lib/ESPUI/library.properties deleted file mode 100644 index 92b17b1..0000000 --- a/watering/lib/ESPUI/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=ESPUI -version=2.2.4 -author=Lukas Bachschwell -maintainer=Lukas Bachschwell -sentence=ESP32 and ESP8266 Web Interface Library -paragraph=A simple library that implements a web graphical user interface for ESP32 and ESP8266. It is simple to use and works side by side with your sketch. -category=Communication -url=https://github.com/s00500/ESPUI -architectures=* -depends=ArduinoJson diff --git a/watering/lib/ESPUI/pio_examples/gui/.gitignore b/watering/lib/ESPUI/pio_examples/gui/.gitignore deleted file mode 100644 index 03f4a3c..0000000 --- a/watering/lib/ESPUI/pio_examples/gui/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.pio diff --git a/watering/lib/ESPUI/pio_examples/gui/platformio.ini b/watering/lib/ESPUI/pio_examples/gui/platformio.ini deleted file mode 100644 index 5c8dc03..0000000 --- a/watering/lib/ESPUI/pio_examples/gui/platformio.ini +++ /dev/null @@ -1,53 +0,0 @@ -; PlatformIO Project Configuration File -; -; Build options: build flags, source filter -; Upload options: custom upload port, speed and extra flags -; Library options: dependencies, extra library storages -; Advanced options: extra scripting -; -; Please visit documentation for the other options and examples -; https://docs.platformio.org/page/projectconf.html - -[platformio] -src_dir = ./src -data_dir = ../../data - -[env] -framework = arduino -board_build.filesystem = littlefs -lib_extra_dirs = ../../ -lib_deps = -; bblanchon/ArduinoJson @ ^6.18.5 - bblanchon/ArduinoJson @ ^7.0.4 - https://github.com/bmedici/ESPAsyncWebServer ; Use a fork of the library that has a bugfix for the compile.... https://github.com/esphome/ESPAsyncWebServer/pull/17 - -lib_ignore = - ESP Async WebServer ; force the use of the esphome version - AsyncTCP ; force the use of the esphome version - LittleFS_esp32 ; force the use of the ESP32 built into the core version - -; Additional scripts: Usage: see https://github.com/s00500/ESPUI/issues/144#issuecomment-1005135077 -;extra_scripts = -; LittleFSBuilder.py - -[env:esp8266] -platform = espressif8266 -board = nodemcuv2 -upload_port = COM8 -monitor_port = COM8 -monitor_speed = 115200 - -[env:esp32] -platform = espressif32 -board = esp32dev -monitor_filters = esp32_exception_decoder -board_build.flash_mode = dout -build_flags = -; -D DEBUG_ESPUI - -lib_deps = - ${env.lib_deps} - me-no-dev/AsyncTCP -upload_port = COM6 -monitor_port = COM6 -monitor_speed = 115200 diff --git a/watering/lib/ESPUI/pio_examples/gui/src/gui.ino b/watering/lib/ESPUI/pio_examples/gui/src/gui.ino deleted file mode 100644 index c479db6..0000000 --- a/watering/lib/ESPUI/pio_examples/gui/src/gui.ino +++ /dev/null @@ -1,328 +0,0 @@ -#include -#include - -const byte DNS_PORT = 53; -IPAddress apIP(192, 168, 4, 1); -DNSServer dnsServer; - -#if defined(ESP32) -#include -#else -#include -#endif - -const char* ssid = "YourNetworkName"; -const char* password = "YourNetworkPassphrase"; - -const char* hostname = "espui"; - -String DisplayTestFileName = "/FileName.txt"; -int fileDisplayId = Control::noParent; - -int statusLabelId = Control::noParent; - -#ifdef TEST_GRAPH -int graphId = Control::noParent; -#endif // def TEST_GRAPH -int millisLabelId = Control::noParent; -int testSwitchId = Control::noParent; - -char HugeText[1025]; - -void numberCall(Control* sender, int type) -{ - Serial.println(sender->value); -} - -void textCall(Control* sender, int type) -{ - Serial.print("Text: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); -} - -void slider(Control* sender, int type) -{ - Serial.print("Slider: ID: "); - Serial.print(sender->id); - Serial.print(", Value: "); - Serial.println(sender->value); - // Like all Control Values in ESPUI slider values are Strings. To use them as int simply do this: - int sliderValueWithOffset = sender->value.toInt() + 100; - Serial.print("SliderValue with offset"); - Serial.println(sliderValueWithOffset); -} - -void buttonCallback(Control* sender, int type) -{ - switch (type) - { - case B_DOWN: - Serial.println("Button DOWN"); - break; - - case B_UP: - Serial.println("Button UP"); - break; - } -} - -void buttonExample(Control* sender, int type, void* param) -{ - Serial.println(String("param: ") + String(long(param))); - switch (type) - { - case B_DOWN: - Serial.println("Status: Start"); - ESPUI.print(statusLabelId, "Start"); - break; - - case B_UP: - Serial.println("Status: Stop"); - ESPUI.print(statusLabelId, "Stop"); - break; - } -} -void padExample(Control* sender, int value) -{ - switch (value) - { - case P_LEFT_DOWN: - Serial.print("left down"); - break; - - case P_LEFT_UP: - Serial.print("left up"); - break; - - case P_RIGHT_DOWN: - Serial.print("right down"); - break; - - case P_RIGHT_UP: - Serial.print("right up"); - break; - - case P_FOR_DOWN: - Serial.print("for down"); - break; - - case P_FOR_UP: - Serial.print("for up"); - break; - - case P_BACK_DOWN: - Serial.print("back down"); - break; - - case P_BACK_UP: - Serial.print("back up"); - break; - - case P_CENTER_DOWN: - Serial.print("center down"); - break; - - case P_CENTER_UP: - Serial.print("center up"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void switchExample(Control* sender, int value) -{ - switch (value) - { - case S_ACTIVE: - Serial.print("Active:"); - break; - - case S_INACTIVE: - Serial.print("Inactive"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void otherSwitchExample(Control* sender, int value) -{ - switch (value) - { - case S_ACTIVE: - Serial.print("Active:"); - break; - - case S_INACTIVE: - Serial.print("Inactive"); - break; - } - - Serial.print(" "); - Serial.println(sender->id); -} - -void setup(void) -{ - ESPUI.setVerbosity(Verbosity::VerboseJSON); - Serial.begin(115200); - - memset(HugeText, 0x0, sizeof(HugeText)); - memset(HugeText, 'a', sizeof(HugeText)-1); - -#if defined(ESP32) - WiFi.setHostname(hostname); -#else - WiFi.hostname(hostname); -#endif - - // try to connect to existing network - WiFi.begin(ssid, password); - Serial.print("\n\nTry to connect to existing network"); - - { - uint8_t timeout = 10; - - // Wait for connection, 5s timeout - do - { - delay(500); - Serial.print("."); - timeout--; - } while (timeout && WiFi.status() != WL_CONNECTED); - - // not connected -> create hotspot - if (WiFi.status() != WL_CONNECTED) - { - Serial.print("\n\nCreating hotspot"); - - WiFi.mode(WIFI_AP); - delay(100); - WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); -#if defined(ESP32) - uint32_t chipid = 0; - for (int i = 0; i < 17; i = i + 8) - { - chipid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i; - } -#else - uint32_t chipid = ESP.getChipId(); -#endif - - char ap_ssid[25]; - snprintf(ap_ssid, 26, "ESPUI-%08X", chipid); - WiFi.softAP(ap_ssid); - - timeout = 5; - - do - { - delay(500); - Serial.print("."); - timeout--; - } while (timeout); - } - } - - dnsServer.start(DNS_PORT, "*", apIP); - - Serial.println("\n\nWiFi parameters:"); - Serial.print("Mode: "); - Serial.println(WiFi.getMode() == WIFI_AP ? "Station" : "Client"); - Serial.print("IP address: "); - Serial.println(WiFi.getMode() == WIFI_AP ? WiFi.softAPIP() : WiFi.localIP()); - - statusLabelId = ESPUI.label("Status:", ControlColor::Turquoise, "Stop"); - millisLabelId = ESPUI.label("Millis:", ControlColor::Emerald, "0"); - ESPUI.button("Push Button", &buttonCallback, ControlColor::Peterriver, "Press"); - ESPUI.button("Other Button", &buttonExample, ControlColor::Wetasphalt, "Press", (void*)19); - ESPUI.padWithCenter("Pad with center", &padExample, ControlColor::Sunflower); - ESPUI.pad("Pad without center", &padExample, ControlColor::Carrot); - testSwitchId = ESPUI.switcher("Switch one", &switchExample, ControlColor::Alizarin, false); - ESPUI.switcher("Switch two", &otherSwitchExample, ControlColor::None, true); - ESPUI.slider("Slider one", &slider, ControlColor::Alizarin, 30, 0, 30); - ESPUI.slider("Slider two", &slider, ControlColor::None, 100); - ESPUI.text("Text Test:", &textCall, ControlColor::Alizarin, "a Text Field"); - - ESPUI.text("Huge Text Test:", &textCall, ControlColor::Alizarin, HugeText); - - ESPUI.number("Numbertest", &numberCall, ControlColor::Alizarin, 5, 0, 10); - - fileDisplayId = ESPUI.fileDisplay("Filetest", ControlColor::Turquoise, DisplayTestFileName); - -#ifdef TEST_GRAPH - graphId = ESPUI.graph("Graph Test", ControlColor::Wetasphalt); -#endif // def TEST_GRAPH - - /* - * .begin loads and serves all files from PROGMEM directly. - * If you want to serve the files from LITTLEFS use ESPUI.beginLITTLEFS - * (.prepareFileSystem has to be run in an empty sketch before) - */ - - // Enable this option if you want sliders to be continuous (update during move) and not discrete (update on stop) - // ESPUI.sliderContinuous = true; - - /* - * Optionally you can use HTTP BasicAuth. Keep in mind that this is NOT a - * SECURE way of limiting access. - * Anyone who is able to sniff traffic will be able to intercept your password - * since it is transmitted in cleartext. Just add a string as username and - * password, for example begin("ESPUI Control", "username", "password") - */ - ESPUI.sliderContinuous = true; - - ESPUI.prepareFileSystem(); - - ESPUI.beginLITTLEFS("ESPUI Control"); - - // these files are used by browsers to auto config a connection. - ESPUI.writeFile("/wpad.dat", " "); - ESPUI.writeFile("/connecttest.txt", " "); - - // create a text file - ESPUI.writeFile("/DisplayFile.txt", "Test Line\n"); -} - -void loop(void) -{ - dnsServer.processNextRequest(); - - static long oldTime = 0; - static bool testSwitchState = false; - delay(10); - - if (millis() - oldTime > 5000) - { - ESPUI.print(millisLabelId, String(millis())); - -#ifdef TEST_GRAPH - ESPUI.addGraphPoint(graphId, random(1, 50)); -#endif // def TEST_GRAPH - - testSwitchState = !testSwitchState; - ESPUI.updateSwitcher(testSwitchId, testSwitchState); - - // update the file Display file. - File testFile = ESPUI.EspuiLittleFS.open(String("/") + DisplayTestFileName, "a"); - uint32_t filesize = testFile.size(); - - String TestLine = String("Current Time = ") + String(millis()) + "\n"; - if(filesize < 1000) - { - testFile.write((const uint8_t*)TestLine.c_str(), TestLine.length()); - ESPUI.updateControl(fileDisplayId); - - TestLine += String("filesize: ") + String(filesize); - // Serial.println(TestLine); - } - testFile.close(); - - oldTime = millis(); - } -} diff --git a/watering/lib/ESPUI/src/ESPUI.cpp b/watering/lib/ESPUI/src/ESPUI.cpp deleted file mode 100644 index 68b1fef..0000000 --- a/watering/lib/ESPUI/src/ESPUI.cpp +++ /dev/null @@ -1,1290 +0,0 @@ -#include "ESPUI.h" - -#include - -#include - -#include "dataControlsJS.h" -#include "dataGraphJS.h" -#include "dataIndexHTML.h" -#include "dataNormalizeCSS.h" -#include "dataSliderJS.h" -#include "dataStyleCSS.h" -#include "dataTabbedcontentJS.h" -#include "dataZeptoJS.h" - -#if ESP8266 -#include -#endif - -static String heapInfo(const __FlashStringHelper* mode) -{ - String result; -#if ESP8266 - - uint32_t hfree; - uint16_t hmax; - uint8_t hfrag; - result.reserve(128); - -#ifdef UMM_HEAP_IRAM - // here esp8266 is configurerd to use an extra 16KB (i)ram - { - HeapSelectIram useInstructionRamHere; - ESP.getHeapStats(&hfree, &hmax, &hfrag); - } - result += F("IRAM: free: "); - result += hfree; - result += F(" max: "); - result += hmax; - result += F(" frag: "); - result += hfrag; - result += "%\n"; -#endif // !UMM_HEAP_IRAM - { - HeapSelectDram useRegularRamHere; - ESP.getHeapStats(&hfree, &hmax, &hfrag); - } - result += F("DRAM: free: "); - result += hfree; - result += F(" max: "); - result += hmax; - result += F(" frag: "); - result += hfrag; - result += "%\n"; - -#else // !ESP8266 - - result += ESP.getFreeHeap(); - result += ' '; - -#endif // !ESP8266 - - result += mode; - - return result; -} - -// ################# LITTLEFS functions -#if defined(ESP32) -void listDir(const char* dirname, uint8_t levels) -{ -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.printf_P(PSTR("Listing directory: %s\n"), dirname); - } -#endif - - File root = ESPUI.EspuiLittleFS.open(dirname); - if (!root) - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("Failed to open directory")); - } -#endif - - return; - } - - if (!root.isDirectory()) - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("Not a directory")); - } -#endif - - return; - } - - File file = root.openNextFile(); - - while (file) - { - if (file.isDirectory()) - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.print(F(" DIR : ")); - Serial.println(file.name()); - } -#endif - - if (levels) - { -#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4 - listDir(file.path(), levels - 1); -#else - listDir(file.name(), levels - 1); -#endif - } - } - else - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.print(F(" FILE: ")); - Serial.print(file.name()); - Serial.print(F(" SIZE: ")); - Serial.println(file.size()); - } -#endif - } - - file = root.openNextFile(); - } -} -#else - -void listDir(const char* dirname, uint8_t levels) -{ -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.printf_P(PSTR("Listing directory: %s\n"), dirname); - } -#endif - - Dir dir = ESPUI.EspuiLittleFS.openDir(dirname); - - while (dir.next()) - { - if (dir.isDirectory()) - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.print(F(" DIR : ")); - Serial.println(dir.fileName()); - } -#endif - if (levels) - { - File file = dir.openFile("r"); - listDir(file.fullName(), levels - 1); - file.close(); - } - } - else - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.print(F(" FILE: ")); - Serial.print(dir.fileName()); - Serial.print(F(" SIZE: ")); - Serial.println(dir.fileSize()); - } -#endif - } - } -} - -#endif - -void ESPUIClass::list() -{ - if (!EspuiLittleFS.begin()) - { - Serial.println(F("Espui LittleFS Mount Failed")); - return; - } - - listDir("/", 1); - -#if defined(ESP32) - Serial.print(F("Total KB: ")); - Serial.println(EspuiLittleFS.totalBytes() / 1024); - Serial.print(F("Used KB: ")); - Serial.println(EspuiLittleFS.usedBytes() / 1024); -#else - FSInfo fs_info; - EspuiLittleFS.info(fs_info); - - Serial.print(F("Total KB: ")); - Serial.println(fs_info.totalBytes / 1024); - Serial.print(F("Used KB: ")); - Serial.println(fs_info.usedBytes / 1024); -#endif // !defined(ESP32) -} - -void deleteFile(const char* path) -{ - bool exists = ESPUI.EspuiLittleFS.exists(path); - if (!exists) - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.printf_P(PSTR("File: %s does not exist, not deleting\n"), path); - } -#endif - - return; - } - -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.printf_P(PSTR("Deleting file: %s\n"), path); - } -#endif - - bool didRemove = ESPUI.EspuiLittleFS.remove(path); - if (didRemove) - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("File deleted")); - } -#endif - } - else - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("Delete failed")); - } -#endif - } -} - -void ESPUIClass::writeFile(const char* path, const char* data) -{ -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.printf_P(PSTR("Writing file: %s\n"), path); - } -#endif - - File file = EspuiLittleFS.open(path, FILE_WRITING); - if (!file) - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("Failed to open file for writing")); - } -#endif - - return; - } - -#if defined(ESP32) - if (file.print(data)) -#else - if (file.print(FPSTR(data))) -#endif // !defined(ESP32) - - { -#if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("File written")); - } - } - else - { - if (ESPUI.verbosity) - { - Serial.println(F("Write failed")); - } -#endif - } - file.close(); -} - -// end LITTLEFS functions - -void ESPUIClass::prepareFileSystem(bool format) -{ - // this function should only be used once - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("About to prepare filesystem...")); - } -#endif - -#if defined(ESP32) - if (!EspuiLittleFS.begin(false)) // Test for an already formatted LittleFS by a mount failure - { - if (!EspuiLittleFS.begin(true)) // Attempt to format LittleFS - { -#else - if (!EspuiLittleFS.begin()) // Test for an already formatted LittleFS by a mount failure - { - if (EspuiLittleFS.format()) // Attempt to format LittleFS - { -#endif // !defined(ESP32) - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("LittleFS Format Failed")); - } -#endif - return; - } - } - else if (format) - { - EspuiLittleFS.format(); - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("LittleFS Formatted")); - } -#endif - } - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - listDir("/", 1); - Serial.println(F("LittleFS Mount ESP32 Done")); - } -#endif - - deleteFile("/index.htm"); - - deleteFile("/css/style.css"); - deleteFile("/css/normalize.css"); - - deleteFile("/js/zepto.min.js"); - deleteFile("/js/controls.js"); - deleteFile("/js/slider.js"); - deleteFile("/js/graph.js"); - deleteFile("/js/tabbedcontent.js"); - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("Cleanup done")); - } -#endif - - // Now write -#ifdef ESP32 - writeFile("/index.htm", HTML_INDEX); - EspuiLittleFS.mkdir("/css"); - writeFile("/css/style.css", CSS_STYLE); - writeFile("/css/normalize.css", CSS_NORMALIZE); - EspuiLittleFS.mkdir("/js"); - writeFile("/js/zepto.min.js", JS_ZEPTO); - writeFile("/js/controls.js", JS_CONTROLS); - writeFile("/js/slider.js", JS_SLIDER); - writeFile("/js/graph.js", JS_GRAPH); - - writeFile("/js/tabbedcontent.js", JS_TABBEDCONTENT); - -#else - writeFile("/index.htm", HTML_INDEX); - - writeFile("/css/style.css", CSS_STYLE); - writeFile("/css/normalize.css", CSS_NORMALIZE); - - writeFile("/js/zepto.min.js", JS_ZEPTO); - writeFile("/js/controls.js", JS_CONTROLS); - writeFile("/js/slider.js", JS_SLIDER); - writeFile("/js/graph.js", JS_GRAPH); - - writeFile("/js/tabbedcontent.js", JS_TABBEDCONTENT); -#endif - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("Done Initializing filesystem :-)")); - } -#endif - -#if defined(ESP32) - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - listDir("/", 1); - } -#endif - -#endif - - EspuiLittleFS.end(); -} - -// Handle Websockets Communication -void ESPUIClass::onWsEvent( - AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) -{ - // Serial.println(String("ESPUIClass::OnWsEvent: type: ") + String(type)); - RemoveToBeDeletedControls(); - - if (WS_EVT_DISCONNECT == type) - { -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("WS_EVT_DISCONNECT")); - } -#endif - - if (MapOfClients.end() != MapOfClients.find(client->id())) - { - // Serial.println("Delete client."); - delete MapOfClients[client->id()]; - MapOfClients.erase(client->id()); - } - } - else - { - if(type == WS_EVT_CONNECT) - { - ws->cleanupClients(); - } - - if (MapOfClients.end() == MapOfClients.find(client->id())) - { - // Serial.println("ESPUIClass::OnWsEvent:Create new client."); - MapOfClients[client->id()] = new ESPUIclient(client); - } - - if(MapOfClients[client->id()]->onWsEvent(type, arg, data, len)) - { - // Serial.println("ESPUIClass::OnWsEvent:notify the clients that they need to be updated."); - NotifyClients(ESPUIclient::UpdateNeeded); - } - } - - return; -} - -uint16_t ESPUIClass::addControl(ControlType type, const char* label) -{ - return addControl(type, label, String("")); -} - -uint16_t ESPUIClass::addControl(ControlType type, const char* label, const String& value) -{ - return addControl(type, label, value, ControlColor::Turquoise); -} - -uint16_t ESPUIClass::addControl(ControlType type, const char* label, const String& value, ControlColor color) -{ - return addControl(type, label, value, color, Control::noParent); -} - -uint16_t ESPUIClass::addControl( - ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl) -{ - return addControl(type, label, value, color, parentControl, new Control(type, label, nullptr, value, color, true, parentControl)); -} - -uint16_t ESPUIClass::addControl(ControlType type, const char* label, const String& value, ControlColor color, - uint16_t parentControl, std::function callback) -{ - uint16_t id = addControl(type, label, value, color, parentControl); - // set the original style callback - getControl(id)->callback = callback; - return id; -} - -uint16_t ESPUIClass::addControl( - ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl, Control* control) -{ -#ifdef ESP32 - xSemaphoreTake(ControlsSemaphore, portMAX_DELAY); -#endif // def ESP32 - - if (controls == nullptr) - { - controls = control; - } - else - { - Control* iterator = controls; - - while (iterator->next != nullptr) - { - iterator = iterator->next; - } - - iterator->next = control; - } - - controlCount++; - -#ifdef ESP32 - xSemaphoreGive(ControlsSemaphore); -#endif // def ESP32 - - NotifyClients(ClientUpdateType_t::RebuildNeeded); - - return control->id; -} - -bool ESPUIClass::removeControl(uint16_t id, bool force_rebuild_ui) -{ - bool Response = false; - - Control* control = getControl(id); - if (control) - { - Response = true; - control->DeleteControl(); - controlCount--; - - if (force_rebuild_ui) - { - jsonReload(); - } - else - { - NotifyClients(ClientUpdateType_t::RebuildNeeded); - } - } -#ifdef DEBUG_ESPUI - else - { - // Serial.println(String("Could not Remove Control ") + String(id)); - } -#endif // def DEBUG_ESPUI - - return Response; -} - -void ESPUIClass::RemoveToBeDeletedControls() -{ -#ifdef ESP32 - xSemaphoreTake(ControlsSemaphore, portMAX_DELAY); -#endif // def ESP32 - - Control* PreviousControl = nullptr; - Control* CurrentControl = controls; - - while (nullptr != CurrentControl) - { - Control* NextControl = CurrentControl->next; - if (CurrentControl->ToBeDeleted()) - { - if (CurrentControl == controls) - { - // this is the root control - controls = NextControl; - } - else - { - PreviousControl->next = NextControl; - } - delete CurrentControl; - CurrentControl = NextControl; - } - else - { - PreviousControl = CurrentControl; - CurrentControl = NextControl; - } - } -#ifdef ESP32 - xSemaphoreGive(ControlsSemaphore); -#endif // def ESP32 -} - -uint16_t ESPUIClass::label(const char* label, ControlColor color, const String& value) -{ - return addControl(ControlType::Label, label, value, color); -} - -uint16_t ESPUIClass::graph(const char* label, ControlColor color) -{ - return addControl(ControlType::Graph, label, "", color); -} - -uint16_t ESPUIClass::slider( - const char* label, std::function callback, ControlColor color, int value, int min, int max) -{ - uint16_t sliderId - = addControl(ControlType::Slider, label, String(value), color, Control::noParent, callback); - addControl(ControlType::Min, label, String(min), ControlColor::None, sliderId); - addControl(ControlType::Max, label, String(max), ControlColor::None, sliderId); - return sliderId; -} - -uint16_t ESPUIClass::button(const char* label, std::function callback, ControlColor color, const String& value) -{ - return addControl(ControlType::Button, label, value, color, Control::noParent, callback); -} - -uint16_t ESPUIClass::switcher(const char* label, std::function callback, ControlColor color, bool startState) -{ - return addControl(ControlType::Switcher, label, startState ? "1" : "0", color, Control::noParent, callback); -} - -uint16_t ESPUIClass::pad(const char* label, std::function callback, ControlColor color) -{ - return addControl(ControlType::Pad, label, "", color, Control::noParent, callback); -} - -uint16_t ESPUIClass::padWithCenter(const char* label, std::function callback, ControlColor color) -{ - return addControl(ControlType::PadWithCenter, label, "", color, Control::noParent, callback); -} - -uint16_t ESPUIClass::number( - const char* label, std::function callback, ControlColor color, int number, int min, int max) -{ - uint16_t numberId = addControl(ControlType::Number, label, String(number), color, Control::noParent, callback); - addControl(ControlType::Min, label, String(min), ControlColor::None, numberId); - addControl(ControlType::Max, label, String(max), ControlColor::None, numberId); - return numberId; -} - -uint16_t ESPUIClass::gauge(const char* label, ControlColor color, int number, int min, int max) -{ - uint16_t numberId = addControl(ControlType::Gauge, label, String(number), color, Control::noParent); - addControl(ControlType::Min, label, String(min), ControlColor::None, numberId); - addControl(ControlType::Max, label, String(max), ControlColor::None, numberId); - return numberId; -} - -uint16_t ESPUIClass::separator(const char* label) -{ - return addControl(ControlType::Separator, label, "", ControlColor::Alizarin); -} - -uint16_t ESPUIClass::fileDisplay(const char* label, ControlColor color, String filename) -{ - return addControl(ControlType::FileDisplay, label, filename, color, Control::noParent); -} - -uint16_t ESPUIClass::accelerometer(const char* label, std::function callback, ControlColor color) -{ - return addControl(ControlType::Accel, label, "", color, Control::noParent, callback); -} - -uint16_t ESPUIClass::text(const char* label, std::function callback, ControlColor color, const String& value) -{ - return addControl(ControlType::Text, label, value, color, Control::noParent, callback); -} - -Control* ESPUIClass::getControl(uint16_t id) -{ -#ifdef ESP32 - xSemaphoreTake(ControlsSemaphore, portMAX_DELAY); - Control* Response = getControlNoLock(id); - xSemaphoreGive(ControlsSemaphore); - return Response; -#else - return getControlNoLock(id); -#endif // !def ESP32 -} - -// WARNING: Anytime you walk the chain of controllers, the protection semaphore -// MUST be locked. This function assumes that the semaphore is locked -// at the time it is called. Make sure YOU locked it :) -Control* ESPUIClass::getControlNoLock(uint16_t id) -{ - Control* Response = nullptr; - Control* control = controls; - - while (nullptr != control) - { - if (control->id == id) - { - if (!control->ToBeDeleted()) - { - Response = control; - } - break; - } - control = control->next; - } - - return Response; -} - -void ESPUIClass::updateControl(Control* control, int) -{ - if (!control) - { - return; - } - // tell the control it has been updated - control->SetControlChangedId(ESPUI.GetNextControlChangeId()); - NotifyClients(ClientUpdateType_t::UpdateNeeded); -} - -uint32_t ESPUIClass::GetNextControlChangeId() -{ - if(uint32_t(-1) == ControlChangeID) - { - // force a reload which resets the counters - jsonReload(); - } - return ++ControlChangeID; -} - -void ESPUIClass::setPanelStyle(uint16_t id, const String& style, int clientId) -{ - Control* control = getControl(id); - if (control) - { - control->panelStyle = style; - updateControl(control, clientId); - } -} - -void ESPUIClass::setElementStyle(uint16_t id, const String& style, int clientId) -{ - Control* control = getControl(id); - if (control) - { - control->elementStyle = style; - updateControl(control, clientId); - } -} - -void ESPUIClass::setInputType(uint16_t id, const String& type, int clientId) -{ - Control* control = getControl(id); - if (control) - { - control->inputType = type; - updateControl(control, clientId); - } -} - -void ESPUIClass::setPanelWide(uint16_t id, bool wide) -{ - Control* control = getControl(id); - if (control) - { - control->wide = wide; - } -} - -void ESPUIClass::setEnabled(uint16_t id, bool enabled, int clientId) -{ - Control* control = getControl(id); - if (control) - { - // Serial.println(String("CreateAllowed: id: ") + String(clientId) + " State: " + String(enabled)); - control->enabled = enabled; - updateControl(control, clientId); - } -} - -void ESPUIClass::setVertical(uint16_t id, bool vert) -{ - Control* control = getControl(id); - if (control) - { - control->vertical = vert; - } -} - -void ESPUIClass::updateControl(uint16_t id, int clientId) -{ - Control* control = getControl(id); - - if (!control) - { -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.printf_P(PSTR("Error: Update Control: There is no control with ID %d\n"), id); - } -#endif - return; - } - - updateControl(control, clientId); -} - -void ESPUIClass::updateControlValue(Control* control, const String& value, int clientId) -{ - if (!control) - { - return; - } - - control->value = value; - updateControl(control, clientId); -} - -void ESPUIClass::updateControlValue(uint16_t id, const String& value, int clientId) -{ - Control* control = getControl(id); - - if (!control) - { -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.printf_P(PSTR("Error: updateControlValue Control: There is no control with ID %d\n"), id); - } -#endif - return; - } - - updateControlValue(control, value, clientId); -} - -void ESPUIClass::updateControlLabel(uint16_t id, const char* value, int clientId) -{ - updateControlLabel(getControl(id), value, clientId); -} - -void ESPUIClass::updateControlLabel(Control* control, const char* value, int clientId) -{ - if (!control) - { -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.printf_P(PSTR("Error: updateControlLabel Control: There is no control with the requested ID \n")); - } -#endif - return; - } - control->label = value; - updateControl(control, clientId); -} - -void ESPUIClass::updateVisibility(uint16_t id, bool visibility, int clientId) -{ - Control* control = getControl(id); - if (control) - { - control->visible = visibility; - updateControl(control, clientId); - } -} - -void ESPUIClass::print(uint16_t id, const String& value) -{ - updateControlValue(id, value); -} - -void ESPUIClass::updateLabel(uint16_t id, const String& value) -{ - updateControlValue(id, value); -} - -void ESPUIClass::updateButton(uint16_t id, const String& value) -{ - updateControlValue(id, value); -} - -void ESPUIClass::updateSlider(uint16_t id, int nValue, int clientId) -{ - updateControlValue(id, String(nValue), clientId); -} - -void ESPUIClass::updateSwitcher(uint16_t id, bool nValue, int clientId) -{ - updateControlValue(id, String(nValue ? "1" : "0"), clientId); -} - -void ESPUIClass::updateNumber(uint16_t id, int number, int clientId) -{ - updateControlValue(id, String(number), clientId); -} - -void ESPUIClass::updateText(uint16_t id, const String& text, int clientId) -{ - updateControlValue(id, text, clientId); -} - -void ESPUIClass::updateSelect(uint16_t id, const String& text, int clientId) -{ - updateControlValue(id, text, clientId); -} - -void ESPUIClass::updateGauge(uint16_t id, int number, int clientId) -{ - updateControlValue(id, String(number), clientId); -} - -void ESPUIClass::updateTime(uint16_t id, int clientId) -{ - updateControl(id, clientId); -} - -void ESPUIClass::clearGraph(uint16_t id, int clientId) -{ - do // once - { - Control* control = getControl(id); - if (!control) - { - break; - } - - AllocateJsonDocument(document, jsonUpdateDocumentSize); - JsonObject root = document.to(); - - root[F("type")] = (int)ControlType::Graph + UpdateOffset; - root[F("value")] = 0; - root[F("id")] = control->id; - - SendJsonDocToWebSocket(document, clientId); - - } while (false); -} - -void ESPUIClass::addGraphPoint(uint16_t id, int nValue, int clientId) -{ - do // once - { - Control* control = getControl(id); - if (!control) - { - break; - } - - AllocateJsonDocument(document, jsonUpdateDocumentSize); - JsonObject root = document.to(); - - root[F("type")] = (int)ControlType::GraphPoint; - root[F("value")] = nValue; - root[F("id")] = control->id; - - SendJsonDocToWebSocket(document, clientId); - - } while (false); -} - -bool ESPUIClass::SendJsonDocToWebSocket(ArduinoJson::JsonDocument& document, uint16_t clientId) -{ - bool Response = false; - - if (0 > clientId) - { - if (MapOfClients.end() != MapOfClients.find(clientId)) - { - Response = MapOfClients[clientId]->SendJsonDocToWebSocket(document); - } - } - else - { - for (auto CurrentClient : MapOfClients) - { - Response |= CurrentClient.second->SendJsonDocToWebSocket(document); - } - } - - return Response; -} - -void ESPUIClass::jsonDom(uint16_t, AsyncWebSocketClient*, bool) -{ - NotifyClients(ClientUpdateType_t::RebuildNeeded); -} - -// Tell all of the clients that they need to ask for an upload of the control data. -void ESPUIClass::NotifyClients(ClientUpdateType_t newState) -{ - for (auto& CurrentClient : MapOfClients) - { - CurrentClient.second->NotifyClient(newState); - } -} - -void ESPUIClass::jsonReload() -{ - for (auto& CurrentClient : MapOfClients) - { - // Serial.println("Requesting Reload"); - CurrentClient.second->NotifyClient(ClientUpdateType_t::ReloadNeeded); - } -} - -void ESPUIClass::beginSPIFFS(const char* _title, const char* username, const char* password, uint16_t port) -{ - // Backwards compatibility wrapper - beginLITTLEFS(_title, username, password, port); -} - -void ESPUIClass::beginLITTLEFS(const char* _title, const char* username, const char* password, uint16_t port) -{ - ui_title = _title; - basicAuthUsername = username; - basicAuthPassword = password; - - if (username == nullptr && password == nullptr) - { - basicAuth = false; - } - else - { - basicAuth = true; - } - - server = new AsyncWebServer(port); - ws = new AsyncWebSocket("/ws"); - - bool fsBegin = EspuiLittleFS.begin(); - if (!fsBegin) - { -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("LITTLEFS Mount Failed, PLEASE CHECK THE README ON HOW TO " - "PREPARE YOUR ESP!!!!!!!")); - } -#endif - - return; - } - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - listDir("/", 1); - } -#endif - - bool indexExists = EspuiLittleFS.exists("/index.htm"); - if (!indexExists) - { -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("Please read the README!!!!!!!, Make sure to " - "prepareFileSystem() once in an empty sketch")); - } -#endif - - return; - } - - ws->onEvent([](AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, - size_t len) { ESPUI.onWsEvent(server, client, type, arg, data, len); }); - server->addHandler(ws); - - if (basicAuth) - { - if (WS_AUTHENTICATION) - { - ws->setAuthentication(basicAuthUsername, basicAuthPassword); - } - server->serveStatic("/", EspuiLittleFS, "/").setDefaultFile("index.htm").setAuthentication(username, password); - } - else - { - server->serveStatic("/", EspuiLittleFS, "/").setDefaultFile("index.htm"); - } - - // Heap for general Servertest - server->on("/heap", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - request->send(200, "text/plain", heapInfo(F("In LITTLEFS mode"))); - }); - - server->onNotFound([this](AsyncWebServerRequest* request) { - if (captivePortal) - { - request->redirect("/"); - } - else - { - request->send(404); - } - }); - - server->begin(); - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("UI Initialized")); - } -#endif -} - -void ESPUIClass::begin(const char* _title, const char* username, const char* password, uint16_t port) -{ - basicAuthUsername = username; - basicAuthPassword = password; - - if (username != nullptr && password != nullptr) - { - basicAuth = true; - } - else - { - basicAuth = false; - } - - ui_title = _title; - - server = new AsyncWebServer(port); - ws = new AsyncWebSocket("/ws"); - - ws->onEvent([](AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, - size_t len) { ESPUI.onWsEvent(server, client, type, arg, data, len); }); - - server->addHandler(ws); - - if (basicAuth && WS_AUTHENTICATION) - ws->setAuthentication(username, password); - - server->on("/", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - AsyncWebServerResponse* response = request->beginResponse_P(200, "text/html", HTML_INDEX); - request->send(response); - }); - - // Javascript files - - server->on("/js/zepto.min.js", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - AsyncWebServerResponse* response - = request->beginResponse_P(200, "application/javascript", JS_ZEPTO_GZIP, sizeof(JS_ZEPTO_GZIP)); - response->addHeader("Content-Encoding", "gzip"); - request->send(response); - }); - - server->on("/js/controls.js", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - AsyncWebServerResponse* response - = request->beginResponse_P(200, "application/javascript", JS_CONTROLS_GZIP, sizeof(JS_CONTROLS_GZIP)); - response->addHeader("Content-Encoding", "gzip"); - request->send(response); - }); - - server->on("/js/slider.js", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - AsyncWebServerResponse* response - = request->beginResponse_P(200, "application/javascript", JS_SLIDER_GZIP, sizeof(JS_SLIDER_GZIP)); - response->addHeader("Content-Encoding", "gzip"); - request->send(response); - }); - - server->on("/js/graph.js", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - AsyncWebServerResponse* response - = request->beginResponse_P(200, "application/javascript", JS_GRAPH_GZIP, sizeof(JS_GRAPH_GZIP)); - response->addHeader("Content-Encoding", "gzip"); - request->send(response); - }); - - server->on("/js/tabbedcontent.js", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - AsyncWebServerResponse* response = request->beginResponse_P( - 200, "application/javascript", JS_TABBEDCONTENT_GZIP, sizeof(JS_TABBEDCONTENT_GZIP)); - response->addHeader("Content-Encoding", "gzip"); - request->send(response); - }); - - // Stylesheets - - server->on("/css/style.css", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - AsyncWebServerResponse* response - = request->beginResponse_P(200, "text/css", CSS_STYLE_GZIP, sizeof(CSS_STYLE_GZIP)); - response->addHeader("Content-Encoding", "gzip"); - request->send(response); - }); - - server->on("/css/normalize.css", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - AsyncWebServerResponse* response - = request->beginResponse_P(200, "text/css", CSS_NORMALIZE_GZIP, sizeof(CSS_NORMALIZE_GZIP)); - response->addHeader("Content-Encoding", "gzip"); - request->send(response); - }); - - // Heap for general Servertest - server->on("/heap", HTTP_GET, [](AsyncWebServerRequest* request) { - if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword)) - { - return request->requestAuthentication(); - } - - request->send(200, "text/plain", heapInfo(F("In Memorymode"))); - }); - - server->onNotFound([this](AsyncWebServerRequest* request) { - if (captivePortal) - { - AsyncResponseStream *response = request->beginResponseStream("text/html"); - String responseText; - responseText.reserve(1024); - responseText += F("Captive Portal"); - responseText += ("

    If site does not re-direct click here this link

    "); - responseText += (""); - response->write(responseText.c_str(), responseText.length()); - request->send(response); - } - else - { - request->send(404); - } - yield(); - }); - - server->begin(); - -#if defined(DEBUG_ESPUI) - if (verbosity) - { - Serial.println(F("UI Initialized")); - } -#endif -} - -void ESPUIClass::setVerbosity(Verbosity v) -{ - verbosity = v; -} - -ESPUIClass ESPUI; diff --git a/watering/lib/ESPUI/src/ESPUI.h b/watering/lib/ESPUI/src/ESPUI.h deleted file mode 100644 index 0e7bcc4..0000000 --- a/watering/lib/ESPUI/src/ESPUI.h +++ /dev/null @@ -1,294 +0,0 @@ -#pragma once - -// comment out to turn off debug output -// #define DEBUG_ESPUI true -#define WS_AUTHENTICATION false - -#include - -#include -#if ARDUINOJSON_VERSION_MAJOR > 6 - #define AllocateJsonDocument(name, size) JsonDocument name - #define AllocateJsonArray(doc, name) doc[name].to() - #define AllocateJsonObject(doc) doc.add() - #define AllocateNamedJsonObject(t, s, n) t[n] = s -#else - #define AllocateJsonDocument(name, size) DynamicJsonDocument name(size) - #define AllocateJsonArray(doc, name) doc.createNestedArray(name) - #define AllocateJsonObject(doc) doc.createNestedObject() - #define AllocateNamedJsonObject(t, s, n) t = s.createNestedObject(n) -#endif - -#include -#ifdef ESP32 - #if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4 - #include - #else - #include - #endif -#else - #include -#endif -#include -#include - -#include "ESPUIcontrol.h" -#include "ESPUIclient.h" - -#if defined(ESP32) -#include -#include "WiFi.h" - -#else - -#include -#include -#include -#include -#include - -#endif - -#define FILE_WRITING "w" - -// Message Types (and control types) - -enum MessageTypes : uint8_t -{ - InitialGui = 200, - Reload = 201, - ExtendGUI = 210, - UpdateGui = 220, - ExtendedUpdateGui = 230, -}; - -#define UI_INITIAL_GUI MessageTypes::InitialGui -#define UI_EXTEND_GUI MessageTypes::ExtendGUI -#define UI_RELOAD MessageTypes::Reload - -// Values -#define B_DOWN -1 -#define B_UP 1 - -#define P_LEFT_DOWN -2 -#define P_LEFT_UP 2 -#define P_RIGHT_DOWN -3 -#define P_RIGHT_UP 3 -#define P_FOR_DOWN -4 -#define P_FOR_UP 4 -#define P_BACK_DOWN -5 -#define P_BACK_UP 5 -#define P_CENTER_DOWN -6 -#define P_CENTER_UP 6 - -#define S_ACTIVE -7 -#define S_INACTIVE 7 - -#define SL_VALUE 8 -#define N_VALUE 9 -#define T_VALUE 10 -#define S_VALUE 11 -#define TM_VALUE 12 - -enum Verbosity : uint8_t -{ - Quiet = 0, - Verbose, - VerboseJSON -}; - -class ESPUIClass -{ -public: - ESPUIClass() - { -#ifdef ESP32 - ControlsSemaphore = xSemaphoreCreateMutex(); - xSemaphoreGive(ControlsSemaphore); -#endif // def ESP32 - } - unsigned int jsonUpdateDocumentSize = 2000; -#ifdef ESP8266 - unsigned int jsonInitialDocumentSize = 2000; - unsigned int jsonChunkNumberMax = 5; -#else - unsigned int jsonInitialDocumentSize = 8000; - unsigned int jsonChunkNumberMax = 0; -#endif - bool sliderContinuous = false; - void onWsEvent(AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len); - bool captivePortal = true; - - void setVerbosity(Verbosity verbosity); - void begin(const char* _title, const char* username = nullptr, const char* password = nullptr, - uint16_t port = 80); // Setup server and page in Memorymode - void beginSPIFFS(const char* _title, const char* username = nullptr, const char* password = nullptr, - uint16_t port = 80); // Setup server and page in LITTLEFS mode (DEPRECATED, use beginLITTLEFS) - void beginLITTLEFS(const char* _title, const char* username = nullptr, const char* password = nullptr, - uint16_t port = 80); // Setup server and page in LITTLEFS mode - - void prepareFileSystem(bool format = true); // Initially preps the filesystem and loads a lot of - // stuff into LITTLEFS - void list(); // Lists LITTLEFS directory - void writeFile(const char* path, const char* data); - - uint16_t addControl(ControlType type, const char* label); - uint16_t addControl(ControlType type, const char* label, const String& value); - uint16_t addControl(ControlType type, const char* label, const String& value, ControlColor color); - uint16_t addControl(ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl); - uint16_t addControl(ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl, std::function callback); - - bool removeControl(uint16_t id, bool force_rebuild_ui = false); - - // create Elements - // Create Event Button - uint16_t button(const char* label, std::function callback, ControlColor color, const String& value = ""); - uint16_t switcher(const char* label, std::function callback, ControlColor color, bool startState = false); // Create Toggle Button - uint16_t pad(const char* label, std::function callback, ControlColor color); // Create Pad Control - uint16_t padWithCenter(const char* label, std::function callback, ControlColor color); // Create Pad Control with Centerbutton - uint16_t slider(const char* label, std::function callback, ControlColor color, int value, int min = 0, int max = 100); // Create Slider Control - uint16_t number(const char* label, std::function callback, ControlColor color, int value, int min = 0, int max = 100); // Create a Number Input Control - uint16_t text(const char* label, std::function callback, ControlColor color, const String& value = ""); // Create a Text Input Control - - // Output only - uint16_t label(const char* label, ControlColor color, - const String& value = ""); // Create Label - uint16_t graph(const char* label, ControlColor color); // Create Graph display - uint16_t gauge(const char* label, ControlColor color, int value, int min = 0, - int max = 100); // Create Gauge display - uint16_t separator(const char* label); //Create separator - uint16_t fileDisplay(const char* label, ControlColor color, String filename); - - // Input only - uint16_t accelerometer(const char* label, std::function callback, ControlColor color); - - // Update Elements - - Control* getControl(uint16_t id); - Control* getControlNoLock(uint16_t id); - - // Update Elements - void updateControlValue(uint16_t id, const String& value, int clientId = -1); - void updateControlValue(Control* control, const String& value, int clientId = -1); - - void updateControlLabel(uint16_t control, const char * value, int clientId = -1); - void updateControlLabel(Control* control, const char * value, int clientId = -1); - - void updateControl(uint16_t id, int clientId = -1); - void updateControl(Control* control, int clientId = -1); - - void print(uint16_t id, const String& value); - void updateLabel(uint16_t id, const String& value); - void updateButton(uint16_t id, const String& value); - void updateSwitcher(uint16_t id, bool nValue, int clientId = -1); - void updateSlider(uint16_t id, int nValue, int clientId = -1); - void updateNumber(uint16_t id, int nValue, int clientId = -1); - void updateText(uint16_t id, const String& nValue, int clientId = -1); - void updateSelect(uint16_t id, const String& nValue, int clientId = -1); - void updateGauge(uint16_t id, int number, int clientId); - void updateTime(uint16_t id, int clientId = -1); - - void clearGraph(uint16_t id, int clientId = -1); - void addGraphPoint(uint16_t id, int nValue, int clientId = -1); - - void setPanelStyle(uint16_t id, const String& style, int clientId = -1); - void setElementStyle(uint16_t id, const String& style, int clientId = -1); - void setInputType(uint16_t id, const String& type, int clientId = -1); - - void setPanelWide(uint16_t id, bool wide); - void setVertical(uint16_t id, bool vert = true); - void setEnabled(uint16_t id, bool enabled = true, int clientId = -1); - - void updateVisibility(uint16_t id, bool visibility, int clientId = -1); - - // Variables - const char* ui_title = "ESPUI"; // Store UI Title and Header Name - Control* controls = nullptr; - void jsonReload(); - void jsonDom(uint16_t startidx, AsyncWebSocketClient* client = nullptr, bool Updating = false); - - Verbosity verbosity = Verbosity::Quiet; - uint32_t GetNextControlChangeId(); - // emulate former extended callback API by using an intermediate lambda (no deprecation) - uint16_t addControl(ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl, std::function callback, void* userData) - { - return addControl(type, label, value, color, parentControl, [callback, userData](Control* sender, int type){ callback(sender, type, userData); }); - } - uint16_t button(const char* label, std::function callback, ControlColor color, const String& value, void* userData) - { - return button(label, [callback, userData](Control* sender, int type){ callback(sender, type, userData); }, color, value); - } - uint16_t switcher(const char* label, std::function callback, ControlColor color, bool startState, void* userData) - { - return switcher(label, [callback, userData](Control* sender, int type){ callback(sender, type, userData); }, color, startState); - } - uint16_t pad(const char* label, std::function callback, ControlColor color, void* userData) - { - return pad(label, [callback, userData](Control* sender, int type){ callback(sender, type, userData); }, color); - } - uint16_t padWithCenter(const char* label, std::function callback, ControlColor color, void* userData) - { - return padWithCenter(label, [callback, userData](Control* sender, int type){ callback(sender, type, userData); }, color); - } - uint16_t slider(const char* label, std::function callback, ControlColor color, int value, int min, int max, void* userData) - { - return slider(label, [callback, userData](Control* sender, int type){ callback(sender, type, userData); }, color, value, min, max); - } - uint16_t number(const char* label, std::function callback, ControlColor color, int value, int min, int max, void* userData) - { - return number(label, [callback, userData](Control* sender, int type){ callback(sender, type, userData); }, color, value, min, max); - } - uint16_t text(const char* label, std::function callback, ControlColor color, const String& value, void* userData) - { - return text(label, [callback, userData](Control* sender, int type){ callback(sender, type, userData); } , color, value); - } - uint16_t accelerometer(const char* label, std::function callback, ControlColor color, void* userData) - { - return accelerometer(label, [callback, userData](Control* sender, int type){ callback(sender, type, userData); }, color); - } - - AsyncWebServer* WebServer() {return server;} - AsyncWebSocket* WebSocket() {return ws;} - -#if defined(ESP32) -# if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4 - fs::LittleFSFS & EspuiLittleFS = LittleFS; - #else - fs::LITTLEFSFS & EspuiLittleFS = LITTLEFS; -# endif -#else - fs::FS & EspuiLittleFS = LittleFS; -#endif - -protected: - friend class ESPUIclient; - friend class ESPUIcontrol; - -#ifdef ESP32 - SemaphoreHandle_t ControlsSemaphore = NULL; -#endif // def ESP32 - - void RemoveToBeDeletedControls(); - - AsyncWebServer* server; - AsyncWebSocket* ws; - - const char* basicAuthUsername = nullptr; - const char* basicAuthPassword = nullptr; - bool basicAuth = true; - uint16_t controlCount = 0; - - uint16_t addControl(ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl, Control* control); - -#define ClientUpdateType_t ESPUIclient::ClientUpdateType_t - void NotifyClients(ClientUpdateType_t newState); - void NotifyClient(uint32_t WsClientId, ClientUpdateType_t newState); - - bool SendJsonDocToWebSocket(ArduinoJson::JsonDocument& document, uint16_t clientId); - - std::map MapOfClients; - - uint32_t ControlChangeID = 0; -}; - -extern ESPUIClass ESPUI; diff --git a/watering/lib/ESPUI/src/ESPUIclient.cpp b/watering/lib/ESPUI/src/ESPUIclient.cpp deleted file mode 100644 index ab47d10..0000000 --- a/watering/lib/ESPUI/src/ESPUIclient.cpp +++ /dev/null @@ -1,600 +0,0 @@ -#include "ESPUI.h" -#include "ESPUIclient.h" -#include "ESPUIcontrol.h" - -// JSONSlave: -// helper to process exact JSON serialization size -// it takes ~2ms on esp8266 and avoid large String reallocation which is really worth the cost -class JSONSlave: public Print -{ -public: - size_t write (uint8_t c) override { counter++; return 1; } - size_t write (const uint8_t* buf, size_t count) override { counter += count; return count; } - size_t get_counter () { return counter; } - - static size_t serializedSize (JsonDocument& doc) - { - JSONSlave counter; - serializeJson(doc, counter); - return counter.get_counter(); - } - - static size_t serialize (JsonDocument& doc, String& str) - { - size_t s = serializedSize(doc) + 10; // 10 is paranoid - str.reserve(s); - serializeJson(doc, str); - return s; - } - - static String toString (JsonDocument& doc) - { - String str; - serialize(doc, str); - return str; - } - -protected: - size_t counter = 0; -}; - -ESPUIclient::ESPUIclient(AsyncWebSocketClient * _client): - client(_client) -{ - fsm_EspuiClient_state_Idle_imp.SetParent(this); - fsm_EspuiClient_state_SendingUpdate_imp.SetParent(this); - fsm_EspuiClient_state_Rebuilding_imp.SetParent(this); - fsm_EspuiClient_state_Reloading_imp.SetParent(this); - - fsm_EspuiClient_state_Idle_imp.Init(); -} - -ESPUIclient::ESPUIclient(const ESPUIclient& source): - client(source.client) -{ - fsm_EspuiClient_state_Idle_imp.SetParent(this); - fsm_EspuiClient_state_SendingUpdate_imp.SetParent(this); - fsm_EspuiClient_state_Rebuilding_imp.SetParent(this); - fsm_EspuiClient_state_Reloading_imp.SetParent(this); - - fsm_EspuiClient_state_Idle_imp.Init(); -} - -ESPUIclient::~ESPUIclient() -{ -} - -bool ESPUIclient::CanSend() -{ - bool Response = false; - if (nullptr != client) - { - Response = client->canSend(); - } - return Response; -} - -void ESPUIclient::FillInHeader(JsonDocument& document) -{ - document[F("type")] = UI_EXTEND_GUI; - document[F("sliderContinuous")] = ESPUI.sliderContinuous; - document[F("startindex")] = 0; - document[F("totalcontrols")] = ESPUI.controlCount; - JsonArray items = AllocateJsonArray(document, F("controls")); - JsonObject titleItem = AllocateJsonObject(items); - titleItem[F("type")] = (int)UI_TITLE; - titleItem[F("label")] = ESPUI.ui_title; -} - -bool ESPUIclient::IsSyncronized() -{ - return ((ClientUpdateType_t::Synchronized == ClientUpdateType) && - (&fsm_EspuiClient_state_Idle_imp == pCurrentFsmState)); -} - -bool ESPUIclient::SendClientNotification(ClientUpdateType_t value) -{ - bool Response = false; - - do // once - { - if(!CanSend()) - { - // Serial.println(F("ESPUIclient::SendClientNotification:CannotSend")); - break; - } - - AllocateJsonDocument(document, ESPUI.jsonUpdateDocumentSize); - FillInHeader(document); - if(ClientUpdateType_t::ReloadNeeded == value) - { - // Serial.println(F("ESPUIclient::SendClientNotification:set type to reload")); - document["type"] = int(UI_RELOAD); - } - // dont send any controls - - Response = SendJsonDocToWebSocket(document); - // Serial.println(String("ESPUIclient::SendClientNotification:NotificationSent:Response: ") + String(Response)); - - } while (false); - return Response; -} - -void ESPUIclient::NotifyClient(ClientUpdateType_t newState) -{ - SetState(newState); - pCurrentFsmState->NotifyClient(); -} - -// Handle Websockets Communication -bool ESPUIclient::onWsEvent(AwsEventType type, void* arg, uint8_t* data, size_t len) -{ - bool Response = false; - // Serial.println(String("ESPUIclient::OnWsEvent: type: ") + String(type)); - - switch (type) - { - case WS_EVT_PONG: - { - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("ESPUIclient::OnWsEvent:WS_EVT_PONG")); - } - #endif - break; - } - - case WS_EVT_ERROR: - { - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("ESPUIclient::OnWsEvent:WS_EVT_ERROR")); - } - #endif - break; - } - - case WS_EVT_CONNECT: - { - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(F("ESPUIclient::OnWsEvent:WS_EVT_CONNECT")); - Serial.println(client->id()); - } - #endif - - // Serial.println("ESPUIclient:onWsEvent:WS_EVT_CONNECT: Call NotifyClient: RebuildNeeded"); - NotifyClient(ClientUpdateType_t::RebuildNeeded); - break; - } - - case WS_EVT_DATA: - { - // Serial.println(F("ESPUIclient::OnWsEvent:WS_EVT_DATA")); - String msg = ""; - msg.reserve(len + 1); - - for (size_t i = 0; i < len; i++) - { - msg += (char)data[i]; - } - - String cmd = msg.substring(0, msg.indexOf(":")); - String value = msg.substring(cmd.length() + 1, msg.lastIndexOf(':')); - uint16_t id = msg.substring(msg.lastIndexOf(':') + 1).toInt(); - - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity >= Verbosity::VerboseJSON) - { - Serial.println(String(F(" WS msg: ")) + msg); - Serial.println(String(F(" WS cmd: ")) + cmd); - Serial.println(String(F(" WS id: ")) + String(id)); - Serial.println(String(F("WS value: ")) + String(value)); - } - #endif - - if (cmd.equals(F("uiok"))) - { - - // Serial.println(String(F("ESPUIclient::OnWsEvent:WS_EVT_DATA:uiok:ProcessAck:")) + pCurrentFsmState->GetStateName()); - pCurrentFsmState->ProcessAck(id, emptyString); - break; - } - - if (cmd.equals(F("uifragmentok"))) - { - // Serial.println(String(F("ESPUIclient::OnWsEvent:WS_EVT_DATA:uiok:uifragmentok:")) + pCurrentFsmState->GetStateName() + ":ProcessAck"); - if(!emptyString.equals(value)) - { - // Serial.println(String(F("ESPUIclient::OnWsEvent:WS_EVT_DATA:uiok:uifragmentok:")) + pCurrentFsmState->GetStateName() + ":ProcessAck:value:'" + value + "'"); - pCurrentFsmState->ProcessAck(uint16_t(-1), value); - } - else - { - Serial.println(F("ERROR:ESPUIclient::OnWsEvent:WS_EVT_DATA:uifragmentok:ProcessAck:Fragment Header is missing")); - } - break; - } - - if (cmd.equals(F("uiuok"))) - { - // Serial.println(F("WS_EVT_DATA: uiuok. Unlock new async notifications")); - break; - } - - // Serial.println(F("WS_EVT_DATA:Process Control")); - Control* control = ESPUI.getControl(id); - if (nullptr == control) - { - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity) - { - Serial.println(String(F("No control found for ID ")) + String(id)); - } - #endif - break; - } - control->onWsEvent(cmd, value); - // notify other clients of change - Response = true; - break; - } - - default: - { - // Serial.println(F("ESPUIclient::OnWsEvent:default")); - break; - } - } // end switch - - return Response; -} - -/* -Prepare a chunk of elements as a single JSON string. If the allowed number of elements is greater than the total -number this will represent the entire UI. More likely, it will represent a small section of the UI to be sent. The -client will acknowledge receipt by requesting the next chunk. - */ -uint32_t ESPUIclient::prepareJSONChunk(uint16_t startindex, - JsonDocument & rootDoc, - bool InUpdateMode, - String FragmentRequestString) -{ -#ifdef ESP32 - xSemaphoreTake(ESPUI.ControlsSemaphore, portMAX_DELAY); -#endif // def ESP32 - - // Serial.println(String("prepareJSONChunk: Start. InUpdateMode: ") + String(InUpdateMode)); - // Serial.println(String("prepareJSONChunk: Start. startindex: ") + String(startindex)); - // Serial.println(String("prepareJSONChunk: Start. FragmentRequestString: '") + FragmentRequestString + "'"); - int elementcount = 0; - uint32_t MaxMarshaledJsonSize = (!InUpdateMode) ? ESPUI.jsonInitialDocumentSize: ESPUI.jsonUpdateDocumentSize; - uint32_t EstimatedUsedMarshaledJsonSize = 0; - - do // once - { - // Follow the list until control points to the startindex'th node - Control* control = ESPUI.controls; - uint32_t currentIndex = 0; - uint32_t DataOffset = 0; - JsonArray items = rootDoc[F("controls")]; - bool SingleControl = false; - - if(!emptyString.equals(FragmentRequestString)) - { - // Serial.println(F("prepareJSONChunk:Fragmentation:Got Header (1)")); - // Serial.println(String("prepareJSONChunk:startindex: ") + String(startindex)); - // Serial.println(String("prepareJSONChunk:currentIndex: ") + String(currentIndex)); - // Serial.println(String("prepareJSONChunk:FragmentRequestString: '") + FragmentRequestString + "'"); - - // this is actually a fragment or directed update request - // parse the string we got from the UI and try to update that specific - // control. - AllocateJsonDocument(FragmentRequest, FragmentRequestString.length() * 3); -/* - ArduinoJson::detail::sizeofObject(N); - if(0 >= FragmentRequest.capacity()) - { - Serial.println(F("ERROR:prepareJSONChunk:Fragmentation:Could not allocate memory for a fragmentation request. Skipping Response")); - break; - } -*/ - size_t FragmentRequestStartOffset = FragmentRequestString.indexOf("{"); - DeserializationError error = deserializeJson(FragmentRequest, FragmentRequestString.substring(FragmentRequestStartOffset)); - if(DeserializationError::Ok != error) - { - Serial.println(F("ERROR:prepareJSONChunk:Fragmentation:Could not extract json from the fragment request")); - break; - } - - if(!FragmentRequest["id"].is()) - { - Serial.println(F("ERROR:prepareJSONChunk:Fragmentation:Request does not contain a control ID")); - break; - } - uint16_t ControlId = uint16_t(FragmentRequest[F("id")]); - - if(!FragmentRequest["offset"].is()) - { - Serial.println(F("ERROR:prepareJSONChunk:Fragmentation:Request does not contain a starting offset")); - break; - } - DataOffset = uint16_t(FragmentRequest[F("offset")]); - control = ESPUI.getControlNoLock(ControlId); - if(nullptr == control) - { - Serial.println(String(F("ERROR:prepareJSONChunk:Fragmentation:Requested control: ")) + String(ControlId) + F(" does not exist")); - break; - } - - // Serial.println(F("prepareJSONChunk:Fragmentation:disable the control search operation")); - currentIndex = 1; - startindex = 0; - SingleControl = true; - } - - // find a control to send - while ((startindex > currentIndex) && (nullptr != control)) - { - // only count active controls - if (!control->ToBeDeleted()) - { - if(InUpdateMode) - { - // In update mode we only count the controls that have been updated. - if(control->NeedsSync(CurrentSyncID)) - { - ++currentIndex; - } - } - else - { - // not in update mode. Count all active controls - ++currentIndex; - } - } - control = control->next; - } - - // any controls left to be processed? - if(nullptr == control) - { - // Serial.println("prepareJSONChunk: No controls to process"); - break; - } - - // keep track of the number of elements we have serialised into this - // message. Overflow is detected and handled later in this loop - // and needs an index to the last item added. - while (nullptr != control) - { - // skip deleted controls or controls that have not been updated - if (control->ToBeDeleted() && !SingleControl) - { - // Serial.println(String("prepareJSONChunk: Ignoring Deleted control: ") + String(control->id)); - control = control->next; - continue; - } - - if(InUpdateMode && !SingleControl) - { - if(control->NeedsSync(CurrentSyncID)) - { - // dont skip this control - } - else - { - // control has not been updated. Skip it - control = control->next; - continue; - } - } - - // Serial.println(String(F("prepareJSONChunk: MaxMarshaledJsonSize: ")) + String(MaxMarshaledJsonSize)); - // Serial.println(String(F("prepareJSONChunk: Cur EstimatedUsedMarshaledJsonSize: ")) + String(EstimatedUsedMarshaledJsonSize)); - - JsonObject item = AllocateJsonObject(items); - elementcount++; - uint32_t RemainingSpace = (MaxMarshaledJsonSize - EstimatedUsedMarshaledJsonSize) - 100; - // Serial.println(String(F("prepareJSONChunk: RemainingSpace: ")) + String(RemainingSpace)); - uint32_t SpaceUsedByMarshaledControl = 0; - bool ControlIsFragmented = control->MarshalControl(item, - InUpdateMode, - DataOffset, - RemainingSpace, - SpaceUsedByMarshaledControl); - // Serial.println(String(F("prepareJSONChunk: SpaceUsedByMarshaledControl: ")) + String(SpaceUsedByMarshaledControl)); - EstimatedUsedMarshaledJsonSize += SpaceUsedByMarshaledControl; - // Serial.println(String(F("prepareJSONChunk: New EstimatedUsedMarshaledJsonSize: ")) + String(EstimatedUsedMarshaledJsonSize)); - // Serial.println(String(F("prepareJSONChunk: ControlIsFragmented: ")) + String(ControlIsFragmented)); - - // did the control get added to the doc? - if (0 == SpaceUsedByMarshaledControl || - (ESPUI.jsonChunkNumberMax > 0 && (elementcount % ESPUI.jsonChunkNumberMax) == 0)) - { - // Serial.println( String("prepareJSONChunk: too much data in the message. Remove the last entry")); - if (1 == elementcount) - { - // Serial.println(String(F("prepareJSONChunk: Control ")) + String(control->id) + F(" is too large to be sent to the browser.")); - // Serial.println(String(F("ERROR: prepareJSONChunk: value: ")) + control->value); - rootDoc.clear(); - item = AllocateJsonObject(items); - control->MarshalErrorMessage(item); - elementcount = 0; - } - else - { - // Serial.println(String("prepareJSONChunk: Defering control: ") + String(control->id)); - // Serial.println(String("prepareJSONChunk: elementcount: ") + String(elementcount)); - - items.remove(elementcount); - --elementcount; - } - // exit the loop - control = nullptr; - } - else if ((SingleControl) || - (ControlIsFragmented) || - (MaxMarshaledJsonSize < (EstimatedUsedMarshaledJsonSize + 100))) - { - // Serial.println("prepareJSONChunk: Doc is Full, Fragmented Control or Single Control. exit loop"); - control = nullptr; - } - else - { - // Serial.println("prepareJSONChunk: Next Control"); - control = control->next; - } - } // end while (control != nullptr) - - } while (false); - -#ifdef ESP32 - xSemaphoreGive(ESPUI.ControlsSemaphore); -#endif // def ESP32 - - // Serial.println(String("prepareJSONChunk: END: elementcount: ") + String(elementcount)); - return elementcount; -} - -/* -Convert & Transfer Arduino elements to JSON elements. This function sends a chunk of -JSON describing the controls of the UI, starting from the control at index startidx. -If startidx is 0 then a UI_INITIAL_GUI message will be sent, else a UI_EXTEND_GUI. -Both message types contain a list of serialised UI elements. Only a portion of the UI -will be sent in order to avoid websocket buffer overflows. The client will acknowledge -receipt of a partial message by requesting the next chunk of UI. - -The protocol is: -SERVER: SendControlsToClient(0): - "UI_INITIAL_GUI: n serialised UI elements" -CLIENT: controls.js:handleEvent() - "uiok:n" -SERVER: SendControlsToClient(n): - "UI_EXTEND_GUI: n serialised UI elements" -CLIENT: controls.js:handleEvent() - "uiok:2*n" -etc. - Returns true if all controls have been sent (aka: Done) -*/ -bool ESPUIclient::SendControlsToClient(uint16_t startidx, ClientUpdateType_t TransferMode, String FragmentRequest) -{ - bool Response = false; - // Serial.println(String("ESPUIclient:SendControlsToClient:startidx: ") + String(startidx)); - do // once - { - if(!CanSend()) - { - // Serial.println("ESPUIclient:SendControlsToClient: Cannot Send to clients."); - break; - } - - else if ((startidx >= ESPUI.controlCount) && (emptyString.equals(FragmentRequest))) - { - // Serial.println(F("ERROR:ESPUIclient:SendControlsToClient: No more controls to send.")); - Response = true; - break; - } - - AllocateJsonDocument(document, ESPUI.jsonInitialDocumentSize); - FillInHeader(document); - document[F("startindex")] = startidx; - document[F("totalcontrols")] = uint16_t(-1); // ESPUI.controlCount; - - if(0 == startidx) - { - // Serial.println("ESPUIclient:SendControlsToClient: Tell client we are starting a transfer of controls."); - document["type"] = (ClientUpdateType_t::RebuildNeeded == TransferMode) ? UI_INITIAL_GUI : UI_EXTEND_GUI; - CurrentSyncID = NextSyncID; - NextSyncID = ESPUI.GetNextControlChangeId(); - } - // Serial.println(String("ESPUIclient:SendControlsToClient:type: ") + String((uint32_t)document["type"])); - - // Serial.println("ESPUIclient:SendControlsToClient: Build Controls."); - if(prepareJSONChunk(startidx, document, ClientUpdateType_t::UpdateNeeded == TransferMode, FragmentRequest)) - { - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity >= Verbosity::VerboseJSON) - { - Serial.println(F("ESPUIclient:SendControlsToClient: Sending elements --------->")); - serializeJson(document, Serial); - Serial.println(); - } - #endif - - // Serial.println("ESPUIclient:SendControlsToClient: Send message."); - if(true == SendJsonDocToWebSocket(document)) - { - // Serial.println("ESPUIclient:SendControlsToClient: Sent."); - } - else - { - // Serial.println("ESPUIclient:SendControlsToClient: Send failed."); - } - } - else - { - // Serial.println("ESPUIclient:SendControlsToClient: No elements to send."); - Response = true; - } - - } while(false); - - // Serial.println(String("ESPUIclient:SendControlsToClient:Response: ") + String(Response)); - return Response; -} - -bool ESPUIclient::SendJsonDocToWebSocket(JsonDocument& document) -{ - bool Response = true; - - do // once - { - if (!CanSend()) - { - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity >= Verbosity::VerboseJSON) - { - Serial.println(F("ESPUIclient::SendJsonDocToWebSocket: Cannot Send to client. Not sending websocket message")); - } - #endif - // Serial.println("ESPUIclient::SendJsonDocToWebSocket: Cannot Send to client. Not sending websocket message"); - Response = false; - break; - } - - String json = JSONSlave::toString(document); - - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity >= Verbosity::VerboseJSON) - { - Serial.println(String(F("ESPUIclient::SendJsonDocToWebSocket: json: '")) + json + "'"); - } - #endif - - #if defined(DEBUG_ESPUI) - if (ESPUI.verbosity >= Verbosity::VerboseJSON) - { - Serial.println(F("ESPUIclient::SendJsonDocToWebSocket: client.text")); - } - #endif - // Serial.println(F("ESPUIclient::SendJsonDocToWebSocket: client.text")); - client->text(json); - - } while (false); - - return Response; -} - -void ESPUIclient::SetState(ClientUpdateType_t value) -{ - // only a higher priority state request can replace the current state request - if(uint32_t(ClientUpdateType) < uint32_t(value)) - { - ClientUpdateType = value; - } -} - diff --git a/watering/lib/ESPUI/src/ESPUIclient.h b/watering/lib/ESPUI/src/ESPUIclient.h deleted file mode 100644 index b013f5e..0000000 --- a/watering/lib/ESPUI/src/ESPUIclient.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once - -#include -#include -#include -#include "ESPUIclientFsm.h" -#include "ESPUIcontrol.h" - -class ESPUIclient -{ -public: - enum ClientUpdateType_t - { // this is an orderd list. highest number is highest priority - Synchronized = 0, - UpdateNeeded = 1, - RebuildNeeded = 2, - ReloadNeeded = 3, - }; - -protected: - // bool HasBeenNotified = false; // Set when a notification has been sent and we are waiting for a reply - // bool DelayedNotification = false; // set if a delayed notification is needed - - ClientUpdateType_t ClientUpdateType = ClientUpdateType_t::RebuildNeeded; - - AsyncWebSocketClient * client = nullptr; - - friend class fsm_EspuiClient_state_Idle; - friend class fsm_EspuiClient_state_SendingUpdate; - friend class fsm_EspuiClient_state_Rebuilding; - friend class fsm_EspuiClient_state_WaitForAck; - friend class fsm_EspuiClient_state_Reloading; - friend class fsm_EspuiClient_state; - - fsm_EspuiClient_state_Idle fsm_EspuiClient_state_Idle_imp; - fsm_EspuiClient_state_SendingUpdate fsm_EspuiClient_state_SendingUpdate_imp; - fsm_EspuiClient_state_Rebuilding fsm_EspuiClient_state_Rebuilding_imp; - fsm_EspuiClient_state_Reloading fsm_EspuiClient_state_Reloading_imp; - fsm_EspuiClient_state* pCurrentFsmState = &fsm_EspuiClient_state_Idle_imp; - - time_t EspuiClientEndTime = 0; - - // bool NeedsNotification() { return pCurrentFsmState != &fsm_EspuiClient_state_Idle_imp; } - - bool CanSend(); - void FillInHeader(ArduinoJson::JsonDocument& document); - uint32_t prepareJSONChunk(uint16_t startindex, JsonDocument& rootDoc, bool InUpdateMode, String value); - bool SendControlsToClient(uint16_t startidx, ClientUpdateType_t TransferMode, String FragmentRequest); - - bool SendClientNotification(ClientUpdateType_t value); - -private: - uint32_t CurrentSyncID = 0; - uint32_t NextSyncID = 0; - -public: - ESPUIclient(AsyncWebSocketClient * _client); - ESPUIclient(const ESPUIclient & source); - virtual ~ESPUIclient(); - void NotifyClient(ClientUpdateType_t value); - bool onWsEvent(AwsEventType type, void* arg, uint8_t* data, size_t len); - bool IsSyncronized(); - uint32_t id() { return client->id(); } - void SetState(ClientUpdateType_t value); - bool SendJsonDocToWebSocket(ArduinoJson::JsonDocument& document); - -}; diff --git a/watering/lib/ESPUI/src/ESPUIclientFsm.cpp b/watering/lib/ESPUI/src/ESPUIclientFsm.cpp deleted file mode 100644 index fe4ca36..0000000 --- a/watering/lib/ESPUI/src/ESPUIclientFsm.cpp +++ /dev/null @@ -1,149 +0,0 @@ -#include "ESPUI.h" -#include "ESPUIclient.h" - -//---------------------------------------------- -// FSM definitions -//---------------------------------------------- -void fsm_EspuiClient_state::Init() -{ - // Serial.println(String("fsm_EspuiClient_state:Init: ") + GetStateName()); - Parent->pCurrentFsmState = this; -} - -//---------------------------------------------- -//---------------------------------------------- -//---------------------------------------------- -bool fsm_EspuiClient_state_Idle::NotifyClient() -{ - bool Response = false; - - // Serial.println(F("fsm_EspuiClient_state_Idle: NotifyClient")); - ClientUpdateType_t TypeToProcess = Parent->ClientUpdateType; - // Clear the type so that we capture any changes in type that happen - // while we are processing the current request. - Parent->ClientUpdateType = ClientUpdateType_t::Synchronized; - - // Start processing the current request. - switch (TypeToProcess) - { - case ClientUpdateType_t::Synchronized: - { - // Serial.println(F("fsm_EspuiClient_state_Idle: NotifyClient:State:Synchronized")); - // Parent->fsm_EspuiClient_state_Idle_imp.Init(); - Response = true; // Parent->SendClientNotification(ClientUpdateType_t::UpdateNeeded); - break; - } - case ClientUpdateType_t::UpdateNeeded: - { - // Serial.println(F("fsm_EspuiClient_state_Idle: NotifyClient:State:UpdateNeeded")); - Parent->fsm_EspuiClient_state_SendingUpdate_imp.Init(); - Response = Parent->SendClientNotification(ClientUpdateType_t::UpdateNeeded); - break; - } - case ClientUpdateType_t::RebuildNeeded: - { - // Serial.println(F("fsm_EspuiClient_state_Idle: NotifyClient:State:RebuildNeeded")); - Parent->fsm_EspuiClient_state_Rebuilding_imp.Init(); - Response = Parent->SendClientNotification(ClientUpdateType_t::RebuildNeeded); - break; - } - case ClientUpdateType_t::ReloadNeeded: - { - // Serial.println(F("fsm_EspuiClient_state_Idle: NotifyClient:State:ReloadNeeded")); - Parent->fsm_EspuiClient_state_Reloading_imp.Init(); - Response = Parent->SendClientNotification(ClientUpdateType_t::ReloadNeeded); - break; - } - } - return Response; -} - -void fsm_EspuiClient_state_Idle::ProcessAck(uint16_t ControlIndex, String FragmentRequestString) -{ - if(!emptyString.equals(FragmentRequestString)) - { - // Serial.println(F("fsm_EspuiClient_state_Idle::ProcessAck:Fragmentation:Got fragment Header")); - Parent->SendControlsToClient(ControlIndex, ClientUpdateType_t::UpdateNeeded, FragmentRequestString); - } - else - { - // This is an unexpected request for control data from the browser - // treat it as if it was a rebuild operation - // Serial.println(F("fsm_EspuiClient_state_Idle: ProcessAck:Error: Rebuild")); - Parent->NotifyClient(ClientUpdateType_t::RebuildNeeded); - } -} - -//---------------------------------------------- -//---------------------------------------------- -//---------------------------------------------- -bool fsm_EspuiClient_state_SendingUpdate::NotifyClient() -{ - // Serial.println(F("fsm_EspuiClient_state_SendingUpdate:NotifyClient")); - return true; /* Ignore request */ -} - -void fsm_EspuiClient_state_SendingUpdate::ProcessAck(uint16_t ControlIndex, String FragmentRequest) -{ - // Serial.println(F("fsm_EspuiClient_state_SendingUpdate: ProcessAck")); - if(Parent->SendControlsToClient(ControlIndex, ClientUpdateType_t::UpdateNeeded, FragmentRequest)) - { - // No more data to send. Go back to idle or start next request - Parent->fsm_EspuiClient_state_Idle_imp.Init(); - Parent->fsm_EspuiClient_state_Idle_imp.NotifyClient(); - } -} - -//---------------------------------------------- -//---------------------------------------------- -//---------------------------------------------- -void fsm_EspuiClient_state_Rebuilding::Init() -{ - // Serial.println(String("fsm_EspuiClient_state:Init: ") + GetStateName()); - Parent->CurrentSyncID = 0; - Parent->NextSyncID = 0; - Parent->pCurrentFsmState = this; -} - -bool fsm_EspuiClient_state_Rebuilding::NotifyClient() -{ - // Serial.println(F("fsm_EspuiClient_state_Rebuilding: NotifyClient")); - return true; /* Ignore request */ -} - -void fsm_EspuiClient_state_Rebuilding::ProcessAck(uint16_t ControlIndex, String FragmentRequest) -{ - // Serial.println(F("fsm_EspuiClient_state_Rebuilding: ProcessAck")); - if(Parent->SendControlsToClient(ControlIndex, ClientUpdateType_t::RebuildNeeded, FragmentRequest)) - { - // No more data to send. Go back to idle or start next request - Parent->fsm_EspuiClient_state_Idle_imp.Init(); - Parent->fsm_EspuiClient_state_Idle_imp.NotifyClient(); - } -} - -//---------------------------------------------- -//---------------------------------------------- -//---------------------------------------------- -void fsm_EspuiClient_state_Reloading::Init() -{ - // Serial.println(String("fsm_EspuiClient_state:Init: ") + GetStateName()); - Parent->CurrentSyncID = 0; - Parent->NextSyncID = 0; - Parent->pCurrentFsmState = this; -} - -void fsm_EspuiClient_state_Reloading::ProcessAck(uint16_t ControlIndex, String FragmentRequestString) -{ - if(!emptyString.equals(FragmentRequestString)) - { - // Serial.println(F("fsm_EspuiClient_state_Reloading::ProcessAck:Fragmentation:Got fragment Header")); - Parent->SendControlsToClient(ControlIndex, ClientUpdateType_t::UpdateNeeded, FragmentRequestString); - } -} - -bool fsm_EspuiClient_state_Reloading::NotifyClient() -{ - // Serial.println(F("fsm_EspuiClient_state_Reloading: NotifyClient")); - return true; /* Ignore request */ -} diff --git a/watering/lib/ESPUI/src/ESPUIclientFsm.h b/watering/lib/ESPUI/src/ESPUIclientFsm.h deleted file mode 100644 index 8fdbaf1..0000000 --- a/watering/lib/ESPUI/src/ESPUIclientFsm.h +++ /dev/null @@ -1,81 +0,0 @@ -#pragma once - -#include -#include - -// forward declaration -class ESPUIclient; - -/*****************************************************************************/ -/* -* Generic fsm base class. -*/ -/*****************************************************************************/ -/*****************************************************************************/ -class fsm_EspuiClient_state -{ -public: - fsm_EspuiClient_state() {}; - virtual ~fsm_EspuiClient_state() {} - - void Init(); - virtual bool NotifyClient() = 0; - virtual void ProcessAck(uint16_t id, String FragmentRequest) = 0; - virtual String GetStateName () = 0; - void SetParent(ESPUIclient * value) { Parent = value; } - -protected: - ESPUIclient * Parent = nullptr; - -}; // fsm_EspuiClient_state - -class fsm_EspuiClient_state_Idle : public fsm_EspuiClient_state -{ -public: - fsm_EspuiClient_state_Idle() {} - virtual ~fsm_EspuiClient_state_Idle() {} - - virtual bool NotifyClient(); - virtual void ProcessAck(uint16_t id, String FragmentRequest); - String GetStateName() { return String(F("Idle")); } - -}; // fsm_EspuiClient_state_Idle - -class fsm_EspuiClient_state_SendingUpdate : public fsm_EspuiClient_state -{ -public: - fsm_EspuiClient_state_SendingUpdate() {} - virtual ~fsm_EspuiClient_state_SendingUpdate() {} - - virtual bool NotifyClient(); - virtual void ProcessAck(uint16_t id, String FragmentRequest); - String GetStateName() { return String(F("Sending Update")); } - -}; // fsm_EspuiClient_state_SendingUpdate - -class fsm_EspuiClient_state_Rebuilding : public fsm_EspuiClient_state -{ -public: - fsm_EspuiClient_state_Rebuilding() {} - virtual ~fsm_EspuiClient_state_Rebuilding() {} - - void Init(); - virtual bool NotifyClient(); - virtual void ProcessAck(uint16_t id, String FragmentRequest); - String GetStateName() { return String(F("Sending Rebuild")); } - -}; // fsm_EspuiClient_state_Rebuilding - -class fsm_EspuiClient_state_Reloading : public fsm_EspuiClient_state -{ -public: - fsm_EspuiClient_state_Reloading() {} - virtual ~fsm_EspuiClient_state_Reloading() {} - - void Init(); - virtual bool NotifyClient(); - virtual void ProcessAck(uint16_t id, String FragmentRequest); - String GetStateName() { return String(F("Reloading")); } - -}; // fsm_EspuiClient_state_Reloading - diff --git a/watering/lib/ESPUI/src/ESPUIcontrol.cpp b/watering/lib/ESPUI/src/ESPUIcontrol.cpp deleted file mode 100644 index 36647bf..0000000 --- a/watering/lib/ESPUI/src/ESPUIcontrol.cpp +++ /dev/null @@ -1,336 +0,0 @@ -#include "ESPUI.h" - -static uint16_t idCounter = 0; -static const String ControlError = "*** ESPUI ERROR: Could not transfer control ***"; - -Control::Control(ControlType type, const char* label, std::function callback, - const String& value, ControlColor color, bool visible, uint16_t parentControl) - : type(type), - label(label), - callback(callback), - value(value), - color(color), - visible(visible), - wide(false), - vertical(false), - enabled(true), - parentControl(parentControl), - next(nullptr) -{ - id = ++idCounter; - ControlChangeID = 1; -} - -Control::Control(const Control& Control) - : type(Control.type), - id(Control.id), - label(Control.label), - callback(Control.callback), - value(Control.value), - color(Control.color), - visible(Control.visible), - parentControl(Control.parentControl), - next(Control.next), - ControlChangeID(Control.ControlChangeID) -{ } - -void Control::SendCallback(int type) -{ - if(callback) - { - callback(this, type); - } -} - -void Control::DeleteControl() -{ - _ToBeDeleted = true; - callback = nullptr; -} - -bool Control::MarshalControl(JsonObject & _item, - bool refresh, - uint32_t StartingOffset, - uint32_t AvailMarshaledLength, - uint32_t &EstimatedMarshaledLength) -{ - // this code assumes MaxMarshaledLength > JsonMarshalingRatio - // Serial.println(String("MarshalControl: StartingOffset: ") + String(StartingOffset)); - // Serial.println(String("MarshalControl: AvailMarshaledLength: ") + String(AvailMarshaledLength)); - // Serial.println(String("MarshalControl: Control ID: ") + String(id)); - - bool ControlIsFragmented = false; - // create a new item in the response document - JsonObject & item = _item; - - // how much space do we expect to use? - uint32_t ValueMarshaledLength = (value.length() - StartingOffset) * JsonMarshalingRatio; - uint32_t LabelMarshaledLength = strlen(label) * JsonMarshalingRatio; - uint32_t MinimumMarshaledLength = LabelMarshaledLength + JsonMarshaledOverhead; - uint32_t MaximumMarshaledLength = ValueMarshaledLength + MinimumMarshaledLength; - uint32_t SpaceForMarshaledValue = AvailMarshaledLength - MinimumMarshaledLength; - // Serial.println(String("MarshalControl: value.length(): ") + String(value.length())); - // Serial.println(String("MarshalControl: ValueMarshaledLength: ") + String(ValueMarshaledLength)); - // Serial.println(String("MarshalControl: LabelMarshaledLength: ") + String(LabelMarshaledLength)); - // Serial.println(String("MarshalControl: MaximumMarshaledLength: ") + String(MaximumMarshaledLength)); - // Serial.println(String("MarshalControl: MinimumMarshaledLength: ") + String(MinimumMarshaledLength)); - // Serial.println(String("MarshalControl: SpaceForMarshaledValue: ") + String(SpaceForMarshaledValue)); - - // will the item fit in the remaining space? Fragment if not - if (AvailMarshaledLength < MinimumMarshaledLength) - { - // Serial.println(String("MarshalControl: Cannot Marshal control. Not enough space for basic headers.")); - EstimatedMarshaledLength = 0; - return false; - } - - uint32_t MaxValueLength = (SpaceForMarshaledValue / JsonMarshalingRatio); - // Serial.println(String("MarshalControl: MaxValueLength: ") + String(MaxValueLength)); - - uint32_t ValueLenToSend = min((value.length() - StartingOffset), MaxValueLength); - // Serial.println(String("MarshalControl: ValueLenToSend: ") + String(ValueLenToSend)); - - uint32_t AdjustedMarshaledLength = (ValueLenToSend * JsonMarshalingRatio) + MinimumMarshaledLength; - // Serial.println(String("MarshalControl: AdjustedMarshaledLength: ") + String(AdjustedMarshaledLength)); - - bool NeedToFragment = (ValueLenToSend < value.length()); - // Serial.println(String("MarshalControl: NeedToFragment: ") + String(NeedToFragment)); - - if ((AdjustedMarshaledLength > AvailMarshaledLength) && (0 != ValueLenToSend)) - { - // Serial.println(String("MarshalControl: Cannot Marshal control. Not enough space for marshaled control.")); - EstimatedMarshaledLength = 0; - return false; - } - - EstimatedMarshaledLength = AdjustedMarshaledLength; - - // are we fragmenting? - if(NeedToFragment || StartingOffset) - { - // Serial.println(String("MarshalControl:Start Fragment Processing")); - // Serial.println(String("MarshalControl:id: ") + String(id)); - // Serial.println(String("MarshalControl:StartingOffset: ") + String(StartingOffset)); -/* - if(0 == StartingOffset) - { - Serial.println(String("MarshalControl: New control to fragement. ID: ") + String(id)); - } - else - { - Serial.println(String("MarshalControl: Next fragement. ID: ") + String(id)); - } -*/ - // indicate that no additional controls should be sent - ControlIsFragmented = true; - - // fill in the fragment header - _item[F("type")] = uint32_t(ControlType::Fragment); - _item[F("id")] = id; - - // Serial.println(String("MarshalControl:Final length: ") + String(length)); - - _item[F("offset")] = StartingOffset; - _item[F("length")] = ValueLenToSend; - _item[F("total")] = value.length(); - AllocateNamedJsonObject(item, _item, F("control")); - } - - item[F("id")] = id; - ControlType TempType = (ControlType::Password == type) ? ControlType::Text : type; - if(refresh) - { - item[F("type")] = uint32_t(TempType) + uint32_t(ControlType::UpdateOffset); - } - else - { - item[F("type")] = uint32_t(TempType); - } - - item[F("label")] = label; - item[F ("value")] = (ControlType::Password == type) ? F ("--------") : value.substring(StartingOffset, StartingOffset + ValueLenToSend); - item[F("visible")] = visible; - item[F("color")] = (int)color; - item[F("enabled")] = enabled; - - if (!panelStyle.isEmpty()) {item[F("panelStyle")] = panelStyle;} - if (!elementStyle.isEmpty()) {item[F("elementStyle")] = elementStyle;} - if (!inputType.isEmpty()) {item[F("inputType")] = inputType;} - if (wide == true) {item[F("wide")] = true;} - if (vertical == true) {item[F("vertical")] = true;} - if (parentControl != Control::noParent) - { - item[F("parentControl")] = String(parentControl); - } - - // special case for selects: to preselect an option, you have to add - // "selected" to