NuGet Package Source

Is the NuGet package source available? I’m trying to understand the RTC .DLL and without an example or documentation, I’m struggling a bit. An example of code or documentation would be great. Or point me to examples if they exist. Thanks

1 Like

The source is not available. The below code should get you going though:

using GHIElectronics.TinyCLR.Devices.Rtc;
using System;
using System.Diagnostics;
using System.Threading;

class Program {
    static void Main() {
        var rtc = RtcController.GetDefault();

        rtc.Now = new DateTime(2019, 1, 8, 9, 0, 0);

        while (true) {
            Debug.WriteLine(rtc.Now.ToString());

            Thread.Sleep(1000);
        }
    }
}
1 Like

Thank you very much.

No luck. Am I missing or doing something wrong? VS2017.

image

image

It’s ok on a PANDA III
Capture

but not on a FEZ. I think RTC isn’t available because there aren’t crystal on the FEZ schematic like this one which is present on PANDA III!

Capture2

On what device, please?

Gotcha. Wondering then how to set the time / date on the FEZ after a restart of the program. I was thinking the RTC device manager would be a start. Don’t need perfect time like an RTC chip. It always starts at 12:00.

You can add RTC breakout board or a shield. There are many RTC circuit options for very cheap on eBay. Or you can try sparkfun or adafruit.

1 Like

I figured out how to pull the time/date from an NTP server and set the system time/date. If one doesn’t really care about long term accuracy, and doesn’t want to add an RTC chip, there is a way to set the system clock using NTP pool servers. The beauty of the STM WiFi module is during association, the module pulls the date/time from an NTP server and I use that information to initiate the system clock. Probably milliseconds off, but close enough and I wrote a way of pulling the time periodically. I will post my code later on today. The FEZ is a great part, thanks GHI!

4 Likes

Great. Yes please do share

The following is two snippets of demo code, all based on the FEZWiFI module that goes out and pulls NTP time and sets the system time. This allows a solution to set the system time from network time server.

    //  constants added to determine state of WiFi - needed for logic control....read on
    private static bool initialization_of_WiFi;
    private static bool wifi_Join_success;

     // Set Wifi States - this is later in code to set the bools before the wifi.Turnon(); call is made
        initialization_of_WiFi = true;
        wifi_Join_success = false;

Add this loop after the wifi.join(ssid, passkey); call is made to allow time for WiFi to complete all its work
// delay loop waiting for operational status to be set
// which is determined by messages received in the message handler
while (initialization_of_WiFi)
{
var wifi_status = wifi.OperationalStatus;// just a dummy call to waste time
Thread.Sleep(50);
}

The following code is 1) A call to check every hour for an update of time needed, 2) the modified handler for messages from the WiFi module, and 3) The call to get the network time

///


/// check_TimeToSet - method that checks the current time to see it if has exceeded the last time set
/// if so, then the network time is updated from an NTP server. This sets the next time update interval to one hour after the current time
/// as the blogs show constant calls to an NTP server may block an IP to avoid ‘slamming’ the server
///

private static void check_TimeToSet()
{
// Update the system time.
// Need to manually compute the offset since timezone is not implmented in TinyCLR
// This call checks to see if one hour has passed. If not, then nothing happens, otherwise
// the call to GetNetworkTime occurs and the time is updated
if (DateTime.Now >= last_TimeSet)
{
DateTime utcDate = GetNetworkTime(-5); // this routine uses the passed parameter as the time offset from UTC (timezone - I am in eastern standard timezone)
SystemTime.SetTime(utcDate); // Sets the system time to the current local time
last_TimeSet = DateTime.Now; // Now update the last_TimeSet to the just retrieved current time
last_TimeSet += new TimeSpan(1, 0, 0); // and adjust it by one hour forward
}
}
///
/// Indication_Received - this is the modified handler for all messages that the WiFi sub-system returns to the TinyCLR
/// operating system. This is in the original FEZWiFI code.
/// In this method the NTP time is extracted and the system time is set along with checking for the WiFi association
/// This is the baseline from FEZWiFI that is modified to look for two specific messages
///

