ar_tourism_flutter_unity/unity/VRProject2/Assets/zhl/zhlScripts/GetData.cs

456 lines
18 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// GetData.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Newtonsoft.Json;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
//[ExecuteInEditMode]
public class GetData : MonoBehaviour
{
//单例
private static GetData instance;
public static GetData Instance
{
get
{
return instance;
}
}
private void Awake()
{
instance = this;
//token = "";
}
[System.Serializable]
public class Source
{
public int sourceID;
public int cX;
public int cY;
public string sourceStatus;
public string part;
public string workAddress;
public string detail;
public string workName;
//[JsonProperty("workId")]
public int workId;
}
// 定义 Root 类来表示整个 JSON 对象
[System.Serializable]
public class Root
{
public Source[] sourceList;
}
Dictionary<string,Texture2D> sourceDic = new();
public Transform GameObjectParent;
public MyPlane[] myPlane;
public MyPlane[] DontScenePlane;
// Start is called before the first frame update
// 新增字段保存最后激活状态
private Dictionary<MyPlane, bool> lastActiveStates = new Dictionary<MyPlane, bool>();
//private string token = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijc4ZDljZWQ1LWQzYTEtNDk5ZC04OTk0LTAyZGMwYTliMjU2NSJ9.hsO_3-7RUJkjxJxDnjTvi_qyqtb9He2YKgwo1EFKMAinjYBjVf9N-ZjM2NQT46Y5K5ywL4hbxZSEbTtIo3UvCw";
//public string token = "";
[SerializeField] private TMP_Text tokenText;
void Start()
{
//GetToken("Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijc4ZDljZWQ1LWQzYTEtNDk5ZC04OTk0LTAyZGMwYTliMjU2NSJ9.hsO_3-7RUJkjxJxDnjTvi_qyqtb9He2YKgwo1EFKMAinjYBjVf9N-ZjM2NQT46Y5K5ywL4hbxZSEbTtIo3UvCw");
//StartCoroutine(PostSource());
//myPlane = GameObjectParent.GetComponentsInChildren<MyPlane>();
//StartCoroutine(CheckActivationChanges()); // 启动状态监测
}
public void SetInitToken()
{
GetToken("Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImI4OTBiZGU2LTUyZmMtNGZlZC05ZDVhLTcyZDQzNjMyYWIyMiJ9._dTDqJ5Y7vqKPG0PvIEo9A8A_9WHnRgDUwP_w_tAGCTvyl6uvMz_QeVzTAda_pO3G3RSUfLYZ2NRu6S3uLRcTw");
}
public void NoScene()
{
StartCoroutine(DontScenePostRequest());
}
public void GetToken(string token){
//this.token = token;
DontDestoryData.token = token;
tokenText.text = "token:"+token;
foreach (MyPlane plane in myPlane)
{
if (plane != null && !plane.GetComponent<ResourceUI>().isResquested && plane.GetComponent<ResourceUI>().isAdded)
{
plane.GetComponent<ResourceUI>().isAdded = false;
}
}
StartCoroutine(PostRequest());
StartCoroutine(DontScenePostRequest());
}
// 新增状态监测协程
private IEnumerator CheckActivationChanges()
{
while (true)
{
bool needUpdate = false;
foreach (MyPlane plane in myPlane)
{
if (plane == null) continue;
bool currentActive = plane.transform.parent.gameObject.activeSelf;
if (!lastActiveStates.ContainsKey(plane) || lastActiveStates[plane] != currentActive)
{
lastActiveStates[plane] = currentActive;
needUpdate = true;
}
}
if (needUpdate)
{
yield return StartCoroutine(PostSource());
}
yield return new WaitForSeconds(0.5f); // 每0.5秒检测一次
}
}
// 修改后的PostSource方法
private IEnumerator PostSource()
{
yield return new WaitForSeconds(1f);
if(DontDestoryData.token == "")
{
Debug.Log("DontDestoryData.token为空取消请求发送");
yield break;
}
else
{
Debug.Log(DontDestoryData.token);
}
//string url = "http://10.0.0.17:8081/app/ar/getAllSource";
string url = "http://14.103.162.172:8081/app/ar/getAllSource";
List<string> activeCoordinates = new List<string>();
foreach (MyPlane plane in myPlane)
{
if (plane != null && plane.transform.parent.gameObject.activeSelf)
{
activeCoordinates.Add($"[{plane.idx},{plane.idy}]");
}
}
// 添加空数据检查
if (activeCoordinates.Count == 0)
{
Debug.Log("没有激活的坐标数据,取消请求发送");
yield break;
}
string json = $"{{\"city\":\"济南\",\"scenic\":\"泉城广场\",\"coordinates\":[{string.Join(",", activeCoordinates)}]}}";
Debug.Log("json"+json);
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
UnityWebRequest request = new UnityWebRequest(url, "POST");
//request.timeout = 60;
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Authorization", DontDestoryData.token);
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError(request.error);
}
else
{
string responseJson = request.downloadHandler.text;
Debug.Log("JSON 接收成功: " + responseJson);
// 解析 JSON 数据
Root root = JsonUtility.FromJson<Root>(responseJson);
if (root != null && root.sourceList != null)
{
foreach (Source source in root.sourceList)
{
//Debug.Log($"cX: {source.cX}, cY: {source.cY}, Address: {source.workAddress}"+",workName"+source.workName+",detail"+source.detail);
MyPlane foundPlane = myPlane.ToList().Find(p => p.idx == source.cX && p.idy == source.cY);
if (foundPlane != null)
{
bool isUserUploaded = false;
if (source.workId != null && source.workId != 0)
{
isUserUploaded = false;
}
else
{
isUserUploaded = true;
}
if(sourceDic.ContainsKey(source.workAddress))
{
foundPlane.GetComponent<ResourceUI>().SetResourceUIClass(sourceDic[source.workAddress], source.detail, source.workName, isUserUploaded);
}
else
{
StartCoroutine(LoadImage(foundPlane, source.workAddress, source.detail, source.workName,isUserUploaded));
}
yield return new WaitForSeconds(1.5f); // 添加延迟
}
}
}
}
yield return new WaitForSeconds(1f);
}
public IEnumerator PostRequest()
{
yield return new WaitForSeconds(1f);
if(DontDestoryData.token == "")
{
Debug.Log("DontDestoryData.token为空取消请求发送");
yield break;
}
else
{
Debug.Log(DontDestoryData.token);
}
//string url = "http://10.0.0.17:8081/app/ar/getAllSource";
string url = "http://14.103.162.172:8081/app/ar/getAllSource";
List<string> activeCoordinates = new List<string>();
foreach (MyPlane plane in myPlane)
{
if (plane != null && plane.transform.parent.gameObject.activeSelf && !plane.GetComponent<ResourceUI>().isResquested && !plane.GetComponent<ResourceUI>().isAdded)
{
activeCoordinates.Add($"[{plane.idx},{plane.idy}]");
plane.GetComponent<ResourceUI>().isAdded = true;
}
else if(plane != null && !plane.transform.parent.gameObject.activeSelf && !plane.GetComponent<ResourceUI>().isResquested && plane.GetComponent<ResourceUI>().isAdded)
{
plane.GetComponent<ResourceUI>().isAdded = false;
}
}
// 添加空数据检查
if (activeCoordinates.Count == 0)
{
Debug.Log("没有激活的坐标数据,取消请求发送");
yield break;
}
string json = $"{{\"city\":\"济南\",\"scenic\":\"泉城广场\",\"coordinates\":[{string.Join(",", activeCoordinates)}]}}";
Debug.Log("json"+json);
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
UnityWebRequest request = new UnityWebRequest(url, "POST");
//request.timeout = 60;
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Authorization", DontDestoryData.token);
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError(request.error);
}
else
{
string responseJson = request.downloadHandler.text;
Debug.Log("JSON 接收成功: " + responseJson);
// 解析 JSON 数据
Root root = JsonUtility.FromJson<Root>(responseJson);
if (root != null && root.sourceList != null)
{
foreach (Source source in root.sourceList)
{
if (myPlane != null && myPlane.Length > 0)
{
MyPlane foundPlane = null;
try
{
foundPlane = myPlane.ToList().Find(p => p != null && p.idx == source.cX && p.idy == source.cY);
}
catch (System.Exception e)
{
Debug.LogError("查找MyPlane时出错: " + e.Message);
}
if (foundPlane != null)
{
bool isUserUploaded = false;
try
{
// 修改为更简单的逻辑如果workId不为0则认为是用户上传的
isUserUploaded = source.workId != 0;
}
catch (System.Exception e)
{
Debug.LogWarning("获取workId时出错使用默认值false: " + e.Message);
isUserUploaded = false;
}
Debug.Log(source.cX + "," + source.cY + ",workId:" + source.workId + ",isUserUploaded:" + isUserUploaded);
if(sourceDic.ContainsKey(source.workAddress))
{
foundPlane.GetComponent<ResourceUI>().SetResourceUIClass(sourceDic[source.workAddress], source.detail, source.workName,isUserUploaded);
yield return null; // 添加延迟
}
else
{
StartCoroutine(LoadImage(foundPlane, source.workAddress, source.detail, source.workName,isUserUploaded));
yield return new WaitForSeconds(1f); // 添加延迟
}
}
}
else
{
Debug.LogError("myPlane数组为空或未初始化");
yield break;
}
}
}
}
yield return new WaitForSeconds(1f);
}
public IEnumerator DontScenePostRequest()
{
yield return new WaitForSeconds(1f);
if(DontDestoryData.token == "")
{
Debug.Log("DontDestoryData.token为空取消请求发送");
yield break;
}
else
{
Debug.Log(DontDestoryData.token);
}
string url = "http://14.103.162.172:8081/app/ar/getAllSource";
string json = $"{{\"city\":\"济南\",\"scenic\":\"泉城广场\",\"coordinates\":[]}}";
Debug.Log("json"+json);
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
UnityWebRequest request = new UnityWebRequest(url, "POST");
//request.timeout = 60;
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Authorization", DontDestoryData.token);
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError(request.error);
}
else
{
string responseJson = request.downloadHandler.text;
Debug.Log("JSON 接收成功: " + responseJson);
int index = 0;
Root root = JsonUtility.FromJson<Root>(responseJson);
if (root != null && root.sourceList != null)
{
foreach (Source source in root.sourceList)
{
if (DontScenePlane != null && DontScenePlane.Length > 0)
{
if (index <= DontScenePlane.Length - 1)
{
bool isUserUploaded = false;
try
{
// 修改为更简单的逻辑如果workId不为0则认为是用户上传的
isUserUploaded = source.workId != 0;
}
catch (System.Exception e)
{
Debug.LogWarning("获取workId时出错使用默认值false: " + e.Message);
isUserUploaded = false;
}
if (isUserUploaded)
{
Debug.Log(source.cX + "," + source.cY + ",workId:" + source.workId + ",isUserUploaded:" + isUserUploaded);
if(sourceDic.ContainsKey(source.workAddress))
{
DontScenePlane[index++].GetComponent<ResourceUI>().SetResourceUIClass(sourceDic[source.workAddress], source.detail, source.workName,isUserUploaded);
yield return null; // 添加延迟
}
else
{
StartCoroutine(LoadImage(DontScenePlane[index++], source.workAddress, source.detail, source.workName,isUserUploaded));
yield return new WaitForSeconds(1f); // 添加延迟
}
}
}
else
{
yield break;
}
}
else
{
Debug.LogError("DontScenePlane数组为空或未初始化");
yield break;
}
}
}
}
yield return new WaitForSeconds(1f);
}
private IEnumerator LoadImage(MyPlane item, string imageUrl, string getText, string biaoTi, bool isUserUploaded)
{
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(imageUrl))
{
// 添加详细的错误日志
//Debug.Log($"开始加载图片: {imageUrl}");
yield return uwr.SendWebRequest();
if (uwr.result == UnityWebRequest.Result.ConnectionError ||
uwr.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"图片加载失败: {uwr.error}\nURL: {imageUrl}\n" +
$"ResponseCode: {uwr.responseCode}\n" +
$"详细错误: {uwr.downloadHandler?.text}");
}
else
{
//Debug.Log($"{item.idx},{item.idy}_图片加载成功");
Texture2D texture = DownloadHandlerTexture.GetContent(uwr);
sourceDic[imageUrl] = texture;
// 添加空值检查
if (texture != null)
{
ResourceUI resourceUI = item.GetComponent<ResourceUI>();
resourceUI.SetResourceUIClass(texture, getText, biaoTi,isUserUploaded);
resourceUI.isResquested = true;
}
else
{
Debug.LogError($"纹理加载失败: {imageUrl}");
}
}
}
}
}
// PostSource保持与方案一相同的实现