Skip to content
Snippets Groups Projects
WorldAnalysisREST_WebSockets.cs 3.52 KiB
Newer Older
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ETSI.ARF.OpenAPI.WorldAnalysis;

using WebSocketSharp;
using static WorldAnalysisInterface;

//Implementation of the WorldAnalysis interface
public partial class WorldAnalysisREST
{
    //
    // Inspector variables
    //
    public StringEvent webSocketMessage;

    //
    // Private members
    //
    private WebSocketSharp.WebSocket webSocket;     // For WebSockets
    private bool websocketConnected = false;

    #region Communication system for WebSockets
    public WebSocket WebSocketClient_Create(string url)
    {
        webSocket = new WebSocketSharp.WebSocket(url);

        //
        // Define standard callbacks
        //
        webSocket.OnOpen += (sender, e) =>
        {
            Debug.Log("[WS] Connected");
            websocketConnected = true;
            webSocket.Send("RegisterClient:UnitySceneManagement");
        };
        webSocket.OnClose += (sender, e) =>
        {
            Debug.Log("[WS] Disconnected");
            websocketConnected = false;
        };
        webSocket.OnError += (sender, e) => Debug.Log("[WS] Error!");
        webSocket.OnMessage += (sender, e) => WebSocketClient_OnReceive(e.Data);
        webSocket.Connect();

        return webSocket;
    }

    private void WebSocketClient_Close()
    {
        if (websocketConnected)
        {
            webSocket.Send("UnregisterClient");
            webSocket.Close();
            webSocket = null;
        }
    }

    public void WebSocketClient_Send(string msg)
    {
        webSocket?.Send(msg);
    }

    bool isRegistered = false;
    public void WebSocketClient_OnReceive(string data)
    {
        //Debug.Log("[WS] Receiving: " + data);

        if (data.Contains("You are now registered"))
        {
            isRegistered = true;
            if (isDebug)
            {
                webSocket.Send("TimeStart:3"); // test                
            }
        }
        else if (isRegistered)
        {
            if (data.StartsWith("Time="))
            {
                // test the communication
                Debug.Log("[WS] Server time is: " + data.Split('=')[1]);
                webSocketMessage?.Invoke(data);
            }
            else if (data == "TimeStop")
            {
                // Get some dummy poses?
                //webSocket.Send("PoseStart:5"); // test
            }
            else if (data == "PoseStop")
            {
                //SetColor(Color.yellow);
            }
            else if (data.StartsWith("Pose=") && data.Contains("estimationState"))
            {
                // Handle the new pose
                string json = data.Substring("Pose=".Length);
                ETSI.ARF.OpenAPI.WorldAnalysis.Pose pose = JsonUtility.FromJson<ETSI.ARF.OpenAPI.WorldAnalysis.Pose>(json);
                Debug.Log("[WS][Pose] State: " + pose.EstimationState.ToString());
                
                // to check: p.Confidence
                // to check: p.Mode, p.Value 
                
                PoseEstimationResult res = pose.EstimationState == PoseEstimationState.OK ? PoseEstimationResult.OK : PoseEstimationResult.FAILURE;
                                
                // Look for the corresponding callbacks
                foreach (var item in m_subscriptionsPoses.Values)
                {
                    if (pose.Uuid == item.uuidTarget)
                    {
                        item.callback(res, pose);
                    }
                }
            }
        }
    }
    #endregion
}