getting the status of arduino digital pins in webpage - javascript

I want to read the status of my digital pins of arduino and want to display it
in web page. For web programming i am using Flask. I tried this code but its not working. from arduino side I am reading the values of 6 digital pins in the form of 1 and 0. How i can do this? Any help would be appreciated.
<!doctype html>
<html>
<head>
</head>
<body>
<h1 style="font-size:30px;font-family:verdana;"><b>STATUS READ </h1><br><br>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="#status1"></p>
<p id="#status2"></p>
<p id="#status3"></p>
<p id="#status4"></p>
<p id="#status5"></p>
<p id="#status6"></p>
<script type=text/javascript>
function updatevalues() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT+"/a",
function(data) {
$("#status1").text(data.m+" %")
$("#status2").text(data.n+" %")
$("#status3").text(data.o+" %")
$("#status4").text(data.p+" %")
$("#status5").text(data.q+" %")
$("#status6").text(data.r+" %")
});
}
</script>
</body>
</html>
Python code:
from flask import Flask, render_template,request,redirect, url_for,jsonify,flash
import flask
from shelljob import proc
import math
import eventlet
eventlet.monkey_patch()
from flask import Response
import serial
import time
from datetime import datetime
import json
import random
from flask.ext.bootstrap import Bootstrap
from flask_bootstrap import WebCDN
app = flask.Flask(__name__)
app.secret_key = 'some_secret'
bootstrap = Bootstrap(app)
app.extensions['bootstrap']['cdns']['jquery'] = WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/')
arduino= serial.Serial( '/dev/ttyACM0' , 9600) #creating object
#app.route('/')
def home():
return render_template('status.html')
#app.route('/a',methods=['GET'])
def a():
mydata=arduino.readline().split(',')
return jsonify(m=float(mydata[0]),n=float(mydata[1]),o=float(mydata[2]),p=float(mydata[3]),q=float(mydata[4]),r=float(mydata[5]))
if __name__ == "__main__":
app.run()

It seems like you're not calling updatevalues in Javascript. You should try with something like this:
setInterval(updatevalues, 1000); //So it runs the function every 1000ms (1 second)

Related

javascript passing data from py script, document.getElementById("demo").innerHTML

