'Continuous serial read and call to write, Python Flask
I'm trying to store a history of serial communication and write simultaneously and show it with flask, but it only works when are someone as client.
import serial # serial port
from flask import Flask, render_template, request # flask utils
import flask
app = Flask(__name__) # flask init
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600)
@app.route("/") # Home page
def root():
history = # get the saved history
return render_template("test1.html", input_from_python=history)
@app.route("/get", methods=["POST"]) # Get the messange to send
def test_get():
msg = request.form["msg"]
if msg != "":
send = msg + "\r\n"
ser.write(send.encode()) # send message
# *save in the history*
return msg
return "Empty"
def event_serial(ser):
str = ser.readline().decode()
yield 'data:' + ''.join(str) + '\n\n'
@app.route('/serupdate')
def serial_update():
newresponse = flask.Response(event_serial(ser),
mimetype="text/event-stream")
newresponse.headers.add('Access-Control-Allow-Origin', '*')
newresponse.headers.add('Cache-Control', 'no-cache')
msg_ = newresponse.data.decode().rstrip().replace("data:", "")
# *save in the history*
return newresponse
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)
I know that it is because the call to read the serial input it's in the frontend, but I don't know how to make it in the backend.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TEST</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"
type="text/javascript"
charset="utf-8"
></script>
<script>
function zfill(number, width) {
var numberOutput = Math.abs(number);
var length = number.toString().length;
var zero = "0";
if (width <= length) {
if (number < 0) {
return "-" + numberOutput.toString();
} else {
return numberOutput.toString();
}
} else {
if (number < 0) {
return "-" + zero.repeat(width - length) + numberOutput.toString();
} else {
return zero.repeat(width - length) + numberOutput.toString();
}
}
}
</script>
<script>
$(document).ready(function () {
if (!!window.EventSource) {
console.log("SSE supported.");
var source = new EventSource(' {{ url_for("serial_update") }} ');
source.addEventListener(
"message",
function (e) {
// *show the data*
},
false
);
source.addEventListener(
"open",
function (e) {
console.log("Connection was opened.");
},
false
);
source.addEventListener(
"error",
function (e) {
if (e.readyState == EventSource.CLOSED) {
console.log("Connection was closed.");
}
},
false
);
} else {
console.log("SSE notsupported.");
}
});
</script>
<script>
$(document).ready(function() {
let list_data = {{ input_from_python | tojson }};
console.log(list_data)
list_data.forEach(function(item){
// *show the data from history*
})
});
</script>
</head>
<body>
<div class="row">
<div class="col-md-10 mr-auto ml-auto">
<h1>System sender</h1>
<form>
<div id="chatbox">
<div class="col-md-8 ml-auto mr-auto">
<textarea rows="10" cols="80" id="data" disabled></textarea>
</div>
</div>
<div id="userInput" class="row">
<div class="col-md-10">
<input
id="text"
type="text"
name="msg"
placeholder="Message"
class="form-control"
/>
<button type="submit" id="send" class="btn btn-warning">
Send
</button>
</div>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function () {
$("form").on("submit", function (event) {
var rawText = $("#text").val();
var userHtml = '<p class="userText"><span>' + rawText + "</span></p>";
$("#text").val("");
document.getElementById("userInput").scrollIntoView({
block: "start",
behavior: "smooth",
});
$.ajax({
data: {
msg: rawText,
},
type: "POST",
url: "/get",
}).done(function (data) {
// Sending data
d = new Date();
day = d.getDate();
month = d.getMonth() + 1;
hour = zfill(d.getHours(), 2);
min = zfill(d.getMinutes(), 2);
sec = zfill(d.getSeconds(), 2);
date = day + "/" + month + " " + hour + ":" + min + ":" + sec;
if (data != "Empty") {
// *show the data*
}
document.getElementById("userInput").scrollIntoView({
block: "start",
behavior: "smooth",
});
});
event.preventDefault();
});
});
</script>
</body>
</html>
Actually, I'm implementing a Postgres db to store the data, but first I want to make it works continuously. I have thinking to make the python script only save the data in the db and the frontend make the queries, but the problem will be to write to the serial.
I hope you can help me with this, probably the answer is much easier than I think, sorry if it's the case.
Thanks for the help
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
