1
0
mirror of https://github.com/s00500/ESPUI.git synced 2024-06-16 02:43:33 +00:00

Compare commits

...

344 Commits

Author SHA1 Message Date
731e6c68d3
Merge pull request #301 from ChrSchu90/master
Cleanup of disconnected clients
2024-06-03 21:23:12 +02:00
ChrSchu
82460d4aed
Trigger a websocket client cleanup on new connection to disconnect old clients and releasing the memory 2024-06-02 23:21:38 +02:00
75bbece7b5
Merge pull request #299 from sunlord2k/sunlord2k-patch-2
Update ESPUI.cpp
2024-04-06 11:16:35 +02:00
efda9b7140
Merge pull request #298 from sunlord2k/sunlord2k-patch-1
Update ESPUI.h
2024-04-06 11:16:15 +02:00
sunlord2k
9ba3f5a940
Update ESPUI.cpp
Changed FILE_WRITE to FILE_WRITING for compatibility with SD.h for usage with SD cards
2024-04-05 12:10:10 +02:00
sunlord2k
84ff52d8cb
Update ESPUI.h
Changed FILE_WRITE to FILE_WRITING for compatibility with SD.h for usage of ESPUI with SD card
2024-04-05 12:09:01 +02:00
dd234135f2
Merge pull request #295 from MartinMueller2003/master
Added a File Display object that can be used to scroll through a text file on the UI
2024-02-26 13:00:48 +01:00
Martin
6724abfef3 removed temporary SSID and network name definitions. 2024-02-22 08:08:21 -05:00
Martin Mueller
a448fdd180
Update README.md 2024-02-21 15:42:11 -05:00
Martin
ba7fa33dfb dded missing shortcut 2024-02-21 15:39:32 -05:00
Martin
624663076f Added File Display 2024-02-21 15:32:17 -05:00
Martin
c43c2c7b72 Added File Display section 2024-02-21 15:31:46 -05:00
MartinMueller2003
e9fc63f86d Modified to use the ESPUI unified littlefs handle 2024-02-12 09:15:00 -05:00
MartinMueller2003
1ba92a3cd6 Fixes for ESP8266 builds 2024-02-12 09:13:37 -05:00
MartinMueller2003
da20c8b0a5 Converted to normalized littlefs definition 2024-02-12 09:09:51 -05:00
MartinMueller2003
707c2aa3bf Added write function
Exposed unified littlefs type for use by our users.
2024-02-12 09:09:05 -05:00
Martin
9efd0c27aa Auto Generated updates 2024-02-10 15:40:34 -05:00
Martin
6a18c59f31 Added code to create a file display dynamic test / demo. 2024-02-10 13:54:58 -05:00
Martin
6e281e302a Added ability to turn on ESPUI debugging 2024-02-10 13:52:56 -05:00
Martin
d2ccf83874 Changes to support processing a file to display 2024-02-10 13:52:06 -05:00
Martin
ea8de92246 Checkpoint adding fileDisplay object 2024-02-06 22:38:17 -05:00
aa9a62bbdf
Merge pull request #288 from TA1AUB/patch-1
Update Turkish Language
2024-01-24 16:38:44 +01:00
Abdullah YILMAZ
f3b105f143
Update Turkish Language
Update Turkish Language
2024-01-20 22:44:38 +03:00
Martin Mueller
7508e034be
Merge pull request #285 from MartinMueller2003/master
Made WebServer and WebSocket globally accusable via access functions.
2024-01-10 09:19:25 -05:00
Martin Mueller
5b36d79395
Merge branch 's00500:master' into master 2024-01-08 08:54:15 -05:00
MartinMueller2003
e4c6906723 Made the Webserver globally accessible. 2024-01-08 08:43:10 -05:00
dc2d5e1205
Merge pull request #277 from MartinMueller2003/master
Restored custom port support.
2023-12-16 11:04:25 +01:00
MartinMueller2003
d3c6df5cfa Restored custom port support. 2023-12-14 08:34:17 -05:00
MartinMueller2003
46ad206a49 Restored missing port identifier for custom port support. 2023-12-14 08:32:59 -05:00
8b64b185a4
Merge pull request #264 from MartinMueller2003/master
Changes to support keeping multiple Browser Clients in sync
2023-11-09 18:15:04 +01:00
MartinMueller2003
00841ce32d Changes to support keeping multiple Browser Clients in sync 2023-11-09 11:06:44 -05:00
85ccff0ee0
Merge pull request #257 from d-a-v/stringref
use more string references
2023-10-14 20:31:01 +02:00
0571f65f6f
Merge pull request #249 from d-a-v/lambda-with-examples
Proposal: use lambda functions
2023-10-14 20:30:20 +02:00
David Gauchard
542ac03656 Merge branch 'master' into lambda-with-examples 2023-10-06 16:45:17 +02:00
8f7cce59bf
Merge pull request #253 from MartinMueller2003/master
Added fragmentation of large control values
2023-10-06 16:04:33 +02:00
David Gauchard
ae5b6d5c0a use more string references 2023-09-22 22:37:50 +02:00
David Gauchard
62b4b56a4d Merge branch 'master' into lambda-with-examples 2023-09-22 22:18:34 +02:00
8a3865e42e
Merge pull request #254 from croghostrider/patch-1
Remove LITTLEFS library
2023-09-22 08:06:14 +02:00
croghostrider
0d9a874ba2
Update library.json 2023-09-20 12:59:25 +02:00
cf1f81bced
Merge pull request #252 from d-a-v/minorchangesagain
some more minor changes
2023-09-19 12:05:47 +02:00
David Gauchard
0b22328bd8 introduce lambda 2023-09-15 00:59:10 +02:00
croghostrider
09596a4e65
fix #196
since Arduino 2.0.0 is LITTLEFS not more required for ESP32.
2023-09-13 17:24:26 +02:00
Martin
8d61abc47d updated files to send to the esp fs 2023-09-12 17:49:38 -04:00
Martin
adf2ba369e Added fragment assembly reset if something happens to the socket. 2023-09-12 06:56:53 -04:00
David Gauchard
93d0bf7d27 some more minor changes before #249 2023-09-11 13:29:32 +02:00
Martin
794d54dc96 updated minify and .h versions. 2023-09-11 06:53:05 -04:00
Martin
1deddad091 Added changes made to ack section 2023-09-11 06:52:35 -04:00
Martin
999d465c79 Add fragmentation support 2023-09-10 17:09:00 -04:00
Martin
83dbb49697 Removed more debug output 2023-09-09 17:01:55 -04:00
Martin
290f0c6fc6 Restored offset to marshal call. 2023-09-09 17:01:36 -04:00
Martin
7e3de1c14f Aligned with latest main branch 2023-09-09 16:52:28 -04:00
Martin
136b182813 Removed debug messages 2023-09-09 16:50:34 -04:00
Martin
43b8cdbfb2 Merge branch 'master' of https://github.com/MartinMueller2003/ESPUI 2023-09-09 16:49:52 -04:00
Martin
488a6cb252 first working version of the fragmentation code. 2023-09-09 15:58:12 -04:00
c7a9438149
Merge pull request #251 from d-a-v/minorfixes
minor fixes for restoring warning-less emulation on host
2023-09-08 17:03:12 +02:00
David Gauchard
03c30fa75c more minor changes for #249 2023-09-06 22:50:42 +02:00
David Gauchard
68c251226d minor fixes for restoring warning-less emulation on host for debugging (using emuAsync, see main readme) 2023-09-06 22:35:41 +02:00
Martin
ec41deab01 Added ClientTransferContext_t to the marshal API 2023-09-03 09:30:31 -04:00
Martin
fae30398b2 Added a client transfer context for use by the control marshaling function 2023-09-03 09:26:36 -04:00
Martin
de09ddbe09 Turned off ESPUI_DEBUG by default 2023-09-03 09:20:12 -04:00
679a3b5a8d
Version 2.2.3
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2023-08-03 16:33:27 +02:00
f8fbcf887a
Fix compile issues #243
Also fix pio example

Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2023-08-03 16:32:54 +02:00
fd1cc14e87
Bump Version
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2023-08-01 13:01:49 +02:00
372157b980
Merge pull request #241 from d-a-v/membreathe
reduce memory footprint
2023-08-01 13:00:52 +02:00
f08cd5c51a
Icon changes, thanks to Mark Kinsley
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2023-07-20 11:39:20 +02:00
David Gauchard
b45f4f7356 update examples with esp8266 specifics 2023-07-19 12:07:25 +02:00
David Gauchard
c3bf9c5d00 reduce memory footprint 2023-07-18 19:49:58 +02:00
678a2ccf53
Merge pull request #235 from MartinMueller2003/master
Exposed  WebServer, Added password support.
2023-05-13 15:55:39 +02:00
270f0dd16b
Merge pull request #218 from d-a-v/ptr2long
pointers can always be casted to long
2023-05-13 15:53:59 +02:00
Martin
be8cf73d55 Exposed WebServer instance 2023-05-12 15:02:32 -04:00
David Gauchard
cc69f8a469 pointers can always be be casted to long 2023-01-17 14:53:02 +01:00
Martin Mueller
48e947287a Added variant of the text type to support hidden password fields 2022-11-27 16:59:28 -05:00
5cf0ce6afa
Merge pull request #212 from leokeba/master
Small fixes for graph UI element
2022-11-24 11:50:59 +01:00
leokeba
35c2f5b6b1 small fixes to graph UI element to make X-axis labels legible and meaningful 2022-11-21 16:05:29 +01:00
leokeba
b1b9fd2c79 Setting SVG overflow property to 'visible' to properly display numbers on the graph UI element 2022-11-21 15:33:56 +01:00
0aaca5449b
Merge pull request #211 from leokeba/master
Fixed step handler to allow using float numbers and sliders
2022-11-14 11:22:34 +01:00
leokeba
7b4ec5920a Fixed step handler to allow using float numbers and sliders 2022-11-11 17:29:02 +01:00
048f337d61
Merge pull request #208 from leokeba/master
fix: initialize graph data with empty array if null
2022-11-06 14:58:18 +01:00
leokeba
8e3c12935e fix: Use ControlType Constant 2022-11-05 14:06:13 +01:00
leokeba
f35d3a19d4 feat: implemented clearGraph function 2022-11-03 03:31:04 +01:00
leokeba
48594de29a fix: initialize graph data with empty array if null 2022-11-03 01:37:46 +01:00
d53fdb57a9
Bump version 2022-10-24 13:51:53 +02:00
b8079cfb63
Bump version 2022-10-24 13:51:34 +02:00
e3ccc216bb
Merge pull request #204 from ncmreynolds/main
Several LittleFS changes, fixes #192, adds option to not format LittleFS
2022-10-24 12:59:52 +02:00
Nick Reynolds
09a550e614 Many LittleFS related changes/fixes 2022-10-13 21:10:20 +01:00
Nick Reynolds
309e53dd1e Sort out includes for LittleFS 2022-10-13 21:09:05 +01:00
Nick Reynolds
4b489c7ce5 Support ESP-IDF versions prior to 4.4/Arduino Core 2.0 2022-10-13 20:52:19 +01:00
Nick Reynolds
0c9586730e Add feature to optionally _not_ format LittleFS to prepareFileSystem() 2022-10-13 19:53:55 +01:00
Nick Reynolds
004a374d79 Add a little more feedback to the user and make it list the files. 2022-10-13 19:52:50 +01:00
e3eea09e43
Merge pull request #199 from MartinMueller2003/master
Significant restructuring by MartinMueller
2022-10-11 21:50:58 +02:00
Martin Mueller
bce624b0f2 Added more robust retry when a socket error occurs. 2022-09-27 10:31:07 -04:00
Martin Mueller
1595b3bd04 Fixed bug that caused a crash when sending graphpoint updates to multiple browsers. 2022-09-22 09:36:12 -04:00
Martin Mueller
a18254b16b Fixed include issues for LittleFS 2022-09-22 09:34:53 -04:00
Martin Mueller
811e0ede4d Cosmetic changes to debug messages 2022-09-22 09:34:11 -04:00
Martin Mueller
ea4a0df4d0 Major Restructuring next part 2022-09-21 15:45:48 -04:00
Martin Mueller
a2923e501f Major restructuring of the code to get past an issue in the web socket where many changes are requested but the WS API cant handle the requests. Requests are now tracked per UI client.
Moved the client out of the main code into its own code and moved control data marshaling into the control class.
NONE of these changes impact the users API. No code changes are needed by the users.
WARNING: The LittleFS support for the ESP32 has been updated to be compatible with the latest ESP32 infrastructure. This includes using an improved WebServer.
2022-09-21 15:37:20 -04:00
Martin Mueller
fdffb9c041 Added a check for an invalid json format to prevent the UI from crashing. Requests a new reload when the issue is encountered. 2022-09-21 15:33:05 -04:00
05ab1734e6
Merge pull request #197 from ncmreynolds/main
Add captive portal functionality, update examples and documentation, resolves #134
2022-09-21 10:06:57 +02:00
Nick Reynolds
79b9acf9f4 Changes per suggestions by maintainer (Lukas Bachschwell). 2022-09-21 08:58:05 +01:00
Nick Reynolds
90ba90a717 Make captive portal redirect on by default. 2022-09-20 15:29:34 +01:00
95f2f9bdd0
Merge pull request #190 from iangray001/master
Small bugfix for inline styles
2022-09-20 10:15:36 +02:00
Nick Reynolds
e81cd1f7f5 Add captive portal functionality, update examples and documentation. 2022-09-19 17:38:10 +01:00
Ian Gray
a150d2db1e
Merge branch 's00500:master' into master 2022-07-17 11:20:31 +01:00
Ian Gray
86c469f5cb Fix small bug applying styles to input elements 2022-07-17 11:17:22 +01:00
70acbc1d2f
Merge pull request #180 from MartinMueller2003/master
Added a user data parameter to the callbacks to support passing a 'this' pointer for lambda functions
2022-06-26 17:18:13 +02:00
Martin Mueller
9d9a165693 Added an example using the button shortcut 2022-06-25 10:25:05 -04:00
Martin Mueller
a553d32570 Corrected class example 2022-06-25 07:40:09 -04:00
Martin Mueller
36f6932538 formatting 2022-06-25 07:31:34 -04:00
Martin Mueller
ba9f83a93b Formatting changes 2022-06-25 07:29:44 -04:00
Martin Mueller
782d339f83
Merge branch 's00500:master' into master 2022-06-25 07:17:37 -04:00
Martin Mueller
c303668a3c Added description and usage for the extended callback functionality 2022-06-25 07:16:51 -04:00
Ian Gray
e0ff99f7b6
Merge pull request #177 from iangray001/master
Small fix for slider moving when grouped
2022-06-12 13:43:33 +01:00
Martin Mueller
511840fa97 Added an example for using the new extended parameter callback 2022-06-11 10:56:35 -04:00
Martin Mueller
1419b2dec0 Updated the rest of the callback functions to support the new UserData parameter 2022-06-11 01:20:25 -04:00
Martin Mueller
02e847a31e First part of extending callback to include a user parm.
Converted addControl to no longer use C Style function definitions. Now using C++ function overload to support multiple invocation modes.
2022-06-11 00:42:25 -04:00
Martin Mueller
9cb962122c Reworked removeControl function 2022-06-10 12:44:53 -04:00
7056cdf044
Update keywords to max 50 chars
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2022-05-31 08:27:11 +02:00
0f3a808e9e
Bump version
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2022-05-30 21:35:15 +02:00
Ian Gray
e3debb9689 Update output files 2022-05-29 10:14:52 +01:00
Ian Gray
e059fe5d79 Merge branch 's00500-master' 2022-05-29 10:14:02 +01:00
Ian Gray
83e1d0a1c9 Merge branch 'master' of https://github.com/s00500/ESPUI into s00500-master 2022-05-29 10:13:37 +01:00
Ian Gray
59430669af
Merge pull request #176 from pcbbc/master
Added 'type' property to text input elements
2022-05-29 10:00:25 +01:00
pcbbc
834a2a2010 Update README.md 2022-05-24 12:36:12 +01:00
pcbbc
59633c3f74 Merge branch 'master' of https://github.com/pcbbc/ESPUI 2022-05-24 11:21:57 +01:00
pcbbc
a3b253665d Updated documentation 2022-05-24 11:21:34 +01:00
pcbbc
31973aeac9
Update README.md 2022-05-23 14:10:28 +01:00
pcbbc
b47d595194 Update ESPUI.cpp 2022-05-23 00:06:42 +01:00
pcbbc
a53124de42 Added 'type' proptert to text input elements
Now the text input element can support other HTML input types suxh as date, time, color, password, etc
2022-05-22 23:31:48 +01:00
Ian Gray
b28752f9c2 Merge branch 'master' of github.com:iangray001/ESPUI 2022-02-26 20:33:37 +00:00
Ian Gray
a958feb152
Merge pull request #163 from iangray001/master
Fix for #162
2022-02-26 18:04:29 +00:00
Ian Gray
c63537a358 Fix issue where grouped sliders are moved programatically. 2022-02-16 21:10:16 +00:00
Ian Gray
ab5ac2dc1d Fix regression caused by f06781bc03. See comments in commit on Github. 2022-02-16 20:28:55 +00:00
Ian Gray
d77daf0c8e Initialise the enabled value to fix #162 2022-02-16 15:40:31 +00:00
Ian Gray
eb21863e09 Use early return to tidy up logic 2022-02-16 14:52:25 +00:00
Ian Gray
e3e5c34953
Merge pull request #154 from iangray001/enabledisable
Support for Enabling and Disabling controls
2022-02-12 17:43:06 +00:00
Ian Gray
c2dadf536e Fix #158, min/max not being applied correctly to grouped elements. 2022-02-11 20:47:15 +00:00
Ian Gray
0fe60e91a9
Merge branch 'master' into enabledisable 2022-02-11 19:57:36 +00:00
b1fd9f71a4
Merge pull request #155 from d-a-v/emuAsync
minor adjustments for emulation on host via emuAsync lib (see readme)
2022-02-07 14:51:10 +01:00
david gauchard
271fd9dd02 doc: change title (review) 2022-02-05 17:46:42 +01:00
david gauchard
c131a6ad1c +doc 2022-02-02 16:47:43 +01:00
david gauchard
f06781bc03 minor fixes for emulation on host
(https://github.com/d-a-v/emuAsync)
2022-02-02 11:19:43 +01:00
Ian Gray
9a4cb277e9 Also support disabling the Pads 2022-01-31 22:34:00 +00:00
Ian Gray
d8b9c35655 Add active styles to Pad to give click feedback 2022-01-31 22:06:54 +00:00
Ian Gray
896dc97c75 Support dynamic enabling and disabling of controls
See documentation in README for how this works. This commit
handles all the main controls. Pads are not yet supported.
2022-01-31 21:43:09 +00:00
Ian Gray
7dcf6a10f4
Merge pull request #152 from iangray001/master
Vertical controls and a major rehaul of the documentation
2022-01-29 14:52:56 +00:00
Ian Gray
576890e033 Dynamic visibility support
The ability to make controls visible and invisible
was basically already supported, we just need to add
some minor handling in controls.js.
2022-01-28 20:31:25 +00:00
Ian Gray
d9a4854855
Merge branch 's00500:master' into master 2022-01-28 17:02:13 +00:00
Ian Gray
f2fa9ba652 Update header files 2022-01-28 16:57:04 +00:00
Ian Gray
a797ae1afa Update example with vertical controls and more documentation 2022-01-28 16:47:19 +00:00
Ian Gray
c12f97de48 Update documentation to explain vertical layout
Also explains how to label groups of sliders/switchers.
Also makes a tiny tweak to the width of vertical sliders so they are the same width as switchers.
2022-01-28 16:45:26 +00:00
Ian Gray
df0c6faa4d Add updated style header 2022-01-28 15:31:53 +00:00
Ian Gray
ba048185db Add major new example 2022-01-25 21:35:33 +00:00
Ian Gray
64b30d13a6 Major documentation rework 2022-01-25 21:32:34 +00:00
Ian Gray
446f83c6c2
Merge pull request #149 from iangray001/master
One bugfix, one small feature
2022-01-23 17:59:14 +00:00
Ian Gray
334bf16b09 Initial support for vertical switchers and sliders.
Documentation to be added in a later commit.
2022-01-21 23:30:08 +00:00
Ian Gray
9cd15db1ad Add Time control
Adds a new invisible control that can fetch the current time from a
connected client. Documentation is in the README.
2022-01-20 21:50:06 +00:00
Ian Gray
b33be0057f
Merge branch 's00500:master' into master 2022-01-20 20:45:44 +00:00
Ian Gray
bc34078f42 Fix bug with multiple clients
If two clients were connected at the same time, the chunked updates
from one could cause the other to recieve UI_EXTEND messages. This
is fixed by passing the client in to jsonDom.
2022-01-20 20:43:04 +00:00
Ian Gray
fa097ce329
Merge pull request #148 from iangray001/chunkupdates2
Make initial UI update reliable (and 4 small fixes)
2022-01-19 19:32:07 +00:00
Ian Gray
55b291eb50 Support update of Button text 2022-01-16 14:47:41 +00:00
Ian Gray
bc6e2bb8af Correct call to elementHTML 2022-01-15 21:44:53 +00:00
Ian Gray
fed603e219 Fix error in graph HTML output 2022-01-15 15:13:28 +00:00
Ian Gray
12a3fb6c80 Fix bug with sliders getting out of sync. 2022-01-15 14:29:38 +00:00
Ian Gray
9eddf2c504 Improve documentation. 2022-01-15 14:29:03 +00:00
Ian Gray
6a513e9f65 Allow Max control to add maxlength to text input. Update docs. 2022-01-14 20:24:23 +00:00
Ian Gray
254912aee5 Add a null check in updateControl
This means that calling any updates before the GUI is created will
now not cause a crash.
2022-01-13 21:29:22 +00:00
Ian Gray
3b8f71a0f5 Fix a bug where the Dark colour wasn't being correctly applied. 2022-01-13 18:26:50 +00:00
Ian Gray
a9460c8c69 Allow runtime updates to button controls. 2022-01-13 17:26:00 +00:00
Ian Gray
dd0fe3165f Fix bug with updating slider values programatically 2022-01-12 23:53:55 +00:00
Ian Gray
c059e30763 Fix issue with switchers getting out of sync with the DOM if updated. 2022-01-12 23:12:45 +00:00
Ian Gray
5909471962 Further improve the reliability of UI element transfer.
A protocol has been implemented between the server and client to acknowledge
each UI_INITIAL_GUI and UI_EXTEND_GUI from the client javascript. This
prevents the internal websocket buffers from becoming flooded when the
number of controls gets too high.
2022-01-12 20:12:20 +00:00
Ian Gray
cf535110ea
Merge pull request #147 from iangray001/designupdates
Separators, grouped controls, and wide controls
2022-01-09 11:01:46 +00:00
Ian Gray
f8462bcd48 Documentation typos 2022-01-08 21:31:19 +00:00
Ian Gray
f5dd757240 Add support for wide panels.
Allows for panels to be displayed in single column mode, regardless of screen width.
For more information, see updates to README.md
2022-01-08 21:25:10 +00:00
Ian Gray
9b228800f9 Implement separators, and grouped controls
This adds separator elements, and allows arbitrary grouping of controls. For details
see the updates to README.md
2022-01-08 20:58:22 +00:00
16adba2ec3
Bump Version 2022-01-08 17:37:50 +01:00
e3638beb14
Some example improvements by @thomastech
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2022-01-08 17:31:39 +01:00
Ian Gray
29964a83f2
Merge pull request #145 from iangray001/master
Add inline styles to documentation
2022-01-05 22:53:53 +00:00
e1fe13bac6
Implement LITTLEFS as requested by @thomastech in #144
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2022-01-04 11:35:43 +01:00
3cbae2ff1b
Reformat examples
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2022-01-04 11:20:04 +01:00
Ian Gray
cdd0f5bac3 Note that images can be displayed with Labels 2022-01-03 20:19:24 +00:00
Ian Gray
6a7cfd857c Update documentation 2022-01-03 16:21:39 +00:00
Ian Gray
2a5815c579 Fix signed (int) being compared against unsigned (size_t)
This used to emit two warnings about signedness comparison, so is updated to use
an appropriate type.
2022-01-03 15:46:38 +00:00
Ian Gray
7e5331d54f Realign with upstream 2022-01-03 15:39:48 +00:00
Ian Gray
0ab401c3b1 Merge branch 'master' of github.com:s00500/ESPUI 2022-01-03 15:18:49 +00:00
Ian Gray
232ca3ead4
Support for dynamic custom inline styling.
Adds two functions in ESPUI.h:
setPanelStyle()
setElementStyle()
These allow for custom inline CSS styles to be applied to the panel and to
the specific UI element repectively.

For example:

```
char stylecol1[30]
sprintf(stylecol1, "background-color: #%06X;", (unsigned int) random(0x0, 0xFFFFFF));
ESPUI.setPanelStyle(switch1, stylecol1);
```
This will set the panel of the given control to a random hex colour.

This is supported by both the initial UI message, and by control update messages, so you
can change these styles dynamically in response to other events.

setElementStyle() is not perfect. Because CSS inline styles can only style one specific
DOM element, for controls made up of multiple elements (like the "pad") this is limited.
I have tried to make an appropriate choice for each supported control.
2022-01-03 13:06:55 +01:00
Ian Gray
06460fcc4d
Chunk updates 2022-01-03 13:06:33 +01:00
Ian Gray
8331255355
Add feedback to buttons when being pessed. One way to address #110. 2022-01-03 13:06:33 +01:00
Ian Gray
6800f0c208
Fixes #122 2022-01-03 13:06:33 +01:00
Ian Gray
6f744a7995
Update minified and header files for previous commit 2022-01-03 13:05:53 +01:00
Ian Gray
c5846ca644
Fixes #127 2022-01-03 13:05:53 +01:00
19e187a280
Add PIO Example
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2022-01-03 13:03:07 +01:00
Ian Gray
ec1862cfe6 Support for dynamic custom inline styling.
Adds two functions in ESPUI.h:
setPanelStyle()
setElementStyle()
These allow for custom inline CSS styles to be applied to the panel and to
the specific UI element repectively.

For example:

```
char stylecol1[30]
sprintf(stylecol1, "background-color: #%06X;", (unsigned int) random(0x0, 0xFFFFFF));
ESPUI.setPanelStyle(switch1, stylecol1);
```
This will set the panel of the given control to a random hex colour.

This is supported by both the initial UI message, and by control update messages, so you
can change these styles dynamically in response to other events.

setElementStyle() is not perfect. Because CSS inline styles can only style one specific
DOM element, for controls made up of multiple elements (like the "pad") this is limited.
I have tried to make an appropriate choice for each supported control.
2022-01-02 21:56:32 +00:00
Ian Gray
78317ce5f2 Chunk updates 2022-01-01 22:04:32 +00:00
Ian Gray
1d78608786 Add feedback to buttons when being pessed. One way to address #110. 2021-12-29 23:01:01 +00:00
Ian Gray
aaea0fb877 Fixes #122 2021-12-29 17:52:03 +00:00
Ian Gray
1df56772d9 Fixes #136 and also severe bug in addControl 2021-12-29 16:37:48 +00:00
Ian Gray
eebefd915c Update minified and header files for previous commit 2021-12-29 10:29:24 +00:00
Ian Gray
777ceb2bed Fixes #127 2021-12-28 17:13:25 +00:00
c66f528702
Send visibility
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2021-10-29 19:47:46 +02:00
aa03c1683d
Add Port Option
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2021-10-29 19:37:56 +02:00
6b3056ab31
Merge pull request #131 from Noctr/master 2021-08-10 08:17:29 +02:00
Noctr
95d13ec5a9
Update ESPUI.h 2021-08-06 21:40:10 +07:00
Noctr
de0c74ab4b
Update ESPUI.h 2021-08-06 21:33:53 +07:00
Noctr
1a8407a0ec
Update ESPUI.h 2021-08-01 23:54:50 +07:00
Noctr
5bec1ed988
Update dataControlsJS.h 2021-08-01 23:50:26 +07:00
Noctr
98ec85ea8b
Update controls.min.js 2021-08-01 23:45:49 +07:00
Noctr
6a9c989766
Update controls.js 2021-08-01 23:38:13 +07:00
0587918621
Merge pull request #109 from A-damW/master
Update README.md
2021-02-06 09:42:08 +01:00
48826caee6
Merge pull request #114 from tecteun/master
slider sends (browser dependent) lots of events, throttle using only …
2021-02-06 09:41:26 +01:00
tecteun
9ab8a84ff0 slider sends (browser dependent) lots of events, throttle using only unique values. 2021-02-05 22:03:02 +00:00
Adam W
d12da60df4
Update README.md
Minor typo, line 107, "to to" > "to do"
2021-01-10 08:20:16 +00:00
8cdedaf3cb
Merge pull request #106 from marcusmiess/master-fix-pad-arrows
Fix for pad arrows
2021-01-02 10:10:54 +01:00
Marcus Miess
02d981cc2b Changed the ascii arrow to the HTML equivalent. Fixes the problem, where the pad arrow strings got broken. 2021-01-02 00:23:13 +01:00
4827688635
Version 2.0.2
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-10-19 08:57:59 +02:00
b71bc81c0d
Fixing rebase errors with littlefs/debug refactor
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-10-18 11:06:38 +02:00
a6ddd48abb
Fix all other occurences
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-10-17 22:46:22 +02:00
8c0161b181
Fix prepare fs example
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-10-16 14:47:32 +02:00
3cf1aa7f49
Fix littleFS does not exist on esp32
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-10-16 14:47:29 +02:00
313a069d4c
Change idcounter to start at 1, closes #95 2020-10-02 19:08:45 +02:00
34d974b03b
Merge pull request #97 from ericBcreator/add_tab_callback_function
Add tab callback function
2020-10-02 19:04:26 +02:00
ericBcreator
1de52c939f
Add files via upload 2020-10-01 20:28:22 +02:00
ericBcreator
950a1fb029
Add files via upload 2020-10-01 20:27:01 +02:00
ericBcreator
5a167091cc
Update controls.js 2020-10-01 18:57:24 +02:00
ericBcreator
57a81dbee3
Update ESPUI.cpp 2020-10-01 18:51:54 +02:00
ericBcreator
acaf6898fd
Update controls.js 2020-10-01 18:49:18 +02:00
37bbb9208d
Merge pull request #91 from enwi/master
Reduce HEAP usage
2020-10-01 18:37:45 +02:00
Moritz Wirger
6b2ef81b12 Fix include of ESPUI header 2020-10-01 18:04:28 +02:00
Moritz Wirger
1e5ee117c5 Use DEBUG_ESPUI to en/disable debug code from being compiled
Include clang-format file for formatting code and format code
2020-10-01 18:04:28 +02:00
Moritz Wirger
db4164f621 Reduce heap usage by using F and PSTR 2020-10-01 18:04:28 +02:00
Moritz Wirger
bfd645d7a1 Use const String& to reduce IROM usage 2020-10-01 18:04:28 +02:00
99cf344d93
Changes suggested in #93
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-09-24 21:50:28 +02:00
291ff8ed80
Bump verison
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-08-26 22:17:18 +02:00
cda1a573d6
cleanup
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-08-26 22:16:02 +02:00
6506f6fe1c
Fixing sliders not updating properly
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-08-26 22:16:02 +02:00
eec13e4934
No reload per default, just send JsonDom 2020-08-26 22:15:56 +02:00
ruslan.teliuk@aspose.com
81366af7f1
Add remControl() method for remove contols 2020-08-26 22:13:38 +02:00
1b7af71d29
Fix littlefs include
Signed-off-by: Lukas Bachschwell <lukas@lbsfilm.at>
2020-08-26 22:13:21 +02:00
c02f357d84
Merge pull request #89 from bastiengrignon/feature/spiffs-update
Update filesystem
2020-06-30 19:30:59 +02:00
Bastien
fffe4a8641 Update filesystem from deprecated SPIFFS to LittleFS 2020-06-30 12:39:51 +02:00
585c1608b8
Fix update_gauge typo, Close #69 2020-06-01 18:09:15 +02:00
5a6b92bb5f
Closes #74 Adds chinese facilino translation 2020-06-01 18:09:15 +02:00
54aeaacf86
Merge pull request #64 from per1234/depends
Specify library dependencies in library.properties
2020-04-03 10:14:39 +02:00
3afd518399
Connect to correct websocket on different port 2020-01-27 13:13:47 +01:00
per1234
65dc2d81a3
Specify library dependencies in library.properties
Specifying the library dependencies in the depends field of library.properties causes the Arduino Library Manager (Arduino IDE 1.8.10 and newer) to offer to install any missing dependencies during installation of this library. "arduino-cli lib install" will automatically install the dependencies (arduino-cli 0.7.0 and newer).
2020-01-06 00:09:22 -08:00
22f6b3922e
Update library.json
Remove ArduinoJSON version constraint
2019-12-30 20:02:12 +01:00
e5475bc099
Merge pull request #51 from s00500/2.0.0
WIP: 2.0.0
2019-12-29 15:05:19 +01:00
301fe0e906
Merge branch 'master' into 2.0.0 2019-12-29 15:05:00 +01:00
36fce6bf25
Final Updates for 2.0 Readme 2019-12-29 15:03:52 +01:00
e0ee932fff
new tab image 2019-12-29 14:50:09 +01:00
71576d7686
More ducumentation 2019-12-29 14:35:54 +01:00
2b4141fed3
Readme getting ready for 2.0 2019-12-28 23:32:45 +01:00
c5dd493cb0
fixing compile issues 2019-12-28 22:28:55 +01:00
daede8799a
sync up examples 2019-12-28 21:30:57 +01:00
f00f7601f4
Some updates to gui example 2019-12-28 15:08:23 +01:00
bd7e324a31
fix sliderupdate 2019-12-28 15:05:27 +01:00
9764db9789
Increase timeout for connecting existing network and add continuous slider mode #60 2019-12-28 14:54:41 +01:00
681a00b3ed
reformate slider 2019-12-28 14:17:29 +01:00
79046d7bd0
remove graph logging 2019-12-27 20:27:10 +01:00
4b0f8e86b4
#10 Enable storing to localstorage 2019-12-27 16:57:11 +01:00
bcddcfc311
#63 add variabbles to public scope of espui 2019-12-27 16:30:15 +01:00
fe45ed8010
#63 Add variables for jsonDynamicDocument Sizes 2019-12-27 16:27:42 +01:00
0323920a0d
Rename new api and some readme cleaning 2019-12-27 15:43:36 +01:00
fcc80b5843
Remove accel from example 2019-12-27 15:37:08 +01:00
9e5756ceef
Update Roadmap 2019-12-27 15:36:54 +01:00
e317d25977
Make AsyncServer instance Pubblic 2019-12-27 15:36:24 +01:00
75ec2590f6
Update js stuff 2019-12-27 15:36:12 +01:00
80621bda22
update version in properties file 2019-12-27 15:33:55 +01:00
c5c6e37dfb
Patch version bump 2019-05-07 09:09:04 +02:00
b03ea9ded7
Patch version pump 2019-05-07 09:08:37 +02:00
a341052c40
Merge pull request #52 from Flawededge/patch-2
Force version 5 ArudinoJson
2019-05-07 09:07:24 +02:00
Chris Diggle
acea3c7d4d
Force version 5 ArudinoJson
When using PIO to auto download libraries, the latest v6 json is used, so forcing v5 is required
2019-05-07 11:32:41 +12:00
79f509da74 #10 Graph points working
- timestap still not great
2019-04-15 15:32:14 +02:00
bff259008f Graph Frontend work
- Adds graph js file
- Adds graph styles
2019-04-15 13:49:15 +02:00
36cfe78205 Knowing websocket msg string length 2019-04-15 12:41:22 +02:00
2c6aaf82f4 two strings less 2019-04-15 12:38:09 +02:00
043ba99ea9 Adding basic structure for new widgets 2019-03-26 16:22:21 +01:00
3c69f013fc Proper wrappers
- update order of params of create functions to be simillar
- changed all numbers to be numbers
- split pad creation function
- updated examples
2019-03-24 19:18:53 +01:00
650411bac4 Consistent use of updateControl on websocket event
- rename updateControl to updateControlValue
- some earlie returns
2019-03-24 18:46:34 +01:00
b66d41a98b more reformating 2019-03-24 18:18:08 +01:00
218ebc67d9 Style change again 2019-03-24 18:10:21 +01:00
70288fc69f Hide tabsnav on :empty 2019-03-24 16:15:30 +01:00
1bb5d16082 Update name 2019-03-24 16:08:05 +01:00
a37ae5eb70 readme update 2019-03-24 16:06:42 +01:00
63b6761044 Cleanup and reformat header
- Construct inside library
- Adds setVerbosity
2019-03-24 16:06:35 +01:00
b9a087c169 Use ArduinoJson 6.10.0 2019-03-24 15:44:27 +01:00
fd12f7ad2a Version Bump 2019-03-24 15:37:47 +01:00
41563454af Update readme with roadmap for 2.0.0 2019-03-24 15:37:37 +01:00
Christian Riggenbach
6873052b6e Added new features, removed dependency on unique labels
- added Min/Max/Step for numbers and sliders
- labels don't have to be unique anymore; controls can't be updated by labels
- new Slider: JS + CSS
2019-03-19 09:34:16 +01:00
Christian Riggenbach
7125374fa3 Color of elementes are now updateable, reformatted control.js 2019-03-08 22:24:20 +01:00
Christian Riggenbach
00d996d8dd The Pad works again
Don't set the style of all the <ul> and <li> in the css, use the class
2019-03-08 21:17:28 +01:00
Christian Riggenbach
b987828a25 Preselect the right option in the select-input 2019-03-06 00:18:19 +01:00
Christian Riggenbach
d0c59ac659 Small bug: don't set the type to Button in ESPUIClass::slider() 2019-03-04 21:08:52 +01:00
Christian Riggenbach
6178e4fc22 Added the dropdown-Control
* added the Control
* added the frontend-code
* added the control to the examples "gui-newAPI.ino" and "tabbedGui.ino"
2019-03-04 21:07:39 +01:00
Christian Riggenbach
3c42b43fe6 Changed signature of the callback
Call the callback with a pointer instead of a copy of the Control.
Changed all the examples
2019-03-04 21:05:13 +01:00
Christian Riggenbach
2b31e81f50 instantiate ESPUI in prepareFileSystem.ino too 2019-03-03 23:38:29 +01:00
Christian Riggenbach
4ea7928fd5 Added Tabbed View
* new member of Control: parentControl
* changed addControl() to add children of elements
* added some styles in the css
* two new divs in index.html
* added frontend code to controls.js
* added new demo to demonstrate the tabbed view
2019-03-03 23:33:15 +01:00
Christian Riggenbach
50de3dad87 Added tabbedcontent.js (from https://github.com/elboletaire/tabbedcontent) 2019-03-03 23:27:11 +01:00
Christian Riggenbach
acce17b82c IDs are uint16_t, removed not used member ESPUIClass::cIndex 2019-03-03 23:27:11 +01:00
Christian Riggenbach
6c8f113861 Added a Demo with the new API 2019-03-03 23:27:04 +01:00
Christian Riggenbach
a4989b4eb0 Reordered arguments of ESPUIClass::addControl
The arguments value, color and callback have defaults
2019-03-03 21:50:06 +01:00
Christian Riggenbach
37ce571b9c added ESPUI::updateLabel (works like ESPUI::print) 2019-03-03 21:46:38 +01:00
Christian Riggenbach
6810f7432f Moved examples/gui/data to data/ and adjusted tools/*.py 2019-03-03 21:23:39 +01:00
Christian Riggenbach
e542ce0178 Updated Demo for changes in the API
updated the gui.ino to reflect the changes in the API:
* reformated/reindented, minor cleanups
* instantation of ESPUI in the users application
* automatic swichtover to station mode if given network is not found
2019-03-03 21:17:49 +01:00
Christian Riggenbach
8865416331 Updated API
* Sourcecode reindented/reformated, added scopes to all the ifs
* Linked list for holding all the controls
* IDs are autogenerated, Control is now a class
* generalised API for creating controls, removed a lot of redundant code
* a lot of glue for the old API
* check if callback exists before calling it
* Instantation moved out of ESPUI.cpp, must be in the users application
* verbose printing on the serial line dependent of instantation ESPUI(...)
* streamlined begin(...), make authentification optional
2019-03-03 21:13:45 +01:00
1529874094 Note on Arduino JSON 2019-02-26 16:15:37 +01:00
2fae44f387 remove color dark, version bump 2019-02-26 16:04:41 +01:00
4f421c84d5 #47 Adding Dark Color, correcting wrong numbering for colors 2019-02-26 12:08:37 +01:00
b21c5d3b2c 1.6.1 2018-12-27 11:37:50 +01:00
98d1215d7a #44 Adding define to reenable WS BasicAuth 2018-12-27 11:34:28 +01:00
7a10457f99 #44 Adding Basic Auth
- Also authing websockets
- Implemented on begin and beginSpiffs
- Added notes to Gui example
2018-12-26 13:38:38 +01:00
f31575b50c #43 Sending Initial GUI as one big array
- Added new  INITIAL_GUI Type
- spliting GUI Blob to events in controls js
- formating the json in jsonDom into one big array
2018-12-26 12:35:35 +01:00
980e20818f
Merge pull request #42 from don41382/patch-2
udpateSlider implementation with label was missing
2018-12-02 14:22:43 +01:00
Felix Eckhardt
e9aca78c9c
udpateSlider implementation with label was missing 2018-12-02 11:41:45 +01:00
a56f5decc7 Update issue templates 2018-11-29 11:49:18 +01:00
02a21ec747
Update README.md 2018-11-27 22:21:39 +01:00
24258da42d
Update README.md 2018-11-27 22:20:51 +01:00
37bb44066b
Merge pull request #38 from orithena/feature-style-input
Input style now similar to switches, fixed max-width
2018-11-27 22:18:51 +01:00
Dave Kliczbor
1d7da26dcd Input style now similar to switches, fixed max-width 2018-11-27 22:01:59 +01:00
999da37e11 1.6.0 2018-11-26 18:32:09 +01:00
7d46a4de96 #9 #21 Adds Text input / Number input Support
also loads of reformating
2018-11-26 18:25:10 +01:00
870e8a06a2 Closes #25 Adding captive Portal to example 2018-11-26 17:02:08 +01:00
8fa4456fa3
Merge pull request #37 from orithena/cleanup-git-and-minifier
Some cleanups and documentation updates
2018-11-26 09:09:57 +01:00
Dave Kliczbor
9b41a0f8b8 Clarified help strings and README 2018-11-25 00:32:23 +01:00
Dave Kliczbor
3aae5954f2 Cleaned up git status, cleaned prepare_static_ui_sources.py, mentioned the latter in README 2018-11-24 17:20:35 +01:00
b3ab9cfb1a
Merge pull request #36 from orithena/bugfix-htmlentity
Bugfix: Inserting htmlentities via jquery requires .html(), not .text()
2018-11-21 08:50:06 +01:00
Dave Kliczbor
d38dac9c4d Bugfix: Inserting htmlentities via jquery requires .html(), not .text() 2018-11-20 20:00:39 +01:00
1c17252b93
Merge pull request #32 from gschintgen/missing-json-dep
add missing ArduinoJson dependency in library.json
2018-11-20 12:37:45 +01:00
22f1806692
Merge pull request #35 from orithena/feature-reinit-on-page-visible
Feature: UI reinit on page visible
2018-11-19 23:18:43 +01:00
Dave Kliczbor
3a905e646a Feature: UI reinit on page visible 2018-11-19 22:23:10 +01:00
Gilles Schintgen
36a94bebe9 add missing ArduinoJson dependency in library.json 2018-11-16 20:50:01 +01:00
5ba42e3361 Versionbump 2018-10-28 22:27:32 +01:00
11422a3b43 Changing text for no connection box 2018-10-28 22:19:14 +01:00
ec0b519fe3 Merge branch 'feature-restart-ui' of github.com:orithena/ESPUI 2018-10-28 21:47:51 +01:00
74d984128b Merge branch 'feature-largetouch' of github.com:orithena/ESPUI 2018-10-28 21:47:06 +01:00
Dave Kliczbor
82adb0f1e1 Enlarge slider controls for touchscreen devices 2018-10-28 13:32:27 +01:00
Dave Kliczbor
6219d4302b 'No Connection' label is now clickable to reinitialize 2018-10-28 13:27:31 +01:00
5b2cec59db
Merge pull request #28 from orithena/bugfix-touchmove
Fixed touchmove problem for at least some mobile browsers
2018-10-27 11:32:34 +02:00
c437b11409
Merge pull request #29 from orithena/feature-headerscript
Script to regenerate client minified/header files from sources
2018-10-27 11:30:33 +02:00
Dave Kliczbor
33daac87f1 Added script to regenerate client minified/header files from sources 2018-10-26 19:13:43 +02:00
Dave Kliczbor
3b3dee7e9a Fixed touchmove problem for at least some mobile browsers 2018-10-26 19:04:05 +02:00
5fb64d4e73 Prepare 1.5.3 2018-07-03 18:01:42 +02:00
30a91bdb85
Merge pull request #20 from wvdv2002/master
Refactored debug define into DEBUG_ESPUI
2018-07-03 18:00:12 +02:00
wvdv2002
600e46c457 refactored debug define into DEBUG_ESPUI 2018-07-03 17:43:58 +02:00
77 changed files with 9663 additions and 2274 deletions

58
.clang-format Executable file
View File

@ -0,0 +1,58 @@
---
# 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

35
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@ -0,0 +1,35 @@
---
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.

View File

@ -0,0 +1,17 @@
---
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.

10
.gitignore vendored
View File

@ -26,3 +26,13 @@
Network Trash Folder
Temporary Items
.apdisk
# Linux
# =========================
# Backup files produced by some editors
*~
*.bak
.vscode/

756
README.md
View File

@ -1,165 +1,723 @@
# ESPUI
![ESPUI](https://github.com/s00500/ESPUI/blob/master/docs/ui_complete.png)
![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)
ESPUI is a simple library to make a web user interface for your projects using the **ESP8266** or the **ESP32**
It uses web sockets and lets you create, control, and update elements on your GUI through multiple devices like phones and tablets.
### Contributed features
ESPUI uses simple Arduino-style syntax for creating a solid, functioning user interface without too much boilerplate code.
- 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
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.
## Roadmap
I completely rewrote the EasyUI Library created by ayushsharma82 [Here](https://github.com/ayushsharma82/)
Now it uses ESPAsyncWebserver and is mainly to be used with the ESP32 Processor.
- Fully implement graphs
- Expand number input features (floats etc.)
- Support for enabling and disabling controls
## Dependencies
This library is dependent on the following libraries to function properly.
This library is dependent on the following libraries.
- [ESPAsyncWebserver](https://github.com/me-no-dev/ESPAsyncWebServer)
- [ArduinoJson](https://github.com/bblanchon/ArduinoJson)
**Plus for ESP8266**
- [ESPAsyncTCP](https://github.com/me-no-dev/ESPAsyncTCP)
**Additionally necessary for ESP32**
- [AsyncTCP](https://github.com/me-no-dev/AsyncTCP)
- [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:
#### Directly Through Arduino IDE (*recommended*)
#### Using PlatformIO (_recommended_)
You can find this Library in the Arduino IDE library manager
Go to Sketch > Include Library > Library Manager > Search for "ESPUI" > Install
Just include this library as a dependency in `lib_deps` like so:
#### Manual Install
```
lib_deps =
ESPUI
ESP Async WebServer
ESPAsyncTCP # (or AsyncTCP on ESP32)
LittleFS_esp32 # (ESP32 only)
```
For Windows: Download the [Repository](https://github.com/s00500/ESPUI/archive/master.zip) and extract the .zip in Documents>Arduino>Libraries>{Place "ESPUI" folder Here}
#### Using the Arduino IDE (_recommended_)
For Linux: Download the [Repository](https://github.com/s00500/ESPUI/archive/master.zip) and extract the .zip in Sketchbook/Libraries/{Place "ESPUI" folder Here}
You can find this Library in the Arduino IDE library manager. Go to
`Sketch > Include Library > Library Manager` search for `ESPUI` and install.
For macOs: Download the [Repository](https://github.com/s00500/ESPUI/archive/master.zip) and extract the .zip in ~/Documents/Arduino/libraries/{Place "ESPUI" folder Here}
#### Manually through IDE
Download the [Repository](https://github.com/s00500/ESPUI/archive/master.zip), Go to Sketch>Include Library>Add .zip Library> Select the Downloaded .zip File.
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 webinterface. This can be achieved in 2 wasy:
*PROGMEM* or *SPIFFS*
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!*
_When `ESPUI.begin()` is called the default is serving files from Memory and
ESPUI should work out of the box!_
But if this causes your program to *use too much memory* you can burn the files into the SPIFFS 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()`
**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*)
#### 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 to 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 that is already saved in the chip's filesystem and you have more programm memory to work with.
#### Manual way (mainly for development)
To do this download and install me-no-devs wonderful [ESP32 sketch data uploader](https://github.com/me-no-dev/arduino-esp32fs-plugin) or for ESP8266 [ESP8266 sketch data uploader](https://github.com/esp8266/arduino-esp8266fs-plugin)
Then open the **gui** example sketch and select "Upload Sketch Data" from the Tools menu for your processor.
Now you are set to go and use any code you want to with this library
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 (updateable)
- Button
- Switch (updateable)
- Control pad
- Control pad with center button
- Slider
Checkout the example for the usage
## Available colors:
- Label
- Button
- Switch
- Control pad
- Slider
- Text Input
- Date, Time, Colour and Password Input
- Numberinput
- Option select
- Separator
- Time
- Graph (partial implementation)
- File Display
- COLOR_TURQUOISE
- COLOR_EMERALD
- COLOR_PETERRIVER
- COLOR_WETASPHALT
- COLOR_SUNFLOWER
- COLOR_CARROT
- COLOR_ALIZARIN
- COLOR_NONE
## Roadmap :
- ~~Setup SPIFFS using values in program memory~~
- ~~ESP8266 support~~
- ~~PlattformIO Integration~~
- ~~Multiline Labels~~
- ~~GZip Files and serve from memory~~
- Datagraph output -> *WIP*
- Number input -> *WIP*
- Text input -> *WIP*
- proper return value (as int and not as string) for slider
- Maybe a slider range setting, meanwhile please use *map()*
- Improve slider stability
## 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 Click Events Etc. The communication between the *ESP32* and the client browser works using web sockets.
ESPUI does not need network access and can be used in standalone access point mode.
All assets are loaded from the internal SPIFFS filesystem of the ESP32.
This section will explain in detail how the Library is to be used from the Arduino code side. As of now the Facilino blocks are not implemented.
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” 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. Here is an overview of the currently implemented different elements of the UI library:
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.
<br><br>
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.
<br><br>
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.
<br><br>
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.
<br><br>
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
}
}
```
<br>
<br>
#### Button
![Buttons](https://github.com/s00500/ESPUI/blob/master/docs/ui_button.png)
![Buttons](docs/ui_button.png)
Buttons have a name and a callback value. They have one event for press and one for release.
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](https://github.com/s00500/ESPUI/blob/master/docs/ui_switches.png)
![Switches](docs/ui_switches.png)
Switches sync their state on all connected devices. This means when you change their value they change visibly on all tablets or computers that currently display the interface. They also have two types of events: one for turning on and one for turning off.
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](https://github.com/s00500/ESPUI/blob/master/docs/ui_controlpad.png)
![control pads](docs/ui_controlpad.png)
Button pads come in two flavours: with or without a center button. They are very useful for con-trolling all kinds of movements of vehicles or also of course our walking robots. They use a single callback per pad and have 8 or 10 different event types to differentiate the button actions.
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](https://github.com/s00500/ESPUI/blob/master/docs/ui_labels.png)
![labels](docs/ui_labels.png)
Labels are a nice tool to get information from the robot to the user interface. This can be done to show states, values of sensors and configuration parameters. To send data from the code use `ESP.print(labelId, “Text”);` . Labels get a name on creation and a initial value. The name is not changeable once the UI initialised.
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 `<br>` 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 `<img>` tag.
```
ESPUI.label("An Image Label", ControlColor::Peterriver, "<img src='path/to/image'>");
```
This requires that the client has access to the image in question, either from the internet or a local web server.
Labels automatically wrap your text. If you want them to have multiple lines use the normal `<br>` tag in the string you print to the label
#### Slider
![labels](https://github.com/s00500/ESPUI/blob/master/docs/ui_slider.png)
![slider](docs/ui_slider.png)
The Slider can be used to slide through a value from 1 to 100. Slides provide realtime data, are touch compatible and can be used to for example control a Servo. The current value is shown while the slider is dragged in a little bubble over the handle.
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()`.
#### Initialisation of the UI
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()`:
After all the elements are configured you can use `ESPUI.begin(“Some Title”);` to start the UI interface. (Or `ESPUI.beginSPIFFS(“Some Title”);` respectively) Make sure you setup a working network connection or AccesPoint **before** (See example). The web interface can then be used from multiple devices at once and also shows an connection status in the top bar.
The library is designed to be easy to use and can still be extended with a lot of more functionality.
```
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
All changes to the client side files can be made in the examples/gui/data directory. Using the file uploader thin can be used for development. After this you have to compress them and then you can gzip them. I wrote a little useful jsfiddle for this, [CHECK IT OUT](https://jsfiddle.net/s00500/yvLbhuuv/)
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/3).
Liked this Library? You can **support** me by sending me a :coffee:
[Coffee](https://paypal.me/lukasbachschwell/5).
Otherwise I really welcome **Pull Requests**.

View File

@ -111,7 +111,7 @@
}
svg:not(:root) {
overflow: hidden;
overflow: visible;
}
/* Grouping content

1
data/css/normalize.min.css vendored Normal file
View File

@ -0,0 +1 @@
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}

1200
data/css/style.css Normal file

File diff suppressed because it is too large Load Diff

1
data/css/style.min.css vendored Normal file

File diff suppressed because one or more lines are too long

35
data/index.htm Normal file
View File

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Control</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="shortcut icon"
href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAPFBMVEUAAACA1VWR21qQ2liR3FqR3FqS3VuR3VqR3VuR3VqO21mS21uS3FqS3FqS21uJ2GKQ21qR3FuR3FoAAAB/3Gu7AAAAEnRSTlMABoA3kPBwz8i5Kzioxg4NVcU3uEJHAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAAN1wAADdcBQiibeAAAAAd0SU1FB+EFEhcEM+HpYwQAAABYSURBVBjThY/JDsAgCESt4lpX/v9jLQZJ6qF9t3khAyj1xXUKbQ4BVowDwqOYgExkkW4iY6lPaF06RqM8YItOuRbMaz6xjbsusDAW/drplBg47jP696cXE8bPA1eUDeK2AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTA1LTE4VDIzOjA0OjUxKzAyOjAwxE59ewAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0wNS0xOFQyMzowNDo1MSswMjowMLUTxccAAAAZdEVYdFNvZnR3YXJlAHd3dy5pbmtzY2FwZS5vcmeb7jwaAAAAAElFTkSuQmCC"
/>
<link rel="stylesheet" href="/css/normalize.css" />
<link rel="stylesheet" href="/css/style.css" />
<script src="/js/zepto.min.js"></script>
<script src="/js/slider.js"></script>
<script src="/js/graph.js"></script>
<script src="/js/controls.js"></script>
<script src="/js/tabbedcontent.js"></script>
</head>
<body onload="javascript:start();">
<div>
<h4>
<div id="mainHeader">Control</div>
<span id="conStatus" class="label">Offline</span>
</h4>
</div>
<hr />
<div class="container">
<div id="row" class="row u-full-width"></div>
<ul id="tabsnav" class="navigation navigation-tabs u-full-width"></ul>
<div id="tabscontent" class="tabscontent u-full-width"></div>
</div>
</body>
</html>

1
data/index.min.htm Normal file
View File

@ -0,0 +1 @@
<!DOCTYPE html><html> <head><meta charset=utf-8><title>Control</title><meta name=viewport content="width=device-width, initial-scale=1"><link rel="shortcut icon" href=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAPFBMVEUAAACA1VWR21qQ2liR3FqR3FqS3VuR3VqR3VuR3VqO21mS21uS3FqS3FqS21uJ2GKQ21qR3FuR3FoAAAB/3Gu7AAAAEnRSTlMABoA3kPBwz8i5Kzioxg4NVcU3uEJHAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAAN1wAADdcBQiibeAAAAAd0SU1FB+EFEhcEM+HpYwQAAABYSURBVBjThY/JDsAgCESt4lpX/v9jLQZJ6qF9t3khAyj1xXUKbQ4BVowDwqOYgExkkW4iY6lPaF06RqM8YItOuRbMaz6xjbsusDAW/drplBg47jP696cXE8bPA1eUDeK2AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTA1LTE4VDIzOjA0OjUxKzAyOjAwxE59ewAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0wNS0xOFQyMzowNDo1MSswMjowMLUTxccAAAAZdEVYdFNvZnR3YXJlAHd3dy5pbmtzY2FwZS5vcmeb7jwaAAAAAElFTkSuQmCC><link rel=stylesheet href=/css/normalize.css><link rel=stylesheet href=/css/style.css><script src=/js/zepto.min.js></script><script src=/js/slider.js></script><script src=/js/graph.js></script><script src=/js/controls.js></script><script src=/js/tabbedcontent.js></script></head> <body onload=javascript:start();> <div> <h4> <div id=mainHeader>Control</div> <span id=conStatus class=label>Offline</span> </h4> </div> <hr> <div class=container> <div id=row class="row u-full-width"></div> <ul id=tabsnav class="navigation navigation-tabs u-full-width"></ul> <div id=tabscontent class="tabscontent u-full-width"></div> </div> </body> </html>

1131
data/js/controls.js vendored Normal file

File diff suppressed because it is too large Load Diff

136
data/js/controls.min.js vendored Normal file
View File

@ -0,0 +1,136 @@
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 &#8635;");$("#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("<li><a onmouseup='tabclick("+data.id+")' href='#tab"+data.id+"'>"+data.value+"</a></li>");$("#tabscontent").append("<div id='tab"+data.id+"'></div>");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("<option id='option"+
data.id+
"' value='"+
data.value+
"' "+
data.selected+
">"+
data.label+
"</option>");}
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){processEnabled(data);}
if(data.type>=UPDATE_OFFSET&&data.type<UI_INITIAL_GUI){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;$("#"+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);}
async function downloadFile(filename)
{let response=await fetch(filename);if(response.status!=200){throw new Error("File Read Server Error: '"+response.status+"'");}
let text_data=await response.text();return text_data;}
function StartFragmentAssemblyTimer(Id)
{StopFragmentAssemblyTimer(Id);FragmentAssemblyTimer[Id]=setInterval(function(_Id)
{if("undefined"!==typeof controlAssemblyArray[_Id])
{if(null!==controlAssemblyArray[_Id])
{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});}else{$(this).on({change:slidercb});}
$(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){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="<div id='id"+data.id+"' "+panelStyle+" class='two columns "+panelwide+" card tcenter "+
colorClass(data.color)+"'><h5>"+data.label+"</h5><hr/>"+
elementHTML(data)+
"</div>";break;case UI_SEPARATOR:html="<div id='id"+data.id+"' "+panelStyle+" class='sectionbreak columns'>"+
"<h5>"+data.label+"</h5><hr/></div>";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"<span id='l"+id+"' "+elementStyle+
" class='label label-wrap'>"+data.value+"</span>";case UI_FILEDISPLAY:return"<textarea id='fd"+id+"' rows='4' "+elementStyle+
" class='label label-wrap'>"+"</textarea>";case UI_BUTTON:return"<button id='btn"+id+"' "+elementStyle+
" onmousedown='buttonclick("+id+", true)'"+
" onmouseup='buttonclick("+id+", false)'>"+
data.value+"</button>";case UI_SWITCHER:return"<label id='sl"+id+"' "+elementStyle+
" class='switch "+(data.value=="1"?"checked":"")+
(data.hasOwnProperty('vertical')?" vert-switcher ":"")+
"'>"+
"<div class='in'>"+
"<input type='checkbox' id='s"+id+"' onClick='switcher("+id+",null)' "+
(data.value=="1"?"checked":"")+"/></div></label>";case UI_CPAD:case UI_PAD:return"<nav class='control'><ul>"+
"<li><a onmousedown='padclick(UP, "+id+", true)' "+
"onmouseup='padclick(UP, "+id+", false)' id='pf"+id+"'>&#9650;</a></li>"+
"<li><a onmousedown='padclick(RIGHT, "+id+", true)' "+
"onmouseup='padclick(RIGHT, "+id+", false)' id='pr"+id+"'>&#9650;</a></li>"+
"<li><a onmousedown='padclick(LEFT, "+id+", true)' "+
"onmouseup='padclick(LEFT, "+id+", false)' id='pl"+id+"'>&#9650;</a></li>"+
"<li><a onmousedown='padclick(DOWN, "+id+", true)' "+
"onmouseup='padclick(DOWN, "+id+", false)' id='pb"+id+"'>&#9650;</a></li>"+
"</ul>"+
(data.type==UI_CPAD?"<a class='confirm' onmousedown='padclick(CENTER,"+id+", true)' "+
"onmouseup='padclick(CENTER, "+id+", false)' id='pc"+id+"'>OK</a>":"")+
"</nav>";case UI_SLIDER:return"<div class='range-slider "+
(data.hasOwnProperty('vertical')?" vert-slider ":"")+
"'>"+
"<input id='sl"+id+"' type='range' min='0' max='100' value='"+data.value+"' "+
elementStyle+" class='range-slider__range'><span class='range-slider__value'>"+
data.value+"</span></div>";case UI_NUMBER:return"<input style='color:black; "+data.elementStyle+"' id='num"+id+
"' type='number' value='"+data.value+"' onchange='numberchange("+id+")' />";case UI_TEXT_INPUT:return"<input "+inputType+"style='color:black; "+data.elementStyle+"' id='text"+id+
"' value='"+data.value+"' onchange='textchange("+id+")' />";case UI_SELECT:return"<select style='color:black; "+data.elementStyle+"' id='select"+id+
"' onchange='selectchange("+id+")' />";case UI_GRAPH:return"<figure id='graph"+id+"'><figcaption>"+data.label+"</figcaption></figure>";case UI_GAUGE:return"WILL BE A GAUGE <input style='color:black;' id='gauge"+id+
"' type='number' value='"+data.value+"' onchange='numberchange("+id+")' />";case UI_ACCEL:return"ACCEL // Not implemented fully!<div class='accelerometer' id='accel"+id+
"' ><div class='ball"+id+"'></div><pre class='accelerometeroutput"+id+"'></pre>";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;}}

297
data/js/graph.js Normal file
View File

@ -0,0 +1,297 @@
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);
}

15
data/js/graph.min.js vendored Normal file
View File

@ -0,0 +1,15 @@
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<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;}))),(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);}

123
data/js/slider.js Normal file
View File

@ -0,0 +1,123 @@
/* -----------------------------------------------------
Material Design Sliders
CodePen URL: https://codepen.io/rkchauhan/pen/xVGGpR
By: Ravikumar Chauhan
-------------------------------------------------------- */
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 =
'<div class="slider">' +
'<div class="slider-fill"></div>' +
'<div class="slider-handle"><div class="slider-label"><span>0</span></div></div>' +
"</div>";
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);
}
}

