72 lines
1.7 KiB
Python
72 lines
1.7 KiB
Python
import tornado.websocket
|
|
import json
|
|
|
|
|
|
# This is our WebSocketHandler - it handles the messages
|
|
# from the tornado server
|
|
class WebSocketHandler(tornado.websocket.WebSocketHandler):
|
|
connections = set()
|
|
|
|
def initialize(self, conn, token):
|
|
"""
|
|
conn: sqlite3 connection
|
|
"""
|
|
self.conn = conn
|
|
self.token = token
|
|
|
|
# the client connected
|
|
def open(self):
|
|
self.connections.add(self)
|
|
print ("New client connected")
|
|
|
|
# the client sent the message
|
|
def on_message(self, message):
|
|
# {"rate":"77*", "count":"4", "time":"14.44"}
|
|
try:
|
|
beat = json.loads(message)
|
|
except Exception as e:
|
|
print("Probably no valid JSON")
|
|
[con.write_message(message) for con in self.connections]
|
|
return False
|
|
|
|
if beat['token'] != self.token:
|
|
raise Exception("Invalid token!")
|
|
|
|
if beat['rate'].endswith('*'):
|
|
beat['rate'] = beat['rate'][:-1]
|
|
beat['rate'] = beat['rate'].strip()
|
|
if beat['count'].endswith('*'):
|
|
beat['count'] = beat['count'][:-1]
|
|
beat['count'] = beat['count'].strip()
|
|
if beat['time'].endswith('*'):
|
|
beat['time'] = beat['time'][:-1]
|
|
beat['time'] = beat['time'].strip()
|
|
|
|
beat['timestamp'] = beat['timestamp'].strip()
|
|
|
|
print(beat)
|
|
|
|
c = self.conn.cursor()
|
|
c.execute("""
|
|
INSERT INTO beats (bpm,beatcount,beattime, recordedAt)
|
|
VALUES (:rate, :count, :time, :timestamp)
|
|
""", beat)
|
|
insertid = c.lastrowid
|
|
self.conn.commit()
|
|
|
|
c.execute("SELECT createdAt FROM beats WHERE id = ?", (insertid,))
|
|
now = c.fetchone()[0]
|
|
|
|
beat['bpm'] = int(beat['rate'])
|
|
beat['timestamp'] = now
|
|
# actively close connection :-)
|
|
[con.write_message(json.dumps(beat)) for con in self.connections]
|
|
self.close()
|
|
|
|
|
|
|
|
|
|
# client disconnected
|
|
def on_close(self):
|
|
self.connections.remove(self)
|
|
print ("Client disconnected")
|