Skip to content

Instantly share code, notes, and snippets.

@nekomimi-daimao
Created September 22, 2019 15:51
Show Gist options
  • Save nekomimi-daimao/1a27e0326833855c1635715505d29e92 to your computer and use it in GitHub Desktop.
Save nekomimi-daimao/1a27e0326833855c1635715505d29e92 to your computer and use it in GitHub Desktop.
MQTT Broker running on Unity https://github.com/chkr1011/MQTTnet
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client.Receiving;
using MQTTnet.Server;
using UnityEngine;
using UnityEngine.UI;
namespace Nekomimi.Daimao
{
/// <summary>
/// MQTT Broker running on Unity
/// using MQTTnet
/// https://github.com/chkr1011/MQTTnet
/// </summary>
public class MQTTBroker : MonoBehaviour
{
#region Debug
private SynchronizationContext _synchronizationContext;
#pragma warning disable 649
[SerializeField]
private Text _address;
[SerializeField]
private Text _log;
#pragma warning restore 649
private static readonly int LogLength = 10;
private List<string> _logList;
private StringBuilder _stringBuilder;
private void ShowLog(string log)
{
_logList.Add(log);
if (_logList.Count > LogLength)
{
_logList.RemoveAt(0);
}
_stringBuilder.Clear();
foreach (var s in _logList)
{
_stringBuilder.AppendLine(s);
}
var show = _stringBuilder.ToString();
if (_log != null)
{
_synchronizationContext.Post((state => { _log.text = show; }), null);
}
}
#endregion
#region LifeCycle
private void Awake()
{
Screen.fullScreen = false;
_synchronizationContext = SynchronizationContext.Current;
var address = GetIpAddress();
if (string.IsNullOrEmpty(address))
{
_address.text = "No Ip...";
return;
}
_address.text = address;
_logList = new List<string>(LogLength);
_stringBuilder = new StringBuilder(LogLength);
StartBroker();
}
private void OnDestroy()
{
_mqttServer?.StopAsync();
}
#endregion
#region MQTT
private IMqttServer _mqttServer;
private void StartBroker()
{
var factory = new MqttFactory();
_mqttServer = factory.CreateMqttServer();
_mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(StartedHandler);
_mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(StoppedHandler);
_mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate((ClientConnectedHandler));
_mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate((ClientDisconnectedHandler));
_mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate((ClientSubscribedHandler));
_mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate((ClientUnsubscribedHandler));
_mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate((ApplicationMessageReceivedHandler));
var options = new MqttServerOptions();
_mqttServer.StartAsync(options);
}
private static string GetIpAddress()
{
var hostname = Dns.GetHostName();
var adrList = Dns.GetHostAddresses(hostname);
foreach (var address in adrList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
return address.ToString();
}
}
return null;
}
#endregion
#region Handler
private Task StartedHandler(EventArgs args)
{
ShowLog("Started");
return Task.CompletedTask;
}
private Task StoppedHandler(EventArgs args)
{
ShowLog("Stopped");
return Task.CompletedTask;
}
private Task ClientConnectedHandler(MqttServerClientConnectedEventArgs args)
{
ShowLog($"ClientConnected : {args.ClientId}");
return Task.CompletedTask;
}
private Task ClientDisconnectedHandler(MqttServerClientDisconnectedEventArgs args)
{
ShowLog($"ClientDisconnected : {args.ClientId} {args.DisconnectType.ToString()}");
return Task.CompletedTask;
}
private Task ClientSubscribedHandler(MqttServerClientSubscribedTopicEventArgs args)
{
ShowLog($"ClientSubscribed : {args.ClientId} {args.TopicFilter.Topic}");
return Task.CompletedTask;
}
private Task ClientUnsubscribedHandler(MqttServerClientUnsubscribedTopicEventArgs args)
{
ShowLog($"ClientUnsubscribed : {args.ClientId} {args.TopicFilter}");
return Task.CompletedTask;
}
private Task ApplicationMessageReceivedHandler(MqttApplicationMessageReceivedEventArgs args)
{
var topic = args.ApplicationMessage.Topic;
var message = Encoding.UTF8.GetString(args.ApplicationMessage.Payload);
ShowLog($"{topic} - {message}");
return Task.CompletedTask;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment