Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • arf/world-storage-api-helpers/unity-world-storage-package
1 result
Show changes
Commits on Source (8)
Showing
with 2376 additions and 229 deletions
//
// ARF - Augmented Reality Framework (ETSI ISG ARF)
//
// Copyright 2022 ETSI
// 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.
......
//
// 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: July 2024
//
using System.Collections;
using UnityEngine;
using UnityEditor;
using ETSI.ARF.OpenAPI;
using ETSI.ARF.WorldStorage;
using ETSI.ARF.WorldStorage.REST;
[CustomEditor(typeof(WorldStorageServer))]
public class WorldStorageServerEditor : Editor
{
WorldStorageServer server;
private string state = "";
private string version = "";
private string test = "";
private Queue handleResponseQueue = new Queue();
private ResponseObject<string> pendingTest = null;
private ResponseObject<string> pendingState = null;
private ResponseObject<string> pendingVersion = null;
public void OnEnable()
{
server = (WorldStorageServer)target;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawDefaultInspector();
EditorGUILayout.Space();
if (GUILayout.Button("Test server"))
{
TestPing();
}
EditorGUILayout.LabelField("Test Response", test);
EditorGUILayout.Space();
if (GUILayout.Button("Query server"))
{
QueryServer();
}
EditorGUILayout.LabelField("Server State", state);
EditorGUILayout.LabelField("OpenAPI Version", version);
if (handleResponseQueue.Count > 0)
{
object o = handleResponseQueue.Dequeue();
if (o.Equals(pendingTest))
{
ResponseObject<string> response = o as ResponseObject<string>;
Debug.Log($"Get '{response.result}' from server");
test = response.result;
pendingTest = null;
EditorUtility.SetDirty(target);
}
else if (o.Equals(pendingState))
{
ResponseObject<string> response = o as ResponseObject<string>;
Debug.Log($"Get '{response.result}' from server");
state = response.result;
pendingState = null;
EditorUtility.SetDirty(target);
}
else if (o.Equals(pendingVersion))
{
ResponseObject<string> response = o as ResponseObject<string>;
Debug.Log($"Get '{response.result}' from server");
version = response.result;
pendingVersion = null;
EditorUtility.SetDirty(target);
}
else
{
Debug.Log("Unsupported response!");
}
}
}
public override bool RequiresConstantRepaint()
{
return handleResponseQueue.Count > 0;
}
void OnSceneGUI()
{
Debug.Log("OnSceneGUI");
}
private void TestPing()
{
test = "";
EditorUtility.SetDirty(target);
if (server == null)
{
Debug.LogError("No server defined!");
return;
}
//string response = AdminRequest.PingSync(server);
//EditorUtility.DisplayDialog("Test Server", $"Get '{response}' from server", "OK");
if (pendingTest != null)
{
pendingTest.Cancel();
}
pendingTest = AdminRequest.PingAsync(server, (response) =>
{
handleResponseQueue.Enqueue(response);
Debug.Log($"Request Time: { response.requestTime.ToLongTimeString() } / Total Time: { response.DeltaTime.TotalMilliseconds }ms\n\n<b>Content:</b>\n{ response.result }");
});
Debug.Log("Starting request @ time: " + pendingTest.requestTime.ToLongTimeString() + "...");
}
private void QueryServer()
{
version = "";
state = "";
if (pendingState != null)
{
pendingState.Cancel();
}
pendingState = AdminRequest.AdminAsync(server, (response) =>
{
handleResponseQueue.Enqueue(response);
});
if (pendingVersion != null)
{
pendingVersion.Cancel();
}
pendingVersion = AdminRequest.VersionAsync(server, (response) =>
{
handleResponseQueue.Enqueue(response);
});
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: e5c9b5bdbeaab49729133f4ac17ded99
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
//
// ARF - Augmented Reality Framework (ETSI ISG ARF)
//
// Copyright 2022 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 2022
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using ETSI.ARF.WorldStorage;
[CustomEditor(typeof(WorldStorageUser))]
public class WorldStorageUserEditor : Editor
{
WorldStorageUser user;
public void OnEnable()
{
user = (WorldStorageUser)target;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawDefaultInspector();
EditorGUILayout.Space();
if (GUILayout.Button("Generate New Creator UUID"))
{
user.UUID = System.Guid.NewGuid().ToString();
EditorUtility.SetDirty(target);
}
}
}
fileFormatVersion: 2
guid: 27356e11ca7a946a6a6cf289f784ee18
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
......@@ -15,6 +15,7 @@ public class OpenAPITest : MonoBehaviour
public TMP_Text servername;
public TMP_Text output;
private string serverState = "-";
private string msg = null;
private Queue handleResponseQ = new Queue();
......@@ -41,7 +42,7 @@ public class OpenAPITest : MonoBehaviour
if (o is ResponseObject<string>)
{
ResponseObject<string> response = o as ResponseObject<string>;
output.text = $"Request Time: { response.requestTime.ToLongTimeString() } / Total Time: { response.DeltaTime.TotalMilliseconds }ms\n\n<b>Content:</b>\n{ response.result }";
output.text = $"Server State:\n\n{ serverState }";
}
else if (o is ResponseObject<Trackable>)
{
......@@ -62,7 +63,7 @@ public class OpenAPITest : MonoBehaviour
}
}
public void OnButtonClick_TestPing()
public void OnButtonClick_ServerTest()
{
if (server == null)
{
......@@ -70,11 +71,23 @@ public class OpenAPITest : MonoBehaviour
return;
}
ResponseObject<string> token = AdminRequest.PingAsync(server, (response) =>
serverState = $"Requesting server state @ time: { DateTime.Now.ToLongTimeString() }...\n";
AdminRequest.PingAsync(server, (response1) =>
{
handleResponseQ.Enqueue(response);
serverState += $"\nSending: Ping\n Receiving: { response1.result }\n Req time: { response1.requestTime.ToLongTimeString() } Tot time: { response1.DeltaTime.TotalMilliseconds }";
handleResponseQ.Enqueue(response1);
});
AdminRequest.AdminAsync(server, (response2) =>
{
serverState += $"\nSending: Admin\n Receiving: { response2.result }\n Req time: { response2.requestTime.ToLongTimeString() } Tot time: { response2.DeltaTime.TotalMilliseconds }";
handleResponseQ.Enqueue(response2);
});
AdminRequest.VersionAsync(server, (response3) =>
{
serverState += $"\nSending: Version\n Receiving: { response3.result }\n Req time: { response3.requestTime.ToLongTimeString() } Tot time: { response3.DeltaTime.TotalMilliseconds }";
handleResponseQ.Enqueue(response3);
});
output.text = "Starting request @ time: " + token.requestTime.ToLongTimeString() + "...";
}
public void OnButtonClick_GetLastTrackable()
......
This diff is collapsed.
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 8a1e3e7961eae84468e6ee20d5b09ffd, type: 3}
m_Name: User ETSI
m_EditorClassIdentifier:
userName: ARF User
company: ETSI Org
UUID: 5090fd9f-64bf-4e06-843f-26aaf2eb8e40
fileFormatVersion: 2
guid: 748585a50399fd64883147cd731ae0b7
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
//
// ARF - Augmented Reality Framework (ETSI ISG ARF)
//
// Copyright 2022 ETSI
// 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.
......
//
// ARF - Augmented Reality Framework (ETSI ISG ARF)
//
// Copyright 2022 ETSI
// 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.
......
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ETSI.ARF.OpenAPI
{
/// <summary>
/// Simple class to debug the requests
/// </summary>
public class BaseClient
{
static public bool EnableClientLog = false;
public string lastJsonText;
public long lastPayload;
protected void _prepareRequest(ETSI.ARF.OpenAPI.IHttpClient client, System.Net.Http.HttpRequestMessage request, string url)
{
if (EnableClientLog)
{
Debug.Log("[REST][URL] Send request: " + client.BaseAddress + url);
Debug.Log("[REST][URL] Send request: " + request);
}
}
protected void _processResponse(ETSI.ARF.OpenAPI.IHttpClient client, System.Net.Http.HttpResponseMessage response)
{
lastJsonText = response.Content.ReadAsStringAsync().Result.ToString();
lastPayload = response.Content.Headers.ContentLength.Value;
var status_ = (int)response.StatusCode;
if (EnableClientLog)
{
Debug.Log("[REST][Data] Status: " + status_ + " Response: " + client.BaseAddress + " Len: " + lastPayload + " JSON: " + lastJsonText);
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 2e0af995ecbb4654a9191f8157a1cf0e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
......@@ -8,6 +8,23 @@ namespace ETSI.ARF.OpenAPI.WorldStorage
public interface IModel
{
public System.Guid UUID { get; set; }
public string ToJson();
}
// Class to monitor the server
public class Server : IModel
{
public System.Guid UUID { get; set; }
public string Name { get; set; }
public Server(string name)
{
UUID = Guid.Empty;
Name = name;
}
public string ToJson() { return JsonUtility.ToJson(this); }
}
//
......@@ -20,6 +37,8 @@ namespace ETSI.ARF.OpenAPI.WorldStorage
UUID = Guid.NewGuid();
Name = name;
}
public string ToJson() { return JsonUtility.ToJson(this); }
}
public partial class WorldAnchor : IModel
......@@ -29,6 +48,8 @@ namespace ETSI.ARF.OpenAPI.WorldStorage
UUID = Guid.NewGuid();
Name = name;
}
public string ToJson() { return JsonUtility.ToJson(this); }
}
public partial class WorldLink : IModel
......@@ -37,5 +58,7 @@ namespace ETSI.ARF.OpenAPI.WorldStorage
{
UUID = Guid.NewGuid();
}
public string ToJson() { return JsonUtility.ToJson(this); }
}
}
\ No newline at end of file
......@@ -15,13 +15,26 @@ using UnityEngine;
namespace ETSI.ARF.OpenAPI
{
public class ResponseObject<T>
public class CancelToken
{
protected CancellationTokenSource tokenSource;
protected CancellationToken ct;
public CancellationToken cancellationToken { get => ct; }
public void Cancel()
{
tokenSource.Cancel();
}
}
public class ResponseObject<T> : CancelToken
{
// Management stuffs
static int ID = 0;
public int transactionId = 0;
public string message = ""; // custom message, type of data...
// Time monitoring
public TimeSpan DeltaTime { get => responseTime - requestTime; }
public DateTime requestTime;
......@@ -30,34 +43,23 @@ namespace ETSI.ARF.OpenAPI
// Incoming data
public T result;
public int payload; // size of data
//public string result = ""; // text result
//public object data = null; // custom result
// Callback
public Action<ResponseObject<T>> callback;
// Task cancelllation
public CancellationToken cancellationToken { get => ct; }
private CancellationTokenSource tokenSource;
private CancellationToken ct;
public ResponseObject(string msg, Action<ResponseObject<T>> func = null)
{
requestTime = DateTime.Now;
transactionId = ++ID;
message = msg;
callback = func;
transactionId = ++ID;
tokenSource = new CancellationTokenSource();
ct = tokenSource.Token;
}
public void Cancel()
{
tokenSource.Cancel();
}
}
}
\ No newline at end of file
//
// 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
//
// Depends on UniTask to support cancellation token and GetAwaiter: https://github.com/Cysharp/UniTask
// Otherwise, the code can be adapted using https://gist.github.com/krzys-h/9062552e33dd7bd7fe4a6c12db109a1a
......
//
// 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: March 2024
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
......@@ -25,28 +5,24 @@ using UnityEngine.Networking;
namespace ETSI.ARF.OpenAPI.WorldStorage
{
// SylR
public partial class WorldStorageClient
/// <summary>
/// Catch the pre/pos request methods from the autogenerated classes
/// </summary>
public partial class WorldStorageClient : BaseClient
{
public string lastJsonText;
public long lastPayload;
partial void PrepareRequest(IHttpClient client, System.Net.Http.HttpRequestMessage request, string url)
partial void PrepareRequest(ETSI.ARF.OpenAPI.IHttpClient client, System.Net.Http.HttpRequestMessage request, string url)
{
// If needed to make some special things !!!
_prepareRequest(client, request, url);
}
partial void PrepareRequest(IHttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder)
partial void PrepareRequest(ETSI.ARF.OpenAPI.IHttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder)
{
// do something...
}
partial void ProcessResponse(IHttpClient client, System.Net.Http.HttpResponseMessage response)
partial void ProcessResponse(ETSI.ARF.OpenAPI.IHttpClient client, System.Net.Http.HttpResponseMessage response)
{
lastJsonText = response.Content.ReadAsStringAsync().Result.ToString();
lastPayload = response.Content.Headers.ContentLength.Value;
// If needed to make some special things !!!
_processResponse(client, response);
}
}
}
\ No newline at end of file
......@@ -32,10 +32,10 @@ namespace ETSI.ARF.WorldStorage.REST
//
// Wrapper for the endpoints
//
static private string Ping(WorldStorageServer ws)
static public string PingSync(WorldStorageServer ws)
{
wsServer = ws;
var httpClient = new UnityWebRequestHttpClient(ws.URI);
var httpClient = new BasicHTTPClient(ws.URI);
apiClient = new WorldStorageClient(httpClient);
string response = apiClient.GetPing();
......@@ -48,33 +48,53 @@ namespace ETSI.ARF.WorldStorage.REST
var httpClient = new UnityWebRequestHttpClient(ws.URI);
apiClient = new WorldStorageClient(httpClient);
Debug.Log("Request Ping...");
Debug.Log("[REST] Request Ping...");
ResponseObject<string> ro = new ResponseObject<string>("Request Ping", func);
apiClient.GetPingAsync().ContinueWith(OnReceiveObject<string>, ro);
apiClient.GetPingAsync(ro.cancellationToken).ContinueWith(OnReceiveObject<string>, ro);
return ro;
}
static public string AdminSync(WorldStorageServer ws)
{
wsServer = ws;
var httpClient = new BasicHTTPClient(ws.URI);
apiClient = new WorldStorageClient(httpClient);
string response = apiClient.GetAdmin();
return response;
}
static public ResponseObject<string> AdminAsync(WorldStorageServer ws, Action<ResponseObject<string>> func)
{
wsServer = ws;
var httpClient = new UnityWebRequestHttpClient(ws.URI);
apiClient = new WorldStorageClient(httpClient);
Debug.Log("Request Admin...");
Debug.Log("[REST] Request Admin...");
ResponseObject<string> ro = new ResponseObject<string>("Request Admin", func);
apiClient.GetAdminAsync().ContinueWith(OnReceiveObject<string>, ro);
apiClient.GetAdminAsync(ro.cancellationToken).ContinueWith(OnReceiveObject<string>, ro);
return ro;
}
static public string VersionSync(WorldStorageServer ws)
{
wsServer = ws;
var httpClient = new BasicHTTPClient(ws.URI);
apiClient = new WorldStorageClient(httpClient);
string response = apiClient.GetVersion();
return response;
}
static public ResponseObject<string> VersionAsync(WorldStorageServer ws, Action<ResponseObject<string>> func)
{
wsServer = ws;
var httpClient = new UnityWebRequestHttpClient(ws.URI);
apiClient = new WorldStorageClient(httpClient);
Debug.Log("Request Version...");
Debug.Log("[REST] Request Version...");
ResponseObject<string> ro = new ResponseObject<string>("Request Version", func);
apiClient.GetVersionAsync().ContinueWith(OnReceiveObject<string>, ro);
apiClient.GetVersionAsync(ro.cancellationToken).ContinueWith(OnReceiveObject<string>, ro);
return ro;
}
}
......
......@@ -32,7 +32,7 @@ namespace ETSI.ARF.WorldStorage.REST
{
wsServer = ws;
var httpClient = new UnityWebRequestHttpClient(ws.URI);
apiClient = new WorldStorageClient(httpClient);
apiClient = new MyWorldStorageClient(httpClient);
ResponseObject<Response> ro = new ResponseObject<Response>("Request Reloc Information ", func);
......@@ -45,12 +45,16 @@ namespace ETSI.ARF.WorldStorage.REST
newOne.Mode = modes[i];
anonymous.Add(newOne);
}
apiClient.GetRelocalizationInformationAsync(token, anonymous, capabilities).ContinueWith(OnReceiveObject<Response>, ro);
apiClient.GetRelocalizationInformationAsync(token, anonymous, capabilities, ro.cancellationToken).ContinueWith(OnReceiveObject<Response>, ro);
return ro;
}
static public Response GetRelocalizationInformation(WorldStorageServer ws, List<Guid> uuids, List<Mode_WorldStorage> modes, List<Capability> capabilities)
{
return GetRelocalizationInformationSync(ws, uuids, modes, capabilities);
}
static public Response GetRelocalizationInformationSync(WorldStorageServer ws, List<Guid> uuids, List<Mode_WorldStorage> modes, List<Capability> capabilities)
{
wsServer = ws;
var httpClient = new BasicHTTPClient(ws.URI);
......@@ -102,6 +106,7 @@ namespace ETSI.ARF.OpenAPI.WorldStorage
}
}
// Custom client to be able to properly serialize objects in the query string
public partial class MyWorldStorageClient : WorldStorageClient
{
public MyWorldStorageClient(IHttpClient httpClient) : base(httpClient)
......
......@@ -49,11 +49,11 @@ namespace ETSI.ARF.WorldStorage.REST
ResponseObject<TObj> o = (ResponseObject<TObj>)id;
o.responseTime = DateTime.Now;
o.result = t.Result;
Debug.Log($"Server Response = {o.result} (ID={o.transactionId}, Msg={o.message})");
Debug.Log($"[REST] Server Response = {o.result.ToString()} (ID={o.transactionId}, Msg={o.message})");
o.callback?.Invoke(o);
}
else Debug.Log("OpenAPI Timeout!");
else Debug.Log("[REST] OpenAPI Timeout!");
}
static protected void OnReceiveListOfObjects<TObj>(Task<List<TObj>> t, object id) where TObj : IModel
......