Fork of the excellent esp8266-react - https://github.com/rjwats/esp8266-react
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

659 lines
28 KiB

6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. # ESP8266 React
  2. [![Build Status](https://travis-ci.org/rjwats/esp8266-react.svg?branch=master)](https://travis-ci.org/rjwats/esp8266-react)
  3. A simple, secure and extensible framework for IoT projects built on ESP8266/ESP32 platforms with responsive [React](https://reactjs.org/) front-end built with [Material-UI](https://material-ui.com/).
  4. Designed to work with the PlatformIO IDE with [limited setup](#getting-started). Please read below for setup, build and upload instructions.
  5. ![Screenshots](/media/screenshots.png?raw=true "Screenshots")
  6. ## Features
  7. Provides many of the features required for IoT projects:
  8. * Configurable WiFi - Network scanner and WiFi configuration screen
  9. * Configurable Access Point - Can be continuous or automatically enabled when WiFi connection fails
  10. * Network Time - Synchronization with NTP
  11. * MQTT - Connection to an MQTT broker for automation and monitoring
  12. * Remote Firmware Updates - Firmware replacement using OTA update or upload via UI
  13. * Security - Protected RESTful endpoints and a secured user interface
  14. Features may be [enabled or disabled](#selecting-features) as required at compile time.
  15. ## Getting Started
  16. ### Prerequisites
  17. You will need the following before you can get started.
  18. * [PlatformIO](https://platformio.org/) - IDE for development
  19. * [Node.js](https://nodejs.org) - For building the interface with npm
  20. ### Building and uploading the firmware
  21. Pull the project and open it in PlatformIO. PlatformIO should download the ESP8266 platform and the project library dependencies automatically.
  22. The project structure is as follows:
  23. Resource | Description
  24. -------------------------------- | ----------------------------------------------------------------------
  25. [interface/](interface) | React based front end
  26. [lib/framework/](lib/framework) | C++ back end for the ESP8266/ESP32 device
  27. [src/](src) | The main.cpp and demo project to get you started
  28. [scripts/](scripts) | Scripts that build the React interface as part of the platformio build
  29. [platformio.ini](platformio.ini) | PlatformIO project configuration file
  30. ### Building the firmware
  31. Once the platform and libraries are downloaded the back end should successfully build within PlatformIO.
  32. The firmware may be built by pressing the "Build" button:
  33. ![build](/media/build.png?raw=true "build")
  34. Alternatively type the run command:
  35. ```bash
  36. platformio run
  37. ```
  38. #### Uploading the firmware
  39. The project is configured to upload over a serial connection by default. You can change this to use OTA updates by uncommenting the relevant lines in ['platformio.ini'](platformio.ini).
  40. The firmware may be uploaded to the device by pressing the "Upload" button:
  41. ![uploadfw](/media/uploadfw.png?raw=true "uploadfw")
  42. Alternatively run the 'upload' target:
  43. ```bash
  44. platformio run -t upload
  45. ```
  46. ### Building & uploading the interface
  47. The interface has been configured with create-react-app and react-app-rewired so the build can customized for the target device. The large artefacts are gzipped and source maps and service worker are excluded from the production build. This reduces the production build to around ~150k, which easily fits on the device.
  48. The interface will be automatically built by PlatformIO before it builds the firmware. The project can be configured to serve the interface from either PROGMEM or the filesystem as your project requires. The default configuration is to serve the content from PROGMEM, serving from the filesystem requires an additional upload step which is [documented below](#serving-the-interface-from-the-filesystem).
  49. #### Serving the interface from PROGMEM
  50. By default, the project is configured to serve the interface from PROGMEM.
  51. > **Tip**: You do not need to upload a file system image unless you configure the framework to [serve the interface from the filesystem](#serving-the-interface-from-the-filesystem).
  52. The interface will consume ~150k of program space which can be problematic if you already have a large binary artefact or if you have added large dependencies to the interface. The ESP32 binaries are fairly large in there simplest form so the addition of the interface resources requires us to use special partitioning for the ESP32.
  53. When building using the "node32s" profile, the project uses the custom [min_spiffs.csv](https://github.com/espressif/arduino-esp32/blob/master/tools/partitions/min_spiffs.csv) partitioning mode. You may want to disable this if you are manually uploading the file system image:
  54. ```ini
  55. [env:node32s]
  56. board_build.partitions = min_spiffs.csv
  57. platform = espressif32
  58. board = node32s
  59. ```
  60. #### Serving the interface from the filesystem
  61. If you choose to serve the interface from the filesystem you will need to change the default configuration and upload the file system image manually.
  62. Disable `-D PROGMEM_WWW build` flag in ['platformio.ini'](platformio.ini) and re-build the firmware. The build process will now copy the compiled interface to the `data/` directory and it may be uploaded to the device by pressing the "Upload File System image" button:
  63. ![uploadfs](/media/uploadfs.png?raw=true "uploadfs")
  64. Alternatively run the 'uploadfs' target:
  65. ```bash
  66. platformio run -t uploadfs
  67. ```
  68. ### Developing the interface locally
  69. UI development is an iterative process so it's best to run a development server locally during interface development (using `npm start`). This can be accomplished by deploying the backend to a device and configuring the interface to point to it:
  70. ![Development Server](/media/devserver.png?raw=true "Development Server")
  71. The following steps can get you up and running for local interface development:
  72. - [Enable CORS](#enabling-cors) in platformio.ini
  73. - Deploy firmware to device
  74. - [Configure endpoint root](#configuring-the-endpoint-root) with device's IP in interface/.env.development
  75. - [Start the development server](#starting-the-development-server) with "npm start"
  76. - Develop interface locally
  77. #### Enabling CORS
  78. You can enable CORS on the back end by uncommenting the -D ENABLE_CORS build flag in ['platformio.ini'](platformio.ini) then re-building and uploading the firmware to the device. The default settings assume you will be accessing the development server on the default port on [http://localhost:3000](http://localhost:3000) this can also be changed if required:
  79. ```ini
  80. -D ENABLE_CORS
  81. -D CORS_ORIGIN=\"http://localhost:3000\"
  82. ```
  83. #### Configuring the endpoint root
  84. The interface has a development environment which is enabled when running the development server using `npm start`. The environment file can be found in ['interface/.env.development'](interface/.env.development) and contains the HTTP root URL and the WebSocket root URL:
  85. ```ini
  86. REACT_APP_HTTP_ROOT=http://192.168.0.99
  87. REACT_APP_WEB_SOCKET_ROOT=ws://192.168.0.99
  88. ```
  89. The `REACT_APP_HTTP_ROOT` and `REACT_APP_WEB_SOCKET_ROOT` properties can be modified to point a ESP device running the back end.
  90. > **Tip**: You must restart the development server for changes to the environment file to come into effect.
  91. #### Starting the development server
  92. Change to the ['interface'](interface) directory with your bash shell (or Git Bash) and use the standard commands you would with any react app built with create-react-app:
  93. ```bash
  94. cd interface
  95. ```
  96. Install the npm dependencies, if required and start the development server:
  97. ```bash
  98. npm install
  99. npm start
  100. ```
  101. > **Tip**: You can (optionally) speed up the build by commenting out the call to build_interface.py under "extra scripts" during local development. This will prevent the npm process from building the production release every time the firmware is compiled significantly decreasing the build time.
  102. ## Selecting features
  103. Many of the framework's built in features may be enabled or disabled as required at compile time. This can help save sketch space and memory if your project does not require the full suite of features. The access point and WiFi management features are "core features" and are always enabled. Feature selection may be controlled with the build flags defined in [features.ini](features.ini).
  104. Customize the settings as you see fit. A value of 0 will disable the specified feature:
  105. ```ini
  106. -D FT_PROJECT=1
  107. -D FT_SECURITY=1
  108. -D FT_MQTT=1
  109. -D FT_NTP=1
  110. -D FT_OTA=1
  111. -D FT_UPLOAD_FIRMWARE=1
  112. ```
  113. Flag | Description
  114. ------------------ | ----------------------------------------------
  115. FT_PROJECT | Controls whether the "project" section of the UI is enabled. Disable this if you don't intend to have your own screens in the UI.
  116. FT_SECURITY | Controls whether the [security features](#security-features) are enabled. Disabling this means you won't need to authenticate to access the device and all authentication predicates will be bypassed.
  117. FT_MQTT | Controls whether the MQTT features are enabled. Disable this if your project does not require MQTT support.
  118. FT_NTP | Controls whether network time protocol synchronization features are enabled. Disable this if your project does not require accurate time.
  119. FT_OTA | Controls whether OTA update support is enabled. Disable this if you won't be using the remote update feature.
  120. FT_UPLOAD_FIRMWARE | Controls the whether the manual upload firmware feature is enabled. Disable this if you won't be manually uploading firmware.
  121. ## Factory settings
  122. The framework has built-in factory settings which act as default values for the various configurable services where settings are not saved on the file system. These settings can be overridden using the build flags defined in [factory_settings.ini](factory_settings.ini).
  123. Customize the settings as you see fit, for example you might configure your home WiFi network as the factory default:
  124. ```ini
  125. -D FACTORY_WIFI_SSID=\"My Awesome WiFi Network\"
  126. -D FACTORY_WIFI_PASSWORD=\"secret\"
  127. -D FACTORY_WIFI_HOSTNAME=\"awesome_light_controller\"
  128. ```
  129. ### Default access point settings
  130. By default, the factory settings configure the device to bring up an access point on start up which can be used to configure the device:
  131. * SSID: ESP8266-React
  132. * Password: esp-react
  133. ### Security settings and user credentials
  134. By default, the factory settings configure two user accounts with the following credentials:
  135. Username | Password
  136. -------- | --------
  137. admin | admin
  138. guest | guest
  139. It is recommended that you change the user credentials from their defaults better protect your device. You can do this in the user interface, or by modifying [factory_settings.ini](factory_settings.ini) as mentioned above.
  140. ### Customizing the factory time zone setting
  141. Changing factory time zone setting is a common requirement. This requires a little effort because the time zone name and POSIX format are stored as separate values for the moment. The time zone names and POSIX formats are contained in the UI code in [TZ.tsx](interface/src/ntp/TZ.tsx). Take the appropriate pair of values from there, for example, for Los Angeles you would use:
  142. ```ini
  143. -D FACTORY_NTP_TIME_ZONE_LABEL=\"America/Los_Angeles\"
  144. -D FACTORY_NTP_TIME_ZONE_FORMAT=\"PST8PDT,M3.2.0,M11.1.0\"
  145. ```
  146. ### Device ID factory defaults
  147. If not overridden with a build flag, the framework will use the device ID to generate factory defaults for settings such as the JWT secret and MQTT client ID.
  148. > **Tip**: Random values are generally better defaults for these settings, so it is recommended you leave these flags undefined.
  149. ## Building for different devices
  150. This project supports ESP8266 and ESP32 platforms. To support OTA programming, enough free space to upload the new sketch and file system image will be required. It is recommended that a board with at least 2mb of flash is used.
  151. The pre-configured environments are "esp12e" and "node32s". These are common ESP8266/ESP32 variants with 4mb of flash:
  152. ![ESP12E](/media/esp12e.jpg?raw=true "ESP12E") ![ESP32](/media/esp32.jpg?raw=true "ESP32")
  153. The settings file ['platformio.ini'](platformio.ini) configures the supported environments. Modify these, or add new environments for the devides you need to support. The default environments are as follows:
  154. ```ini
  155. [env:esp12e]
  156. platform = espressif8266
  157. board = esp12e
  158. board_build.f_cpu = 160000000L
  159. [env:node32s]
  160. platform = espressif32
  161. board = node32s
  162. ```
  163. If you want to build for a different device, all you need to do is re-configure ['platformio.ini'](platformio.ini) and select an alternative environment by modifying the default_envs variable. Building for the common esp32 "node32s" board for example:
  164. ```ini
  165. [platformio]
  166. ;default_envs = esp12e
  167. default_envs = node32s
  168. ```
  169. ## Customizing and theming
  170. The framework, and MaterialUI allows for a reasonable degree of customization with little effort.
  171. ### Theming the app
  172. The app can be easily themed by editing the [MaterialUI theme](https://material-ui.com/customization/theming/). Edit the theme in ['interface/src/CustomMuiTheme.tsx'](interface/src/CustomMuiTheme.tsx) as you desire. For example, here is a dark theme:
  173. ```js
  174. const theme = createMuiTheme({
  175. palette: {
  176. type:"dark",
  177. primary: {
  178. main: '#222',
  179. },
  180. secondary: {
  181. main: '#666',
  182. },
  183. info: {
  184. main: blueGrey[500]
  185. },
  186. warning: {
  187. main: orange[500]
  188. },
  189. error: {
  190. main: red[500]
  191. },
  192. success: {
  193. main: green[500]
  194. }
  195. }
  196. });
  197. ```
  198. ![Dark Theme](/media/dark.png?raw=true "Dark Theme")
  199. ### Changing the app icon
  200. You can replace the app icon is located at ['interface/public/app/icon.png'](interface/public/app/icon.png) with one of your preference. A 256 x 256 PNG is recommended for best compatibility.
  201. ### Changing the app name
  202. The app name displayed on the sign in page and on the menu bar can be modified by editing the REACT_APP_NAME property in ['interface/.env'](interface/.env)
  203. ```ini
  204. REACT_APP_NAME=Funky IoT Project
  205. ```
  206. There is also a manifest file which contains the app name to use when adding the app to a mobile device, so you may wish to also edit ['interface/public/app/manifest.json'](interface/public/app/manifest.json):
  207. ```json
  208. {
  209. "name":"Funky IoT Project",
  210. "icons":[
  211. {
  212. "src":"/app/icon.png",
  213. "sizes":"48x48 72x72 96x96 128x128 256x256"
  214. }
  215. ],
  216. "start_url":"/",
  217. "display":"fullscreen",
  218. "orientation":"any"
  219. }
  220. ```
  221. ## Back end
  222. The back end is a set of REST endpoints hosted by a [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) instance. The ['lib/framework'](lib/framework) directory contains the majority of the back end code. The framework contains of a number of useful utility classes which you can use when extending it. The project also comes with a demo project to give you some help getting started.
  223. The framework's source is split up by feature, for example [WiFiScanner.h](lib/framework/WiFiScanner.h) implements the end points for scanning for available networks where as [WiFiSettingsService.h](lib/framework/WiFiSettingsService.h) handles configuring the WiFi settings and managing the WiFi connection.
  224. ### Initializing the framework
  225. The ['src/main.cpp'](src/main.cpp) file constructs the webserver and initializes the framework. You can add endpoints to the server here to support your IoT project. The main loop is also accessable so you can run your own code easily.
  226. The following code creates the web server and esp8266React framework:
  227. ```cpp
  228. AsyncWebServer server(80);
  229. ESP8266React esp8266React(&server);
  230. ```
  231. Now in the `setup()` function the initialization is performed:
  232. ```cpp
  233. void setup() {
  234. // start serial and filesystem
  235. Serial.begin(SERIAL_BAUD_RATE);
  236. // start the framework and demo project
  237. esp8266React.begin();
  238. // start the server
  239. server.begin();
  240. }
  241. ```
  242. Finally the loop calls the framework's loop function to service the frameworks features.
  243. ```cpp
  244. void loop() {
  245. // run the framework's loop function
  246. esp8266React.loop();
  247. }
  248. ```
  249. ### Developing with the framework
  250. The framework promotes a modular design and exposes features you may re-use to speed up the development of your project. Where possible it is recommended that you use the features the frameworks supplies. These are documented in this section and a comprehensive example is provided by the demo project.
  251. The following diagram visualises how the framework's modular components fit together, each feature is described in detail below.
  252. ![framework diagram](/media/framework.png?raw=true "framework diagram")
  253. #### Stateful service
  254. The [StatefulService.h](lib/framework/StatefulService.h) class is responsible for managing state. It has an API which allows other code to update or respond to updates in the state it manages. You can define a data class to hold state, then build a StatefulService class to manage it. After that you may attach HTTP endpoints, WebSockets or MQTT topics to the StatefulService instance to provide commonly required features.
  255. Here is a simple example of a state class and a StatefulService to manage it:
  256. ```cpp
  257. class LightState {
  258. public:
  259. bool on = false;
  260. uint8_t brightness = 255;
  261. };
  262. class LightStateService : public StatefulService<LightState> {
  263. };
  264. ```
  265. You may listen for changes to state by registering an update handler callback. It is possible to remove an update handler later if required.
  266. ```cpp
  267. // register an update handler
  268. update_handler_id_t myUpdateHandler = lightStateService.addUpdateHandler(
  269. [&](const String& originId) {
  270. Serial.print("The light's state has been updated by: ");
  271. Serial.println(originId);
  272. }
  273. );
  274. // remove the update handler
  275. lightStateService.removeUpdateHandler(myUpdateHandler);
  276. ```
  277. An "originId" is passed to the update handler which may be used to identify the origin of an update. The default origin values the framework provides are:
  278. Origin | Description
  279. --------------------- | -----------
  280. http | An update sent over REST (HttpEndpoint)
  281. mqtt | An update sent over MQTT (MqttPubSub)
  282. websocket:{clientId} | An update sent over WebSocket (WebSocketRxTx)
  283. StatefulService exposes a read function which you may use to safely read the state. This function takes care of protecting against parallel access to the state in multi-core enviornments such as the ESP32.
  284. ```cpp
  285. lightStateService.read([&](LightState& state) {
  286. digitalWrite(LED_PIN, state.on ? HIGH : LOW); // apply the state update to the LED_PIN
  287. });
  288. ```
  289. StatefulService also exposes an update function which allows the caller to update the state with a callback. This function automatically calls the registered update handlers if the state has been changed. The example below changes the state of the light (turns it on) using the arbitrary origin "timer" and returns the "CHANGED" state update result, indicating that a change was made:
  290. ```cpp
  291. lightStateService.update([&](LightState& state) {
  292. if (state.on) {
  293. return StateUpdateResult::UNCHANGED; // lights were already on, return UNCHANGED
  294. }
  295. state.on = true; // turn on the lights
  296. return StateUpdateResult::CHANGED; // notify StatefulService by returning CHANGED
  297. }, "timer");
  298. ```
  299. There are three possible return values for an update function which are as follows:
  300. Origin | Description
  301. ----------------------------- | ---------------------------------------------------------------------------
  302. StateUpdateResult::CHANGED | The update changed the state, propagation should take place if required
  303. StateUpdateResult::UNCHANGED | The state was unchanged, propagation should not take place
  304. StateUpdateResult::ERROR | There was an error updating the state, propagation should not take place
  305. #### Serialization
  306. When reading or updating state from an external source (HTTP, WebSockets, or MQTT for example) the state must be marshalled into a serializable form (JSON). SettingsService provides two callback patterns which facilitate this internally:
  307. Callback | Signature | Purpose
  308. ---------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------
  309. JsonStateReader | void read(T& settings, JsonObject& root) | Reading the state object into a JsonObject
  310. JsonStateUpdater | StateUpdateResult update(JsonObject& root, T& settings) | Updating the state from a JsonObject, returning the appropriate StateUpdateResult
  311. The static functions below can be used to facilitate the serialization/deserialization of the light state:
  312. ```cpp
  313. class LightState {
  314. public:
  315. bool on = false;
  316. uint8_t brightness = 255;
  317. static void read(LightState& state, JsonObject& root) {
  318. root["on"] = state.on;
  319. root["brightness"] = state.brightness;
  320. }
  321. static StateUpdateResult update(JsonObject& root, LightState& state) {
  322. state.on = root["on"] | false;
  323. state.brightness = root["brightness"] | 255;
  324. return StateUpdateResult::CHANGED;
  325. }
  326. };
  327. ```
  328. For convenience, the StatefulService class provides overloads of its `update` and `read` functions which utilize these functions.
  329. Read the state to a JsonObject using a serializer:
  330. ```cpp
  331. JsonObject jsonObject = jsonDocument.to<JsonObject>();
  332. lightStateService->read(jsonObject, LightState::read);
  333. ```
  334. Update the state from a JsonObject using a deserializer:
  335. ```cpp
  336. JsonObject jsonObject = jsonDocument.as<JsonObject>();
  337. lightStateService->update(jsonObject, LightState::update, "timer");
  338. ```
  339. #### Endpoints
  340. The framework provides an [HttpEndpoint.h](lib/framework/HttpEndpoint.h) class which may be used to register GET and POST handlers to read and update the state over HTTP. You may construct an HttpEndpoint as a part of the StatefulService or separately if you prefer.
  341. The code below demonstrates how to extend the LightStateService class to provide an unsecured endpoint:
  342. ```cpp
  343. class LightStateService : public StatefulService<LightState> {
  344. public:
  345. LightStateService(AsyncWebServer* server) :
  346. _httpEndpoint(LightState::read, LightState::update, this, server, "/rest/lightState") {
  347. }
  348. private:
  349. HttpEndpoint<LightState> _httpEndpoint;
  350. };
  351. ```
  352. Endpoint security is provided by authentication predicates which are [documented below](#security-features). The SecurityManager and authentication predicate may be provided if a secure endpoint is required. The placeholder project shows how endpoints can be secured.
  353. #### Persistence
  354. [FSPersistence.h](lib/framework/FSPersistence.h) allows you to save state to the filesystem. FSPersistence automatically writes changes to the file system when state is updated. This feature can be disabled by calling `disableUpdateHandler()` if manual control of persistence is required.
  355. The code below demonstrates how to extend the LightStateService class to provide persistence:
  356. ```cpp
  357. class LightStateService : public StatefulService<LightState> {
  358. public:
  359. LightStateService(FS* fs) :
  360. _fsPersistence(LightState::read, LightState::update, this, fs, "/config/lightState.json") {
  361. }
  362. private:
  363. FSPersistence<LightState> _fsPersistence;
  364. };
  365. ```
  366. #### WebSockets
  367. [WebSocketTxRx.h](lib/framework/WebSocketTxRx.h) allows you to read and update state over a WebSocket connection. WebSocketTxRx automatically pushes changes to all connected clients when state is updated.
  368. The code below demonstrates how to extend the LightStateService class to provide an unsecured WebSocket:
  369. ```cpp
  370. class LightStateService : public StatefulService<LightState> {
  371. public:
  372. LightStateService(AsyncWebServer* server) :
  373. _webSocket(LightState::read, LightState::update, this, server, "/ws/lightState"), {
  374. }
  375. private:
  376. WebSocketTxRx<LightState> _webSocket;
  377. };
  378. ```
  379. WebSocket security is provided by authentication predicates which are [documented below](#security-features). The SecurityManager and authentication predicate may be provided if a secure WebSocket is required. The placeholder project shows how WebSockets can be secured.
  380. #### MQTT
  381. The framework includes an MQTT client which can be configured via the UI. MQTT requirements will differ from project to project so the framework exposes the client for you to use as you see fit. The framework does however provide a utility to interface StatefulService to a pair of pub/sub (state/set) topics. This utility can be used to synchronize state with software such as Home Assistant.
  382. [MqttPubSub.h](lib/framework/MqttPubSub.h) allows you to publish and subscribe to synchronize state over a pair of MQTT topics. MqttPubSub automatically pushes changes to the "pub" topic and reads updates from the "sub" topic.
  383. The code below demonstrates how to extend the LightStateService class to interface with MQTT:
  384. ```cpp
  385. class LightStateService : public StatefulService<LightState> {
  386. public:
  387. LightStateService(AsyncMqttClient* mqttClient) :
  388. _mqttPubSub(LightState::read,
  389. LightState::update,
  390. this,
  391. mqttClient,
  392. "homeassistant/light/my_light/set",
  393. "homeassistant/light/my_light/state") {
  394. }
  395. private:
  396. MqttPubSub<LightState> _mqttPubSub;
  397. };
  398. ```
  399. You can re-configure the pub/sub topics at runtime as required:
  400. ```cpp
  401. _mqttPubSub.configureBroker("homeassistant/light/desk_lamp/set", "homeassistant/light/desk_lamp/state");
  402. ```
  403. The demo project allows the user to modify the MQTT topics via the UI so they can be changed without re-flashing the firmware.
  404. ### Security features
  405. The framework has security features to prevent unauthorized use of the device. This is driven by [SecurityManager.h](lib/framework/SecurityManager.h).
  406. On successful authentication, the /rest/signIn endpoint issues a [JSON Web Token (JWT)](https://jwt.io/) which is then sent using Bearer Authentication. The framework come with built-in predicates for verifying a users access privileges. The built in AuthenticationPredicates can be found in [SecurityManager.h](lib/framework/SecurityManager.h) and are as follows:
  407. Predicate | Description
  408. -------------------- | -----------
  409. NONE_REQUIRED | No authentication is required.
  410. IS_AUTHENTICATED | Any authenticated principal is permitted.
  411. IS_ADMIN | The authenticated principal must be an admin.
  412. You can use the security manager to wrap any request handler function with an authentication predicate:
  413. ```cpp
  414. server->on("/rest/someService", HTTP_GET,
  415. _securityManager->wrapRequest(std::bind(&SomeService::someService, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)
  416. );
  417. ```
  418. ### Accessing settings and services
  419. The framework supplies access to various features via getter functions:
  420. SettingsService | Description
  421. ---------------------------- | ----------------------------------------------
  422. getFS() | The filesystem used by the framework
  423. getSecurityManager() | The security manager - detailed above
  424. getSecuritySettingsService() | Configures the users and other security settings
  425. getWiFiSettingsService() | Configures and manages the WiFi network connection
  426. getAPSettingsService() | Configures and manages the Access Point
  427. getNTPSettingsService() | Configures and manages the network time
  428. getOTASettingsService() | Configures and manages the Over-The-Air update feature
  429. getMqttSettingsService() | Configures and manages the MQTT connection
  430. getMqttClient() | Provides direct access to the MQTT client instance
  431. The core features use the [StatefulService.h](lib/framework/StatefulService.h) class and can therefore you can change settings or observe changes to settings through the read/update API.
  432. Inspect the current WiFi settings:
  433. ```cpp
  434. esp8266React.getWiFiSettingsService()->read([&](WiFiSettings& wifiSettings) {
  435. Serial.print("The ssid is:");
  436. Serial.println(wifiSettings.ssid);
  437. });
  438. ```
  439. Configure the WiFi SSID and password manually:
  440. ```cpp
  441. esp8266React.getWiFiSettingsService()->update([&](WiFiSettings& wifiSettings) {
  442. wifiSettings.ssid = "MyNetworkSSID";
  443. wifiSettings.password = "MySuperSecretPassword";
  444. return StateUpdateResult::CHANGED;
  445. }, "myapp");
  446. ```
  447. Observe changes to the WiFiSettings:
  448. ```cpp
  449. esp8266React.getWiFiSettingsService()->addUpdateHandler(
  450. [&](const String& originId) {
  451. Serial.println("The WiFi Settings were updated!");
  452. }
  453. );
  454. ```
  455. ## Libraries Used
  456. * [React](https://reactjs.org/)
  457. * [Material-UI](https://material-ui.com/)
  458. * [notistack](https://github.com/iamhosseindhv/notistack)
  459. * [ArduinoJson](https://github.com/bblanchon/ArduinoJson)
  460. * [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer)
  461. * [AsyncMqttClient](https://github.com/marvinroger/async-mqtt-client)