public new void Send()
        {
            string serverIP = __IpAddress;//coapsharp.Properties.Settings.Default.IpAddress;// "10.90.202.182";//"localhost";

            if (HdkUtils.IsIPv4Address(serverIP))
            {
                CoAPSettings.Instance.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork;
            }
            else
            {
                CoAPSettings.Instance.AddressFamily = System.Net.Sockets.AddressFamily.InterNetworkV6;
            }

            __coapClient.Initialize(serverIP, __ServerPort);
            __coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);

            __coapClient.CoAPError += new CoAPErrorHandler(OnCoAPError);

            coapReq = new CoAPRequest(this.ConfirmableMessageType, //CoAPMessageType.NON,
                                      CoAPMessageCode.GET,
                                      100);                        //hardcoded message ID as we are using only once
            string uriToCall = "coap://" + serverIP + ":" + __ServerPort + __URI;

            coapReq.SetURL(uriToCall);
            __Token       = DateTime.Now.ToString("HHmmss"); //Token value must be less than 8 bytes
            coapReq.Token = new CoAPToken(__Token);          //A random token
            __coapClient.Send(coapReq);
            __Done.WaitOne();
            __Done.Reset();
            __Done.Close();
            __Done = null;
            __coapClient.Shutdown();
            __coapClient = null;
        }
        public override void Send()
        {
            string serverIP = __IpAddress;

            __coapClient = new CoAPClientChannel();

            __coapClient.Initialize(serverIP, __ServerPort);
            __coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            __coapClient.CoAPRequestReceived  += new CoAPRequestReceivedHandler(OnCoAPRequestReceived);
            __coapClient.CoAPError            += new CoAPErrorHandler(OnCoAPError);
            //Send a NON request to get the temperature...in return we will get a NON request from the server
            coapReq = new CoAPRequest(CoAPMessageType.RST,
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());          //hardcoded message ID as we are using only once
            string uriToCall = "coap://" + serverIP + ":" + __ServerPort + __URI;

            coapReq.SetURL(uriToCall);
            __Token       = DateTime.Now.ToString("HHmmss"); //Token value must be less than 8 bytes
            coapReq.Token = new CoAPToken(__Token);          //A random token
            __coapClient.Send(coapReq);
            __Done.WaitOne();
            __Done.Reset();
            __Done.Close();
            __Done = null;
            __coapClient.Shutdown();
            __coapClient = null;
        }
 /// <summary>
 /// Get the request message that was pending response
 /// </summary>
 /// <param name="msgId">The message Id corresponding to the message that needs to be extracted</param>
 /// <returns>A copy of the request object pending response (if found), else null</returns>
 public CoAPRequest GetRequestPendingResponse(UInt16 msgId)
 {                        
     this._waitEvent.WaitOne();//Wait for thread to release the queue            
     CoAPRequest foundReq = null;
     try
     {
         int count = 0;
         for (count = 0; count < this._conMessageQ.Count; count++)
         {
             AbstractCoAPMessage coapMsgInQ = (AbstractCoAPMessage)this._conMessageQ[count];
             if (coapMsgInQ.ID.Value == msgId)
             {
                 /*Found*/
                 foundReq = new CoAPRequest(coapMsgInQ.MessageType.Value, coapMsgInQ.Code.Value, coapMsgInQ.ID.Value);
                 foreach (CoAPHeaderOption option in coapMsgInQ.Options)
                     foundReq.AddOption(option.Number, option.Value);
                 foundReq.Token = coapMsgInQ.Token;
                 foundReq.Payload = coapMsgInQ.Payload;
                 foundReq.RemoteSender = coapMsgInQ.RemoteSender;
                 break;
             }
         }                
     }
     catch (Exception e)
     {
         AbstractLogUtil.GetLogger().LogError(e.ToString());
         ; ;//TOCHECK::nothing for now
     }
     finally
     {
         this._waitEvent.Set();//Now allow others to work on the queue
     }
     return foundReq;
 }