11
data/js/slider.min.js vendored Normal file
View File

@ -0,0 +1,11 @@
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='<div class="slider">'+
'<div class="slider-fill"></div>'+
'<div class="slider-handle"><div class="slider-label"><span>0</span></div></div>'+
"</div>";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);}}

351
data/js/tabbedcontent.js Normal file
View File

@ -0,0 +1,351 @@
/**
* 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 <elboletaire at underave dot net>
*/
;(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 <a> 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);

35
data/js/tabbedcontent.min.js vendored Normal file
View File

@ -0,0 +1,35 @@
;(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(current,true);}else if(loop&&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&&current<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);

BIN
docs/inlinestyles.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 326 KiB

BIN
docs/ui_colours.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

After

Width:  |  Height:  |  Size: 59 KiB

BIN
docs/ui_fileDisplay.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
docs/ui_graph.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
docs/ui_groupedbuttons.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
docs/ui_groupedbuttons2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

BIN
docs/ui_groupedbuttons3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

BIN
docs/ui_inlinestyles2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

BIN
docs/ui_inputtypes.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
docs/ui_number.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

BIN
docs/ui_select1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
docs/ui_select2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
docs/ui_separators.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

BIN
docs/ui_tabs.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
docs/ui_text.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

BIN
docs/ui_widecontrols.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -0,0 +1,564 @@
/**
* @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 <Arduino.h>
#include <EEPROM.h>
#include <ESPUI.h>
#if defined(ESP32)
#include <WiFi.h>
#include <ESPmDNS.h>
#else
// esp8266
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <umm_malloc/umm_heap_select.h>
#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://<ip>/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';
}

View File

@ -0,0 +1,4 @@
// placeholder
#if CORE_MOCK
#include "completeExample.cpp"
#endif

View File

@ -0,0 +1,544 @@
/**
* @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 <Arduino.h>
#include <EEPROM.h>
#include <ESPUI.h>
#if defined(ESP32)
#include <WiFi.h>
#include <ESPmDNS.h>
#else
// esp8266
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <umm_malloc/umm_heap_select.h>
#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://<ip>/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';
}

View File

@ -0,0 +1,322 @@
#include <DNSServer.h>
#include <ESPUI.h>
const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 4, 1);
DNSServer dnsServer;
#if defined(ESP32)
#include <WiFi.h>
#else
// esp8266
#include <ESP8266WiFi.h>
#include <umm_malloc/umm_heap_select.h>
#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://<ip>/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();
}
}

View File

@ -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:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}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 #c0c0c0;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}

View File

@ -1,765 +0,0 @@
.container {
position: relative;
width: 79%;
margin: 20px;
box-sizing: border-box;
}
.column, .columns {
width: 100%;
float: left;
}
.card {
margin-top: 2%;
border-radius: 6px;
box-shadow: 0 4px 4px rgba(204, 197, 185, 0.5);
padding-left: 20px;
padding-right: 20px;
margin-bottom: 10px;
min-width: 150px;
color: #fff;
}
.card-slider {
padding-bottom: 10px
}
.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;
}
.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;
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: 2%;
}
.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.0%;
}
.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.0%;
}
.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.0;
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: 4.0rem;
line-height: 1.2;
letter-spacing: -.1rem;
}
h2 {
font-size: 3.6rem;
line-height: 1.25;
letter-spacing: -.1rem;
}
h3 {
font-size: 3.0rem;
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;
}
/* Larger than phablet */
@media (min-width: 630px) {
h1 {
font-size: 5.0rem;
}
h2 {
font-size: 4.2rem;
}
h3 {
font-size: 3.6rem;
}
h4 {
font-size: 3.0rem;
}
h5 {
font-size: 2.0rem;
}
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;
}
/* Main Head Part
*/
#mainHeader {
display: inline-block;
}
#conStatus {
position: inherit;
font-size: 0.75em;
}
/* Spacing
*/
button, .button {
margin-bottom: 1rem;
}
/* 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%, .1), hsla(0, 0%, 100%, .1));
border-radius: 50%;
box-shadow: inset 0 1px 1px 1px hsla(0, 0%, 100%, .5), 0 0 1px 1px hsla(0, 0%, 100%, .75), 0 0 1px 2px hsla(0, 0%, 100%, .25), 0 0 1px 3px hsla(0, 0%, 100%, .25), 0 0 1px 4px hsla(0, 0%, 100%, .25), 0 0 1px 6px hsla(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%, .5), 0 0 1px hsla(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%, .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%, .4);
transition: .15s;
}
.control .confirm {
background-color: #ddd;
background-image: linear-gradient(hsla(0, 0%, 0%, .15), hsla(0, 0%, 100%, .25));
box-shadow: inset 0 1px 1px 1px hsla(0, 0%, 100%, .5), 0 0 1px 1px hsla(0, 0%, 100%, .25), 0 0 1px 2px hsla(0, 0%, 100%, .25), 0 0 1px 3px hsla(0, 0%, 100%, .25), 0 0 1px 4px hsla(0, 0%, 100%, .25), 0 0 1px 6px hsla(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;
}
/* 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-bottom: 12px;
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: 4px;
background-color: #bebebe;
}
.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: -5.5px;
left: 0%;
width: 15px;
height: 15px;
margin-left: -8px;
border-radius: 50%;
transition: all .2s ease;
user-select: none;
z-index: 2;
}
.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: -2px;
width: 30px;
height: 30px;
-webkit-transform-origin: 50% 100%;
transform-origin: 50% 100%;
border-radius: 50%;
-webkit-transform: scale(0.5) rotate(-45deg);
transform: scale(0.5) rotate(-45deg);
-webkit-transition: all .2s ease;
transition: all .2s ease;
}
.rkmd-slider.slider-discrete .slider .slider-handle .slider-label span {
position: absolute;
top: 7px;
left: 0px;
width: 100%;
color: #fff;
font-size: 12px;
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;
}
.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;
}
*/

