コード例 #1
0
        /// <summary>
        /// Overloaded constructor
        /// </summary>
        /// <param name="optionNumber">The option number</param>
        /// <param name="optionValue">The option value</param>
        public CoAPHeaderOption(UInt16 optionNumber, byte[] optionValue)
        {
            int maxLengthOfOptionValue = this.GetOptionValueMaxLengthInBytes(optionNumber);
            int minLengthOfOptionValue = this.GetOptionValueMinLengthInBytes(optionNumber);
            int lengthOfOptionValue    = (optionValue == null) ? 0 : optionValue.Length;

            this.Number = optionNumber;
            if (this.IsRecognized())
            {
                if (lengthOfOptionValue < minLengthOfOptionValue || lengthOfOptionValue > maxLengthOfOptionValue)
                {
                    throw new CoAPFormatException("Invalid length of option value for the given option number " + optionNumber);
                }
            }

            if (this.Number == CoAPHeaderOption.CONTENT_FORMAT)
            {
                CoAPContentFormatOption contentFormat = new CoAPContentFormatOption(AbstractByteUtils.ToUInt16(optionValue));
                if (!contentFormat.IsValid())
                {
                    throw new CoAPFormatException("Content format not supported");
                }
            }

            if (optionValue != null && optionValue.Length > 0)
            {
                this.Value = new byte[optionValue.Length];
                Array.Copy(optionValue, this.Value, optionValue.Length);
                this.ValueSizeInBytes = (UInt16)optionValue.Length;
            }
        }
コード例 #2
0
        /// <summary>
        /// Get the query parameter
        /// </summary>
        /// <param name="paramKey">The parameter key</param>
        /// <returns>string if key found else null</returns>
        public string GetQueryParam(string paramKey)
        {
            String qString = null;

            if (paramKey == null || paramKey.Trim().Length == 0)
            {
                return(null);
            }

            foreach (CoAPHeaderOption headerOption in this.Options)
            {
                if (headerOption.Number == CoAPHeaderOption.URI_QUERY)
                {
                    qString = AbstractByteUtils.ByteToStringUTF8(headerOption.Value);
                    if (qString.IndexOf("=") > 0)
                    {
                        string[] qpParts = qString.Split(new char[] { '=' });
                        //index 0 will have key and 1 will have value
                        if (paramKey.Trim().ToLower() == qpParts[0].Trim().ToLower())
                        {
                            return(AbstractURIUtils.UrlDecode(qpParts[1]));
                        }
                    }
                    else if (qString.Trim().ToLower() == paramKey.Trim().ToLower())
                    {
                        return("");//Only key no value
                    }
                }
            }
            return(null);
        }
コード例 #3
0
        private void OnCoAPResponseReceived(CoAPResponse coapResp)
        {
            string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : "";

            if (tokenRx == _mToken)
            {
                //This response is against the NON request for getting temperature we issued earlier
                if (coapResp.Code.Value == CoAPMessageCode.CONTENT)
                {
                    //Get the temperature
                    string tempAsJSON = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);

                    //  Light light = Light.Deserialize(tempAsJSON);
                    // Hashtable tempValues = JSONResult.FromJSON(tempAsJSON);
                    // int temp = Convert.ToInt32(tempValues["temp"].ToString());
                    // int temp = Convert.ToInt32(tempAsJSON);
                    //Now do something with this temperature received from the server
                    Application.Current.Dispatcher.BeginInvoke((Action)(() => { gridError.Visibility = Visibility.Visible; }));
                    Application.Current.Dispatcher.BeginInvoke((Action)(() => { txtError.Text = $"Response received: {tempAsJSON}"; }));
                }
                else
                {
                    //Will come here if an error occurred..
                }
            }
        }
コード例 #4
0
        /// <summary>
        /// Called when a response is received against a sent request
        /// </summary>
        /// <param name="coapResp">The CoAPResponse object</param>
        private void OnCoAPSessionResponseReceived(CoAPResponse coapResp)
        {
            __TimedOut = false;
            string tokenRx = "";// (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : "";

            if (coapResp != null)
            {
                if (coapResp.Token != null)
                {
                    tokenRx = AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value);
                }
            }
            try
            {
                FileLogger.Write("Received response from server - token = " + tokenRx);
                FileLogger.Write(coapResp.ToString());
            }
            catch { }

            if (tokenRx == __Token)
            {
                int classCode = ((coapResp.Code.Value & 0xE0) >> 5);
                if (classCode == 2)
                {
                    __SessionRequestSucceeded = true;
                    FileLogger.Write("Session request completed successfully");
                }
                else
                {
                    FileLogger.Write("Session call code " + coapResp.Code.Value.ToString());
                    //Will come here if an error occurred..
                }
                __Done.Set();
            }
        }
コード例 #5
0
        /// <summary>
        /// Called when a response is received against a sent request
        /// </summary>
        /// <param name="coapResp">The CoAPResponse object</param>
        private void OnCoAPResponseReceived(CoAPResponse coapResp)
        {
            string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : "";

            if (tokenRx == __Token)
            {
                if (coapResp.Code.Value == CoAPMessageCode.CONTENT)
                {
                    ArrayList options = coapResp.Options.GetOptions((ushort)CoAPHeaderOption.CONTENT_FORMAT);
                    if (options.Count > 0)
                    {
                        bool proceed = false;
                        foreach (CoAPHeaderOption o in options)
                        {
                            CoAPContentFormatOption ccformat = new CoAPContentFormatOption(AbstractByteUtils.ToUInt16(o.Value));
                            if (ccformat.Value == CoAPContentFormatOption.APPLICATION_LINK_FORMAT)
                            {
                                proceed = true;
                            }
                        }
                        if (proceed)
                        {
                            string discovery = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);
                            Console.WriteLine("Discovery " + __coapClient.EndPoint.ToString() + " = " + discovery);
                            __DiscoveryResult = discovery;
                        }
                    }
                }
                else
                {
                    //Will come here if an error occurred..
                }
            }
            __Done.Set();
        }
コード例 #6
0
        /// <summary>
        /// Remove an observer for the given observable resource
        /// </summary>
        /// <param name="observableResourceURL">The observable URL for which the observer has to be removed</param>
        /// <param name="tokenValue">The Token value the observer</param>
        public void RemoveResourceObserver(string observableResourceURL, byte[] tokenValue)
        {
            if (!this.IsResourceBeingObserved(observableResourceURL))
            {
                return;
            }

            this._observableListSync.WaitOne();
            bool      observerExists = false;
            ArrayList observers      = (ArrayList)this._observers[observableResourceURL];
            int       count          = 0;

            for (count = 0; count < observers.Count; count++)
            {
                CoAPRequest storedObserver = (CoAPRequest)observers[count];
                if (AbstractByteUtils.AreByteArraysEqual(storedObserver.Token.Value, tokenValue))
                {
                    observerExists = true;
                    break;
                }
            }
            if (observerExists && count < observers.Count)
            {
                observers.RemoveAt(count);
            }
            this._observableListSync.Set();
        }
コード例 #7
0
        /// <summary>
        /// For some implementations, we need to retrieve the returned payload from a different source.
        /// This method allows us to push that payload into this object.
        /// </summary>
        /// <param name="payload"></param>
        public void SetDiscovery(byte[] payload)
        {
            string discovery = AbstractByteUtils.ByteToStringUTF8(payload);

            Console.WriteLine("Discovery = " + discovery);
            __DiscoveryResult = discovery;
        }
コード例 #8
0
        /// <summary>
        /// Notify listeners of the new temperature
        /// </summary>
        /// <param name="temp">The temperature</param>
        static private void NotifyListeners(int temp)
        {
            ArrayList resObservers = coapServer.ObserversList.GetResourceObservers(OBSERVED_RESOURCE_URI);

            if (resObservers == null || resObservers.Count == 0)
            {
                return;
            }

            //The next observe sequence number
            UInt16 obsSeq = (UInt16)Convert.ToInt16(DateTime.Today.ToString("mmss"));//Will get accomodated in 24-bits limit and will give good sequence

            foreach (CoAPRequest obsReq in resObservers)
            {
                UInt16      mId       = coapServer.GetNextMessageID();
                CoAPRequest notifyReq = new CoAPRequest(CoAPMessageType.CON, CoAPMessageCode.PUT, mId);
                notifyReq.RemoteSender = obsReq.RemoteSender;
                notifyReq.Token        = obsReq.Token;
                //Add observe option with sequence number
                notifyReq.AddOption(CoAPHeaderOption.OBSERVE, AbstractByteUtils.GetBytes(obsSeq));

                //The payload will be JSON
                Hashtable ht = new Hashtable();
                ht.Add("temp", temp);
                string jsonStr = JSONResult.ToJSON(ht);
                notifyReq.AddPayload(jsonStr);
                //Tell recipient about the content-type of the response
                notifyReq.AddOption(CoAPHeaderOption.CONTENT_FORMAT, AbstractByteUtils.GetBytes(CoAPContentFormatOption.APPLICATION_JSON));
                //send it
                coapServer.Send(notifyReq);
            }
        }