Example #4
0
        private void AcknowledgeResponse(CoAPResponse coapResp)
        {
            string serverIP = __IpAddress;

            // Response handlers already set - leave them alone

            coapReq = new CoAPRequest(CoAPMessageType.ACK,
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());

            string uriToCall = "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + __ServerPort + __URI;

            coapReq.SetURL(uriToCall);
            __Token       = DateTime.Now.ToString("HHmmss");//Token value must be less than 8 bytes
            coapReq.Token = coapResp.Token;

            string blat = coapReq.ToString();

            // JJK - Changes in v2.0.7
            //coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            // make Proxy packet
            coapReq.Options.AddOption(CoAPHeaderOption.BLOCK2, new byte[] { CoAPBlockOption.BLOCK_SIZE_128 });
            coapReq.Options.AddOption(CoAPHeaderOption.PROXY_URI, "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + "4849" + __URI);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_HOST);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_QUERY);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PATH);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PORT);
            coapReq.Options.RemoveOption(CoAPHeaderOption.CONTENT_FORMAT);
            // JJK - end of Changes in v2.0.7

            FileLogger.Write("About to send CoAP ACK request");
            FileLogger.Write(coapReq.ToString());
            CoApGatewaySessionManager.Instance.Client.Send(coapReq);
        }
        /// <summary>
        /// Entry point
        /// </summary>
        public static void Main()
        {
            NetworkHelpers.SetupAndConnectNetwork();

            string serverIP   = "localhost";
            int    serverPort = 5683;

            coapClient = new CoAPClientChannel();
            coapClient.Initialize(serverIP, serverPort);
            coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            coapClient.CoAPRequestReceived  += new CoAPRequestReceivedHandler(OnCoAPRequestReceived);
            coapClient.CoAPError            += new CoAPErrorHandler(OnCoAPError);
            //Send a NON request to get the temperature...in return we will get a NON request from the server
            CoAPRequest coapReq = new CoAPRequest(CoAPMessageType.NON,
                                                  CoAPMessageCode.GET,
                                                  100);//hardcoded message ID as we are using only once
            string uriToCall = "coap://" + serverIP + ":" + serverPort + "/sensors/temp";

            coapReq.SetURL(uriToCall);
            _mToken       = DateTime.Today.ToString("HHmmss"); //Token value must be less than 8 bytes
            coapReq.Token = new CoAPToken(_mToken);            //A random token
            coapClient.Send(coapReq);
            Thread.Sleep(Timeout.Infinite);                    //blocks
            while (true)
            {
                Thread.Sleep(3000);
            }
        }
Example #6
0
        /// <summary>
        /// This method composes a UDP call to the simulator to acquire the device list.
        /// </summary>
        private void RequestDeviceList()
        {
            string serverIP = __IpAddress;

            __coapClient.Initialize(serverIP, __ServerPort);
            __coapClient.AckTimeout            = __Timeout;
            __coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            __coapClient.CoAPRequestReceived  += new CoAPRequestReceivedHandler(OnCoAPRequestReceived);
            __coapClient.CoAPError            += new CoAPErrorHandler(OnCoAPError);
            //Send a NON request to get the temperature...in return we will get a NON request from the server
            coapReq = new CoAPRequest(this.ConfirmableMessageType,                     //CoAPMessageType.NON
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());                           //hardcoded message ID as we are using only once
            string uriToCall = "coap://" + serverIP + ":" + __ServerPort + "/devices"; //"/sensors/temp";"/time";//

            coapReq.SetURL(uriToCall);
            __Token       = DateTime.Now.ToString("HHmmss"); //Token value must be less than 8 bytes
            coapReq.Token = new CoAPToken(__Token);          //A random token
            __coapClient.Send(coapReq);
            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            __Done.Reset();
            __Done.Close();
            __Done = null;
            __coapClient.Shutdown();
            __coapClient = null;
        }
Example #7
0
        public override void Send()
        {
            // If we can't establish a socket with a good login to the gateway api, then just return;
            bool gotSession = false;

            try
            {
                gotSession = CoApGatewaySessionManager.Instance.EstablishSession();
            }
            catch (Exception noSession)
            {
                FileLogger.Write("Error obtaining session");
                FileLogger.Write(noSession.Message);
                FileLogger.Write(noSession.StackTrace);
                this.ErrorResult = "Error obtaining session" + noSession.Message;
            }

            if (!gotSession)
            {
                FileLogger.Write("Session NOT Established");
                return;
            }
            string serverIP = __IpAddress;

            // Set the response handlers.
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            += new CoAPErrorHandler(OnCoAPError);

            coapReq = new CoAPRequest(this.ConfirmableMessageType,
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());

            string uriToCall = "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + __ServerPort + __URI;

            coapReq.SetURL(uriToCall);
            SetToken();

            // Send out the request.
            // JJK - Changes in v2.0.7
            //coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            // make Proxy packet header
            coapReq.Options.AddOption(CoAPHeaderOption.BLOCK2, new byte[] { CoAPBlockOption.BLOCK_SIZE_128 });
            coapReq.Options.AddOption(CoAPHeaderOption.PROXY_URI, "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + "4849" + __URI);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_HOST);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_QUERY);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PATH);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PORT);
            coapReq.Options.RemoveOption(CoAPHeaderOption.CONTENT_FORMAT);
            // JJK - end of Changes in v2.0.7

            FileLogger.Write("About to send CoAP request");
            FileLogger.Write(coapReq.ToString());
            coapReq.Timeout = GatewaySettings.Instance.RequestTimeout;//////////////////////////////////////
            CoApGatewaySessionManager.Instance.Client.Send(coapReq);

            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            __Done.Reset();
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived -= new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            -= new CoAPErrorHandler(OnCoAPError);
        }
Example #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);
            }
        }
        /// <summary>
        /// Send the CoAP request to the server
        /// </summary>
        public override void Send()
        {
            string device   = __IpAddress;
            string serverIP = "localhost";

            __coapClient.Initialize(serverIP, __ServerPort);

            __coapClient.Initialize(serverIP, __ServerPort);
            __coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);

            __coapClient.CoAPError += new CoAPErrorHandler(OnCoAPError);

            coapReq = new CoAPRequest(this.ConfirmableMessageType,//CoAPMessageType.NON,
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());
            string uriToCall = "coap://" + serverIP + ":" + __ServerPort + "/" + __IpAddress + __URI;

            coapReq.SetURL(uriToCall);
            SetToken();
            // Send out the request.
            coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            FileLogger.Write("About to send CoAP request");
            FileLogger.Write(coapReq.ToString());
            __coapClient.Send(coapReq);

            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            __Done.Reset();
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived -= new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            -= new CoAPErrorHandler(OnCoAPError);
        }
        /// <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();
        }
        /// <summary>
        /// Add an observer for the given observable resource
        /// </summary>
        /// <param name="coapReq">A request message from client that is requesting resource observation</param>
        public void AddResourceObserver(CoAPRequest coapReq)
        {
            if (coapReq == null)
            {
                throw new ArgumentNullException("CoAP message requesting for observation is NULL");
            }
            if (!coapReq.IsObservable())
            {
                throw new ArgumentException("CoAP message requesting for observation is not marked as observable");
            }
            string observableURL = coapReq.GetURL().Trim().ToLower();

            //First, add this URL as an observable resource
            this.AddObservableResource(observableURL);

            //Now, add this observer for the given observable resource
            this._observableListSync.WaitOne();
            bool      observerAlreadyExists = false;
            ArrayList observers             = (ArrayList)this._observers[observableURL];

            for (int count = 0; count < observers.Count; count++)
            {
                CoAPRequest storedObserver = (CoAPRequest)observers[count];
                if (storedObserver.ID.Value == coapReq.ID.Value)
                {
                    observerAlreadyExists = true;
                    break;
                }
            }
            if (!observerAlreadyExists)
            {
                observers.Add(coapReq);
            }
            this._observableListSync.Set();
        }
        /// <summary>
        /// Send CoAP request to the server
        /// </summary>
        public override void Send()
        {
            string device   = __IpAddress;
            string serverIP = "localhost";

            __coapClient.Initialize(serverIP, __ServerPort);
            __coapClient.AckTimeout            = __Timeout;
            __coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            __coapClient.CoAPRequestReceived  += new CoAPRequestReceivedHandler(OnCoAPRequestReceived);
            __coapClient.CoAPError            += new CoAPErrorHandler(OnCoAPError);
            //Send a NON request to get the temperature...in return we will get a NON request from the server
            coapReq = new CoAPRequest(this.ConfirmableMessageType,                                                  //CoAPMessageType.NON
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());                                                        //hardcoded message ID as we are using only once
            string uriToCall = "coap://" + serverIP + ":" + __ServerPort + "/" + __IpAddress + "/.well-known/core"; //"/sensors/temp";"/time";//

            coapReq.SetURL(uriToCall);
            SetToken();
            __coapClient.Send(coapReq);
            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            __Done.Reset();
            __Done.Close();
            __Done = null;
            __coapClient.Shutdown();
            __coapClient = null;
        }
