def __init__(self, car, team, driver, country):

        #-------------------Settings of window-----------------#
        self.height = 728
        self.width = 1024

        #Window itself
        self.V_test = Toplevel()
        self.V_test.title('Test Drive')
        self.V_test.minsize(self.width, self.height)
        self.V_test.resizable(width=NO, height=NO)

        #Main canvas
        self.C_test = Canvas(self.V_test, width=self.width, height=self.height, bg='#f0f0f0')
        self.C_test.place(x=0, y=0)

        #Configuracion del carro, variables necesarias
        self.pwm = 0

        self.lf = 0
        self.lb = 0
        self.ld = 0
        self.li = 0
        self.le = 0
        self.dir_state = 0
        self.direccion = 0
        #-------------------Datos---------------------#
        self.car = car
        self.driver = driver
        self.country = country
        self.team = team
        # ------------------Instancia del carro-------------------#
        self.myCar = NodeMCU()
        self.myCar.start()
def Ventana_Test_Driver():
    global estado, luces,vel,GAS,fre
    estado=1
    luces=1
    GAS=0
    fre=1
    W = NodeMCU()
    W.start()
    
    root = tkinter.Tk()
    root.minsize(900,800)
    root.resizable(width=NO,height=NO)
    root.title('TEST DRIVER')
    boton = tkinter.Button(root,text="Volver a la Página principal")
    boton.place(x=270,y=710)
    img=PhotoImage(file='izquierda apagada.gif')
    logo=Label(root,image=img,width=50,height=50).place(x=125,y=20)
    img3=PhotoImage(file='derecha apagada.gif')
    logo3=Label(root,image=img3,width=50,height=50).place(x=225,y=20)
    img4=PhotoImage(file='luz apagada.png')
    logo4=Label(root,image=img4,width=50,height=50).place(x=25,y=20)
    img2=PhotoImage(file='table.png')
    logo2=Label(root,image=img2,width=400,height=225).place(x=0,y=125)
    velocidad = StringVar()
    Label(root,textvariable=velocidad,font=("Verdana", 40, "bold")).place(x=425,y=20)
    velocidad.set(str(GAS)+"Km/h")
    img8=PhotoImage(file='emergencia.png')
    intermitentes = tkinter.Button(root, image=img8,command=lambda :thread_intermitentes(), width=100, height=100)
    intermitentes.place(x=450,y=250)
    img9=PhotoImage(file='Luz.png')
    luz = tkinter.Button(root, image=img9,command=lambda :thread_luz(), width=150, height=100)
    luz.place(x=550,y=250)
    img10=PhotoImage(file='mov.png')
    movimiento = tkinter.Button(root, image=img10,command=lambda :thread_especial(), width=100, height=100)
    movimiento.place(x=700,y=250)

    #Pedales
    img5=PhotoImage(file='gas1.gif')
    botongas = tkinter.Button(root, image=img5,command=lambda :thread_gas(),  width=100, height=200)
    botongas.place(x=270,y=470)
    img6=PhotoImage(file='freno1.gif')
    botonfreno = tkinter.Button(root, image=img6,command=lambda :thread_freno(), width=150, height=100)
    botonfreno.place(x=75,y=550)

    #informacion piloto
    a=Label(root, text=("Escuderia:"),justify=LEFT, font=("Arial", 15, "bold"))
    a.place(x=450,y=400)
    b=Label(root, text=("Piloto:"),justify=LEFT, font=("Arial", 15, "bold"))
    b.place(x=450,y=450)
    c=Label(root, text=("Nacionalidad:"),justify=LEFT, font=("Arial", 15, "bold"))
    c.place(x=450,y=500)

    #Bateria
    bat=PhotoImage(file='100.png')
    bate=Label(root,image=bat,width=100,height=100).place(x=780,y=0)
    def bat():
        bat=PhotoImage(file='100.png')
        bate=Label(root,image=bat,width=100,height=100).place(x=780,y=0)
        time.sleep(600)
        bat=PhotoImage(file='80.png')
        bate=Label(root,image=bat,width=100,height=100).place(x=780,y=0)
        time.sleep(600)
        bat=PhotoImage(file='60.png')
        bate=Label(root,image=bat,width=100,height=100).place(x=780,y=0)
        time.sleep(600)
        bat=PhotoImage(file='40.png')
        bate=Label(root,image=bat,width=100,height=100).place(x=780,y=0)
        time.sleep(600)
        bat=PhotoImage(file='20.png')
        bate=Label(root,image=bat,width=100,height=100).place(x=780,y=0)
        time.sleep(600)
    def thread_bateria():
        p=threading.Thread(target=bat)
        p.start()

        
    #sensor de luz
    sen=PhotoImage(file='com.png')
    sensor=Label(root,image=sen,width=100,height=100).place(x=780,y=125)


    def seleccionar():
        if (opcion.get()==3):
            thread_derecha()

        if (opcion.get()==1):
            thread_izquierda()  

    opcion = IntVar()

    uno=PhotoImage(file='izquierda encendida.gif')
    dos=PhotoImage(file='derecha encendida.gif')
    Radiobutton(root, image=uno, variable=opcion, 
        value=1, command=seleccionar).place(x=450,y=150)
    Radiobutton(root, text="OFF", variable=opcion, 
        value=2, command=seleccionar).place(x=535,y=167)
    Radiobutton(root,image=dos, variable=opcion,   
        value=3, command=seleccionar).place(x=600,y=150)

    monitor = Label(root)
    monitor.pack()   
    
    
    def thread_especial():
        f=threading.Thread(target=send('zigzag;'))
        f.start()
    def thread_der():
        f=threading.Thread(target=send('derecha;'))
        f.start()
    def thread_izq():
        f=threading.Thread(target=send('izquierda;'))
        f.start()
    def thread_detener():
        f=threading.Thread(target=send('detener;'))
        f.start()
    def thread_avanzar():
        f=threading.Thread(target=send('avanzar;'))
        f.start()
        
    def izq():
        global img
        x=0
        send('dir-izq;')
        while((opcion.get())==1):
            img=PhotoImage(file='izquierda encendida.gif')
            logo=Label(root,image=img,width=50,height=50).place(x=125,y=20)
            time.sleep(0.5)
            img=PhotoImage(file='izquierda apagada.gif')
            logo=Label(root,image=img,width=50,height=50).place(x=125,y=20)
            time.sleep(0.5)
            x+=1
        
    def thread_izquierda():
        p=threading.Thread(target=izq)
        p.start()

    def der():
        global img3
        x=0
        send('dir-der;')
        while(opcion.get()==3):
            img3=PhotoImage(file='derecha encendida.gif')
            logo3=Label(root,image=img3,width=50,height=50).place(x=225,y=20)
            time.sleep(0.5)
            img3=PhotoImage(file='derecha apagada.gif')
            logo3=Label(root,image=img3,width=50,height=50).place(x=225,y=20)
            time.sleep(0.5)
            x+=1

    
    def thread_derecha():
        p=threading.Thread(target=der)
        p.start()

    def luz():
        global img4,luces
        luces=luces+1
        
        while(luces%2==0):
            send('luz;')
            img4=PhotoImage(file='luz encendida.png')
            logo4=Label(root,image=img4,width=50,height=50).place(x=25,y=20)
            time.sleep(0.5)
        send('luz-off')      
        img4=PhotoImage(file='luz apagada.png')
        logo4=Label(root,image=img4,width=50,height=50).place(x=25,y=20)

            
    def thread_luz():
        p=threading.Thread(target=luz)
        p.start()
        f=threading.Thread(target=send('luz'))
        f.start()

    def intermitente():
        global img3
        global img
        x=0
        while(opcion.get()==2):
            send('parpadear;')
            img3=PhotoImage(file='derecha encendida.gif')
            logo3=Label(root,image=img3,width=50,height=50).place(x=225,y=20)
            img=PhotoImage(file='izquierda encendida.gif')
            logo=Label(root,image=img,width=50,height=50).place(x=125,y=20)
            time.sleep(0.5)
            img3=PhotoImage(file='derecha apagada.gif')
            logo3=Label(root,image=img3,width=50,height=50).place(x=225,y=20)
            img=PhotoImage(file='izquierda apagada.gif')
            logo=Label(root,image=img,width=50,height=50).place(x=125,y=20)
            time.sleep(0.5)
            x+=1
        
    def estado_emergencia():
        global img3
        global img
        global estado
        estado=estado+1

        

        while((estado%2==0)and (opcion.get()==2) ):
            send('parpadear;')
            img3=PhotoImage(file='derecha encendida.gif')
            logo3=Label(root,image=img3,width=50,height=50).place(x=225,y=20)
            img=PhotoImage(file='izquierda encendida.gif')
            logo=Label(root,image=img,width=50,height=50).place(x=125,y=20)
            time.sleep(0.5)
            img3=PhotoImage(file='derecha apagada.gif')
            logo3=Label(root,image=img3,width=50,height=50).place(x=225,y=20)
            img=PhotoImage(file='izquierda apagada.gif')
            logo=Label(root,image=img,width=50,height=50).place(x=125,y=20)
            time.sleep(0.5)

        img3=PhotoImage(file='derecha apagada.gif')
        logo3=Label(root,image=img3,width=50,height=50).place(x=225,y=20)
        img=PhotoImage(file='izquierda apagada.gif')
        logo=Label(root,image=img,width=50,height=50).place(x=125,y=20)
            
            
    def thread_intermitentes():
        d=threading.Thread(target=estado_emergencia)
        d.start()
    def volante_der(event):
        global img2
        thread_der()
        img2=PhotoImage(file='table_der.png')
        logo2=Label(root,image=img2,width=400,height=225).place(x=0,y=125)

    def volante_izq(event):
        global img2
        thread_izq()
        img2=PhotoImage(file='table_izq.png')
        logo2=Label(root,image=img2,width=400,height=225).place(x=0,y=125)
        
    def volante(event):
        global img2
        thread_detener()
        img2=PhotoImage(file='table.png')
        logo2=Label(root,image=img2,width=400,height=225).place(x=0,y=125)
    def gas():
        global GAS
        x=0
        thread_avanzar()
        while(x<6):
            GAS=GAS+20
            velocidad.set(str(GAS)+"Km/h")
            time.sleep(0.25)
            x+=1
    def thread_gas():
        d=threading.Thread(target=gas)
        d.start()

        
    def freno():
        global GAS,fre
        fre=+1
        if(fre%2==0):
            while(GAS<61):
                velocidad.set(str(GAS)+"Km/h")
                GAS=GAS+20
                time.sleep(0.25)
                print(GAS)
            
        
        else:
            while(GAS>-1):
                velocidad.set(str(GAS)+"Km/h")
                GAS=GAS-20
                time.sleep(0.25)
                print(GAS)
        
            GAS=GAS+20
    def thread_freno():
        d=threading.Thread(target=freno)
        d.start()
        f=threading.Thread(target=send('atras'))
        f.start()
    def send(comando):
        x=0
        while(x<1):
            mns=str(comando)
            W.send(mns)
            print("Envianto mensaje:",comando)
            x+=1
            
    #Teclado volante
    root.bind('<a>', volante_der)
    root.bind('<d>', volante_izq)
    root.bind('<w>',thread_gas)
    root.bind('<s>',volante)

    root.mainloop() 
