Initial commit
This commit is contained in:
82
Assets/Scripting/MQTT/MQTTBroker.cs
Normal file
82
Assets/Scripting/MQTT/MQTTBroker.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using MQTTnet;
|
||||
using MQTTnet.Server;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
public class MQTTBroker : MonoBehaviour
|
||||
{
|
||||
public int port = 1883;
|
||||
public string username = "";
|
||||
public string password = "";
|
||||
public bool allowAnonymousConnections = true;
|
||||
|
||||
private MqttServer mqttServer;
|
||||
|
||||
private async void Start()
|
||||
{
|
||||
var optionsBuilder = new MqttServerOptionsBuilder()
|
||||
.WithDefaultEndpoint()
|
||||
.WithDefaultEndpointPort(port);
|
||||
|
||||
mqttServer = new MqttFactory().CreateMqttServer(optionsBuilder.Build());
|
||||
|
||||
mqttServer.ValidatingConnectionAsync += args =>
|
||||
{
|
||||
if (string.IsNullOrEmpty(args.Username))
|
||||
{
|
||||
if (allowAnonymousConnections)
|
||||
{
|
||||
args.ReasonCode = MqttConnectReasonCode.Success;
|
||||
//Debug.Log($"[MQTT] Anonymous client connected: {args.ClientId}");
|
||||
}
|
||||
else
|
||||
{
|
||||
args.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
|
||||
Debug.LogWarning($"[MQTT] Anonymous not allowed: {args.ClientId}");
|
||||
}
|
||||
}
|
||||
else if (args.Username == username && args.Password == password)
|
||||
{
|
||||
args.ReasonCode = MqttConnectReasonCode.Success;
|
||||
Debug.Log($"[MQTT] Authenticated client: {args.ClientId}");
|
||||
}
|
||||
else
|
||||
{
|
||||
args.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
|
||||
Debug.LogWarning($"[MQTT] Invalid credentials: {args.ClientId}");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
mqttServer.ClientConnectedAsync += e =>
|
||||
{
|
||||
//Debug.Log($"[MQTT] Client connected: {e.ClientId}");
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
mqttServer.InterceptingPublishAsync += e =>
|
||||
{
|
||||
string payload = e.ApplicationMessage?.Payload == null
|
||||
? ""
|
||||
: System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
|
||||
|
||||
//Debug.Log($"[MQTT] Topic: {e.ApplicationMessage.Topic} - Payload: {payload}");
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await mqttServer.StartAsync();
|
||||
//Debug.Log($"MQTT broker started on port {port}");
|
||||
}
|
||||
|
||||
private async void OnApplicationQuit()
|
||||
{
|
||||
if (mqttServer != null)
|
||||
{
|
||||
await mqttServer.StopAsync();
|
||||
Debug.Log("MQTT broker stopped.");
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripting/MQTT/MQTTBroker.cs.meta
Normal file
2
Assets/Scripting/MQTT/MQTTBroker.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 29bbd3dbef6acad4d853bdb166d95684
|
||||
134
Assets/Scripting/MQTT/MqttClientManager.cs
Normal file
134
Assets/Scripting/MQTT/MqttClientManager.cs
Normal file
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Extensions.ManagedClient;
|
||||
using MQTTnet.Packets;
|
||||
using UnityEngine;
|
||||
|
||||
public class MqttClientManager
|
||||
{
|
||||
private readonly string mqttBroker;
|
||||
private readonly int mqttPort;
|
||||
private readonly string mqttUsername;
|
||||
private readonly string mqttPassword;
|
||||
private readonly string mqttClientId;
|
||||
private readonly string orderTopic;
|
||||
private readonly string instantActionsTopic;
|
||||
private readonly ConcurrentQueue<string> jsonQueue;
|
||||
private readonly ConcurrentQueue<string> instantActionQueue;
|
||||
private IManagedMqttClient mqttClient;
|
||||
|
||||
public MqttClientManager(string broker, int port, string username, string password, string clientId,
|
||||
string orderTopic, string instantActionsTopic, ConcurrentQueue<string> jsonQueue,
|
||||
ConcurrentQueue<string> instantActionQueue)
|
||||
{
|
||||
mqttBroker = broker;
|
||||
mqttPort = port;
|
||||
mqttUsername = username;
|
||||
mqttPassword = password;
|
||||
mqttClientId = clientId;
|
||||
this.orderTopic = orderTopic;
|
||||
this.instantActionsTopic = instantActionsTopic;
|
||||
this.jsonQueue = jsonQueue;
|
||||
this.instantActionQueue = instantActionQueue;
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var mqttFactory = new MqttFactory();
|
||||
mqttClient = mqttFactory.CreateManagedMqttClient();
|
||||
|
||||
var optionsBuilder = new MqttClientOptionsBuilder()
|
||||
.WithTcpServer(mqttBroker, mqttPort)
|
||||
.WithClientId(mqttClientId);
|
||||
if (!string.IsNullOrEmpty(mqttUsername) && !string.IsNullOrEmpty(mqttPassword))
|
||||
{
|
||||
optionsBuilder.WithCredentials(mqttUsername, mqttPassword);
|
||||
}
|
||||
|
||||
var managedOptions = new ManagedMqttClientOptionsBuilder()
|
||||
.WithClientOptions(optionsBuilder.Build())
|
||||
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
|
||||
.Build();
|
||||
|
||||
mqttClient.ApplicationMessageReceivedAsync += async e =>
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
string topic = e.ApplicationMessage.Topic;
|
||||
string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? Array.Empty<byte>());
|
||||
if (topic == orderTopic)
|
||||
{
|
||||
Debug.Log($"{payload}");
|
||||
jsonQueue.Enqueue(payload);
|
||||
}
|
||||
else if (topic == instantActionsTopic)
|
||||
{
|
||||
Debug.Log($"Nhận được JSON từ chủ đề {instantActionsTopic}: {payload}");
|
||||
instantActionQueue.Enqueue(payload);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
mqttClient.ConnectedAsync += async e =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await mqttClient.SubscribeAsync(new List<MqttTopicFilter>
|
||||
{
|
||||
new MqttTopicFilterBuilder().WithTopic(orderTopic).Build(),
|
||||
new MqttTopicFilterBuilder().WithTopic(instantActionsTopic).Build()
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"Lỗi khi kết nối hoặc đăng ký chủ đề: {ex.Message}");
|
||||
}
|
||||
};
|
||||
|
||||
mqttClient.DisconnectedAsync += async e =>
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
};
|
||||
|
||||
await mqttClient.StartAsync(managedOptions);
|
||||
//Debug.Log("Đã khởi động MQTT client");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"Không thể khởi tạo MQTT client: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
if (mqttClient != null)
|
||||
{
|
||||
await mqttClient.StopAsync();
|
||||
mqttClient.Dispose();
|
||||
Debug.Log("Đã dừng và hủy MQTT client");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task PublishAsync(string topic, string payload)
|
||||
{
|
||||
if (mqttClient == null || !mqttClient.IsConnected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var message = new MqttApplicationMessageBuilder()
|
||||
.WithTopic(topic)
|
||||
.WithPayload(Encoding.UTF8.GetBytes(payload))
|
||||
.Build();
|
||||
|
||||
await mqttClient.EnqueueAsync(message);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripting/MQTT/MqttClientManager.cs.meta
Normal file
2
Assets/Scripting/MQTT/MqttClientManager.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 94facf4719dd13944aa270b45bb689cf
|
||||
Reference in New Issue
Block a user