Example #13
0
 /// <summary>
 /// Handle error
 /// </summary>
 /// <param name="e">The exception that occurred</param>
 /// <param name="associatedMsg">The associated message (if any)</param>
 private static void OnCoAPError(Exception e, AbstractCoAPMessage associatedMsg)
 {
     if (e.GetType() == typeof(UndeliveredException))
     {
         //Some CON message never got delivered...
         CoAPRequest undeliveredCONReq = (CoAPRequest)associatedMsg;
         //Now take action on this underlivered request
     }
 }
        public override void Send()
        {
            // If we can't establish a socket with a good login to the gateway api, then just return;
            if (!CoApGatewaySessionManager.Instance.EstablishSession())
            {
                return;
            }

            string serverIP = __IpAddress;

            // Set the response handlers.
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            += new CoAPErrorHandler(OnCoAPError);
            __URI = "/";

            coapReq = new CoAPRequest(CoAPMessageType.CON,
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());

            string uriToCall = "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + __ServerPort + __URI;

            coapReq.SetURL(uriToCall);
            SetToken();

            // Send out the request.
            // JJK - Changes in v2.0.7
            //coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            // make Proxy packet
            coapReq.Options.AddOption(CoAPHeaderOption.BLOCK2, new byte[] { CoAPBlockOption.BLOCK_SIZE_128 });
            coapReq.Options.AddOption(CoAPHeaderOption.PROXY_URI, "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + "4849" + __URI);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_HOST);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_QUERY);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PATH);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PORT);
            coapReq.Options.RemoveOption(CoAPHeaderOption.CONTENT_FORMAT);
            // JJK - end of Changes in v2.0.7

            //////coapReq = new CoAPRequest(CoAPMessageType.CON,
            //////                                    CoAPMessageCode.EMPTY,
            //////                                    HdkUtils.MessageId());

            //////string uriToCall = "coap://" + HdkUtils.UriFromMac(__IpAddress);// + ":" + __ServerPort + __URI;
            //////coapReq.SetURL(uriToCall);
            ////////SetToken();

            //////// Send out the request.
            ////////coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            FileLogger.Write("About to send CoAP request");
            FileLogger.Write(coapReq.ToString());
            CoApGatewaySessionManager.Instance.Client.Send(coapReq);

            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            __Done.Reset();
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived -= new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            -= new CoAPErrorHandler(OnCoAPError);
        }
        /// <summary>
        /// Get the next request from the Q that was pending a separate response.
        /// If nothing is pending then NULL value is returned
        /// </summary>
        /// <returns>CoAPRequest</returns>
        public virtual CoAPRequest GetNextRequestPendingSeparateResponse()
        {
            if (this._separateResponseQ == null)
            {
                throw new InvalidOperationException("Please initialize the server first");
            }
            CoAPRequest coapReq = (CoAPRequest)this._separateResponseQ.GetNextPendingRequest();

            return(coapReq);
        }
 /// <summary>
 /// Add this request to the pending separate response queue.
 /// The message can be extracted later and acted upon
 /// </summary>
 /// <param name="coapReq">CoAPRequest</param>
 public virtual void Add(CoAPRequest coapReq)
 {
     if (coapReq == null)
     {
         throw new ArgumentNullException("CoAPRequest to add to this queue cannot be NULL");
     }
     this._separateRespQSync.WaitOne();
     this._separateResponseQ.Enqueue(coapReq);
     this._separateRespQSync.Set();
 }
Example #17
0
        /// <summary>
        /// Perform a session request (acquire or terminate).
        /// </summary>
        /// <param name="messageCode">CoAPMessageCode.POST for establishing a session or oAPMessageCode.DELETE for terminating a session</param>
        /// <returns>a boolean indicating success or failure of the request</returns>
        private bool SessionCall(byte messageCode)
        {
            __TimedOut = true;
            __SessionRequestSucceeded = false;
            string token = GatewaySettings.Instance.SfdpToken;
            //api.coap-test.developer.ssni.com
            string serverIP = AbstractNetworkUtils.GetIPAddressFromHostname(GatewaySettings.Instance.GatewayURI).ToString();

            __coapClient.Initialize(GatewaySettings.Instance.GatewayURI, __ServerPort);
            __coapClient.AckTimeout            = __Timeout;
            __coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPSessionResponseReceived);
            __coapClient.CoAPError            += new CoAPErrorHandler(OnCoAPError);

            coapReq = new CoAPRequest(this.ConfirmableMessageType,
                                      messageCode,
                                      HdkUtils.MessageId());
            string uriToCall = "coap://" + GatewaySettings.Instance.GatewayURI + ":"
                               + __ServerPort + "/sessions?security=none";//?token="

            //+ GatewaySettings.Instance.SfdpToken;
            //+ "&security=none";

            coapReq.SetURL(uriToCall);
            byte[] zero = { 0x00 };
            coapReq.AddOption(CoAPHeaderOption.CONTENT_FORMAT, zero);
            if (messageCode != CoAPMessageCode.DELETE)
            {
                coapReq.Payload = new CoAPPayload(GatewaySettings.Instance.SfdpToken);
            }
            SetToken();

            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_QUERY);  // JJK - Change in v2.0.7

            FileLogger.Write("About to send session request");
            try
            {
                FileLogger.Write(coapReq.ToString());
            }
            catch (Exception flErr)
            {
                FileLogger.Write(flErr.Message);
            }
            __coapClient.Send(coapReq);
            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            __Done.Reset();
            if (__TimedOut)
            {
                this.ErrorResult = "Request timed out";
                FileLogger.Write(this.ErrorResult);
            }
            __coapClient.CoAPResponseReceived -= new CoAPResponseReceivedHandler(OnCoAPSessionResponseReceived);

            return(__SessionRequestSucceeded);
        }
 /// <summary>
 /// Add this request to the pending separate response queue.
 /// The message can be extracted later and acted upon
 /// </summary>
 /// <param name="coapReq">CoAPRequest</param>
 public virtual void AddToPendingSeparateResponse(CoAPRequest coapReq)
 {
     if (this._separateResponseQ == null)
     {
         throw new InvalidOperationException("Please initialize the server first");
     }
     if (coapReq == null)
     {
         throw new ArgumentNullException("CoAPRequest to add to this queue cannot be NULL");
     }
     this._separateResponseQ.Add(coapReq);
 }
        /// <summary>
        /// Get the next request from the Q that was pending a separate response.
        /// If nothing is pending then NULL value is returned
        /// </summary>
        /// <returns>CoAPRequest</returns>
        public virtual CoAPRequest GetNextPendingRequest()
        {
            CoAPRequest coapReq = null;

            this._separateRespQSync.WaitOne();
            if (this._separateResponseQ.Count > 0 && this._separateResponseQ.Peek() != null)
            {
                coapReq = (CoAPRequest)this._separateResponseQ.Dequeue();
            }
            this._separateRespQSync.Set();

            return(coapReq);
        }
