public static byte[] ConvertToMqtt(MqttSession session, EventMessage message) { if (message.Protocol == ProtocolType.MQTT) { return(MqttConversion(session, message.Message)); } if (message.Protocol == ProtocolType.COAP) { CoapMessage msg = CoapMessage.DecodeMessage(message.Message); CoapUri curi = new CoapUri(msg.ResourceUri.ToString()); QualityOfServiceLevelType qos = QualityOfServiceLevelType.AtLeastOnce; QualityOfServiceLevelType?qosType = session.GetQoS(curi.Resource); qos = qosType ?? QualityOfServiceLevelType.AtLeastOnce; PublishMessage pub = new PublishMessage(false, qos, false, session.NewId(), curi.Resource, msg.Payload); return(pub.Encode()); } if (message.Protocol == ProtocolType.REST) { PublishMessage pubm = new PublishMessage(false, session.GetQoS(message.ResourceUri).Value, false, session.NewId(), message.ResourceUri, message.Message); return(pubm.Encode()); } return(MqttConversion(session, message.Message)); }
private void MqttServer_OnClientApplicationMessageReceive(MqttSession session, MqttClientApplicationMessage message) { if (session.Protocol == "MQTT") { // 异步的推送 } else { // 同步网络 if (message.Topic == "StartPLC") { string tmp = StartPLC( ); LogNet?.WriteInfo(tmp); // 远程启动设备 mqttServer.PublishTopicPayload(session, tmp, Encoding.UTF8.GetBytes(tmp)); } else if (message.Topic == "StopPLC") { string tmp = StopPLC( ); LogNet?.WriteInfo(tmp); // 远程停止设备 mqttServer.PublishTopicPayload(session, tmp, Encoding.UTF8.GetBytes(tmp)); } else { mqttServer.PublishTopicPayload(session, message.Topic, message.Payload); } } }
private void MqttServer_OnClientApplicationMessageReceive(MqttSession session, MqttClientApplicationMessage message) { if (message.Topic == "ndiwh是本地AIHDniwd") // 用户客户端的压力测试 { mqttServer.PublishTopicPayload(session, message.Topic, message.Payload); } if (session.Protocol == "HUSL") { // 当前的会话是同步通信的情况 if (message.Topic == "A") { // 测试回传一条数据信息 mqttServer.PublishTopicPayload(session, "B", Encoding.UTF8.GetBytes("这是回传的一条测试数据")); } // 如果不回传数据,客户端就会引发超时,关闭连接 } Invoke(new Action(() => { if (!isStop) { receiveCount++; textBox8.AppendText($"Cliend Id[{message.ClientId}] Topic:[{message.Topic}] Payload:[{Encoding.UTF8.GetString( message.Payload )}]" + Environment.NewLine); } })); }
private void MqttServer_OnClientConnected(MqttSession session) { if (checkBox3.Checked) { // 当客户端连接上来时,可以立即返回一些数据内容信息 mqttServer.PublishTopicPayload(session, "HslMqtt", Encoding.UTF8.GetBytes("This is a test message")); } }
private void MqttServer_OnClientConnected(MqttSession session) { if (session.Protocol == "MQTT") { // 当客户端连接上来的时候,进行回发一个初始化的数据信息 mqttServer.PublishTopicPayload(session, "2", GetHistory( )); } }
private void MqttServer_OnClientApplicationMessageReceive(MqttSession session, MqttClientApplicationMessage message) { if (message.Topic == "ndiwh是本地AIHDniwd") // 用户客户端的压力测试 { mqttServer.PublishTopicPayload(session, message.Topic, message.Payload); } if (session.Protocol == "HUSL") { // 当前的会话是同步通信的情况 if (message.Topic == "A") { // 测试回传一条数据信息 mqttServer.PublishTopicPayload(session, "B", Encoding.UTF8.GetBytes("这是回传的一条测试数据")); } else if (message.Topic == "B") { System.Threading.Thread.Sleep(1000); // 假设服务器处理数据要耗费10秒钟 for (int i = 0; i < 10; i++) { System.Threading.Thread.Sleep(1000); mqttServer.ReportProgress(session, ((i + 1) * 10).ToString( ), $"当前正在处理{i + 1}步"); } System.Threading.Thread.Sleep(1000); mqttServer.PublishTopicPayload(session, StringResources.Language.SuccessText, Encoding.UTF8.GetBytes("B操作处理成功")); } else if (message.Topic == "C") { // 回传一条1M的数据 byte[] buffer = new byte[1024 * 1024]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = 0x30; } mqttServer.PublishTopicPayload(session, "C", buffer); } // 如果不回传数据,客户端就会引发超时,关闭连接 } Invoke(new Action(() => { if (!isStop) { receiveCount++; if (message.Payload?.Length > 100) { textBox8.AppendText($"Cliend Id[{message.ClientId}] Topic:[{message.Topic}] Payload:[{Encoding.UTF8.GetString( message.Payload.SelectBegin( 100 ) )}...]" + Environment.NewLine); } else { textBox8.AppendText($"Cliend Id[{message.ClientId}] Topic:[{message.Topic}] Payload:[{Encoding.UTF8.GetString( message.Payload )}]" + Environment.NewLine); } } })); }
private int MqttServer_ClientVerification(MqttSession mqttSession, string clientId, string userName, string passwrod) { if (userName == "admin" && passwrod == "123456") { return(0); // 成功 } else { return(5); // 账号密码验证失败 } }
public void TestInitialize() { var logger = new TestLogger(); var options = new MqttServerOptions(); var retainedMessagesManager = new MqttRetainedMessagesManager(new MqttServerEventContainer(), logger); var eventContainer = new MqttServerEventContainer(); var clientSessionManager = new MqttClientSessionsManager(options, retainedMessagesManager, eventContainer, logger); var session = new MqttSession("", false, new ConcurrentDictionary <object, object>(), options, eventContainer, retainedMessagesManager, clientSessionManager); _subscriptionsManager = new MqttClientSubscriptionsManager(session, new MqttServerEventContainer(), retainedMessagesManager, clientSessionManager); }
public GenericMqttClient(MqttConfig config, IChannel channel, IMqttDispatch dispatcher = null) { this.dispatcher = dispatcher ?? new GenericMqttDispatcher(); session = new MqttSession(config); session.OnConnect += Session_OnConnect; session.OnDisconnect += Session_OnDisconnect; session.OnRetry += Session_OnRetry; this.channel = channel; this.channel.OnReceive += Channel_OnReceive; this.channel.OnClose += Channel_OnClose; this.channel.OnError += Channel_OnError; this.channel.OnStateChange += Channel_OnStateChange; }
public static MqttMessageHandler Create(MqttSession session, MqttMessage message, IMqttDispatch dispatcher = null) { switch (message.MessageType) { case MqttMessageType.CONNACK: return(new MqttConnackHandler(session, message)); case MqttMessageType.CONNECT: return(new MqttConnectHandler(session, message)); case MqttMessageType.DISCONNECT: return(new MqttDisconnectHandler(session, message)); case MqttMessageType.PINGREQ: return(new MqttPingReqHandler(session, message)); case MqttMessageType.PINGRESP: return(new MqttPingRespHandler(session, message)); case MqttMessageType.PUBACK: return(new MqttPubAckHandler(session, message)); case MqttMessageType.PUBCOMP: return(new MqttPubCompHandler(session, message)); case MqttMessageType.PUBLISH: return(new MqttPublishHandler(session, message, dispatcher)); case MqttMessageType.PUBREC: return(new MqttPubRecHandler(session, message)); case MqttMessageType.PUBREL: return(new MqttPubRelHandler(session, message, dispatcher)); case MqttMessageType.SUBACK: return(new MqttSubAckHandler(session, message)); case MqttMessageType.SUBSCRIBE: return(new MqttSubscribeHandler(session, message)); case MqttMessageType.UNSUBACK: return(new MqttUnsubAckHandler(session, message)); case MqttMessageType.UNSUBSCRIBE: return(new MqttUnsubscribeHandler(session, message)); default: throw new InvalidCastException("MqttMessageType"); } }
private static byte[] MqttConversion(MqttSession session, byte[] message, string contentType = null) { PublishMessage msg = MqttMessage.DecodeMessage(message) as PublishMessage; MqttUri uri = new MqttUri(msg.Topic); QualityOfServiceLevelType?qos = session.GetQoS(uri.Resource); PublishMessage pm = new PublishMessage(false, qos.HasValue ? qos.Value : QualityOfServiceLevelType.AtMostOnce, false, session.NewId(), uri.Resource, msg.Payload); if (pm.QualityOfService != QualityOfServiceLevelType.AtMostOnce) { session.Quarantine(pm, SkunkLab.Protocols.Mqtt.Handlers.DirectionType.Out); } return(pm.Encode()); }
public GenericMqttClient(MqttConfig config, IChannel channel, IMqttDispatch dispatcher = null) { this.dispatcher = dispatcher != null ? dispatcher : new GenericMqttDispatcher(); timeoutMilliseconds = config.MaxTransmitSpan.TotalMilliseconds; session = new MqttSession(config); session.OnConnect += Session_OnConnect; session.OnDisconnect += Session_OnDisconnect; session.OnRetry += Session_OnRetry; this.channel = channel; this.channel.OnReceive += Channel_OnReceive; this.channel.OnClose += Channel_OnClose; this.channel.OnError += Channel_OnError; this.channel.OnStateChange += Channel_OnStateChange; }
private void MqttServer_OnClientApplicationMessageReceive(MqttSession session, MqttClientApplicationMessage message) { if (message.Topic == "ndiwh是本地AIHDniwd") // 用户客户端的压力测试 { mqttServer.PublishTopicPayload(session, message.Topic, message.Payload); } Invoke(new Action(() => { if (!isStop) { receiveCount++; textBox8.AppendText($"Cliend Id[{message.ClientId}] Topic:[{message.Topic}] Payload:[{Encoding.UTF8.GetString( message.Payload )}]" + Environment.NewLine); } })); }
private static byte[] MqttConversion(MqttSession session, byte[] message) { PublishMessage msg = MqttMessage.DecodeMessage(message) as PublishMessage; MqttUri uri = new MqttUri(msg.Topic); QualityOfServiceLevelType?qos = session.GetQoS(uri.Resource); PublishMessage pm = new PublishMessage(false, qos ?? QualityOfServiceLevelType.AtMostOnce, false, session.NewId(), uri.Resource, msg.Payload); if (pm.QualityOfService != QualityOfServiceLevelType.AtMostOnce) { session.Quarantine(pm, DirectionType.Out); } return(pm.Encode()); }
/// <summary> /// Disconnect from Piraeus /// </summary> /// <returns></returns> public async Task DisconnectAsync() { string id = null; try { id = channel.Id; DisconnectMessage msg = new DisconnectMessage(); if (channel.IsConnected) { await channel.SendAsync(msg.Encode()); } } catch (Exception ex) { string disconnectMsgError = String.Format("ERROR: Sending MQTT Disconnect message '{0}'", ex.Message); Console.WriteLine(disconnectMsgError); Trace.TraceError(disconnectMsgError); } try { channel.Dispose(); } catch (Exception ex) { string channelDisposeMsgError = String.Format("ERROR: MQTT channel dispose after disconnect '{0}'", ex.Message); Console.WriteLine(channelDisposeMsgError); Trace.TraceError(channelDisposeMsgError); } try { if (session != null) { session.Dispose(); session = null; } } catch (Exception ex) { string sessionDisposeMsgError = String.Format("ERROR: MQTT session dispose after disconnect '{0}'", ex.Message); Console.WriteLine(sessionDisposeMsgError); Trace.TraceError(sessionDisposeMsgError); } }
public PiraeusMqttClient(MqttConfig config, IChannel channel, IMqttDispatch dispatcher = null) { this.dispatcher = dispatcher ?? new GenericMqttDispatcher(); timeoutMilliseconds = config.MaxTransmitSpan.TotalMilliseconds; session = new MqttSession(config); session.OnKeepAlive += Session_OnKeepAlive; session.OnConnect += Session_OnConnect; session.OnDisconnect += Session_OnDisconnect; session.OnRetry += Session_OnRetry; Channel = channel; Channel.OnReceive += Channel_OnReceive; Channel.OnClose += Channel_OnClose; Channel.OnError += Channel_OnError; Channel.OnStateChange += Channel_OnStateChange; queue = new Queue <byte[]>(); }
public MqttProtocolAdapter(PiraeusConfig config, IAuthenticator authenticator, IChannel channel, ILogger logger, HttpContext context = null) { this.config = config; this.logger = logger; MqttConfig mqttConfig = new MqttConfig(config.KeepAliveSeconds, config.AckTimeoutSeconds, config.AckRandomFactor, config.MaxRetransmit, config.MaxLatencySeconds, authenticator, config.ClientIdentityNameClaimType, config.GetClientIndexes()); this.context = context; session = new MqttSession(mqttConfig); InitializeAuditor(config); Channel = channel; Channel.OnClose += Channel_OnClose; Channel.OnError += Channel_OnError; Channel.OnStateChange += Channel_OnStateChange; Channel.OnReceive += Channel_OnReceive; Channel.OnOpen += Channel_OnOpen; }
public async Task CloseAsync() { if (session != null) { session.Dispose(); session = null; } try { channel.Dispose(); } catch (Exception ex) { Console.WriteLine("Channel close exception {0}", ex.Message); Console.WriteLine("Channel close exception stack trace {0}", ex.StackTrace); } await Task.CompletedTask; }
public static MqttMessageHandler Create(MqttSession session, MqttMessage message, IMqttDispatch dispatcher = null) { return(message.MessageType switch { MqttMessageType.CONNACK => new MqttConnackHandler(session, message), MqttMessageType.CONNECT => new MqttConnectHandler(session, message), MqttMessageType.DISCONNECT => new MqttDisconnectHandler(session, message), MqttMessageType.PINGREQ => new MqttPingReqHandler(session, message), MqttMessageType.PINGRESP => new MqttPingRespHandler(session, message), MqttMessageType.PUBACK => new MqttPubAckHandler(session, message), MqttMessageType.PUBCOMP => new MqttPubCompHandler(session, message), MqttMessageType.PUBLISH => new MqttPublishHandler(session, message, dispatcher), MqttMessageType.PUBREC => new MqttPubRecHandler(session, message), MqttMessageType.PUBREL => new MqttPubRelHandler(session, message, dispatcher), MqttMessageType.SUBACK => new MqttSubAckHandler(session, message), MqttMessageType.SUBSCRIBE => new MqttSubscribeHandler(session, message), MqttMessageType.UNSUBACK => new MqttUnsubAckHandler(session, message), MqttMessageType.UNSUBSCRIBE => new MqttUnsubscribeHandler(session, message), _ => throw new InvalidCastException("MqttMessageType") });
private OperateResult MqttServer_FileOperateVerification(MqttSession session, byte code, string[] groups, string[] fileNames) { // 进行文件操作时候的验证 if (string.IsNullOrEmpty(session.UserName)) { // 用户名为空时,不能删除文件 if (code == MqttControlMessage.FileDelete) { return(new OperateResult("Null Account Not Allowed operation")); } } if (session.UserName == "hsl") { // 用户名为hsl时,不能上传,下载,删除 if (code == MqttControlMessage.FileUpload || code == MqttControlMessage.FileDelete || code == MqttControlMessage.FileDownload) { return(new OperateResult("Account hsl not Allowed operation")); } } return(OperateResult.CreateSuccessResult( )); }
public static byte[] ConvertToMqtt(MqttSession session, EventMessage message) { if (message.Protocol == ProtocolType.MQTT) { return(MqttConversion(session, message.Message)); } else if (message.Protocol == ProtocolType.COAP) { CoapMessage msg = CoapMessage.DecodeMessage(message.Message); CoapUri curi = new CoapUri(msg.ResourceUri.ToString()); QualityOfServiceLevelType qos = QualityOfServiceLevelType.AtLeastOnce; try { QualityOfServiceLevelType?qosType = session.GetQoS(curi.Resource); qos = qosType.HasValue ? qosType.Value : QualityOfServiceLevelType.AtLeastOnce; } catch (Exception ex) { Trace.TraceWarning("{0} - Fault in ProtocolTransition.ConvertToMqtt", DateTime.UtcNow.ToString()); Trace.TraceError("{0} - {1} - {2}", DateTime.UtcNow.ToString(""), "ProtocolTransition", ex.Message); } PublishMessage pub = new PublishMessage(false, qos, false, session.NewId(), curi.Resource, msg.Payload); return(pub.Encode()); } else if (message.Protocol == ProtocolType.REST) { PublishMessage pubm = new PublishMessage(false, session.GetQoS(message.ResourceUri).Value, false, session.NewId(), message.ResourceUri, message.Message); return(pubm.Encode()); } else { return(MqttConversion(session, message.Message, message.ContentType)); } }
public MqttConnectHandler(MqttSession session, MqttMessage message) : base(session, message) { }
public MqttSubAckHandler(MqttSession session, MqttMessage message) : base(session, message) { }
protected MqttMessageHandler(MqttSession session, MqttMessage message, IMqttDispatch dispatcher = null) { Session = session; Message = message; Dispatcher = dispatcher; }
public MqttUnsubscribeHandler(MqttSession session, MqttMessage message) : base(session, message) { }
public MqttPingRespHandler(MqttSession session, MqttMessage message) : base(session, message) { }
public MqttPubRelHandler(MqttSession session, MqttMessage message, IMqttDispatch dispatcher) : base(session, message, dispatcher) { }
private void MqttServer_OnClientApplicationMessageReceive(MqttSession session, MqttClientApplicationMessage message) { if (message.Topic == "ndiwh是本地AIHDniwd") // 用户客户端的压力测试 { mqttServer.PublishTopicPayload(session, message.Topic, message.Payload); } if (session.Protocol == "HUSL") { // 当前的会话是同步通信的情况 if (message.Topic == "A") { // 测试回传一条数据信息 mqttServer.PublishTopicPayload(session, "B", Encoding.UTF8.GetBytes("这是回传的一条测试数据")); } else if (message.Topic == "B") { System.Threading.Thread.Sleep(1000); // 假设服务器处理数据要耗费10秒钟 for (int i = 0; i < 10; i++) { System.Threading.Thread.Sleep(1000); mqttServer.ReportProgress(session, ((i + 1) * 10).ToString( ), $"当前正在处理{i + 1}步"); } System.Threading.Thread.Sleep(1000); mqttServer.PublishTopicPayload(session, StringResources.Language.SuccessText, Encoding.UTF8.GetBytes("B操作处理成功")); } else if (message.Topic == "C") { // 回传一条1M的数据 byte[] buffer = new byte[1024 * 1024]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = 0x30; } mqttServer.PublishTopicPayload(session, "C", buffer); } else if (message.Topic == "D") { // 返回一条操作失败的信息 mqttServer.ReportOperateResult(session, "当前的功能码不支持!"); } else if (message.Topic == "E") { // 返回一条操作结果的信息 if (random.Next(100) < 50) { mqttServer.ReportOperateResult(session, new OperateResult <string>("当前的结果为失败信息")); } else { mqttServer.ReportOperateResult(session, OperateResult.CreateSuccessResult("成功")); } } else if (message.Topic == "F") { // 返回当前对象支持的API信息 mqttServer.PublishTopicPayload(session, "list", Encoding.UTF8.GetBytes(JArray.FromObject(MqttHelper.GetSyncServicesApiInformationFromObject(this)).ToString( ))); } else { // 如果不回传数据,客户端就会引发超时,关闭连接 // 下面是示例,支持了一个CheckName的接口数据,返回类型必须是 OperateResult<string> // mqttServer.ReportObjectApiMethod( session, message, this ); } } Invoke(new Action(() => { if (!isStop) { receiveCount++; if (message.Payload?.Length > 100) { textBox8.AppendText($"Cliend Id[{message.ClientId}] Topic:[{message.Topic}] Payload:[{Encoding.UTF8.GetString( message.Payload.SelectBegin( 100 ) )}...]" + Environment.NewLine); } else { textBox8.AppendText($"Cliend Id[{message.ClientId}] Topic:[{message.Topic}] Payload:[{Encoding.UTF8.GetString( message.Payload )}]" + Environment.NewLine); } } })); }
public MqttPubRecHandler(MqttSession session, MqttMessage message) : base(session, message) { }