- Funcando de una vezzzzzz

parent 6b9b7537
import paho.mqtt.client as mqtt #import paho.mqtt.client as mqtt
import json import ujson
from umqtt.robust import MQTTClient
class Conexion: class Conexion:
def __init__(self, topics,on_msg): def __init__(self, topics:list,on_msg):
with open(file="conexionConfig.json",mode='r') as f: with open("conexionConfig.json",'r') as f:
data = json.load(f) data = ujson.load(f)
self.__broker_address = data['ipbroker'] self.__broker_address = data['ipbroker']
self.__port = int(data['portbroker']) self.__port = int(data['portbroker'])
...@@ -20,6 +21,7 @@ class Conexion: ...@@ -20,6 +21,7 @@ class Conexion:
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")))
# print("message topic=",message.topic) # print("message topic=",message.topic)
...@@ -30,29 +32,34 @@ class Conexion: ...@@ -30,29 +32,34 @@ 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)
self.client = MQTTClient("RobotPACO",self.__broker_address)
self.client.set_callback(on_msg)
self.client.connect()
#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
print("connecting to broker")
client.connect(self.__broker_address,self.__port) #connect to broker
client.loop_start() #start the loop
if(len(self.__topic) == 0): """
print(f" Subscrito a {self.__topic}") for tp,df in zip(topics,on_msg):
else: self.client.message_callback_add(tp,df)
for tp in self.__topic: print(f" Funcion {df} adjunta a {tp}")
client.subscribe(tp)
print(f" Subscrito a {tp}") print("connecting to broker")
self.client.connect(self.__broker_address,self.__port) #connect to broker
"""
for tp in topics:
self.client.subscribe(tp)
print("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.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
...@@ -62,31 +69,39 @@ class Conexion: ...@@ -62,31 +69,39 @@ 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) print("Enviar a topic",topic," mensage ",msg)
client.disconnect() self.client.publish(topic,msg)
#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]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
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): def desubscribir(self,topic):
self.__client.unsubscribe(topic) self.client.unsubscribe(topic)
print(f"Desubscrito topic : {topic}") #print(f"Desubscrito topic : {topic}")
def checkMensages(self):
self.client.check_msg()
# Función para enviar mensajes MQTT al broker # Función para enviar mensajes MQTT al broker
def publicarOut( topic, msg):
# client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
# client.connect(self.__broker_address, self.__port)
print("Enviar a topic", topic, " mensage ", msg)
client = MQTTClient("PACO", "192.168.48.245")
client.connect()
client.publish(topic, msg)
"""
def send_mqtt_message( topic,message): def send_mqtt_message( topic,message):
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) client = MQTTClient("PACO",)
client.connect("192.168.0.19" , 1883) client.connect("192.168.0.19" , 1883)
client.publish(topic, message) client.publish(topic, message)
client.disconnect() client.disconnect()
...@@ -121,3 +136,5 @@ def send_mqtt_message( topic,message): ...@@ -121,3 +136,5 @@ def send_mqtt_message( topic,message):
# subscribe(client) # subscribe(client)
# client.loop_forever() # client.loop_forever()
"""
{ {
"ipbroker" :"192.168.0.19", "ipbroker" :"192.168.48.245",
"portbroker" : "1883", "portbroker" : "1883",
"topicSubsRobot" : ["A3-467/GrupoL/Robot","A3-467/GrupoL/Sinc"], "topicSubsRobot" : ["A3-467/GrupoL/Robot","A3-467/GrupoL/SincRobot"],
"topicSubsInterfaz" : ["A3-467/GrupoL/Interfaz","map","A3-467/GrupoL/Sinc"], "topicSubsInterfaz" : ["A3-467/GrupoL/Interfaz","map","A3-467/GrupoL/SincInterfaz"],
"topicSendRobot" : "A3-467/GrupoL/Interfaz", "topicSendRobot" : ["A3-467/GrupoL/Interfaz","A3-467/GrupoL/SincInterfaz"],
"topicSendInterfaz" : "A3-467/GrupoL/Robot", "topicSendInterfaz" : ["A3-467/GrupoL/Robot","A3-467/GrupoL/SincRobot"],
"separadorMensaje" : ":", "separadorMensaje" : ":",
"prefijoMensajes" : { "prefijoMensajes" : {
"mapa":"map", "mapa":"map",
"pedido":"ped", "pedido":"ped",
"posicion":"pos" "posicion":"pos",
"sinc" : "Sincronizar"
} }
} }
\ No newline at end of file
...@@ -2,9 +2,37 @@ ...@@ -2,9 +2,37 @@
from robot import Robot from robot import Robot
import camino import camino
from camino import MovGiro as mov from camino import MovGiro as mov
from umqtt.robust import MQTTClient
import conexion as cn
def sub_cp(topic, msg):
print("Recibido topic", topic.decode(), " mensage ", msg.decode())
subs = ["A3-467/GrupoL/Robot","A3-467/GrupoL/SincRobot"]
send = ["A3-467/GrupoL/Interfaz","A3-467/GrupoL/SincInterfaz"]
#cx = cn.Conexion(subs,on_msg=sub_cp)
#cx.publicar(send[0],"BBBBBBBBBB")
cx = cn.Conexion(subs,sub_cp)
print("Creado")
while True:
cx.checkMensages()
"""
import mensajeRobot as m
mR = m.MensajeRobot()
print("creada conexion")
mapa = mR.getMapa()
print(mapa)
pos = (4,4)
mR.sendPosicion(pos)
"""
"""
robot = Robot() robot = Robot()
mapa = "0202000105030705000200041109060110031000000200080101100110000106010701" mapa = "0202000105030705000200041109060110031000000200080101100110000106010701"
#robot.calibraSensorColor() #robot.calibraSensorColor()
...@@ -15,3 +43,4 @@ robot.recorreRuta(mov,cas) ...@@ -15,3 +43,4 @@ robot.recorreRuta(mov,cas)
robot.recogePaquete() robot.recogePaquete()
"""
\ No newline at end of file
#from typing import Any #from typing import Any
import conexion as cn import conexion as cn
import time import time
import json import ujson
class MensajeRobot: class MensajeRobot:
def __init__(self) -> None: def __init__(self) -> None:
def on_message(client, userdata, message): print("Inicizlizando")
print(f'Recive Topic:{message.topic} Mensage:{str(message.payload.decode("utf-8"))}')
if(message.topic == self.topicSubs[-1]): def sub_cp(topic,msg):
if(str(message.payload.decode("utf-8")) != str(self.__class__)): print("Recibido topic", topic, " mensage ", msg)
if(topic == self.topicSubs[-2]):
self.sinc = True self.sinc = True
else: else:
self.mensaje = str(msg.decode('utf-8'))
def on_message_default(client,userdata,message):
#print(f'Recive Topic:{message.topic} Mensage:{str(message.payload.decode("utf-8"))}')
self.mensaje = str(message.payload.decode("utf-8")) self.mensaje = str(message.payload.decode("utf-8"))
if(self.mensaje.split(self.sepMsg)[0] != self.prefMsg['mapa']):
print("EL MAPA EL MAPA EL MAPA")
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")))
#if(message.topic == self.topicSubs[-1]):
# if(str(message.payload.decode("utf-8")) != str(self.__class__)):
# self.sinc = True
#else:
# self.mensaje = str(message.payload.decode("utf-8"))
with open(file="conexionConfig.json",mode='r') as f: with open("conexionConfig.json",'r') as f:
data = json.load(f) data = ujson.load(f)
#self.topicSubs = ["A3-467/GrupoL/Robot"] #self.topicSubs = ["A3-467/GrupoL/Robot"]
self.topicSubs = data['topicSubsRobot'] self.topicSubs = data['topicSubsRobot']
#print(f'Topics a subscribir {self.topicSubs}')
#self.topicSend = ["A3-467/GrupoL/Interfaz"] #self.topicSend = ["A3-467/GrupoL/Interfaz"]
self.topicSend = data['topicSendRobot'] self.topicSend = data['topicSendRobot']
#print(f'Topics a enviar {self.topicSend}')
#self.prefMsg = {"mapa":'map', #self.prefMsg = {"mapa":'map',
# "pedido":'ped', # "pedido":'ped',
...@@ -34,39 +55,58 @@ class MensajeRobot: ...@@ -34,39 +55,58 @@ class MensajeRobot:
self.prefMsg = data['prefijoMensajes'] self.prefMsg = data['prefijoMensajes']
self.sepMsg = data['separadorMensaje'] self.sepMsg = data['separadorMensaje']
self.conex = cn.Conexion(self.topicSubs,on_msg=on_message) defs = [on_message_default,on_message_sinc]
self.conex = cn.Conexion(self.topicSubs,on_msg=sub_cp)
self.mensaje = "" self.mensaje = ""
print("sincronizando")
self.sinc = False self.sinc = False
self.__sincronizacion() self.__sincronizacion()
#self.sinc = True
def __sincronizacion(self): def __sincronizacion(self):
while(not self.sinc): while(not self.sinc):
self.conex.publicar(self.topicSubs[-1],str(self.__class__)) self.conex.publicar(self.topicSend[-1],self.prefMsg['sinc'])
time.sleep(5) time.sleep(2)
print("SINCRONIZADO")
self.conex.desubscribir(self.topicSubs[-1]) self.conex.desubscribir(self.topicSubs[-1])
self.conex.publicar(self.topicSubs[-1],str(self.__class__)) self.conex.publicar(self.topicSend[-1],self.prefMsg['sinc'])
def getMapa(self): def getMapa(self):
while(self.mensaje.split(self.sepMsg)[0] != self.prefMsg['mapa']): while(self.mensaje.split(self.sepMsg)[0] != self.prefMsg['mapa']):
time.sleep(1) time.sleep(2)
return self.mensaje.split(self.sepMsg)[1] return self.mensaje.split(self.sepMsg)[1]
def getPedido(self): def getPedido(self):
self.conex.publicar(self.topicSend,self.prefMsg['pedido'] + self.sepMsg) self.conex.publicar(self.topicSend[0],self.prefMsg['pedido'] + self.sepMsg)
while(self.mensaje.split(self.sepMsg)[0] != self.prefMsg['pedido']): while(self.mensaje.split(self.sepMsg)[0] != self.prefMsg['pedido']):
print(f"Esperando Pedido - {self.mensaje.split(self.sepMsg)[0],self.prefMsg['pedido']}") #print(f"Esperando Pedido - {self.mensaje.split(self.sepMsg)[0],self.prefMsg['pedido']}")
time.sleep(1) time.sleep(1)
return self.mensaje.split(self.sepMsg)[1] ped = []
pos = []
i = 0
for c in self.mensaje.split(self.sepMsg)[1]:
pos.append(int(c))
if( i%2 == 1):
ped.append(pos)
pos = []
i = i+1
return ped
def sendPosicion(self,posicion): def sendPosicion(self,posicion):
self.conex.publicar(self.topicSend,self.prefMsg['posicion'] + self.sepMsg + str(posicion)) self.conex.publicar(self.topicSend[0],self.prefMsg['posicion'] + self.sepMsg + str(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