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.

408 lines
15 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
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
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
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 front-end.
  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. * Remote Firmware Updates - Enable secured OTA updates
  12. * Security - Protected RESTful endpoints and a secured user interface
  13. The back end is provided by a set of RESTful endpoints and the React based front end is responsive and scales well to various screen sizes.
  14. The front end has the prerequisite manifest file and icon, so it can be added to the home screen of a mobile device if required.
  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. * Bash shell, or [Git Bash](https://gitforwindows.org/) if you are under windows
  21. ### Building and uploading the firmware
  22. Pull the project and open it in PlatformIO. PlatformIO should download the ESP8266 platform and the project library dependencies automatically.
  23. The project structure is as follows:
  24. Resource | Description
  25. ---- | -----------
  26. [data/](data) | The file system image directory
  27. [interface/](interface) | React based front end
  28. [src/](src) | The main.cpp and demo project to get you started
  29. [platformio.ini](platformio.ini) | PlatformIO project configuration file
  30. [lib/framework/](lib/framework) | C++ back end for the ESP8266 device
  31. ### Building the firmware
  32. Once the platform and libraries are downloaded the back end should successfully build within PlatformIO.
  33. The firmware may be built by pressing the "Build" button:
  34. ![build](/media/build.png?raw=true "build")
  35. Alternatively type the run command:
  36. ```bash
  37. platformio run
  38. ```
  39. #### Uploading the firmware
  40. 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).
  41. The firmware may be uploaded to the device by pressing the "Upload" button:
  42. ![uploadfw](/media/uploadfw.png?raw=true "uploadfw")
  43. Alternatively run the 'upload' target:
  44. ```bash
  45. platformio run -t upload
  46. ```
  47. ### Building the interface
  48. 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 ~200k, which easily fits on the device.
  49. 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:
  50. #### Change to interface directory
  51. ```bash
  52. cd interface
  53. ```
  54. #### Download and install the node modules
  55. ```bash
  56. npm install
  57. ```
  58. #### Build the interface
  59. ```bash
  60. npm run build
  61. ```
  62. > **Note**: The build command will also delete the previously built interface, in the ['data/www'](data/www) directory, replacing it with the freshly built one ready to upload to the device.
  63. #### Uploading the file system image
  64. The compiled user interface may be uploaded to the device by pressing the "Upload File System image" button:
  65. ![uploadfs](/media/uploadfs.png?raw=true "uploadfs")
  66. Alternatively run the 'uploadfs' target:
  67. ```bash
  68. platformio run -t uploadfs
  69. ```
  70. ### Running the interface locally
  71. You can run a local development server to allow you preview changes to the front end without the need to upload a file system image to the device after each change. Change to the interface directory and run the following command:
  72. ```bash
  73. npm start
  74. ```
  75. > **Note**: To run the interface locally you will need to modify the endpoint root path and enable CORS.
  76. #### Changing the endpoint root
  77. The endpoint root path can be found in ['interface/.env.development'](interface/.env.development), defined as the environment variable 'REACT_APP_ENDPOINT_ROOT'. This needs to be the root URL of the device running the back end, for example:
  78. ```js
  79. REACT_APP_ENDPOINT_ROOT=http://192.168.0.6/rest/
  80. ```
  81. #### Enabling CORS
  82. 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:
  83. ```
  84. -D ENABLE_CORS
  85. -D CORS_ORIGIN=\"http://localhost:3000\"
  86. ```
  87. ## Device Configuration
  88. As well as containing the interface, the SPIFFS image (in the ['data'](data) folder) contains a JSON settings file for each of the configurable features. The config files can be found in the ['data/config'](data/config) directory:
  89. File | Description
  90. ---- | -----------
  91. [apSettings.json](data/config/apSettings.json) | Access point settings
  92. [ntpSettings.json](data/config/ntpSettings.json) | NTP synchronization settings
  93. [otaSettings.json](data/config/otaSettings.json) | OTA update configuration
  94. [securitySettings.json](data/config/securitySettings.json) | Security settings and user credentials
  95. [wifiSettings.json](data/config/wifiSettings.json) | WiFi connection settings
  96. ### Access point settings
  97. The default settings configure the device to bring up an access point on start up which can be used to configure the device:
  98. * SSID: ESP8266-React
  99. * Password: esp-react
  100. ### Security settings and user credentials
  101. The security settings and user credentials provide the following users by default:
  102. Username | Password
  103. -------- | --------
  104. admin | admin
  105. guest | guest
  106. It is recommended that you change the JWT secret and user credentials from their defaults protect your device. You can do this in the user interface, or by modifying [securitySettings.json](data/config/securitySettings.json) before uploading the file system image.
  107. ## Building for different devices
  108. 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.
  109. By default, the target device is "esp12e". This is a common ESP8266 variant with 4mb of flash:
  110. ![ESP12E](/media/esp12e.jpg?raw=true "ESP12E")
  111. The settings file ['platformio.ini'](platformio.ini) configures the platform and board:
  112. ```
  113. [env:esp12e]
  114. platform = espressif8266
  115. board = esp12e
  116. ```
  117. If you want to build for an ESP32 device, all you need to do is re-configure ['platformio.ini'](platformio.ini) with your devices settings.
  118. ![ESP32](/media/esp32.jpg?raw=true "ESP32")
  119. Building for the common esp32 "node32s" board for example requires the following configuration:
  120. ```
  121. [env:node32s]
  122. platform = espressif32
  123. board = node32s
  124. ```
  125. ## Customizing and theming
  126. The framework, and MaterialUI allows for a reasonable degree of customization with little effort.
  127. ### Theming the app
  128. The app can be easily themed by editing the [MaterialUI theme](https://material-ui.com/customization/themes/). Edit the theme in ['interface/src/App.js'](interface/src/App.js) as you desire:
  129. ```js
  130. const theme = createMuiTheme({
  131. palette: {
  132. primary: red,
  133. secondary: deepOrange,
  134. highlight_idle: blueGrey[900],
  135. highlight_warn: orange[500],
  136. highlight_error: red[500],
  137. highlight_success: green[500],
  138. },
  139. });
  140. ```
  141. ### Changing the app icon
  142. 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.
  143. ### Changing the app name
  144. The app name displayed on the login page and on the menu bar can be modified by editing the REACT_APP_NAME property in ['interface/.env'](interface/.env)
  145. ```js
  146. REACT_APP_NAME=Funky IoT Project
  147. ```
  148. 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):
  149. ```json
  150. {
  151. "name":"Funky IoT Project",
  152. "icons":[
  153. {
  154. "src":"/app/icon.png",
  155. "sizes":"48x48 72x72 96x96 128x128 256x256"
  156. }
  157. ],
  158. "start_url":"/",
  159. "display":"fullscreen",
  160. "orientation":"any"
  161. }
  162. ```
  163. ## Back end overview
  164. 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.
  165. 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.
  166. ### Initializing the framework
  167. 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.
  168. The following code creates the web server, esp8266React framework and the demo project instance:
  169. ```cpp
  170. AsyncWebServer server(80);
  171. ESP8266React esp8266React(&server, &SPIFFS);
  172. DemoProject demoProject = DemoProject(&server, &SPIFFS, esp8266React.getSecurityManager());
  173. ```
  174. Now in the `setup()` function the initialization is performed:
  175. ```cpp
  176. void setup() {
  177. // start serial and filesystem
  178. Serial.begin(SERIAL_BAUD_RATE);
  179. // start the file system (must be done before starting the framework)
  180. SPIFFS.begin();
  181. // start the framework and demo project
  182. esp8266React.begin();
  183. // start the demo project
  184. demoProject.begin();
  185. // start the server
  186. server.begin();
  187. }
  188. ```
  189. Finally the loop calls the framework's loop function to service the frameworks features. You can add your own code in here, as shown with the demo project:
  190. ```cpp
  191. void loop() {
  192. // run the framework's loop function
  193. esp8266React.loop();
  194. // run the demo project's loop function
  195. demoProject.loop();
  196. }
  197. ```
  198. ### Adding endpoints
  199. There are some simple classes that support adding configurable services/features to the device:
  200. Class | Description
  201. ----- | -----------
  202. [SimpleService.h](lib/framework/SimpleService.h) | Exposes an endpoint to read and write settings as JSON. Extend this class and implement the functions which serialize the settings to/from JSON.
  203. [SettingsService.h](lib/framework/SettingsService.h) | As above, however this class also handles persisting the settings as JSON to the file system.
  204. [AdminSettingsService.h](lib/framework/AdminSettingsService.h) | Extends SettingsService to secure the endpoint to administrators only, the authentication predicate can be overridden if required.
  205. The demo project shows how these can be used, explore the framework classes for more examples.
  206. ### Security features
  207. The framework has security features to prevent unauthorized use of the device. This is driven by [SecurityManager.h](lib/framework/SecurityManager.h).
  208. On successful authentication, the /rest/signIn endpoint issues a JWT which is then sent using Bearer Authentication. The framework come with built in predicates for verifying a users access level. The built in AuthenticationPredicates can be found in [SecurityManager.h](lib/framework/SecurityManager.h):
  209. Predicate | Description
  210. -------------------- | -----------
  211. NONE_REQUIRED | No authentication is required.
  212. IS_AUTHENTICATED | Any authenticated principal is permitted.
  213. IS_ADMIN | The authenticated principal must be an admin.
  214. You can use the security manager to wrap any web handler with an authentication predicate:
  215. ```cpp
  216. server->on("/rest/someService", HTTP_GET,
  217. _securityManager->wrapRequest(std::bind(&SomeService::someService, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)
  218. );
  219. ```
  220. Alternatively you can extend [AdminSettingsService.h](lib/framework/AdminSettingsService.h) and optionally override `getAuthenticationPredicate()` to secure an endpoint.
  221. ## Extending the framework
  222. ```cpp
  223. #include <SettingsService.h>
  224. class ExampleSettingsService : public SettingsService {
  225. public:
  226. ExampleSettingsService(AsyncWebServer* server, FS* fs)
  227. : SettingsService(server, fs, "/exampleSettings", "/config/exampleSettings.json") {}
  228. ~ExampleSettingsService(){}
  229. protected:
  230. void readFromJsonObject(JsonObject& root) {
  231. _username = root["username"] | "";
  232. _password = root["password"] | "";
  233. }
  234. void writeToJsonObject(JsonObject& root) {
  235. root["username"] = _username;
  236. root["password"] = _password;
  237. }
  238. private:
  239. String _username;
  240. String _password;
  241. };
  242. ```
  243. Now this can be constructed, added to the server, and started as such:
  244. ```cpp
  245. ExampleSettingsService exampleSettingsService = ExampleSettingsService(&server, &SPIFFS);
  246. exampleSettingsService.begin();
  247. ```
  248. There will now be a REST service exposed on "/exampleSettings" for reading and writing (GET/POST) the settings. Any modifications will be persisted in SPIFFS, in this case to "/config/exampleSettings.json"
  249. Sometimes you need to perform an action when the settings are updated, you can achieve this by overriding the onConfigUpdated() function which gets called every time the settings are updated. You can also perform an action when the service starts by overriding the begin() function, being sure to call SettingsService::begin():
  250. ```cpp
  251. void begin() {
  252. // make sure we call super, so the settings get read!
  253. SettingsService::begin();
  254. reconfigureTheService();
  255. }
  256. void onConfigUpdated() {
  257. reconfigureTheService();
  258. }
  259. void reconfigureTheService() {
  260. // do whatever is required to react to the new settings
  261. }
  262. ```
  263. ## Libraries Used
  264. * [React](https://reactjs.org/)
  265. * [Material-UI](https://material-ui-next.com/)
  266. * [notistack](https://github.com/iamhosseindhv/notistack)
  267. * [Time](https://github.com/PaulStoffregen/Time)
  268. * [NtpClient](https://github.com/gmag11/NtpClient)
  269. * [ArduinoJson](https://github.com/bblanchon/ArduinoJson)
  270. * [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer)