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."); } } }