0

Mi problema es que Unity no lee ni procesa toda la información de otro software, que en este caso es Anylogic, como se puede ver en las fotos, el print de ambos software no coincide, print que muestra la informacion enviada (por Anylogic) y la recibida (por Unity), también muestro el código UDP en Unity, si es necesario también puedo enviar el código UDP realizado en Anylogic. PRINT ANYLOGIC PRINT UNITY

hat using UnityEngine;
using System.Collections;
 
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Globalization;
using UnityEditor;
using static JSONReader;

[Serializable]
public class RealTimeItem
{
public GameObject Object;
public int NetID;
public Vector3 Position;
public Vector3 Target;
public float TimeReach;
public float TimeReachNext;
public bool change;

public Agente agent;
}
public class UDPClient : MonoBehaviour
{
public List<RealTimeItem> items;


public static UDPClient instance;
public int portListen = 4444;
public string ipSend = "";
public int portSend = 5555;

public GameObject[]  notifyObjects;
public string messageToNotify;

private string received = "";

private UdpClient client;
private Thread receiveThread;
private IPEndPoint remoteEndPoint;
private IPAddress ipAddressSend;

public float TimeStamp = 1;

public bool SetData(Agente ag)
{
    if (getObjWithID(ag.id) == null) return false;
    RealTimeItem itemUse = items[GetID(ag.id)];
    int id = Convert.ToInt32(ag.id);

    GameObject obj = getObjWithID(id);

    /*
    if (ag.coordenadas.Count > (ag.coordenadas.Count - 2))
    { 
        itemUse.Position = ag.coordenadas[ag.coordenadas.Count - 2]; 
    }
    */

    itemUse.Position = ag.coordenadas[ag.coordenadas.Count - 1];
    itemUse.Target = ag.coordenadas[ag.coordenadas.Count - 1];

    itemUse.TimeReach = ag.tiempos[ag.tiempos.Count - 1];
    itemUse.TimeReachNext = ag.tiempos[ag.tiempos.Count - 1];
    itemUse.change = true;


//  Debug.LogError("Checking: " + itemUse.NetID + "|||AGID: " + ag.id);
    //  obj.transform.position = itemUse.Position;
    return true;
    
}

private void FixedUpdate()
{
    foreach(var xItem in items)
    {
    //  xItem.Object.transform.position = Vector3.MoveTowards(xItem.Object.transform.position, xItem.Position, TimeStamp * Time.deltaTime);
    //  xItem.Object.transform.LookAt(xItem.Target);
    }
}

public int GetID(int SearchID)
{
    foreach (var item in items)
    {
        if (item.NetID.Equals(SearchID)) return items.IndexOf(item);
    }
        return 0;
}

public GameObject getObjWithID(int SearchID)
{
    foreach (var item in items)
    {
        if (item.NetID.Equals(SearchID)) return item.Object;
    }

    return null;
}


public void Awake ()
{
    instance = this;

    //Check if the ip address entered is valid. If not, sendMessage will broadcast to all ip addresses 
    IPAddress ip;
    if (IPAddress.TryParse (ipSend, out ip)) {

        remoteEndPoint = new IPEndPoint (ip, portSend);

    } else {

        remoteEndPoint = new IPEndPoint (IPAddress.Broadcast, portSend);

    }

    //Initialize client and thread for receiving

    client = new UdpClient (portListen);

    receiveThread = new Thread (new ThreadStart (ReceiveData));
    receiveThread.IsBackground = true;
    receiveThread.Start ();
    
}

void Update ()
{


    //Check if a message has been recibed
    if (received != ""){

        Debug.Log("UDPClient: message received \'" + received + "\'");

        //Notify each object defined in the array with the message received
        foreach (GameObject g in notifyObjects)
        {
            g.SendMessage(messageToNotify, received, SendMessageOptions.DontRequireReceiver);

        }
        //Clear message
        received = "";
    }
}

//Call this method to send a message from this app to ipSend using portSend
public void SendValue (string valueToSend)
{
    try {
        if (valueToSend != "") {

            //Get bytes from string
            byte[] data = Encoding.UTF8.GetBytes (valueToSend);

            // Send bytes to remote client
            client.Send (data, data.Length, remoteEndPoint);
            Debug.Log ("UDPClient: send \'" + valueToSend + "\'");
            //Clear message
            valueToSend = "";

        }
    } catch (Exception err) {
        Debug.LogError ("Error udp send : " + err.Message);
    }
}

//This method checks if the app receives any message
public void ReceiveData ()
{

    while (true) {

        try {
            // Bytes received
            IPEndPoint anyIP = new IPEndPoint (IPAddress.Any, 0);
            byte[] data = client.Receive (ref anyIP);

            // Bytes into text
            string text = "";
            text = Encoding.UTF8.GetString (data);

            received = text;        
   
        } catch (Exception err) {
            Debug.Log ("Error:" + err.ToString ());
        }
    }
}
    
//Exit UDP client
public void OnDisable ()
{
    if (receiveThread != null) {
            receiveThread.Abort ();
            receiveThread = null;
    }
    client.Close ();
    Debug.Log ("UDPClient: exit");
}
    
}

No probé cambiando nada hasta este momento, porque soy inexperto en esta área, pero funcionaba bien hasta que puse una biblioteca en Anylogic, tal vez ese sea el problema, pero no estoy seguro, así que cualquier cosa será bienvenido, y mis resultados esperados son que se procese toda la información por segundo y se lea toda y como debería de ser.

ACTUALIZACIÓN En la función ReceiveData luego de la línea received = text; se colocó el print Debug.Log("UDPClient: message received \'" + received + "\'"); y este mismo se borró de la funcion Update, Y se descubrió que los print coinciden totalmente, ahora la pregunta y la duda de este post es, donde está el error que no permite la actualización de los datos siendo que estos son leídos por el Unity de manera correcta.

10
  • Que es lo no coincide ??
    – Yussef
    el 3 ene. 2023 a las 15:48
  • @Yussef De hecho, para darte un ejemplo de la misma imagen, en la de Anylogic (que es la de fondo blanco), se ve como por cada segundo hay una información de datos distinta para el "Worker", sin embargo, Unity recibe la informacion del "Worker" en los segundos 1, 3 y 6, al menos esos se ven. Los print son la información que es enviada (Anylogic) y la recibida (Unity)
    – ambioss
    el 3 ene. 2023 a las 15:59
  • Sigo sin ver la diferencia....te refieres al orden en que llega la información?
    – Yussef
    el 3 ene. 2023 a las 16:11
  • ¿No crees que sea algo normal del protocolo? TCP se asegura que el mensaje llegue por eso es más lento. UDP simplemente envía el mensaje
    – Mateo
    el 3 ene. 2023 a las 16:15
  • @Mateo He recibido varias respuestas en varios foros, y casi todas apuntan a que es algo netamente del protocolo UDP ,pero quería asegurar si era eso u otra cosa, quizás la solución sea cambiar a TCP.
    – ambioss
    el 3 ene. 2023 a las 16:22

1 respuesta 1

0

Tú tienes: ReceiveData y Update, estas 2 funciones corren por separado en paralelo, pero no a la misma velocidad.

Tu ocupas la variable received para comunicar a Update lo obtenido en ReceiveData, pero resulta que está variable puede ser cambiada muchas veces antes que entre el siguiente frame del Update

La solución es crear una cola que te sirva de buffer

Queue<string> Cola = new Queue<string>();
void Update ()
{

    while(Cola.Count>0){
        var reciev = Cola.Dequeue();

        Debug.Log("UDPClient: message received \'" + reciev + "\'");

        //Notify each object defined in the array with the message received
        foreach (GameObject g in notifyObjects)
        {
            g.SendMessage(messageToNotify, reciev , SendMessageOptions.DontRequireReceiver);

        }
   
    }
}

public void ReceiveData ()
{

    while (true) {

        try {
            // Bytes received
            IPEndPoint anyIP = new IPEndPoint (IPAddress.Any, 0);
            byte[] data = client.Receive (ref anyIP);

            Cola.Enqueue( Encoding.UTF8.GetString (data));    
   
        } catch (Exception err) {
            Debug.Log ("Error:" + err.ToString ());
        }
    }
}
0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.