From fe77e80d24cf67655bf7304e7fa1c43371364dab Mon Sep 17 00:00:00 2001
From: s84716 <s84716@bht-berlin.de>
Date: Tue, 10 Dec 2024 16:20:08 +0100
Subject: [PATCH] websocket code

---
 websocket | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 96 insertions(+)
 create mode 100644 websocket

diff --git a/websocket b/websocket
new file mode 100644
index 0000000..bbd228d
--- /dev/null
+++ b/websocket
@@ -0,0 +1,96 @@
+#!/usr/bin/python3
+
+# Tornado web server
+import tornado.ioloop
+import tornado.options
+import tornado.web
+import tornado.websocket
+
+# General functionalities
+import time
+
+# Sensor libs
+import board
+import adafruit_dht
+
+# sensor type is DHT22, 4 in D4 is the GPIO4 and *not* the actual pin number
+dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)
+
+from tornado.options import define, options
+define("port", default=8081, help="run on the given port", type=int)
+
+# HTML page to be returned by default
+class IndexHandler(tornado.web.RequestHandler):
+    def get(self):
+        self.render("index.html")
+
+# Defining WebSocket Operations
+class WebSocketHandler(tornado.websocket.WebSocketHandler):
+
+    # New incoming connection, remember clients for later replies
+    def open(self):
+        print ("Incoming connection from: {}".format(self.request.connection.context.address))
+        clients.append(self)
+
+    # Message processing
+    def on_message(self, message):
+        print ("Processing message: " + message)
+
+        # Helper variable
+        valueDisplayed = False
+
+        # repeat in case of failed measurements 
+        while (not valueDisplayed):
+            try:
+
+                # retrieve measured values
+                temperature = dhtDevice.temperature
+                humidity = dhtDevice.humidity
+                # convert to string
+                temperaturestr = "{:.1f}".format(temperature)
+                humiditystr = "{:.1f}".format(humidity)
+        
+                # JSON-formatted data string
+                data = "{\"temperature\":" + temperaturestr + ", \"humidity\":" + humiditystr + "}"
+
+                # reply to clients
+                for c in clients:
+                    c.write_message(data)
+                    print ("reply to: " + str(c.request.connection.context.address))
+            
+                # success
+                valueDisplayed = True
+                time.sleep(2.0)
+
+            except RuntimeError as error:
+
+                # In case of error - repeat measurement
+                print(error.args[0])
+                time.sleep(2.0)
+                continue
+            
+            except Exception as error:
+                dhtDevice.exit()
+                raise error            
+
+    def on_close(self):
+        print ("connection closed: {}".format(self.request.remote_ip))
+        clients.remove(self)
+
+if __name__ == "__main__":
+
+    try:
+        # clients of this webserver
+        clients = []
+        
+        # setting up Tornado
+        tornado.options.parse_command_line()
+        app = tornado.web.Application(handlers=[(r"/ws", WebSocketHandler),(r"/", IndexHandler)])
+
+        httpServer = tornado.httpserver.HTTPServer(app)
+        httpServer.listen(options.port)
+        print ("Listening on port:" + str(options.port))
+        tornado.ioloop.IOLoop.instance().start()
+
+    except KeyboardInterrupt:
+        tornado.ioloop.IOLoop.instance().stop()
\ No newline at end of file
-- 
GitLab