Skip to content
Snippets Groups Projects
Commit fe77e80d authored by s84716's avatar s84716
Browse files

websocket code

parent 5d04ee47
No related branches found
No related tags found
No related merge requests found
#!/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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment