In order to set up a web socket connection, we need to install the necessary libraries. We will be using the websockets library for network communication between the Pi and the website that it will be running. Run the following command to install the library from python’s pip package manager.
$ pip install websockets
After that, create a new folder in your home directory called IoT_project, create a file inside of that folder called app.py and open it in your editor of choice. I recommend using Geany on the Pi, simply because it has support for JavaScript and HTML, which will be useful later.
Now comes the fun part: writing code! First, we need to import all of our libraries. We will need the websockets and json libraries we just installed, asyncio, which is preinstalled on python and helps us manage waiting for messages to come in from the webpage, and gpiozero for controlling the LED.
We then need to setup our LED, which is on GPIO pin 17 if you remember.
Next, we need to define the handler function. This will take in a websocket as a parameter and handler the messages it receives. To start, we will make it loop infinitely and print out any messages that we receive. The keyword async in front of it allows for the asynchronous functionality needed for websockets. This is needed in order to account for network lag and the process of waiting for incoming signals from the client webpage.
After this, we can define out main function and our WebSocket. This simply starts a websocket that is served on the localhost at port 8001.
Before you go on to building the website to control your Pi from, test that everything in app.py is running properly. To do this, open a terminal, navigate to the directory containing app.py and run the below command.
$ python app.py
If the program just runs without any output, that means that it is working. You are now ready to build the website portion of this project.