Commit 3c91c677 by Samuel Valverde Garcia

Merge branch 'adicional_interfaz' into Interfaz

parents 538747d1 cbdbb574
import paho.mqtt.client as mqtt import paho.mqtt.client as mqtt
import json
class Conexion: class Conexion:
def on_message(client,userdata,message):
print(f'MENSAGE PERDIDO - Recive Topic:{message.topic} Mensage:{str(message.payload.decode("utf-8"))}')
def __init__(self, topics,on_msg): def __init__(self, topics:list,on_msg:list):
with open(file="conexionConfig.json",mode='r') as f:
data = json.load(f)
# Configuración del broker MQTT self.__broker_address = data['ipbroker']
self.__broker_address = "192.168.48.245" # Cambia por la dirección de tu broker MQTT self.__port = int(data['portbroker'])
#self.__broker_address = "192.168.0.100" # Cambia por la dirección de tu broker MQTT
self.__port = 1883 # Puerto predeterminado para MQTT # Configuración del broker MQTT
#self.__broker_address = "192.168.48.245" # Cambia por la dirección de tu broker MQTT
#self.__broker_address = "192.168.0.100" # Cambia por la dirección de tu broker MQTT
#self.__port = 1883 # Puerto predeterminado para MQTT
#self.__topic = ["A3-467/GrupoL","map"] #self.__topic = ["A3-467/GrupoL","map"]
self.__topic = topics self.__topic = topics
#def on_message(client, userdata, message): #def on_message(client, userdata, message):
# print("message received " ,str(message.payload.decode("utf-8"))) # print("message received " ,str(message.payload.decode("utf-8")))
...@@ -26,26 +33,30 @@ class Conexion: ...@@ -26,26 +33,30 @@ class Conexion:
#broker_address="192.168.0.19" #broker_address="192.168.0.19"
#broker_address="iot.eclipse.org" #broker_address="iot.eclipse.org"
print("creating new instance") print("creating new instance")
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
#client.on_message = on_message #client.on_message = on_message
#client.on_message=on_message #attach function to callback #client.on_message=on_message #attach function to callback
client.on_message = on_msg #client.on_message = on_msg
for tp,df in zip(topics,on_msg):
self.client.message_callback_add(tp,df)
print(f" Funcion {df} adjunta a {tp}")
print("connecting to broker") print("connecting to broker")
client.connect(self.__broker_address,self.__port) #connect to broker self.client.connect(self.__broker_address,self.__port) #connect to broker
client.loop_start() #start the loop
for tp in self.__topic: for tp in topics:
client.subscribe(tp) self.client.subscribe(tp)
print(f" Subscrito a {tp}") print(f" Subscrito a {tp}")
#self.__client = self.__connect_mqtt() #self.__client = self.__connect_mqtt()
#self.inicializar() #self.inicializar()
#self.__client.loop_start() #self.__client.loop_start()
self.client.on_message = self.on_message
self.client.loop_start() #start the loop
#self.subscribe(cliente=client,topic=self.__topic) #self.subscribe(cliente=client,topic=self.__topic)
self.__client = client
print("Inicializado") print("Inicializado")
#self.__listaPendientes = listaPendientes #self.__listaPendientes = listaPendientes
...@@ -55,10 +66,10 @@ class Conexion: ...@@ -55,10 +66,10 @@ class Conexion:
def publicar(self,topic,msg): def publicar(self,topic,msg):
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) #client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.connect(self.__broker_address, self.__port) #client.connect(self.__broker_address, self.__port)
result = client.publish(topic,msg) result = self.client.publish(topic,msg)
client.disconnect() #client.disconnect()
#result = self.__client.publish(self.__topic[0],msg) #result = self.__client.publish(self.__topic[0],msg)
# result: [0, 1] # result: [0, 1]
status = result[0] status = result[0]
...@@ -68,10 +79,14 @@ class Conexion: ...@@ -68,10 +79,14 @@ class Conexion:
print(f"Failed to send message to topic {topic}") print(f"Failed to send message to topic {topic}")
def desconectar(self): def desconectar(self):
self.__client.loop_stop() self.client.loop_stop()
self.__client.disconnect() self.client.disconnect()
print("Desconectado") print("Desconectado")
def desubscribir(self,topic):
self.client.unsubscribe(topic)
print(f"Desubscrito topic : {topic}")
# Función para enviar mensajes MQTT al broker # Función para enviar mensajes MQTT al broker
def send_mqtt_message( topic,message): def send_mqtt_message( topic,message):
......
{
"ipbroker" :"192.168.0.19",
"portbroker" : "1883",
"topicSubsRobot" : ["A3-467/GrupoL/Robot","A3-467/GrupoL/SincRobot"],
"topicSubsInterfaz" : ["A3-467/GrupoL/Interfaz","map","A3-467/GrupoL/SincInterfaz"],
"topicSendRobot" : ["A3-467/GrupoL/Interfaz","A3-467/GrupoL/SincInterfaz"],
"topicSendInterfaz" : ["A3-467/GrupoL/Robot","A3-467/GrupoL/SincRobot"],
"separadorMensaje" : ":",
"prefijoMensajes" : {
"mapa":"map",
"pedido":"ped",
"posicion":"pos",
"sinc" : "Sincronizar"
}
}
\ No newline at end of file
#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
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
# Create your objects here.
ev3 = EV3Brick()
colorSensor = ColorSensor(Port.S4)
left_motor = Motor(Port.A)
right_motor = Motor(Port.D)
giroSensor = GyroSensor(Port.S1)
robot = DriveBase(left_motor, right_motor, wheel_diameter=55.5, axle_track=124)
#Metodo para el giro
def giro(grados):
robot.reset()
giroSensor.reset_angle(0)
robot.turn(grados)
while(giroSensor.angle() != grados):
diferencia = giroSensor.angle() - grados
ajuste = diferencia * -1
for i in range(abs(ajuste)):
if(ajuste > 0):
robot.turn(1)
else:
if (ajuste < 0):
robot.turn(-1)
import mensajeInterfaz as msg
import time
msgInterfaz = msg.MensajeInterfaz()
mapa = msgInterfaz.getMapa()
print(f"Mapa recibido {mapa}")
print("Comprobando solicitud")
while(not msgInterfaz.pedidoSolicitado):
time.sleep(1)
print("Comprobando solicitud")
posicion = msgInterfaz.getPosicion()
print(f"Posicion Recibida {posicion}")
print(f'Posicion x = {posicion[0]} : y = {posicion[1]}')
pedido = ((4,5),(7,9))
msgInterfaz.sendPedido(pedido)
print("Pedido enviado")
time.sleep(60)
\ No newline at end of file
import conexion as cn
import time
mapa = "0202000105030705000200041109060110031000000200080101100110000106010701"
while(True):
cn.send_mqtt_message("map",mapa)
print("Enviado")
time.sleep(30)
\ No newline at end of file
#from typing import Any
import conexion as cn
import time
import json
class MensajeInterfaz:
def __init__(self) -> None:
def on_message_default(client,userdata,message):
print(f'Recive Topic:{message.topic} Mensage:{str(message.payload.decode("utf-8"))}')
mensaje = str(message.payload.decode("utf-8"))
if(mensaje.split(self.sepMsg)[0] == self.prefMsg['pedido']):
self.pedidoSolicitado = True
if(mensaje.split(self.sepMsg)[0] == self.prefMsg['posicion']):
mensaje = str(message.payload.decode("utf-8"))
sspos = mensaje.split(self.sepMsg)[1].split(",")
ssx = int(sspos[0].split("(")[1])
ssy = int(sspos[1].split(")")[0])
self.posicion = (ssx,ssy)
def on_message_mapa(client,userdata,message):
print(f'Recive Topic:{message.topic} Mensage:{str(message.payload.decode("utf-8"))}')
self.mapa = str(message.payload.decode("utf-8"))
while(not self.sinc):
time.sleep(2)
self.__enviarMapa()
self.conex.desubscribir(message.topic)
def on_message_sinc(client,userdata,message):
print(f'Recive Topic:{message.topic} Mensage:{str(message.payload.decode("utf-8"))}')
self.sinc = True
#def on_message(client, userdata, message):
# print(f'Recive Topic:{message.topic} Mensage:{str(message.payload.decode("utf-8"))}')
# filtrarMensage(message.topic,str(message.payload.decode("utf-8")))
with open(file="conexionConfig.json",mode='r') as f:
data = json.load(f)
#self.topicSubs = ["A3-467/GrupoL/Robot"]
self.topicSubs = data['topicSubsInterfaz']
print(f'Topics a subscribir {self.topicSubs}')
#self.topicSend = ["A3-467/GrupoL/Interfaz"]
self.topicSend = data['topicSendInterfaz']
print(f'Topics a enviar {self.topicSend}')
#self.prefMsg = {"mapa":'map',
# "pedido":'ped',
# "posicion":'pos'}
self.prefMsg = data['prefijoMensajes']
self.sepMsg = data['separadorMensaje']
defs = [on_message_default,on_message_mapa,on_message_sinc]
self.conex = cn.Conexion(self.topicSubs,on_msg=defs)
self.mapa = ""
self.posicion : list
self.pedidoSolicitado = False
self.sinc = False
self.__sincronizacion()
def __sincronizacion(self):
while(not self.sinc):
self.conex.publicar(self.topicSend[-1],self.prefMsg['sinc'])
time.sleep(2)
print("SINCRONIZADO")
self.conex.desubscribir(self.topicSubs[-1])
self.conex.publicar(self.topicSend[-1],self.prefMsg['sinc'])
def __enviarMapa(self):
self.conex.publicar(self.topicSend[0],str(self.prefMsg['mapa'] + self.sepMsg + self.mapa))
def getMapa(self):
while(len(self.mapa) == 0):
time.sleep(1)
return self.mapa
def sendPedido(self,pedido):
msg = ""
for pos in pedido:
for num in pos:
msg = msg + str(num)
self.conex.publicar(self.topicSend[0],self.prefMsg['pedido'] + self.sepMsg + msg)
self.pedidoSolicitado = False
def getPosicion(self):
while(self.posicion is None):
print("No hay posicion")
time.sleep(1)
return self.posicion
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment