Example #1
0
        /// <summary>
        /// Constructor for creating the web server
        /// Example: HttpWebServer  webServer = new HttpWebServer("SSID", "password", -4);
        /// </summary>
        public HttpWebServer(string SSID, string Password, Double TimeOffSet = -5)
        {
            bool success;

            CancellationTokenSource cs = new(60000);

            success = NetworkHelper.ConnectWifiDhcp(SSID, Password, setDateTime: true, token: cs.Token);

            // Initialize Socket class
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Request and bind to an IP from DHCP server
            socket.Bind(new IPEndPoint(IPAddress.Any, 80));

            Debug.WriteLine("IP " + NetworkInterface.GetAllNetworkInterfaces()[0].IPv4Address);

            String macString = BitConverter.ToString(NetworkInterface.GetAllNetworkInterfaces()[0].PhysicalAddress);

            Debug.WriteLine("Mac " + macString);

            // Start listen for web requests
            socket.Listen(10);

            // SMTP connects automatically to get time
            Rtc.SetSystemTime(DateTime.UtcNow.AddHours(TimeOffSet));

            Debug.WriteLine("System time is:" + DateTime.UtcNow.ToString());

            // Create and start a thead for listening for server requests
            Thread tListenforRequest = new Thread(ListenForRequest);

            tListenforRequest.Start();
        }
Example #2
0
        // This method is run when the mainboard is powered up or reset.
        public static void Main()
        {
            // Use Trace to show messages in Visual Studio's "Output" window during debugging.
            Trace("Program Started");

            telemetryTopic = String.Format("devices/{0}/messages/events/", deviceID);

            Debug.WriteLine("Waiting for network up and IP address...");
            bool success;
            CancellationTokenSource cs = new(60000);

#if HAS_WIFI
            success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
            success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
            if (!success)
            {
                Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                }
                return;
            }

            Thread.Sleep(3000); //used to reliably allow redeployment in VS2019

            DoMqttStuff();

            Thread.Sleep(Timeout.Infinite);
        }
Example #3
0
        public static void Main()
        {
            Debug.WriteLine("Waiting for network up and IP address...");
            bool success;
            CancellationTokenSource cs = new(60000);

#if BUILD_FOR_ESP32
            success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
            success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
            if (!success)
            {
                Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                }
                return;
            }

            // setup user button
            _userButton = GpioController.GetDefault().OpenPin(0);
            _userButton.SetDriveMode(GpioPinDriveMode.Input);
            _userButton.ValueChanged += UserButton_ValueChanged;

            /////////////////////////////////////////////////////////////////////////////////////
            ////add certificate in PEM format(as a string in the app). This was taken from Azure's sample at https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c
            /// chis cert should be used when connecting to Azure IoT on the Azure Cloud available globally. Additional certs can be found in the link above
            X509Certificate rootCACert = new X509Certificate(azurePEMCertBaltimore);
            /////////////////////////////////////////////////////////////////////////////////////

            ///////////////////////////////////////////////////////////////////////////////////
            /// enter your Shared Access Signature. You can create this using the Azure IOT Explorer under "Device Identity" format is
            /// "SharedAccessSignature sr=<iotHubName>.azure-devices.net%2Fdevices%2F<deviceName>&sig=<signature>"
            /// See "Readme" for more details
            string sas = "<Enter SAS Token Here See Read Me for example>";
            ///////////////////////////////////////////////////////////////////////////////////

            //strip the device iotHubName from the SAS token
            var    from       = sas.IndexOf('=') + 1;
            var    to         = sas.IndexOf(".");
            string iotHubName = sas.Substring(from, to - from);
            // strip the deviceName from the SAS
            to   = sas.IndexOf("&");
            from = sas.IndexOf("%2Fdevices%2F") + 13;
            string deviceName = sas.Substring(from, to - from);

            //Create the url for the azure iot hub
            string url = $"https://{iotHubName}.azure-devices.net/devices/{deviceName}/messages/devicebound?api-version=2020-03-13";
            Debug.WriteLine($"Your IOT Hub Name: {iotHubName} and your Device Name: {deviceName}");
            Debug.WriteLine($"Performing Http request to: {url}");

            WorkerThread(url, sas, rootCACert);

            // A custom class that we will convert to Json and pass as the body of the post
            Thread.Sleep(Timeout.Infinite);
        }
