예제 #1
0
        private void Adapter_OnObserve(object sender, ObserveMessageEventArgs e)
        {
            MessageAuditRecord record = null;
            int      length           = 0;
            DateTime sendTime         = DateTime.UtcNow;

            try
            {
                byte[] message = ProtocolTransition.ConvertToMqtt(session, e.Message);
                Send(message).LogExceptions();

                MqttMessage mm = MqttMessage.DecodeMessage(message);

                length = mm.Payload.Length;
                record = new MessageAuditRecord(e.Message.MessageId, session.Identity, Channel.TypeId, "MQTT", length,
                                                MessageDirectionType.Out, true, sendTime);
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0} - MQTT adapter observe error on channel '{1}' with '{2}'",
                                           DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), Channel.Id, ex.Message);
                logger?.LogErrorAsync(ex, $"MQTT adapter observe error on channel '{Channel.Id}'.").GetAwaiter();
                record = new MessageAuditRecord(e.Message.MessageId, session.Identity, Channel.TypeId, "MQTT", length,
                                                MessageDirectionType.Out, true, sendTime, msg);
            }
            finally
            {
                if (e.Message.Audit)
                {
                    messageAuditor?.WriteAuditRecordAsync(record).Ignore();
                }
            }
        }
예제 #2
0
        public static byte[] ConvertToCoap(CoapSession session, EventMessage message, byte[] observableToken = null)
        {
            CoapMessage coapMessage = null;
            CoapToken   token       = CoapToken.Create();

            ushort id = observableToken == null?session.CoapSender.NewId(token.TokenBytes) : session.CoapSender.NewId(observableToken);

            string uriString = CoapUri.Create(session.Config.Authority, message.ResourceUri, IsEncryptedChannel);

            if (message.Protocol == ProtocolType.MQTT)
            {
                MqttMessage    msg = MqttMessage.DecodeMessage(message.Message);
                PublishMessage pub = msg as PublishMessage;
                MqttUri        uri = new MqttUri(pub.Topic);
                if (observableToken == null)
                {
                    RequestMessageType messageType = msg.QualityOfService == QualityOfServiceLevelType.AtMostOnce ? RequestMessageType.NonConfirmable : RequestMessageType.Confirmable;
                    //request
                    coapMessage = new CoapRequest(id, messageType, MethodType.POST, new Uri(uriString), MediaTypeConverter.ConvertToMediaType(message.ContentType));
                }
                else
                {
                    //response
                    coapMessage = new CoapResponse(id, ResponseMessageType.NonConfirmable, ResponseCodeType.Content, observableToken, MediaTypeConverter.ConvertToMediaType(uri.ContentType), msg.Payload);
                }
            }
            else if (message.Protocol == ProtocolType.COAP)
            {
                CoapMessage msg = CoapMessage.DecodeMessage(message.Message);
                if (observableToken == null)
                {
                    //request
                    coapMessage = new CoapRequest(id, msg.MessageType == CoapMessageType.Confirmable ? RequestMessageType.Confirmable : RequestMessageType.NonConfirmable, MethodType.POST, new Uri(uriString), MediaTypeConverter.ConvertToMediaType(message.ContentType), msg.Payload);
                }
                else
                {
                    //response
                    coapMessage = new CoapResponse(id, ResponseMessageType.NonConfirmable, ResponseCodeType.Content, observableToken, MediaTypeConverter.ConvertToMediaType(message.ContentType), msg.Payload);
                }
            }
            else
            {
                if (observableToken == null)
                {
                    //request
                    coapMessage = new CoapRequest(id, RequestMessageType.NonConfirmable, MethodType.POST, new Uri(uriString), MediaTypeConverter.ConvertToMediaType(message.ContentType), message.Message);
                }
                else
                {
                    //response
                    coapMessage = new CoapResponse(id, ResponseMessageType.NonConfirmable, ResponseCodeType.Content, observableToken, MediaTypeConverter.ConvertToMediaType(message.ContentType), message.Message);
                }
            }

            return(coapMessage.Encode());
        }
예제 #3
0
        private void Channel_OnReceive(object sender, ChannelReceivedEventArgs args)
        {
            MqttMessage        msg     = MqttMessage.DecodeMessage(args.Message);
            MqttMessageHandler handler = MqttMessageHandler.Create(session, msg);

            MqttMessage response = handler.ProcessAsync().GetAwaiter().GetResult();

            if (response != null)
            {
                channel.SendAsync(response.Encode()).GetAwaiter();
            }
        }
예제 #4
0
        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());
        }
예제 #5
0
        private void Channel_OnReceive(object sender, ChannelReceivedEventArgs e)
        {
            try
            {
                MqttMessage msg = MqttMessage.DecodeMessage(e.Message);
                OnObserve?.Invoke(this, new ChannelObserverEventArgs(Channel.Id, null, null, e.Message));

                if (!session.IsAuthenticated)
                {
                    if (!(msg is ConnectMessage message))
                    {
                        throw new SecurityException("Connect message not first message");
                    }

                    if (session.Authenticate(message.Username, message.Password))
                    {
                        IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context,
                                                                      session.Config.Indexes);
                        session.Identity = decoder.Id;
                        session.Indexes  = decoder.Indexes;
                        adapter.Identity = decoder.Id;

                        UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity,
                                                                     session.Config.IdentityClaimType, Channel.TypeId, "MQTT", "Granted", DateTime.UtcNow);
                        userAuditor?.WriteAuditRecordAsync(record).Ignore();
                    }
                    else
                    {
                        throw new SecurityException("Session could not be authenticated.");
                    }
                }
                else if (forcePerReceiveAuthn)
                {
                    if (!session.Authenticate())
                    {
                        throw new SecurityException("Per receive authentication failed.");
                    }
                }

                ProcessMessageAsync(msg).GetAwaiter();
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"MQTT adapter Channel_OnReceive error on channel '{Channel.Id}'.")
                .GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }
        }
