store recordedAt

This commit is contained in:
Ruben van de Ven 2018-10-30 15:55:16 +01:00
parent 73c3152e21
commit 29d8a18476
5 changed files with 24 additions and 5 deletions

1
.gitignore vendored
View file

@ -1,5 +1,6 @@
heartbeat.db heartbeat.db
venv/ venv/
*.pyc *.pyc
token.json

View file

@ -23,7 +23,7 @@ class ExportHandler(tornado.web.RequestHandler):
# Not found # Not found
raise tornado.web.HTTPError(404) raise tornado.web.HTTPError(404)
c.execute("SELECT * FROM beats WHERE createdAt > date('now', ?) ORDER BY createdAt ASC", (ranges[range],)) c.execute("SELECT * FROM beats WHERE recordedAt > date('now', ?) ORDER BY recordedAt ASC", (ranges[range],))
self.write("id,bpm,timestamp\n") self.write("id,bpm,timestamp\n")
for row in c: for row in c:
self.write("{},{},{}\n".format(row['id'], row['bpm'], row['createdAt'])) self.write("{},{},{}\n".format(row['id'], row['bpm'], row['createdAt']))

View file

@ -6,11 +6,18 @@ from .frontend import FrontendHandler
from .export import ExportHandler from .export import ExportHandler
import sqlite3 import sqlite3
import os import os
import json
def start(args): def start(args):
basedir = os.path.dirname(os.path.realpath(__file__)) +'/../' basedir = os.path.dirname(os.path.realpath(__file__)) +'/../'
conn = sqlite3.connect(basedir + 'heartbeat.db') conn = sqlite3.connect(basedir + 'heartbeat.db')
with open(basedir+'token.json', 'r') as fp:
t = json.load(fp)
token = t['token']
print("VALIDATE WITH TOKEN: '{}'".format(token))
conn.cursor() conn.cursor()
conn.row_factory = sqlite3.Row conn.row_factory = sqlite3.Row
c = conn.cursor() c = conn.cursor()
@ -20,9 +27,11 @@ def start(args):
bpm INTEGER, bpm INTEGER,
beatcount INTEGER, beatcount INTEGER,
beattime REAL, beattime REAL,
recordedAt TIMESTAMP,
createdAt TIMESTAMP DEFAULT (datetime('now','localtime')) createdAt TIMESTAMP DEFAULT (datetime('now','localtime'))
); );
""") """)
c.execute("CREATE INDEX IF NOT EXISTS beats_recordedAt ON beats (recordedAt);")
conn.commit() conn.commit()
# start a new WebSocket Application # start a new WebSocket Application
@ -30,7 +39,7 @@ def start(args):
# WebSocketHandler as our handler # WebSocketHandler as our handler
application = tornado.web.Application([ application = tornado.web.Application([
(r"/", FrontendHandler, {"conn": conn}), (r"/", FrontendHandler, {"conn": conn}),
(r"/ws", WebSocketHandler, {"conn": conn}), (r"/ws", WebSocketHandler, {"conn": conn, "token": token}),
(r"/(.*).csv", ExportHandler, {"conn": conn}), (r"/(.*).csv", ExportHandler, {"conn": conn}),
],debug=True) ],debug=True)

View file

@ -7,11 +7,12 @@ import json
class WebSocketHandler(tornado.websocket.WebSocketHandler): class WebSocketHandler(tornado.websocket.WebSocketHandler):
connections = set() connections = set()
def initialize(self, conn): def initialize(self, conn, token):
""" """
conn: sqlite3 connection conn: sqlite3 connection
""" """
self.conn = conn self.conn = conn
self.token = token
# the client connected # the client connected
def open(self): def open(self):
@ -28,6 +29,9 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler):
[con.write_message(message) for con in self.connections] [con.write_message(message) for con in self.connections]
return False return False
if beat['token'] != self.token:
raise Exception("Invalid token!")
if beat['rate'].endswith('*'): if beat['rate'].endswith('*'):
beat['rate'] = beat['rate'][:-1] beat['rate'] = beat['rate'][:-1]
beat['rate'] = beat['rate'].strip() beat['rate'] = beat['rate'].strip()
@ -38,10 +42,14 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler):
beat['time'] = beat['time'][:-1] beat['time'] = beat['time'][:-1]
beat['time'] = beat['time'].strip() beat['time'] = beat['time'].strip()
beat['timestamp'] = beat['timestamp'].strip()
print(beat)
c = self.conn.cursor() c = self.conn.cursor()
c.execute(""" c.execute("""
INSERT INTO beats (bpm,beatcount,beattime) INSERT INTO beats (bpm,beatcount,beattime, recordedAt)
VALUES (:rate, :count, :time) VALUES (:rate, :count, :time, :timestamp)
""", beat) """, beat)
insertid = c.lastrowid insertid = c.lastrowid
self.conn.commit() self.conn.commit()

1
token.example.json Normal file
View file

@ -0,0 +1 @@
{"token":"abcdefghijklmnop"}