L_Titulo = Label(C_root,
                 text="Respuesta Mensaje",
                 font=('Agency FB', 14),
                 bg='#131313',
                 fg='white')
L_Titulo.place(x=550, y=10)

SentCarScrolledTxt = tkscrolled.ScrolledText(C_root, height=10, width=45)
SentCarScrolledTxt.place(x=50, y=50)

RevCarScrolledTxt = tkscrolled.ScrolledText(C_root, height=10, width=45)
RevCarScrolledTxt.place(x=460, y=50)

#           _____________________________________
#__________/Creando el cliente para NodeMCU
myCar = NodeMCU()
myCar.start()


def get_log():
    """
    Hilo que actualiza los Text cada vez que se agrega un nuevo mensaje al log de myCar
    """
    indice = 0
    # Variable del carro que mantiene el hilo de escribir.
    while (myCar.loop):
        while (indice < len(myCar.log)):
            mnsSend = "[{0}] cmd: {1}\n".format(indice, myCar.log[indice][0])
            SentCarScrolledTxt.insert(END, mnsSend)
            SentCarScrolledTxt.see("end")
class Test_Drive:

    def __init__(self, car, team, driver, country):

        #-------------------Settings of window-----------------#
        self.height = 728
        self.width = 1024

        #Window itself
        self.V_test = Toplevel()
        self.V_test.title('Test Drive')
        self.V_test.minsize(self.width, self.height)
        self.V_test.resizable(width=NO, height=NO)

        #Main canvas
        self.C_test = Canvas(self.V_test, width=self.width, height=self.height, bg='#f0f0f0')
        self.C_test.place(x=0, y=0)

        #Configuracion del carro, variables necesarias
        self.pwm = 0

        self.lf = 0
        self.lb = 0
        self.ld = 0
        self.li = 0
        self.le = 0
        self.dir_state = 0
        self.direccion = 0
        #-------------------Datos---------------------#
        self.car = car
        self.driver = driver
        self.country = country
        self.team = team
        # ------------------Instancia del carro-------------------#
        self.myCar = NodeMCU()
        self.myCar.start()
    # Funcion que carga las imagenes a Tkinter

    def cargarImagen(self, nombre):
        ruta = os.path.join("resources", nombre)
        imagen = PhotoImage(file=ruta)
        return imagen
    #Funcion que dibuja en la ventana
    def __draw__(self):
        #Configuraciones del carro
        aceleracion = 100
        #Configuracion del velocimetro
        count = StringVar()
        count.set(0)
        #Configuracion del medidor de bateria
        battery_level = StringVar()
        battery_level.set(0)
        color = 'black'

        #Funcion que aumenta la velocidad
        def acelera(event): #YA ENVIA COMANDOS

            if self.pwm == 1000:
                print("velocidad maxima")
            else:
                self.pwm += aceleracion
                speed.config(text=str(self.pwm))

                msg = 'pwm: ' + str(self.pwm) + ' ;'
                self.myCar.send(msg)
                cambiaColor()
                print('comando enviado: ', msg)
        #Funcion que disminuye la velocidad y hace reversa
        def reverse(event): #YA ENVIA COMANDOS

            if self.pwm == -800:
                print("reversa maxima")
            else:

                self.pwm-=aceleracion
                speed.config(text=str(self.pwm))
                msg = 'pwm: ' + str(self.pwm) + ' ;'
                self.myCar.send(msg)
                print('comando enviado: ', msg)
                cambiaColor()
        #Funcion que enciende direcionales derechas
        def dir_lights_right(): #YA ENVIA COMANDOS

            if self.dir_state == -1:
                self.dir_state = 0
                msg = 'lr: 0;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)


            else:

                self.dir_state = 1
                msg = 'lr:1;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)
                time.sleep(0.5)

                self.dir_state = 0
                msg = 'lr:0;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)
                time.sleep(0.5)

                self.dir_state = 1
                msg = 'lr:1;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)
                time.sleep(0.5)

                self.dir_state = 0
                msg = 'lr:0;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)

                time.sleep(0.5)

                #print('done')
        #Funcion que enciende direccionales izquierdas
        def dir_lights_left(): #YA ENVIA COMANDOS

            if self.dir_state == 1:
                self.dir_state = 0
            # print('comando direccionales: ',self.dir_state)

            else:

                self.dir_state = -1
                msg = 'll:1;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)
                time.sleep(0.5)

                self.dir_state = 0
                msg = 'll:0;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)
                time.sleep(0.5)

                self.dir_state = -1
                msg = 'll:1;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)
                time.sleep(0.5)

                self.dir_state = 0
                msg = 'll:0;'
                self.myCar.send(msg)
                #print('Comando enviado: ', msg)



                time.sleep(0.5)


                #print('done')
        #Funcion que gira a la derecha
        def gira_derecha():
            if self.direccion == 0:
                self.direccion = 1
                dir_lights_right()
                msg = 'dir:1;'
                self.myCar.send(msg)
                print('Comando giro enviado: ', msg)
                time.sleep(2)
            else:
                self.direccion=0
                msg = 'dir:0;'
                self.myCar.send(msg)
                print('Comando giro enviado: ', msg)
        #Funcion que gira a la izquierda
        def gira_izquierda():
            if self.direccion == 0:
                self.direccion = -1
                dir_lights_left()
                msg = 'dir:-1;'
                self.myCar.send(msg)
                print('Comando giro enviado: ', msg)
                time.sleep(2)
            else:
                self.direccion = 0
                msg = 'dir:0;'
                self.myCar.send(msg)
                print('Comando giro enviado: ', msg)
            #msg = 'dir:0;'
            #self.myCar.send(msg)
            #print('Comando giro enviado: ', msg)
        #Funcion que frena el carro
        def brake(event):
            if self.pwm > 0:
                self.pwm -= 50
                speed.config(text=str(self.pwm))
                print(count)
                msg = 'pwm: ' + str(self.pwm)+ ' ;'
                self.myCar.send(msg)
                print('comando enviado: ', msg)
                cambiaColor()
            elif self.pwm <0:
                self.pwm +=50
                speed.config(text=str(self.pwm))
                self.myCar.send(msg)
                print('comando enviado: ', msg)
                cambiaColor()

        #===================Celebracion==============#

        def celebracion(event):
           self.myCar.send('celebra:1;')
           print('celebracion')
           #--------------------Boton Update bateria---------------------#
        def especial(event):
            self.myCar.send('especial:1;')
            print('mov. especial')
        #Funcion que enciende luces frontales
        def enciende_frontales(event):
            if self.lf == 0:
                self.myCar.send('lf:1;')
                print('Comando enviado: ', 'lf:1;')
                self.lf = 1
            else:
                self.myCar.send('lf:0;')
                print('Comando enviado: ', 'lf:0;')
                self.lf = 0
        #Funicion que enciende luces traseras
        def enciende_traseras(event):
            if self.lb == 0:
                self.myCar.send('lb:1;')
                print('Comando enviado: ', 'lb:1;')
                self.lb = 1
            else:
                self.myCar.send('lb:0;')
                print('Comando enviado: ', 'lb:0;')
                self.lb = 0
        #Funcion que enciende luces de emergencia
        def enciende_emergencia(event):
            if self.le == 0:
                self.myCar.send('le:1;')
                self.le = 1
            else:
                self.myCar.send('le:0;')
                self.le = 0
        #Funcion que lee la bateria

        def read_battery():

            while True:
                level = self.myCar.send("sense;")
                #print(self.myCar.read())
                time.sleep(2)
                bat = self.myCar.read()
                battery_level.set(bat)

        marcaAuto = Label(self.C_test, text='Model: ' + str(self.car), font=("Arial ", 20), justify=CENTER)
        marcaAuto.place(x=0,y=10)
        #Etiqueta conductor.
        Nombre = Label(self.C_test, text ="Driver: " + str(self.driver), font=("Arial", 20), width = 15, justify= LEFT)
        Nombre.place(x=-25, y= 50)
        #Etiqueta pais
        Country = Label(self.C_test, text= str(self.country), font=('Arial', 20), justify=CENTER)
        Country.place(x=220, y= 50)
        #Etiqueta del equipo
        Team = Label(self.C_test, text ='Team: ' + str(self.team), font=('Arial', 20), justify=CENTER)
        Team.place(x=0, y =90)


        #---|------------------------|
        #   |  COMANDOS DEL CARRO    |
        #---|------------------------|

        #---------------Volante con medidor velocidad----------------#
        steer_image = self.cargarImagen('bg.png')
        steer = Label(self.C_test, image = steer_image)
        steer.image = steer_image
        steer.place(x=0,y=450)


        #-----------------Indicador velocidad------------------------#
        speed = Label(self.C_test, text='0', font=('Unispace', 45), fg=color)
        speed.place(x=490,y=570)

        #--------------------Indicador de bateria--------------------#
        mark_battery = Label(self.C_test, text=' Battery Level: ', font=('Arial', 20))
        bat_level = Label(self.C_test, textvariable= (battery_level), font=('Unispace', 20))
        bat_level.place(x=940,y=0)
        mark_battery.place(x=750,y=0)

        #------------------Boton ayuda--------------------------------#
        def ayuda():
            Ayuda = Canvas(self.V_test, width = 400, height=600, bg='white')
            Ayuda.place(x=300, y= 50)

            Ayuda.create_text(200,20,text = 'How to drive ?',font=('Unispace', 20))

            Ayuda.create_text(200, 80, text='Movement:', font=('Unispace', 14))
            Ayuda.create_text(120, 140, text= ' Forward: W\n Reverse: s\n Brake: Space Bar', font=('Unispace', 12))

            Ayuda.create_text(200, 200,text= 'Direction:', font=('Unispace', 14))
            Ayuda.create_text(140,250, text='Right: Right arrow\nLeft: Left arrow', font=('Unispace',12))

            Ayuda.create_text(200, 300, text='Turn lights,¡Keep Shift down!:', font=('Unispace', 14))
            Ayuda.create_text(140,350, text='Left: Left arrow \n Right: Right arrow', font=("Unispace", 12))

            Ayuda.create_text(200, 450, text='Other lights: ', font=('Unispace', 14))
            Ayuda.create_text(140, 500, text=' Front: press l \n Back: press b \n Emergency: press e \n All: press a', font=("Unispace", 12))


            def exit():
                Ayuda.destroy()
            exit_button = Button(Ayuda, bitmap = 'error', command=exit)
            exit_button.place(x=380,y=580)
        botton_help = Button(self.C_test, bitmap='question', relief = FLAT, command= ayuda)
        botton_help.place(x=990, y=695)

        #Funcion que cambia el color del indicador
        def cambiaColor():

            if self.pwm == 0:
                speed.config(fg = 'green')
            elif self.pwm >= 10 and self.pwm <= 490:
                speed.config(fg= 'blue')
            elif self.pwm >= 500:
                speed.config(fg='red')
            elif self.pwm <= -10 and self.pwm >= -490:
                speed.config(fg = 'black')
            elif self.pwm <=-500:
                speed.config(fg='red')

        #-----------------Threads necesarios--------------------------#
        #Threads para encender y apagar direccionales:
        def thread_dir_izq(event):
            dir_izq_thread = Thread(target= dir_lights_left, args=())
            dir_izq_thread.start()
        def thread_dir_der(event):

            dir_der_thread = Thread(target=dir_lights_right, args=())
            dir_der_thread.start()
        #Threads para girar, y encender las direccionales
        def thread_turn_right(event):
            turn_right = Thread(target=gira_derecha, args=())
            turn_right.start()
        def thread_turn_left(event):
            turn_left = Thread(target = gira_izquierda,args=())
            turn_left.start()

        thread = Thread(target=read_battery, args=())
        thread.start()
        #---------------------------Binding Events--------------------#
        self.V_test.bind("w", acelera) ##Acelerador, con tecla W
        self.V_test.bind("s", reverse) ##Freno, con tecla S
        self.V_test.bind("<Right>", thread_turn_right)
        self.V_test.bind("<Left>", thread_turn_left)
        self.V_test.bind("<space>", brake)
        self.V_test.bind("<Shift-Right>", thread_dir_der)
        self.V_test.bind("<Shift-Left>", thread_dir_izq)
        self.V_test.bind("l", enciende_frontales)
        self.V_test.bind('b', enciende_traseras)
        self.V_test.bind('e', enciende_emergencia)
        self.V_test.bind('c', celebracion)
        self.V_test.bind('z',especial)

        self.V_test.mainloop()
    def test_drive():
        #Esconder ventana principal
        main.withdraw()
        #Ventana de testeo del carro y sus atributos
        test = Toplevel()
        test.title("Driving Test")
        test.minsize(450, 625)
        test.resizable(width=NO, height=NO)

        C_test = Canvas(test, width=450, height=625, bg="white")
        C_test.place(x=0, y=0)

        #Fondo Test Drive
        Background = loadImg("T.1.png")
        Game_Background = Label(C_test, bg="white")
        Game_Background.place(x=0, y=0)
        Game_Background.config(image=Background)
        Game_Background.lower()

        #Creando el cliente para NodeMCU
        myCar = NodeMCU()
        myCar.start()

        def get_log():
            #Hilo que actualiza los Text cada vez que se agrega un nuevo mensaje al log de myCar
            indice = 0
            while (myCar.loop):
                while (indice < len(myCar.log)):
                    mnsSend = "[{0}] cmd: {1}\n".format(
                        indice, myCar.log[indice][0])
                    SentCarScrolledTxt.insert(END, mnsSend)
                    SentCarScrolledTxt.see("end")

                    mnsRecv = "[{0}] result: {1}\n".format(
                        indice, myCar.log[indice][1])
                    RevCarScrolledTxt.insert(END, mnsRecv)
                    RevCarScrolledTxt.see('end')

                    indice += 1
                time.sleep(0.200)

        def lights(event):
            global Lfront, Lback, Lleft, Lright
            if event.char == "f":
                if Lfront == False:
                    mns = "lf:1;"
                    myCar.send(mns)
                    Lfront = True
                else:
                    mns = "lf:0;"
                    myCar.send(mns)
                    Lfront = False

            if event.char == "b":
                if Lback == False:
                    mns = "lb:1;"
                    myCar.send(mns)
                    Lback = True
                else:
                    mns = "lb:0;"
                    myCar.send(mns)
                    Lback = False

            if event.char == "l":
                if Lleft == False:
                    mns = "ll:1;"
                    myCar.send(mns)
                    Lleft = True
                else:
                    mns = "ll:0;"
                    myCar.send(mns)
                    Lleft = False

            if event.char == "r":
                if Lright == False:
                    mns = "lr:1;"
                    myCar.send(mns)
                    Lright = True
                else:
                    mns = "lr:0;"
                    myCar.send(mns)
                    Lright = False

        def move_forward(event):
            global Forward, Back
            Back = -700
            if Forward < 1023:
                Forward += 1
                print(Forward)
                mns = "pwm:" + str(Forward) + ";"
                myCar.send(mns)
                time.sleep(0.01)
            else:
                Forward = 1023
                print(Forward)
                mns = "pwm:" + str(Forward) + ";"
                myCar.send(mns)
                time.sleep(0.01)

        def move_back(event):
            global Forward, Back
            Forward = 700
            if Back > -1023:
                Back -= 1
                print(Back)
                mns = "pwm:" + str(Back) + ";"
                myCar.send(mns)
                time.sleep(0.01)

            else:
                Back = -1023
                print(Back)
                mns = "pwm:" + str(Back) + ";"
                myCar.send(mns)
                time.sleep(0.01)

        def stop(event):
            global Forward, Back
            Forward = 700
            Back = -700
            velocidad = 0
            mns = "pwm:" + str(velocidad) + ";"
            myCar.send(mns)

        def move_left(event):
            mns = "dir:-1;"
            myCar.send(mns)

        def move_right(event):
            mns = "dir:1;"
            myCar.send(mns)

        def move_direct(event):
            mns = "dir:0;"
            myCar.send(mns)

        def send(event):
            mns = str(E_Command.get())
            if (len(mns) > 0 and mns[-1] == ";"):
                E_Command.delete(0, 'end')
                myCar.send(mns)
            else:
                messagebox.showwarning(
                    "Error del mensaje",
                    "Mensaje sin caracter de finalización (';')")

        def back():
            test.destroy()
            main.deiconify()

        Btn_back = Button(test,
                          text="Back",
                          command=back,
                          bg="#cb3234",
                          fg="white")
        Btn_back.place(x=10, y=10)

        Start = loadImg("S1.1.png")
        Btn_start = Button(C_test,
                           command=test_drive,
                           fg="black",
                           bg="light blue")
        Btn_start.place(x=380, y=555)
        Btn_start.config(image=Start)

        test.bind("<Up>", move_forward)
        test.bind("<Down>", move_back)
        test.bind("p", stop)
        test.bind("<Left>", move_left)
        test.bind("<Right>", move_right)
        test.bind("d", move_direct)
        test.bind("<Key>", lights)

        p = Thread(target=get_log).start()
        main.mainloop()
