Websocket – python Raspberry pi

In this page, I will share on how to create a WebSockets to control the GPIO in Python and using Tornado as a webserver.

Install the Tornado by running the following command:

sudo pip install tornado

Then, download the template from repository:
wget git clone https://github.com/iphton/Raspberry-Pi-WebSocket.git or simply download locally. 
After download the repo extract it.

Then, create a file name "server.py" and run nano editor
sudo nano server.py

write the following code:

! /usr/bin/python3
 from gpiozero import LED
 from time import sleep
 import os.path
 import tornado.httpserver
 import tornado.websocket
 import tornado.ioloop
 import tornado.web
 PORT = 80
 led1 = LED(17)
 led2 = LED(18)
 led1.off()
 led2.off()
 Tornado Folder paths
 settings = dict(
     template_path = os.path.join(os.path.dirname(file),"templates"),
     static_path = os.path.join(os.path.dirname(file),"static")
     )
 print(settings)
 class MainHandler(tornado.web.RequestHandler):
     def get(self):
         print("HTTP User Connected.")
         self.render("index.html")
 class WSHandler(tornado.websocket.WebSocketHandler):
   def open(self):
     print ('[WS] Connection was opened.')
 def on_message(self, message):
     print ('[WS] Incoming message:', message)
 if message == "green_on":   led1.on() if message == "green_off":   led1.off() #if message == "on_r": #   led1.on() #if message == "off_r": #   led1.off() #if message == 'on_b':  # GPIO.output(11 , True) #if message == 'off_b':   #GPIO.output(11 , False) #if message == 'on_w':  # GPIO.output(13 , True) #if message == 'off_w':  # GPIO.output(13 , False)
 def on_close(self):
     print ('[WS] Connection was closed.')
 application = tornado.web.Application([
   (r'/', MainHandler),
   (r'/ws', WSHandler),
   ], **settings)
 if name == "main":
     try:
         http_server = tornado.httpserver.HTTPServer(application)
         http_server.listen(PORT)
         main_loop = tornado.ioloop.IOLoop.instance()
     print ("Tornado Server started")     main_loop.start() except:     print ("Exception triggered - Tornado Server stopped.")     led1.off()

Then, create a html file name "index.html" and put in a folder named templates:

sudo mkdir templates
cd templates
sudo nano index.html

Write the following code:
<html>

<head>
<title> Socket IO</title>
<!-- <link rel = "stylesheet" type = "text/css" href = "C:\Users\Mohammed Innat\Downloads\Compressed\a\ws-webio\templates\view.css"/> -->

<style type="text/css">
	
.button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 34px 44px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    margin: 10px 10px;
    -webkit-transition-duration: 0.4s; /* Safari */
    transition-duration: 0.4s;
    cursor: pointer;
}

.button1 {
    background-color: white; 
    color: black; 
    border: 6px solid #4CAF50;
}
.button1:hover {
    background-color: #4CAF50;
    color: white;
}


.button2 {
    background-color: white; 
    color: black; 
    border: 6px solid #008CBA;
}
.button2:hover {
    background-color: #008CBA;
    color: white;
}

</style>

</head>

<body>

<div> <!-- LEDs -->
<h1>Web Socket IO</h1>


<button id="green_on" class="button button1">ON</button>
<button id="green_off" class="button button2">OFF</button>


<hr>
Websocket status:
<br>
<div id="ws-status"> Waiting... </div>

<!-- Scripts -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="{{ static_url("ws-client.js")}}"></script>

</body>

</html>
Then, create a node.js file name "ws-client.js" and put in a folder named static:

sudo mkdir static
cd static
sudo nano ws-client.js

Write the following code:
$(document).ready(function(){

        var WEBSOCKET_ROUTE = "/ws";

        if(window.location.protocol == "http:"){
            //localhost
            var ws = new WebSocket("ws://" + window.location.host + WEBSOCKET_ROUTE);
            }
        else if(window.location.protocol == "https:"){
            //Dataplicity
            var ws = new WebSocket("wss://" + window.location.host + WEBSOCKET_ROUTE);
            }

        ws.onopen = function(evt) {
            $("#ws-status").html("Connected");
            };

        ws.onmessage = function(evt) {
            };

        ws.onclose = function(evt) {
            $("#ws-status").html("Disconnected");
            };

        $("#green_on").click(function(){
            ws.send("green_on");
            });

        $("#green_off").click(function(){
            ws.send("green_off");
            });

 });

Now from your pi browser or from any brower in pc , go folowing –your_raspberry_pi_ip_address:80

Now we can control GPIO pin from our brower by making a web socket.