Example #4
0
        public static void Main()
        {
            //Setup I2C pins for ESP32 board
            Configuration.SetPinFunction(21, DeviceFunction.I2C1_DATA);
            Configuration.SetPinFunction(22, DeviceFunction.I2C1_CLOCK);

            CancellationTokenSource cs = new(sleepTimeMinutes);

            var success = NetworkHelper.ConnectWifiDhcp(wifiSSID, wifiApPASSWORD, setDateTime: true, token: cs.Token);

            if (!success)
            {
                Debug.WriteLine($"Can't connect to wifi: {NetworkHelper.ConnectionError.Error}");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"NetworkHelper.ConnectionError.Exception");
                }

                GoToSleep();
            }

            // Reset the time counter if the previous date was not valid
            if (allupOperation.Year < 2018)
            {
                allupOperation = DateTime.UtcNow;
            }

            Debug.WriteLine($"Date and time is now {DateTime.UtcNow}");

            const int busId = 1;

            //If SDO pin connected to the 3V,Bmp280.DefaultI2cAddress if SDO pin connected to the GND then Bmp280.SecondaryI2cAddress
            I2cConnectionSettings i2cSettings = new(busId, Bmp280.SecondaryI2cAddress);
            I2cDevice             i2cDevice   = I2cDevice.Create(i2cSettings);

            bme280Sensor = new Bme280(i2cDevice);

            if (!SetupThingsBoard())
            {
                Debug.WriteLine("Error connecting to the server");
                return;
            }

            // launch telemetry thread
            Thread telemetryThread = new Thread(new ThreadStart(TelemetryLoop));

            telemetryThread.Start();

            Debug.WriteLine("Connected to the server.");

            while (true)
            {
                Thread.Sleep(10000);
            }
        }
Example #5
0
        public static void Main()
        {
            Debug.WriteLine("Waiting for network up and IP address...");
            bool success;
            CancellationTokenSource cs = new(60000);

#if HAS_WIFI
            success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
            success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
            if (!success)
            {
                Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                }
                return;
            }

            // setup user button
            // F769I-DISCO -> USER_BUTTON is @ PA0 -> (0 * 16) + 0 = 0
            _userButton = GpioController.GetDefault().OpenPin(3 * 16 + 7);
            _userButton.SetDriveMode(GpioPinDriveMode.Input);
            _userButton.ValueChanged += UserButton_ValueChanged;

            // setup AMQP
            // set trace level
            AmqpTrace.TraceLevel = TraceLevel.Frame | TraceLevel.Information;

            // enable trace
            AmqpTrace.TraceListener = WriteTrace;

            /////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////
            // *** CHECK README for details on this configuration **** //
            Connection.DisableServerCertValidation = false;
            /////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////

            // launch worker thread
            new Thread(WorkerThread).Start();

            Thread.Sleep(Timeout.Infinite);
        }
Example #6
0
        private static bool ConnectToWifi()
        {
            Debug.WriteLine("Program Started, connecting to WiFi.");

            // As we are using TLS, we need a valid date & time
            // We will wait maximum 1 minute to get connected and have a valid date
            var success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: new CancellationTokenSource(WifiSleepTime).Token);

            if (!success)
            {
                Debug.WriteLine($"Can't connect to wifi: {NetworkHelper.ConnectionError.Error}");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"NetworkHelper.ConnectionError.Exception");
                }
            }

            Debug.WriteLine($"Date and time is now {DateTime.UtcNow}");
            return(success);
        }