Example #20
0
        public void StartObserving()
        {
            string serverIP = __IpAddress;

            // Set the response handlers.
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPObserveResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            += new CoAPErrorHandler(OnCoAPError);

            coapReq = new CoAPRequest(this.ConfirmableMessageType,
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());

            string uriToCall = "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + __ServerPort + __URI;

            coapReq.SetURL(uriToCall);
            SetToken();

            string blat = coapReq.ToString();

            byte[] observerOption = new byte[1];
            observerOption[0] = 0; // Start observing
            coapReq.Options.AddOption(CoAPHeaderOption.OBSERVE, new byte[0]);

            //coapReq.Options.AddOption(CoAPHeaderOption.OBSERVE, observerOption);
            // JJK - Changes in v2.0.7
            //coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            // make Proxy packet
            coapReq.Options.AddOption(CoAPHeaderOption.BLOCK2, new byte[] { CoAPBlockOption.BLOCK_SIZE_128 });
            coapReq.Options.AddOption(CoAPHeaderOption.PROXY_URI, "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + "4849" + __URI);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_HOST);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_QUERY);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PATH);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PORT);
            coapReq.Options.RemoveOption(CoAPHeaderOption.CONTENT_FORMAT);
            // JJK - end of Changes in v2.0.7

            FileLogger.Write("About to send CoAP request");
            FileLogger.Write(coapReq.ToString());
            CoApGatewaySessionManager.Instance.Client.Send(coapReq);

            __Observing = true;

            while (__Observing)
            {
                //FileLogger.Write(CoApGatewaySessionManager.Instance.Client.ToString());
                Application.DoEvents();
                Thread.Sleep(100);
                //__Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            }
            __Done.Reset();
        }
Example #21
0
        public bool GetRequest()
        {
            CoAPRequest coapReq = new CoAPRequest(CoAPMessageType.CON,
                                                  CoAPMessageCode.GET,
                                                  id);

            id++;

            string uriToCall = "coap://" + serverIP + ":" + serverPort + "/.well-known/core";

            coapReq.SetURL(uriToCall);
            _mToken       = DateTime.Now.ToString("HHmmss"); //Token value must be less than 8 bytes
            coapReq.Token = new CoAPToken(_mToken);          //A random token

            _coapClient.Send(coapReq);

            tempAsJSON = "";
            timeOut    = false;

            Timer timer = new Timer(delay);

            timer.Elapsed += Timer_Elapsed;

            timer.Start();

            while (tempAsJSON == string.Empty && timeOut == false)
            {
                ;
            }

            timer.Stop();

            if (timeOut == true && tempAsJSON == string.Empty)
            {
                return(false);
            }

            Services.Clear();
            ObserveServices.Clear();
            InteractServices.Clear();

            ParseServices(tempAsJSON);

            string s = tempAsJSON;

            tempAsJSON = "";

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public new byte[] ToBytes()
        {
            string serverIP = __IpAddress;                         //coapsharp.Properties.Settings.Default.IpAddress;// "10.90.202.182";//"localhost";

            coapReq = new CoAPRequest(this.ConfirmableMessageType, //CoAPMessageType.NON,
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());       //hardcoded message ID as we are using only once
            string uriToCall = "coap://" + serverIP + ":" + __ServerPort + __URI;

            coapReq.SetURL(uriToCall);
            __Token       = DateTime.Now.ToString("HHmmss"); //Token value must be less than 8 bytes
            coapReq.Token = new CoAPToken(__Token);          //A random token
            byte[] b = __coapClient.ToBytes(coapReq);
            return(b);
        }
Example #23
0
        /// <summary>
        /// Send the request to get the temperature
        /// </summary>
        private static void SendRequest()
        {
            string      urlToCall = "coap://localhost:5683/sensors/temp";
            UInt16      mId       = coapClient.GetNextMessageID();//Using this method to get the next message id takes care of pending CON requests
            CoAPRequest tempReq   = new CoAPRequest(CoAPMessageType.CON, CoAPMessageCode.GET, mId);

            tempReq.SetURL(urlToCall);

            /*Uncomment the two lines below to use non-default values for timeout and retransmission count*/
            /*Dafault value for timeout is 2 secs and retransmission count is 4*/
            //tempReq.Timeout = 10;
            //tempReq.RetransmissionCount = 5;

            coapClient.Send(tempReq);
        }
        /// <summary>
        /// Raised when a CoAP request is received
        /// </summary>
        /// <param name="coapReq">CoAPRequest</param>
        protected void HandleRequestReceived(CoAPRequest coapReq)
        {
            CoAPRequestReceivedHandler reqRxHandler = CoAPRequestReceived;

            try
            {
                if (reqRxHandler != null)
                {
                    reqRxHandler(coapReq);
                }
            }
            catch (Exception e)
            {
                AbstractLogUtil.GetLogger().LogError(e.ToString());
                //Do nothing else...do not want to bring down the whole thing because handler failed
            }
        }
Example #25
0
        /// <summary>
        /// Send the request to get the temperature
        /// </summary>
        public static void SendRequest()
        {
            string      urlToCall = "coap://localhost:5683/sensors/temp/observe";
            UInt16      mId       = coapClient.GetNextMessageID();//Using this method to get the next message id takes care of pending CON requests
            CoAPRequest tempReq   = new CoAPRequest(CoAPMessageType.CON, CoAPMessageCode.GET, mId);

            tempReq.SetURL(urlToCall);
            //Important::Add the Observe option
            tempReq.AddOption(CoAPHeaderOption.OBSERVE, null);        //Value of observe option has no meaning in request
            tempReq.AddTokenValue(DateTime.Today.ToString("HHmmss")); //must be <= 8 bytes
            /*Uncomment the two lines below to use non-default values for timeout and retransmission count*/
            /*Dafault value for timeout is 2 secs and retransmission count is 4*/
            //tempReq.Timeout = 10;
            //tempReq.RetransmissionCount = 5;

            coapClient.Send(tempReq);
        }
        /// <summary>
        /// Send the CoAP message to client
        /// </summary>
        /// <param name="coapMsg">The CoAP message to send</param>
        /// <returns>Number of bytes sent</returns>
        public override int Send(AbstractCoAPMessage coapMsg)
        {
            if (coapMsg == null)
            {
                throw new ArgumentNullException("Message is NULL");
            }
            if (this._socket == null)
            {
                throw new InvalidOperationException("CoAP server not yet started");
            }

            int bytesSent = 0;

            try
            {
                //We do not want server to die when a socket send error occurs...
                //just clean all settings specific to the remote client and
                //keep going
                byte[] coapBytes = coapMsg.ToByteStream();
                bytesSent = this._socket.SendTo(coapBytes, coapMsg.RemoteSender);
                if (coapMsg.MessageType.Value == CoAPMessageType.CON)
                {
                    //confirmable message...need to wait for a response
                    coapMsg.DispatchDateTime = DateTime.Now;
                    this._msgPendingAckQ.AddToWaitQ(coapMsg);
                }
            }
            catch (Exception e)
            {
                this._msgPendingAckQ.RemoveFromWaitQ(coapMsg.ID.Value);
                if (coapMsg.GetType() == typeof(CoAPRequest))
                {
                    CoAPRequest coapReq = (CoAPRequest)coapMsg;
                    this._observers.RemoveResourceObserver(coapReq.GetURL(), coapReq.Token.Value);
                }
                else if (coapMsg.GetType() == typeof(CoAPResponse))
                {
                    CoAPResponse coapResp = (CoAPResponse)coapMsg;
                    this._observers.RemoveResourceObserver(coapResp);
                }
                this.HandleError(e, coapMsg);
            }

            return(bytesSent);
        }
Example #27
0
        public void SendMessage(string message, string location)
        {
            CoAPRequest coapReq = new CoAPRequest(CoAPMessageType.CON,
                                                  CoAPMessageCode.PUT,
                                                  id); //hardcoded message ID as we are using only once

            id++;

            string uriToCall = $"coap://{serverIP}:{serverPort}{location}";

            coapReq.SetURL(uriToCall);
            _mToken       = DateTime.Now.ToString("HHmmss"); //Token value must be less than 8 bytes
            coapReq.Token = new CoAPToken(_mToken);          //A random token

            coapReq.Payload = new CoAPPayload(message);

            _coapClient.Send(coapReq);
        }
Example #28
0
        public string GetDeviceStatus(string location)
        {
            CoAPRequest coapReq = new CoAPRequest(CoAPMessageType.CON,
                                                  CoAPMessageCode.GET,
                                                  id);

            id++;

            string uriToCall = $"coap://{serverIP}:{serverPort}{location}";

            coapReq.SetURL(uriToCall);
            _mToken       = DateTime.Now.ToString("HHmmss"); //Token value must be less than 8 bytes
            coapReq.Token = new CoAPToken(_mToken);          //A random token

            _coapClient.Send(coapReq);

            tempAsJSON = "";
            timeOut    = false;

            Timer timer = new Timer(delay);

            timer.Elapsed += Timer_Elapsed;

            timer.Start();

            while (tempAsJSON == string.Empty && timeOut == false)
            {
                ;
            }

            timer.Stop();

            if (timeOut == true && tempAsJSON == string.Empty)
            {
                return("not found");
            }

            string s = tempAsJSON;

            tempAsJSON = "";

            return(s);
        }
Example #29
0
        /// <summary>
        /// Send the PUT request
        /// </summary>
        public override void Send()
        {
            string serverIP = __IpAddress;

            // Set up the handlers
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            += new CoAPErrorHandler(OnCoAPError);

            coapReq = new CoAPRequest(this.ConfirmableMessageType,
                                      CoAPMessageCode.PUT,
                                      HdkUtils.MessageId());

            string uriToCall = "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + __ServerPort + __URI;

            coapReq.SetURL(uriToCall);
            SetToken();
            byte[] octet = new byte[1];
            // As of this moment, the expectation is that the content is an octet stream.
            octet[0] = (byte)CoAPContentFormatOption.APPLICATION_OCTET_STREAM;
            // JJK - Changes in v2.0.7
            //coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            // make Proxy packet
            coapReq.Options.AddOption(CoAPHeaderOption.BLOCK2, new byte[] { CoAPBlockOption.BLOCK_SIZE_128 });
            coapReq.Options.AddOption(CoAPHeaderOption.PROXY_URI, "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + "4849" + __URI);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_HOST);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_QUERY);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PATH);
            coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PORT);
            coapReq.Options.RemoveOption(CoAPHeaderOption.CONTENT_FORMAT);
            // JJK - end of Changes in v2.0.7

            coapReq.Options.AddOption(CoAPHeaderOption.CONTENT_FORMAT, octet);
            coapReq.Payload = __Payload;

            FileLogger.Write("About to send CoAP request");
            FileLogger.Write(coapReq.ToString());
            CoApGatewaySessionManager.Instance.Client.Send(coapReq);

            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            __Done.Reset();
        }
Example #30
0
        /// <summary>
        /// Called when a CoAP request is received...we will only support CON requests
        /// of type GET... the path is sensors/temp
        /// </summary>
        /// <param name="coapReq">CoAPRequest object</param>
        private static void OnCoAPRequestReceived(CoAPRequest coapReq)
        {
            string reqPath = (coapReq.GetPath() != null) ? coapReq.GetPath().ToLower() : "";

            if (coapReq.MessageType.Value == CoAPMessageType.CON)
            {
                if (coapReq.Code.Value != CoAPMessageCode.GET)
                {
                    CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK,
                                                         CoAPMessageCode.METHOD_NOT_ALLOWED,
                                                         coapReq /*Copy all necessary values from request in the response*/);
                    //When you use the constructor that accepts a request, then automatically
                    //the message id , token and remote sender values are copied over to the response
                    coapServer.Send(resp);
                }
                else if (reqPath != "sensors/temp")
                {
                    //We do not understand this..
                    CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK,
                                                         CoAPMessageCode.NOT_FOUND,
                                                         coapReq /*Copy all necessary values from request in the response*/);
                    coapServer.Send(resp);
                }
                else
                {
                    Debug.WriteLine(coapReq.ToString());
                    CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK,
                                                         CoAPMessageCode.CONTENT,
                                                         coapReq /*Copy all necessary values from request in the response*/);
                    //The payload will be JSON
                    Hashtable ht = new Hashtable();
                    ht.Add("temp", GetRoomTemperature());
                    string jsonStr = JSONResult.ToJSON(ht);
                    resp.AddPayload(jsonStr);
                    //Tell recipient about the content-type of the response
                    resp.AddOption(CoAPHeaderOption.CONTENT_FORMAT, AbstractByteUtils.GetBytes(CoAPContentFormatOption.APPLICATION_JSON));
                    //send it
                    coapServer.Send(resp);
                }
            }
        }