Some trst implementation for REST.

Final websocket functions (register modules and clients, send capabilities, poses, cache system fow WS...)

Merge request reports

Loading
+94
Changes for server/worldanalysis/src/ETSI.ARF.OpenAPI.WorldAnalysis/ETSI-ARF/ControllersImpl/CapabilitiesImpl.cs: 94 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
// ARF - Augmented Reality Framework (ETSI ISG ARF)
//
// Copyright 2024 ETSI
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Last change: June 2024
//

/*
 * World Analysis API
 *
 * API ensuring interoperability between Scene Management and a World Analysis service
 *
 * The version of the OpenAPI document: 2.0.1
 * 
 * Generated by: https://openapi-generator.tech
 */

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using ETSI.ARF.OpenAPI.WorldAnalysis.Attributes;
using ETSI.ARF.OpenAPI.WorldAnalysis.Models;

namespace ETSI.ARF.OpenAPI.WorldAnalysis.Controllers
{ 
    /// <summary>
    /// 
    /// </summary>
    [ApiController]
    public class CapabilitiesApiControllerImpl : CapabilitiesApiController
    { 
        /// <summary>
        /// Get the supported capabilities of the World Analysis
        /// </summary>
        public override IActionResult GetCapabilities([FromHeader (Name = "token")]string token, [FromHeader (Name = "sessionID")]string sessionID)
        {
            if (!Startup.IsAccessGranted(token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            // Get all capabilities from all anchors/trackables
            // Info: Capabilities are collected after a module is connected via websockets

            // Create list
            List<Capability> capabilitiesList = new List<Capability>();
            capabilitiesList.AddRange(WorldAnalysisConnections.Singleton.GetCapabilities());

            // Create response object
            GetCapabilities200Response response = new GetCapabilities200Response();
            response.Capabilities = capabilitiesList;
            return new ObjectResult(response);
            //return StatusCode(405, "Not supported yet!");
        }

        /// <summary>
        /// For a given trackable or anchor, get its support information
        /// </summary>
        public override IActionResult GetSupport([FromRoute (Name = "trackableOrAnchorUUID")][Required]Guid trackableOrAnchorUUID, [FromHeader (Name = "token")]string token, [FromHeader (Name = "sessionID")]string sessionID)
        {
            if (!Startup.IsAccessGranted(token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            // Create list
            List<Capability> capabilitiesList = new List<Capability>();
            capabilitiesList.AddRange(WorldAnalysisConnections.Singleton.GetCapabilitiesFromUuid(trackableOrAnchorUUID));

            // Create response object
            GetSupport200Response response = new GetSupport200Response();
            response.Capabilities = capabilitiesList;
            return new ObjectResult(response); 
            //return StatusCode(405, "Not supported yet!");
        }
    }
}
+173
Changes for server/worldanalysis/src/ETSI.ARF.OpenAPI.WorldAnalysis/ETSI-ARF/ControllersImpl/DefaultImpl.cs: 173 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
// ARF - Augmented Reality Framework (ETSI ISG ARF)
//
// Copyright 2024 ETSI
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Last change: June 2024
//

/*
 * ETSI ARF Core System API
 *
 * API ensuring interoperability between the various services, tools and apps in ARF
 *
 * The version of the OpenAPI document: 2.0.1
 * 
 * Generated by: https://openapi-generator.tech
 */

using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using ETSI.ARF.OpenAPI.WorldAnalysis.Attributes;
using ETSI.ARF.OpenAPI.WorldAnalysis.Models;
//using ETSI.ARF.OpenAPI.WorldAnalysis.Services;

namespace ETSI.ARF.OpenAPI.WorldAnalysis.Controllers
{
#pragma warning disable CS1591 // Fehlendes XML-Kommentar fr ffentlich sichtbaren Typ oder Element
    /// <summary>
    /// 
    /// </summary>
    public class DefaultApiControllerImpl : DefaultApiController
    {
        public override IActionResult GetPing()
        {
            string answer = "Pong";
            return new ObjectResult(answer);
        }

        public override IActionResult GetAdmin()
        {
            string answer = "ETSI ARF World Analysis Server is running.";
            return new ObjectResult(answer);
        }

        public override IActionResult GetVersion()
        {
            string answer = "ETSI ARF RESTful API v" + Startup.apiVersion;
            return new ObjectResult(answer);
        }

        [NonAction]
        private string writeMsg(string title, string msg)
        {
            return $"<p>{title}: \t {msg}</p>";
        }

        [NonAction]
        public /*override*/ IActionResult GetReport()
        {
            string projectName = "ETSI ARF - STF 669";
            string machinename = System.Environment.MachineName;
            string hostname = Dns.GetHostName();
            var ips = Dns.GetHostAddresses(hostname);

            string status = "Running";
            string mongoStatus = "Running";
            //string mongoCollectionUsers = "Number = " + UserService.Singleton?.NumOfDocuments();
            //string mongoCollectionMachines = "Number = " + MachineService.Singleton?.NumOfDocuments();
            //string mongoCollectionAssets = "Number = " + AssetService.Singleton?.NumOfDocuments();
            //string mongoCollectionJobs = "Number = " + JobService.Singleton?.NumOfDocuments();

            //List<User> users = UserService.Singleton?.Get();
            //int activeU = 0;
            //int nonActiveU = 0;
            //foreach (var u in users)
            //    if (u.IsLogged) activeU++;
            //    else nonActiveU++;

            //List<Job> jobs = JobService.Singleton?.Get();
            //int jobNum = 0;
            //foreach (var j in jobs)
            //    if (j.Progress != 100) jobNum++;

            //
            // Simple output
            //
            string html = "<!DOCTYPE html> <html>" +
                "<head>" +
                " <title>SmartSiteCloud</title>" +
                "</head>" +
                "<body>" +
                " <h1>SmartSite Cloud</h1>" +
                " <h2>Server based on IIS/ASP.NET</h1>" +
                   writeMsg("Local Date & Time:", DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString()) +
                   writeMsg("Machine Name", machinename) + writeMsg("Host Name", hostname) + writeMsg("IPv6", ips[0].ToString()) +
                " <h3>Services</h3>" +
                   writeMsg("WebServer", status) +
                   writeMsg("MongoDB", mongoStatus) +
                   //writeMsg(" > Users", mongoCollectionUsers) +
                   //writeMsg(" > Machines", mongoCollectionMachines) +
                   //writeMsg(" > Assets", mongoCollectionAssets) +
                   //writeMsg(" > Jobs", mongoCollectionJobs) +
                " <h2>Database</h1>" +
                //" <h3>Users</h1>" +
                //   writeMsg(" - Active", activeU.ToString()) +
                //   writeMsg(" - Non active", nonActiveU.ToString()) +
                //" <h3>Jobs</h1>" +
                //   writeMsg(" - Running jobs", jobNum.ToString()) +
                "</body></html> ";

            //
            // Complex output (for RocketCake)
            //            
            // always use https
            //string domainName = (HttpContext.Request.IsHttps ? "https://" : "https://") + HttpContext.Request.Host.ToUriComponent() + "/portal"; // Ex: "https://localhost:44301/portal"
            //string root = Path.Combine(Startup.wPath, "portal");
            //string htmlFname = Path.Combine(root, "status.html");
            //string[] template = System.IO.File.ReadAllLines(htmlFname);
            //string html2 = "";

            //string msg1 =
            //   writeMsg("Domain", domainName) +
            //   writeMsg("Project", projectName) +
            //   writeMsg("Local Date", DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString()) +
            //   writeMsg("Machine Name", machinename) + writeMsg("Host Name", hostname) + writeMsg("IPv6", ips[0].ToString());
            //string msg2 =
            //    writeMsg("WebServer", status) +
            //    writeMsg("MongoDB", mongoStatus) +
            //    //writeMsg(" > Users", mongoCollectionUsers) +
            //    //writeMsg(" > Machines", mongoCollectionMachines) +
            //    //writeMsg(" > Assets", mongoCollectionAssets) +
            //    //writeMsg(" > Jobs", mongoCollectionJobs) +
            //    writeMsg("MinIO", "-");


            //foreach (var line in template)
            //{
            //    string res = line;
            //    res = res.Replace("src=\"", "src=\"" + domainName + "/");
            //    res = res.Replace("href=\"", "href=\"" + domainName + "/");
            //    res = res.Replace("$name1$", projectName);
            //    res = res.Replace("$msg1$", msg1);
            //    res = res.Replace("$msg2$", msg2);
            //    html2 += res;
            //}

            return Content(html, "text/html");
            //return Content(html2, "text/html");
        }
    }
#pragma warning restore CS1591 // Fehlendes XML-Kommentar fr ffentlich sichtbaren Typ oder Element
}
+253
Changes for server/worldanalysis/src/ETSI.ARF.OpenAPI.WorldAnalysis/ETSI-ARF/ControllersImpl/PoseImpl.cs: 253 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
// ARF - Augmented Reality Framework (ETSI ISG ARF)
//
// Copyright 2024 ETSI
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Last change: June 2024
//

/*
 * World Analysis API
 *
 * API ensuring interoperability between Scene Management and a World Analysis service
 *
 * The version of the OpenAPI document: 2.0.1
 * 
 * Generated by: https://openapi-generator.tech
 */

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using ETSI.ARF.OpenAPI.WorldAnalysis.Attributes;
using ETSI.ARF.OpenAPI.WorldAnalysis.Models;

namespace ETSI.ARF.OpenAPI.WorldAnalysis.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [ApiController]
    public class PoseApiControlleImpl : PoseApiController
    {
        /// <summary>
        /// Specify the a minimum frame rate for pose estimation for Trackable types
        /// </summary>
        public override IActionResult ConfigureFramerate([FromBody] PoseConfiguration poseConfiguration, [FromHeader(Name = "token")] string token, [FromHeader(Name = "sessionID")] string sessionID)
        {
            if (!Startup.IsAccessGranted(token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            // Notify the modules that the client need a new framerate
            bool result = WorldAnalysisConnections.Singleton.ConfigureFramerate(poseConfiguration);
            return result ? StatusCode(200, "Ok.") : StatusCode(405, "Not supported.");
        }

        /// <summary>
        /// Request the last pose of a single Anchor or Trackable
        /// </summary>
        public override IActionResult GetPose([FromRoute(Name = "trackableOrAnchorUUID")][Required] Guid trackableOrAnchorUUID, [FromQuery(Name = "mode")][Required()] ModeWorldAnalysis mode, [FromHeader(Name = "token")] string token, [FromHeader(Name = "sessionID")] string sessionID)
        {
            if (!Startup.IsAccessGranted(token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            // Request from the modules a new pose of a single UUID
            Pose result;
            result = WorldAnalysisConnections.Singleton.GetPose(trackableOrAnchorUUID, mode);
            return new ObjectResult(result);
        }

        /// <summary>
        /// Request the last pose of a batch of Anchor or Trackable
        /// </summary>
        public override IActionResult GetPoses([FromQuery(Name = "uuid")][Required()] List<UuidAndMode> uuid, [FromHeader(Name = "token")] string token, [FromHeader(Name = "sessionID")] string sessionID)
        {
            if (!Startup.IsAccessGranted(token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            // Request from the modules new poses from all UUIDs
            GetPoses200Response result = new GetPoses200Response();
            foreach (var item in uuid)
            {
                result.Poses.Add(WorldAnalysisConnections.Singleton.GetPose(item.Uuid, item.Mode));
            }
            return new ObjectResult(result);
        }

#pragma warning disable CS1591 // Fehlendes XML-Kommentar fr ffentlich sichtbaren Typ oder Element

        //
        // Management of subscriptions
        //
        /// <summary>
        /// Dictionnary of susbscription informations for poses, for each item, stored using the UUID of the item (anchor/trackable)
        /// </summary>
        private Dictionary<Guid, SubscriptionInfo> m_subscriptionsPoses = new Dictionary<Guid, SubscriptionInfo>();

        public struct SubscriptionInfo
        {
            public Guid uuidSub;           // id of subscription (id is defined by the WA server)

            public SubscribeToPoseRequest subscription;
            public string webSocket;
            public Pose pose;
            public DateTime timeValidity;

            //public PoseCallback callback;
        }
#pragma warning restore CS1591 // Fehlendes XML-Kommentar fr ffentlich sichtbaren Typ oder Element

        /// <summary>
        /// Get information about a subscription
        /// </summary>
        public override IActionResult GetSubscription([FromRoute(Name = "subscriptionUUID")][Required] Guid subscriptionUUID, [FromHeader(Name = "token")] string token, [FromHeader(Name = "sessionID")] string sessionID)
        {
            if (!Startup.IsAccessGranted(token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            // todo: search for a subscription and send it back
            foreach (var item in m_subscriptionsPoses)
            {
                if (item.Key == subscriptionUUID)
                {
                    SubscriptionSingle response = new SubscriptionSingle();
                    response.Uuid = subscriptionUUID;
                    response.Target = item.Value.subscription.Target;
                    response.Mode = item.Value.pose.Mode;
                    response.Validity = item.Value.timeValidity.Millisecond;
                    response.WebhookUrl = item.Value.subscription.WebhookUrl;
                    response.WebsocketUrl = item.Value.webSocket;
                    return new ObjectResult(response);
                }
            }
            return StatusCode(404, "Not found.");
        }

        /// <summary>
        /// Subscribe to collect the pose of an AR device, an Anchor or a Trackable
        /// </summary>
        public override IActionResult SubscribeToPose([FromBody] SubscribeToPoseRequest subscribeToPoseRequest, [FromHeader(Name = "token")] string token, [FromHeader(Name = "sessionID")] string sessionID)
        {
            // Simulation ON for STF669 pose calcualtion
            string _token = token;
            Guid parentUUID = Guid.Empty;
            if (token.Contains(","))
            {
                _token = token.Split(',')[0];
                parentUUID = new Guid(token.Split(',')[1]);
            }

            if (!Startup.IsAccessGranted(_token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            if (subscribeToPoseRequest.Targets != null && subscribeToPoseRequest.Targets.Count > 0)
            {
                return StatusCode(404, "Multiple subscriptions are not implemented (targets).");
            }
            else if (subscribeToPoseRequest.Modes != null && subscribeToPoseRequest.Modes.Count > 0)
            {
                return StatusCode(404, "Multiple subscriptions are not implemented (modes).");
            }

            int validity = subscribeToPoseRequest.Validity; // todo: is to handle here or by the client?

            SubscribeToPose200Response response = new SubscribeToPose200Response();
            response.Validity = validity;
            response.Uuid = Guid.NewGuid();
            response.Target = subscribeToPoseRequest.Target;
            response.Mode = subscribeToPoseRequest.Mode;
            response.WebhookUrl = subscribeToPoseRequest.WebhookUrl;
            response.WebsocketUrl = "";

            // Send the websocket connection URL
            if (string.IsNullOrEmpty(response.WebhookUrl))
            {
                // Notice: starting websocket server is done autom. by the client, when calling "URL:xxx/ws"
                // Registering the client is done in the analysis module, so the websocket can send to it pose updates
                response.WebsocketUrl = "wss://" + Request.Host.ToString() + "/ws";
            }

            // We add the subscription
            SubscriptionInfo info = new SubscriptionInfo();
            info.uuidSub = response.Uuid;
            info.webSocket = response.WebsocketUrl;
            info.timeValidity = DateTime.Now.AddMilliseconds(validity / 1000.0f);

            info.pose = new Pose();
            info.pose.Mode = response.Mode;

            info.subscription = new SubscribeToPoseRequest();
            info.subscription.Target = response.Target;
            info.subscription.Mode = response.Mode;
            info.subscription.Validity = response.Validity;
            info.subscription.WebhookUrl = response.WebhookUrl;

            m_subscriptionsPoses.Add(info.uuidSub, info);
            
            // todo: inform the module(s) that the client will track an anchor/trackable and need the pose
            // todo: has the module to call GetRelocalizationInformation() then?!?
            WorldAnalysisConnections.Singleton.SubscribeToPose(info, parentUUID);

            return new ObjectResult(response);
        }

        /// <summary>
        /// Remove a subscription to a given pose
        /// </summary>
        public override IActionResult UnsubscribeFromPose([FromRoute(Name = "subscriptionUUID")][Required] Guid subscriptionUUID, [FromHeader(Name = "token")] string token, [FromHeader(Name = "sessionID")] string sessionID)
        {
            if (!Startup.IsAccessGranted(token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            // Remove the subscription from the list?
            if (m_subscriptionsPoses.ContainsKey(subscriptionUUID)) m_subscriptionsPoses.Remove(subscriptionUUID);
            else
            {
                //return StatusCode(404, new Error() { Message = "Unsubscribe UUID not found!" });
            }

            // Inform the module(s) that the subscription ended
            WorldAnalysisConnections.Singleton.UnsubscribeFromPose(subscriptionUUID);

            return StatusCode(200, new Success() { Message = "Unsubscription successfull." });
        }

        /// <summary>
        /// Update a subscription
        /// </summary>
        public override IActionResult UpdateSubscription([FromRoute(Name = "subscriptionUUID")][Required] Guid subscriptionUUID, [FromBody] UpdateSubscriptionRequest updateSubscriptionRequest, [FromHeader(Name = "token")] string token, [FromHeader(Name = "sessionID")] string sessionID)
        {
            if (!Startup.IsAccessGranted(token)) return StatusCode(511, new Error() { Message = "Invalid token!" });

            // todo: compare sessionID

            // todo: inform the module(s) that the subscription changed

            return StatusCode(405, "Not supported yet!");
        }
    }
}
+378
Changes for server/worldanalysis/src/ETSI.ARF.OpenAPI.WorldAnalysis/ETSI-ARF/ControllersImpl/WebSocketController.cs: 378 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
// ARF - Augmented Reality Framework (ETSI ISG ARF)
//
// Copyright 2024 ETSI
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Last change: June 2024
//

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Net.WebSockets;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;

using ETSI.ARF.OpenAPI.WorldAnalysis.Models;

#pragma warning disable CS1591 // Fehlendes XML-Kommentar fr ffentlich sichtbaren Typ oder Element
namespace ETSI.ARF.OpenAPI.WorldAnalysis.Controllers
{
    //
    // ETSI-ARF World Analysis WebSocket implementation
    // see also: https://learn.microsoft.com/de-de/aspnet/core/fundamentals/websockets?view=aspnetcore-5.0
    //
    public class WebSocketController : ControllerBase
    {
        private WebSocket websocket;
        static public int WebSocketControllerInstanceCount = 0;

        private string currentName = "";
        private bool registered = false;
        private bool firstTime = true;
        private int timeCnt = 3;

        [HttpGet("/ws")]
        public async Task Get()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();

                if (webSocket.State == WebSocketState.Connecting)
                {
                    // Response an OK message?
                }
                else if (webSocket.State == WebSocketState.Open)
                {
                    // Go to the loop...
                    await WebSocketServer_Loop(HttpContext, webSocket);
                }
            }
            else
            {
                await HttpContext.Response.WriteAsync("ETSI-ARF World Analysis: Not a valid WebSocket request.");
                HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
        }

        //
        // Send a line of text
        //
        static private async Task SendText(WebSocket ws, string msg)
        {
            var message = msg;
            var bytes = Encoding.UTF8.GetBytes(message);
            var arraySegment = new ArraySegment<byte>(bytes, 0, bytes.Length);
            await ws.SendAsync(arraySegment, WebSocketMessageType.Text, true, CancellationToken.None);
        }

        public void SendText(string msg)
        {
            var message = msg;
            var bytes = Encoding.UTF8.GetBytes(message);
            var arraySegment = new ArraySegment<byte>(bytes, 0, bytes.Length);
            websocket.SendAsync(arraySegment, WebSocketMessageType.Text, true, CancellationToken.None);
        }

        //
        // Send a demo pose all seconds
        //
        float rotInc = 0;
        private async Task SendDemoPose(WebSocket ws)
        {
            while (true)
            {
                if (ws.State == WebSocketState.Open)
                {
                    timeCnt--;
                    if (timeCnt < 0)
                    {
                        await SendText(ws, "PoseStop");
                        break;
                    }
                    else
                    {
                        PoseValue val = new PoseValue();
                        val.Unit = UnitSystem.MEnum;
                        val.Position = new List<float>() { 1, 2, 3 };
                        val.Rotation = new List<float>() { rotInc, 0, 0, 0 };
                        rotInc += 0.01f;

                        Pose pose = new Pose();
                        pose.Uuid = new Guid();
                        pose.EstimationState = Pose.EstimationStateEnum.OKEnum;
                        //pose.SubscriptionUrl = "";
                        pose.Value = val;
                        pose.Timestamp = (int)DateTime.Now.ToFileTime();
                        pose.Confidence = 1;
                        pose.Mode = ModeWorldAnalysis.DEVICETOTRACKABLESEnum;

                        string json = pose.ToJson();

                        await SendText(ws, "NewPose=" + json);
                    }
                }
                else if (ws.State == WebSocketState.Closed || ws.State == WebSocketState.Aborted)
                {
                    if (WorldAnalysisConnections.Singleton.modules.Contains(currentModule)) WorldAnalysisConnections.Singleton.modules.Remove(currentModule);
                    if (WorldAnalysisConnections.Singleton.clients.Contains(currentClient)) WorldAnalysisConnections.Singleton.clients.Remove(currentClient);
                    currentClient = null;
                    currentModule = null;
                    break;
                }
                Thread.Sleep(250);
            }
        }

        private Module currentModule;
        private Client currentClient;

        private async void OnReceiveText(string msg)
        {
            #region Register the client/module
            if (firstTime)
            {
                if (msg.StartsWith("RegisterModule="))
                {
                    registered = true;
                    firstTime = false;
                    currentName = msg.Split('=')[1];

                    // If module exist already reuse it
                    Module module = null;
                    foreach (var item in WorldAnalysisConnections.Singleton.modules) if (item.name == currentName) module = item;
                    if (module != null)
                    {
                        currentModule = module;
                        currentModule.name = currentName;
                        currentModule.websockets = this;
                        currentModule.capabilities.Clear();
                    }

                    if (currentModule == null && currentClient == null)
                    {
                        currentModule = new Module();
                        currentModule.name = currentName;
                        currentModule.websockets = this;
                        WorldAnalysisConnections.Singleton.modules.Add(currentModule);
                    }
                    SendText($"ARF World Analysis Server: #{ WebSocketControllerInstanceCount } You are now registered as module: { currentName }");
                }
                else if (msg.StartsWith("RegisterClient="))
                {
                    registered = true;
                    firstTime = false;
                    currentName = msg.Split('=')[1];
                    if (currentModule == null && currentClient == null)
                    {
                        currentClient = new Client();
                        currentClient.name = currentName;
                        currentClient.websockets = this;
                        WorldAnalysisConnections.Singleton.clients.Add(currentClient);
                        SendText($"ARF World Analysis Server: #{ WebSocketControllerInstanceCount } You are now registered as client: { currentName }");
                    }
                }
                else
                {
                    registered = false;
                    SendText("ARF World Analysis Server: Cannot register " + msg);
                }
                return;
            }
            #endregion

            if (registered)
            {
                //
                // Some admin stuffs
                //
                if (msg == "Idle")
                {
                    SendText("Idle");
                }
                else if (msg == "Busy")
                {
                    SendText("Busy");
                }
                else if (msg.StartsWith("UnregisterModule="))
                {
                    string name = msg.Split('=')[1];

                    // Unregister a client (e.g. Unity client)
                    Module module = null;
                    foreach (var item in WorldAnalysisConnections.Singleton.modules) if (item.name == name) module = item;
                    if (module != null)
                    {
                        WorldAnalysisConnections.Singleton.modules.Remove(module);
                        SendText("UnregisterModuleOK");
                    }
                    currentName = "";
                    firstTime = true;
                    registered = false;
                }
                else if (msg.StartsWith("UnregisterClient="))
                {
                    string name = msg.Split('=')[1];

                    // Unregister a client (e.g. Unity client)
                    Client client = null;
                    foreach (var item in WorldAnalysisConnections.Singleton.clients) if (item.name == name) client = item;
                    if (client != null)
                    {
                        WorldAnalysisConnections.Singleton.clients.Remove(client);
                        SendText("UnregisterClientOK");
                    }
                    currentName = "";
                    firstTime = true;
                    registered = false;
                }
                //
                // OpenAPI
                //
                else if (msg == "PoseIsNowSubscribed")
                {
                    SendText("RequestNextPose");
                }

                //
                // Messages from a module (Analysis)
                //
                else if (msg.StartsWith("Capabilities="))  // Receive capab. from a module
                {
                    // Module is sending their capabilities
                    string[] str_cap = msg.Split('=');
                    string moduleName = str_cap[1];
                    Capability _c = JsonConvert.DeserializeObject<Capability>(str_cap[2]);

                    // Has the module already send their capabilities?
                    Module module = null;
                    foreach (var item in WorldAnalysisConnections.Singleton.modules) if (item.name == moduleName) module = item;
                    if (module != null) module.capabilities.Add(_c);
                }
                else if (msg.StartsWith("NewPose="))
                {
                    string[] str_pose = msg.Split('=');

                    // Send the pose to the client(s)
                    Pose pose = JsonConvert.DeserializeObject<Pose>(str_pose[1]);

                    //WorldAnalysisConnections.Singleton.SendPoseToClients(pose);
                    WorldAnalysisConnections.Singleton.SendPoseToClients(str_pose[1]);

                    // todo: if there are some subscription ask modules for new pose
                    SendText("RequestNextPose");
                }
                else if (msg.StartsWith("Error="))
                {
                    string errorMsg = msg.Split('=')[1];
                    foreach (var item in WorldAnalysisConnections.Singleton.clients)
                    {
                        await SendText(item.websockets.websocket, errorMsg);
                    }
                }

                //
                // Messages from a client (Unity)
                //
                else if (msg.StartsWith("PoseStart")) // send some fake poses to Unity clients
                {
                    await SendDemoPose(websocket);
                }
                else if (msg.StartsWith("CurrentUserPose="))
                {
                    // A client (Unity) is sending the current user posistion

                    // Send new user pose to all modules
                    foreach (var item in WorldAnalysisConnections.Singleton.modules)
                    {
                        await SendText(item.websockets.websocket, msg);
                    }

                    //// Test: send user pose back to clients
                    //string[] str_pose = msg.Split('=');
                    //Pose pose = JsonConvert.DeserializeObject<Pose>(str_pose[1]);
                    //pose.Value.Position[2] += 1f;
                    //WorldAnalysisConnections.Singleton.SendPoseToClients(pose);
                }

                //
                // Messages from modules and clients
                //
                else
                {
                    // Send a response
                    SendText("ARF World Analysis Server: I got this unknown message: " + msg);
                }
            }
        }

        private async Task WebSocketServer_Loop(HttpContext context, WebSocket ws)
        {
            websocket = ws;
            WebSocketControllerInstanceCount++;

            var buffer = new byte[1024 * 4];

            // Read/get the first data block
            WebSocketReceiveResult result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            if (result.MessageType == WebSocketMessageType.Text)
            {
                string getMsg = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
                OnReceiveText(getMsg);
            }

            // Entering the loop
            while (!result.CloseStatus.HasValue)
            {
                // Read/get the next block
                result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    string getMsg = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
                    OnReceiveText(getMsg);
                }
            }
            await ws.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
            WebSocketControllerInstanceCount--;
        }


        //
        // Echo incoming messages
        //
        private async Task Echo(WebSocketReceiveResult context, WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];

            // Read/get the first data block
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

            // Send/echo the message back to the client
            await SendText(webSocket, "ARF World Analysis Server: I got this (raw) message: ");
            await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
        }
    }
}
#pragma warning restore CS1591 // Fehlendes XML-Kommentar fr ffentlich sichtbaren Typ oder Element

Empty file added.

Loading
Loading