def windrives(nombreG):
    """
Gabriel Solano
Haansel Hampton
función: Ventana test

    """

    global adelante, atras, leftlight, rigthlight, frontlight, backlight, dirR, dirL, dirN, pwm, stop, nothing, Bpwm, pressing, sense, Blevel, blevel, lightoff, config_active
    leftlight = False
    rigthlight = False
    frontlight = False
    backlight = True
    dirN = True
    dirR = False
    dirL = False
    stop = True
    pwm_back = False
    pressing = False
    belvel = 0
    pwm = 0
    Blevel = 0
    lightfpress = False
    adelante = False
    atras = False
    config_active = False

    winini.withdraw()
    windrive = Toplevel()
    windrive.title("Text drive")
    windrive.minsize(1000, 650)
    windrive.resizable(0, 0)

    canvas = Canvas(windrive, width=1000, height=650, bg="white")
    canvas.place(x=0, y=0)

    bg1 = cargarImg('test.png')  #bg=background
    dirR = cargarImg("direccional1.png")
    dirL = cargarImg("direccional2.png")
    delante = cargarImg("direccional3.png")
    atras = cargarImg("direccional4.png")

    canvas.create_image(0, 0, image=bg1, anchor=NW)
    LabelNomb = Label(canvas,
                      text=nombreG,
                      font=('Arial', 15),
                      bg='white',
                      fg='black')
    LabelNomb.place(x=0, y=10)

    textura = cargarImg('textura.png')
    panel = cargarImg('PANEL.png')
    off = cargarImg("off.png")
    on = cargarImg("on.png")
    canvas.create_image(450, 324, image=textura, anchor=NW)
    canvas.create_image(0, 325, image=panel, anchor=NW)
    canvas.create_image(660,
                        400,
                        image=dirR,
                        anchor=NW,
                        tags=("dirR1", "direccion"),
                        state=HIDDEN)
    canvas.create_image(660,
                        400,
                        image=dirL,
                        anchor=NW,
                        tags=("dirL1", "direccion"),
                        state=HIDDEN)
    canvas.create_image(660,
                        400,
                        image=delante,
                        anchor=NW,
                        tags=("delante1", "direccion"),
                        state=HIDDEN)
    canvas.create_image(660,
                        400,
                        image=atras,
                        anchor=NW,
                        tags=("atras11", "direccion"),
                        state=HIDDEN)

    canvas.create_image(760,
                        470,
                        image=off,
                        anchor=NW,
                        tags=("offF", "luces"),
                        state=NORMAL)
    canvas.create_image(760,
                        470,
                        image=on,
                        anchor=NW,
                        tags=("onF", "luces"),
                        state=HIDDEN)

    canvas.create_image(760,
                        570,
                        image=off,
                        anchor=NW,
                        tags=("offB", "luces"),
                        state=NORMAL)
    canvas.create_image(760,
                        570,
                        image=on,
                        anchor=NW,
                        tags=("onB", "luces"),
                        state=HIDDEN)

    canvas.create_image(700,
                        520,
                        image=on,
                        anchor=NW,
                        tags=("onI", "luces"),
                        state=HIDDEN)
    canvas.create_image(700,
                        520,
                        image=off,
                        anchor=NW,
                        tags=("offI", "luces"),
                        state=NORMAL)

    canvas.create_image(800,
                        520,
                        image=on,
                        anchor=NW,
                        tags=("onD", "luces"),
                        state=HIDDEN)
    canvas.create_image(800,
                        520,
                        image=off,
                        anchor=NW,
                        tags=("offD", "luces"),
                        state=NORMAL)

    #_________________________________________________________
    #____________________________________/Cliente para el NodeCMU
    myCar = NodeMCU()
    myCar.start()

    #_________________
    #__/Envía los mensajes
    def send(mns):
        """
Gabriel Solano
Haansel Hampton
función: Envía los mensajes y comunica con el wificlient

    """
        if (len(mns) > 0 and mns[-1] == ";"):
            myCar.send(mns)
        else:
            return

    #_____________________________________________

    #________/Depende de la tecla presionada realiza una acción

    def bind_press(event):
        """
Gabriel Solano
Haansel Hampton
función: presiona boton y obtiene el valor

        """
        global dirR, dirL, dirN, Bpwm, pwm, adelante, atras, stop, backlight, frontlight, leftlight, rigthlight
        key = event.char
        if key == "a":
            if dirR:
                return
            else:
                if dirL:
                    dirN = False
                    dirL = True
                else:
                    dirN = False
                    dirL = True
                    canvas.itemconfig("dirR1", state=HIDDEN)
                    canvas.itemconfig("dirL1", state=NORMAL)
                    canvas.itemconfig("atras11", state=HIDDEN)
                    canvas.itemconfig("delante1", state=HIDDEN)
                    send("dir:-1;")
        elif key == "d":
            if dirL:
                return
            else:
                if dirR:
                    dirN = False
                    dirR = True
                else:
                    dirN = False
                    dirR = True
                    canvas.itemconfig("dirR1", state=NORMAL)
                    canvas.itemconfig("dirL1", state=HIDDEN)
                    canvas.itemconfig("atras11", state=HIDDEN)
                    canvas.itemconfig("delante1", state=HDDEN)
                    send("dir:1;")
        elif key == "w":
            if atras:
                return
            else:
                if adelante:
                    adelante = True
                    stop = False
                else:
                    adelante = True
                    canvas.itemconfig("dirR1", state=HIDDEN)
                    canvas.itemconfig("dirL1", state=HIDDEN)
                    canvas.itemconfig("atras11", state=HIDDEN)
                    canvas.itemconfig("delante1", state=NORMAL)
                    send("pwm:1000;")
        elif key == "s":
            if adelante:
                return
            else:
                if atras:
                    atras = True
                    stop = False
                else:
                    atras = True
                    stop = False
                    canvas.itemconfig("dirR1", state=HIDDEN)
                    canvas.itemconfig("dirL1", state=HIDDEN)
                    canvas.itemconfig("atras11", state=NORMAL)
                    canvas.itemconfig("delante1", state=HIDDEN)
                    send("pwm:-1023;")
        elif key == "f":
            if backlight:
                return
            else:
                if frontlight:
                    frontlight = True
                    backlight = False
                else:
                    frontlight = True
                    backlight = False
                    canvas.itemconfig("offF", state=HIDDEN)
                    canvas.itemconfig("onF", state=NORMAL)
                    send("lf:1;")
        elif key == "b":
            if backlight:
                return
            else:
                if frontlight:
                    frontlight = False
                    backlight = True
                else:
                    frontlight = False
                    backlight = True
                    canvas.itemconfig("offB", state=HIDDEN)
                    canvas.itemconfig("onB", state=NORMAL)
                    send("lb:1;")
        elif key == "q":
            if rigthlight:
                return
            else:
                if leftlight:
                    rigthlight = False
                    leftlight = True
                else:
                    rigthlight = False
                    leftlight = True
                    canvas.itemconfig("offI", state=HIDDEN)
                    canvas.itemconfig("onI", state=NORMAL)
                    send("ll:1;")
        elif key == "e":
            if leftlight:
                return
            else:
                if rigthlight:
                    rigthlight = True
                    leftlight = False
                else:
                    rigthlight = True
                    leftlight = False
                    canvas.itemconfig("offD", state=HIDDEN)
                    canvas.itemconfig("onD", state=NORMAL)
                    send("lr:1;")

    #_______________________________
    #________/Depende de la tecla que suelte
    def bind_release(event):

        global dirR, dirN, dirL, pressing, adelante, atras, frontlight, backlight, leftlight, rightlight
        key = event.char
        if key in ["a", "d"]:
            if dirR and dirL:
                return
            else:
                dirN = True
                dirR = False
                dirL = False
                canvas.itemconfig("dirR1", state=HIDDEN)
                canvas.itemconfig("dirL1", state=HIDDEN)
                canvas.itemconfig("atras", state=HIDDEN)
                canvas.itemconfig("adelante", state=HIDDEN)
                send("dir:0;")
        elif key == "s":
            if atras:
                atras = False
                canvas.itemconfig("dirR1", state=HIDDEN)
                canvas.itemconfig("dirL1", state=HIDDEN)
                canvas.itemconfig("atras11", state=HIDDEN)
                canvas.itemconfig("delante1", state=HIDDEN)
                send("pwm:0;")
        elif key == "w":
            if adelante:
                adelante = False
                canvas.itemconfig("dirR1", state=HIDDEN)
                canvas.itemconfig("dirL1", state=HIDDEN)
                canvas.itemconfig("atras", state=HIDDEN)
                canvas.itemconfig("adelante", state=HIDDEN)
                send("pwm:0;")
                return
        elif key == "f":
            if frontlight:
                frontlight = False
                canvas.itemconfig("onF", state=HIDDEN)
                canvas.itemconfig("offF", state=NORMAL)
                send("lf:0;")
        elif key == "b":
            if backlight:
                backlight = False
                canvas.itemconfig("onB", state=HIDDEN)
                canvas.itemconfig("offB", state=NORMAL)
                send("lb:0;")
        elif key == "q":
            if leftlight:
                leftlight = False
                canvas.itemconfig("onI", state=HIDDEN)
                canvas.itemconfig("offI", state=NORMAL)
                send("ll:0;")
        elif key == "b":
            if rightlight:
                rigthlight = False
                canvas.itemconfig("onD", state=HIDDEN)
                canvas.itemconfig("offD", state=NORMAL)
                send("lr:0;")

    def config(variable):
        global config_active
        if variable == "TurnTime:1":
            if not config_active:
                config_active = True
                send("TurnTime:1;")
                print("started")
                time.sleep(20)
                print("ended")
                config_active = False
        elif variable == "TurnTime:-1":
            if not config_active:
                config_active = True
                send("TurnTime:-1;")
                print("started")
                time.sleep(20)
                print("ended")
                config_active = False
        elif variable == "Infinite":
            if not config_active:
                config_active = True
                send("Infinite;")
                print("started")
                time.sleep(20)
                print("ended")
                config_active = False
        elif variable == "Especial":
            if not config_active:
                config_active = True
                send("Especial;")
                print("started")
                time.sleep(20)
                print("ended")
                config_active = False

    ###________________________________________________-
    #_______________________/Se agrega el .bind para cuando se presiona la tecla y cuando es liberada
    windrive.bind("<KeyPress>", bind_press)

    windrive.bind("<KeyRelease>", bind_release)

    #___________________________________
    #____________________/Fin nodemcu

    Btn_command1 = Button(windrive,
                          text="TurnTime \n derecha",
                          command=lambda: config("TurnTime:1"),
                          fg='white',
                          bg='black')
    Btn_command1.place(x=50, y=580)

    Btn_command11 = Button(windrive,
                           text="TurnTime \n izquierda",
                           command=lambda: config("TurnTime:-1"),
                           fg='white',
                           bg='black')
    Btn_command11.place(x=150, y=580)

    Btn_command2 = Button(windrive,
                          text="Infinite",
                          command=lambda: config("Infinite"),
                          fg='white',
                          bg='black')
    Btn_command2.place(x=385, y=590)

    bmovimientoespecial = Button(windrive,
                                 text="Especial",
                                 command=lambda: config("Especial"),
                                 bg="black",
                                 activebackground="white",
                                 fg="white",
                                 font="Century")
    bmovimientoespecial.place(x=485, y=590)

    def out():
        windrive.destroy()
        winini.deiconify()

    botonatras = Button(windrive,
                        text="Atrás",
                        command=out,
                        bg="black",
                        activebackground="white",
                        fg="white",
                        font="Century")
    botonatras.place(x=875, y=615)

    windrive.mainloop()