コード例 #9
0
        /// <summary>
        /// Called when a response is received against a sent request
        /// </summary>
        /// <param name="coapResp">The CoAPResponse object</param>
        private void OnCoAPResponseReceived(CoAPResponse coapResp)
        {
            string tokenRx = "";// (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : "";

            if (coapResp != null)
            {
                if (coapResp.Token != null)
                {
                    tokenRx = AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value);
                }
            }
            try
            {
                FileLogger.Write("Received response from server - token = " + tokenRx);
                FileLogger.Write(coapResp.ToString());
            }
            catch { }
            if (tokenRx == __Token)
            {
                if (BreakIfError(coapResp.Code.Value))
                {
                    return;
                }
                if (coapResp.Code.Value == CoAPMessageCode.CHANGED)
                {
                    __Response = coapResp;
                    __Done.Set();
                }
                else
                {
                    // Will come here if an error occurred.
                    // For now, let the request time out.
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Called when a response is received against a sent request
        /// </summary>
        /// <param name="coapResp">The CoAPResponse object</param>
        private void OnCoAPResponseReceived(CoAPResponse coapResp)
        {
            string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : "";

            FileLogger.Write("Received response from server - token = " + tokenRx);
            FileLogger.Write(coapResp.ToString());
            if (tokenRx == __Token)
            {
                if (BreakIfError(coapResp.Code.Value))
                {
                    return;
                }

                if (coapResp.Code.Value == CoAPMessageCode.CONTENT)
                {
                    ArrayList options = coapResp.Options.GetOptions((ushort)CoAPHeaderOption.CONTENT_FORMAT);
                    if (options.Count > 0)
                    {
                        CoAPContentFormatOption ccformat = new CoAPContentFormatOption();
                        bool proceed = false;
                        foreach (CoAPHeaderOption o in options)
                        {
                            ccformat = new CoAPContentFormatOption(AbstractByteUtils.ToUInt16(o.Value));
                            if (ccformat.IsValid())
                            {
                                proceed = true;
                                break;
                            }
                        }
                        if (proceed)
                        {
                            if (ccformat.Value == CoAPContentFormatOption.TEXT_PLAIN)
                            {
                                string result = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);
                                __PingResult = result;
                            }
                            if (ccformat.Value == CoAPContentFormatOption.APPLICATION_OCTET_STREAM)
                            {
                                string result = HdkUtils.BytesToHexView(coapResp.Payload.Value);
                                __PingResult = result;
                            }
                            if (ccformat.Value == CoAPContentFormatOption.APPLICATION_JSON)
                            {
                                string result = HdkUtils.BytesToHexView(coapResp.Payload.Value);
                                __PingResult = result;
                            }

                            __Response = coapResp;
                            __Done.Set();
                        }
                    }
                }
                else
                {
                    //Will come here if an error occurred..
                }
            }
        }
コード例 #11
0
 /// <summary>
 /// A CoAP token created from string value
 /// </summary>
 /// <param name="tokenValue">The string value that represents the CoAP token</param>
 public CoAPToken(string tokenValue)
 {
     if (tokenValue == null || tokenValue.Trim().Length == 0)
     {
         throw new ArgumentNullException("Token value cannot be NULL or empty string");
     }
     this.Value  = AbstractByteUtils.StringToByteUTF8(tokenValue);
     this.Length = (byte)this.Value.Length;
 }
コード例 #12
0
        /// <summary>
        /// Get the payload as a string (A UTF-8 formatted string)
        /// </summary>
        /// <returns>The payload as string</returns>
        public string GetPayload()
        {
            if (this.Payload == null || this.Payload.Value == null || this.Payload.Value.Length == 0)
            {
                return(null);
            }

            return(AbstractByteUtils.ByteToStringUTF8(this.Payload.Value));
        }
コード例 #13
0
        /// <summary>
        /// As bytes...endian ness is taken care of in this method
        /// </summary>
        /// <param name="reserved">Not used now</param>
        /// <returns>byte[]</returns>
        public byte[] ToStream(UInt16 reserved)
        {
            if (this.SequenceNumber <= 0xF)
            {
                //single byte
                byte[] retVal = new byte[1];
                retVal[0] = (byte)this.SequenceNumber;
                retVal[0] = (byte)(retVal[0] << 4);                                      //seq number in top 4 bits
                retVal[0] = (this.HasMoreBlocks) ? (byte)(retVal[0] | 0x08) : retVal[0]; //more flag in 5th bit
                retVal[0] = (byte)(retVal[0] | this.SizeExponent);                       //size exponent, last 3 bits

                return(retVal);
            }
            else if (this.SequenceNumber > 0xF && this.SequenceNumber <= 0xFFF)
            {
                //double byte
                byte[] temp = new byte[2];

                if (AbstractByteUtils.IsTargetLittleEndian())
                {
                    temp    = AbstractByteUtils.GetBytes((UInt16)(this._seqNumber << 4));
                    temp[0] = (this.HasMoreBlocks) ? (byte)(temp[0] | 0x08) : (byte)(temp[0] & 0xF7);
                    temp[0] = (byte)(temp[0] | this.SizeExponent);
                }
                else
                {
                    temp    = AbstractByteUtils.GetBytes((UInt16)(this._seqNumber >> 4));
                    temp[1] = (this.HasMoreBlocks) ? (byte)(temp[1] | 0x08) : (byte)(temp[1] & 0xF7);
                    temp[1] = (byte)(temp[1] | this.SizeExponent);
                }
                return(temp);
            }
            else
            {
                //3 bytes...we start with 4(long) and then return last 3 only
                byte[] temp   = new byte[4];
                byte[] retVal = new byte[3];

                if (AbstractByteUtils.IsTargetLittleEndian())
                {
                    temp    = AbstractByteUtils.GetBytes((UInt64)(this._seqNumber << 4));
                    temp[0] = (this.HasMoreBlocks) ? (byte)(temp[0] | 0x08) : (byte)(temp[0] & 0xF7);
                    temp[0] = (byte)(temp[0] | this.SizeExponent);
                    Array.Copy(temp, 0, retVal, 0, 3);
                }
                else
                {
                    //use the index  =2, index 3 will be discarded
                    temp    = AbstractByteUtils.GetBytes((UInt64)(this._seqNumber >> 4));
                    temp[2] = (this.HasMoreBlocks) ? (byte)(temp[1] | 0x08) : (byte)(temp[1] & 0xF7);
                    temp[2] = (byte)(temp[1] | this.SizeExponent);
                    Array.Copy(temp, 1, retVal, 0, 3);
                }

                return(retVal);
            }
        }
コード例 #14
0
 /// <summary>
 /// Convert to a string representation
 /// </summary>
 /// <returns>string</returns>
 public override string ToString()
 {
     if (this.Length > 0)
     {
         return("Token : Length =" + this.Length + ", Value=" + AbstractByteUtils.ByteToStringUTF8(this.Value));
     }
     else
     {
         return("Token : Length = 0, Value = NULL");
     }
 }
コード例 #15
0
 /// <summary>
 /// Convert to a string representation
 /// </summary>
 /// <returns>string</returns>
 public override string ToString()
 {
     if (this.Value == null || this.Value.Length == 0)
     {
         return("");
     }
     else
     {
         return(AbstractByteUtils.ByteToStringUTF8(this.Value));
     }
 }
コード例 #16
0
 /// <summary>
 /// Get the token value
 /// </summary>
 /// <returns>long</returns>
 public UInt64 GetTokenValue()
 {
     if (this.Token == null || this.Token.Length == 0)
     {
         return(0);
     }
     else
     {
         return(AbstractByteUtils.ToUInt64(this.Token.Value));
     }
 }
コード例 #17
0
        ///// <summary>
        ///// Called when a request is received...
        ///// </summary>
        ///// <param name="coapReq">The CoAPRequest object</param>
        //private void OnCoAPRequestReceived(CoAPRequest coapReq)
        //{
        //    Console.WriteLine(coapReq.QueryString);
        //}

        /// <summary>
        /// Called when a response is received against a sent request
        /// </summary>
        /// <param name="coapResp">The CoAPResponse object</param>
        private void OnCoAPResponseReceived(CoAPResponse coapResp)
        {
            string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : "";

            if (tokenRx == __Token)
            {
                if (coapResp.Code.Value == CoAPMessageCode.CONTENT)
                {
                    ArrayList options = coapResp.Options.GetOptions((ushort)CoAPHeaderOption.CONTENT_FORMAT);
                    if (options.Count > 0)
                    {
                        CoAPContentFormatOption ccformat = new CoAPContentFormatOption();
                        bool proceed = false;
                        foreach (CoAPHeaderOption o in options)
                        {
                            ccformat = new CoAPContentFormatOption(AbstractByteUtils.ToUInt16(o.Value));
                            if (ccformat.IsValid())
                            {
                                proceed = true;
                                break;
                            }
                        }
                        if (proceed)
                        {
                            if (ccformat.Value == CoAPContentFormatOption.TEXT_PLAIN)
                            {
                                string result = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);
                                Console.WriteLine("Get on Olimex " + __coapClient.EndPoint.ToString() + " = " + result);
                                __GetResult = result;
                            }
                            if (ccformat.Value == CoAPContentFormatOption.APPLICATION_OCTET_STREAM)
                            {
                                string result = SSNUtils.Conversion.BytesToHexView(coapResp.Payload.Value);
                                Console.WriteLine("Get on Olimex " + __coapClient.EndPoint.ToString() + " = " + result);
                                __GetResult = result;
                            }
                            if (ccformat.Value == CoAPContentFormatOption.APPLICATION_JSON)
                            {
                                string result = SSNUtils.Conversion.BytesToHexView(coapResp.Payload.Value);
                                Console.WriteLine("Get on Olimex " + __coapClient.EndPoint.ToString() + " = " + result);
                                __GetResult = result;
                            }

                            __Response = coapResp;
                        }
                    }
                }
                else
                {
                    //Will come here if an error occurred..
                }
            }
            __Done.Set();
        }
