/// <summary>
 /// Called when error occurs
 /// </summary>
 /// <param name="e">The exception that occurred</param>
 /// <param name="associatedMsg">The associated message (if any)</param>
 private void OnCoAPDiscoveryError(Exception e, AbstractCoAPMessage associatedMsg)
 {
     __TimedOut = false;
     FileLogger.Write(e.Message);
     //Write your error logic here
     __Done.Set();
 }
예제 #2
0
 private void button1_Click_1(object sender, EventArgs e)
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         if (CoApGatewaySessionManager.Instance.IsSessionEstablished())
         {
             // Terminate and re-establish session
             CoApGatewaySessionManager.Instance.TerminateSession();
             CoApGatewaySessionManager.Instance.EstablishSession();
         }
         // Check status again.  It not established then Token stale and need new Token
         if (!CoApGatewaySessionManager.Instance.IsSessionEstablished())
         {
             mnuRefreshDevices_Click(this, EventArgs.Empty);  // refresh of devices gets new Token
             CoApGatewaySessionManager.Instance.EstablishSession();
         }
     } catch (Exception ex)
     {
         FileLogger.Write("Problem Establishing Session - " + ex.Message);
     }
     finally
     {
         Cursor.Current = Cursors.Default;
     }
 }
예제 #3
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();
            }
        }
예제 #4
0
        /// <summary>
        /// Initial form load.
        /// Set all default parameters and
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmNewMain_Load(object sender, EventArgs e)
        {
            // Set various client connection settings.
            GatewaySettings.Instance.Restore();

            // Set up the debug log
            SetDebugLogPath();
            FileLogger.Enabled = true;
            FileLogger.Level   = FileLogger.LogLevel.Debug;
            FileLogger.Write("Starting HDK Client");
            FileLogger.DebugWindow = txtLog;

            // Display the options panel to the right of the main form.
            __EdgeWidth = pnlEdge.Right - pnlOptions.Right;
            mnuFunctions.BringToFront();
            mnuFunctions.Visible = false;

            //radAutoDiscover.Checked = true;
            radDemandDiscover.Checked = true;
            NetworkInterface.Instance.SelectedInterface = NetworkInterface.NetworkOption.Gateway;
            radGateway.Checked        = true;
            radConfirmable.Enabled    = true;
            radConfirmable.Checked    = true;
            radNonConfirmable.Enabled = true;
            radNonConfirmable.Checked = false;

            __PreferredResultsHeight = pnlResults.Height;
            txtLog.Width             = treeDevices.Width + pnlOptions.Width;

            cboPort.SelectedIndex = 0;
            txtTimeout.Text       = Convert.ToString(GatewaySettings.Instance.RequestTimeout / 1000);
        }
예제 #5
0
        /// <summary>
        /// Serializes an object into XML
        /// </summary>
        /// <param name="pObject">the object to serialize</param>
        /// <returns>an XML equivalent of the object</returns>
        public static String SerializeObject(Object pObject)
        {
            try
            {
                String            XmlizedString = null;
                MemoryStream      memoryStream  = new MemoryStream();
                XmlWriterSettings ws            = new XmlWriterSettings();
                ws.OmitXmlDeclaration = true;
                ws.Encoding           = Encoding.UTF8;
                ws.Indent             = true;
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                ns.Add(string.Empty, "");
                XmlWriter     xmlWriter = XmlWriter.Create(memoryStream, ws);
                XmlSerializer xs        = new XmlSerializer(pObject.GetType(), "");

                xs.Serialize(xmlWriter, pObject, ns);
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                return(XmlizedString);
            }
            catch (Exception e)
            {
                FileLogger.Write("Error serializing object: " + e.Message + e.StackTrace, FileLogger.LogLevel.FatalError);
                return(null);
            }
        }
예제 #6
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.
                }
            }
        }
        /// <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);
        }
예제 #8
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);
        }
예제 #9
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);
        }