File diff suppressed because one or more lines are too long

View File

@ -1,28 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Control</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAPFBMVEUAAACA1VWR21qQ2liR3FqR3FqS3VuR3VqR3VuR3VqO21mS21uS3FqS3FqS21uJ2GKQ21qR3FuR3FoAAAB/3Gu7AAAAEnRSTlMABoA3kPBwz8i5Kzioxg4NVcU3uEJHAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAAN1wAADdcBQiibeAAAAAd0SU1FB+EFEhcEM+HpYwQAAABYSURBVBjThY/JDsAgCESt4lpX/v9jLQZJ6qF9t3khAyj1xXUKbQ4BVowDwqOYgExkkW4iY6lPaF06RqM8YItOuRbMaz6xjbsusDAW/drplBg47jP696cXE8bPA1eUDeK2AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTA1LTE4VDIzOjA0OjUxKzAyOjAwxE59ewAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0wNS0xOFQyMzowNDo1MSswMjowMLUTxccAAAAZdEVYdFNvZnR3YXJlAHd3dy5pbmtzY2FwZS5vcmeb7jwaAAAAAElFTkSuQmCC"
/>
<link rel="stylesheet" href="/css/normalize.css">
<link rel="stylesheet" href="/css/style.css">
<script src="/js/zepto.min.js"></script>
<script src="/js/slider.js"></script>
<script src="/js/controls.js"></script>
</head>
<body onload="javascript:start();">
<div>
<h4><div id="mainHeader">Control</div> <span id="conStatus" class="label">Offline</span></h4></div>
<hr />
<div class="container">
<div id="row" class="row u-full-width">
</div>
</div>
</body>
</html>

