Files
Studio/Assets/Scripts/Studio/Connect/StudioRepoistory.cs
2025-05-24 15:54:06 +09:00

191 lines
6.3 KiB
C#

using Best.MQTT;
using Best.MQTT.Packets.Builders;
using Newtonsoft.Json.Linq;
using Studio.Conifg;
using Studio.Setting.Connect;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Studio
{
public class StudioRepoistory
{
private MQTTClient client;
public bool isMQTTConnected;
public bool isConnected
{
get
{
if (client == null)
return false;
return client.State == ClientStates.Connected;
}
}
public Action<string, Dictionary<string, Dictionary<string, string>>> OnTopicList;
public StudioRepoistory()
{
//MQTTCreateConnect();
Application.quitting += OnDestroy;
}
public void MQTTCreateConnect()
{
Debug.Log($"MQTT Domain{Constants.MQTTDomain} , MQTTPORT{Constants.MQTTPort}");
var options = new ConnectionOptionsBuilder()
.WithTCP(Constants.MQTTDomain, Constants.MQTTPort)
.Build();
if (client != null)
{
client.OnConnected -= OnConnectedMQTT;
client.OnStateChanged -= OnStateChangedMQTT;
client.OnDisconnect -= OnDisconnectedMQTT;
client.OnError -= OnErrorMQTT;
}
client = new MQTTClient(options);
client.OnConnected += OnConnectedMQTT;
client.OnStateChanged += OnStateChangedMQTT;
client.OnDisconnect += OnDisconnectedMQTT;
client.OnError += OnErrorMQTT;
}
private ConnectPacketBuilder ConnectPacketBuilderCallback(MQTTClient client, ConnectPacketBuilder builder)
{
return builder.WithKeepAlive(60 * 60);//keep alive 1시간으로
}
public async Task<StudioEntityWithState<object>> BaseInfo(string url)
{
try
{
return await Task.Run<StudioEntityWithState<object>>(async () =>
{
ResponseModel<object> response = await RestAPI.RequestGet<ResponseModel<object>>(url);
Debug.Log(response);
if (response.code == "SUCCESS")
return new StudioEntityWithState<object>(APIState.Loaded, response.data,response.requestsize);
return new StudioEntityWithState<object>(APIState.Error, null, 0,response.message);
});
}
catch (Exception e)
{
return new StudioEntityWithState<object>(APIState.Error, null,0, e.Message);
}
}
public void MQTTConnect()
{
client.BeginConnect(ConnectPacketBuilderCallback);
}
private void OnErrorMQTT(MQTTClient client, string error)
{
Debug.Log($"OnError reason: '{error}'");
}
private void OnDisconnectedMQTT(MQTTClient client, DisconnectReasonCodes reasonCode, string reasonMessage)
{
if (Application.isPlaying)
{
//MQTT재시작
}
}
private void OnStateChangedMQTT(MQTTClient client, ClientStates oldState, ClientStates newState)
{
Debug.Log($"{oldState} => {newState}");
}
private void OnConnectedMQTT(MQTTClient client)
{
Debug.Log($"MQTT OnConnected");
}
/// <summary>
/// 구독
/// </summary>
/// <param name="topic"></param>
public void Subscribe(string topic)
{
client.CreateBulkSubscriptionBuilder()
.WithTopic(new SubscribeTopicBuilder(topic).WithMessageCallback(OnTopic))
.BeginSubscribe();
}
/// <summary>
/// 구독 취소
/// </summary>
/// <param name="topic"></param>
public void UnSubscibe(string topic)
{
client.CreateUnsubscribePacketBuilder(topic)
.WithAcknowledgementCallback((client, topicFilter, reasonCode) => Debug.Log($"Unsubscribe request to topic filter '{topicFilter}' returned with code: {reasonCode}"))
.BeginUnsubscribe();
}
private void OnTopic(MQTTClient client, SubscriptionTopic topic, string topicName, ApplicationMessage message)
{
string payload = Encoding.UTF8.GetString(message.Payload.Data, message.Payload.Offset, message.Payload.Count);
var type = topic.Filter.ToString();
JObject json = JObject.Parse(payload);
foreach(JProperty prop in json.Children())
{
string key = prop.Name.ToString();
string value = prop.Value.ToString();
}
var T = json["data"];
var split = T.ToString().Split('[');
var t = $"[{split[1]}";
JArray jarray = JArray.Parse(t);
var list = new Dictionary<string, Dictionary<string, string>>();
foreach (JObject obj in jarray.Children())
{
Dictionary<string, string> keyvalue = new();
int index = 0;
string id = string.Empty;
foreach (JProperty prop in obj.Children())
{
string key = prop.Name.ToString();
string value = prop.Value.ToString();
if (index == 0)
{
if (!list.ContainsKey(value))
list.Add(value, new());
id = value;
index = 1;
}
keyvalue.Add(key, value);
}
list[id] = keyvalue;
}
CheckUpdate(type, list);
}
private void CheckUpdate(string type, Dictionary<string, Dictionary<string, string>> data)
{
if (data == null)
return;
if(data.Count > 0)
OnTopicList?.Invoke(type, data);
}
private void OnDestroy()
{
client?.CreateDisconnectPacketBuilder()
.WithReasonCode(DisconnectReasonCodes.NormalDisconnection)
.WithReasonString($"{Constants.MQTTDomain} Disconnecting")
.BeginDisconnect();
}
}
}