using Best.HTTP.JSON.LitJson; using Best.MQTT; using Best.MQTT.Packets; using Best.MQTT.Packets.Builders; using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using UnityEngine; using WI; public class MQTT : Protocol, ISingle, IOptionable { MQTTClient client; [OptionSection] string mqttClientSetting; [OptionKey] string host ="106.247.236.204"; [OptionKey] string port="8901"; [OptionKey] string topics= "MES/PDV/BOARD1,MES/PDV/BOARD2"; private int portData; private string[] subscriptionTopics; public event Action> onMachineData; public event Action> onWorkshopData; public void Start() { MQTTConnect(); } public void MQTTConnect() { Disconnect(); int.TryParse(port, out portData); subscriptionTopics = topics.Split(","); SubscriptionTopic(subscriptionTopics[0], onWorkshopData); SubscriptionTopic(subscriptionTopics[1], onMachineData); //SubscriptionTopic(subscriptionTopics[0], (data) => { }); Connect(host, portData.ToString(), topics); } public event Action portParsingError; public void Connect(string ip, string port, string topics) { //Debug.Log($"1MQTT CONNECTING... {ip}:{port} {topics}"); host = ip; if (!int.TryParse(port, out int pd)) { portParsingError?.Invoke(); return; } this.portData = pd; subscriptionTopics = topics.Split(','); //Debug.Log($"2MQTT CONNECTING... {host}:{this.port} {subscriptionTopics.Length}"); Connect(); } void Disconnect() { client?.CreateDisconnectPacketBuilder() .WithReasonCode(DisconnectReasonCodes.NormalDisconnection) .WithReasonString("Bye") .BeginDisconnect(); } public void Connect() { //Disconnect(); //#if !UNITY_EDITOR // HTTPManager.RootFolderName = "EdukitDT"; //#endif client = new MQTTClientBuilder() //#if !UNITY_WEBGL || UNITY_EDITOR .WithOptions(new ConnectionOptionsBuilder().WithTCP(host, portData)) //#else //.WithOptions(new ConnectionOptionsBuilder().WithWebSocket(host, port).WithTLS()) //#endif .WithEventHandler(OnConnected) .WithEventHandler(OnStateChange) .WithEventHandler(OnDisconnected) .WithEventHandler(OnError) .CreateClient(); client.BeginConnect(ConnectPacketBuilderCallback); } public event Action onConnectedEvent; private void OnConnected(MQTTClient client) { //Debug.Log("OnConnected"); for (int i = 0; i < subscriptionTopics.Length; i++) { client.AddTopicAlias(subscriptionTopics[i]); client.CreateSubscriptionBuilder(subscriptionTopics[i]) .WithMessageCallback(OnMessage) .WithAcknowledgementCallback(OnSubscriptionAcknowledged) .WithMaximumQoS(QoSLevels.ExactlyOnceDelivery) .BeginSubscribe(); } onConnectedEvent?.Invoke(client); isSuccess = true; errorMessage = client.State.ToString(); //client.createapplicationmessagebuilder("best_mqtt/test_topic") // .withpayload("hello mqtt world!") // .withqos(best.mqtt.packets.qoslevels.exactlyoncedelivery) // .withcontenttype("text/plain; charset=utf-8") // .beginpublish(); } [Serializable] public class WorkShopInfo { public string groupcd; public string groupnm; public string mchcnt; public string planqty; public string workqty; public string goodqty; public string badqty; public string badrate; public string progressrate; } [Serializable] public class CompleteInfo { public string datagbn; public string wordno; public string workdt; public string daynight; public string sitecd; public string wccd; public string workcd; public string worknm; public string workseq; public string status; public string statusnm; public string itemcd; public string itemdesc; public string pjtcd; public string matcd; public string cycletime; public string cavity; public string planqty; public string goalqty; public string workqty; public string goodqty; public string badqty; public string adrate; public string efficiency; public string progressrate; public string sttm; public string totm; public string goaltime; public string ptotm; public string psttm; } public List infos = new List(); public List workShopInfo = new List(); public List workerIds = new List(); Dictionary>> topicSubscriptionTable = new(); Dictionary>> workShopTopicTable = new(); private void OnMessage(MQTTClient client, SubscriptionTopic topic, string topicName, ApplicationMessage message) { // Convert the raw payload to a string var payload = Encoding.UTF8.GetString(message.Payload.Data, message.Payload.Offset, message.Payload.Count); //Debug.Log($"Content-Type: '{message.ContentType}' Payload: '{payload}'"); if (topicName == "MES/PDV/BOARD1") { List data = JsonConvert.DeserializeObject>(payload); workShopInfo = data; workShopTopicTable[topicName]?.Invoke(data); } else if(topicName== "MES/PDV/BOARD2") { List data = JsonConvert.DeserializeObject>(payload); infos = data; workerIds.Clear(); foreach (var i in infos) { if (i.worknm == "") workerIds.Add(i.workcd); } //Print(workerIds); topicSubscriptionTable[topicName]?.Invoke(data); } } StringBuilder sb = new StringBuilder(); void Print(List target) { foreach(var t in target) { sb.AppendLine(t); } Debug.Log(sb.ToString()); sb.Clear(); } public void SubscriptionTopic(string topic, Action> callback) { if (!topicSubscriptionTable.ContainsKey(topic)) topicSubscriptionTable.Add(topic, null); topicSubscriptionTable[topic] += callback; } public void SubscriptionTopic(string topic, Action> callback) { if (!workShopTopicTable.ContainsKey(topic)) workShopTopicTable.Add(topic, null); workShopTopicTable[topic] += callback; } private void OnSubscriptionAcknowledged(MQTTClient client, SubscriptionTopic topic, SubscribeAckReasonCodes reasonCode) { // if (reasonCode <= SubscribeAckReasonCodes.GrantedQoS2) // Debug.Log($"Successfully subscribed with topic filter '{topic.Filter.OriginalFilter}'. QoS granted by the server: {reasonCode}"); // else // Debug.Log($"Could not subscribe with topic filter '{topic.Filter.OriginalFilter}'! Error code: {reasonCode}"); } void OnDestroy() { //Debug.Log("MQTT DESTROY"); client?.CreateDisconnectPacketBuilder() .WithReasonCode(DisconnectReasonCodes.NormalDisconnection) //.WithReasonString("Bye") .BeginDisconnect(); infos.Clear(); topicSubscriptionTable.Clear(); } private ConnectPacketBuilder ConnectPacketBuilderCallback(MQTTClient client, ConnectPacketBuilder builder) { return builder; } public event Action onErrorEvent; private void OnError(MQTTClient client, string error) { isSuccess = false; errorMessage = client.State.ToString(); //Debug.Log($"OnError! :{error}"); onErrorEvent?.Invoke(client, error); //throw new NotImplementedException(); } public event Action onDisconnectedEvent; private void OnDisconnected(MQTTClient client, DisconnectReasonCodes reasonCode, string reasonMessage) { if (client == null) { Debug.Log("Client Missing"); return; } onDisconnectedEvent?.Invoke(client, reasonCode, reasonMessage); } public event Action onStateChangeEvent; private void OnStateChange(MQTTClient client, ClientStates oldState, ClientStates newState) { onStateChangeEvent?.Invoke(client, oldState, newState); //throw new NotImplementedException(); } }