コード例 #18
0
 /// <summary>
 /// Creates a payload with string data
 /// </summary>
 /// <param name="payloadData">Payload data as string</param>
 public CoAPPayload(string payloadData)
 {
     if (payloadData == null || payloadData.Trim().Length == 0)
     {
         throw new ArgumentNullException("Payload data cannot be NULL or empty string");
     }
     if (payloadData.Trim().Length > AbstractNetworkUtils.GetMaxMessageSize() / 2)
     {
         throw new ArgumentException("Payload size cannot be more than " + AbstractNetworkUtils.GetMaxMessageSize() / 2);
     }
     this.Value = AbstractByteUtils.StringToByteUTF8(payloadData.Trim());
 }
コード例 #19
0
 /// <summary>
 /// We should receive the temperature from sever in the response
 /// </summary>
 /// <param name="coapResp">CoAPResponse</param>
 private static void OnCoAPResponseReceived(CoAPResponse coapResp)
 {
     if (coapResp.MessageType.Value == CoAPMessageType.ACK &&
         coapResp.Code.Value == CoAPMessageCode.CONTENT)
     {
         //We got the temperature..it will be in payload in JSON
         string    payload = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);
         Hashtable keyVal  = JSONResult.FromJSON(payload);
         int       temp    = Convert.ToInt32(keyVal["temp"].ToString());
         //do something with the temperature now
     }
 }
