/// <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;
        }
예제 #2
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;
        }
        /// <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);
        }
예제 #4
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);
        }
예제 #5
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);
        }
예제 #6
0
        private void btnPut_Click(object sender, EventArgs e)
        {
            CoApPut put = (CoApPut)NetworkInterface.Instance.ResourcePutter;

            put.IpAddress  = txtDevice.Text;
            put.ServerPort = GatewaySettings.Instance.CoApPort;
            // Drill into the device tree and fetch the related resource to fetch.
            put.URI = txtURI.Text;
            if (!(__Payload == null || __Payload.Length == 0))
            {
                put.Payload = new CoAPPayload(__Payload);
            }
            put.Send();
            string result = "";

            try
            {
                result = put.Response.ToString();
                if (put.Response.Payload.Value != null)
                {
                    if (put.Response.Payload.Value.Length != 0)
                    {
                        result += HdkUtils.BytesToHexView(put.Response.Payload.Value);
                    }
                }
            }
            catch
            {
                result = "Unable to retreive response from resource";
            }
            // Show the outcome from the PUT request.
            MessageBox.Show(result);
            Cursor.Current = Cursors.Default;
        }
        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;
        }
        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;
        }
예제 #9
0
        /// <summary>
        /// Handle About menu item click
        /// </summary>
        /// <param name="sender">the object related to the click event</param>
        /// <param name="e">all events related to the request</param>
        private void mnuAbout_Click(object sender, EventArgs e)
        {
            // Fetch the version number from this assembly.
            System.Reflection.Assembly thisAssembly = System.Reflection.Assembly.GetExecutingAssembly();

            MessageBox.Show(this.Text + "\r\nVersion " + HdkUtils.GetAssemblyVersion(thisAssembly)
                            + "\r\nCopyright 2016, 2017 Silver Spring Networks", "About HDK CoAP Client", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        /// <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..
                }
            }
        }
        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);
        }
예제 #12
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);
        }
예제 #13
0
 /// <summary>
 /// Capture the file contents.
 /// </summary>
 /// <param name="sender">the object dropped from</param>
 /// <param name="e">the arguments containing the data content</param>
 private void txtToPut_DragDrop(object sender, DragEventArgs e)
 {
     string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
     foreach (string file in files)
     {
         Console.WriteLine(file);
     }
     if (File.Exists(files[0]))
     {
         __Payload     = File.ReadAllBytes(files[0]);
         txtToPut.Text = HdkUtils.BytesToHexView(__Payload);
     }
 }
예제 #14
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();
        }
        /// <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);
        }
예제 #16
0
        /// <summary>
        /// Handle GET request
        /// </summary>
        /// <param name="sender">the object generating the click</param>
        /// <param name="e">click-related arguments</param>
        private void btnGet_Click(object sender, EventArgs e)
        {
            // Set the wait cursor.
            Cursor.Current = Cursors.WaitCursor;

            // Hide any previous results
            pnlResults.Visible = false;
            lblResult.Visible  = false;

            CoApGet get = (CoApGet)NetworkInterface.Instance.ResourceGetter;

            // Use the device property for the target location.
            get.IpAddress = txtDevice.Text;

            // Use the pre-defined CoAP port number.
            get.ServerPort = GatewaySettings.Instance.CoApPort;

            // Use the resource property for the target resource.
            get.URI = txtURI.Text;

            // Send the request!
            get.Send();

            // Parse out the GET response.
            try
            {
                txtResult.Text = get.Response.ToString();
                if (get.Response.Payload.Value != null)
                {
                    if (get.Response.Payload.Value.Length != 0)
                    {
                        txtResult.Text += HdkUtils.BytesToHexView(get.Response.Payload.Value);
                    }
                }
            }
            catch
            {
                txtResult.Text = "Unable to retreive response from resource";
            }

            // Finally, make the results visible.
            pnlResults.Visible = true;
            lblResult.Visible  = true;

            // Reset the wait cursor.
            Cursor.Current = Cursors.Default;
        }
예제 #17
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();
        }
예제 #18
0
        /// <summary>
        /// Send the request to the CoAP server.
        /// </summary>
        public override void Send()
        {
            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.DELETE,
                                      HdkUtils.MessageId());

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

            coapReq.SetURL(uriToCall);
            SetToken();

            // 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);

            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);

            __Done.Reset();
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived -= new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            -= new CoAPErrorHandler(OnCoAPError);
        }
