Merge pull request #152 from iangray001/master

Vertical controls and a major rehaul of the documentation
This commit is contained in:
Ian Gray 2022-01-29 14:52:56 +00:00 committed by GitHub
commit 7dcf6a10f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 998 additions and 337 deletions

635
README.md
View File

@ -1,8 +1,8 @@
# 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 user interface for your projects using
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,
control, and update elements on your GUI through multiple devices like phones
and tablets.
@ -14,37 +14,59 @@ 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 fine on any kind of **ESP8266** and **ESP32** (NodeMCU Boards, usw)
The Library runs on any kind of **ESP8266** and **ESP32** (NodeMCU, AI Thinker, etc.).
## Changelog for 2.0:
- [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)
* [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)
* [Grouped controls](#grouped-controls)
* [Wide controls](#wide-controls)
* [Graph (Experimental)](#graph--experimental-)
- [Notes for Development](#notes-for-development)
- [Contribute](#contribute)
- ArduinoJSON 6.10.0 Support
- split pad into pad and padWithCenter
- Cleaned Order or parameters on switch
- cleaned Order of parameters on pad
- Changes all numbers to actually be numbers (slider value, number value, min and max)
### Added features
### Contributed features
- Tabs by @eringerli #45
- Tabs by @eringerli
- Generic API by @eringerli
- Min Max on slider by @eringerli
- OptionList by @eringerli
- Public Access to ESPAsyncServer
- Graph Widget (Persist save graph in local storage #10)
- 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
## Further Roadmap
## Roadmap
- Slider css issues
- implement Gauge
- File upload ?
- 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) (Last tested with
@ -58,37 +80,25 @@ This library is dependent on the following libraries to function properly.
Make sure all the dependencies are installed, then install like so:
#### Using PlattformIO (_recommended_)
#### Using PlatformIO (_recommended_)
Just include this library as a dependency on lib_deps like so:
Just include this library as a dependency in `lib_deps` like so:
```
lib_deps =
ESPUI
ESPAsyncWebserver
ESPAsyncTCP # or AsyncTCP on ESP32
ESP Async WebServer
ESPAsyncTCP # (or AsyncTCP on ESP32)
LittleFS_esp32 # (ESP32 only)
```
#### Directly Through Arduino IDE (_recommended_)
#### Using the Arduino IDE (_recommended_)
You can find this Library in the Arduino IDE library manager Go to Sketch >
Include Library > Library Manager > Search for "ESPUI" > Install
You can find this Library in the Arduino IDE library manager. Go to
`Sketch > Include Library > Library Manager` search for `ESPUI` and install.
#### Manual Install Arduino IDE
_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}
_For Linux:_ Download the
[Repository](https://github.com/s00500/ESPUI/archive/master.zip) and extract the
.zip in Sketchbook/Libraries/{Place "ESPUI" folder Here}
_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}
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
@ -120,36 +130,22 @@ more program memory to work with.
- Button
- Switch
- Control pad
- Control pad with center button
- Slider
- Text Input
- Numberinput
- Graph
- Option select
- Separator
- Time
- Graph (partial implementation)
Checkout the example for the usage or see the detailed info below
## Available colors:
- Turquoise
- Emerald
- Peterriver
- Wetasphalt
- Sunflower
- Carrot
- Alizarin
- Dark
- None
(Use like `ControlColor::Sunflower`)
## 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 _ESP_ and the client browser works using web
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.
@ -162,60 +158,58 @@ 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:
statement.
#### 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 (`B_DOWN`) and one
for release (`B_UP`).
Buttons have a name and a callback value. Their text can be changed at runtime using `ESPUI.updateButton()`.
- B_DOWN
- B_UP
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 when turning on (`S_ACTIVE`)
and one when turning off (`S_INACTIVE`).
their value (either by pressing them, or programmatically using `ESPUI.updateSwitcher()`) they change visibly
on all tablets or computers that currently display the interface.
- S_ACTIVE
- S_INACTIVE
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
- `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.
@ -232,250 +226,107 @@ This requires that the client has access to the image in question, either from t
#### Slider
![slider](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. In the Callback the slider does not return an int but a String.
Use the .toInt function to convert the value, see the **gui** example to check how it works.
Sliders can be used to select (or display) a numerical value. Sliders provide
realtime data and are touch compatible. Note that like all ESPUI functions, the callback does not return an `int`
but a `String` so should be converted with the `.toInt()` function. See the examples for more details. Sliders can
be updated from code using `ESP.updateSlider()`.
A slider usually only sends a new value when it is released to save the esps from being spammed with values. This behaviour can be cahnged globally using a property of the ESPUI object before `begin()`:
A slider usually only sends a new value when it is released to save network bandwidth.
This behaviour can be changed globally by setting `sliderContinuous` before `begin()`:
```
ESPUI.sliderContinuous = true;
ESPUI.begin("ESPUI Control");
ESPUI.sliderContinuous = true;
ESPUI.begin("ESPUI Control");
```
Events:
- `SL_VALUE` - Fired when a slider value changes.
#### Number Input
![number](https://github.com/s00500/ESPUI/blob/master/docs/ui_number.png)
![number](docs/ui_number.png)
The numberinput can be used to directly input numbers to your program. 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:
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](https://github.com/s00500/ESPUI/blob/master/docs/ui_text.png)
The textinput works very similar like the number input but with a string. You
can enter a String into it and when you are done with your change it is sent to
the ESP.
![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 = 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.
#### Graph
Events:
- `T_VALUE` - Fired when a text value changes.
![graph](https://github.com/s00500/ESPUI/blob/master/docs/ui_graph.png)
The graph widget can display graph points with timestamp at wich they arrive
#### Select control
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.
![option1](docs/ui_select1.png)
![option2](docs/ui_select2.png)
#### Option select
![option1](https://github.com/s00500/ESPUI/blob/master/docs/ui_select1.png)
![option2](https://github.com/s00500/ESPUI/blob/master/docs/ui_select2.png)
The option select works by first creating a select widget like so
`uint16_t select1 = ESPUI.addControl( ControlType::Select, "Select:", "", ControlColor::Alizarin, tab1, &selectExample );`
And then adding Options to it like seperate widgets, specifying the select as the parent:
The Select control lets the user select from a predefined list of options. First create a select widget like so
```
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 );
uint16_t select1 = ESPUI.addControl( ControlType::Select, "Select Title", "Initial Value", ControlColor::Alizarin, tab1, &selectExample );
```
Check the **tabbedGui** example for a working demo
### Using Tabs
![tabs](https://github.com/s00500/ESPUI/blob/master/docs/ui_tabs.png)
Tabs can be used to organize your widgets in pages. Check the tabbedGui example.
Tabs can be created using the generic functions like so:
`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 parrent (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 );`
### 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:
Then add Options to it, specifying the Select as the parent:
```
ESPUI.separator("Separator name");
//or
ESPUI.addControl(ControlType::Separator, "Separator name", "", ControlColor::None, maintab);
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);
```
### Initialisation of the UI
Check the **tabbedGui** example for a working demo. Selectors can be updated from code using `ESP.updateSelect()`.
After all the elements are configured you can use `ESPUI.begin("Some Title");`
to start the UI interface. (Or `ESPUI.beginLITTLEFS("Some Title");` respectively)
Make sure you setup a working network connection or AccesPoint **before** (See
gui.ino example). The web interface can then be used from multiple devices at once and
also shows an connection status in the top bar.
Events:
- `S_VALUE` - Fired when a select value changes.
### Advanced: Generic creation and updates of control widgets
#### Getting the Time
There are 2 generic functions to create and update controls, to see them in action check the **gui-generic-api** example.
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.
To create a generic control use:
`uint16_t switchOne = ESPUI.addControl(ControlType::Switcher, "Switch one", "", ControlColor::Alizarin, Control::noParent, &switchExample);`
Then its value can be updated by doing:
`ESPUI.updateControlValue(status, "Start");`
You can also update other parameters of the control like its color using:
```
ESPUI.getControl(switchOne)->color = ControlColor::Carrot;
ESPUI.updateControl(switchOne);
```
### 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.
### Advanced properties
If you have many different widgets it might be necessary to adjust the JSON Buffers used internally in ESPUI before .begin() :
```
ESPUI.jsonUpdateDocumentSize = 2000; // This is the default, and this value is not affected by the amount of widgets
ESPUI.jsonInitialDocumentSize = 8000; // This is the default, adjust when you have too many widgets or options
ESPUI.begin("ESPUI Control");
```
### 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)
Note: The images in this example are formed by setting a Label to contain an `<img>` tag:
```
ESPUI.addControl(ControlType::Label, "Label", "<img src='path/to/image'>", ControlColor::Peterriver);
```
### 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 elements](docs/ui_groupedbuttons2.png)
If you group too many elements it might throw the layout of the rest of the UI out of line. Consider adding separators to correct this.
### Advanced: 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.
### Advanced: 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. If this is not a concern, you can do the following:
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.
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
@ -495,6 +346,205 @@ void timeCallback(Control *sender, int type) {
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
Cotrols 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)
### 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!_
# Notes for Development
If you want to work on the HTML/CSS/JS files, do make changes in the _data_
@ -514,6 +564,23 @@ 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)
## 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:

View File

@ -1128,3 +1128,23 @@ svg {
text {
text-anchor: end;
}
/* Styles to implement vertical orientations */
.vert-switcher {
transform: rotate(270deg);
margin-top: 15px;
margin-bottom: 25px;
}
.vert-slider {
width: 150px;
transform: rotate(270deg);
display: inline-block;
margin: 50px -42px 70px -42px;
}
.vert-slider span {
transform: rotate(90deg);
}

File diff suppressed because one or more lines are too long

46
data/js/controls.js vendored
View File

@ -575,6 +575,13 @@ function start() {
$("#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"
@ -700,7 +707,6 @@ var rangeSlider = function (isDiscrete) {
var addToHTML = function(data) {
panelStyle = data.hasOwnProperty('panelStyle') ? " style='" + data.panelStyle + "' " : "";
elementStyle = data.hasOwnProperty('elementStyle') ? " style='" + data.elementStyle + "' " : "";
panelwide = data.hasOwnProperty('wide') ? "wide" : "";
if(!data.hasOwnProperty('parentControl') || $("#tab" + data.parentControl).length > 0) {
@ -725,7 +731,7 @@ var addToHTML = function(data) {
case UI_ACCEL:
html = "<div id='id" + data.id + "' " + panelStyle + " class='two columns " + panelwide + " card tcenter " +
colorClass(data.color) + "'><h5>" + data.label + "</h5><hr/>" +
elementHTML(data.type, data.id, data.value, data.label, elementStyle) +
elementHTML(data) +
"</div>";
break;
case UI_SEPARATOR:
@ -742,26 +748,30 @@ var addToHTML = function(data) {
} else {
//We are adding to an existing panel so we only need the HTML for the element
var parent = $("#id" + data.parentControl);
parent.append(elementHTML(data.type, data.id, data.value, data.label, elementStyle));
parent.append(elementHTML(data));
}
}
var elementHTML = function(type, id, value, label, elementStyle) {
switch(type) {
var elementHTML = function(data) {
var id = data.id
var elementStyle = data.hasOwnProperty('elementStyle') ? " style='" + data.elementStyle + "' " : "";
switch(data.type) {
case UI_LABEL:
return "<span id='l" + id + "' " + elementStyle +
" class='label label-wrap'>" + value + "</span>";
" class='label label-wrap'>" + data.value + "</span>";
case UI_BUTTON:
return "<button id='btn" + id + "' " + elementStyle +
" onmousedown='buttonclick(" + id + ", true)'" +
" onmouseup='buttonclick(" + id + ", false)'>" +
value + "</button>";
data.value + "</button>";
case UI_SWITCHER:
return "<label id='sl" + id + "' " + elementStyle +
" class='switch " + (value == "1" ? "checked" : "") + "'>" +
" class='switch " + (data.value == "1" ? "checked" : "") +
(data.hasOwnProperty('vertical') ? " vert-switcher " : "") +
"'>" +
"<div class='in'>" +
"<input type='checkbox' id='s" + id + "' onClick='switcher(" + id + ",null)' " +
(value == "1" ? "checked" : "") + "/></div></label>";
(data.value == "1" ? "checked" : "") + "/></div></label>";
case UI_CPAD:
case UI_PAD:
return "<nav class='control'><ul>" +
@ -774,30 +784,32 @@ var elementHTML = function(type, id, value, label, elementStyle) {
"<li><a onmousedown='padclick(DOWN, " + id + ", true)' " +
"onmouseup='padclick(DOWN, " + id + ", false)' id='pb" + id + "'>&#9650;</a></li>" +
"</ul>" +
(type == UI_CPAD
(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'>" +
"<input id='sl" + id + "' type='range' min='0' max='100' value='" + value + "' " +
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'>" +
value + "</span></div>";
data.value + "</span></div>";
case UI_NUMBER:
return "<input style='color:black;' " + elementStyle + " id='num" + id +
"' type='number' value='" + value + "' onchange='numberchange(" + id + ")' />";
"' type='number' value='" + data.value + "' onchange='numberchange(" + id + ")' />";
case UI_TEXT_INPUT:
return "<input style='color:black;' " + elementStyle + " id='text" + id +
"' value='" + value + "' onchange='textchange(" + id + ")' />";
"' value='" + data.value + "' onchange='textchange(" + id + ")' />";
case UI_SELECT:
return "<select style='color:black;' " + elementStyle + " id='select" + id +
"' onchange='selectchange(" + id + ")' />";
case UI_GRAPH:
return "<figure id='graph" + id + "'><figcaption>" + label + "</figcaption></figure>";
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='" + value + "' onchange='numberchange(" + 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>";

View File

@ -41,6 +41,9 @@ break;case UPDATE_BUTTON:$("#btn"+data.id).val(data.value);$("#btn"+data.id).tex
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;default:console.error("Unknown type or event");break;}
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));}}
$(".range-slider__range").each(function(){$(this)[0].value=$(this).attr("value");$(this).next().html($(this).attr("value"));});};websock.onmessage=handleEvent;}
function sliderchange(number){var val=$("#sl"+number).val();websock.send("slvalue:"+val+":"+number);$(".range-slider__range").each(function(){$(this).attr("value",$(this)[0].value);});}
@ -52,21 +55,24 @@ function buttonclick(number,isdown){if(isdown)websock.send("bdown:"+number);else
function padclick(type,number,isdown){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+"' ":"";elementStyle=data.hasOwnProperty('elementStyle')?" style='"+data.elementStyle+"' ":"";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:html="<div id='id"+data.id+"' "+panelStyle+" class='two columns "+panelwide+" card tcenter "+
$(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:html="<div id='id"+data.id+"' "+panelStyle+" class='two columns "+panelwide+" card tcenter "+
colorClass(data.color)+"'><h5>"+data.label+"</h5><hr/>"+
elementHTML(data.type,data.id,data.value,data.label,elementStyle)+
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.type,data.id,data.value,data.label,elementStyle));}}
var elementHTML=function(type,id,value,label,elementStyle){switch(type){case UI_LABEL:return"<span id='l"+id+"' "+elementStyle+
" class='label label-wrap'>"+value+"</span>";case UI_BUTTON:return"<button id='btn"+id+"' "+elementStyle+
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+"' ":"";switch(data.type){case UI_LABEL:return"<span id='l"+id+"' "+elementStyle+
" class='label label-wrap'>"+data.value+"</span>";case UI_BUTTON:return"<button id='btn"+id+"' "+elementStyle+
" onmousedown='buttonclick("+id+", true)'"+
" onmouseup='buttonclick("+id+", false)'>"+
value+"</button>";case UI_SWITCHER:return"<label id='sl"+id+"' "+elementStyle+
" class='switch "+(value=="1"?"checked":"")+"'>"+
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)' "+
(value=="1"?"checked":"")+"/></div></label>";case UI_CPAD:case UI_PAD:return"<nav class='control'><ul>"+
(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)' "+
@ -76,14 +82,16 @@ value+"</button>";case UI_SWITCHER:return"<label id='sl"+id+"' "+elementStyle+
"<li><a onmousedown='padclick(DOWN, "+id+", true)' "+
"onmouseup='padclick(DOWN, "+id+", false)' id='pb"+id+"'>&#9650;</a></li>"+
"</ul>"+
(type==UI_CPAD?"<a class='confirm' onmousedown='padclick(CENTER,"+id+", true)' "+
(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'>"+
"<input id='sl"+id+"' type='range' min='0' max='100' value='"+value+"' "+
"</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'>"+
value+"</span></div>";case UI_NUMBER:return"<input style='color:black;' "+elementStyle+" id='num"+id+
"' type='number' value='"+value+"' onchange='numberchange("+id+")' />";case UI_TEXT_INPUT:return"<input style='color:black;' "+elementStyle+" id='text"+id+
"' value='"+value+"' onchange='textchange("+id+")' />";case UI_SELECT:return"<select style='color:black;' "+elementStyle+" id='select"+id+
"' onchange='selectchange("+id+")' />";case UI_GRAPH:return"<figure id='graph"+id+"'><figcaption>"+label+"</figcaption></figure>";case UI_GAUGE:return"WILL BE A GAUGE <input style='color:black;' id='gauge"+id+
"' type='number' value='"+value+"' onchange='numberchange("+id+")' />";case UI_ACCEL:return"ACCEL // Not implemented fully!<div class='accelerometer' id='accel"+id+
data.value+"</span></div>";case UI_NUMBER:return"<input style='color:black;' "+elementStyle+" id='num"+id+
"' type='number' value='"+data.value+"' onchange='numberchange("+id+")' />";case UI_TEXT_INPUT:return"<input style='color:black;' "+elementStyle+" id='text"+id+
"' value='"+data.value+"' onchange='textchange("+id+")' />";case UI_SELECT:return"<select style='color:black;' "+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"";}}

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_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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

View File

@ -0,0 +1,523 @@
/**
* @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
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#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);
//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() {
//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, generalCallback);
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);
}
//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);
}
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
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

@ -855,6 +855,14 @@ void ESPUIClass::setPanelWide(uint16_t id, bool wide) {
}
}
void ESPUIClass::setVertical(uint16_t id, bool vert) {
Control* control = getControl(id);
if (control)
{
control->vertical = vert;
}
}
void ESPUIClass::updateControl(uint16_t id, int clientId)
{
Control* control = getControl(id);
@ -902,6 +910,15 @@ void ESPUIClass::updateControlValue(uint16_t id, const String& value, int client
updateControlValue(control, value, clientId);
}
void ESPUIClass::updateVisibility(uint16_t id, bool visibility, int clientId) {
Control* control = getControl(id);
if(control)
{
control->visible = visibility;
updateControl(id);
}
}
void ESPUIClass::print(uint16_t id, const String& value)
{
updateControlValue(id, value);
@ -1097,6 +1114,8 @@ void ESPUIClass::prepareJSONChunk(AsyncWebSocketClient* client, uint16_t startin
item["elementStyle"] = String(control->elementStyle);
if (control->wide == true)
item["wide"] = true;
if (control->vertical == true)
item["vertical"] = true;
if (control->parentControl != Control::noParent)
{

View File

@ -141,6 +141,7 @@ public:
ControlColor color;
bool visible;
bool wide;
bool vertical;
uint16_t parentControl;
String panelStyle;
String elementStyle;
@ -157,6 +158,7 @@ public:
color(color),
visible(visible),
wide(false),
vertical(false),
parentControl(parentControl),
next(nullptr)
{
@ -298,6 +300,8 @@ public:
void setElementStyle(uint16_t id, String style, int clientId = -1);
void setPanelWide(uint16_t id, bool wide);
void setVertical(uint16_t id, bool vert = true);
void updateVisibility(uint16_t id, bool visibility, int clientId = -1);
// Variables
const char* ui_title = "ESPUI"; // Store UI Title and Header Name

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long