예제 #10
0
        public override void Send()
        {
            CoAPSettings.Instance.AddressFamily = System.Net.Sockets.AddressFamily.InterNetworkV6;
            byte[]        payload        = this.ToBytes();
            TestStatus    result         = new TestStatus();
            TestManager   m_test_manager = new TestManager();
            BasicReporter r = new BasicReporter(result);

            m_test_manager.TestReporter = r;

            CoApFsuCommand cmd = new CoApFsuCommand();

            cmd.CoApPayload           = this.ToBytes();
            FsuFacade.UseSecurePort   = false;
            FsuFacade.UseNullHeader   = false;
            FsuFacade.RequiresUserPIN = false;
            FileLogger.Write(String.Format("FsuFacade.UseSecurePort={0}", FsuFacade.UseSecurePort));
            FileLogger.Write(String.Format("FsuFacade.UseNullHeader={0}", FsuFacade.UseNullHeader));
            FileLogger.Write(String.Format("FsuFacade.RequiresUserPIN={0}", FsuFacade.RequiresUserPIN));
            CattEng.Test test = cmd.ToTest(this.IpAddress);//);SSNUtils.MiscTypes.fsu_ip_address);

            m_test_manager.Add(test);
            DateTime startTime = DateTime.Now;

            while (!m_test_manager.Empty)
            {
                Console.WriteLine("Sleeping");
                Thread.Sleep(50);
                DateTime now  = DateTime.Now;
                TimeSpan diff = now - startTime;
                if (diff.TotalMilliseconds > CoApSettings.Instance.RequestTimeout)
                {
                    m_test_manager.Clear();
                    break;
                }
            }

            CoApFsuTest t = (CoApFsuTest)r.TestResult;

            FileLogger.Write(String.Format("Fsu call returned {0}", r.TestResult.CurStatus));
            try
            {
                CoApFsuResponse resp        = (CoApFsuResponse)r.TestResult.ResponseResult.response;
                byte[]          respPayload = resp.Payload;

                //CoAPResponse cr = new CoAPResponse();
                //cr.FromByteStream(respPayload);
                //CoAPPayload p = cr.Payload;
                base.SetGetResult(resp.Payload);
                string toLog = SSNUtils.Conversion.BytesToHexView(resp.Payload);
                FileLogger.Write(String.Format("Payload returned:\n {0}", toLog));
            }
            catch
            {
                base.SetGetResult(new byte[0]);
            }
            //(p.ToStream(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..
                }
            }
        }
        /// <summary>
        /// Fetch a list of devices, in JSON format, from the Gateway.
        /// </summary>
        /// <returns>A JSON document containing the available devices.</returns>
        public DevicesResponse GetDevices()
        {
            var json = "";

            SLDPAPI.SilverLink link = new SilverLink();

            // Set up the SLDP API request.
            link.ClientID  = GatewaySettings.Instance.ClientId;
            link.Secret    = GatewaySettings.Instance.ClientSecret;
            link.Solution  = GatewaySettings.Instance.Solution;
            link.BaseURL   = GatewaySettings.Instance.GatewayBaseURL;
            link.TokenPath = GatewaySettings.Instance.GatewayTokens;

            FileLogger.Write("About to send Gateway request");
            FileLogger.Write("Customer Id = " + GatewaySettings.Instance.Solution);
            FileLogger.Write("Base URL = " + GatewaySettings.Instance.GatewayBaseURL);
            FileLogger.Write("Path = " + GatewaySettings.Instance.GatewayDeviceSearch);

            try
            {
                string path = GatewaySettings.Instance.GatewayDeviceSearch.Replace("<solution>", GatewaySettings.Instance.Solution);
                FileLogger.Write("About to send Gateway request");
                FileLogger.Write("Customer Id = " + GatewaySettings.Instance.Solution);
                FileLogger.Write("Base URL = " + GatewaySettings.Instance.GatewayBaseURL);
                FileLogger.Write("Path = " + path);
                json = link.Get(path);
            }
            catch (Exception e)
            {
                FileLogger.Write("Get failed");
                FileLogger.Write(e.Message);
                FileLogger.Write(e.StackTrace);

                // Rethrow the error if the POST failed.
                throw e;
            }
            FileLogger.Write("JSON response = " + json);

            GatewaySettings.Instance.SfdpToken = link.SilverLinkToken;
            FileLogger.Write("Token acquired from SFDP");
            FileLogger.Write(GatewaySettings.Instance.SfdpToken);

            DevicesResponse devices = null;

            try
            {
                devices = JsonConvert.DeserializeObject <DevicesResponse>(json);
            }
            catch (Exception jsonDeserializeError)
            {
                FileLogger.Write("Error deserializing device search response");
                FileLogger.Write(jsonDeserializeError.Message);
                FileLogger.Write(jsonDeserializeError.Message);
            }

            return(devices);
        }
        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);
        }
예제 #14
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);
        }
예제 #15
0
        /// <summary>
        /// ShutDown terminates any open Gateway session, and cleans up the local socket.
        /// </summary>
        public void ShutDown()
        {
            TerminateSession();
            FileLogger.Write("Shutting down session manager");
            __Done.Reset();
            __Done.Close();
            __Done = null;

            __coapClient.Shutdown();
            __coapClient = null;
        }
예제 #16
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();
        }
