I am working on a Flask app which starts as soon as Nvidia Jestson bootsup. There are 2 threads : 1. serial read continually gets the values from uart and updates the web page
- backgroundthread which does some calculation based on the values got from the html form.
My code goes something like this:
thread1 = Thread()
thread2 = Thread()
thread1_stop_event = Event()
class serial_read_Thread(Thread):
def __init__(self):
self.delay = 0.1
self.port = serial.Serial ( port='/dev/ttyTHS2', baudrate=115200,
parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS, timeout=1)
super(serial_read_Thread, self).__init__()
def serial_read (self):
try:
x = self.port.read().decode()
recvd_string += x
#receive the list as string and convert it to list
for val in range(1, len(recvd_string)):
if (val % 2 != 0):
index = int(float(recvd_string[val]))
else:
received_signal_values[index] = recvd_string[val]
number1 = received_signal_values[0]
number2 = received_signal_values[1]
socketio.emit('newnumber', {'number1':number1, 'number2':number2}, namespace='/test')
time.sleep(self.delay)
except UnicodeDecodeError:
print("UnicodeDecodeError \n")
pass
def run(self):
self.serial_read()
class Backgroundthread(Thread):
def __init__(self):
super(Backgroundthread, self).__init__()
def process_data(self):
do_calculation()
def run(self):
self.process_data()
@app.route("/", methods=['GET', 'POST'])
def hello():
form = TestForm()
global thread2
if request.method == 'POST':
Get the values from the html form
if not thread2.isAlive():
thread2 = Backgroundthread()
thread2.start()
return render_template('hello.html', form=form)
@socketio.on('connect', namespace='/test')
def test_connect():
# need visibility of the global thread object
global thread1
print('Client connected')
#Start the serial read thread
print("Starting Serial Read Thread")
thread1 = serial_read_Thread()
thread1.daemon = True
thread1.start()
@socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected')
if __name__== "__main__":
socketio.run(app)
When I manually run the code I see the Web-browser with my page loaded, the values being updated from the serial thread. Also when I input the values through the web page I see the background thread being processed. But the same does not work when I run the code from the startup script on Jetson. I see the webpage with values being updated but when I input the values from the html form I do not see the background thread being processed. Also I would like to know if this is a correct way to merge threads with the flask app. Sorry for the long post. Thanks in advance