View File

@ -1,342 +0,0 @@
const UI_TITEL = 0;
const UI_LABEL = 1;
const UPDATE_LABEL = 6;
const UI_BUTTON = 2;
const UI_SWITCHER = 3;
const UPDATE_SWITCHER = 7;
const UI_PAD = 4;
const UI_CPAD = 5;
const UI_SLIDER = 8;
const UPDATE_SLIDER = 9;
const UI_NUMBER = 10;
const UPDATE_NUMBER = 11;
const UI_TEXT_INPUT = 12;
const UPDATE_TEXT_INPUT = 13;
const UI_GRAPH = 14;
const CLEAR_GRAPH = 15;
const ADD_GRAPH_POINT = 16;
const FOR = 0;
const BACK = 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_NONE = 7;
function colorClass(colorId) {
colorId = Number(colorId);
switch (colorId) {
case C_TURQUOISE:
return "turquoise";
break;
case C_EMERALD:
return "emerald";
break;
case C_PETERRIVER:
return "peterriver";
break;
case C_WETASPHALT:
return "wetasphalt";
break;
case C_SUNFLOWER:
return "sunflower";
break;
case C_CARROT:
return "carrot"
break;
case C_ALIZARIN:
return "alizarin"
break;
case C_NONE:
return ""
break;
default:
return "";
}
}
var websock;
function start() {
websock = new WebSocket('ws://' + window.location.hostname + '/ws');
websock.onopen = function(evt) {
console.log('websock open');
$("#conStatus").addClass("color-green");
$("#conStatus").text("Connected");
};
websock.onclose = function(evt) {
console.log('websock close');
$("#conStatus").removeClass("color-green");
$("#conStatus").addClass("color-red");
$("#conStatus").text("Error / No Connection");
};
websock.onerror = function(evt) {
console.log(evt);
$("#conStatus").removeClass("color-green");
$("#conStatus").addClass("color-red");
$("#conStatus").text("Error / No Connection");
};
websock.onmessage = function(evt) {
console.log(evt);
var data = JSON.parse(evt.data);
var e = document.body;
var center = "";
switch (data.type) {
case UI_TITEL:
document.title = data.label;
$('#mainHeader').html(data.label);
break;
case UI_LABEL:
$('#row').append("<div class='two columns card tcenter " + colorClass(data.color) + "'><h5 id='" + data.id + "'>" + data.label + "</h5><hr /><span id='l" + data.id + "' class='label label-wrap'>" + data.value + "</span></div>");
break;
case UI_BUTTON:
$('#row').append("<div class='one columns card tcenter " + colorClass(data.color) + "'><h5>" + data.label + "</h5><hr/><button onmousedown='buttonclick(" + data.id + ", true)' onmouseup='buttonclick(" + data.id + ", false)' id='" + data.id + "'>" + data.value + "</button></div>");
$('#' + data.id).on({
'touchstart': function(e) {
e.preventDefault();
buttonclick(data.id, true)
}
});
$('#' + data.id).on({
'touchend': function(e) {
e.preventDefault();
buttonclick(data.id, false)
}
});
break;
case UI_SWITCHER:
var label = "<label id='sl" + data.id + "' class='switch checked'>";
var input = "<div class='in'><input type='checkbox' id='s" + data.id + "' onClick='switcher(" + data.id + ",null)' checked></div>";
if (data.value == "0") {
label = "<label id='sl" + data.id + "' class='switch'>";
input = "<div class='in'><input type='checkbox' id='s" + data.id + "' onClick='switcher(" + data.id + ",null)' ></div>";
}
$('#row').append(
"<div id='" + data.id + "' class='one columns card tcenter " + colorClass(data.color) + "'><h5>" + data.label + "</h5><hr/>" +
label + input +
"</label>" +
"</div>");
break;
case UI_CPAD:
center = "<a class='confirm' onmousedown='padclick(CENTER, " + data.id + ", true)' onmouseup='padclick(CENTER, " + data.id + ", false)' href='#' id='pc" + data.id + "'>OK</a>";
//NO BREAK
case UI_PAD:
$('#row').append(
"<div class='two columns card tcenter " + colorClass(data.color) + "'><h5>" + data.label + "</h5><hr/>" +
"<nav class='control'>" +
"<ul>" +
"<li><a onmousedown='padclick(FOR, " + data.id + ", true)' onmouseup='padclick(FOR, " + data.id + ", false)' href='#' id='pf" + data.id + "'>▲</a></li>" +
"<li><a onmousedown='padclick(RIGHT, " + data.id + ", true)' onmouseup='padclick(RIGHT, " + data.id + ", false)' href='#' id='pr" + data.id + "'>▲</a></li>" +
"<li><a onmousedown='padclick(LEFT, " + data.id + ", true)' onmouseup='padclick(LEFT, " + data.id + ", false)' href='#' id='pl" + data.id + "'>▲</a></li>" +
"<li><a onmousedown='padclick(BACK, " + data.id + ", true)' onmouseup='padclick(BACK, " + data.id + ", false)' href='#' id='pb" + data.id + "'>▲</a></li>" +
"</ul>" +
center +
"</nav>" +
"</div>");
$('#pf' + data.id).on({
'touchstart': function(e) {
e.preventDefault();
padclick(FOR, data.id, true)
}
});
$('#pf' + data.id).on({
'touchend': function(e) {
e.preventDefault();
padclick(FOR, data.id, false)
}
});
$('#pl' + data.id).on({
'touchstart': function(e) {
e.preventDefault();
padclick(LEFT, data.id, true)
}
});
$('#pl' + data.id).on({
'touchend': function(e) {
e.preventDefault();
padclick(LEFT, data.id, false)
}
});
$('#pr' + data.id).on({
'touchstart': function(e) {
e.preventDefault();
padclick(RIGHT, data.id, true)
}
});
$('#pr' + data.id).on({
'touchend': function(e) {
e.preventDefault();
padclick(RIGHT, data.id, false)
}
});
$('#pb' + data.id).on({
'touchstart': function(e) {
e.preventDefault();
padclick(BACK, data.id, true)
}
});
$('#pb' + data.id).on({
'touchend': function(e) {
e.preventDefault();
padclick(BACK, data.id, false)
}
});
$('#pc' + data.id).on({
'touchstart': function(e) {
e.preventDefault();
padclick(CENTER, data.id, true)
}
});
$('#pc' + data.id).on({
'touchend': function(e) {
e.preventDefault();
padclick(CENTER, data.id, false)
}
});
break;
case UPDATE_LABEL:
$('#l' + data.id).html(data.value);
break;
case UPDATE_SWITCHER:
if (data.value == "0")
switcher(data.id, 0);
else
switcher(data.id, 1);
break;
case UI_SLIDER:
$('#row').append(
"<div class='two columns card tcenter card-slider " + colorClass(data.color) + "'>" +
"<h5 id='" + data.id + "'>" + data.label + "</h5><hr />" +
"<div id='sl" + data.id + "' class='rkmd-slider slider-discrete slider-" + colorClass(data.color) + "'>" +
"<input type='range' min='0' max='100' value='" + data.value + "'>" +
"</div>" +
"</div>"
);
$('#row').append(
"<script>" +
"rkmd_rangeSlider('#sl" + data.id + "');" +
"</script>"
);
break;
case UPDATE_SLIDER:
slider_move($('#sl' + data.id), data.value, '100', false);
break;
case UI_NUMBER:
$('#row').append(
"<div class='two columns card tcenter" + colorClass(data.color) + "'>" +
"<h5 id='" + data.id + "'>" + data.label + "</h5><hr />" +
"<input id='num" + data.id + "' type='number' value='" + data.value + "' onchange='numberchange(" + data.id + ")' />" +
"</div>"
);
break;
case UPDATE_NUMBER:
$('#num' + data.id).val(data.value);
break;
case UI_TEXT_INPUT:
$('#row').append(
"<div class='two columns card tcenter" + colorClass(data.color) + "'>" +
"<h5 id='" + data.id + "'>" + data.label + "</h5><hr />" +
"<input id='num" + data.id + "' type='number' value='" + data.value + "' onchange='numberchange(" + data.id + ")' />" +
"</div>"
);
break;
case UPDATE_TEXT_INPUT:
$('#num' + data.id).val(data.value);
break;
default:
console.error('Unknown type or event');
break;
}
};
}
function numberchange(number) {
var val = $('#num' + data.id).val();
websock.send("nchange:" + number + ":" + val);
console.log(val);
}
function buttonclick(number, isdown) {
if (isdown) websock.send("bdown:" + number);
else websock.send("bup:" + number);
}
function padclick(type, number, isdown) {
switch (type) {
case CENTER:
if (isdown) websock.send("pcdown:" + number);
else websock.send("pcup:" + number);
break;
case FOR:
if (isdown) websock.send("pfdown:" + number);
else websock.send("pfup:" + number);
break;
case BACK:
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 ($('#s' + number).is(':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);
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,125 +0,0 @@
/* -----------------------------------------------------
Material Design Sliders
CodePen URL: https://codepen.io/rkchauhan/pen/xVGGpR
By: Ravikumar Chauhan
-------------------------------------------------------- */
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 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);
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 = '<div class="slider">' +
'<div class="slider-fill"></div>' +
'<div class="slider-handle"><div class="slider-label"><span>0</span></div></div>' +
'</div>';
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"]');
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);
}
}