예제 #17
0
        /// <summary>
        /// Display a form to load the user's Gateway credentials.
        /// </summary>
        /// <returns>a boolean indicating whether or not we successfully set credentials</returns>
        //private bool SetGatewayCoapApiCredentials()
        //{
        //    FileLogger.Write("Fetch Gateway credentials");

        //    // If we have already established credentials don't display the credentials form.
        //    // If credentials are incorrect or we want to use a different set, then they must be reset via the UI.
        //    if (GatewaySettings.Instance.CoApPassword != "" && GatewaySettings.Instance.CoApId != "")
        //        return true;

        //    frmCoApApiLogin f = new frmCoApApiLogin();
        //    DialogResult r = f.ShowDialog();

        //    // OK and CANCEL are the only dialog results allowed.
        //    // If we get an OK, it is assumed that the credentials have been loaded.
        //    if (r == DialogResult.OK)
        //        return true;

        //    FileLogger.Write("Credentials not loaded");

        //    return false;
        //}

        /// <summary>
        /// Load detalis of all CoAP resources associated with a device
        /// </summary>
        /// <param name="device">The tree node in the device list containing the device</param>
        private CoApResources LoadResources(TreeNode device)
        {
            Cursor.Current = Cursors.WaitCursor;    // Show as buys while loading the resources.

            FileLogger.Write("Loading all known resources for device " + device.Text);
            device.Nodes.Clear();

            CoApDiscovery disc = (CoApDiscovery)NetworkInterface.Instance.DiscoveryRequest;

            disc.ServerPort = GatewaySettings.Instance.CoApPort;
            disc.IpAddress  = device.Text;

            CoApResources resources = disc.LoadResources();

            // Display the error where we would otherwise have displayed the resources.
            if (disc.ErrorResult != "")
            {
                TreeNode[] resNode = new TreeNode[1];
                device.ForeColor = Color.Red;
                resNode[0]       = new TreeNode(disc.ErrorResult);
                device.Nodes.AddRange(resNode);
            }

            if (resources != null && disc.ErrorResult == "")
            {
                FileLogger.Write("Resources returned");
                foreach (CoApResource res in resources)
                {
                    TreeNode[] resNode = new TreeNode[1];
                    resNode[0] = new TreeNode(res.URI);
                    device.Nodes.AddRange(resNode);

                    foreach (CoApLinkAttribute a in res.LinkAttributes)
                    {
                        TreeNode[] node = new TreeNode[1];
                        node[0] = new TreeNode(a.ToString());
                        resNode[0].Nodes.AddRange(node);
                    }
                }
            }
            else
            {
                FileLogger.Write("Resources NOT returned");
            }
            disc = null;
            GC.Collect();
            Cursor.Current = Cursors.Default;   // Clear the "busy" cursor
            return(resources);
        }
        /// <summary>
        /// Uses reflection to instantiate a core HDK client class.
        /// </summary>
        /// <param name="classPrefix">a string describing the base class of the object to return</param>
        /// <returns></returns>
        private object ObjectLoader(string classPrefix)
        {
            // All classes come from the currently executing assembly.
            Assembly assem = System.Reflection.Assembly.GetExecutingAssembly();

            FileLogger.Write(String.Format("Assembly name: {0}", assem.FullName));

            string thisNamespace = assem.FullName.Substring(0, assem.FullName.IndexOf(','));
            Type   t             = assem.GetType(thisNamespace + "." + classPrefix + __InterfaceMethod.ToString());

            object o = Activator.CreateInstance(t);

            FileLogger.Write(String.Format("Object returned: {0}", o.ToString()));
            return(o);
        }