Example #7
0
        public static void Main()
        {
            Debug.WriteLine("Hello from a webserver!");

            try
            {
                int connectRetry = 0;

                Debug.WriteLine("Waiting for network up and IP address...");
                bool success;
                CancellationTokenSource cs = new(60000);
#if HAS_WIFI
                success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
                success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
                if (!success)
                {
                    Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                    if (NetworkHelper.ConnectionError.Exception != null)
                    {
                        Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                    }
                    return;
                }

                // Instantiate a new web server on port 80.
                using (WebServer server = new WebServer(80, HttpProtocol.Http, new Type[] { typeof(ControllerGpio) }))
                {
                    // Start the server.
                    server.Start();

                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{ex}");
            }
        }
Example #8
0
        public static void Main()
        {
            X509Certificate _myWebServerCertificate509 = new X509Certificate2(_myWebServerCrt, _myWebServerPrivateKey, "");

            Debug.WriteLine("Waiting for network up and IP address...");
            bool success;
            CancellationTokenSource cs = new(60000);

#if BUILD_FOR_ESP32
            success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
            success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
            if (!success)
            {
                Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                }
                return;
            }

            // setup HTTP response
            string responseString = "<HTML><BODY>Hello world! This is nanoFramework.</BODY></HTML>";
            byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

            // Create a listener.
            string prefix = "https";
            int    port   = prefix == "http" ? 80 : 443;

            Debug.WriteLine("* Creating Http Listener: " + prefix + " on port " + port);
            HttpListener listener = new HttpListener(prefix, port);

            // assign server certificate
            listener.HttpsCert = _myWebServerCertificate509;

            listener.SslProtocols = System.Net.Security.SslProtocols.Tls | System.Net.Security.SslProtocols.Tls11 | System.Net.Security.SslProtocols.Tls12;

            Debug.WriteLine($"Listening for HTTP requests @ {NetworkInterface.GetAllNetworkInterfaces()[0].IPv4Address}:{port} ...");
            listener.Start();

            while (true)
            {
                try
                {
                    // now wait on context for a connection
                    HttpListenerContext context = listener.GetContext();

                    // Get the response stream and write the response content to it
                    context.Response.ContentLength64 = buffer.Length;
                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);

                    // output stream must be closed
                    context.Response.Close();

                    // context must be closed
                    context.Close();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("* Error getting context: " + ex.Message + "\r\nSack = " + ex.StackTrace);
                }
            }
        }
        public static void Main()
        {
            var success = NetworkHelper.ConnectWifiDhcp(Ssid, Paswword, token: new CancellationTokenSource(60000).Token);

            if (!success)
            {
                Debug.WriteLine("Can't connect to wifi");
                return;
            }

            Debug.WriteLine("Hello from nanoFramework MQTT 5.0 real v5.0 server test!");
            // You can change the server to test
            // Mosquitto supports MQTT5.0 but send some of the messages as v3.1.1 (forgetting the specific MQTT v5.0 property size)
            // MqttClient mqtt = new MqttClient("test.mosquitto.org", 8883, true, new X509Certificate(CertMosquitto), null, MqttSslProtocols.TLSv1_2);
            // EMQX fully supports v5.0 and sends properly the v.5 property size
            // MqttClient mqtt = new MqttClient("broker.emqx.io", 8883, true, new X509Certificate(CertEMQX), null, MqttSslProtocols.TLSv1_2);
            // Azure IoT Edge
            MqttClient mqtt = new MqttClient(IoTHub, 8883, true, new X509Certificate(CertAzure), null, MqttSslProtocols.TLSv1_2);

            mqtt.ProtocolVersion          = MqttProtocolVersion.Version_5;
            mqtt.ConnectionOpened        += MqttConnectionOpened;
            mqtt.ConnectionClosed        += MqttConnectionClosed;
            mqtt.MqttMsgPublished        += MqttMsgPublished;
            mqtt.MqttMsgPublishReceived  += MqttMqttMsgPublishReceived;
            mqtt.MqttMsgSubscribed       += MqttMqttMsgSubscribed;
            mqtt.MqttMsgUnsubscribed     += MqttMqttMsgUnsubscribed;
            mqtt.ConnectionClosedRequest += MqttConnectionClosedRequest;

            mqtt.RequestResponseInformation = true;
            // Seems like no need of password or user name for Mosquitto or EMQX
            // var ret = mqtt.Connect("nanoTestDevice", true);
            // Need device ID and Sas token for Azure

            var    at           = DateTime.UtcNow;
            var    atString     = (at.ToUnixTimeSeconds() * 1000).ToString();
            var    expiry       = at.AddMinutes(40);
            var    expiryString = (expiry.ToUnixTimeSeconds() * 1000).ToString();
            string toSign       = $"{IoTHub}\n{DeviceID}\n\n{atString}\n{expiryString}\n";
            var    hmac         = new HMACSHA256(Convert.FromBase64String(Sas));
            var    sas          = hmac.ComputeHash(Encoding.UTF8.GetBytes(toSign));

            mqtt.AuthenticationMethod = "SAS";
            mqtt.AuthenticationData   = sas;
            mqtt.UserProperties.Add(new UserProperty("sas-at", atString));
            mqtt.UserProperties.Add(new UserProperty("sas-expiry", expiryString));
            mqtt.UserProperties.Add(new UserProperty("api-version", "2020-10-01-preview"));
            mqtt.UserProperties.Add(new UserProperty("host", IoTHub));
            var ret = mqtt.Connect(DeviceID,
                                   null,
                                   null,
                                   false,
                                   MqttQoSLevel.AtLeastOnce,
                                   false, null,
                                   null,
                                   true,
                                   60
                                   );

            if (ret != MqttReasonCode.Success)
            {
                Debug.WriteLine($"ERROR connecting: {ret}");
                mqtt.Disconnect();
                return;
            }

            // 30 seconds max waiting
            var token = new CancellationTokenSource(30000).Token;

            while (!mqtt.IsConnected && !token.IsCancellationRequested)
            {
                Thread.Sleep(200);
            }

            if (token.IsCancellationRequested)
            {
                Debug.WriteLine($"Too long time to connect, connection closed");
                mqtt.Disconnect();
                return;
            }

            // Uncomment to get flooded with topics
            // mqtt.Subscribe(new string[] { "$SYS/#" }, new MqttQoSLevel[] { MqttQoSLevel.AtLeastOnce });
            // mqtt.Subscribe(new string[] { "nanoTestDevice/#" }, new MqttQoSLevel[] { MqttQoSLevel.AtLeastOnce });
            // For Azure IoT, if you have a subscription that allow cloud to device, you can subscribe to it:
            // mqtt.Subscribe(new string[] { "$iothub/commands" }, new MqttQoSLevel[] { MqttQoSLevel.AtLeastOnce });

            //mqtt.UserProperties.Add(new UserProperty("my beautiful", "property"));
            for (int i = 0; (i < 100) && mqtt.IsConnected; i++)
            {
                // For normal servers
                // var number = mqtt.Publish("nanoTestDevice/publish", Encoding.UTF8.GetBytes($"{{\"Number\":{i}}}"), MqttQoSLevel.ExactlyOnce, false);
                // For Azure IoT
                var number = mqtt.Publish("$iothub/telemetry", Encoding.UTF8.GetBytes($"{{\"Number\":{i}}}"), MqttQoSLevel.AtLeastOnce, false);
                Debug.WriteLine($"Posted message: {number}");
                Thread.Sleep(10000);
            }

            if (mqtt.IsConnected)
            {
                mqtt.Disconnect();
            }

            Thread.Sleep(Timeout.Infinite);
        }
