Skip to content

Commit

Permalink
add flask+plotly
Browse files Browse the repository at this point in the history
  • Loading branch information
binh-bk committed Aug 8, 2018
1 parent 211f193 commit e5b870e
Show file tree
Hide file tree
Showing 5 changed files with 158 additions and 0 deletions.
73 changes: 73 additions & 0 deletions FlaskandPlotly/app_pi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from flask import Flask, render_template

import json
import plotly
from plotly import tools
import plotly.graph_objs as go
import sqlite3

app = Flask(__name__)



class SqlReader:

def getData(self):
#connection = sqlite3.connect('/fullpath/to/sqlit3/pirs.db')
connection = sqlite3.connect('pirs.db')
cursor = connection.cursor()

sql_command = """
SELECT * from pirone
ORDER BY thetime DESC
LIMIT 2000;"""

cursor.execute(sql_command)
result = cursor.fetchall()

cursor.close()
return result


@app.route('/')
def index():
sql = SqlReader()
result = sql.getData()

numOfPoints = len(result)

pir = [yValues[1] for yValues in result]
xValues = [xValues[0] for xValues in result]

graphs = [

dict(
data=[
dict(
x=xValues,
y=pir,
type='bar'
),
],
layout=dict(
title='Motion vs Time'
)
)
]

# Add "ids" to each of the graphs to pass up to the client
# for templating
ids = ['Graph {}'.format(i) for i, _ in enumerate(graphs)]

# Convert the figures to JSON
# PlotlyJSONEncoder appropriately converts pandas, datetime, etc
# objects to their JSON equivalents
graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

return render_template('layouts/index.html',
ids=ids,
graphJSON=graphJSON)


if __name__ == '__main__':
app.run(host='0.0.0.0', port=9999)
43 changes: 43 additions & 0 deletions FlaskandPlotly/listen_to_pir.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#! /usr/bin/python3
import time
import sqlite3, json
import paho.mqtt.client as mqtt


mqtt_topic = "sensor/door/pir"
mqtt_username = "janedoe"
mqtt_password = "johndoe"
dbFile = "pir.db"
mqtt_broker_ip = '192.168.1.50'

def takeTime():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(mqtt_topic, 0)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
time_ = takeTime()
topic = msg.topic
payload = json.dumps(msg.payload.decode('utf-8'))
sql_cmd = sql_cmd = "INSERT INTO {1[sensor]} VALUES ('{0}', {1[motion]})".format(time_, payload)
writeToDB(sql_cmd)
print(sql_cmd)
return None

def writeToDB(sql_command):
conn = sqlite3.connect(dbFile)
cur = conn.cursor()
cur.execute(sql_command)
conn.commit()

client = mqtt.Client()
client.username_pw_set(username=mqtt_username, password=mqtt_password)
client.connect(mqtt_broker_ip, 1883, 60)
client.on_connect = on_connect
client.on_message = on_message
time.sleep(1)

client.loop_forever()
Binary file added FlaskandPlotly/pirs.db
Binary file not shown.
2 changes: 2 additions & 0 deletions FlaskandPlotly/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
plotly
flask
40 changes: 40 additions & 0 deletions FlaskandPlotly/templates/layouts/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!doctype html>
<html>

<head>
<meta http-equiv="refresh" content="60">

</head>

<body>
{% for id in ids %}
<!--<h3><font face='Arial'>{{id}}</font></h2>-->
<div id="{{id}}"></div>
{% endfor %}

</body>


<footer>
<!-- D3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<!-- Plotly.js -->
<script src="https://d14fo0winaifog.cloudfront.net/plotly-basic.js"></script>

<script type="text/javascript">

var graphs = {{graphJSON | safe}};
var ids = {{ids | safe}};

for(var i in graphs) {
Plotly.plot(ids[i], // the ID of the div, created above
graphs[i].data,
graphs[i].layout || {});
}

</script>
</footer>

</html>

0 comments on commit e5b870e

Please sign in to comment.