/// Event arguments passed to this method
private static void Indication_Received(SPWF04SxIndicationReceivedEventArgs e)
{
Debug.WriteLine($“WIND: {Program.WindToName(e.Indication)} {e.Message}”); // display the WiFi module message

        //  the NTP time is returned in the NtpServerDelivery message
        if (e.Indication == SPWF04SxIndication.NtpServerDelivery)
        {
            initialization_of_WiFi = false;     // remember those bits defined above?
            string[] words = e.Message.Split('.', ':');     // needed for the parse
            TimeSpan dateSpan = new TimeSpan(-5, 0, 0);     // set UTC time -5
            DateTime utcDate = new DateTime(int.Parse(words[0]), int.Parse(words[1]), int.Parse(words[2]),  // parse out the NTP message
                    int.Parse(words[4]), int.Parse(words[5]), int.Parse(words[6]));
            SystemTime.SetTime(utcDate + dateSpan);     // set the system time/date
            last_TimeSet = DateTime.Now;                     // save the current time in last_TimeSet for 1 hour update
            last_TimeSet += new TimeSpan(1, 0, 0);      // Move the last_TimeSet forward one hour 
        }
        //  Look for the messsage to avoid moving forward in the code until the WiFi is established
        //  Avoids erronously thinking the WiFi hung
        //  The learning with the WiFi is it takes time to get the connection up and running
        //  and patence is the virtue in the WiFi connection
        if (e.Indication == SPWF04SxIndication.WiFiAssociationSuccessful)
        {
            wifi_Join_success = true;     // another bit defined earlier
            if (lcd_present)
            {
                my_LCD.clrscr();
                my_LCD.prints("WiFi Connected");
                my_LCD.gotoSecondLine();
                my_LCD.prints(e.Message.ToString());
            }
            else
            {
                Debug.WriteLine("WiFi Connected");
                Debug.WriteLine(e.Message.ToString());
            }
        }
    }
    /// <summary>
    /// GetNetworkTime - routine that:
    /// 1) obtains a time server from the pool of servers at time.windows.com
    /// 2) Sends 0x1B to the server asking for the current time in NTP format
    /// 3) Computes the date/time from the data received from the NTP server
    /// 4) Turns the computed date/time into a DateTime structure (windows specific)
    /// 5) Adjusts the time for the passed timeSpan which is basically the esired UTC offset
    /// 6) Returns the date/time structure
    /// </summary>
    /// <param name="timeSpan">UTC Offset for desired timezone</param>
    /// <returns>DateTime structure for setting the system time/date</returns>
    private static DateTime GetNetworkTime(int timeSpan)
    {
        TimeSpan dateSpan = new TimeSpan(timeSpan, 0, 0);
        var ntpServer = "time.windows.com";
        var ntpData = new byte[48];

        //  set the command to send to the time server
        ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
        var addresses = Dns.GetHostEntry(ntpServer).AddressList;    // get available server IP address
        string my_IP = addresses[0].ToString();
                    
        var mySocket = wifi.OpenSocket(my_IP, 123, SPWF04SxConnectionType.Udp, SPWF04SxConnectionSecurityType.None, null);
        wifi.WriteSocket(mySocket, ntpData);
        Thread.Sleep(150);
        wifi.ReadSocket(mySocket, ntpData, 0, 48);
        wifi.CloseSocket(mySocket);
        
        //  Now convert the NTP data to a formatted time/date.  This code was harvested from samples on the NIST time website
        //  and from other NTP sites
        ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
        ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
        DateTime networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
        networkDateTime = networkDateTime + dateSpan;

        return networkDateTime;
    }

There all calls to displaying data which in my solution I have a 4-line I2C LCD display and the Adafruit BMP280 sensor. That code can be ignored in this example.

Enjoy. Hope this is worthwhile.

3 Likes