heartbeatserver/heartbeat/ws.py

65 lines
1.5 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):
"""
conn: sqlite3 connection
"""
self.conn = conn
# 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['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()
c = self.conn.cursor()
c.execute("""
INSERT INTO beats (bpm,beatcount,beattime)
VALUES (:rate, :count, :time)
""", 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")