At this point, you have yourself a website and a web socket and an LED, but the LED is still not turning on and off. In order to get that functionality, we need to go back to the app.py file and add some code to the handler function beneath the print(message). We first need to convert the incoming JSON object into a python dictionary that we can read. This is done using the json library we installed earlier like so.
Next, we need to turn the LED on and off depending on what is in the data. The “value” field of our JSON is either true or false, so we can create a simple if loop to use it. Put this code block after your data = json line.
When you are finished, app.py should look like this. You can now rerun app.py and you should be able to toggle the LED from your browser. Yay!
Congratulations, you now have your own website that controls an LED running on your Pi. All done, mission complete, you are a master of web socket. Right? Well, the system works all well and good on your machine, but if you try to open http://0.0.0.0:8000 on your PC or phone, it will just tell you that it cannot connect to that URL. Why? Well, every machine has a localhost at the IP address 127.0.0.1 that they can serve web traffic on, but it only lets that machine connect to itself. In order to get past this, we need to take the next step and broadcast your Pi to the rest of the network.
To do this, you need to first get your Pi’s IP address. To do this, open a terminal window and run
$ ifconfig | grep “inet”
This will get all the network information for your Pi and filter it for IP addresses. The output should look something like this:
In our case, we want the address that is the third one down and that I have highlighted here. Copy that, which uses Ctrl+Shift+C in the terminal instead of Crtl+C, and then go to back to the editor where you have app.py opened. We can now change the address that our Pi broadcasts the web socket on from the localhost to this public address by just pasting it in place of where you had localhost before in the websockets.serve function
Now that it is serving the websocket differently, you also need to make sure that main.js is connecting to it on the new URI that will be generated. So, go to main.js, go to the part of the URI you created the web socket connection with that says localhost, and change it out for your IP address like so.
Now, if you rerun app.py, you should still be able to control the LED from the browser on your Pi. If not, you may want to double check that you have the correct IP address. If that is all running well, try going to another computer or your phone that is on the same WiFi network as your Pi and open the URL <your pi’s ip address here>:8000 to see if it connects. You should now be able to control the LED from any device that is connected to the same WiFi network as the Pi!