Beispiel #7
0
def Tablero(pilot):
    """Instito Tecnológico de Costa Rica
Área Académica de Ingeniería en Computadores
Taller de Programación
Proyecto 3
Versión 1.0
Lenguaje: Python 3.7.3
----------------------------------------------
Objetivo del módulo: función que crea una nueva ventana con el tablero de control mediante
el cual se pueden enviar tanto los comandos básicos de movimiento (hacia el frente, atrás,
izquierda, derecha, freno) como los comandos de movimientos especiales: Turn Time, North,
Infinite, Especial, Diagnóstico y el control de luces. Además, en el tablero se muestran
los valores sensados por el MPU9250 de porcentaje de luz, temperatura, mayor aceleración,
tiempo de giro, yaw (en puntos cardinales), pitch y roll.
"""
    global DirI, DirD, fl, bl, exe, piloto, sensors, comando, diagnostico, Salir, resultado  #Variables globales para el manejo de
    Salir = False
    diagnostico = False
    comando = 'nada;'
    sensors = False
    piloto = pilot
    exe = ''
    root.withdraw()
    tablero = Toplevel(root)
    tablero.title('Proyecto 3')
    tablero.minsize(893, 522)
    tablero.resizable(width=NO, height=NO)

    #Creando el cliente para NodeMCU
    myCar = NodeMCU()
    myCar.start()

    C_tablero = Canvas(tablero, width=893, height=522)  #Se crea el canvas
    C_tablero.pack()

    Fondo = cargar_imag(
        'Interior_camera.gif')  #Se carga y coloca la imagen de fondo
    C_tablero.fondo = Fondo
    C_tablero.create_image(2, 2, anchor=NW, image=Fondo)

    def get_log():
        """Instito Tecnológico de Costa Rica
Área Académica de Ingeniería en Computadores
Taller de Programación
Proyecto 3
Versión 1.0
Lenguaje: Python 3.7.3
----------------------------------------------
Objetivo del módulo: Hilo que actualiza el label del comando en ejecución cada vez que se agrega un nuevo mensaje al log de myCar.

Entradas: Está constantentemente revisando el tamaño de la lista log de la clase myCar para ver si se ha agregado un nuevo comando.
Salidas: Imprime en el label correspondiente la respuesta recibida del servidor.
"""
        global exe, piloto, Salir, sensors, comando, diagnostico, volteo1, volteo2, state, resultado
        indice = 0
        if Salir:
            return
        while (myCar.loop
               ):  #Mientras esté activo el loop infinito en la comunicación
            if Salir:
                return
            if diagnostico:
                #Se recibe cúal es el estado del auto y se muestra en el tablero
                time.sleep(3)
                estado = myCar.log[indice][1]
                estado = estado.split()
                state = estado[0]
                L_estado.config(text='Estado del auto: ' + estado[0])
                indice += 1
                diagnostico = False
            if sensors:
                resultado.append(piloto)
                resultado.append(state)
                #Se reciben todos los valores sensados y se muestran en el tablero
                mns = 'Luz;'
                myCar.send(mns)
                time.sleep(2)
                luz = myCar.log[indice][1]
                luz = luz.split()
                indice += 1
                print(luz)
                barra = '| Porcentaje de Luz: ' + luz[
                    0] + '% \t Temperatura: ' + 'ºC \t Mayor Aceleración: ' + '\t T. de giro: |'
                L_superior.config(text=barra)

                mns = 'Temp;'
                myCar.send(mns)
                time.sleep(2)
                temp = myCar.log[indice][1]
                temp = temp.split()
                indice += 1
                print(temp)
                resultado.append(temp[0])
                barra = '| Porcentaje de Luz: ' + luz[
                    0] + '% \t Temperatura: ' + temp[
                        0] + 'ºC \t Mayor Aceleración: ' + '\t T. de giro: |'
                L_superior.config(text=barra)

                mns = 'Acel;'
                myCar.send(mns)
                time.sleep(2)
                acel = myCar.log[indice][1]
                acel = acel.split()
                indice += 1
                print(acel)
                resultado.append(acel[0])
                barra = '| Porcentaje de Luz: ' + luz[
                    0] + '% \t Temperatura: ' + temp[
                        0] + 'ºC \t Mayor Aceleración: ' + acel[
                            0] + 'g \t T. de giro: |'
                L_superior.config(text=barra)

                mns = 'Tiempo;'
                myCar.send(mns)
                time.sleep(2)
                tiempo = myCar.log[indice][1]
                tiempo = tiempo.split()
                indice += 1
                print(tiempo)
                resultado.append(tiempo[0])
                barra = '| Porcentaje de Luz: ' + luz[
                    0] + '% \t Temperatura: ' + temp[
                        0] + 'ºC \t Mayor Aceleración: ' + acel[
                            0] + 'g \t T. de giro: ' + tiempo[0] + 's |'
                L_superior.config(text=barra)

                mns = 'roll;'
                myCar.send(mns)
                time.sleep(2)
                roll = myCar.log[indice][1]
                roll = roll.split()
                indice += 1
                #Se activan los mensajes de alerta en caso de haber riesgo de volteo
                if float(roll[0]) < 0.0:
                    alabeo = round(float(roll[0]) + 180, 2)
                    roll[0] = str(alabeo)
                    if abs(alabeo) >= 30:
                        volteo1 = True
                    else:
                        volteo1 = False

                else:
                    alabeo = round(float(roll[0]) - 180, 2)
                    roll[0] = str(alabeo)
                    if abs(alabeo) >= 30:
                        volteo1 = True
                    else:
                        volteo1 = False
                print(roll)
                L_roll.config(text='Roll: ' + roll[0])

                mns = 'pitch;'
                myCar.send(mns)
                time.sleep(2)
                pitch = myCar.log[indice][1]
                pitch = pitch.split()
                indice += 1
                if abs(float(pitch[0])) >= 30:
                    volteo2 = True
                else:
                    volteo2 = False
                print(pitch)
                L_pitch.config(text='Pitch: ' + pitch[0])

                mns = 'yaw;'
                myCar.send(mns)
                time.sleep(2)
                yaw = myCar.log[indice][1]
                yaw = yaw.split()
                yaw = float(yaw[0])
                if 0 <= yaw <= 40:
                    yaw = 'Norte'
                elif 40 < yaw <= 90:
                    yaw = 'Oeste'
                elif 90 < yaw <= 150:
                    yaw = 'Sur'
                else:
                    yaw = 'Este'
                indice += 1
                print(yaw)
                L_compass.config(text='Orientación: ' + yaw)
                L_name.config(text=' Nombre del piloto: ' + piloto +
                              '\n Comando en ejecución: sensores')
                sensors = False

            while (indice < len(myCar.log)):
                #Se actualiza el valor del comando en ejecución mostrado en el tablero
                exe = myCar.log[indice][1]
                print(exe)
                L_name.config(text=' Nombre del piloto: ' + piloto +
                              '\n Comando en ejecución: ' + exe)
                indice += 1

            time.sleep(0.200)

    def moveF(event
              ):  #Función que envía el comando del movimiento hacia el frente
        global comando
        mns = 'dir:0;'
        comando = mns
        myCar.send(mns)

    Forward = cargar_imag('Forward.png')
    C_tablero.create_image(
        447, 100, anchor=N, image=Forward,
        activeimage=Forward)  #Se coloca la imagen de la flecha hacia arriba
    L_Forward = Label(tablero,
                      font=('fixedsys', 8),
                      text='Directo',
                      fg='white',
                      bg='red',
                      anchor=N,
                      justify=CENTER)
    L_Forward.place(x=414, y=143)
    L_Forward.bind(
        '<Button-1>', moveF
    )  #Se enlaza el label con la función de movimiento correspondiente

    def moveB(event):  #Función que envía el comando del movimiento hacia atrás
        global comando
        mns = 'pwm:-800;'
        comando = mns
        myCar.send(mns)

    Backwards = cargar_imag('Backwards.png')
    C_tablero.create_image(
        447, 300, anchor=N, image=Backwards,
        activeimage=Backwards)  #Se coloca la imagen de la flecha hacia abajo
    L_Back = Label(tablero,
                   font=('fixedsys', 8),
                   text='Atrás',
                   fg='white',
                   bg='red',
                   anchor=N,
                   justify=CENTER)
    L_Back.place(x=423, y=382)
    L_Back.bind(
        '<Button-1>', moveB
    )  #Se enlaza el label con la función de movimiento correspondiente

    def moveR(
        event
    ):  #Función que envía el comando del movimiento giratorio hacia la derecha
        global comando
        mns = 'dir:1;'
        comando = mns
        myCar.send(mns)

    Right = cargar_imag('Right.png')
    C_tablero.create_image(
        493, 260, anchor=W, image=Right,
        activeimage=Right)  #Se coloca la imagen de la flecha a la derecha
    L_Right = Label(tablero,
                    font=('fixedsys', 8),
                    text='Der.',
                    fg='white',
                    bg='red',
                    anchor=W,
                    justify=CENTER)
    L_Right.place(x=575, y=250)
    L_Right.bind(
        '<Button-1>', moveR
    )  #Se enlaza el label con la función de movimiento correspondiente

    def moveL(
        event
    ):  #Función que envía el comando del movimiento giratorio hacia la derecha
        global comando
        mns = 'dir:-1;'
        comando = mns
        myCar.send(mns)

    Left = cargar_imag('Left.png')
    C_tablero.create_image(
        400, 260, anchor=E, image=Left,
        activeimage=Left)  #Se coloca la imagen de la flecha a la izquierda
    L_Left = Label(tablero,
                   font=('fixedsys', 8),
                   text='Izq.',
                   fg='white',
                   bg='red',
                   anchor=W,
                   justify=CENTER)
    L_Left.place(x=280, y=250)
    L_Left.bind(
        '<Button-1>', moveL
    )  #Se enlaza el label con la función de movimiento correspondiente

    tablero.bind(
        '<Up>', moveF
    )  #Se enlaza la tecla del puntero hacia arriba con la función de movimiento hacia el frente
    tablero.bind(
        '<Down>', moveB
    )  #Se enlaza la tecla del puntero hacia abajo con la función de movimiento hacia atrás
    tablero.bind(
        '<Right>', moveR
    )  #Se enlaza la tecla del puntero hacia la derecha con la función de movimiento hacia la derecha
    tablero.bind(
        '<Left>', moveL
    )  #Se enlaza la tecla del puntero hacia la izquierda con la función de movimiento hacia la izquierda

    def freno(event):
        global comando
        mns = 'pwm:0;'
        comando = mns
        myCar.send(mns)

    tablero.bind('<space>', freno)

    compass = cargar_imag('compass.png')
    C_tablero.create_image(770,
                           25,
                           anchor=NW,
                           image=compass,
                           activeimage=compass)
    Compass = '******'
    L_compass = Label(tablero,
                      font=('fixedsys', 16),
                      text=Compass,
                      fg='white',
                      bg='gray',
                      anchor=N,
                      justify=CENTER,
                      width=19,
                      relief=RIDGE)
    L_compass.place(x=737, y=115)

    roll = cargar_imag('roll.png')
    C_tablero.create_image(5, 40, anchor=NW, image=roll, activeimage=roll)
    Roll = 'Roll: '
    L_roll = Label(tablero,
                   font=('fixedsys', 16),
                   text=Roll,
                   fg='white',
                   bg='gray',
                   anchor=N,
                   justify=CENTER,
                   width=22,
                   relief=RIDGE)
    L_roll.place(x=18, y=110)

    pitch = cargar_imag('pitch.png')
    C_tablero.create_image(5, 140, anchor=NW, image=pitch, activeimage=pitch)
    Pitch = 'Pitch: '
    L_pitch = Label(tablero,
                    font=('fixedsys', 16),
                    text=Pitch,
                    fg='white',
                    bg='gray',
                    anchor=N,
                    justify=CENTER,
                    width=22,
                    relief=RIDGE)
    L_pitch.place(x=18, y=215)

    def alertaVolteo1(
    ):  #Hilo que cada vez que se activa la bandera volteo1, muestra un mensaje de alerta de volteo de forma intermitente
        global Salir, volteo1
        while True:  #ciclo infinito para estar revisando constantemente el valor de la bandera
            if Salir:
                return
            if volteo1:
                while volteo1:  #Ciclo para controla la intermitencia del mensaje
                    if Salir:
                        return
                    L_alerta1 = Label(C_tablero,
                                      font=('fixedsys', 16),
                                      text=' ¡Alerta! \n Riesgo de volteo',
                                      fg='white',
                                      bg='red',
                                      anchor=N,
                                      justify=CENTER,
                                      relief=RIDGE)
                    L_alerta1.place(x=40, y=60)
                    time.sleep(0.8)
                    L_alerta1.place(x=1000, y=1000)
                    time.sleep(0.5)

    def alertaVolteo2(
    ):  #Hilo que cada vez que se activa la bandera volteo2, muestra un mensaje de alerta de volteo de forma intermitente
        global Salir, volteo2
        while True:  #ciclo infinito para estar revisando constantemente el valor de la bandera
            if Salir:
                return
            if volteo2:
                while volteo2:  #Ciclo para controlar la intermitencia del mensaje
                    if Salir:
                        return
                    L_alerta2 = Label(C_tablero,
                                      font=('fixedsys', 16),
                                      text=' ¡Alerta! \n Riesgo de volteo',
                                      fg='white',
                                      bg='red',
                                      anchor=N,
                                      justify=CENTER,
                                      relief=RIDGE)
                    L_alerta2.place(x=40, y=160)
                    time.sleep(0.8)
                    L_alerta2.place(x=1000, y=1000)
                    time.sleep(0.5)

    #Hilos para el control del mensaje de alerta de volteo
    hilo_volteo1 = Thread(target=alertaVolteo1)
    hilo_volteo1.start()
    hilo_volteo2 = Thread(target=alertaVolteo2)
    hilo_volteo2.start()

    barra = '|Porcentaje de Luz: \t Temperatura: \t Mayor aceleración: \t T. de giro:|'
    L_superior = Label(tablero,
                       font=('fixedsys', 16),
                       text=barra,
                       fg='white',
                       bg='gray',
                       anchor=N,
                       justify=CENTER)
    L_superior.place(x=2, y=2)
    L_superior.config(width=111)
    fl, bl = False, False  #Banderas para indicar el valor de las luces traseras y delanteras

    def f_light(
    ):  #Función que envía los comandos de control del las luces delanteras
        global fl, comando
        fl = not (fl)
        if fl:
            B_frontlight.config(bg='white', fg='black')
            mns = 'lf:1;'
            comando = mns
            myCar.send(mns)
        else:
            B_frontlight.config(bg='black', fg='white')
            mns = 'lf:0;'
            comando = mns
            myCar.send(mns)

    #Botón par el control de las luces delanteras
    B_frontlight = Button(tablero,
                          font=('fixedsys', 16),
                          text='Luces delanteras',
                          fg='white',
                          bg='black',
                          anchor=N,
                          justify=CENTER,
                          command=f_light)
    B_frontlight.place(x=680, y=350)

    def b_light(
    ):  #Función que envía los comandos de control del las luces delanteras
        global bl, comando
        bl = not (bl)
        if bl:
            B_backlight.config(bg='red', fg='white')
            mns = 'lb:1;'
            comando = mns
            myCar.send(mns)
        else:
            B_backlight.config(bg='black', fg='white')
            mns = 'lb:0;'
            comando = mns
            myCar.send(mns)

    #Botón par el control de las luces traseras
    B_backlight = Button(tablero,
                         font=('fixedsys', 16),
                         text='Luces traseras',
                         fg='white',
                         bg='black',
                         anchor=N,
                         justify=CENTER,
                         command=b_light)
    B_backlight.place(x=687, y=380)

    def dirder(
    ):  #Hilo para activar una rutina de intermitencia del botón de la direccional derecha para indicar que dicha función está activada
        global DirD, Salir
        while True:  #ciclo infinito para estar revisando constantemente el valor de la bandera
            if Salir:
                return
            if DirD:
                B_dirder.config(bg='red', fg='white')
                time.sleep(0.8)
                B_dirder.config(bg='black', fg='white')
                time.sleep(0.8)

    def activaD(
    ):  #Envía comandos de control de la direccionale derecha y cambia los valores de las banderas
        global DirD, DirI, comando
        DirD = not (DirD)
        DirI = False
        if DirD:
            mns = 'lr:1;'
            comando = mns
            myCar.send(mns)

        else:
            mns = 'lr:0;'
            comando = mns
            myCar.send(mns)

    #Botón par el control de la luz direccional derecha
    B_dirder = Button(tablero,
                      font=('fixedsys', 16),
                      text='Dir. der.',
                      fg='white',
                      bg='black',
                      anchor=N,
                      justify=CENTER,
                      command=activaD)
    B_dirder.place(x=811, y=380)

    def dirizq(
    ):  #Hilo para activar una rutina de intermitencia del botón de la direccional izquierda para indicar que dicha función está activada
        global DirI, Salir
        while True:  #ciclo infinito para estar revisando constantemente el valor de la bandera
            if Salir:
                return
            if DirI:
                B_dirizq.config(bg='red', fg='white')
                time.sleep(0.8)
                B_dirizq.config(bg='black', fg='white')
                time.sleep(0.8)

    def activaI(
    ):  #Envía comandos de control de la direccional izquierda y cambia los valores de las banderas
        global DirI, DirD, comando
        DirI = not (DirI)
        DirD = False
        if DirI:
            mns = 'll:1;'
            comando = mns
            myCar.send(mns)
        else:
            mns = 'll:0;'
            comando = mns
            myCar.send(mns)

    #Botón par el control de la luz direccional izquierda
    B_dirizq = Button(tablero,
                      font=('fixedsys', 16),
                      text='Dir. izq.',
                      fg='white',
                      bg='black',
                      anchor=N,
                      justify=CENTER,
                      command=activaI)
    B_dirizq.place(x=603, y=380)

    #Hilos para el control de la intermitencia de los botones de control de las luces direccionales
    p1 = Thread(target=dirder, args=())
    p1.start()
    p2 = Thread(target=dirizq, args=())
    p2.start()

    def freno1():  #Función que envía el comando para frenar los motores
        global comando
        mns = 'pwm:0;'
        comando = mns
        myCar.send(mns)

    Freno = Button(tablero,
                   font=('fixedsys', 16),
                   text='Freno',
                   fg='white',
                   bg='red',
                   anchor=N,
                   justify=CENTER,
                   command=freno1)
    Freno.place(x=421, y=250)

    def salir(
    ):  #Se destruye la ventana del tablero y se vuelve a la principal
        global Salir, resultado
        tablero.destroy()
        root.deiconify()
        f = open('Registro.txt', 'a')
        linea = '\t\t'
        lineas = '\n' + linea.join(
            resultado
        )  #Se agrega el resultado de la última prueba al archivo de texto
        f.write(lineas)
        f.close()
        resultado = []
        TreeV()  #Se actualiza el Treeview
        Salir = True

    Back = Button(tablero,
                  font=('fixedsys', 16),
                  text='Salir',
                  fg='black',
                  bg='yellow',
                  anchor=N,
                  justify=CENTER,
                  command=salir)
    Back.place(x=843, y=498)

    #Funciones para invocar los movimientos especiales
    def TurnTime1():
        global comando
        mns = 'TurnTime:-1;'
        comando = mns
        myCar.send(mns)

    turntime = Button(tablero,
                      font=('fixedsys', 16),
                      text='TurnTime:L',
                      fg='black',
                      bg='white',
                      anchor=N,
                      justify=CENTER,
                      command=TurnTime1,
                      width=10)
    turntime.place(x=25, y=270)

    def TurnTime2():
        global comando
        mns = 'TurnTime:1;'
        comando = mns
        myCar.send(mns)

    turntime = Button(tablero,
                      font=('fixedsys', 16),
                      text='TurnTime:R',
                      fg='black',
                      bg='white',
                      anchor=N,
                      justify=CENTER,
                      command=TurnTime2,
                      width=10)
    turntime.place(x=25, y=300)

    def Infinite():
        global comando
        mns = 'Infinite;'
        comando = mns
        myCar.send(mns)

    infinite = Button(tablero,
                      font=('fixedsys', 16),
                      text='Infinite',
                      fg='black',
                      bg='white',
                      anchor=N,
                      justify=CENTER,
                      command=Infinite,
                      width=10)
    infinite.place(x=25, y=330)

    def North():
        global comando
        mns = 'North;'
        comando = mns
        myCar.send(mns)

    north = Button(tablero,
                   font=('fixedsys', 16),
                   text='North',
                   fg='black',
                   bg='white',
                   anchor=N,
                   justify=CENTER,
                   command=North,
                   width=10)
    north.place(x=25, y=360)

    def Diag():
        global diagnostico
        mns = 'Diag;'
        myCar.send(mns)
        time.sleep(9)
        mns = 'saved;'
        myCar.send(mns)
        diagnostico = True

    diag = Button(tablero,
                  font=('fixedsys', 16),
                  text='Diagnostic',
                  fg='black',
                  bg='white',
                  anchor=N,
                  justify=CENTER,
                  command=Diag,
                  width=10)
    diag.place(x=25, y=390)

    def Special():
        global comando
        mns = 'Especial;'
        comando = mns
        myCar.send(mns)

    special = Button(tablero,
                     font=('fixedsys', 16),
                     text='Special',
                     fg='black',
                     bg='white',
                     anchor=N,
                     justify=CENTER,
                     command=Special,
                     width=10)
    special.place(x=25, y=420)

    name = ' Nombre del piloto: ' + piloto + '\n Comando en ejecución: ' + exe
    L_name = Label(tablero,
                   font=('fixedsys', 16),
                   text=name,
                   fg='white',
                   bg='black',
                   anchor=N,
                   justify=CENTER,
                   relief=RIDGE)
    L_name.place(x=300, y=40)

    L_estado = Label(tablero,
                     font=('fixedsys', 16),
                     text="Estado del auto: ",
                     fg='white',
                     bg='black',
                     anchor=N,
                     justify=CENTER,
                     relief=RIDGE,
                     width=25)
    L_estado.place(x=20, y=480)

    #Se activa la bandera para ejecutar los sensores
    def activaSensores():
        global sensors
        sensors = True

    p = Thread(target=get_log)
    p.start()

    B_Sensores = Button(tablero,
                        font=('fixedsys', 16),
                        text='Refrescar sensores',
                        fg='white',
                        bg='black',
                        anchor=N,
                        justify=CENTER,
                        command=activaSensores,
                        width=20)
    B_Sensores.place(x=360, y=450)

    tablero.mainloop()