I'm making javascript call python result, but the new data not came back from .py script / or document.getElementById("demo").innerHTML not activate
environment: windows, python, and I open with live server in visual studio code
<!DOCTYPE html>
<html>
<body>
<p id="demo">original data</p>
<script type="text/javascript">
const spawner = require('child_process').spawn;
const data_to_pass_in ={
data_sent:'Send this to python script',
data_returned: undifined
};
console.log('Data sent to py script:', data_to_pass_in);
const python_process = spawner('python',['./get_sql_where_02.py', JSON.stringify(data_to_pass_in)]);
python_process.stdout.on('data',(data)=>{
console.log('Data receive from py script:',JSON.parse(data.toString()));
});
document.getElementById("demo").innerHTML = data_to_pass_in;
</script>
</body>
</html>
get_sql_where_02.py
import mysql.connector
import webbrowser
import time
import pymysql
import sys
import ast
mydb = mysql.connector.connect(
host="196.8.98.141",
user="root",
password="password",
database="data_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
mycursor.execute("SELECT P_TITLE,P_PRODUCT FROM webpage WHERE P_ID = '001'")
myresult = mycursor.fetchall()
print(myresult)
data_to_pass_back = myresult
result picture
I just learn js for few hour so maybe is a simple question, that I need javascript call python result on web

Displaying D3.js Chart with Django Backend

I am learning to build dashboard using Django as backend and D3.js for visualization.
Following is my index.html:
{% load static %}
<html>
<script src="https://d3js.org/d3.v7.min.js"></script>
<body>
<h1> Hello! </h1>
<script src={% static "js\linechart.js" %}>
var data = {{ AAPL|safe }};
var chart = LineChart(data, {
x: d => d.date,
y: d => d.close,
yLabel: "↑ Daily close ($)",
width,
height: 500,
color: "steelblue"
})
</script>
</body>
</html>
Data AAPl is extracted from database and the views.py is as follows:
from django.shortcuts import render
from django.http import HttpResponse
from cnxn import mysql_access
import pandas as pd
# Create your views here.
def homepage(request):
sql = ''' select Date, Close from tbl_historical_prices where ticker = 'AAPL' '''
cnxn = mysql_access()
conn = cnxn.connect()
df = pd.read_sql(sql, con=conn)
context = {'AAPL':df.to_json()}
return render(request, 'index.html', context=context)
Function line chart can be viewed here which is being used in js\linechat.js in index.html file.
I can see the Hello! being displayed on the page but can't see the line chart. I am unable to debug the problem. No errors found in console tab either.
How can I display the line plot?
I've added the current page display in attached image.
Close off your script with a src and start a new script tag. The presence of src precludes internal code.
<script src={% static "js\linechart.js" %}></script>
<script>
...

How to save matplotlib figure to jpeg file from javascript request?

I'm developing a web application in linux environnement to display image of data array.
So i would like to save images from python plot to jpeg files to be able to display them in a browser. Python code works correctly when executed from the console. But if called with a javascript request it hangs due to plt use, even with pltioff(). done message is send if i remove all plt code.
python :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import os
import json
curr = os.getcwd()
plt.ioff()
fig, ax = plt.subplots( 1 )
ax.plot([1, 2, 3])
plt.show()
fig.savefig(curr+"/"+'test.jpeg',dpi=224,quality=50)
messJ = json.dumps( "done" )
print('Content-type: text/html')
print("\n")
print "%s" %messJ
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>my page</title>
</head>
<body >
<input type="button" id="plotsrv" value="plotsrv" />
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="pythonplot.js"></script>
javascript :
document.getElementById('plotsrv').addEventListener('click', trait_Vdatasrv, false);
function trait_Vdatasrv (e) {
var url = 'pyplot.py';
console.log("url:"+url);
$.post(url,{ file:'ncfile' }, function(data){
$('#data').html(data);
console.log("data"+data);
var jsdec=JSON.parse(data);
console.log(jsdec); }
); }
Regards
I finally found ,
it is needed to add matplotlib.use('Agg')
to avoid display output

Auto refresh not working in javascript

I try to draw circular gauge using jQuery and circularchart and I'm able to make it.
I want the setInterval() function of javascript to auto-refresh the value so that the gauge value keep update by itself without manual refresh.
But the setinterval() function is not working at all.
I don't want to refresh the whole page or the body of html.
I just want to refresh the particular circleChart#0 function.
Your help is needed.
This is circle.html
<body>
<div class="circleChart" id="0"></div>
<div class="circleChart" id="1" data-value="77"></div>
<script src="{{ url_for('static', filename='jquery-1.12.4.min.js') }}"></script>
<script src="{{ url_for('static', filename='circleChart.js') }}"></script>
<script>
$(".circleChart#1").circleChart();
$(".circleChart#0").circleChart({
size: 200,
value: {{temperature}},
text: 0,
onDraw: function(el, circle) {
circle.text(Math.round(circle.value) + "'C");
}
});
setInterval(function() {
$("#0").circleChart({
value: {{temperature}},
onDraw: function(el, circle) {
circle.text(Math.round(circle.value) + "'C");
}
});
}, 2000);
</script>
</body>
</html>
This is my python code (main.py)
#!/usr/bin/python
from flask import Flask, render_template
app = Flask(__name__)
import os
import glob
import time
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f
#app.route("/")
def main():
temperature , humidity = read_temp()
templateData = {
'temperature' : temperature,
'humidity': humidity
}
return render_template('circle.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
Assuming {{temperature}} is some kind of template variable, those are (typically) only evaluated once when generating the page from your template.
You will need some kind of AJAX call to fetch the updated temperature value.

Passing array from Flask to Javascript to create options for drop down menu

I am new to Flask and Javascript. I am trying to upload a file and use one of its columns as options in the drop down menu. Please correct me where I am wrong.
Here are the codes:
Flask:
from flask import Flask, render_template, redirect, url_for, request, flash, send_from_directory
from werkzeug import secure_filename
import os
import pandas as pd
import numpy as np
import json
UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = set(['csv'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['data_file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
data = pd.read_csv(os.path.join(app.config['UPLOAD_FOLDER'], filename))
names = data['some_column']
return redirect(url_for('drop_down', names=names))
#return render_template('drop_down.html', names=names)
return render_template('file_upload.html')
#app.route('/meta')
def drop_down():
return render_template('drop_down.html')
Javascript:
function my_script(){
console.log('script called.');
//var cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"];
var cars = {{ names|safe }};
console.log('cars assigned.');
function make_drop_down(list_of_names, element_id){
select_elem = document.getElementById(element_id)
if(select_elem){
for(var i = 0; i < list_of_names.length; i++) {
var option = document.createElement('option');
option.innerHTML = list_of_names[i];
option.value = list_of_names[i];
select_elem.appendChild(option);
}
}
};
console.log("Making Drop Downs!!");
make_drop_down(cars, 'drop_down_1');
make_drop_down(cars, 'drop_down_2');
console.log("Made Drop Downs!!");
};
html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="static/drop_down.js"></script>
<title>DROP DOWN</title>
</head>
<body onload="my_script()">
<select id="drop_down_1">
<option>Choose Option 1</option>
</select>
</br></br>
<select id="drop_down_2">
<option>Choose Option 2</option>
</select>
</body>
</html>
I get the following error on the console:
ReferenceError: my_script is not defined
There are two problems.
The first one is that you are not passing the list of cars in your view handeling /meta
#app.route('/meta')
def drop_down():
return render_template('drop_down.html')
This should probably look something like this:
#app.route('/meta')
def drop_down():
cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"]
return render_template('drop_down.html',
names=cars)
The second problem is that your javascript won't be able to access the list, unless you pass it in your call to the function.
html
<body onload="my_script({{ names }})">
javascript
function my_script(names){
console.log('script called.');
var cars = names;
...
Edit:
The function that handles the view is the function that needs to pass the data. You could also use the commented away part of your upload file, which calls render_template... with the necessary data, but this doesn't feel as a "nice" approach.
You need to make the data available to your drop_down() view, either by storing it in a database, reading the data from the file in this function or by storing it in the session. So that you can pass the data along with the template

Categories

Resources