예제 #6
0
        public static byte[] ConvertToHttp(EventMessage message)
        {
            if (message.Protocol == ProtocolType.MQTT)
            {
                MqttMessage mqtt = MqttMessage.DecodeMessage(message.Message);
                return(mqtt.Payload);
            }

            if (message.Protocol == ProtocolType.COAP)
            {
                CoapMessage coap = CoapMessage.DecodeMessage(message.Message);
                return(coap.Payload);
            }

            return(message.Message);
        }
예제 #7
0
        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());
        }
예제 #8
0
        private void Channel_OnReceive(object sender, ChannelReceivedEventArgs args)
        {
            MqttMessage        msg     = MqttMessage.DecodeMessage(args.Message);
            MqttMessageHandler handler = MqttMessageHandler.Create(session, msg, dispatcher);

            try
            {
                MqttMessage message = handler.ProcessAsync().GetAwaiter().GetResult();
                if (message != null)
                {
                    channel.SendAsync(message.Encode()).GetAwaiter();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Trace.TraceError(ex.Message);
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex));
            }

            //Task task = Task.Factory.StartNew(async () =>
            //{
            //    try
            //    {
            //        MqttMessage message = await handler.ProcessAsync();
            //        if (message != null)
            //        {
            //            await channel.SendAsync(message.Encode());
            //        }
            //    }
            //    catch(Exception ex)
            //    {
            //        Console.WriteLine(ex.Message);
            //        Trace.TraceError(ex.Message);
            //    }
            //});

            //Task.WaitAll(task);

            //if (task.Exception != null)
            //{
            //    OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, task.Exception.InnerException));
            //}
        }
예제 #9
0
        private void Channel_OnReceive(object sender, ChannelReceivedEventArgs args)
        {
            MqttMessage        msg     = MqttMessage.DecodeMessage(args.Message);
            MqttMessageHandler handler = MqttMessageHandler.Create(session, msg, dispatcher);

            try
            {
                MqttMessage message = handler.ProcessAsync().GetAwaiter().GetResult();
                if (message != null)
                {
                    Channel.SendAsync(message.Encode()).GetAwaiter();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Trace.TraceError(ex.Message);
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(Channel.Id, ex));
            }
        }
예제 #10
0
        private byte[] GetPayload(EventMessage message)
        {
            switch (message.Protocol)
            {
            case ProtocolType.COAP:
                CoapMessage coap = CoapMessage.DecodeMessage(message.Message);
                return(coap.Payload);

            case ProtocolType.MQTT:
                MqttMessage mqtt = MqttMessage.DecodeMessage(message.Message);
                return(mqtt.Payload);

            case ProtocolType.REST:
                return(message.Message);

            case ProtocolType.WSN:
                return(message.Message);

            default:
                return(null);
            }
        }
예제 #11
0
        void DecodeMessage(byte[] buffer)
        {
            var msg = MqttMessage.DecodeMessage(buffer);

            Debug.WriteLine("onRecv:{0}", msg.FixedHeader.MessageType);
            switch (msg.FixedHeader.MessageType)
            {
            case MessageType.CONNACK:
                var connAckMsg = (ConnAckMessage)msg;
                if (connAckMsg.ReturnCode == MqttConnectReturnCode.BrokerUnavailable ||
                    connAckMsg.ReturnCode == MqttConnectReturnCode.IdentifierRejected ||
                    connAckMsg.ReturnCode == MqttConnectReturnCode.UnacceptedProtocolVersion ||
                    connAckMsg.ReturnCode == MqttConnectReturnCode.NotAuthorized ||
                    connAckMsg.ReturnCode == MqttConnectReturnCode.BadUsernameOrPassword)
                {
                    ConnectionState = ConnectionState.Disconnecting;
                    Dispose();
                    conn            = null;
                    ConnectionState = ConnectionState.Disconnected;
                }
                else
                {
                    ConnectionState = ConnectionState.Connected;
                }
                connResetEvent.Set();
                break;

            case MessageType.PUBLISH:
                var    pubMsg = (PublishMessage)msg;
                string topic  = pubMsg.TopicName;
                var    data   = pubMsg.Payload;
                if (pubMsg.FixedHeader.Qos == Qos.AtLeastOnce)
                {
                    var ackMsg = new PublishAckMessage();
                    ackMsg.MessageIdentifier = pubMsg.MessageIdentifier;
                    conn.SendMessage(ackMsg);
                }
                OnMessageReceived(topic, data);
                break;

            case MessageType.PUBACK:
                var pubAckMsg = (PublishAckMessage)msg;
                Debug.WriteLine("PUBACK MessageIdentifier:" + pubAckMsg.MessageIdentifier);
                break;

            case MessageType.PUBREC:
                break;

            case MessageType.PUBREL:
                break;

            case MessageType.PUBCOMP:
                break;

            case MessageType.SUBSCRIBE:
                break;

            case MessageType.SUBACK:
                break;

            case MessageType.UNSUBSCRIBE:
                break;

            case MessageType.UNSUBACK:
                break;

            case MessageType.PINGREQ:
                conn.SendMessage(new PingRespMessage());
                break;

            case MessageType.DISCONNECT:
                Disconnect();
                break;
            }
        }