Example #10
0
        public static void Main()
        {
            Debug.WriteLine("Hello from a webserver!");

            try
            {
                Debug.WriteLine("Waiting for network up and IP address...");
                bool success;
                CancellationTokenSource cs = new(60000);
#if HAS_WIFI
                success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
                success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
                if (!success)
                {
                    Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                    if (NetworkHelper.ConnectionError.Exception != null)
                    {
                        Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                    }
                    return;
                }

#if HAS_STORAGE
                _storage = KnownFolders.RemovableDevices.GetFolders()[0];
#endif

                _controller = new GpioController();

#if USE_TLS
                X509Certificate _myWebServerCertificate509 = new X509Certificate2(_myWebServerCrt, _myWebServerPrivateKey, "1234");

                // Instantiate a new web server on port 443.
                using (WebServer server = new WebServer(443, HttpProtocol.Https, new Type[] { typeof(ControllerPerson), typeof(ControllerTest), typeof(ControllerAuth) }))
#else
                // Instantiate a new web server on port 80.
                using (WebServer server = new WebServer(80, HttpProtocol.Http, new Type[] { typeof(ControllerPerson), typeof(ControllerTest), typeof(ControllerAuth) }))
#endif
                {
                    // To test authentication with various scenarios
                    server.ApiKey     = _securityKey;
                    server.Credential = new NetworkCredential("user", "password");
                    // Add a handler for commands that are received by the server.
                    server.CommandReceived += ServerCommandReceived;

#if USE_TLS
                    server.HttpsCert = _myWebServerCertificate509;

                    server.SslProtocols = System.Net.Security.SslProtocols.Tls11 | System.Net.Security.SslProtocols.Tls12;
#endif

                    // Start the server.
                    server.Start();

                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{ex}");
            }
        }
Example #11
0
        public static void Main()
        {
            Debug.WriteLine("Waiting for network up and IP address...");
            bool success;
            CancellationTokenSource cs = new(60000);

#if BUILD_FOR_ESP32
            success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
            success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
            if (!success)
            {
                Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                }
                return;
            }

            /////////////////////////////////////////////////////////////////////////////////////
            // add certificate in PEM format (as a string in the app)
            X509Certificate letsEncryptCACert = new X509Certificate(_dstRootCAX3);
            /////////////////////////////////////////////////////////////////////////////////////

            /////////////////////////////////////////////////////////////////////////////////////
            // add certificate in CER format (as a managed resource)
            X509Certificate digiCertGlobalRootCACert = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.DigiCertGlobalRootCA));
            /////////////////////////////////////////////////////////////////////////////////////


            // get host entry for How's my SSL test site
            //IPHostEntry hostEntry = Dns.GetHostEntry("www.howsmyssl.com");
            // get host entry for Global Root test site
            IPHostEntry hostEntry = Dns.GetHostEntry("https://global-root-ca.chain-demos.digicert.com");

            // need an IPEndPoint from that one above
            IPEndPoint ep = new IPEndPoint(hostEntry.AddressList[0], 443);

            Debug.WriteLine("Opening socket...");
            using (Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try
                {
                    Debug.WriteLine("Connecting...");

                    // connect socket
                    mySocket.Connect(ep);

                    Debug.WriteLine("Authenticating with server...");

                    // setup SSL stream
                    using (SslStream sslStream = new SslStream(mySocket))
                    {
                        ///////////////////////////////////////////////////////////////////////////////////
                        // Authenticating using a client certificate stored in the device is possible by
                        // setting the UseStoredDeviceCertificate property.
                        //
                        // In practice it's equivalent to providing a client certificate in
                        // the 'clientCertificate' parameter when calling AuthenticateAsClient(...)
                        //
                        ///////////////////////////////////////////////////////////////////////////////////
                        //stream.UseStoredDeviceCertificate = true;

                        ///////////////////////////////////////////////////////////////////////////////////
                        // Authenticating the server can be handled in one of three ways:
                        //
                        // 1. By providing the root CA certificate of the server being connected to.
                        //
                        // 2. Having the target device preloaded with the root CA certificate.
                        //
                        // !! NOT SECURED !! NOT RECOMENDED !!
                        // 3. Forcing the authentication workflow to NOT validate the server certificate.
                        //
                        ///////////////////////////////////////////////////////////////////////////////////

                        // option 1
                        // setup authentication (add CA root certificate to the call)
                        // Let's encrypt test certificate
                        //stream.AuthenticateAsClient("www.howsmyssl.com", null, letsEncryptCACert, SslProtocols.Tls11);
                        // GlobalRoot CA cert from resources
                        sslStream.AuthenticateAsClient("global-root-ca.chain-demos.digicert.com", null, digiCertGlobalRootCACert, SslProtocols.Tls12);

                        // option 2
                        // setup authentication (without providing root CA certificate)
                        // this requires that the trusted root CA certificates are available in the device certificate store
                        //stream.AuthenticateAsClient("www.howsmyssl.com", SslProtocols.Tls11);
                        //stream.AuthenticateAsClient("global-root-ca.chain-demos.digicert.com", SslProtocols.Tls12);

                        // option 3
                        // disable certificate validation
                        //stream.SslVerification = SslVerification.NoVerification;
                        //stream.AuthenticateAsClient("www.howsmyssl.com", SslProtocols.TLSv11);

                        Debug.WriteLine("SSL handshake OK!");

                        // write an HTTP GET request to receive data
                        byte[] buffer = Encoding.UTF8.GetBytes("GET / HTTP/1.0\r\n\r\n");
                        sslStream.Write(buffer, 0, buffer.Length);

                        Debug.WriteLine($"Wrote {buffer.Length} bytes");

                        int bytesCounter = 0;

                        do
                        {
                            var bufferLenght = sslStream.Length;

                            // if available length is 0, need to read at least 1 byte to get it started
                            if (bufferLenght == 0)
                            {
                                bufferLenght = 1;
                            }

                            // setup buffer to read data from socket
                            buffer = new byte[bufferLenght];

                            // trying to read from socket
                            int bytes = sslStream.Read(buffer, 0, buffer.Length);

                            bytesCounter += bytes;

                            if (bytes > 0)
                            {
                                // data was read!
                                // output as string
                                // mind to use only the amount of data actually read because it could be less than the requested count
                                Debug.Write(new String(Encoding.UTF8.GetChars(buffer, 0, bytes)));
                            }
                        }while (sslStream.DataAvailable);

                        Debug.WriteLine($"Read {bytesCounter} bytes");
                    }
                }
                catch (SocketException ex)
                {
                    Debug.WriteLine($"** Socket exception occurred: {ex.Message} error code {ex.ErrorCode}!**");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"** Exception occurred: {ex.Message}!**");
                }
            }

            Thread.Sleep(Timeout.Infinite);
        }