예제 #19
0
        /// <summary>
        /// Send the request to the CoAP 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,
                                      CoAPMessageCode.DELETE,
                                      HdkUtils.MessageId());

            string uriToCall = "coap://" + serverIP + ":" + __ServerPort + "/" + __IpAddress + __URI;

            coapReq.SetURL(uriToCall);
            SetToken();
            // Send out the request.
            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;
            coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            coapReq.Options.AddOption(CoAPHeaderOption.CONTENT_FORMAT, octet);
            coapReq.Payload = __Payload;
            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>
        /// Load resources associated with a specific device.
        /// This is the CoAP Gateway implementation of CoApDiscovery.
        /// </summary>
        /// <returns>a collection of CoApResource objects</returns>
        ///
        public override CoApResources LoadResources()
        {
            // 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(null);
            }

            // This represents the device being examined.
            string serverIP = __IpAddress;

            // Set up the notification handlers.
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPDiscoveryResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            += new CoAPErrorHandler(OnCoAPDiscoveryError);
            __TimedOut = true;

            // Discovery requires confirmation and a message type of GET
            coapReq = new CoAPRequest(this.ConfirmableMessageType,
                                      CoAPMessageCode.GET,
                                      HdkUtils.MessageId());

            string uriToCall = "coap://" + UriFromMac(__IpAddress) + ":" + __ServerPort + "/.well-known/core";//"/.well-known/core";

            coapReq.SetURL(uriToCall);
            SetToken();
            // Send out the coap request

            // JJK - Change in v2.0.7
            //coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap");
            // make Proxy packet Change in v2.0.7
            coapReq.Options.AddOption(CoAPHeaderOption.BLOCK2, new byte[] { CoAPBlockOption.BLOCK_SIZE_128 });
            //coapReq.Options.AddOption(CoAPHeaderOption.PROXY_URI, "coap://SSN001350050047dc9a.SG.YEL01.SSN.SSNSGS.NET:4849/.well-known/core");
            coapReq.Options.AddOption(CoAPHeaderOption.PROXY_URI, "coap://" + UriFromMac(__IpAddress) + ":" + "4849" + "/.well-known/core");
            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);
            // end of Changes in v2.0.7

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

            CoApDiscoveryResponse response = null;

            // Wait for a response from the discovery request.
            // Time out after the pre-defined maximum wait time.
            __Done.WaitOne(GatewaySettings.Instance.RequestTimeout);
            response = this.DiscoveryResponse;

            // Reset the wait object
            __Done.Reset();
            if (__TimedOut)
            {
                this.ErrorResult = "Request timed out";
            }
            // Remove event handlers.
            CoApGatewaySessionManager.Instance.Client.CoAPResponseReceived -= new CoAPResponseReceivedHandler(OnCoAPDiscoveryResponseReceived);
            CoApGatewaySessionManager.Instance.Client.CoAPError            -= new CoAPErrorHandler(OnCoAPDiscoveryError);
            return(response.Resources);
        }
        public void SetGetResult(byte[] payload)
        {
            string discovery = AbstractByteUtils.ByteToStringUTF8(payload);

            Console.WriteLine("Discovery = " + discovery);
            __GetResult       = discovery;
            __InternalPayload = payload;
            CoAPResponse coapResp = new CoAPResponse();

            try
            {
                coapResp.FromByteStream(payload);
                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 " + " = " + result);
                                    __GetResult = result;
                                }
                                if (ccformat.Value == CoAPContentFormatOption.APPLICATION_OCTET_STREAM)
                                {
                                    string result = HdkUtils.BytesToHexView(coapResp.Payload.Value);
                                    Console.WriteLine("Get " + " = " + result);
                                    __GetResult = result;
                                }
                                if (ccformat.Value == CoAPContentFormatOption.APPLICATION_JSON)
                                {
                                    string result = HdkUtils.BytesToHexView(coapResp.Payload.Value);
                                    Console.WriteLine("Get " + " = " + result);
                                    __GetResult = result;
                                }

                                __Response = coapResp;
                            }
                        }
                    }
                    else
                    {
                        //Will come here if an error occurred..
                    }
                }
            }
            catch
            { }
        }
예제 #22
0
        /// <summary>
        /// Load devices based on the network interface settings.
        /// For each valid device, load a list of related CoAP resources.
        /// </summary>
        private void LoadNodes()
        {
            Cursor.Current = Cursors.WaitCursor;    // Show as buys while loading the resources.

            FileLogger.Write("Loading all known devices");

            // Load the correct device class based on current network option
            CoApDeviceFinder finder  = (CoApDeviceFinder)NetworkInterface.Instance.NodeFinder;
            CoApDevices      devices = new CoApDevices();

            try
            {
                // With the Ping change, we are capturing the gateway credentials earlier than we had planned.
                //SetGatewayCoapApiCredentials();
                devices = finder.LoadNodes();
            }
            catch (Exception devFail)
            {
                MessageBox.Show("Device fetch failed - " + devFail.Message);
                return;
            }

            // Loop through all fetched devices.
            // If the device was successfully pinged, then we can load related resources.
            // Otherwise, we ignore it.
            foreach (CoApDevice d in devices)
            {
                TreeNode deviceNode = treeDevices.Nodes.Add(d.Name);
                if (d.Reachable)
                {
                    deviceNode.ForeColor = treeDevices.ForeColor;
                    if (NetworkInterface.Instance.UsingGateway)
                    {
                        CoAPSettings.Instance.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork;
                    }
                    if (NetworkInterface.Instance.UsingSimulator)
                    {
                        CoAPSettings.Instance.AddressFamily = System.Net.Sockets.AddressFamily.InterNetworkV6;
                    }
                    // We should never get here, but this is added in case we add other communication methods later.
                    if (!NetworkInterface.Instance.UsingGateway && !NetworkInterface.Instance.UsingSimulator)
                    {
                        if (HdkUtils.IsIPv4Address(d.Name))
                        {
                            CoAPSettings.Instance.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork;
                        }
                        else
                        {
                            CoAPSettings.Instance.AddressFamily = System.Net.Sockets.AddressFamily.InterNetworkV6;
                        }
                    }

                    // We need to load the credentials if they have not already been set.
                    bool credentialsOk = true;
                    //if (NetworkInterface.Instance.UsingGateway)
                    //{
                    //    credentialsOk = SetGatewayCoapApiCredentials();
                    //}

                    // Check to see if we are ready to load resources related to a device.
                    if (__LoadResources && credentialsOk)
                    {
                        //d.Resources = LoadResources(deviceNode);
                    }
                }
                // Unreachable devices will be grayed out.
                else
                {
                    deviceNode.ForeColor = Color.Gray;
                }
            }

            // Expand the tree so that all loaded devices and resources are visible.
            treeDevices.ExpandAll();

            Cursor.Current = Cursors.Default;   // Clear the "busy" cursor
        }