public void ProcessTransfer(AMQPData data, long?handle, bool?settled, long?_deliveryId)
        {
            QOS qos = QOS.AT_LEAST_ONCE;

            if (settled.HasValue && settled.Value)
            {
                qos = QOS.AT_MOST_ONCE;
            }
            else
            {
                AMQPDisposition disposition = new AMQPDisposition();
                disposition.Channel = _channel;
                disposition.Role    = RoleCodes.RECEIVER;
                disposition.First   = _deliveryId.Value;
                disposition.Last    = _deliveryId.Value;
                disposition.Settled = true;
                disposition.State   = new AMQPAccepted();
                _client.Send(disposition);
            }

            String topicName = null;

            if (!handle.HasValue || !_usedMappings.ContainsKey(handle.Value))
            {
                return;
            }

            topicName = _usedMappings[handle.Value];
            _dbInterface.StoreMessage(topicName, data.Data, qos);

            if (_listener != null)
            {
                _listener.MessageReceived(MessageType.PUBLISH);
            }
        }
Beispiel #2
0
        private void addTopicButton_Click(object sender, EventArgs e)
        {
            if (txtNewTopicName.Text.Length == 0)
            {
                MessageBox.Show("Topic is required");
                return;
            }

            if (cmbNewTopicQOS.SelectedIndex == -1)
            {
                MessageBox.Show("Please choose QOS");
                return;
            }

            QOS topicQOS = QOS.AT_MOST_ONCE;

            switch (cmbNewTopicQOS.SelectedIndex)
            {
            case 1:
                topicQOS = QOS.AT_LEAST_ONCE;
                break;

            case 2:
                topicQOS = QOS.EXACTLY_ONCE;
                break;
            }

            mqtt.avps.Topic[] topics = new mqtt.avps.Topic[] { new mqtt.avps.Topic(txtNewTopicName.Text, topicQOS) };
            txtNewTopicName.Text = String.Empty;

            cmbNewTopicQOS.SelectedIndex = -1;

            MessageBox.Show("Topic Request Sent", "Adding new topic request sent to server", MessageBoxButtons.OK, MessageBoxIcon.Information);
            _client.Subscribe(topics);
        }
Beispiel #3
0
        public void StoreTopic(string topicName, QOS qos)
        {
            MQTTModel model  = new MQTTModel();
            var       topics = from t in model.Topics where t.TopicName == topicName where t.Account.ID == defaultAccount.ID select t;

            if (topics.Count() > 0)
            {
                Topic currTopic = topics.First();
                currTopic.QOS = qos;
                model.Topics.Attach(currTopic);
                var entry = model.Entry(currTopic);
                entry.Property(t => t.QOS).IsModified = true;
                model.SaveChanges();
            }
            else
            {
                Topic newTopic = new Topic();
                newTopic.QOS       = qos;
                newTopic.TopicName = topicName;
                newTopic.Account   = defaultAccount;

                model.Accounts.Attach(defaultAccount);
                model.Topics.Add(newTopic);
                model.Entry(defaultAccount).State = EntityState.Unchanged;
                model.SaveChanges();
            }
        }
        public void ProcessSuback(Int32 packetID, List <SubackCode> codes)
        {
            MQMessage message = _timers.Remove(packetID);

            foreach (SubackCode code in codes)
            {
                if (code == SubackCode.FAILURE)
                {
                    throw new CoreLogicException("received invalid message suback");
                }
                else
                {
                    Subscribe subscribe   = (Subscribe)message;
                    Topic     topic       = subscribe.Topics[0];
                    QOS       expectedQos = topic.Qos;
                    QOS       actualQos   = (QOS)((int)code);
                    if (expectedQos == actualQos)
                    {
                        _dbInterface.StoreTopic(topic.Name, expectedQos);
                    }
                    else
                    {
                        _dbInterface.StoreTopic(topic.Name, actualQos);
                    }

                    if (_listener != null)
                    {
                        _listener.MessageReceived(MessageType.SUBACK);
                    }
                }
            }
        }
        public void ProcessPublish(Int32?packetID, Topic topic, byte[] content, Boolean retain, Boolean isDup)
        {
            QOS publisherQos = topic.Qos;

            switch (publisherQos)
            {
            case QOS.AT_LEAST_ONCE:
                Puback puback = new Puback(packetID.Value);
                _client.Send(puback);
                break;

            case QOS.EXACTLY_ONCE:
                Pubrec pubrec = new Pubrec(packetID.Value);
                _client.Send(pubrec);
                break;

            default:
                break;
            }

            String topicName = topic.Name;

            if (!(isDup && publisherQos == QOS.EXACTLY_ONCE))
            {
                _dbInterface.StoreMessage(topicName, content, publisherQos);
            }

            if (_listener != null)
            {
                _listener.MessageReceived(MessageType.PUBLISH);
            }
        }