Example #12
0
        public static void Main()
        {
            Debug.WriteLine("Waiting for network up and IP address...");
            bool success;
            CancellationTokenSource cs = new(60000);

#if BUILD_FOR_ESP32
            success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
            success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
            if (!success)
            {
                Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                }
                return;
            }

            // follow some test URLs and root CA certificates

            /////////////////////////////////////////////////////////////////////////////////////
            ////add certificate in PEM format(as a string in the app)
            //X509Certificate rootCACert = new X509Certificate(letsEncryptCACertificate);
            ////test URL for Let's encrypt certificate
            //string url = "https://www.howsmyssl.com";
            /////////////////////////////////////////////////////////////////////////////////////

            ///////////////////////////////////////////////////////////////////////////////////
            // add certificate from resources in CRT format
            X509Certificate rootCACert = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.DigiCertGlobalRootCA));
            // test URL for DigiCert certificate
            string url = "https://global-root-ca.chain-demos.digicert.com";
            ///////////////////////////////////////////////////////////////////////////////////


            Debug.WriteLine($"Performing Http request to: {url}");

            // perform the request as a HttpWebRequest
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = "GET";

            //////////////////////////////////////////////////////////////////////
            // need to set the SSL protocol that the connection is going to use //
            // *** this MANDATORY otherwise the authentication will fail ***    //
            //////////////////////////////////////////////////////////////////////
            httpWebRequest.SslProtocols = System.Net.Security.SslProtocols.Tls12;

            // if the request is to a secured server we need to make sure that we either:
            // 1. provide the root CA certificate
            // 2. the device has already stored a root CA bundle that will use when performing the authentication
            httpWebRequest.HttpsAuthentCert = rootCACert;

            // get the response as a HttpWebResponse
            // wrap the response object with a using statement to make sure that it's disposed
            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                // wrap the response stream on a using statement to make sure that it's disposed
                using (var stream = httpWebResponse.GetResponseStream())
                {
                    // read response in chunks of 1k

                    byte[] buffer    = new byte[1024];
                    int    bytesRead = 0;

                    Debug.WriteLine("Http response follows");
                    Debug.WriteLine(">>>>>>>>>>>>>");

                    do
                    {
                        bytesRead = stream.Read(buffer, 0, buffer.Length);
                        Debug.Write(Encoding.UTF8.GetString(buffer, 0, bytesRead));
                    }while (bytesRead >= buffer.Length);
                }

                Debug.WriteLine(">>>>>>>>>>>>>");
                Debug.WriteLine("End of Http response");
            }

            Thread.Sleep(Timeout.Infinite);
        }
