Web server to control GPIO on a Raspberry Pi with websockets

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
So i thought we'd start off this video by showing  the end result of this video and that is we have   a raspberry pi here with a web server running woth  have four leds that are connected to the gpio pins   and we have a ipad here with safari open  and we're going to the ip address of the   pi which in this case is 192.168.18.105 and  so what we have here on the top is we have   four toggle buttons that turn the leds on  and off so we just go ahead and hit those   one at a time and you can see the  leds will go off as we hit them and then we have four  momentary buttons on the bottom   that will turn the leds on as long as we hold them and we go ahead and turn the l keep the  leds on by just hitting the toggle buttons   and not only that we can actually uh do several  button presses at the same time so i can go ahead   and i hit this led turn it on and i go ahead and  hit this one and turn this led on and then let's   go ahead and just toggle these off here and i can  go ahead and hit this one and i go ahead and hit   this one and all four leds are on as i release  the buttons here they turn off individually   and not only that our pi can actually handle  multiple users at the same time what i have   open right now is i got my ipad on the right  here with just one page open and then i have   my laptop right here and i actually have eight  browser windows open all pointing to the same pi   and uh it will display uh they'll all  display the feedback instantaneously   from the pie and i could i could do it  here i could also do it from the pie here   and you can see uh they all get feedback and  that is the power of web sockets with web sockets   you can have multiple users connected and  you get instantaneous feedback to all of them   without having to refresh the web page so this  sounds like something that you're interested in   well watch on and i'll show you  how to do that in this video so for purposes of this uh demo i  i'm going to use the raspberry pi   desktop os with recommended software and i'm  going to use the one with the release date   of december the 2nd 2020. so all you do is go to  the raspberry pi website hit the download button   download the file i've already done that so i'm  not going to do it again you're going to unzip   that file and then you're going to you're going to  burn that image to the flash card using whatever   flash burner you want to use a lot of people  use etcher i myself personally just use the   usb image writer that's built into linux mint  but that's up to you but you download that file   stick it in your pi boot the pi up go through  the initial setup and you should be ready to go so after you get your raspberry pi set up  on the first time setup you want to go to   go to the preferences and then  raspberry pi configuration and what you want to do is go to interfaces  you want to enable remote gpio that allows   you to change the gpio pins to turn your leds on  and off uh if you want to remote manage your pi   remotely like which i'm going to do here and i  am doing here you're going to want to enable ssh   and if you want to do a remote desktop like i'm  doing right here you're going to enable vnc also so lastly you're going to want to find  out what the ip address of your pi is   and you do that by just opening up  a terminal and entering i f config oops if i can spell correctly and i'm connected  by ethernet lan port and you can see the address   of my pi is at 192.168.18.105 we'll use  that to remote into the pi via the ssh   and we'll also use that to access the pi's web  server through a browser so you need to write down   whatever that number is you need to write that  down because we're going to use it in the future okay let's talk a little bit about web servers   i originally started this project using uh nginx  but i had some stability problems with that where   the web server would crash intermittently  and that may be something that i didn't   set up correctly i just don't know uh but  i went on to try uh apache 2 after that   and i found apache 2 to be very stable in fact  it never crashed once on me and then i used a uh php and wordpress on top of that as my backend  server but when it came time to implement web   sockets which you need if you want to do really  fast feedback um i just couldn't get it to work   so i started looking for another  solution and i stumbled across   node.js and when i installed that uh it uh worked  perfectly and the web sockets worked very well   and so that is what we're going to use for this  project so uh the first thing you need to do is uh   you need to go ahead and ssh into your pie  here and we'll go ahead and do that here you   notice i have a it's ssh dash x and then pi  at then whatever the ip address of your pi is   now you notice i have the dash x here that mainly  just allows you to use the x window window system   through the ssh connection which allows  you to basically pull up gui's and later on   we're going to be using genie as our editor  and that allows us to use genie through the   through the ssh connection so let's go ahead  and do that i'll go ahead and key in my password and we're in uh so first thing we need to  do is we need to go ahead and update our pi   so we'll go ahead and do that i've already updated  so we'll come back it should be all up to date   and it is and then if it wasn't you would  go ahead and do upgrade on top of that   and that's okay and then lastly  we'll do a distro upgrade okay so there we are we need to find out what  version of processor we're using though and   that is would type in you name dash m and you'll see we're  using an arm version 7 l so we'll go to nodejs.org here and you might be  just tempted to click this download link here   the issue is i'm doing this from a linux  computer uh linux mint in particular so it's   going to download the version for my linux mint so  instead we want to go to the downloads folder here   and here it has all the different versions of  node.js and the one we're interested in is the   arm7 which we just found out and uh i had issues  with uh node version 14.15.4 so we're not even   going to use that version instead we're  going to drop down to our previous release   and that is node 12 and that one i know does  work so that for at least the immediate future   that is the one i recommend that you use  so we'll go ahead and click on that link   and then you'll see all the different  packages here and we want the arm 7 version   and we'll scroll down here and there we go there  it is and there's two versions we want to get   the one with the xz extension so we'll right  click on that we'll copy that link location   and then we'll go down to our pie we'll  change our directory to the downloads folder and then we'll do a w get and  then we'll paste in that link and it just got no js for us okay we  could go ahead and close this up now   and bring this up here actually let  me close this we don't need that okay so let's do a directory listing here  on our downloads folder and you'll see   we have we have a zip file here or an archive  file we need to unpack that and we do that with um   this command right here and of course you're  gonna if you're using a different version of   node.js you're gonna change the the last  part of this do that extracts all the files   and then we go we do another directory listing uh we see we see we have a directory uh called uh   node version 12.2 la da da so we'll  go ahead and switch to that directory and do directory listing on that directory and you see we have a number of files there and  a number of subdirectories on top of that so uh   basically all you need to do to install node.js is  basically copy all these files and subdirectories   to your user local folder on your pie and  so we'll go ahead and do that right here and believe it or not node js and the mpn  manager are installed and you can confirm that by typing in node v and you  see we're using version 12.20.1   i'll go ahead and update my  documentation to have that version and then we'll go ahead and check if no the node  package manager is running or npn it's also called and you see we're running version 6.14.10. we'll go ahead and update our text here okay so the next thing  we need to do is uh we're going to   create a project folder and we're going  to make make we're going to go ahead   and make a directory called web  server in our home directory here and then we're going to switch to that directory and then we're going to run npn and net  and that initializes the package manager   this is not an absolutely necessary  step but i recommend that you do it   because if you don't do it you'll get  a bunch of errors when you install when you install packages okay so it's asking what you want to call this  package name web server that's fine we'll just   go ahead and keep that version one is fine  description we'll call this web server for pi uh   entry point in uh that's fine uh test command we  don't need that git directory we don't need that   we'll just leave that blank uh keywords we don't  put any their author we'll say steve's projects uh license we're gonna head go ahead and do these   mit license is this okay yes and that's it so if  we do a directory listing now we see we have a we have a package.json file and basically that  gives you the dependencies of your project so the next thing we need to do is go ahead and  install a few uh pack packages and the first   one we're going to install is on off and when on  off does it allows you to control the gpio pins   on your pi uh viva node.js so we'll  go ahead install that package here   and install we got one uh warning it said that  there's no uh repository field that's okay we   don't have to worry about that and then the  next package we need to install is uh socket io   and what that will allow is that  will allow us to use web sockets and so it's npn install socket.o  io and then dash dash save and you could also put a dash g   field in both of these commands and they will  install it globally but we're going to leave   that out and basically if you leave that out  you can only use these packages in this web   server directory we created or any subdirectory  below it so let's go ahead and install that and uh no errors there okay the last thing we need  to do um there's a little uh   fact that a lot of people don't  know with linux and that is   if you're trying to set up a server like a tcp  server like a web server on port 80 on linux that   has to be run as root normally and the last thing  you want to do is run your uh your web server as   root uh so there is a way around it and that is  to install these this particular package called   cap 2 dash binary and we already did an update so  we don't need to do that but let's go ahead and   install that package and what this will allow us  to do it will allow us to run a web server on port   80 because it's below 1024 and without  having to run node as a as a root user   so this command here now that we have that  package installed which turned out it was   already installed um this is the command that  will allow node just node alone to use por   uh use any port below 1024 as a server port  so let's go ahead and execute that command   and it's there now if you want to check what  packages do have this extra privilege privilege   uh like let's say you want to check all your  programs in your us usr directory you can type in   get cap dash r for recurs cursive and then your  your directory that you want to check and it   will scan the directory and it will tell you all  the programs that have these elevated privileges and as you can see the only  package that does is just node so let's get our web server going now now so the first thing we're going to do is we're  going to go ahead and go to our downloads folder   let's go ahead and do a directory listing and we no longer need this node folder here  we've already moved those files to the proper   folder so we just go ahead and  remove that folder completely   and we do that with this command and i'm  going to go ahead and leave this archive   file here because in case we have to reinstall  node later on we can we already have the file   so the next thing we do is go ahead and get the  code and you can get the code at my github page   and so basically you do a wget and then this  very long address we'll go ahead and get it and then let's do a listing and now you see we have a  file called main.zip that   zip file has all the code  so let's go ahead unzip that let's unzip and let's go ahead and  change our directory to that folder and let's do a listing and there are our files and so the next thing we  want to do is uh we want to go ahead and create a   folder to move all these files in  so what i'm going to do is create a   subdirectory called gpio in our web server folder  that we've previously created and we're going to   put all our files in there and because it's  under that subdirectory web server uh our   node packages that we downloaded will execute  in that directory also so we've created that   directory so let's go ahead and copy all these  files in our current directory to that folder i keep from deleting it so we'll go ahead and copy those files over and then let's go ahead and change  our directory to that folder paste and then let's do a listing here and so you'll see several files in here this very  first file is just basically these instructions   here on the left so you have these instructions  to refer to if you need to we have a mit license   that's this next file we have a public folder the  public folder contains all the files that your   web browser can download in order to run the web  page and so let's go ahead and take a look here   in that folder and you see we have an in doc  index.html file that is the very first file   your web browser downloads when you go to the  ip address of the pi and then main dot js here   that is the javascript code that actually runs on  your web browser in your web browser not on the pi   and then css contains our cascading style sheets   the 404 html that's just basically a dummy  file that gets called up if you attempt to   access a web page that doesn't exist on the pie  it will basically serve up that page instead   and then we got a folder called images and  the only file in the image folder right now is   we'll go ahead and do a listing  is this favoricon dash dot ico   and what that is a lot of web browsers  will complain if you don't have that file   and basically all it is is when you bookmark a web  page you'll see a little icon by that bookmark and   this favoricon icon is that little image you see  so that's the only purpose of that file so let's   go ahead and go back to our main directory  here or our gpio directory do a listing here and so now all we have to do  is type in node web server   actually before i do that let me  just go ahead and clear the page here   get a clean slate let me do a listing again and  all we have to do is type in node web server dot js and that will run our code and so you  can see uh the server is running on port 80   uh and by default i turn on 21 and 16 but  i turn off 26 and 20. so it's just letting   you know what the states of the of the files  are so let's go ahead and bring a web browser   into the picture here so let  me go ahead and go over here   and so let's go ahead and type in the address  of the pi which in my case is 192.168.18.105   and there you go and as you can see gpio16 and  21 are on that's what we initialized them to   and so you can go ahead and turn them on and off  and the video on the beginning of the video is   showed you how that all operated and so that's  basically it we have our web server running now   now if you want to go ahead and stop the web  server you just go over here to our terminal   window and then hit control c and that stops  the web server so now if i go ahead and try and   do a page refresh it says the page doesn't exist  anyway that's it i'll go ahead and do some quick   look at the code here but that's all basically  you need to get your web server running okay so let's uh take a little more look at  the code here so let me go ahead and close   this up one thing i failed to mention here let's  just do a directory listing uh the readme file   just basically refers you to this document  it also refers to this youtube video and then   the webserver.js file that is the javascript  code that runs on your pi so when i typed in when i typed in node webserver.js it was  executing the code in that file and so   that runs on your your pi and that's also  called the back end so let's go ahead and   start genie here uh that's uh the text editor  that i'm using here and we'll go ahead and start   that so the first file that your web browser  calls up like i said is the image.html file   and i'm not going to go in a whole lot of detail  here i just want to cover a few highlights   but basically uh you're like i said your browser  downloads this file first and in here it's got a   couple of references here's that reference to the  favorite favorite con uh image file that a lot   of web browsers like to see and here is a link to  our cascading style sheets uh right there and then   we got our body of our of our web page here and  in here we have our four little containers here   that have each gpio pin on them they're all  little separate little containers there and   about the only thing i'm doing special here is uh  is the toggle button uh where you can toggle the the pin either on or off uh it has an id of like  this first one gpio20 but you see i have a disable   command at the end of this and the reason for that  is normally the normal behavior of a check box is   when you when you press that button first of all  you got to click it you can't press and hold it   and then when you click it it will toggle  that check box from one direction to the   other and we don't want that to happen  because what we want is we want the pi   to actually send that feedback back to  our web browser so we want to disable   that toggling action and that's what this  command does here uh and then this button here that is our little momentary button and i  give it an id of gpio26m for momentary so   we have our other ones here and that's basically  it uh and then down here is our reference to our   uh to our javascript files so the first one is  uh socket io javascript file and if you look   for that on your pi you won't find it and the  reason why is it's actually generated by nodejs   on the fly so if you want to look at this file  it's actually in the other documentation so let   me just go first of all let me go ahead and  turn this uh let me go ahead and turn this   message pane off down here on the bottom and  so let me go ahead and move that over here kind of get this lined up here okay so if you go up here to this documentation  here and it's right here socket io so if you   actually want to look at that uh socket io file  you get it by just opening a terminal on any uh on   any computer that can do a wget command uh and you  just do wget and then the ip address of your pi   and then you uh and then this and that  will download that file for you and you can   actually go ahead and take a look at it if you  if you want to and then this is our call to our   uh main.js file and that's the like i said  the code that runs on in your web browser so that's basically it for the index file uh so let's go ahead and take a  look at our cascading style sheets   there's a lot in here it's a very it's very there's nothing too difficult about it but  it is just a lot of information basically   every web browser has these different defaults  for you know what kind of font it displays   or how the text is oriented and you don't  want to rely upon the defaults of those   of the web browser so in this case we're going  to say here font family uh i want you to do   aerial if you can't do ariel go ahead and do  helvetica and if you can't do that go ahead and do   this font here which virtually is all  web browsers have that font in it uh   then we have a no select that was the file that we  that we call in the in the index file right here   no select class no select and all that does like  i said i believe is that just keeps when you're   pressing a button it won't bring up the clipboard  on your touch screen device and then here's our   gpio containers each one and if you look in there   there's a a float command and what that float  command does is if if your screen is narrow   narrow enough where everything doesn't fit on the  width of the screen uh the float command will that   do will do is rearrange the objects so that they  don't go off screen basically and so if you if you   look at this project on you know an old iphone  or something like that it probably won't all   fit on the page and so what you'll see is the the  the the various gpio containers they'll actually   uh will move down to the next level so you can  see them texa line this is the thing where uh we   say we want all text to be center align this  right here is defining how that slider looks   it's normally just a check box but this  changes the look of it to be a slider   what i suggest if you want to look  into this further uh go to w3schools   uh that's where i got this at and uh they  they got all this uh code right there on their   website and here i'm defining how a  button looks and behaves and so um   that's basically i'm saying how i'm saying  60 pixels wide and the width is auto so if   i put text on there bigger than what the that 60  pixels is the the button width will automatically   increase in size got the height of  50 pixels again i set the font family the color is black for the text the background  color is set to a gray color here this gives the uh gives the edges a button uh a rounded look  uh so there's all these things and it's just   way too much that i could cover in this video  this video is also already getting kind of long   but uh i suggest that you look at some of  the resources i have in the document here   if you have any questions so let's go back up here   right here useful resources so go ahead and  look at these these things in particular here   these videos from uh traverse from this person  here i found particularly useful and here's   just the various videos he has on basically  html javascript no.js uh css and whatnot   so now let's look at our main.js file and this is  the code that javascript code that runs on your   web browser so basically the uh first thing i do  is i create a variable called uh socket and uh   that basically starts socket io is basically all  that does uh and then uh then i have uh i add a   few event listeners and what you'll notice here  is i have this little thing if mobile so if you   go down here to the very bottom you'll see here's  where that is mobile function is defined and all   that does is it tells you if it's a mobile device  or touch screen device or if it's a desktop so mobile devices and desktops have different  different methods of reporting whether something   is pressed and on a on a mobile device it's touch  start and touch and there's also a touch move uh   and then on desktop devices if you're using a  mouse it's mouse up and mouse down and so if we're   doing a mobile device we add these event listeners  and if it's a a desktop we're calling these event   listeners uh and uh so like if when you press a  button on a touch screen it's going to call this   touch start function and if you look down here  there's a function called uh report touch start   and so it causes cause this calls this function  right here uh okay so the next thing here is um this here updates the feedback  when the server changes the l   led state so our pi web server will actually  send updated messages to your web browser   when the state of an led changes so right  here if the state of gpio26 changes uh it   basically uh decodes it and then it updates your  webpage with this new data and likewise for gpio 20 and 21 and 16. okay so let's go to our touch  start here so one of the issues i had with the   toggle buttons is if you just click the button it  would work right but if you actually pressed and   hold the toggle function would never happen and  it only would happen when you release the button   and i wanted to have it happen when you first  touch the button so that's the purpose of   this and this was basically a work around  right here to get that to work because um uh basically there's no  command to do that normally   and so this is calling up uh a pre it's actually  looking at the what they call the document   file and then if it sees in that document file  that you push the gpio26 then what it does   is it sends that command and in this case i  sent a gpio26-t for toggle this is being sent   to the pi and the pie then updates the feedback on  the led and then sends the feedback back and then   this is where your web browser gets it back  right here uh so this is coming from the pie this is going to the pie and so i  do that for each of the i test each   test each one to see if one of those  buttons has been pressed on that touch start   and then uh then here i'm testing uh if  you've pushed one of the momentary buttons   below and if you push like gpio26  the momentary button it will send a it will send a gpio26 command with a 1 to the pi  for the data and that one tells the pi to turn   the led on and then likewise under the touch and  here when you release the button this function   gets called and we send a gpio26 with the data of  zero to the pi and the zero turns the led back off likewise exact same commands for the  mouse down function if you're on a desktop   exactly the same as the touch start and  touch hand and another one for the mouse up and then here's a function for touch move if  you want to use that i'm not doing anything   with that but if after you touch the pi  and you start moving your finger around   uh this function gets called and lets you know  where you're moving your finger at basically and   then again this is the function that determines  whether you're a mobile device or a or a desktop so let's look at the web server.js this is the  backend code this is the code that runs on your pi   and uh so there's a lot of stuff here   but basically um uh if you have any questions on  this like i said refer to these references here   but basically here we're starting our web  server right here on this very first line and   we're assigning it a function called handler  that gets called whenever your web browser   talks to this uh to the pi it calls this  handler function if you look down here there's a   handler function right here and that handler  function basically serves up the web pages   tested that the web page exists and then  it serves them up if you're if you're   calling for an image file it it sends  back the proper response for that   uh here it reads the file if it if that  file doesn't exist it calls it calls the   404 html file instead but if if it uh if that  page does exist then it serves that page up so right here we're defining our gpio pins  basically uh we're we're telling node to   know the on off module in particular to go ahead  and and set up these pins and that right here i'm initializing the value of those pins so  like you saw before uh gpio 26 and gpio20   when you started the web server it defaulted  those leds to off and it defaulted uh gpio21   and gpio16 to on and so if you wanted all the  leds to be off when you start the pi server you   would change these two values to zero here right  here we're defining uh what port we're using   so if you want to use port 8080 instead you  would go ahead and put in 8080 here instead   where you might want to do that is if you want  to run several web servers on your pi at the   same time they all can't be having the same uh  they all can't be using the same port and the   difference is is when you open up your web browser  in addition to keying in the ip address of the pi   you would go ahead and put a colon  behind that in 80 80 and then it   will be able to access the pie then there but  the default is 80 and so if you're using the   defaults you don't need to put in that  colon 80. you can but you don't have to so here we're starting the web server  and here we're running uh the uh   led values uh to the leds  when the web server starts   and then we're also printing out what those  led values are and printing out what port   the web server is running on you saw that  at the when i went ahead and started the node.nodespace webserver.js and there's our event  handler and that's what cause calls up the web   pages uh when when a when you terminate the web  server when you did that control c to terminate   the web server this process gets called here and  all this is doing is it's releasing the gpio pins   so somebody else can use them and then uh and then  it's uh and that's basically it that's all it does and here is uh here's our socket io functions  here so when you press a button on the pi you're   actually not using this handler function instead  you have a direct connection viva web sockets   to this right here so when your web browser first  connects it's going to call this function here and   then i in the console i print out and this is on  the pi console i do client has connected send led   status and then here i'm sending the led statuses  to that client that just connect connected and then uh and so when you do socket emit it  sends it just to the client that's requesting it   if you do a io and that will send it to all  the clients so when your web browser calls the   gpio26 toggle button that's the little toggle  switches on the top uh first thing it does is   it sees what the current uh led status is and it  flips it around the other way so the led is off it   turns it on if the led is on it turns it off and  then it prints it out to the console that's just   some debugging information tells you what the the  new value is and then here it writes it to the led   right here it's actually writing that new  value to the led to turn the led on or off   and then uh and then uh right here i'm just  saying a console.log we're going to go ahead   and send this new state to all the clients and so  here's that iomet and this i omit then sends this   new status along with the it sends gpio26 along  with the new value to all the clients and so all   their web pages get updated with this new value  same thing for gpio2020 gpio21 and gpio26 toggling   and then if somebody presses the momentary buttons  they send this gpio26 command along with the data   and so the first thing we do is read that data  into uh into our variable that we defined above   and it's going to be either a zero or one and  then we check and see if the led is already   in that state if it's not in that state we  go ahead and write the new value to the uh rewrite the new value to the led we go ahead  and console log it out for debug information   and then we also emitted back all to the clients  now actually we don't need this in here but if you   wanted to update the html file so that you would  see those button presses on all the web browsers   that have it open you could do that i'm just not  doing that here but uh this is how you would do   it you would admit it all back to the clients  and you would update your html file to use the   feedback from the pi rather than the the default  action of that button that's normal in html and so we got for all four four momentary  buttons here and then uh the last thing here   is on disconnect whenever somebody disconnects  uh we just send a cons console log to the   node.js console that says uh a user has  disconnected and so that's basically it   uh there's a lot here i know it if you've  never done web development like me uh this is   very um very overwhelming i guess you could say uh  and so uh that's why i made this example to help   other people uh trying to get started with this  and now i do have a full-time job so i don't have   a lot of time to answer questions so if you ask  a question oh i can't get this to work i probably   won't respond uh but that's why i'm giving you  these resources here uh you just have to look   it up yourself but hopefully this gives you a head  start uh if you like this video go ahead and give   it a like and uh i plan to do some additional  ones here uh additional uh web server projects   in particular talking to third-party devices uh so  um i should have some other videos coming up here   shortly anyway good luck uh i hope you found this  informating informative and we'll see you later
Info
Channel: StevesProjects
Views: 15,757
Rating: undefined out of 5
Keywords: Raspberry Pi, web server, node.js, gpio, websockets
Id: TVxQROFPjy0
Channel Id: undefined
Length: 51min 6sec (3066 seconds)
Published: Sat Jan 23 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.