Beispiel #6
0
        public void ProcessPublish(Int32?packetID, SNTopic topic, Byte[] content, Boolean retain, Boolean isDup)
        {
            SNQoS publisherQos = topic.getQos();
            QOS   realQos      = QOS.AT_MOST_ONCE;

            switch (publisherQos)
            {
            case SNQoS.AT_LEAST_ONCE:
                SNPuback puback = new SNPuback();
                puback.MessageID  = packetID;
                puback.ReturnCode = ReturnCode.ACCEPTED;
                int topicID = 0;
                if (topic is IdentifierTopic)
                {
                    topicID = ((IdentifierTopic)topic).Value;
                }
                else if (topic is ShortTopic)
                {
                    topicID = Int32.Parse(((ShortTopic)topic).Value);
                }

                puback.topicID = topicID;
                _client.Send(puback);
                realQos = QOS.AT_LEAST_ONCE;
                break;

            case SNQoS.EXACTLY_ONCE:
                realQos = QOS.EXACTLY_ONCE;
                SNPubrec pubrec = new SNPubrec(packetID.Value);
                _client.Send(pubrec);
                break;

            default:
                break;
            }

            String topicName = String.Empty;

            if (topic is IdentifierTopic && mappedTopics.ContainsKey(((IdentifierTopic)topic).Value))
            {
                topicName = mappedTopics[((IdentifierTopic)topic).Value];
            }

            if (topicName.Length == 0)
            {
                return;
            }

            if (!(isDup && publisherQos == SNQoS.EXACTLY_ONCE))
            {
                _dbInterface.StoreMessage(topicName, content, realQos);
            }

            if (_listener != null)
            {
                _listener.MessageReceived(MessageType.PUBLISH);
            }
        }
Beispiel #7
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="topic">Message topic</param>
 /// <param name="message">Message data</param>
 /// <param name="dupFlag">Duplicate delivery flag</param>
 /// <param name="qosLevel">Quality of Service level</param>
 /// <param name="retain">Retain flag</param>
 public MqttMsgPublishEventArgs(string topic,
                                byte[] message,
                                bool dupFlag,
                                QOS qosLevel,
                                bool retain)
 {
     Topic    = topic;
     Message  = message;
     DupFlag  = dupFlag;
     QosLevel = qosLevel;
     Retain   = retain;
 }
Beispiel #8
0
        public void From_XML(System.Xml.Linq.XElement xml)
        {
            Reset();
            if (xml == null)
            {
                return;
            }
            var element = xml.Name == "network" ? xml : null;

            if (element == null)
            {
                return;
            }
            var attr = element.Attribute("ipv6");

            if (attr != null)
            {
                ipv6 = attr.Value.ToLower() == "yes";
            }

            var ele = element.Element("name");

            if (ele != null)
            {
                name = ele.Value;
            }
            ele = element.Element("mac");
            if (ele != null)
            {
                attr = ele.Attribute("name");
                if (attr != null)
                {
                    mac = attr.Value;
                }
            }
            ele = element.Element("uuid");
            if (ele != null)
            {
                uuid = ele.Value;
            }
            ele = element.Element("forward");
            if (ele != null)
            {
                attr = ele.Attribute("mode");
                if (attr != null)
                {
                    Forward_Type = (Forward_Types)Enum.Parse(typeof(Forward_Types), attr.Value);
                }
            }
            Bridge.From_XML(element.Element("bridge"));
            QOS.From_XML(element.Element("bandwidth"));
            Configuration.From_XML(element.Element("ip"));
        }