コード例 #20
0
 /// <summary>
 /// Check if the collection holds the given option number with the given value
 /// </summary>
 /// <param name="optionNumber">The option number whose existence has to be checked</param>
 /// <param name="optionValue">The option value to match</param>
 /// <returns>bool</returns>
 public bool HasOption(UInt16 optionNumber, byte[] optionValue)
 {
     foreach (CoAPHeaderOption headerOption in this)
     {
         if (headerOption.Number == optionNumber)
         {
             if (AbstractByteUtils.AreByteArraysEqual(headerOption.Value, optionValue))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
コード例 #21
0
        private void OnCoAPResponseReceived(CoAPResponse coapResp)
        {
            string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : "";

            if (tokenRx == _mToken)
            {
                if (coapResp.Code.Value == CoAPMessageCode.CONTENT)
                {
                    tempAsJSON = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);
                }
                else
                {
                }
            }
        }
コード例 #22
0
 /// <summary>
 /// Add the token value. If the value is larger than 8 bytes, then it is truncated to 8 bytes
 /// The string is treated as UTF-8 string
 /// </summary>
 /// <param name="tokenValue">The token value (maximum 8 bytes)</param>
 public void AddTokenValue(string tokenValue)
 {
     if (this.Token == null)
     {
         this.Token = new CoAPToken();
     }
     if (tokenValue != null)
     {
         byte[] asBytes = AbstractByteUtils.StringToByteUTF8(tokenValue);
         int    len     = (asBytes.Length > 8) ? 8 : asBytes.Length;
         this.Token.Value = new byte[len];
         Array.Copy(asBytes, 0, this.Token.Value, 0, len);
         this.Token.Length = (byte)this.Token.Value.Length;
     }
 }
コード例 #23
0
 /// <summary>
 /// Get the first matching option from the list that has the value
 /// which starts with the given input value
 /// </summary>
 /// <param name="optionNumber">The option number to get</param>
 /// <param name="valueStartsWith">The option value must start with this value</param>
 /// <returns>CoAPHeaderOption if available else null</returns>
 public CoAPHeaderOption GetOption(UInt16 optionNumber, string valueStartsWith)
 {
     foreach (CoAPHeaderOption headerOption in this)
     {
         if (headerOption.Number == optionNumber)
         {
             string optionValue = AbstractByteUtils.ByteToStringUTF8(headerOption.Value);
             if (optionValue.Trim().IndexOf(valueStartsWith) == 0)
             {
                 return(headerOption);
             }
         }
     }
     return(null);
 }
コード例 #24
0
        /// <summary>
        /// Add a new option to the list of options
        /// </summary>
        /// <param name="optionNumber">The option number</param>
        /// <param name="optionValue">The associated option value as UTF-8string. This will be converted to bytes internally</param>
        public virtual void AddOption(UInt16 optionNumber, string optionValue)
        {
            CoAPHeaderOption headerOption = new CoAPHeaderOption(optionNumber, AbstractByteUtils.StringToByteUTF8(optionValue));

            if (!headerOption.IsRepeatable() && this.HasOption(optionNumber))
            {
                //Specs say that if an option is not repeatable and it still appears multiple times,
                //each subsequent option must be treated as un-recognized....
                //In this implementation, we do not allow non-repetable options to be added to the list
                throw new CoAPFormatException("Non-repeatable option already present in collection. Cannot add more.");
            }
            else
            {
                this.Add(headerOption);
            }
        }
コード例 #25
0
        /// <summary>
        /// Add the payload...limited to 1024 bytes...we assume the string is in UTF-8 format
        /// </summary>
        /// <param name="payload">A unicode string not longer than 1024 bytes</param>
        public void AddPayload(string payload)
        {
            if (payload == null || payload.Trim().Length == 0)
            {
                return;
            }

            this.Payload = new CoAPPayload();
            byte[] payloadAsUtf8 = AbstractByteUtils.StringToByteUTF8(payload);
            int    length        = payloadAsUtf8.Length;

            //if (length > 1024) length = 1024;

            this.Payload.Value = new byte[length];
            Array.Copy(payloadAsUtf8, 0, this.Payload.Value, 0, length);
        }
コード例 #26
0
 /// <summary>
 /// Remove the given option that has the given value. If the option and value appears
 /// multiple times, all entries will be removed
 /// </summary>
 /// <param name="optionNumber">The option number to remove</param>
 /// <param name="optionValue">The option value that must match the option number to be removed</param>
 public virtual void RemoveOption(UInt16 optionNumber, byte[] optionValue)
 {
     while (this.HasOption(optionNumber, optionValue))
     {
         foreach (CoAPHeaderOption option in this)
         {
             if (option.Number == optionNumber)
             {
                 if (AbstractByteUtils.AreByteArraysEqual(option.Value, optionValue))
                 {
                     this.Remove(option);
                     break;
                 }
             }
         }
     }
 }
コード例 #27
0
        /// <summary>
        /// From the given byte stream, just check what is the message Id (CON/NON/ACK/RST).
        /// The message byte stream might be corrupted, so we only make a best case attempt
        /// </summary>
        /// <param name="data">The data stream to parse</param>
        /// <returns>The message type identifier</returns>
        public static UInt16 PeekMessageID(byte[] data)
        {
            if (data == null || data.Length < AbstractCoAPMessage.HEADER_LENGTH)
            {
                throw new ArgumentNullException("Invalid byte stream to parse");
            }
            UInt16 mId = 0;

            try
            {
                byte[] mIdBytes = new byte[2];
                Array.Copy(data, 2, mIdBytes, 0, 2);
                mId = AbstractByteUtils.ToUInt16(mIdBytes);
            }
            catch { }
            return(mId);
        }
コード例 #28
0
        /// <summary>
        /// Get the request path
        /// </summary>
        /// <returns>The coap path associated with the request</returns>
        public string GetPath()
        {
            string path = "";

            //Path components
            foreach (CoAPHeaderOption headerOption in this.Options)
            {
                if (headerOption.Number == CoAPHeaderOption.URI_PATH)
                {
                    if (path.Trim().Length > 0)
                    {
                        path += "/";
                    }
                    path += AbstractByteUtils.ByteToStringUTF8(headerOption.Value);
                }
            }
            return(path);
        }
コード例 #29
0
        /// <summary>
        /// The byte array from which we need to construct this block option.
        /// </summary>
        /// <param name="data">
        /// The byte array (max 3 bytes).Endian-ness is taken care of in this method
        /// </param>
        public CoAPBlockOption(byte[] data)
        {
            if (data == null || data.Length == 0 || data.Length > 3)
            {
                throw new ArgumentNullException("Block option byte array must be 1-3 bytes in length");
            }

            if (data.Length == 1 /*single byte*/)
            {
                this._seqNumber = (UInt16)(data[0] >> 4);
                this._hasMore   = (((data[0] & 0x08) >> 3) == 1) ? true : false;
                this._sizeExp   = (byte)(data[0] & 0x07);
            }
            else if (data.Length == 2 /*double byte*/)
            {
                if (AbstractByteUtils.IsTargetLittleEndian())
                {
                    this._seqNumber = (UInt16)(AbstractByteUtils.ToUInt16(data) >> 4);
                    this._hasMore   = (((data[0] & 0x08) >> 3) == 1) ? true : false;
                    this._sizeExp   = (byte)(data[0] & 0x07);
                }
                else
                {
                    this._seqNumber = (UInt16)(AbstractByteUtils.ToUInt16(data) << 4);
                    this._hasMore   = (((data[1] & 0x08) >> 3) == 1) ? true : false;
                    this._sizeExp   = (byte)(data[1] & 0x07);
                }
            }
            else if (data.Length == 3 /*Triple byte*/)
            {
                if (AbstractByteUtils.IsTargetLittleEndian())
                {
                    this._seqNumber = (UInt32)(AbstractByteUtils.ToUInt64(data) >> 4);
                    this._hasMore   = (((data[0] & 0x08) >> 3) == 1) ? true : false;
                    this._sizeExp   = (byte)(data[0] & 0x07);
                }
                else
                {
                    this._seqNumber = (UInt32)(AbstractByteUtils.ToUInt64(data) << 4);
                    this._hasMore   = (((data[2] & 0x08) >> 3) == 1) ? true : false;
                    this._sizeExp   = (byte)(data[2] & 0x07);
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Set the location URL. This is set by the response to indicate "Created" result if the
        /// request is POST (to create a new resource)
        /// </summary>
        /// <param name="locationURL">The location URL relative to the URI that got created</param>
        public void SetLocation(string locationURL)
        {
            if (locationURL == null || locationURL.Trim().Length == 0)
            {
                throw new ArgumentException("Invalid CoAP location URL");
            }
            locationURL = locationURL.Trim().ToLower();

            if (locationURL.IndexOf("#") >= 0)
            {
                throw new ArgumentException("Fragments not allowed in CoAP location URL");
            }
            //Add these items as option

            //Path components
            string[] segments = AbstractURIUtils.GetUriSegments(locationURL);

            if (segments != null && segments.Length > 0)
            {
                foreach (string segment in segments)
                {
                    if (segment.Trim().Length == 0)
                    {
                        continue;
                    }
                    this.Options.AddOption(CoAPHeaderOption.LOCATION_PATH, AbstractByteUtils.StringToByteUTF8(AbstractURIUtils.UrlDecode(segment)));
                }
            }
            //Query
            string[] qParams = AbstractURIUtils.GetQueryParameters(locationURL);
            if (qParams != null && qParams.Length > 0)
            {
                foreach (string queryComponent in qParams)
                {
                    if (queryComponent.Trim().Length == 0)
                    {
                        continue;
                    }
                    this.Options.AddOption(CoAPHeaderOption.LOCATION_QUERY, AbstractByteUtils.StringToByteUTF8(AbstractURIUtils.UrlDecode(queryComponent)));
                }
            }
        }