Ejemplo n.º 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();
        }
Ejemplo n.º 2
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)
        {
            _SSID = SSID;

            _Password = Password;

            _TimeOffSet = TimeOffSet;

            ConnectNetwork();

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

            Console.WriteLine(NetworkInterface.GetAllNetworkInterfaces()[0].IPv4Address);

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

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

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

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

            tListenforRequest.Start();
        }
Ejemplo n.º 3
0
        public static void Main()
        {
            Console.WriteLine("system time is: " + DateTime.UtcNow);

            // set RTC
            Rtc.SetSystemTime(new DateTime(2018, 2, 28, 10, 20, 30));

            Console.WriteLine("system time is: " + DateTime.UtcNow);

            Thread.Sleep(Timeout.Infinite);
        }
        private void Sync_clocks()
        {
            var time = clock.GetDateTime();

            if (time.Year < 2100)
            {
                Rtc.SetSystemTime(time);
                InvokeOn1Spassed(time);
            }
            else
            {
                InvokeOn1Spassed(DateTime.UtcNow, false);
            }
        }
Ejemplo n.º 5
0
        private static bool SetupNetwork()
        {
            CancellationTokenSource cs = new CancellationTokenSource(5000); //5 seconds.

            // We are using TLS and it requires valid date & time (so we should set the option to true, but SNTP is run in the background, and setting it manually causes issues for the moment!!!)
            // Although setting it to false seems to cause a worse issue. Let us fix this by using a managed class instead.

            try
            {
                _logger.LogInformation("Waiting for network up and IP address...");
                var success = NetworkHelper.SetupAndConnectNetwork(requiresDateTime: true, token: cs.Token);


                if (!success)
                {
                    _logger.LogWarning($"Failed to receive an IP address and/or valid DateTime. Error: {NetworkHelper.Status}.");
                    if (NetworkHelper.HelperException != null)
                    {
                        _logger.LogWarning($"Failed to receive an IP address and/or valid DateTime. Error: {NetworkHelper.HelperException}.");
                    }
                    _logger.LogInformation("It is likely a DateTime problem, so we will now try to set it using a managed helper class!");

                    success = Rtc.SetSystemTime(ManagedNtpClient.GetNetworkTime());
                    if (success)
                    {
                        _logger.LogInformation("Retrived DateTime using Managed NTP Helper class...");
                    }
                    else
                    {
                        _logger.LogWarning("Failed to Retrive DateTime (or IP Address)! Retrying...");
                        SetupNetwork();
                    }
                    _logger.LogInformation($"RTC = {DateTime.UtcNow}");

                    return(false);
                }

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e.Message.ToString());
                return(false);
            }
        }
Ejemplo n.º 6
0
        static void UpdateRTCFromNetwork()
        {
            Console.WriteLine("... requesting time from NTP server ...");

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // the following code block uses an async call to SNTP client which should be OK for most of the use scenarios
            // check an alternative in the code block commented bellow

            SIM800H.SntpClient.SyncNetworkTimeAsync("pool.ntp.org", TimeSpan.Zero, (ar) =>
            {
                // update RTC only if update was successful
                if (((SyncNetworkTimeAsyncResult)ar).Result == SyncResult.SyncSuccessful)
                {
                    // get current date time and update RTC
                    DateTime rtcValue = SIM800H.GetDateTime();
                    // set framework date time
                    Rtc.SetSystemTime(rtcValue);

                    Console.WriteLine("!!! new time from NTP server: " + rtcValue.ToString());

                    // done here, dispose SNTP client to free up memory
                    SIM800H.SntpClient.Dispose();
                    SIM800H.SntpClient = null;
                }
                else
                {
                    Console.WriteLine("### failed to get time from NTP server ###");
                }
            });

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // if your network connection is not that good and you definitely need a valid RTC better do this inside a try/catch AND using a retry strategy
            // the implementation bellow uses a synchronous call to SNTP client
            // for the simplest async call see the

            //byte retryCounter = 0;

            //while (retryCounter <= 3)
            //{
            //    try
            //    {
            //        var result = SIM800H.SntpClient.SyncNetworkTimeAsync("time.nist.gov", TimeSpan.Zero).End();

            //        // check result
            //        if (result == SyncResult.SyncSuccessful)
            //        {
            //            // get current date time and update RTC
            //            DateTime rtcValue = SIM800H.GetDateTime();
            //            // set framework date time
            //            Rtc.SetSystemTime(rtcValue);

            //            Console.WriteLine("!!! new time from NTP server: " + rtcValue.ToString());

            //            // done here, dispose SNTP client to free up memory
            //            SIM800H.SntpClient.Dispose();
            //            SIM800H.SntpClient = null;

            //            return;
            //        }
            //        else
            //        {
            //            Console.WriteLine("### failed to get time from NTP server ###");
            //        }
            //    }
            //    catch
            //    {
            //        // failed updating RTC
            //        // flag this
            //    }

            //    // add retry
            //    retryCounter++;

            //    // progressive wait 15*N seconds before next retry
            //    Thread.Sleep(15000 * retryCounter);
            //}
        }