Example #13
0
        public static void Main()
        {
            NetworkStream netStream      = null;
            Socket        listenerSocket = null;

            CertificateManager.AddCaCertificateBundle(testCACertificate);

            // server certificate
            // make sure to add a correct PEM encoded certificate, including the RSA key
            X509Certificate2 serverCert = new X509Certificate2(serverTestCertificate, serverTestCertificateKey, "");

            Debug.WriteLine("Waiting for network up and IP address...");
            bool success;
            CancellationTokenSource cs = new(60000);

#if BUILD_FOR_ESP32
            success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token);
#else
            success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token);
#endif
            if (!success)
            {
                Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}.");
                if (NetworkHelper.ConnectionError.Exception != null)
                {
                    Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}");
                }
                return;
            }

            Debug.WriteLine("Setting up socket...");

            using (Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IPv4))
            {
                // create a local IPEndPoint
                IPEndPoint ep = new IPEndPoint(0, 443);

                Debug.WriteLine("Listen to connections...");

                // bind socket to local endpoint
                mySocket.Bind(ep);

                // wait for connection
                mySocket.Listen(1);

                listenerSocket = mySocket.Accept();

                try
                {
                    // Once connection established need to create secure stream and authenticate server.
                    netStream = new SslStream(listenerSocket);

                    ///////////////////////////////////////////////////////////////////////////////////
                    // Using a server certificate stored in the device is possible by
                    // setting the UseStoredDeviceCertificate property.
                    //
                    // In practice it's equivalent to providing a server certificate in
                    // the 'serverCertificate' parameter when calling AuthenticateAsServer(...)
                    //
                    ///////////////////////////////////////////////////////////////////////////////////
                    ((SslStream)netStream).UseStoredDeviceCertificate = true;

                    // Throws exception if this fails
                    // pass the server certificate
                    // do not require client certificate
                    ((SslStream)netStream).AuthenticateAsServer(serverCert, false, SslProtocols.Tls11);

                    // setup buffer to read data from socket
                    byte[] buffer = new byte[1024];

                    // trying to read from socket
                    int bytes = netStream.Read(buffer, 0, buffer.Length);

                    Debug.WriteLine($"Read {bytes} bytes");

                    if (bytes > 0)
                    {
                        // we have data!
                        // output as string
                        Debug.WriteLine(new string(Encoding.UTF8.GetChars(buffer)));
                    }
                }
                catch
                {
                }
                finally
                {
                    if (netStream != null)
                    {
                        netStream.Close();
                        listenerSocket.Close();
                    }
                }
            }
        }