Beispiel #9
0
        public static byte ToByte(this QOS value)
        {
            switch (value)
            {
            case QOS.QOS0: return(0);

            case QOS.QOS1: return(1);

            case QOS.QOS2: return(2);
            }

            throw new Exception("Unexpected QOS value");
        }
Beispiel #10
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="topic">Message topic</param>
        /// <param name="message">Message data</param>
        /// <param name="dupFlag">Duplicate flag</param>
        /// <param name="qosLevel">Quality of Service level</param>
        /// <param name="retain">Retain flag</param>
        public MqttMsgPublish(string topic,
                              byte[] message,
                              bool dupFlag,
                              QOS qosLevel,
                              bool retain) : base()
        {
            this._type = MQTT_MSG_PUBLISH_TYPE;

            this.topic       = topic;
            this.message     = message;
            this._dupFlag    = dupFlag;
            this._qosLevel   = qosLevel;
            this._retainFlag = retain;
            this._messageId  = 0;
        }
Beispiel #11
0
        public void ProcessSuback(Int32 packetID, Int32 topicID, ReturnCode returnCode, SNQoS allowedQos)
        {
            SNMessage message = _timers.Remove(packetID);

            if (returnCode != ReturnCode.ACCEPTED)
            {
                throw new CoreLogicException("received invalid message suback");
            }
            else
            {
                SNSubscribe subscribe = (SNSubscribe)message;
                String      topicName = String.Empty;
                if (subscribe.SnTopic is IdentifierTopic)
                {
                    topicName = mappedTopics[((IdentifierTopic)subscribe.SnTopic).Value];
                }
                else
                {
                    topicName = ((FullTopic)subscribe.SnTopic).Value;
                }

                SNQoS actualQos = allowedQos;
                QOS   realQos   = QOS.AT_LEAST_ONCE;
                switch (actualQos)
                {
                case SNQoS.AT_MOST_ONCE:
                    realQos = QOS.AT_MOST_ONCE;
                    break;

                case SNQoS.EXACTLY_ONCE:
                    realQos = QOS.EXACTLY_ONCE;
                    break;

                case SNQoS.LEVEL_ONE:
                    realQos = QOS.AT_MOST_ONCE;
                    break;
                }

                _dbInterface.StoreTopic(topicName, realQos);

                if (_listener != null)
                {
                    _listener.MessageReceived(MessageType.SUBACK);
                }
            }
        }
Beispiel #12
0
        public void StoreMessage(string topicName, byte[] content, QOS qos)
        {
            Message newMessage = new Message();

            newMessage.QOS       = qos;
            newMessage.Content   = content;
            newMessage.TopicName = topicName;
            newMessage.Incoming  = true;
            newMessage.Account   = defaultAccount;

            MQTTModel model = new MQTTModel();

            model.Accounts.Attach(defaultAccount);
            model.Messages.Add(newMessage);
            model.Entry(defaultAccount).State = EntityState.Unchanged;
            model.SaveChanges();
        }
Beispiel #13
0
        public string To_XML()
        {
            var ret = "<network ipv6='" + (ipv6 ? "yes" : "no") + "' >";

            ret += "<name>" + name + "</name>";
            if (!string.IsNullOrWhiteSpace(mac))
            {
                ret += "<mac name='" + mac + "'/>";
            }
            if (!string.IsNullOrWhiteSpace(uuid))
            {
                ret += "<uuid>" + uuid + "</uuid>";
            }
            ret += "<forward mode ='" + Forward_Type.ToString() + "' />";
            ret += Bridge.To_XML();
            ret += QOS.To_XML();
            ret += Configuration.To_XML();
            ret += "</network>";
            return(ret);
        }
 public Topic(String name, QOS qos)
 {
     this._name = name;
     this._qos  = qos;
 }