Beispiel #8
0
def test_drive(escuderias, nombres):
    global Veloci
    global prueba
    global escuderia
    global nombre
    #            _____________________
    #___________/Crear ventana //se crea la pantalla
    ventana = Toplevel()
    ventana.title("Test Drive")  # título de la misma
    ventana.minsize(800, 400)  # tamaño de la pantalla
    ventana.resizable(width=NO, height=NO)  # no se puede ajustar su tamaño
    canvas = Canvas(ventana, width=800, height=400,
                    bg='Pink')  # color de la pantalla principal
    canvas.place(x=0, y=0)  #ubicación

    #            _____________________
    #___________/Velocidad // funcion para aumentar o disminuir la velocidad en la pantalla de test drive
    velocidades = 0

    def velocidad(velo):
        global Veloci
        velocidades = 0

        def vel():
            global velocidades
            if Veloci:
                velocidades += 1
                velo.config(text=str(velocidades) + 'kpm')
                velo.after(velocidad(velo))

        vel()
#           ______________________
#__________/Cargar imágenes // función para cargar imágenes a la pantalla del test drive

    def cargarimagen(carro):
        ruta = os.path.join('imagenes',
                            carro)  #ubicacion de a imagen (folder, nombre)
        imagen = PhotoImage(file=ruta)
        return imagen

    #logo = cargarimagen("logo.png")
    #logo1 = canvas.create_image(480,50, image=logo, anchor = NW)

    carro = cargarimagen("vistapiloto.png")
    carro1 = canvas.create_image(-90, 22, image=carro, anchor=NW)

    canvas.create_rectangle(0, 0, 800, 150, fill="skyblue")

    #           ______________________
    #__________/Textos // textos incluídos a la ventana del test drive
    Test_Drive = Label(canvas,
                       text="TEST DRIVE",
                       font=('Times New Roman', 20),
                       bg='red',
                       fg='black')
    Test_Drive.place(x=585, y=10)
    NombrePiloto = Label(canvas,
                         text=nombres,
                         font=('Arial', 15),
                         bg='skyblue',
                         fg='white')
    NombrePiloto.place(x=585, y=55)
    NombreEscuderia = Label(canvas,
                            text=escuderias,
                            font=('Arial', 15),
                            bg='skyblue',
                            fg='white')
    NombreEscuderia.place(x=625, y=95)
    piloto = Label(canvas,
                   text='Piloto:',
                   font=('Arial', 15),
                   fg='black',
                   bg='skyblue')
    piloto.place(x=500, y=55)
    escuderia = Label(canvas,
                      text='Escudería:',
                      font=('Arial', 15),
                      fg='black',
                      bg='skyblue')
    escuderia.place(x=500, y=95)
    label = Label(canvas, fg='black', font=('Arial', 15),
                  bg='skyblue')  #.place(x=100, y=100)
    label.place(x=105, y=110)
    velo = Label(canvas, fg='black', font=('Arial', 15), bg='grey')
    velo.place(x=375, y=177)
    bateria = Label(canvas,
                    text='Batería: ',
                    font=("Arial", 15),
                    fg='black',
                    bg="skyblue")
    bateria.place(x=20, y=110)
    #label.pack()
    counter_label(label)
    #//cuadros que reflejan la información enviada por el cliente en otras palabras da un status de cómo está la sitauación al mandar
    #//mensajes al nodeMCU
    SentCarScrolledTxt = tkscrolled.ScrolledText(canvas, height=5, width=5)
    SentCarScrolledTxt.place(x=-400, y=200)
    RevCarScrolledTxt = tkscrolled.ScrolledText(canvas, height=5, width=5)
    RevCarScrolledTxt.place(x=-410, y=200)

    #           ______________________
    #__________/Funcion del NodeMCU // funciones para recibir un mensaje y mandarlo al nodeMCU
    myCar = NodeMCU()
    myCar.start()

    def get_log():
        """
        Hilo que actualiza los Text cada vez que se agrega un nuevo mensaje al log de myCar
        """
        indice = 0
        # Variable del carro que mantiene el hilo de escribir.
        while (myCar.loop):
            while (indice < len(myCar.log)):
                mnsSend = "[{0}] cmd: {1}\n".format(indice,
                                                    myCar.log[indice][0])
                SentCarScrolledTxt.insert(END, mnsSend)
                SentCarScrolledTxt.see("end")
                mnsRecv = "[{0}] result: {1}\n".format(indice,
                                                       myCar.log[indice][1])
                RevCarScrolledTxt.insert(END, mnsRecv)
                RevCarScrolledTxt.see('end')
                indice += 1
            time.sleep(0.200)

    p = Thread(target=get_log)
    p.start()

    #//funciones específicas ya con su propio código para que el cliente solo tenga que estripar un botón y la función se ejecute
    def Circle(event):
        if myCar.send('circle' + ';'):
            myCar.send('circle' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def Mov_Especial(event):
        if myCar.send('Movimiento especial1' + ';'):
            myCar.send('Movimiento especial1' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def Mov_Especial2(event):
        if myCar.send('Movimiento especial2' + ';'):
            myCar.send('Movimiento especial2' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def ZigZag(event):
        if myCar.send('zigzag' + ';'):
            myCar.send('zigzag' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def Infinite(event):
        if myCar.send('infinite' + ';'):
            myCar.send('infinite' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def Especial(event):
        if myCar.send('especial' + ';'):
            myCar.send('especial' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def Recto(event):
        if myCar.send('Recto' + ';'):
            myCar.send('Recto' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def Izquierda(event):
        if myCar.send('Izquierda' + ';'):
            myCar.send('Izquierda' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def Derecha(event):
        if myCar.send('Derecha' + ';'):
            myCar.send('Derecha' + ';')
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def sendShowID():
        """
        Ejemplo como capturar un ID de un mensaje específico.
        """
        mns = str(E_Command.get())
        if (len(mns) > 0 and mns[-1] == ";"):
            E_Command.delete(0, 'end')
            mnsID = myCar.send(mns)
            messagebox.showinfo(
                "Mensaje pendiente",
                "Intentando enviar mensaje, ID obtenido: {0}\n\La respuesta definitiva se obtine en un máximo de {1}s"
                .format(mnsID, myCar.timeoutLimit))
        else:
            messagebox.showwarning(
                "Error del mensaje",
                "Mensaje sin caracter de finalización (';')")

    def read():
        """
        Ejemplo de como leer un mensaje enviado con un ID específico
        """
        mnsID = str(E_read.get())
        if (len(mnsID) > 0 and ":" in mnsID):
            mns = myCar.readById(mnsID)
            if (mns != ""):
                messagebox.showinfo(
                    "Resultado Obtenido",
                    "El mensaje con ID:{0}, obtuvo de respuesta:\n{1}".format(
                        mnsID, mns))
                E_read.delete(0, 'end')
            else:
                messagebox.showerror(
                    "Error de ID", "No se obtuvo respuesta\n\
    El mensaje no ha sido procesado o el ID es invalido\n\
    Asegurese que el ID: {0} sea correcto".format(mnsID))
        else:
            messagebox.showwarning("Error en formato",
                                   "Recuerde ingresar el separador (':')")

    #ventana.bind('<Return>', Circle) #Vinculando tecla Enter a la función send

#           ______________________
#__________/Botones

#//Botones relacionados con las funciones de comandos enseñados anteriormente la función de estos botones es que ya tienen el comando
#//dentro de ellos por lo que con tan solo presionarlos ya se enviará el mensaje

    Btn_ConnectControl2 = Button(canvas,
                                 text='Circle',
                                 command=lambda: Circle(None),
                                 fg='black',
                                 bg='red',
                                 font=('Agency FB', 15))
    Btn_ConnectControl2.place(x=10, y=10)

    Btn_ConnectControl3 = Button(canvas,
                                 text='Movimiento Especial1',
                                 command=lambda: Mov_Especial(None),
                                 fg='black',
                                 bg='red',
                                 font=('Agency FB', 15))
    Btn_ConnectControl3.place(x=55, y=10)

    Btn_ConnectControl4 = Button(canvas,
                                 text='Movimiento Especial2',
                                 command=lambda: Mov_Especial2(None),
                                 fg='black',
                                 bg='red',
                                 font=('Agency FB', 15))
    Btn_ConnectControl4.place(x=185, y=10)

    Btn_ConnectControl5 = Button(canvas,
                                 text='ZigZag',
                                 command=lambda: ZigZag(None),
                                 fg='black',
                                 bg='red',
                                 font=('Agency FB', 15))
    Btn_ConnectControl5.place(x=10, y=60)

    Btn_ConnectControl6 = Button(canvas,
                                 text='Infinite',
                                 command=lambda: Infinite(None),
                                 fg='black',
                                 bg='red',
                                 font=('Agency FB', 15))
    Btn_ConnectControl6.place(x=55, y=60)

    Btn_ConnectControl7 = Button(canvas,
                                 text='Especial',
                                 command=lambda: Especial(None),
                                 fg='black',
                                 bg='red',
                                 font=('Agency FB', 15))
    Btn_ConnectControl7.place(x=104, y=60)

    Btn_ConnectControl8 = Button(canvas,
                                 text='Recto',
                                 command=lambda: Recto(None),
                                 fg='black',
                                 bg='red',
                                 font=('Agency FB', 15))
    Btn_ConnectControl8.place(x=380, y=110)

    Btn_ConnectControl9 = Button(canvas,
                                 text='Izquierda',
                                 command=lambda: Izquierda(None),
                                 fg='black',
                                 bg='red',
                                 font=('Agency FB', 15))
    Btn_ConnectControl9.place(x=50, y=250)

    Btn_ConnectControl10 = Button(canvas,
                                  text='Derecha',
                                  command=lambda: Derecha(None),
                                  fg='black',
                                  bg='red',
                                  font=('Agency FB', 15))
    Btn_ConnectControl10.place(x=680, y=250)

    Veloci = Button(canvas,
                    text='PWM',
                    command=lambda: velocidad(velo),
                    fg="black",
                    bg="grey",
                    font=('Arial', 10))
    Veloci.place(x=380, y=177)

    ventana.mainloop()