예제 #19
0
        private void treeResources_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            CoApGet get = new CoApGet();

            get.IpAddress  = lstDevices.SelectedItem.ToString();
            get.ServerPort = Convert.ToInt32(cboPort.Text);
            get.URI        = treeResources.SelectedNode.Text;
            if (NetworkInterface.Instance.UsingFSU)
            {
                byte[]        payload        = get.ToBytes();
                TestStatus    result         = new TestStatus();
                TestManager   m_test_manager = new TestManager();
                BasicReporter r = new BasicReporter(result);
                m_test_manager.TestReporter = r;

                CoApFsuCommand cmd = new CoApFsuCommand();
                cmd.CoApPayload           = get.ToBytes();
                FsuFacade.UseSecurePort   = false;
                FsuFacade.UseNullHeader   = false;
                FsuFacade.RequiresUserPIN = false;
                FileLogger.Write(String.Format("FsuFacade.UseSecurePort={0}", FsuFacade.UseSecurePort));
                FileLogger.Write(String.Format("FsuFacade.UseNullHeader={0}", FsuFacade.UseNullHeader));
                FileLogger.Write(String.Format("FsuFacade.RequiresUserPIN={0}", FsuFacade.RequiresUserPIN));
                CattEng.Test test = cmd.ToTest(lstDevices.SelectedItem.ToString());//);SSNUtils.MiscTypes.fsu_ip_address);

                m_test_manager.Add(test);
                while (!m_test_manager.Empty)
                {
                    Console.WriteLine("Sleeping");
                    Thread.Sleep(50);
                }

                CoApFsuTest     t           = (CoApFsuTest)r.TestResult;
                CoApFsuResponse resp        = (CoApFsuResponse)r.TestResult.ResponseResult.response;
                byte[]          respPayload = resp.Payload;
                //CoAPResponse cr = new CoAPResponse();
                //cr.FromByteStream(respPayload);
                //CoAPPayload p = cr.Payload;
                get.SetGetResult(resp.Payload);//(p.ToStream(0));
            }
            else
            {
                get.Send();
            }
            txtResult.Text = get.Response.ToString();
            Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// Process GET responses related to observe.
        /// </summary>
        /// <param name="coapResp">the CoAPResponse object that we are going to report</param>
        private void HandleObserveResponse(CoAPResponse coapResp)
        {
            string toAdd = "";

            try
            {
                toAdd = coapResp.ToString();
                // Setting the text in a method that may have to be Invoked.
                SetText(txtResult, txtResult.Text + toAdd);
            }
            catch (Exception oops)
            {
                FileLogger.Write(oops.Message);
                FileLogger.Write(oops.StackTrace);
            }
        }
예제 #21
0
 /// <summary>
 /// TerminaeSession closes any open Gateway session.
 /// </summary>
 /// <returns></returns>
 public bool TerminateSession()
 {
     if (__SessionTerminated)
     {
         return(true);
     }
     if (!__SessionEstablished)
     {
         return(true);
     }
     FileLogger.Write("Terminating current session");
     __SessionTerminated  = SessionCall(CoAPMessageCode.DELETE);
     __SessionEstablished = false;
     FileLogger.Write("Session terminated = " + __SessionTerminated.ToString());
     return(__SessionTerminated);
 }
예제 #22
0
        /// <summary>
        /// EstablishSession passes the user's credentials to the Gateway.
        /// If the credentials are accepted, the related socket is left open and
        /// subsequent CoAP calls are made using that socket.
        /// </summary>
        /// <returns></returns>
        public bool EstablishSession()
        {
            if (__SessionEstablished)
            {
                return(true);
            }
            FileLogger.Write("Establishing new session");
            __SessionEstablished = SessionCall(CoAPMessageCode.POST);
            if (__SessionEstablished)
            {
                __SessionTerminated = false;
            }

            FileLogger.Write("Session established = " + __SessionEstablished.ToString());
            return(__SessionEstablished);
        }
예제 #23
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();
        }
예제 #24
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);
        }
예제 #25
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());
            __Response = coapResp;
            if (tokenRx == __Token)
            {
                if (BreakIfError(coapResp.Code.Value))
                {
                    return;
                }

                if (coapResp.Code.Value == CoAPMessageCode.DELETED)
                {
                    __Done.Set();
                }
                else
                {
                    //Will come here if an error occurred..
                }
            }
        }
예제 #26
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>
        /// Called when a response is received against a sent request
        /// </summary>
        /// <param name="coapResp">The CoAPResponse object</param>
        private void OnCoAPDiscoveryResponseReceived(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)
            {
                if (BreakIfError(coapResp.Code.Value))
                {
                    this.ErrorResult = coapResp.Code.ToString();
                    return;
                }

                if (coapResp.Code.Value == CoAPMessageCode.CONTENT)
                {
                    // Looks like we have the expected response.
                    // Check the content format and figure out how to store the response.
                    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;
                            }
                        }
                        // The header options match what we expected.
                        // Set the discovery result.
                        if (proceed)
                        {
                            if (ccformat.Value == CoAPContentFormatOption.APPLICATION_LINK_FORMAT)
                            {
                                string discovery = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);
                                __DiscoveryResult = discovery;
                            }

                            __Response = coapResp;
                            __Done.Set();
                        }
                    }
                }
                else
                {
                    //Will come here if an error occurred..
                }
            }
        }
        /// <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);
        }
예제 #29
0
 /// <summary>
 /// Called when error occurs
 /// </summary>
 /// <param name="e">The exception that occurred</param>
 /// <param name="associatedMsg">The associated message (if any)</param>
 private void OnCoAPError(Exception e, AbstractCoAPMessage associatedMsg)
 {
     FileLogger.Write(e.Message);
     __Done.Set();
 }
예제 #30
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
        }