Skip to content
Snippets Groups Projects
WorldAnalysisREST_WebSockets.cs 3.55 KiB
Newer Older
#define IS_HHI_LAN

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using WebSocketSharp;

using ETSI.ARF.OpenAPI.WorldAnalysis;
using static WorldAnalysisInterface;

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

    //
    // Private members
    //
    private WebSocketSharp.WebSocket webSocket = null;     // For WebSockets

    #region Communication system for WebSockets
    public WebSocket WebSocketClient_Create(string url)
    {
        if (webSocket != null) return webSocket;

        string _url = url;

#if IS_HHI_LAN
        _url = "ws://192.168.20.29:8084/ws";
        Debug.LogWarning("[WS] Changing the websocket URL to: " + _url + " (local network VM, HHI)");
#endif

        webSocket = new WebSocketSharp.WebSocket(_url);

        //
        // Define standard callbacks
        //
        webSocket.OnOpen += (sender, e) =>
        {
            Debug.Log("[WS] Connected");
            webSocket.Send("RegisterClient=" + modulename);
        };
        webSocket.OnClose += (sender, e) =>
        {
            Debug.Log("[WS] Disconnected");
        };
        webSocket.OnMessage += (sender, e) => WebSocketClient_OnReceive(e.Data);
        webSocket.OnError += (sender, e) => Debug.Log("[WS] Websocket error!");
        webSocket.Connect();

        return webSocket;
    }

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

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

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

        if (serverMessage.Contains("You are now registered"))
            Debug.Log($"[WS] {serverMessage }");
            //Debug.Log($"[WS] Registration of { modulename } was succesfull.");
            if (serverMessage == "PoseStop")
                //SetColor(Color.yellow);
            else if (serverMessage == "PoseIsNowSubscribed")
            else if (serverMessage == "PoseIsNowUnubscribed")
            else if (serverMessage.StartsWith("NewPose=") && serverMessage.Contains("estimationState"))
            {
                // Handle the new pose
                string _str = serverMessage.Substring("NewPose=".Length);
                ETSI.ARF.OpenAPI.WorldAnalysis.Pose pose = JsonConvert.DeserializeObject<ETSI.ARF.OpenAPI.WorldAnalysis.Pose>(_str);
                //Debug.Log("[WS] JSON - my new pose : " + pose.ToJson());

                // to check: p.Confidence?

                PoseEstimationResult res = pose.EstimationState == PoseEstimationState.OK ? PoseEstimationResult.OK : PoseEstimationResult.FAILURE;
                // Look for the corresponding callbacks
                foreach (var item in subscriptionsPoses.Values)
                    if (item.uuidTarget == pose.Uuid)
                        item.pose.Value = pose.Value;
            else webSocketMessage?.Invoke(serverMessage);