#!/usr/bin/python3 from flask import Flask, request import threading import serial import time app = Flask(__name__) globals()['data'] = "" globals()['lock'] = threading.Lock() @app.route('/update', methods=['PUT']) def update(): grid = request.json['data'] grid_string = prepare_grid(grid) with globals()['lock']: globals()['data'] = grid_string return grid_string def prepare_grid(grid): # follow down up down down up down HEIGHT = 5 WIDTH = 6 out = "" for x in range(WIDTH): for y in (range(0,HEIGHT,1) if x%3 == 1 else range(HEIGHT-1,-1,-1)): for r in range(3): out += hex(grid[x][y][r])[2:] + 'n' out += 'l' out += 'q' return out def serial_func(): with serial.Serial('/dev/ttyACM0', 9600, timeout=1) as ser: while True: with globals()['lock']: if globals()['data'] != '': t1 = time.time() ser.write(bytes(globals()['data'], 'ascii')) t2 = time.time() print("time taken: " + str(t2-t1) + "s") globals()['data'] = '' time.sleep(0.1) serial_thread = threading.Thread(target=serial_func) serial_thread.start() if __name__ == '__main__': app.run(host='0.0.0.0')