View File

@ -1 +0,0 @@
function rkmd_rangeSlider(b){var f,e,c,a,g,d,h;f=$(b);e=f.width();c=f.offset().left;g=f;g.each(function(k,j){a=$(this);a.append(sliderDiscrete_tmplt());d=a.find('input[type="range"]');h=a.find(".slider");slider_fill=h.find(".slider-fill");slider_handle=h.find(".slider-handle");slider_label=h.find(".slider-label");var l=parseInt(d.val());slider_fill.css("width",l+"%");slider_handle.css("left",l+"%");slider_label.find("span").text(l)});f.on("mousedown touchstart",".slider-handle",function(o){if(o.button===2){return false}var m=$(this).parents(".rkmd-slider");var l=m.width();var i=m.offset().left;var k=m.find('input[type="range"]').is(":disabled");if(k===true){return false}$(this).addClass("is-active");var p=function(r){var q=r.pageX-i;if(q<=l&&!(q<"0")){slider_move(m,q,l,true)}};var n=function(q){$(this).off(j);m.find(".is-active").removeClass("is-active")};var j={mousemove:p,touchmove:p,mouseup:n,touchend:n};$(document).on(j)});f.on("mousedown touchstart",".slider",function(p){if(p.button===2){return false}var m=$(this).parents(".rkmd-slider");var l=m.width();var i=m.offset().left;var k=m.find('input[type="range"]').is(":disabled");if(k===true){return false}var o=p.pageX-i;if(o<=l&&!(o<"0")){slider_move(m,o,l,true)}var n=function(q){$(this).off(j)};var j={mouseup:n,touchend:n};$(document).on(j)})}function sliderDiscrete_tmplt(){var a='<div class="slider"><div class="slider-fill"></div><div class="slider-handle"><div class="slider-label"><span>0</span></div></div></div>';return a}function slider_move(g,a,h,e){var i=parseInt(Math.round(a/h*100));var b=g.find(".slider-fill");var c=g.find(".slider-handle");var f=g.find('input[type="range"]');b.css("width",i+"%");c.css({left:i+"%",transition:"none","-webkit-transition":"none","-moz-transition":"none"});f.val(i);if(g.find(".slider-handle span").text()!=i){g.find(".slider-handle span").text(i);var d=g.attr("id").substring(2);if(e){websock.send("slvalue:"+i+":"+d)}}};

View File

