# Copyright (C) 2020 Daniel Richardson richardson.daniel@hotmail.co.uk # # This file is part of stockTicker project for justinodunn. # # stockTicker can not be copied and/or distributed without the express # permission of Daniel Richardson from flask import Flask, render_template, request from stockTicker import StockTicker from werkzeug.utils import secure_filename import os import datetime import threading import csv import pexpect import time import json from multiprocessing import Process from subprocess import Popen, PIPE #stock_ticker = StockTicker() api_caller = pexpect.spawn("sudo -E python3 api_caller.py") command = 300 tickerList = 0 DelayTime = 20 LastCommand = '' speedTime = 25 LOGO_FOLDER = 'logos/' CSV_FOLDER = 'csv/new/' ALLOWED_EXTENSIONS = {'csv', 'png'} #ticker.stdin.write(b'from server') #print(ticker.stdout.readlines()) #(output, errs) #time.sleep(10) # let api calls finish ticker = pexpect.spawn("sudo -E python3 stockTicker.py") ticker.sendline('S') # run by default #stock_ticker = StockTicker() def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def process_file(path, filename): default_csv = csv.writer(open('csv/tickers.csv', 'w')) new_csv = csv.reader(open((path), 'r')) for row in new_csv: default_csv.writerow(row) app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def hello(): global command now = datetime.datetime.now() timeString = now.strftime("%Y-%m-%d %H:%M") logos_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos') LogoList = os.listdir(logos_path) templateData = { 'title' : 'Stock Ticker Control Panel', 'time': timeString, 'runtime': command, 'tickers': tickerList, 'logofiles':LogoList, 'lastcommand':LastCommand, 'delay':DelayTime, 'speedtime':speedTime } return render_template('index.html', **templateData) @app.route("/Runtime", methods=['POST']) def Runtime(): global command command = request.form['text'] print(command) global LastCommand LastCommand = 'Change runtime' return hello() @app.route("/Delay", methods=['POST']) def Delay(): global DelayTime DelayTime = request.form['text'] print(DelayTime) global LastCommand LastCommand = 'Change Delay' return hello() @app.route("/Speed", methods=['POST']) def Speed(): global speed speed = request.form['text'] print(speed) ticker.sendline(speed) f = open('csv/settings.csv', 'r') CSV = csv.reader(f) next(CSV) for line in CSV: _, brightness = line f.close() f = open('csv/settings.csv', 'w+') f.write('speed,brightness\n') f.write(str(speed) + ',' + brightness) f.close() global LastCommand LastCommand = 'Change Speed' return hello() @app.route("/Brightness", methods=['POST']) def Brightness(): global brightness brightness = int(request.form['text'])-1 print(brightness) ticker.sendline(str(brightness)) f = open('csv/settings.csv', 'r') CSV = csv.reader(f) next(CSV) for line in CSV: speed, _ = line f.close() f = open('csv/settings.csv', 'w+') f.write('speed,brightness\n') f.write(str(speed) + ',' + str(brightness)) f.close() global LastCommand LastCommand = 'Change Brightness' return hello() @app.route("/DisplayText", methods=['POST']) def DisplayText(): text = request.form['text'] f = open('csv/scroll_text.csv', 'w+') f.write(text) f.close() ticker.sendline('K') ticker.sendline('T') return hello() @app.route("/SetNews", methods=['POST']) def SetNews(): text = request.form['text'] #args = ['q', 'sources', 'category', 'country'] args = ['q', 'category', 'country'] arg_dict = {} lst = text.split(',') try: for i, arg in enumerate(args): if len(lst[i])>0: arg_dict[arg] = lst[i] print(arg_dict) json.dump( arg_dict, open( "csv/news_settings.json", 'w+' )) print(settings) except Exception as e: #reset settings print(e) f = open( "csv/news_settings.json", 'w+' ) f.close() api_caller.sendline('R') return hello() @app.route("/SetWeather", methods=['POST']) def SetWeather(): text = request.form['text'] #args = ['q', 'sources', 'category', 'country'] f = open( "csv/weather_location.txt", 'w+' ) f.write(text) f.close() api_caller.sendline('R') return hello() @app.route("/DisplayImage", methods=['POST']) def DisplayImage(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return hello() fle = request.files['file'] if fle.filename == '': print('No file selected') return hello() if fle and allowed_file(fle.filename): filename = 'display_image' fle.save(os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)) global LastCommand LastCommand = 'Add a new logo file' ticker.sendline('K') ticker.sendline('I') return hello() return hello() @app.route("/DisplayGIF", methods=['POST']) def DisplayGIF(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return hello() fle = request.files['file'] if fle.filename == '': print('No file selected') return hello() if fle: print('in') filename = 'display_gif' fle.save(os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)) global LastCommand LastCommand = 'Add a new logo file' ticker.sendline('K') ticker.sendline('G') return hello() return hello() @app.route("/Ticker", methods=['POST']) def Ticker(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return hello() fle = request.files['file'] if fle.filename == '': print('No file selected') return hello() if fle and allowed_file(fle.filename): filename = secure_filename(fle.filename) fle.save(os.path.join(CSV_FOLDER, filename)) process_file(os.path.join(CSV_FOLDER, filename), filename) global LastCommand LastCommand = 'Change CSV file' return hello() return hello() @app.route("/AddLogo", methods=['POST']) def AddLogo(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return hello() fle = request.files['file'] if fle.filename == '': print('No file selected') return hello() if fle and allowed_file(fle.filename): filename = secure_filename(fle.filename) fle.save(os.path.join(LOGO_FOLDER, filename)) global LastCommand LastCommand = 'Add a new logo file' return hello() return hello() @app.route("/matrix", methods=['POST']) def matrix(): global LastCommand if "Run Stocks" in request.form: pass print('run display') #stock_ticker.runStockTicker(command, DelayTime, speedTime) #stock_ticker.displayMatrix() #os.system("sudo -E python3 test.py") # #child.sendline('sent from server') #process = Popen(["sudo", "-E", "python3", "stockTicker.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE) ticker.sendline('K') ticker.sendline('S') print('back in flask') LastCommand = 'Run display' elif "Run News" in request.form: print('run display') ticker.sendline('K') ticker.sendline('N') print('back in flask') LastCommand = 'Run display' elif "Run Weather" in request.form: ticker.sendline('K') ticker.sendline('W') print('back in flask') LastCommand = 'Run display' elif "Run Daily Weather" in request.form: ticker.sendline('K') ticker.sendline('D') print('back in flask') LastCommand = 'Run display' elif "Past NHL" in request.form: ticker.sendline('K') ticker.sendline('P') elif "Future NHL" in request.form: ticker.sendline('K') ticker.sendline('F') elif "Live NHL" in request.form: ticker.sendline('K') ticker.sendline('L') elif "Premier league table" in request.form: print('teams') ticker.sendline('K') ticker.sendline('t') elif "Stop Display" in request.form: print('run display') #ticker.kill() try: #stock_ticker.stopStockTicker() LastCommand = 'Stop display at next checkpoint' ticker.sendline('K') except: print("none running") elif "Shutdown the pi" in request.form: try: LastCommand = 'shutdown' os.system("sudo shutdown now") except: print("couldn't shutdown") return hello() if __name__ == "__main__": app.run(host='0.0.0.0', port=1024, debug=False) # the debuggger causes flickering #sudo ./demo -D1 final.ppm -t 50 -m 25 --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=256 --led-slowdown-gpio=4