Project

General

Profile

Codigo Utilizado » History » Version 14

« Previous - Version 14/21 (diff) - Next » - Current version
fernando diaz, 11/18/2024 04:47 PM


Código Utilizado

Servidor


import socket
from main import *

server = socket.socket()

PORT = 8080

server.bind(('', PORT))
server.listen(1)

connection, adress = server.accept()

actions = {
    "w" : move_front,
    "a" : move_left,
    "d" : move_right,
    "s" : move_back,
    "e" : move_grab,
}

while True:
    data = connection.recv(1)
    keyword = data.decode("utf-8")

    if keyword in actions:
        actions[keyword]()

    elif keyword == "q":
        break

Funciones

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.parameters import Port, Stop, Direction, Button, Color
from pybricks.tools import wait, StopWatch, DataLog
from pybricks.robotics import DriveBase
from pybricks.media.ev3dev import SoundFile, ImageFile

#Initialize the EV3 brick.
ev3 = EV3Brick()

motor_right = Motor(Port.A, Direction.COUNTERCLOCKWISE)
motor_left = Motor(Port.D, Direction.COUNTERCLOCKWISE)
motor_garra= Motor(Port.B)

robot = DriveBase(motor_left,motor_right, wheel_diameter=55.5, axle_track=84)
robot.settings(600, 500, 1000, 500)

def move_front():
        robot.straight(150)

def move_back():
        robot.straight(-150)

def move_right():
        robot.turn(300)

def move_left():
        robot.turn(-300)

def move_grab():
    robot.run_until_stalled(-300, Stop.HOLD, 40)
    motor_garra.run_until_stalled(300, Stop.COAST, 40)

# Detener el robot
robot.stop()

ev3.speaker.beep()

Interfaz Gráfica

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import socket

class App(tk.Tk):
    STATUS_CONNECTION = False
    PORT = 8080

    def __init__(self):
        super().__init__()
        self.title("Ball-e")
        self.config(padx=10, pady=10, bg="#FFC0CB")
        self.geometry("800x600")
        self.canvas = tk.Canvas(self, width=800, height=600)
        self.canvas.pack()
        self.resizable(width=False, height=False)
        self.imagen_fondo = tk.PhotoImage(file="fondo.png")
        self.imagen_fondo = self.imagen_fondo.subsample(5,5)
        self.canvas.create_image(0, 0, anchor=tk.NW, image=self.imagen_fondo)
        self.init_images()
        self.init_elements()
        self.grab_open = True  # Inicialmente, la garra está abierta

    def init_images(self):
        imagenes = ["encendido.png"]
        self.images = [tk.PhotoImage(file=imagen).subsample(12, 12) for imagen in imagenes]

        self.garra_abierta_img = tk.PhotoImage(file="garra_abierta.png").subsample(10, 10)  
        self.garra_cerrada_img = tk.PhotoImage(file="garra_cerrada.png").subsample(10, 10)

        imagenes1 = ["flechaFront.png", "flechaBack.png", "flechaLeft.png", "flechaRight.png"]
        self.images1 = [tk.PhotoImage(file=imagen).subsample(25, 25) for imagen in imagenes1]
        self.flechaFront, self.flechaBack, self.flechaLeft, self.flechaRight= self.images1

    def init_elements(self):
        btn_color = "#fff" if self.STATUS_CONNECTION else "#000" 
        self.btn_Connect = tk.Button(self, bd=0, bg=btn_color, width=40, height=40, command=self.ip_connect).place(x=710, y=500)
        self.btn_Front = tk.Button(self, image= self.flechaFront, bd=0, bg="white", highlightbackground='white', width=80, height=80, command=lambda: self.move_front_car(None)).place(x=545,y=100)
        self.btn_Back = tk.Button(self, image= self.flechaBack, bd=0, width=80, height=80, command=lambda:self.move_back_car(None)).place(x=545,y=300)
        self.btn_Left = tk.Button(self, image= self.flechaLeft, bd=0, width=80, height=80, command=lambda:self.move_left_car(None)).place(x=450,y=200)
        self.btn_Right = tk.Button(self, image= self.flechaRight, bd=0, width=80, height=80, command=lambda: self.move_right_car(None)).place(x=640,y=200)
        self.btn_Grab = tk.Button(self, image=self.garra_abierta_img, bd=0, command=lambda: self.move_grab_car(None)).place(x=545, y=200)

    def ip_connect(self):
        if not self.STATUS_CONNECTION:
            ventana_conexion = tk.Toplevel(self)
            ventana_conexion.title("Ventana de Conexión")
            ventana_conexion.geometry("200x150")
            ventana_conexion.resizable(width=False, height=False)
            etiqueta = tk.Label(ventana_conexion, text="Ingrese la dirección IP:")
            etiqueta.pack(pady=10)
            self.IP = tk.StringVar()
            entry_ip = tk.Entry(ventana_conexion, textvariable=self.IP)
            entry_ip.pack(pady=10)
            btn_conectar = tk.Button(ventana_conexion, text="Conectar", command= lambda: self.robot_connection(self.IP.get()))
            btn_conectar.pack(pady=10)
        else:
            self.robot_connection(self.IP.get())

    def robot_connection(self, IP):
        if self.STATUS_CONNECTION:
            self.STATUS_CONNECTION = not self.STATUS_CONNECTION
            self.init_elements()  
        else:
            try:
                self.client = socket.socket()
                self.client.connect((IP, self.PORT))  
                self.STATUS_CONNECTION = True
                self.init_elements()
                messagebox.showinfo("Conexión exitosa", "Se ha conectado al robot correctamente.")  
                self.window_ip.destroy()
            except socket.error:
                messagebox.showerror("Error", "No se pudo conectar al robot.")
                self.STATUS_CONNECTION = False

    def move_front_car(self, event):
        self.client.send(bytes([ord('w')]))

    def move_left_car(self, event):
        self.client.send(bytes([ord('a')]))

    def move_right_car(self, event):
        self.client.send(bytes([ord('d')]))

    def move_back_car(self, event):
        self.client.send(bytes([ord('s')]))

    def move_grab_car(self, event):
        self.client.send(bytes([ord('e')])) 
        if self.grab_open:
            self.grab_open = False  # Ahora la garra está cerrada
            self.btn_Grab.config(image=self.garra_cerrada_img)
        else:
            self.grab_open = True  # Ahora la garra está abierta
            self.btn_Grab.config(image=self.garra_abierta_img)

if __name__ == "__main__":
    app = App()
    app.mainloop()