#!/usr/bin/python3
import time
from flask import Flask, render_template, Response, send_from_directory, request
import random
import threading
import serial
import json
import drivers
import sys
import logging

app = Flask(__name__, static_url_path='', 
            static_folder='./static',
            template_folder='./templates')

logging.basicConfig(level=logging.DEBUG)

glob_txt = ""
glob_count = 0
glob_running = 0
glob_serial_open = 0

def wait_for_serial_close():
	global glob_serial_open
	while True:
		if glob_serial_open==0:
			break
		else:
			time.sleep(0.1)

def read_serial():
	global glob_txt, glob_count, glob_running, glob_serial_open
	ser = serial.Serial("/dev/ttyAMA0", 38400)
	glob_serial_open = 1
	while glob_running:
		glob_txt = ser.readline().decode('ascii').strip() # publishing the data stream to all instances via glob_txt
		#print(glob_txt)
		glob_count += 1 # announcing a new stream available
	ser.close()
	glob_serial_open = 0
	print("closed")
		
		

@app.route('/')
def root():
	return send_from_directory("static", "index.html")
	#return render_template('index.html')
	
@app.route('/read_config', methods = ['POST'])
def read_config():
	global glob_running
	was_running = glob_running
	glob_running = 0
	wait_for_serial_close()
	msg = drivers.read_rpict_config()
	if was_running:
		glob_running = 1
		threading.Thread(target=read_serial, daemon=True).start()
	return msg
	
@app.route('/write_config', methods = ['POST'])
def write_config():
	global glob_running
	was_running = glob_running
	glob_running = 0
	wait_for_serial_close()
	config = request.values.get('config')
	msg = drivers.write_rpict_config(config)
	if was_running:
		glob_running = 1
		threading.Thread(target=read_serial, daemon=True).start()
	return msg
	
@app.route('/stop_serial')
def stop_serial():
	print("stop asked")
	global glob_running
	glob_running = 0;
	return { "success": "true", "error": ""}

@app.route('/start_serial')
def start_serial():
	global glob_running
	print("start asked")
	(is_used, pid) = drivers.is_serial_port_used()
	if is_used:
		return { "success": "false", "error": "Serial Port already in use by pid %s." % pid } 
	
	if not glob_running:
		
		glob_running = 1
		threading.Thread(target=read_serial, daemon=True).start()
		#print('ok')
	return { "success": "true", "error": ""}


@app.route('/stream')
def stream():
	def eventStream():
		global glob_count, glob_running
		local_count = -1
		myid = str(int(random.random()*10)) # giving a random id to the instance
		print("#%s launched" % myid)
		while glob_running:
			# wait for source data to be available, then push it
			if glob_count != local_count:
				local_count = glob_count
				yield 'data: {} \n\n'.format(json.dumps({"running": glob_running, "stream": glob_txt}))
			time.sleep(0.1) # just to ease the loop a bit
			#print('ok')
				
		# Just tell the client serial is stopped
		yield 'retry:15000\ndata: {} \n\n'.format(json.dumps({"running": glob_running}))
		print(myid+" killed")	
	
	return Response(eventStream(), mimetype="text/event-stream")

	
if __name__ == "__main__":

	app.run(host="0.0.0.0", port=8000)
	
