
from subprocess import *
from threading import Thread
import time

class Modell(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.aktiv= True

        self.aktiv2 = True
    
    def stop(self):
        print("stop thread")
        self.aktiv = False
    
    def setFunktion(self, func, args=None, kwargs=None):
        self.func = func
        self.args = args or []
        self.kwargs = kwargs or {}
    
    def run(self): 
        print("start thread")
        #self.aktiv = True
        t = Thread(target=self.func, args=self.args, kwargs=self.kwargs)
        t.setDaemon(True)
        t.start()
        
        while self.aktiv:
            time.sleep(0.1)
    
    def counter(self):
        n = 0
        while self.aktiv2:
            print(n)
            time.sleep(0.1)
            n = n+1

            if not self.aktiv2:
                print("stop")
                break
    
    def stop2(self):
        self.aktiv2 = False
        #self.aktiv = False
    
    def test(self):
        command = ["bash", "meta/dist/Release/openvibe-designer.sh", "--play", "Projekte/OpenViBE_visual_BCI-master/openvibe_visual_bci/p300-visual-1-acquisition.xml", "--no-gui"]
        process = Popen(command, stdout=PIPE, universal_newlines=True)                  
        while self.aktiv2:
            output = process.stdout.readline()
            print(output.strip())
            x = output.find("Application terminated")
            y = output.find("Error")
            z = output.find("Initialization")
            if(x != -1):
                print("Training finished")
                process.terminate()
                break
            elif(y != -1 ):
                process.terminate()
                break
            if not self.aktiv:
                print("stop")
                break


m = Modell()
m.setFunktion(m.test)
m.start()
time.sleep(2)
m.stop()
m.join()
while True:
    pass