@ -1,161 +1,301 @@
#include <DNSServer.h>
#include <ESPUI.h>
const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 4, 1);
DNSServer dnsServer;
#if defined(ESP32)
#include <WiFi.h>
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
// esp8266
#include <ESP8266WiFi.h>
#include <umm_malloc/umm_heap_select.h>
#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://<ip>/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 = "";
const char* ssid = "ESPUI";
const char* password = "espui";
long oldTime = 0;
bool switchi = false;
const char* hostname = "espui";
void slider(Control sender, int type) {
Serial.println(sender.value);
int statusLabelId;
int graphId;
int millisLabelId;
int testSwitchId;
void numberCall(Control* sender, int type)
{
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 textCall(Control* sender, int type)
{
Serial.print("Text: ID: ");
Serial.print(sender->id);
Serial.print(", Value: ");
Serial.println(sender->value);
}
void buttonExample(Control sender, int type) {
switch (type) {
case B_DOWN:
Serial.println("Status: Start");
ESPUI.print(0, "Status: Start");
break;
case B_UP:
Serial.println("Status: Stop");
ESPUI.print(0, "Status: 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 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 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 buttonCallback(Control* sender, int type)
{
switch (type)
{
case B_DOWN:
Serial.println("Button DOWN");
break;
case B_UP:
Serial.println("Button UP");
break;
}
}
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 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 setup(void) {
Serial.begin(115200);
WiFi.mode(WIFI_AP);
void switchExample(Control* sender, int value)
{
switch (value)
{
case S_ACTIVE:
Serial.print("Active:");
break;
#if defined(ESP32)
WiFi.setHostname(ssid);
#else
WiFi.hostname(ssid);
#endif
case S_INACTIVE:
Serial.print("Inactive");
break;
}
WiFi.softAP(ssid);
// WiFi.softAP(ssid, password);
Serial.println("");
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
// change the beginning to this if you want to join an existing network
/*
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
*/
ESPUI.label("Status:", COLOR_TURQUOISE, "Stop");
ESPUI.label("Millis:", COLOR_EMERALD, "0");
ESPUI.button("Push Button", &buttonCallback, COLOR_PETERRIVER);
ESPUI.button("Other Button", &buttonExample, COLOR_WETASPHALT, "Press");
ESPUI.pad("Pad with center", true, &padExample, COLOR_SUNFLOWER);
ESPUI.pad("Pad without center", false, &padExample, COLOR_CARROT);
ESPUI.switcher("Switch one", false, &switchExample, COLOR_ALIZARIN);
ESPUI.switcher("Switch two", true, &otherSwitchExample, COLOR_NONE);
ESPUI.slider("Slider one", &slider, COLOR_ALIZARIN, "30");
ESPUI.slider("Slider two", &slider, COLOR_NONE, "100");
/*
.begin loads and serves all files from PROGMEM directly.
If you want to serve the files from SPIFFS use .beginSPIFFS (.prepareFileSystem has to be run in an empty sketch before)
*/
ESPUI.begin("ESPUI Control");
Serial.print(" ");
Serial.println(sender->id);
}
void loop(void) {
if (millis() - oldTime > 5000) {
ESPUI.print("Millis:", String(millis()));
switchi = !switchi;
ESPUI.updateSwitcher("Switch one", switchi);
oldTime = millis();
}
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();
}
}

View File

@ -1,9 +1,16 @@
#include <ESPUI.h>
void setup(void) {
void setup(void)
{
Serial.begin(115200);
ESPUI.prepareFileSystem();
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() {
void loop()
{
}

View File

@ -0,0 +1,319 @@
#include <DNSServer.h>
#include <ESPUI.h>
const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 4, 1);
DNSServer dnsServer;
#if defined(ESP32)
#include <WiFi.h>
#else
// esp8266
#include <ESP8266WiFi.h>
#include <umm_malloc/umm_heap_select.h>
#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://<ip>/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();
}
}

View File

@ -21,9 +21,11 @@ slider KEYWORD2
begin KEYWORD2
beginSPIFFS KEYWORD2
beginLITTLEFS KEYWORD2
print KEYWORD2
updateSwitcher KEYWORD2
updateSlider KEYWORD2
captivePortal LITERAL1
#######################################
# Instances (KEYWORD2)

View File

@ -1,10 +1,7 @@
{
"langs":
{
"en-GB":
{
"keys":
{
"langs": {
"en-GB": {
"keys": {
"LANG_SUBCATERGORY_ESPUI": "User Interface",
"LANG_ESPUI_ESPUI_TITLE": "Title",
"LANG_ESPUI_ESPUI_HOTSPOT": "Enable Wifi Hotspot Code",
@ -22,6 +19,45 @@
"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?"
}
}
}
}
}

View File

@ -1,14 +1,12 @@
{
"name": "ESPUI",
"keywords": "espressif web interface iot control simple easy ui userinterface",
"keywords": "espressif web interface iot easy ui",
"description": "ESP32 and ESP8266 Web Interface Library",
"repository":
{
"repository": {
"type": "git",
"url": "https://github.com/s00500/ESPUI.git"
},
"authors":
[
"authors": [
{
"name": "Lukas Bachschwell",
"email": "lukas@lbsfilm.at",
@ -16,13 +14,19 @@
"maintainer": true
}
],
"dependencies":
{
"name": "ESP Async WebServer",
"authors": "Hristo Gochkov",
"frameworks": "arduino"
},
"version": "1.5.2",
"dependencies": [
{
"name": "ESP Async WebServer",
"authors": "Hristo Gochkov",
"frameworks": "arduino"
},
{
"name": "ArduinoJson",
"authors": "Benoit Blanchon",
"frameworks": "arduino"
}
],
"version": "2.2.3",
"frameworks": "arduino",
"platforms": "*"
}
}

View File

@ -1,5 +1,5 @@
name=ESPUI
version=1.5.2
version=2.2.3
author=Lukas Bachschwell
maintainer=Lukas Bachschwell <lukas@lbsfilm.at>
sentence=ESP32 and ESP8266 Web Interface Library
@ -7,3 +7,4 @@ paragraph=A simple library that implements a web graphical user interface for ES
category=Communication
url=https://github.com/s00500/ESPUI
architectures=*
depends=ArduinoJson

1
pio_examples/gui/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.pio

View File

@ -0,0 +1,51 @@
; 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
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 = COM9
monitor_port = COM9
monitor_speed = 115200

View File

@ -0,0 +1,309 @@
#include <DNSServer.h>
#include <ESPUI.h>
const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 4, 1);
DNSServer dnsServer;
#if defined(ESP32)
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
const char* ssid = "ESPUI";
const char* password = "espui";
const char* hostname = "espui";
String DisplayTestFileName = "/FileName.txt";
int statusLabelId = Control::noParent;
int graphId = Control::noParent;
int millisLabelId = Control::noParent;
int testSwitchId = Control::noParent;
int fileDisplayId = Control::noParent;
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);
#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.number("Numbertest", &numberCall, ControlColor::Alizarin, 5, 0, 10);
fileDisplayId = ESPUI.fileDisplay("Filetest", ControlColor::Turquoise, DisplayTestFileName);
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.sliderContinuous = true;
ESPUI.prepareFileSystem();
ESPUI.beginLITTLEFS("ESPUI Control");
// create a text file
ESPUI.writeFile("/DisplayFile.txt", "Test Line\n");
// these files are used by browsers to auto config a connection.
ESPUI.writeFile("/wpad.dat", " ");
ESPUI.writeFile("/connecttest.txt", " ");
}
void loop(void)
{
dnsServer.processNextRequest();
static long oldTime = 0;
static bool testSwitchState = false;
delay(10);
if (millis() - oldTime > 5000)
{
ESPUI.print(millisLabelId, String(millis()));
ESPUI.addGraphPoint(graphId, random(1, 50));
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();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,72 +1,57 @@
#ifndef ESPUI_h
#define ESPUI_h
#pragma once
#define debug true
// comment out to turn off debug output
// #define DEBUG_ESPUI true
#define WS_AUTHENTICATION false
#include "Arduino.h"
#include "ArduinoJson.h"
#include "FS.h"
#include "stdlib_noniso.h"
#include <Arduino.h>
#include <ArduinoJson.h>
#include <stdlib_noniso.h>
#ifdef ESP32
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
#include <LittleFS.h>
#else
#include <LITTLEFS.h>
#endif
#else
#include <LittleFS.h>
#endif
#include <map>
#include <ESPAsyncWebServer.h>
#include "ESPUIcontrol.h"
#include "ESPUIclient.h"
#if defined(ESP32)
#include "SPIFFS.h"
#include "WiFi.h"
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "WiFi.h"
#else
#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <FS.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFSEditor.h>
#include <Hash.h>
#define FILE_WRITE "w"
#define FILE_WRITING "w"
#endif
typedef struct Control {
unsigned int type;
unsigned int id; // just mirroring the id here for practical reasons
const char *label;
void (*callback)(Control, int);
String value;
unsigned int color;
} Control;
// Message Types (and control types)
#define UI_TITEL 0
#define UI_LABEL 1
#define UPDATE_LABEL 6
#define UI_BUTTON 2
#define UI_SWITCHER 3
#define UPDATE_SWITCHER 7
#define UI_PAD 4
#define UI_CPAD 5
#define UI_SLIDER 8
#define UPDATE_SLIDER 9
#define UI_NUMBER 10
#define UPDATE_NUMBER 11
#define UI_TEXT_INPUT 12
#define UPDATE_TEXT_INPUT 13
#define UI_GRAPH 14
#define CLEAR_GRAPH 15
#define ADD_GRAPH_POINT 16
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
@ -88,72 +73,209 @@ typedef struct Control {
#define SL_VALUE 8
#define N_VALUE 9
#define T_VALUE 10
#define S_VALUE 11
#define TM_VALUE 12
// Colors
#define COLOR_TURQUOISE 0
#define COLOR_EMERALD 1
#define COLOR_PETERRIVER 2
#define COLOR_WETASPHALT 3
#define COLOR_SUNFLOWER 4
#define COLOR_CARROT 5
#define COLOR_ALIZARIN 6
#define COLOR_NONE 6
class ESPUIClass {
enum Verbosity : uint8_t
{
Quiet = 0,
Verbose,
VerboseJSON
};
class ESPUIClass
{
public:
void begin(const char *_title); // Setup servers and page in Memorymode
void beginSPIFFS(const char *_title); // Setup servers and page in SPIFFSmode
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 prepareFileSystem(); // Initially preps the filesystem and loads a lot of stuff into SPIFFS
void list();
// Creating Elements
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
int button(const char *label, void (*callBack)(Control, int), int color, String value = ""); // Create Event Button
int switcher(const char *label, bool startState, void (*callBack)(Control, int), int color); // Create Toggle Button
int pad(const char *label, bool centerButton, void (*callBack)(Control, int), int color); // Create Pad Control
int slider(const char *label, void (*callBack)(Control, int), int color, String value); // Create Slider Control
int number(const char *label, void (*callBack)(Control, int), int color, int number, int min, int max); // Create a Number Input Control
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);
// Output only
int label(const char *label, int color, String value = ""); // Create Label
int graph(const char *label, int color); // Create Graph display
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<void(Control*, int)> callback);
// Update Elements
void print(int id, String value);
void print(String label, String value);
bool removeControl(uint16_t id, bool force_rebuild_ui = false);
void updateSwitcher(int id, bool nValue, int clientId = -1);
void updateSwitcher(String label, bool nValue, int clientId = -1);
// create Elements
// Create Event Button
uint16_t button(const char* label, std::function<void(Control*, int)> callback, ControlColor color, const String& value = "");
uint16_t switcher(const char* label, std::function<void(Control*, int)> callback, ControlColor color, bool startState = false); // Create Toggle Button
uint16_t pad(const char* label, std::function<void(Control*, int)> callback, ControlColor color); // Create Pad Control
uint16_t padWithCenter(const char* label, std::function<void(Control*, int)> callback, ControlColor color); // Create Pad Control with Centerbutton
uint16_t slider(const char* label, std::function<void(Control*, int)> callback, ControlColor color, int value, int min = 0, int max = 100); // Create Slider Control
uint16_t number(const char* label, std::function<void(Control*, int)> callback, ControlColor color, int value, int min = 0, int max = 100); // Create a Number Input Control
uint16_t text(const char* label, std::function<void(Control*, int)> callback, ControlColor color, const String& value = ""); // Create a Text Input Control
void updateSlider(int id, int nValue, int clientId = -1);
void updateSlider(String label, int nValue, int clientId = -1);
// 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);
void updateNumber(int id, int nValue, int clientId = -1);
void updateNumber(String label, int nValue, int clientId = -1);
// Input only
uint16_t accelerometer(const char* label, std::function<void(Control*, int)> callback, ControlColor color);
void clearGraph(int id, int clientId = -1);
void clearGraph(String label, int clientId = -1);
// Update Elements
void addGraphPoint(int id, int nValue, int clientId = -1);
void addGraphPoint(String label, int nValue, int clientId = -1);
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 textThem(String text, int clientId);
void updateControlLabel(uint16_t control, const char * value, int clientId = -1);
void updateControlLabel(Control* control, const char * value, int clientId = -1);
// Variables ---
const char *ui_title = "ESPUI"; // Store UI Title and Header Name
int cIndex = 0; // Control index
Control *controls[25];
void jsonDom(AsyncWebSocketClient *client);
int getIdByLabel(String label);
bool labelExists(String label);
void updateControl(uint16_t id, int clientId = -1);
void updateControl(Control* control, int clientId = -1);
private:
AsyncWebServer *server;
AsyncWebSocket *ws;
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<void(Control*, int, void*)> 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<void(Control*, int, void*)> 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<void(Control*, int, void*)> 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<void(Control*, int, void*)> 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<void(Control*, int, void*)> 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<void(Control*, int, void*)> 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<void(Control*, int, void*)> 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<void(Control*, int, void*)> 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<void(Control*, int, void*)> 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::DynamicJsonDocument& document, uint16_t clientId);
std::map<uint32_t, ESPUIclient*> MapOfClients;
uint32_t ControlChangeID = 0;
};
extern ESPUIClass ESPUI;
#endif

574
src/ESPUIclient.cpp Normal file
View File

@ -0,0 +1,574 @@
#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(DynamicJsonDocument& document)
{
document[F("type")] = UI_EXTEND_GUI;
document[F("sliderContinuous")] = ESPUI.sliderContinuous;
document[F("startindex")] = 0;
document[F("totalcontrols")] = ESPUI.controlCount;
JsonArray items = document.createNestedArray(F("controls"));
JsonObject titleItem = items.createNestedObject();
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;
}
DynamicJsonDocument 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,
DynamicJsonDocument & rootDoc,
bool InUpdateMode,
String FragmentRequestString)
{
#ifdef ESP32
xSemaphoreTake(ESPUI.ControlsSemaphore, portMAX_DELAY);
#endif // def ESP32
// Serial.println(String("prepareJSONChunk: Start. InUpdateMode: ") + String(InUpdateMode));
int elementcount = 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.
DynamicJsonDocument FragmentRequest(FragmentRequestString.length() * 3);
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.containsKey(F("id")))
{
Serial.println(F("ERROR:prepareJSONChunk:Fragmentation:Request does not contain a control ID"));
break;
}
uint16_t ControlId = uint16_t(FragmentRequest[F("id")]);
if(!FragmentRequest.containsKey(F("offset")))
{
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;
}
}
JsonObject item = items.createNestedObject();
elementcount++;
control->MarshalControl(item, InUpdateMode, DataOffset);
if (rootDoc.overflowed() || (ESPUI.jsonChunkNumberMax > 0 && (elementcount % ESPUI.jsonChunkNumberMax) == 0))
{
// String("prepareJSONChunk: too much data in the message. Remove the last entry");
if (1 == elementcount)
{
Serial.println(String(F("ERROR: 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 = items.createNestedObject();
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)
{
// Serial.println("prepareJSONChunk: exit loop");
control = nullptr;
}
else
{
control = control->next;
}
} // end while (control != nullptr)
} while (false);
#ifdef ESP32
xSemaphoreGive(ESPUI.ControlsSemaphore);
#endif // def ESP32
// Serial.println(String("prepareJSONChunk: 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;
}
DynamicJsonDocument 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(DynamicJsonDocument& 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;
}
}

67
src/ESPUIclient.h Normal file
View File

@ -0,0 +1,67 @@
#pragma once
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#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::DynamicJsonDocument& document);
uint32_t prepareJSONChunk(uint16_t startindex, DynamicJsonDocument& 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::DynamicJsonDocument& document);
};

149
src/ESPUIclientFsm.cpp Normal file
View File

@ -0,0 +1,149 @@
#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 */
}

81
src/ESPUIclientFsm.h Normal file
View File

@ -0,0 +1,81 @@
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
// 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

283
src/ESPUIcontrol.cpp Normal file
View File

@ -0,0 +1,283 @@
#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<void(Control*, int)> 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;
}
void Control::MarshalControl(JsonObject & _item, bool refresh, uint32_t StartingOffset)
{
JsonObject & item = _item;
uint32_t length = value.length();
uint32_t maxLength = uint32_t(double(ESPUI.jsonInitialDocumentSize) * 0.75);
if((length > maxLength) || StartingOffset)
{
/*
Serial.println(String("MarshalControl:Start Fragment Processing"));
Serial.println(String("MarshalControl:id: ") + String(id));
Serial.println(String("MarshalControl:length: ") + String(length));
Serial.println(String("MarshalControl:StartingOffset: ") + String(StartingOffset));
Serial.println(String("MarshalControl:maxLength: ") + String(maxLength));
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
_item[F("type")] = uint32_t(ControlType::Fragment);
_item[F("id")] = id;
length = min((length - StartingOffset), maxLength);
// Serial.println(String("MarshalControl:Final length: ") + String(length));
_item[F("offset")] = StartingOffset;
_item[F("length")] = length;
_item[F("total")] = value.length();
item = _item.createNestedObject(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, length + StartingOffset);
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 <option>
if (ControlType::Option == type)
{
Control* ParentControl = ESPUI.getControlNoLock(parentControl);
if (nullptr == ParentControl)
{
item[F("selected")] = emptyString;
}
else if (ParentControl->value == value)
{
item[F("selected")] = F("selected");
}
else
{
item[F("selected")] = "";
}
}
}
void Control::MarshalErrorMessage(JsonObject & item)
{
item[F("id")] = id;
item[F("type")] = uint32_t(ControlType::Label);
item[F("label")] = ControlError.c_str();
item[F("value")] = ControlError;
item[F("visible")] = true;
item[F("color")] = (int)ControlColor::Carrot;
item[F("enabled")] = true;
if (parentControl != Control::noParent)
{
item[F("parentControl")] = String(parentControl);
}
}
void Control::onWsEvent(String & cmd, String& data)
{
do // once
{
// Serial.println(String(F("Control::onWsEvent")));
SetControlChangedId(ESPUI.GetNextControlChangeId());
if (!HasCallback())
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(String(F("Control::onWsEvent:No callback found for ID ")) + String(id));
}
#endif
break;
}
// Serial.println("Control::onWsEvent:Generating callback");
if (cmd.equals(F("bdown")))
{
SendCallback(B_DOWN);
break;
}
if (cmd.equals(F("bup")))
{
SendCallback(B_UP);
break;
}
if (cmd.equals(F("pfdown")))
{
SendCallback(P_FOR_DOWN);
break;
}
if (cmd.equals(F("pfup")))
{
SendCallback(P_FOR_UP);
break;
}
if (cmd.equals(F("pldown")))
{
SendCallback(P_LEFT_DOWN);
break;
}
else if (cmd.equals(F("plup")))
{
SendCallback(P_LEFT_UP);
}
else if (cmd.equals(F("prdown")))
{
SendCallback(P_RIGHT_DOWN);
}
else if (cmd.equals(F("prup")))
{
SendCallback(P_RIGHT_UP);
}
else if (cmd.equals(F("pbdown")))
{
SendCallback(P_BACK_DOWN);
}
else if (cmd.equals(F("pbup")))
{
SendCallback(P_BACK_UP);
}
else if (cmd.equals(F("pcdown")))
{
SendCallback(P_CENTER_DOWN);
}
else if (cmd.equals(F("pcup")))
{
SendCallback(P_CENTER_UP);
}
else if (cmd.equals(F("sactive")))
{
value = "1";
SendCallback(S_ACTIVE);
}
else if (cmd.equals(F("sinactive")))
{
value = "0";
// updateControl(c, client->id());
SendCallback(S_INACTIVE);
}
else if (cmd.equals(F("slvalue")))
{
value = data;
// updateControl(c, client->id());
SendCallback(SL_VALUE);
}
else if (cmd.equals(F("nvalue")))
{
value = data;
// updateControl(c, client->id());
SendCallback(N_VALUE);
}
else if (cmd.equals(F("tvalue")))
{
value = data;
// updateControl(c, client->id());
SendCallback(T_VALUE);
}
else if (cmd.equals(F("tabvalue")))
{
SendCallback(0);
}
else if (cmd.equals(F("svalue")))
{
value = data;
// updateControl(c, client->id());
SendCallback(S_VALUE);
}
else if (cmd.equals(F("time")))
{
value = data;
// updateControl(c, client->id());
SendCallback(TM_VALUE);
}
else
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("Control::onWsEvent:Malformed message from the websocket"));
}
#endif
}
} while (false);
}

128
src/ESPUIcontrol.h Normal file
View File

@ -0,0 +1,128 @@
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
#include <functional>
enum ControlType : uint8_t
{
// fixed Controls
Title = 0,
// updatable Controls
Pad,
PadWithCenter,
Button,
Label,
Switcher,
Slider,
Number,
Text,
Graph,
GraphPoint,
Tab,
Select,
Option,
Min,
Max,
Step,
Gauge,
Accel,
Separator,
Time,
FileDisplay,
Fragment = 98,
Password = 99,
UpdateOffset = 100,
};
enum ControlColor : uint8_t
{
Turquoise,
Emerald,
Peterriver,
Wetasphalt,
Sunflower,
Carrot,
Alizarin,
Dark,
None = 0xFF
};
class Control
{
public:
ControlType type;
uint16_t id; // just mirroring the id here for practical reasons
const char* label;
std::function<void(Control*, int)> callback;
String value;
ControlColor color;
bool visible;
bool wide;
bool vertical;
bool enabled;
uint16_t parentControl;
String panelStyle;
String elementStyle;
String inputType;
Control* next;
static constexpr uint16_t noParent = 0xffff;
Control(ControlType type,
const char* label,
std::function<void(Control*, int)> callback,
const String& value,
ControlColor color,
bool visible,
uint16_t parentControl);
Control(const Control& Control);
void SendCallback(int type);
bool HasCallback() { return (nullptr != callback); }
void MarshalControl(ArduinoJson::JsonObject& item, bool refresh, uint32_t DataOffset);
void MarshalErrorMessage(ArduinoJson::JsonObject& item);
void DeleteControl();
void onWsEvent(String& cmd, String& data);
inline bool ToBeDeleted() { return _ToBeDeleted; }
inline bool NeedsSync(uint32_t lastControlChangeID) {return (false == _ToBeDeleted) && (lastControlChangeID < ControlChangeID);}
void SetControlChangedId(uint32_t value) {ControlChangeID = value;}
private:
bool _ToBeDeleted = false;
uint32_t ControlChangeID = 0;
String OldValue = emptyString;
};
#define UI_TITLE ControlType::Title
#define UI_LABEL ControlType::Label
#define UI_BUTTON ControlType::Button
#define UI_SWITCHER ControlType::Switcher
#define UI_PAD ControlType::Pad
#define UI_CPAD ControlType::Cpad
#define UI_SLIDER ControlType::Slider
#define UI_NUMBER ControlType::Number
#define UI_TEXT_INPUT ControlType::Text
#define UI_GRAPH ControlType::Graph
#define UI_ADD_GRAPH_POINT ControlType::GraphPoint
#define UPDATE_LABEL ControlType::UpdateLabel
#define UPDATE_SWITCHER ControlType::UpdateSwitcher
#define UPDATE_SLIDER ControlType::UpdateSlider
#define UPDATE_NUMBER ControlType::UpdateNumber
#define UPDATE_TEXT_INPUT ControlType::UpdateText
#define CLEAR_GRAPH ControlType::ClearGraph
// Colors
#define COLOR_TURQUOISE ControlColor::Turquoise
#define COLOR_EMERALD ControlColor::Emerald
#define COLOR_PETERRIVER ControlColor::Peterriver
#define COLOR_WETASPHALT ControlColor::Wetasphalt
#define COLOR_SUNFLOWER ControlColor::Sunflower
#define COLOR_CARROT ControlColor::Carrot
#define COLOR_ALIZARIN ControlColor::Alizarin
#define COLOR_DARK ControlColor::Dark
#define COLOR_NONE ControlColor::None

File diff suppressed because one or more lines are too long

19
src/dataGraphJS.h Normal file
View File

@ -0,0 +1,19 @@
const char JS_GRAPH[] PROGMEM = R"=====(
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<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;}))),(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);}
)=====";
const uint8_t JS_GRAPH_GZIP[1280] PROGMEM = { 31,139,8,0,3,199,199,101,2,255,205,87,95,111,219,54,16,127,247,167,112,4,52,16,99,89,86,27,175,3,170,240,33,109,135,174,64,18,20,77,48,96,24,246,192,73,180,76,76,150,4,138,182,69,184,254,238,59,146,162,36,59,82,134,58,41,182,135,56,34,239,47,239,126,119,71,46,214,89,36,88,158,141,83,150,209,79,156,20,75,183,32,156,102,194,171,174,163,136,150,101,206,61,105,191,208,46,202,179,82,140,183,44,22,75,252,246,77,16,154,245,146,178,100,41,240,188,217,72,214,66,80,142,231,118,93,176,138,166,229,23,202,31,88,244,55,190,12,194,133,53,155,173,87,148,179,232,129,147,172,92,228,28,22,110,76,4,185,101,153,167,255,147,202,43,42,181,130,95,82,161,221,134,240,177,34,124,100,139,5,174,57,166,86,162,168,244,182,102,157,26,49,69,250,74,192,20,54,196,153,21,246,162,60,231,177,33,217,189,153,225,9,57,21,107,158,237,68,254,65,241,188,179,206,106,207,208,206,80,245,194,90,70,23,141,157,137,182,27,238,61,145,127,132,189,86,88,219,107,164,245,202,248,136,46,90,87,38,181,194,112,191,15,247,163,38,74,164,98,229,87,154,197,148,67,124,114,206,32,63,138,59,243,132,141,155,137,140,226,251,196,243,117,129,227,60,130,200,102,194,143,56,37,130,254,146,82,181,186,187,119,157,165,16,197,187,217,108,187,221,250,219,75,63,231,201,236,77,16,4,179,114,147,56,158,147,56,40,180,138,190,16,72,242,137,122,10,144,5,85,141,63,126,73,197,181,16,156,253,181,22,212,117,162,148,148,165,227,117,78,50,113,166,138,185,54,175,194,130,13,136,234,53,169,176,70,221,180,179,43,21,151,193,222,225,54,48,215,107,182,232,134,11,99,236,84,14,218,217,211,29,121,21,131,227,183,99,103,162,172,79,28,248,144,230,227,70,239,145,170,217,67,33,132,220,85,182,24,214,217,102,87,88,49,132,108,50,65,59,176,233,178,169,206,236,43,247,0,249,23,151,8,92,8,206,207,217,25,214,130,38,107,130,86,226,212,64,43,89,8,154,250,231,179,44,163,252,215,135,219,27,156,209,237,24,208,71,221,91,117,202,69,10,248,114,27,168,184,12,33,228,139,252,38,143,72,74,31,216,138,222,67,8,178,196,173,213,28,6,165,114,60,214,75,144,142,103,98,209,67,139,129,232,188,166,171,3,8,144,162,0,8,127,88,178,52,118,149,12,2,144,239,33,56,244,180,124,52,123,208,22,58,249,144,58,15,87,88,234,188,180,249,208,190,190,58,108,68,77,46,100,155,11,216,127,145,10,74,56,139,111,160,167,62,179,130,94,30,27,67,144,24,72,126,53,148,99,57,4,140,24,164,156,169,255,147,78,255,16,56,252,75,77,182,81,250,183,204,179,227,50,84,166,109,170,14,144,101,53,14,209,13,242,6,80,105,37,52,52,71,253,76,22,172,40,52,131,242,17,209,106,104,219,183,154,173,77,251,238,153,171,94,213,204,63,79,62,28,182,244,244,249,24,106,44,250,156,66,156,161,206,229,163,29,40,146,179,150,111,73,202,59,136,147,139,190,125,59,147,143,119,237,20,131,51,42,23,149,25,211,66,176,201,90,115,132,246,176,126,102,36,77,205,182,12,242,152,33,220,66,32,169,219,227,203,249,121,175,43,173,245,9,54,32,25,61,233,192,72,121,48,122,210,133,253,40,125,140,201,122,102,57,37,220,87,168,26,84,105,47,110,91,119,122,1,146,106,104,118,176,81,228,44,19,167,130,67,11,63,187,93,181,90,6,142,172,175,58,154,171,252,193,112,250,222,228,235,203,129,186,103,253,70,210,53,197,199,217,54,151,7,220,197,67,195,108,136,178,21,150,125,194,18,119,145,114,36,28,49,30,165,39,87,167,145,134,128,154,143,227,216,171,222,59,68,83,179,119,128,198,65,243,188,158,65,63,116,120,116,34,9,69,61,131,162,234,16,187,145,26,152,43,131,151,138,225,161,242,250,201,145,50,245,127,214,244,14,156,187,149,103,162,53,72,174,111,36,163,158,154,109,37,20,67,11,38,220,243,120,105,17,184,98,153,139,188,206,154,84,176,14,38,230,102,234,117,111,179,80,65,79,42,149,71,74,229,145,210,131,59,112,99,194,76,185,166,181,232,160,55,90,125,243,60,57,230,81,241,127,204,243,29,243,203,175,31,77,135,106,244,86,29,250,151,80,212,233,159,92,171,211,47,215,251,77,162,95,101,215,156,19,233,25,194,231,216,52,137,5,75,214,188,83,170,9,21,117,37,188,151,159,99,183,97,174,199,143,97,87,157,70,67,224,46,143,105,169,250,77,189,207,233,42,223,80,131,142,122,11,90,165,208,27,168,158,138,80,70,167,214,158,250,69,33,252,30,193,124,195,232,246,125,174,42,33,24,7,227,183,243,96,60,159,7,189,156,133,106,196,124,67,175,203,130,70,66,63,45,65,10,174,83,241,239,240,55,94,81,42,234,9,102,222,252,160,193,115,15,222,185,30,64,205,91,217,39,55,195,129,125,21,215,221,183,125,216,218,246,61,102,87,74,208,79,105,150,136,37,188,128,179,126,54,197,244,7,220,204,255,244,43,96,210,19,163,203,165,76,237,149,245,30,209,149,126,89,131,87,125,52,184,247,171,87,51,234,96,64,119,36,16,82,229,156,74,253,26,242,26,42,20,79,209,158,57,111,20,229,202,47,132,106,97,82,157,34,140,254,131,104,202,255,105,52,229,115,162,169,133,225,74,86,87,89,183,45,3,102,161,214,254,1,223,145,42,131,193,18,0,0 };

View File

@ -1,27 +1,5 @@
const char HTML_INDEX[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Control</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAPFBMVEUAAACA1VWR21qQ2liR3FqR3FqS3VuR3VqR3VuR3VqO21mS21uS3FqS3FqS21uJ2GKQ21qR3FuR3FoAAAB/3Gu7AAAAEnRSTlMABoA3kPBwz8i5Kzioxg4NVcU3uEJHAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAAN1wAADdcBQiibeAAAAAd0SU1FB+EFEhcEM+HpYwQAAABYSURBVBjThY/JDsAgCESt4lpX/v9jLQZJ6qF9t3khAyj1xXUKbQ4BVowDwqOYgExkkW4iY6lPaF06RqM8YItOuRbMaz6xjbsusDAW/drplBg47jP696cXE8bPA1eUDeK2AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTA1LTE4VDIzOjA0OjUxKzAyOjAwxE59ewAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0wNS0xOFQyMzowNDo1MSswMjowMLUTxccAAAAZdEVYdFNvZnR3YXJlAHd3dy5pbmtzY2FwZS5vcmeb7jwaAAAAAElFTkSuQmCC"
/>
<link rel="stylesheet" href="/css/normalize.css">
<link rel="stylesheet" href="/css/style.css">
<script src="/js/zepto.min.js"></script>
<script src="/js/slider.js"></script>
<script src="/js/controls.js"></script>
</head>
<body onload="javascript:start();">
<div>
<h4><div id="mainHeader">Control</div> <span id="conStatus" class="label">Offline</span></h4></div>
<hr />
<div class="container">
<div id="row" class="row u-full-width">
</div>
</div>
</body>
</html>
)=====";
const char HTML_INDEX[] PROGMEM = R"=====(
<!DOCTYPE html><html> <head><meta charset=utf-8><title>Control</title><meta name=viewport content="width=device-width, initial-scale=1"><link rel="shortcut icon" href=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAPFBMVEUAAACA1VWR21qQ2liR3FqR3FqS3VuR3VqR3VuR3VqO21mS21uS3FqS3FqS21uJ2GKQ21qR3FuR3FoAAAB/3Gu7AAAAEnRSTlMABoA3kPBwz8i5Kzioxg4NVcU3uEJHAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAAN1wAADdcBQiibeAAAAAd0SU1FB+EFEhcEM+HpYwQAAABYSURBVBjThY/JDsAgCESt4lpX/v9jLQZJ6qF9t3khAyj1xXUKbQ4BVowDwqOYgExkkW4iY6lPaF06RqM8YItOuRbMaz6xjbsusDAW/drplBg47jP696cXE8bPA1eUDeK2AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTA1LTE4VDIzOjA0OjUxKzAyOjAwxE59ewAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0wNS0xOFQyMzowNDo1MSswMjowMLUTxccAAAAZdEVYdFNvZnR3YXJlAHd3dy5pbmtzY2FwZS5vcmeb7jwaAAAAAElFTkSuQmCC><link rel=stylesheet href=/css/normalize.css><link rel=stylesheet href=/css/style.css><script src=/js/zepto.min.js></script><script src=/js/slider.js></script><script src=/js/graph.js></script><script src=/js/controls.js></script><script src=/js/tabbedcontent.js></script></head> <body onload=javascript:start();> <div> <h4> <div id=mainHeader>Control</div> <span id=conStatus class=label>Offline</span> </h4> </div> <hr> <div class=container> <div id=row class="row u-full-width"></div> <ul id=tabsnav class="navigation navigation-tabs u-full-width"></ul> <div id=tabscontent class="tabscontent u-full-width"></div> </div> </body> </html>
)=====";
const uint8_t HTML_INDEX_GZIP[916] PROGMEM = { 31,139,8,0,3,199,199,101,2,255,133,148,235,115,162,58,20,192,255,21,174,159,238,157,221,22,95,181,237,174,56,19,20,108,85,68,64,240,241,45,64,42,193,240,40,9,162,254,245,155,128,157,238,157,189,211,235,12,201,201,57,191,243,200,17,206,240,175,137,57,94,239,86,154,20,177,132,140,134,245,42,13,35,4,195,209,48,65,12,74,65,4,11,138,152,82,178,183,187,167,209,144,97,70,208,104,156,165,172,200,200,80,110,142,13,153,194,4,41,39,140,170,60,43,152,20,112,4,165,76,105,85,56,100,145,18,162,19,14,208,93,125,248,46,225,20,51,12,201,29,13,32,65,74,167,53,26,18,156,30,165,2,17,165,69,35,238,30,148,76,194,60,68,75,138,10,244,166,132,144,193,31,56,129,7,36,231,233,225,167,15,41,26,244,191,99,79,53,237,170,61,159,30,50,192,127,75,199,141,52,247,192,37,85,28,129,53,6,134,216,179,133,245,188,22,130,58,13,213,181,171,1,176,152,174,198,242,57,82,45,174,28,171,177,163,207,150,220,58,152,113,223,195,43,87,174,68,188,49,24,240,53,20,158,102,46,162,14,18,190,232,189,113,80,18,237,73,196,91,233,170,225,105,110,205,118,188,141,221,237,188,91,93,130,237,158,254,46,30,167,231,149,118,207,227,114,179,155,221,78,226,116,59,165,83,219,248,195,229,89,119,58,183,184,31,231,57,163,139,188,170,220,155,150,143,34,190,150,218,206,154,24,64,205,64,239,184,82,171,235,19,126,152,95,113,118,62,244,151,94,224,246,74,109,246,82,223,116,51,91,216,109,11,96,224,134,78,173,32,149,163,147,171,232,73,167,2,96,18,6,170,133,177,143,106,91,216,118,220,142,174,126,211,116,45,10,52,227,219,75,190,171,68,35,212,157,227,218,170,167,198,235,104,39,207,38,20,28,198,154,195,250,36,223,202,167,231,120,97,237,103,131,119,253,153,245,142,17,184,196,157,243,214,157,251,86,95,245,178,106,82,189,155,187,131,118,62,30,55,125,188,27,144,21,212,219,3,251,221,120,218,189,50,179,180,125,3,94,7,231,216,167,37,157,128,141,28,22,57,81,15,253,199,120,53,120,30,4,91,237,201,95,129,14,114,39,104,222,21,213,205,182,182,190,121,177,143,187,173,77,204,100,121,217,111,244,246,222,2,23,99,162,245,22,107,208,89,172,181,190,55,121,189,154,49,104,155,177,123,158,95,193,133,203,213,89,123,120,70,149,248,43,188,182,237,69,237,253,148,251,173,115,230,119,237,124,159,30,129,17,131,243,242,210,174,150,78,251,108,234,214,197,184,102,213,114,146,117,12,135,86,70,156,85,198,194,93,159,131,64,148,176,15,53,111,23,234,203,211,62,181,123,187,237,140,128,151,176,23,94,30,114,63,97,215,93,87,175,246,206,195,41,72,144,255,24,87,176,110,169,70,244,245,209,41,173,100,60,254,237,77,166,236,66,16,141,16,98,205,75,44,7,148,202,105,86,36,144,224,43,186,231,167,255,131,107,101,3,210,160,192,57,147,104,17,40,114,76,229,43,202,89,118,159,224,244,62,230,70,185,177,254,65,81,130,67,84,124,137,28,10,152,71,95,18,65,243,173,211,47,33,6,125,31,133,183,111,254,223,164,92,15,19,105,232,103,225,69,202,82,146,193,80,137,225,9,54,246,31,148,193,130,253,253,207,79,78,132,248,36,102,79,191,17,37,28,42,9,196,233,11,119,71,197,231,200,105,40,154,195,84,16,60,165,195,32,43,169,20,16,72,169,66,160,143,200,200,124,123,227,157,69,188,8,142,113,90,174,131,222,92,163,226,150,160,241,16,69,243,52,168,248,76,91,100,213,205,216,18,98,121,247,86,18,210,204,46,62,170,110,97,74,34,80,126,113,154,194,143,88,45,46,226,3,100,56,75,165,79,241,78,64,127,68,41,201,103,66,1,220,154,247,17,233,119,213,127,23,240,177,137,198,214,119,172,103,247,47,103,53,186,226,210,5,0,0 };

View File

@ -1,5 +1,5 @@
const char CSS_NORMALIZE[] PROGMEM = R"=====(
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:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}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 #c0c0c0;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}
)=====";
const uint8_t CSS_NORMALIZE_GZIP[865] PROGMEM = { 31,139,8,0,0,0,0,0,0,3,149,84,93,111,219,58,12,125,223,175,8,90,12,184,3,228,194,237,221,214,65,198,126,73,144,7,90,162,109,45,250,130,36,167,201,12,255,247,81,182,227,36,93,122,129,139,60,196,166,37,242,240,156,67,118,201,232,161,113,54,21,13,24,165,79,60,130,141,69,196,160,154,170,48,177,72,120,76,69,84,191,177,0,249,171,143,137,63,151,229,231,170,120,195,122,175,210,253,175,99,237,228,105,48,16,90,101,121,57,66,72,74,104,100,16,149,68,38,49,129,210,145,53,170,21,224,147,114,54,63,246,1,89,227,92,194,192,58,4,153,255,218,224,122,207,12,40,203,12,218,158,89,56,176,136,98,186,17,123,67,233,79,131,84,209,107,56,241,90,59,177,31,161,151,202,49,1,246,0,145,249,224,218,128,49,178,3,85,117,235,73,101,181,178,88,76,23,170,3,102,104,160,11,208,170,181,188,134,136,249,235,156,136,91,151,254,217,10,98,38,56,29,119,95,214,20,214,89,172,58,84,109,151,168,187,109,167,164,68,187,99,9,13,125,78,120,115,110,132,161,6,177,207,189,88,89,8,167,93,224,41,16,195,30,2,218,52,2,7,234,232,64,228,240,206,17,156,193,245,41,67,200,180,213,117,216,38,149,52,238,134,218,5,226,164,168,93,74,206,240,103,127,220,72,122,68,57,214,44,18,60,219,206,10,190,205,160,106,167,229,40,27,59,7,99,58,105,228,42,81,143,98,236,158,151,32,73,198,95,208,84,139,74,79,223,95,209,108,202,145,94,247,87,136,249,99,211,148,213,12,251,177,44,203,49,26,208,250,42,197,15,82,59,246,132,162,247,87,209,215,111,159,171,137,230,51,75,149,119,81,101,229,120,64,226,136,26,254,144,251,156,41,57,207,139,242,233,27,154,156,124,88,218,166,200,75,14,41,211,46,132,16,75,241,208,78,66,241,64,238,249,50,100,14,27,237,222,248,172,202,56,91,235,236,197,103,234,241,107,233,143,99,23,134,194,184,223,68,232,49,35,86,182,229,89,104,82,36,135,170,15,194,171,230,158,82,174,149,160,79,110,20,142,172,189,175,37,217,14,89,4,227,111,70,202,56,235,72,113,129,108,125,170,46,108,17,170,177,238,169,69,203,148,245,125,98,206,167,217,252,68,9,25,158,229,33,35,187,192,48,11,161,108,71,211,153,166,12,235,203,58,109,115,166,11,188,131,138,170,214,120,174,48,167,28,166,185,157,140,216,184,96,102,171,46,39,58,90,8,155,9,200,54,157,60,254,124,152,227,15,59,118,29,164,209,194,244,46,70,90,25,69,193,225,188,29,192,123,4,42,34,144,207,73,42,209,135,72,45,120,167,136,214,176,148,220,210,196,0,97,148,187,235,226,107,112,88,46,73,108,160,215,105,185,196,249,164,96,227,68,31,11,101,45,173,140,233,222,223,241,213,44,149,7,41,179,168,229,56,29,29,174,61,106,137,7,208,227,117,63,162,67,177,39,225,223,183,14,180,29,30,242,80,174,46,89,231,243,248,190,198,114,199,246,166,198,240,176,35,116,11,55,19,180,34,122,101,139,107,241,63,60,79,139,225,246,252,176,0,159,252,119,35,3,113,46,186,251,50,100,221,27,133,90,86,255,229,255,243,197,255,53,30,119,49,92,240,207,145,66,100,24,250,94,203,31,94,145,40,92,128,188,61,238,117,52,89,119,106,137,12,121,150,58,111,200,232,180,146,155,71,81,230,223,58,31,155,23,127,209,232,233,95,218,39,155,167,239,47,211,223,107,94,46,26,91,180,242,158,101,214,41,188,157,252,243,176,254,189,129,83,182,239,121,117,211,232,106,240,17,249,249,161,90,62,228,109,176,20,144,44,117,195,165,224,167,63,69,20,17,138,155,7,0,0 };
const char CSS_NORMALIZE[] PROGMEM = R"=====(
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}
)=====";
const uint8_t CSS_NORMALIZE_GZIP[859] PROGMEM = { 31,139,8,0,3,199,199,101,2,255,149,84,237,110,163,58,16,125,149,168,171,74,187,146,137,104,247,163,87,70,247,73,162,252,24,236,1,124,227,47,217,38,77,22,241,238,59,6,66,147,54,93,233,254,2,6,123,230,204,57,103,166,75,70,15,141,179,169,104,192,40,125,230,17,108,44,34,6,213,84,133,137,69,194,83,42,162,250,141,5,200,255,250,152,248,83,89,62,86,197,43,214,7,149,238,255,29,107,39,207,131,129,208,42,203,203,17,66,82,66,35,131,168,36,50,137,9,148,142,172,81,173,0,159,148,179,249,181,15,200,26,231,18,6,214,33,200,252,104,131,235,61,51,160,44,51,104,123,102,225,200,34,138,233,70,236,13,165,63,15,82,69,175,225,204,107,237,196,97,132,94,42,199,4,216,35,68,230,131,107,3,198,200,142,84,213,173,39,149,213,202,98,49,93,168,142,152,161,129,46,64,171,214,242,26,34,230,191,115,34,110,93,250,186,19,196,76,112,58,238,191,173,41,172,179,88,117,168,218,46,81,119,187,78,73,137,118,207,18,26,250,157,240,230,220,8,67,13,226,144,123,177,178,16,78,187,192,83,32,134,61,4,180,105,4,14,212,209,145,200,225,157,35,56,131,235,83,134,144,105,171,235,176,75,42,105,220,15,181,11,196,73,81,187,148,156,225,79,254,180,145,244,138,114,172,89,36,120,182,157,21,124,157,65,213,78,203,81,54,118,14,198,116,214,200,85,162,30,197,216,61,45,65,146,140,63,163,169,22,149,182,191,94,208,108,202,145,62,15,87,136,249,151,166,41,171,25,246,151,178,44,199,104,64,235,171,20,255,144,218,177,39,20,189,191,138,190,252,124,172,38,154,47,44,85,222,69,149,149,227,1,137,35,106,248,83,238,115,166,228,60,47,182,63,209,228,220,195,210,117,177,125,206,17,101,218,133,14,226,40,30,219,73,38,30,200,59,223,134,204,96,163,221,43,63,170,168,106,141,227,236,172,139,21,159,168,197,31,165,63,141,93,24,10,227,126,19,159,167,12,88,217,150,103,157,73,144,28,170,62,9,175,146,123,74,185,150,130,62,185,81,56,114,246,161,150,228,58,100,17,140,191,153,40,227,172,35,193,5,178,245,173,122,35,139,80,141,117,79,45,90,166,172,239,19,115,62,205,222,39,70,200,239,44,207,24,185,5,134,89,7,101,59,26,206,52,101,88,63,214,97,155,51,125,100,98,169,48,167,28,166,177,157,124,216,184,96,102,167,46,39,58,218,7,155,9,200,46,157,61,254,251,48,199,31,246,236,58,72,147,133,233,93,140,180,50,138,130,195,101,57,128,247,8,84,68,32,159,147,84,162,15,145,90,240,78,17,173,97,41,185,163,129,1,194,40,247,215,197,215,224,176,92,146,216,64,175,211,114,137,243,73,193,198,137,62,22,202,90,218,24,211,189,143,241,213,45,149,7,41,179,168,229,56,29,29,174,45,106,137,7,208,227,117,63,162,67,113,32,225,223,183,14,180,28,30,242,76,174,46,89,199,243,244,190,198,114,199,246,166,198,240,176,39,116,11,55,19,180,34,122,101,139,107,241,63,61,79,123,225,246,252,176,0,159,252,119,35,3,113,46,186,251,50,100,221,27,133,90,86,127,243,255,229,226,255,26,143,187,24,222,240,207,145,66,100,24,250,94,203,159,94,145,40,92,128,188,60,238,117,52,89,119,106,137,12,121,145,58,47,200,232,180,146,155,168,52,77,194,58,30,155,103,255,38,209,246,59,237,147,205,246,215,243,244,120,201,203,69,99,139,86,222,115,204,58,132,183,131,127,153,213,143,251,55,101,247,94,22,55,77,174,6,31,145,95,94,170,229,71,94,6,75,1,201,82,55,188,21,252,3,26,45,63,124,152,7,0,0 };

View File

@ -1,6 +1,15 @@
const char JS_SLIDER[] PROGMEM = R"=====(
function rkmd_rangeSlider(b){var f,e,c,a,g,d,h;f=$(b);e=f.width();c=f.offset().left;g=f;g.each(function(k,j){a=$(this);a.append(sliderDiscrete_tmplt());d=a.find('input[type="range"]');h=a.find(".slider");slider_fill=h.find(".slider-fill");slider_handle=h.find(".slider-handle");slider_label=h.find(".slider-label");var l=parseInt(d.val());slider_fill.css("width",l+"%");slider_handle.css("left",l+"%");slider_label.find("span").text(l)});f.on("mousedown touchstart",".slider-handle",function(o){if(o.button===2){return false}var m=$(this).parents(".rkmd-slider");var l=m.width();var i=m.offset().left;var k=m.find('input[type="range"]').is(":disabled");if(k===true){return false}$(this).addClass("is-active");var p=function(r){var q=r.pageX-i;if(q<=l&&!(q<"0")){slider_move(m,q,l,true)}};var n=function(q){$(this).off(j);m.find(".is-active").removeClass("is-active")};var j={mousemove:p,touchmove:p,mouseup:n,touchend:n};$(document).on(j)});f.on("mousedown touchstart",".slider",function(p){if(p.button===2){return false}var m=$(this).parents(".rkmd-slider");var l=m.width();var i=m.offset().left;var k=m.find('input[type="range"]').is(":disabled");if(k===true){return false}var o=p.pageX-i;if(o<=l&&!(o<"0")){slider_move(m,o,l,true)}var n=function(q){$(this).off(j)};var j={mouseup:n,touchend:n};$(document).on(j)})}function sliderDiscrete_tmplt(){var a='<div class="slider"><div class="slider-fill"></div><div class="slider-handle"><div class="slider-label"><span>0</span></div></div></div>';return a}function slider_move(g,a,h,e){var i=parseInt(Math.round(a/h*100));var b=g.find(".slider-fill");var c=g.find(".slider-handle");var f=g.find('input[type="range"]');b.css("width",i+"%");c.css({left:i+"%",transition:"none","-webkit-transition":"none","-moz-transition":"none"});f.val(i);if(g.find(".slider-handle span").text()!=i){g.find(".slider-handle span").text(i);var d=g.attr("id").substring(2);if(e){websock.send("slvalue:"+i+":"+d)}}};
)=====";
const uint8_t JS_SLIDER_GZIP[] PROGMEM = { 31,139,8,0,0,0,0,0,0,3,213,85,203,146,211,48,16,252,149,172,106,33,22,235,104,195,30,227,40,23,184,112,224,196,133,42,138,218,146,45,217,86,34,75,142,37,103,1,87,254,157,145,108,231,13,236,149,139,31,51,147,86,207,244,184,147,183,58,115,210,232,73,179,169,248,115,195,116,33,190,40,201,69,19,165,184,219,177,102,146,199,34,206,98,22,23,49,143,203,36,167,247,144,72,4,205,201,139,228,174,140,112,146,193,179,201,115,43,92,132,137,18,185,75,10,154,39,5,17,44,43,163,124,128,143,54,241,26,119,12,126,237,74,105,113,194,8,171,107,161,121,100,195,97,31,165,205,26,225,196,179,171,106,5,56,56,225,148,145,92,66,193,84,234,186,117,223,220,207,90,80,20,248,161,239,83,156,148,99,30,145,30,2,225,164,127,120,206,165,82,180,60,207,206,124,240,88,82,50,205,149,184,42,234,195,199,50,197,82,113,13,21,162,80,228,167,163,104,205,26,43,62,105,23,113,178,99,202,83,63,161,65,50,107,35,20,38,133,98,245,128,222,92,82,232,11,252,212,46,243,225,148,225,100,91,51,141,48,113,226,135,139,20,222,227,4,38,174,35,84,153,214,10,110,94,244,196,153,54,43,173,99,13,192,92,118,19,31,52,48,184,147,121,100,72,218,58,103,52,165,244,9,119,48,245,182,209,147,156,41,43,246,190,163,106,212,136,64,103,66,59,160,71,252,110,204,14,99,238,251,174,14,11,224,223,37,188,159,47,129,143,110,32,250,23,17,137,4,240,5,151,150,165,74,112,64,6,118,27,160,229,154,86,92,48,27,57,49,206,63,40,230,103,38,237,140,65,91,59,49,48,170,233,161,207,166,223,220,45,109,160,135,66,124,157,73,143,188,93,82,245,246,237,29,220,209,28,97,220,13,115,174,204,78,68,85,188,141,85,28,206,221,239,3,156,62,194,109,113,55,30,15,45,70,107,156,84,227,70,156,144,32,141,240,80,215,236,122,188,53,237,130,92,190,102,81,199,65,176,225,57,196,219,122,161,251,40,124,21,11,189,79,238,35,110,178,182,2,5,176,23,123,253,90,217,79,244,174,131,222,245,255,168,183,71,51,180,62,213,207,12,250,153,155,250,153,131,126,255,82,239,92,143,215,204,125,63,130,77,110,187,85,216,54,70,167,75,46,119,147,204,47,0,69,195,244,86,215,177,222,138,86,203,71,200,220,74,15,159,237,173,84,239,60,171,165,247,131,213,124,249,24,238,3,208,201,117,154,12,179,100,151,204,251,105,21,96,231,101,44,122,222,242,232,96,159,153,43,73,99,90,16,144,61,150,239,222,207,231,184,87,59,165,197,109,59,245,201,236,42,121,176,209,240,255,49,166,255,96,228,233,153,71,202,222,3,179,16,236,252,98,45,66,8,180,101,218,74,223,202,2,105,163,193,214,208,236,69,164,27,233,102,199,20,58,230,42,243,235,70,34,124,67,222,166,101,88,190,219,196,39,167,118,139,239,168,196,221,43,10,101,223,46,135,118,153,115,13,88,0,108,56,177,109,106,93,35,117,17,61,133,19,97,232,192,218,154,108,67,172,8,214,174,128,78,43,22,232,1,250,132,43,7,3,218,39,191,1,31,225,29,112,150,7,0,0 };
const char JS_SLIDER[] PROGMEM = R"=====(
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='<div class="slider">'+
'<div class="slider-fill"></div>'+
'<div class="slider-handle"><div class="slider-label"><span>0</span></div></div>'+
"</div>";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);}}
)=====";
const uint8_t JS_SLIDER_GZIP[881] PROGMEM = { 31,139,8,0,3,199,199,101,2,255,237,86,77,143,218,48,16,189,243,43,88,107,187,196,93,240,210,61,18,204,165,85,165,30,122,106,165,86,90,173,144,73,156,141,69,112,162,216,129,182,44,255,189,227,143,132,36,192,106,219,83,15,61,37,246,60,143,223,204,60,123,156,84,50,210,34,151,195,114,189,137,151,37,147,79,252,75,38,98,94,6,138,103,60,210,121,137,247,91,86,14,97,148,140,149,181,44,119,34,214,105,61,200,147,68,113,61,142,170,82,106,63,247,65,168,168,228,154,143,173,59,63,25,26,15,244,250,232,54,108,123,163,198,74,236,111,208,88,156,107,103,114,255,1,38,25,79,116,216,221,199,34,122,115,132,179,40,13,18,31,93,32,198,91,188,183,28,129,130,78,133,194,161,29,17,86,20,92,198,65,119,241,82,111,138,12,54,195,161,141,128,58,104,34,0,56,18,178,168,244,131,254,89,112,138,172,21,61,142,106,198,109,32,34,110,14,53,225,36,34,203,168,251,239,66,38,198,114,196,165,76,198,25,63,143,116,182,35,54,99,43,126,193,169,53,1,210,84,207,18,93,110,89,70,11,86,42,254,73,234,192,78,17,152,50,97,182,24,146,72,169,0,217,74,160,113,179,238,22,189,233,19,116,64,83,142,75,56,203,192,179,82,5,147,8,19,205,127,248,173,13,26,135,7,28,186,242,202,0,109,242,74,241,56,223,201,161,206,171,40,85,154,149,224,186,31,250,184,169,41,199,123,145,4,156,172,42,173,115,73,41,189,199,123,168,30,148,96,152,176,76,241,240,48,48,177,67,196,92,106,85,215,157,248,49,36,202,72,126,210,84,201,170,188,45,73,15,108,84,217,2,120,101,214,136,174,56,13,46,74,121,180,118,199,169,65,189,160,31,34,128,207,44,22,138,173,50,30,3,25,8,172,237,130,82,93,86,252,36,188,58,36,22,199,239,51,102,202,33,212,132,65,118,182,220,7,180,201,183,252,99,69,219,57,115,57,121,226,223,41,39,246,251,252,12,181,76,205,62,241,87,147,120,174,30,166,143,206,212,142,89,242,93,147,24,48,77,58,169,48,132,251,184,57,109,167,243,230,230,234,20,129,166,8,227,189,159,54,92,3,159,172,113,31,218,189,123,108,54,194,195,193,242,171,138,94,132,117,90,128,90,224,84,83,194,121,239,148,1,145,86,166,72,201,205,222,103,82,232,54,168,125,208,189,149,168,193,206,92,98,199,86,169,237,9,139,168,138,153,33,229,172,112,189,184,209,33,188,14,226,60,170,54,64,3,27,197,31,185,189,254,24,252,215,127,47,188,19,117,122,85,255,11,250,28,252,129,60,207,74,237,111,132,116,24,212,155,13,207,119,53,123,3,216,127,58,154,199,98,59,140,140,240,41,242,74,88,140,110,7,103,230,93,147,90,204,239,192,114,9,226,175,232,197,25,147,235,70,139,185,233,3,139,233,252,206,126,157,179,198,37,114,127,40,244,101,182,28,79,227,233,22,2,42,240,205,39,31,190,144,35,255,94,57,214,167,211,246,62,51,157,146,50,175,64,138,129,89,122,231,151,226,183,239,166,83,220,17,185,237,215,189,91,163,219,176,91,96,223,180,207,195,155,174,221,244,226,215,28,10,247,248,32,210,180,76,76,82,189,201,44,227,203,221,186,27,243,165,150,189,55,135,116,118,138,5,209,50,169,132,73,244,12,201,92,66,171,69,147,29,95,173,133,158,28,77,232,104,219,228,191,206,25,14,53,113,243,182,232,110,99,207,245,75,41,26,182,159,9,248,138,246,150,239,95,189,182,191,175,73,188,172,54,43,120,163,213,62,152,214,37,220,246,112,219,16,85,173,148,46,133,124,10,238,45,69,43,35,8,93,229,209,154,152,1,188,95,50,240,83,241,25,186,237,103,14,166,156,103,211,144,126,3,128,124,107,46,79,11,0,0 };

File diff suppressed because one or more lines are too long

39
src/dataTabbedcontentJS.h Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,134 @@
#!/usr/bin/env python3
from jsmin import jsmin as jsminify
from htmlmin import minify as htmlminify
from csscompressor import compress as cssminify
import gzip
import sys
import os.path
import argparse
import re
from glob import glob
TARGET_TEMPLATE = '''const char {constant}[] PROGMEM = R"=====(
{minidata}
)=====";
const uint8_t {constant}_GZIP[{gziplen}] PROGMEM = {{ {gzipdata} }};
'''
def parse_arguments(args=None):
parser = argparse.ArgumentParser(
description="Prepares ESPUI header files by minifying and gzipping HTML, JS and CSS source files.")
parser.add_argument("--auto", "--all", "-a", dest="auto", action="store_true",
help="Automatically find all source files in data/ and write C header files to src/")
parser.add_argument("--source", "--sources", "-s", dest="sources", default=None,
help="Sources directory containing CSS or JS files OR one specific file to minify")
parser.add_argument("--target", "-t", dest="target", default=None,
help="Target directory containing C header files OR one C header file")
parser.add_argument("--nostoremini", "-m", action="store_false", dest="storemini",
help="Do not store intermediate minified files next to the originals (i.e. only write to the C header files)")
args = parser.parse_args(args)
if not args.auto and (not args.sources or not args.target):
print("ERROR: You need to specify either --auto or both --source and --target\n")
parser.print_help()
sys.exit(1)
return args
def get_context(infile, outfile):
infile = os.path.realpath(infile)
dir, name, type = (os.path.basename(os.path.dirname(infile)), os.path.basename(infile).split(os.path.extsep)[0], os.path.basename(infile).split(os.path.extsep)[-1] )
type = type.strip(".").lower()
if dir.lower() == type:
dir = os.path.basename(os.path.dirname(os.path.dirname(infile)))
if type == "htm":
type = 'html'
name = os.path.basename(name)
indir = os.path.dirname(infile)
if os.path.isdir(outfile):
outdir = os.path.realpath(outfile)
outfilename = "%s%s%s.h" % (dir, name.capitalize(), type.upper())
outfile = os.path.realpath(os.path.sep.join([outdir, outfilename]))
else:
outfile = os.path.realpath(outfile)
outdir = os.path.dirname(outfile)
outfilename = os.path.basename(outfile)
minifile = re.sub('\.([^.]+)$', '.min.\\1', infile) if not ".min." in infile else infile
constant = '%s_%s' % (type.upper(), name.upper())
return locals()
def perform_gzip(c):
compressed = gzip.compress(bytes(c['minidata'], 'utf-8'))
c['gzipdata'] = ','.join([ str(b) for b in compressed ])
c['gziplen'] = len(compressed)
print(" GZIP data length: %s" % c['gziplen'])
return c
def perform_minify(c):
with open(c['infile']) as infile:
minifier = {
'css': cssminify,
'js': jsminify,
'html': htmlminify
}.get(c['type']) or htmlminify
print(" Using %s minifier" % c['type'])
c['minidata'] = minifier(infile.read())
return perform_gzip(c)
def process_file(infile, outdir, storemini=True):
print("Processing file %s" % infile)
c = get_context(infile, outdir)
c = perform_minify(c)
if storemini:
if c['infile'] == c['minifile']:
print(" Original file is already minified, refusing to overwrite it")
else:
print(" Writing minified file %s" % c['minifile'])
with open(c['minifile'], 'w+') as minifile:
minifile.write(c['minidata'])
with open(c['outfile'], 'w+') as outfile:
print(" Using C constant names %s and %s_GZIP" % (c['constant'], c['constant']))
print(" Writing C header file %s" % c['outfile'])
outfile.write(TARGET_TEMPLATE.format(**c))
def filenamefilter(pattern, strings):
return filter(re.compile(pattern).search, strings)
def process_dir(sourcedir, outdir, recursive=True, storemini=True):
pattern = r'/*\.(css|js|htm|html)$'
files = glob(sourcedir + "/**/*", recursive=True)+glob(sourcedir + "/*") if recursive else glob(sourcedir + "/*")
files = filenamefilter(pattern, files)
for f in set(files):
if not '.min.' in f:
process_file(f, outdir, storemini)
elif not os.path.isfile(f.replace(".min.", ".")):
process_file(f, outdir, storemini)
def check_args(args):
abort = 0
if not os.path.exists(args.sources):
print("ERROR: Source %s does not exist" % args.sources)
abort += 2
if not os.path.isdir(os.path.dirname(args.target)):
print("ERROR: Parent directory of target %s does not exist" % args.target)
abort += 4
if os.path.isdir(args.sources) and not os.path.isdir(args.target):
print("ERROR: Source %s is a directory, target %s is not" % (args.sources, args.target))
abort += 8
if abort > 0:
print("Aborting.")
sys.exit(abort)
def main(args):
args.sources = os.path.realpath(args.sources or os.sep.join((os.path.dirname(os.path.realpath(__file__)), "..", "data")))
args.target = os.path.realpath(args.target or os.sep.join((os.path.dirname(os.path.realpath(__file__)), "..", "src")))
check_args(args)
if os.path.isfile(args.sources):
print("Source %s is a file, will process one file only." % args.sources)
process_file(args.sources, args.target, storemini = args.storemini)
elif os.path.isdir(args.sources):
print("Source %s is a directory, searching for files recursively..." % args.sources)
process_dir(args.sources, args.target, recursive = True, storemini = args.storemini)
if __name__ == "__main__" and "get_ipython" not in dir():
main(parse_arguments())