Beispiel #15
0
        /// <exception cref="MalformedMessageException">Exception is thrown in case of invalid packet format</exception>
        public static MQMessage Decode(IByteBuffer buf)
        {
            MQMessage header = null;

            byte fixedHeader = buf.ReadByte();

            LengthDetails length = DecodeLength(buf);

            MessageType type = (MessageType)((fixedHeader >> 4) & 0xf);

            switch (type)
            {
            case MessageType.CONNECT:

                Byte[] nameValue = new byte[buf.ReadUnsignedShort()];
                buf.ReadBytes(nameValue, 0, nameValue.Length);
                String name = Encoding.UTF8.GetString(nameValue);
                if (!name.Equals(Connect.PROTOCOL_NAME))
                {
                    throw new MalformedMessageException("CONNECT, protocol-name set to " + name);
                }

                Byte protocolLevel = buf.ReadByte();
                Byte contentFlags  = buf.ReadByte();

                Boolean userNameFlag = (((contentFlags >> 7) & 1) == 1) ? true : false;
                Boolean userPassFlag = (((contentFlags >> 6) & 1) == 1) ? true : false;
                Boolean willRetain   = (((contentFlags >> 5) & 1) == 1) ? true : false;

                Int32 QOSValue = ((contentFlags & 0x1f) >> 3) & 3;
                QOS   willQos  = (QOS)QOSValue;
                if (!Enum.IsDefined(typeof(QOS), QOSValue))
                {
                    throw new MalformedMessageException("CONNECT, will QoS set to " + willQos);
                }
                Boolean willFlag = (((contentFlags >> 2) & 1) == 1) ? true : false;

                if (willQos != QOS.AT_MOST_ONCE && !willFlag)
                {
                    throw new MalformedMessageException("CONNECT, will QoS set to " + willQos + ", willFlag not set");
                }

                if (willRetain && !willFlag)
                {
                    throw new MalformedMessageException("CONNECT, will retain set, willFlag not set");
                }

                Boolean cleanSession = (((contentFlags >> 1) & 1) == 1) ? true : false;

                Boolean reservedFlag = ((contentFlags & 1) == 1) ? true : false;
                if (reservedFlag)
                {
                    throw new MalformedMessageException("CONNECT, reserved flag set to true");
                }

                int keepalive = buf.ReadUnsignedShort();

                Byte[] clientIdValue = new byte[buf.ReadUnsignedShort()];
                buf.ReadBytes(clientIdValue, 0, clientIdValue.Length);
                String clientID = Encoding.UTF8.GetString(clientIdValue);
                if (!StringVerifier.verify(clientID))
                {
                    throw new MalformedMessageException("ClientID contains restricted characters: U+0000, U+D000-U+DFFF");
                }

                String willTopic   = null;
                Byte[] willMessage = null;
                String username    = null;
                String password    = null;

                Will will = null;
                if (willFlag)
                {
                    if (buf.ReadableBytes < 2)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    byte[] willTopicValue = new byte[buf.ReadUnsignedShort()];
                    if (buf.ReadableBytes < willTopicValue.Length)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    buf.ReadBytes(willTopicValue, 0, willTopicValue.Length);

                    willTopic = Encoding.UTF8.GetString(willTopicValue);
                    if (!StringVerifier.verify(willTopic))
                    {
                        throw new MalformedMessageException("WillTopic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }

                    if (buf.ReadableBytes < 2)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    willMessage = new byte[buf.ReadUnsignedShort()];
                    if (buf.ReadableBytes < willMessage.Length)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    buf.ReadBytes(willMessage, 0, willMessage.Length);
                    if (willTopic.Length == 0)
                    {
                        throw new MalformedMessageException("invalid will encoding");
                    }
                    will = new Will(new Topic(willTopic, willQos), willMessage, willRetain);
                    if (!will.IsValid())
                    {
                        throw new MalformedMessageException("invalid will encoding");
                    }
                }

                if (userNameFlag)
                {
                    if (buf.ReadableBytes < 2)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    byte[] userNameValue = new byte[buf.ReadUnsignedShort()];
                    if (buf.ReadableBytes < userNameValue.Length)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    buf.ReadBytes(userNameValue, 0, userNameValue.Length);
                    username = Encoding.UTF8.GetString(userNameValue);
                    if (!StringVerifier.verify(username))
                    {
                        throw new MalformedMessageException("Username contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }
                }

                if (userPassFlag)
                {
                    if (buf.ReadableBytes < 2)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    byte[] userPassValue = new byte[buf.ReadUnsignedShort()];
                    if (buf.ReadableBytes < userPassValue.Length)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    buf.ReadBytes(userPassValue, 0, userPassValue.Length);
                    password = Encoding.UTF8.GetString(userPassValue);
                    if (!StringVerifier.verify(password))
                    {
                        throw new MalformedMessageException("Password contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }
                }

                if (buf.ReadableBytes > 0)
                {
                    throw new MalformedMessageException("Invalid encoding will/username/password");
                }

                Connect connect = new Connect(username, password, clientID, cleanSession, keepalive, will);
                if (protocolLevel != 4)
                {
                    connect.ProtocolLevel = protocolLevel;
                }
                header = connect;
                break;

            case MessageType.CONNACK:
                byte sessionPresentValue = buf.ReadByte();
                if (sessionPresentValue != 0 && sessionPresentValue != 1)
                {
                    throw new MalformedMessageException("CONNACK, session-present set to " + (sessionPresentValue & 0xff));
                }

                Boolean isPresent = sessionPresentValue == 1 ? true : false;

                Int32       connackByte = ((Int32)buf.ReadByte()) & 0xFF;
                ConnackCode connackCode = (ConnackCode)connackByte;
                if (!Enum.IsDefined(typeof(ConnackCode), connackByte))
                {
                    throw new MalformedMessageException("Invalid connack code: " + connackByte);
                }
                header = new Connack(isPresent, connackCode);
                break;

            case MessageType.PUBLISH:
                int dataLength = length.Length;
                fixedHeader &= 0xf;

                Boolean dup = (((fixedHeader >> 3) & 1) == 1) ? true : false;

                QOSValue = (fixedHeader & 0x07) >> 1;
                QOS qos = (QOS)QOSValue;
                if (!Enum.IsDefined(typeof(QOS), (byte)QOSValue))
                {
                    throw new MalformedMessageException("invalid QoS value");
                }
                if (dup && qos == QOS.AT_MOST_ONCE)
                {
                    throw new MalformedMessageException("PUBLISH, QoS-0 dup flag present");
                }

                Boolean retain = ((fixedHeader & 1) == 1) ? true : false;

                byte[] topicNameValue = new byte[buf.ReadUnsignedShort()];
                buf.ReadBytes(topicNameValue, 0, topicNameValue.Length);
                String topicName = Encoding.UTF8.GetString(topicNameValue);
                if (!StringVerifier.verify(topicName))
                {
                    throw new MalformedMessageException("Publish-topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                }
                dataLength -= topicName.Length + 2;

                Int32?packetID = null;
                if (qos != QOS.AT_MOST_ONCE)
                {
                    packetID = buf.ReadUnsignedShort();
                    if (packetID < 0 || packetID > 65535)
                    {
                        throw new MalformedMessageException("Invalid PUBLISH packetID encoding");
                    }
                    dataLength -= 2;
                }
                byte[] data = new byte[dataLength];
                if (dataLength > 0)
                {
                    buf.ReadBytes(data, 0, data.Length);
                }
                header = new Publish(packetID, new Topic(topicName, qos), data, retain, dup);
                break;

            case MessageType.PUBACK:
                header = new Puback(buf.ReadUnsignedShort());
                break;

            case MessageType.PUBREC:
                header = new Pubrec(buf.ReadUnsignedShort());
                break;

            case MessageType.PUBREL:
                header = new Pubrel(buf.ReadUnsignedShort());
                break;

            case MessageType.PUBCOMP:
                header = new Pubcomp(buf.ReadUnsignedShort());
                break;

            case MessageType.SUBSCRIBE:
                Int32        subID         = buf.ReadUnsignedShort();
                List <Topic> subscriptions = new List <Topic>();
                while (buf.IsReadable())
                {
                    byte[] value = new byte[buf.ReadUnsignedShort()];
                    buf.ReadBytes(value, 0, value.Length);
                    QOSValue = buf.ReadByte();
                    QOS requestedQos = (QOS)QOSValue;
                    if (!Enum.IsDefined(typeof(QOS), QOSValue))
                    {
                        throw new MalformedMessageException("Subscribe qos must be in range from 0 to 2: " + requestedQos);
                    }
                    String topic = Encoding.UTF8.GetString(value);
                    if (!StringVerifier.verify(topic))
                    {
                        throw new MalformedMessageException("Subscribe topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }
                    Topic subscription = new Topic(topic, requestedQos);
                    subscriptions.Add(subscription);
                }
                if (subscriptions.Count == 0)
                {
                    throw new MalformedMessageException("Subscribe with 0 topics");
                }

                header = new Subscribe(subID, subscriptions.ToArray());
                break;

            case MessageType.SUBACK:
                Int32             subackID    = buf.ReadUnsignedShort();
                List <SubackCode> subackCodes = new List <SubackCode>();
                while (buf.IsReadable())
                {
                    Int32      subackByte = ((Int32)buf.ReadByte()) & 0xFF;
                    SubackCode subackCode = (SubackCode)subackByte;
                    if (!Enum.IsDefined(typeof(SubackCode), subackByte))
                    {
                        throw new MalformedMessageException("Invalid suback code: " + subackByte);
                    }
                    subackCodes.Add(subackCode);
                }
                if (subackCodes.Count == 0)
                {
                    throw new MalformedMessageException("Suback with 0 return-codes");
                }

                header = new Suback(subackID, subackCodes);
                break;

            case MessageType.UNSUBSCRIBE:
                Int32         unsubID           = buf.ReadUnsignedShort();
                List <String> unsubscribeTopics = new List <String>();
                while (buf.IsReadable())
                {
                    byte[] value = new byte[buf.ReadUnsignedShort()];
                    buf.ReadBytes(value, 0, value.Length);
                    String topic = Encoding.UTF8.GetString(value);
                    if (!StringVerifier.verify(topic))
                    {
                        throw new MalformedMessageException("Unsubscribe topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }
                    unsubscribeTopics.Add(topic);
                }
                if (unsubscribeTopics.Count == 0)
                {
                    throw new MalformedMessageException("Unsubscribe with 0 topics");
                }
                header = new Unsubscribe(unsubID, unsubscribeTopics.ToArray());
                break;

            case MessageType.UNSUBACK:
                header = new Unsuback(buf.ReadUnsignedShort());
                break;

            case MessageType.PINGREQ:
                header = new Pingreq();
                break;

            case MessageType.PINGRESP:
                header = new Pingresp();
                break;

            case MessageType.DISCONNECT:
                header = new Disconnect();
                break;

            default:
                throw new MalformedMessageException("Invalid header type: " + type);
            }

            if (buf.IsReadable())
            {
                throw new MalformedMessageException("unexpected bytes in content");
            }

            if (length.Length != header.GetLength())
            {
                throw new MalformedMessageException("Invalid length. Encoded: " + length.Length + ", actual: " + header.GetLength());
            }

            return(header);
        }
Beispiel #16
0
        private void sendButton_Click(object sender, EventArgs e)
        {
            if (txtContent.Text.Length == 0)
            {
                MessageBox.Show("Content is required");
                return;
            }

            if (txtTopic.Text.Length == 0)
            {
                MessageBox.Show("Topic is required");
                return;
            }

            if (cmbQOS.SelectedIndex == -1)
            {
                MessageBox.Show("Please choose QOS");
                return;
            }

            QOS messageQOS = QOS.AT_MOST_ONCE;

            switch (cmbQOS.SelectedIndex)
            {
            case 1:
                messageQOS = QOS.AT_LEAST_ONCE;
                break;

            case 2:
                messageQOS = QOS.EXACTLY_ONCE;
                break;
            }

            MQTTModel mqtt     = new MQTTModel();
            var       accounts = from a in mqtt.Accounts where a.IsDefault == true select a;

            dal.Message newMessage = new dal.Message();
            newMessage.Content   = Encoding.UTF8.GetBytes(txtContent.Text);
            newMessage.Incoming  = false;
            newMessage.QOS       = messageQOS;
            newMessage.TopicName = txtTopic.Text;
            newMessage.Account   = accounts.First();

            _client.Publish(new mqtt.avps.Topic(newMessage.TopicName, newMessage.QOS), newMessage.Content, chkRetain.Checked, chkDuplicate.Checked);
            mqtt.Accounts.Attach(newMessage.Account);
            mqtt.Messages.Add(newMessage);
            mqtt.Entry(newMessage.Account).State = EntityState.Unchanged;
            mqtt.SaveChanges();

            txtContent.Text      = String.Empty;
            txtTopic.Text        = String.Empty;
            cmbQOS.SelectedIndex = -1;
            chkDuplicate.Checked = false;
            chkRetain.Checked    = false;
            MessageBox.Show("Message Sent Succesfully", "Message Sent", MessageBoxButtons.OK, MessageBoxIcon.Information);

            List <dal.Message> messages = (from m in mqtt.Messages.Include("Account") where m.Account.ID == _account.ID orderby m.ID descending select m).ToList();

            this.Invoke((MethodInvoker) delegate { this.messagesGrid.DataSource = messages; });
            mqtt.Dispose();
        }
        public void PacketReceived(CoapMessage message)
        {
            CoapType type = message.CoapType;

            if ((message.CoapCode == CoapCode.POST || message.CoapCode == CoapCode.PUT) && type != CoapType.ACKNOWLEDGEMENT)
            {
                String topic = null;
                QOS    qos   = QOS.AT_MOST_ONCE;
                foreach (CoapOption option in message.Options)
                {
                    if (option.Number == (int)CoapOptionType.URI_PATH)
                    {
                        topic = Encoding.UTF8.GetString(option.Value);
                    }
                    else if (option.Number == (int)CoapOptionType.ACCEPT)
                    {
                        qos = (QOS)option.Value[option.Value.Length - 1];
                    }
                }

                if (topic == null)
                {
                    List <CoapOption> options   = new List <CoapOption>();
                    byte[]            textBytes = Encoding.UTF8.GetBytes("text/plain");
                    options.Add(new CoapOption((int)CoapOptionType.CONTENT_FORMAT, textBytes.Length, textBytes));
                    byte[] nodeIdBytes = Encoding.UTF8.GetBytes(_clientID);
                    options.Add(new CoapOption((int)CoapOptionType.NODE_ID, nodeIdBytes.Length, nodeIdBytes));
                    CoapMessage ack = new CoapMessage(VERSION, CoapType.ACKNOWLEDGEMENT, CoapCode.BAD_OPTION, message.MessageID, message.Token, options, new byte[0]);
                    _client.Send(ack);
                    return;
                }

                byte[] content = message.Payload;
                _dbInterface.StoreMessage(topic, content, 0);

                if (_listener != null)
                {
                    _listener.MessageReceived(MessageType.PUBLISH);
                }
            }

            switch (type)
            {
            case CoapType.CONFIRMABLE:
            {
                List <CoapOption> options     = new List <CoapOption>();
                byte[]            nodeIdBytes = Encoding.UTF8.GetBytes(_clientID);
                options.Add(new CoapOption((int)CoapOptionType.NODE_ID, nodeIdBytes.Length, nodeIdBytes));
                CoapMessage ack = new CoapMessage(message.Version, CoapType.ACKNOWLEDGEMENT, message.CoapCode, message.MessageID, message.Token, options, new byte[0]);
                _client.Send(ack);
            }
            break;

            case CoapType.NON_CONFIRMABLE:
            {
                _timers.Remove(message.Token);
            }
            break;

            case CoapType.ACKNOWLEDGEMENT:
            {
                if (message.CoapCode == CoapCode.GET)
                {
                    Boolean?observe = null;
                    QOS     qos     = QOS.AT_MOST_ONCE;
                    foreach (CoapOption option in message.Options)
                    {
                        if (option.Number == (int)CoapOptionType.OBSERVE && option.Value.Length > 0)
                        {
                            if (option.Value[option.Value.Length - 1] == 0x00)
                            {
                                observe = false;
                            }
                            else
                            {
                                observe = true;
                            }
                        }
                        else if (option.Number == (int)CoapOptionType.ACCEPT)
                        {
                            if (option.Value[option.Value.Length - 1] == 0)
                            {
                                qos = QOS.AT_LEAST_ONCE;
                            }
                        }
                    }

                    if (observe.HasValue)
                    {
                        if (!observe.Value)
                        {
                            CoapMessage originalMessage = _timers.Remove(message.Token);
                            if (originalMessage != null)
                            {
                                List <String> topics = new List <String>();
                                foreach (CoapOption option in originalMessage.Options)
                                {
                                    if (option.Number == (int)CoapOptionType.URI_PATH)
                                    {
                                        topics.Add(Encoding.UTF8.GetString(option.Value));
                                    }
                                }

                                for (int i = 0; i < topics.Count; i++)
                                {
                                    _dbInterface.StoreTopic(topics[i], qos);
                                }

                                if (_listener != null)
                                {
                                    _listener.MessageReceived(MessageType.SUBACK);
                                }
                            }
                        }
                        else
                        {
                            CoapMessage originalMessage = _timers.Remove(message.Token);
                            if (originalMessage != null)
                            {
                                List <String> topics = new List <String>();
                                foreach (CoapOption option in originalMessage.Options)
                                {
                                    if (option.Number == (int)CoapOptionType.URI_PATH)
                                    {
                                        topics.Add(Encoding.UTF8.GetString(option.Value));
                                    }
                                }

                                for (int i = 0; i < topics.Count; i++)
                                {
                                    _dbInterface.DeleteTopic(topics[i]);
                                }
                            }

                            if (_listener != null)
                            {
                                _listener.MessageReceived(MessageType.UNSUBACK);
                            }
                        }
                    }
                }
                else
                {
                    _timers.Remove(message.Token);
                    if (_listener != null)
                    {
                        _listener.MessageReceived(MessageType.PUBACK);
                    }
                }
            }
            break;

            case CoapType.RESET:
            {
                _timers.Remove(message.Token);
            }
            break;
            }
        }
Beispiel #18
0
        /*
         * MPLS Packet contains some data in string format and
         * a stack of labels
         */

        public MPLSPacket(int[] label, string data, QOS qos = QOS.HIGH)
        {
            labels    = new Stack <int>(label);
            this.data = data;
            this.qos  = qos;
        }
Beispiel #19
0
 public Task <UInt16> PublishAsync(String topic, byte[] buffer, QOS qosLevel = QOS.QOS0, bool retainFlag = false)
 {
     return(_mqttClient.PublishAsync(topic, buffer, qosLevel, retainFlag));
 }
Beispiel #20
0
        public Task <UInt16> PublishAsync(String topic, String payload = "", QOS qosLevel = QOS.QOS0, bool retainFlag = false)
        {
            var buffer = String.IsNullOrEmpty(payload) ? new byte[0] : System.Text.UTF8Encoding.UTF8.GetBytes(payload);

            return(PublishAsync(topic, buffer, qosLevel, retainFlag));
        }
Beispiel #21
0
        public Task <UInt16> PublishAsync <T>(String topic, T payload, QOS qosLevel = QOS.QOS0, bool retainFlag = false)
        {
            var json = JsonConvert.SerializeObject(payload);

            return(PublishAsync(topic, json, qosLevel));
        }