ESP32 LoBo MicroPython WebSocket Server with ReactJS & MST

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this tutorial will demonstrate hosting a WebSocket server on ESP 32 using the Lobo micro Python firmware WebSocket protocol enables real-time two-way data transfer between a server and a client such as a web browser in a very efficient and standardized manner a WebSocket server will broadcast temperature data from a DES 18 B 20 sensor connect to 20 SP 32 a web page built with react and mob ik state tree on a Raspberry Pi will be the client this is the sixth segment in my micro Python ESP 32 series my videos are fast paced but my website contains complete coded notes for all my tutorials a link will be placed in the description along with links to prior videos which I recommend you watch first if you're just getting started I've taken the touchpad mp3 circuit from my last video and attach it to the side of a plastic cup the touch volume slider controls position so it can detect the fluid level when liquid is poured into the cup the gauge on the screen reports the level the SP 32 on the mp3 board is hosting a WebSocket server the react app running on the tablet is being served by a Raspberry Pi which is acting as a WebSocket client and gets instantly updated when the capacitive level sensors on the SP 32 detect change WebSockets are a great way to provide real-time Fulton Plex communication over the Internet react is a powerful and relatively easy solution for interactive web or mobile UIs there are tons of open source react components available for download on the web such as this fluid level sensor which really expedites coding for this tutorial I'll be using the Lobo micro Python firmware which has many advantages over the standard micro python.org build used in my previous videos Lobo has support for up to 16 megabytes of PS ram this is just as a common problem which is the limited amount of free memory available when using micro Python on an ESB 32 and many sp3 chip boards now come with PS RAM the local firmware is built as an ESP IDF component ESP IDF is the expressive official development framework for the ESP 32 chip this means the regular ESP IDF menu config system can be used for the configuration this supports many ESP 32 specific features not found in the standard build there is SD card support which greatly increases storage capacity the lobo firmware comes with many built-in modules implemented in c which improves performance and saves memory such as an FTP server telnet server and qtt client mdns and GSM additionally there's an SSH curl a real-time clock with NTP synchronization threading a performant TFT display module and much more I believe all the code in the Lobel library is either MIT or apache licensing also laborious the creator of the project has a forum and provides fantastic technical support is very quick to address issues and implement new features a logo build comes with Sean Christoph's micro webserver library which includes WebSockets I demonstrated this library of my third micro Python tutorial which shows how to set up a web server on an ESB 32 like the standard library logo provides pre-built firmware which makes installation easy there are several available firmware from bare-bones to fully loaded with features such as spy Ram OTA duel partitions and additional modules if your ESP 32 board has PS RAM click micro Python Lobo ESP 32 PS Ram all to download the full feature build with PS Ram support if your ESP 32 doesn't have the PS Ram and choose one of the other non PS Ram versions a local wiki lists several ESP 32 breakout boards that come with PS ram in this video I'm using a wii most lowland pro which has four megabytes of PS ram unfortunately this board has been discontinued once the download completes open a blank terminal CD into the downloaded folder LS shows the firmware a zip file unzip the file to the current directory LS shows the uncompressed folder CD into the new folder again to see the contents Lobo provides a flash script that automates the entire process uploading the firmware to the ESB 32 this really makes installation a breeze you'll need to have the ESP tool installed which is demonstrated in the first video of this series d message grep TTY USB indicates that I have a DSP 32 connected to my Raspberry Pi on USB port TTY USB 0 . / flash dot SH TTY USB 0 writes the Lobo firmware to the ESP 32 in case you're wondering the video is sped up but not by much the flash script only takes about 30 seconds ok that's all it takes to load the level firmware on 20 SP 32 in idle I have the main dot PI program used in the last video may not PI runs automatically when the ESP 32 boots the micro Python program establishes a connection to my Wi-Fi access point I'll make a few modifications to implement some of the great features that come with a Lobo firmware from Network imports are added for mdns FTP and telnet an EM DNS service is instantiated after a successful Wi-Fi connection the EM DNS service is started the hostname is set to M PI this will allow computers on your network to communicate with the SP 32 by a friendly name as opposed to an IP address which might change an FTP server is started with the username PI and password raspberry this will afford quick file transfers to and from the esv 32 using any ftp client it's good practice to pick a better password a telnet server is started with the same credentials this allows for Uppal access over the network before using these new services the main del PI file has to be copied to the ESP 32 I'll save the changes in exit out of idle in a new terminal our shell is used to connect to the ESP 32 via the USB cable CD into the Documents folder LS shows the main dot PI program that I just saved LS / PI board / flash shows the contents of the ESP 32 which so far only has a boot PI file note the Lobo build expects the files to be in the subdirectory flash as opposed to the root CP main dot I / pi board / flash copies the main dot PI file - the ESP 32 repple enters the repple import machine and then machine reset can be used to perform a hard reset of the ESP 32 you could also just press the reset button on the board the main dot pop file runs automatically on boot and starts the services my access point is found and the Wi-Fi connection is successful with FTP and telnet running full wireless control of the ESP 32 is now possible and the USB cable can be disconnected assuming you provide an alternative source of power from the raspberry pi pinging M PI dot local shows the ESP 32 M dns service is working instead of the IP address AppScan l reference the SP 32 by name m dns service is built into Linux and Mac it doesn't come with Windows but can be easily added by installing a free program called Bonjour and if you have my Tunes it's probably already installed on your computer in the third video of this series I built a simple HTML web server on the SP 32 to provide temperature and humidity readings from a dht22 sensor in this video I'll use a 1 wired ES 18 B 20 temperature sensor which is what I used in my server room temperature monitor which has been running flawlessly 24/7 for over 4 years now the d s 18 B 20 digital thermometer provides 9 bit 12 bits Celsius temperature measurements it communicates over a 1-wire bus that only requires one data line and multiple ones can be daisy chained together on the same line wiring the d s 18 b 22 the SP 32 is straightforward the red VDD wire is connected to three point three bolts on the SP 32 the black wire is connected to ground the yellow data line is connected to GPIO 23 a 10k pull-up resistor is required between 3.3 volts in the data line you can use any available GPIO under 34 for the data line however there could be a few exceptions because some boards reserved a few of the pins for example on the lowland 32 pro pins 2 and 22 don't work on a breadboard I have a way most low on 32 Pro I've already connected a 3.3 volt pin to a rail on my breadboard i've also connected a ground pin to the other rail here's tsa TV 20 this version of the temperature sensor is encapsulated in a waterproof stainless steel tube I've soldered header pins to the other end of the sensor the VDD and ground pins are plugged into the corresponding rails on the breadboard the data line is plugged into an empty terminal strip a jumper wire connects GPIO 23 to the data line a 10k ohm resistor pulls the data line up to 3.3 volts okay the hardware is good to go now let's take a look at some code here's the micro Python WebSocket server code which I called ws1 from machine import one wire RTC and timer from micro webster import micro web serve this is the web server / WebSocket library import JSON a 1-wire devices instantiated on GPIO 23 add es 18 V 20 is instantiate it on the 1-wire bus a real-time clock is instantiated the time is synchronized to NTP org and the timezone a set the program can now track the correct time the ESB 32 hardware timer zero is instantiated this affords the ability to fire functions and specified intervals the WebSocket server uses for callback methods CB received text will fire when the WebSocket server receives a text string the method has passed a reference to the WebSocket server and the message text for this example will just print the message to the terminal send text is also used to send an acknowledgment reply back to the client CB receive binary is similar to the received text callback but fires when a binary message is received it's passed a variable data which contains the binary data another print statement outputs the data the callback CB closed fires when the client disconnects from the WebSocket server dn8 is used to dispose of the hardware timer the closed status is displayed in the terminal the callback CB timer is not part of the WebSocket model instead it will be fired at specified intervals by the ESP 32 hardware timer it's passed a reference to the timer and the WebSocket server addictive used to build a JSON message that will be transmitted to the WebSocket client an entry temp holds the temperature which is retrieved from the DES 18 B 20 sensor using des convert read temperature is also printed to the terminal an entry internal stores the internal temperature of the esv 32 which can be accessed using the machine method internal temp and referencing item 1 the third entry time stores the current time which is returned by calling RTC now WebSockets sent text sends the message text which is converted to Jason by using the dumps method on the dict the callback CB accept WS is the fourth WebSocket callback and as far as what a client connects to the server after printing the accept status to the terminal the WebSocket callbacks created above are signed receive text callback is set to CB receive text again this is the callback the response of text messages sent from the client next CB received binaries aside and CB close as assigned when the client connects the hardware timer is turned on to periodically pull the temperature sensor the timer will need a reference to the WebSocket server so a lambda is used to inject the WebSocket server into the timer callback teaming it starts the hardware timer the interval is set to 3 seconds and the callback is assigned the micro webserver is instantiated max WebSockets received length is set to 256 WebSocket threaded is set to true this uses a new thread for each WebSocket connection the stack size is set to 4096 accept WebSocket callback is assigned to CB except WS this is the callback function above which bars when a client connects mws start starts the web server threaded a set to false this results in a blocking call aside from the hardware timer and callbacks which operate independently the program will wait here until control C is pressed thread II could be set the true to continue with other operations upon control C the web server is stopped the timer is disposed and the real-time clock is cleared that's it for the WebSocket server the FTP client FileZilla is used to upload the ws one program from the PI to the SP 32 click the site manager icon already to find a site for the SP 32 the connection is successful note that the site took advantage of the M PI local address to connect to the ESB 32 double-click the flash folder to change directories on the SP 32 then right-click on the WS 1 pipe file and select upload ok the WebSocket server program is now on the SP 32 by the way that wasn't sped up the FTP server is very fast compared to our shell now close FileZilla and open a blank terminal on the Raspberry Pi sudo apt-get install telnet installs a simple telnet client after installation type telnet and PI local the SP 32 prompts for credentials which were defined in main dot pi ok the SP 32 repple is now active via telnet from you pius h import star this is a minimalistic micro Python shell library to run file commands from the rebel PWD prints the working directory flash LS lists the directory files the WebSocket server file ws1 pi is present typing man displays all available you PI SH commands head and cat displays the beginning and end of text files I assume new file creates a new file MV to move a file RM to delete a file M Kader to make a directory RM dirt or remove a directory CP to copy a file and clear can be used to clear the rebel screen import WS one starts the WebSocket server it's now running and waiting for client connections let's give it a test open a new terminal on the PI pip 3 install WebSocket client insults a Python WebSocket client library it provides WebSocket client connections from within Python programs open Idol 3 and in the Python shell from web socket import create connection create a connection called ws but the URL WS colon slash slash M PI dot local this connects to the WebSocket server on the ESP 32 and fires the accept callback which in turn starts the hardware timer to pull the temperature sensor every three seconds the wsre-tv method shows the receive JSON data which includes the time of the reading the sensor temperature approximately 26 degrees Celsius and the internal ESP thirty-two temperature of about 68 degrees Celsius re cv again and notice the time is incremented by a few seconds the sensor temperature is the same but the internal is dropped about half a degree WS Sen sends the text hello world to the WebSocket server switching back to the repple shows the text was received and printed to the screen of course instead of a simple text message commands or binary data could be sent to control the device such as an LED a relay and display the motor etc now let's create a react app on the PI to interact with the WebSocket server react requires a newer version of no GS than what currently comes with raspbian note tak V indicates that the PI is running version four point eight point two before installing the newer version of node the existing component should be removed sudo apt-get remove node read sudo apt-get removed nodejs and nodejs legacy next curls used to download and run and install which installs the nodejs version manager and updates nodejs and npm to the latest versions no GS version 9.10 0.1 is now installed before proceeding a reboot of the PI is required again the node version is now nine point 10.1 and NPM is at version five point six point zero the next step is to use curl to install the penisy manager called yarn which facilitates creating react apps yarn tack v indicates that yarn version one point six point zero is installed okay that's it for the tools now for some react code CD into the Documents folder the easiest way to get started is by using yarn create react app the project is called D S 18 sock create react app generates a react application and does not require any built configuration there's no need to mess around with web pack or babble everything gets pre-configured for you and you can just start writing code that took 109 seconds but the one command created a working react app that's ready to go LS shows the react app folder D s 18 sock seeding into the folder and yarn start this fires up the development web server and launches the browser with some sample code running any changes to the rack code will cause the browser to automatically update react GS is an amazing tool for building user interfaces this video is not meant to be an in-depth tutorial on react that would require several videos instead I'm just going to walk through how quick and easy it is to build a UI control C is used to stop the server reactors built with components which let you split the UI into independent reusable pieces creating a complex application could be a daunting task components that you focus on smaller pieces and thereby chip away at the larger goal many great open-source react components are available on a website called NPM J Escom since we're using a temperature sensor I'll search for a react thermometer and choose react thermometer component this one looks good a graphical thermometer with a numeric temperature label it can be installed by using the yarn add command this automatically adds the component to the project and resolves any dependencies I'll also add react loading which is a basic loading indicator prop types for type checking and mob X and mob X date tree error okay I forgot the add command let's try again that's better mob X is an application state manager which can be used with react I find it much more intuitive than redux and it doesn't require copious boilerplate bobak state tree builds on mob X and provides a container that leverages the best features of immutability and mutability in a very opinionated approach it lets you create a component model for your data it's basically a library that helps you organize your application state don't worry if that sounds vague or meaningless it's really not that complicated but I think you do have to see code to understand and all the code in this video will be available online ok all the necessary component packages have been added here's the sample project generated by the create react app starter kit most of the relevant sample code is in the SRC or source directory add a new folder called models this will hold models which are the core of mob X state tree models describe what the data looks like and performs type validation create a new file called sensors j/s this will describe the shape of the data for the DES 18 B 20 temperature sensor import types from Babak state tree yes 18 b20 type is defined types consist of models views and actions types model holds the properties this sensor has a temperature property to hold the current temperature in Celsius zero indicates its numeric and the default value is zero is ready indicates that the sensor has temperature data available false indicates its boolean and it defaults to false actions perform operations on models which are otherwise read-only a single action set temperature updates the temperature property it also sets the Israeli property to true to indicate sensor data is available views returns data derived from properties mob x recommends during as little state as possible in models for example instead of storing the temperature in both Celsius and Fahrenheit only Celsius is stored and a view called convert Fahrenheit returns the conversion upon request export D s 18 B 20 is default and the sensor model is complete next to model called socket J s is added to handle the WebSocket client connections apply action is important for mark state tree it sees to perform model actions a default function called sync store WS is exported it takes a socket and a sensor model the on socket message function takes a handler which is fired upon socket on message for example when the WebSocket server on the ESP 32 transmits new temperature data the handler has passed the parse JSON data if the data contains a field called temp then apply action is used to fire the sensors set temperature action with the received data next to new folder is created to hold components a new react component called temp gauge is added this will display the thermometer component react as imported prop types is imported for type checking import observed from objects react this is used to turn components into reactive components when the underlying data changes a reactive component will automatically render and thanks to react instead of the whole webpage inefficiently reloading only the parts that need to be updated or changed thermometer is imported for react thermometer component this is a thermometer component from the NPM GS website that was added using yarn react loading is imported from react loading this is the simple visual loading indicator that was also added using yarn temp gauge is defined and has passed props these property's past when you create a component the props include a sensor and if the sensors is ready flag is true then a div is returned containing the thermometer component which has several properties the value property terms the thermometer temperature and is set to the sensors convert Fahrenheit view this converts the Celsius reading from the D s 18 B 22 Fahrenheit and displays it on the thermometer the other properties are pretty straightforward min max temperature range the steps between tix degree format and size and height if the sensor is ready flag is false and the react loading component is displayed it's set to spin in a blue color with dimensions of 100 by 100 finally prop types are added for type checking this ensures the react component has passed the required properties in the correct type this is a good practice and it helps in debugging the temp gauge should receive a sensor comprised of the Israeli boolean which is required and the convert Fahrenheit string which is also required temp gauge is the default export and the mob X observer is used to ensure this component is reactive in other words any time the underlying temperature data changes the component will automatically update itself ok now the models and components are ready to be used open index J is the app starting point delete most of the sample code the sinc store WS function is imported from models socket D s 18 B 20 is imported for model sensors a constant socket is defined as a new WebSocket client and passed the ESP 32 WebSocket servers and DNS address the sensor is created using the DSA TV 20 create method sync store ws links the web socket and the sensor models react Dom renders the app to the Dom and passes the sensor property the app component is the final part of the program open app TS let's start from scratch erase all the existing sample code react is imported prop types is imported the react logo SVG file is imported the sample CSS stylesheet is imported and a temp gauge component is important app is defined and returns a div container a header contains to react local image and h1 displays the web page title temp gauge is added this is the temp gauge component with the thermometer display it's passed the sensor prop prop types ensures that the app component receives the sensor prop as before its shape includes an Israeli boolean and a conferred fahrenheit string app is exported as default okay in theory the react app should be ready to go in the PI terminal LS shows the code and I made a mistake the components and model folders should not be in the root instead they should be in the source folder MV components models tact ESRC moves the folders to their correct location verify with LS and LS SRC that looks correct yarn start serves up the react app development service starts and a browser is open to the localhost port 3000 a loading indicator displays while the WebSocket connection is created as soon as the WebSocket server sends a data package thermometer is displayed 74 point nine seven degrees Fahrenheit and the thermometer component will automatically refresh when new data is received I'll warm up the sensor with my fingers as the sensor heats up the gauge updates in real-time automatically I hope you found this video helpful you can support this channel by subscribing leaving a like and sharing thanks for watching
Info
Channel: rdagger68
Views: 21,936
Rating: undefined out of 5
Keywords: ESP32, MicroPython, React, MobX, MobX State Tree, MobX React, WebSockets, Raspberry Pi, DS18b20, LoBo, Loboris
Id: uzY6aSg9Ly8
Channel Id: undefined
Length: 24min 32sec (1472 seconds)
Published: Mon May 14 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.