[Answered]NTP Problem or 5100 problem? (or me)

With the follow code I get the following error:

An unhandled exception of type ‘System.Exception’ occurred in GHIElectronics.NETMF.W5100.dll
Additional information: Currently, Connect() method is only for TCP socket use.

Any Ideas what I am doing wrong?

using System;                   //Needed to create Sockets
using System.Text;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Net;       //Needed to create Sockets
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Time;

using GHIElectronics.NETMF.Net;
using GHIElectronics.NETMF.Hardware;
using GHIElectronics.NETMF.Net.Sockets;
using GHIElectronics.NETMF.Net.NetworkInformation;
using GHIElectronics.NETMF.FEZ;
using Socket = GHIElectronics.NETMF.Net.Sockets.Socket;



namespace FEZ_Panda_II_Get_Time_From_TimeServer
{
            public class Program
            {
                        public static void Main()
                        {
                            const Int32 c_port = 80;                            // Port used for http requests
                            byte[] ip = { 192, 168, 0, 150 };                   // Assigned IP address
                            byte[] subnet = { 255, 255, 255, 0 };               // Assigned Subnet
                            byte[] gateway = { 192, 168, 0, 1 };                // Assigned Gateway Address
                            byte[] mac = { 0x00, 0x9A, 0xD2, 0xC2, 0xD9, 0x2A }; //Randomly generated MAC from http://www.macvendorlookup.com
                            WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di10, (Cpu.Pin)FEZ_Pin.Digital.Di9, true); // WIZnet interface with FEZ Connect
                            //NetworkInterface.EnableStaticIP(ip, subnet, gateway, mac); //Assigns ip/subnet/gateway/mac to Wiznet
                            //NetworkInterface.EnableStaticDns(new byte[] { 192, 168, 0, 1 }); //
                            //Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, c_port);
                            Dhcp.EnableDhcp(mac); //Used to check if there were any problems with the network settings
                            Debug.Print("Current Time: " + DateTime.Now.ToString());
                            Utility.SetLocalTime(NTPTime("time-a.nist.gov"));
                            
                            Debug.Print("Updated Time: " + DateTime.Now.ToString());
                            Debug.GC(true); // Enable Garbage Collector
                            Debug.EnableGCMessages(true); // Enable / Disable Garbage Collector Messages

                            Thread.Sleep(Timeout.Infinite);                            
                        }

                        
                       

                        /// <summary>
                        /// Get DateTime from NTP Server 
                        /// Based on:
                        /// http://weblogs.asp.net/mschwarz/archive/2008/03/09/wrong-datetime-on-net-micro-framework-devices.aspx
                        /// </summary>
                        /// <param name="TimeServer">Timeserver</param>
                        /// <returns>Local NTP Time</returns>
                        public static DateTime NTPTime(String TimeServer)
                        {
                            // Find endpoint for timeserver
                            IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
                            // Connect to timeserver
                            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                            s.Connect(ep);
                            // Make send/receive buffer
                            byte[] ntpData = new byte[48];
                            Array.Clear(ntpData, 0, 48);
                            // Set protocol version
                            ntpData[0] = 0x1B;
                            // Send Request
                            s.Send(ntpData);
                            // Receive Time
                            s.Receive(ntpData);
                            byte offsetTransmitTime = 40;
                            ulong intpart = 0;
                            ulong fractpart = 0;
                            for (int i = 0; i <= 3; i++)
                                intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
                            for (int i = 4; i <= 7; i++)
                                fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
                            ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
                            s.Close();
                            TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                            DateTime dateTime = new DateTime(1900, 1, 1);
                            dateTime += timeSpan;
                            TimeSpan offsetAmount = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
                            DateTime networkDateTime = (dateTime + offsetAmount);
                            return networkDateTime;
                        }
                        
            }


    
}

That is normal, you can’t “connect” a UDP connection.

Go here http://code.tinyclr.com and search fro UDP for examples

Here is my NTP code for WIZ5100.
GmtOffset in minutes.
Updates system time and RTC
Correctly handling timeouts (sometimes, you don’t receive an answer) and exceptions.


// Try to update time according to TimeServer
        private bool NTPTime(string TimeServer, int GmtOffset = 0)
        {
            Socket s = null;
            try
            {
                EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);             
                byte[] ntpData = new byte[48];
                Array.Clear(ntpData, 0, 48);
                ntpData[0] = 0x1B; // Set protocol version
                s.SendTo(ntpData, rep); // Send Request   
                if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout
                {
                    s.ReceiveFrom(ntpData, ref rep); // Receive Time
                    byte offsetTransmitTime = 40;
                    ulong intpart = 0;
                    ulong fractpart = 0;
                    for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
                    for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
                    ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
                    s.Close();          
                    TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                    DateTime dateTime = new DateTime(1900, 1, 1);
                    dateTime += timeSpan;
                    Utility.SetLocalTime(dateTime.AddMinutes(GmtOffset));
                    RealTimeClock.SetTime(DateTime.Now);
                    return true;
                }
                s.Close();
            }
            catch
            {      
                try { s.Close(); } 
                catch { } 
            }
            return false;
        }

Thanks Nicolas. Newbie question: How do you call it? No C# experience here. Trying to learn as I go along.

Assuming Nicolas3’s function was in a class called MyTime and you made the function public, it would look something like:


// instantiate your object
MyTime t = new MyTime();
// call the function
t.NTPTime("sometimeserver.com", -5);

The -5 is Eastern Standard Time (my time zone). Your value will vary. This will set your real time clock and system time to your local time if the NTP server responds. If you only need this one function, you can make it static and add it to the Program() class that gets created when you open a new FEZ project template.

@ Nicolas3 - I haven’t forgotten about your resource question. I attempted to use your beta5 (or 6?) code this weekend and quickly found out I needed to update to the latest SDK first! Then Easter happened. Dang holidays are cutting into my geek time again :slight_smile: I hope your Panda arrives soon! I’m having a blast with the Tinkerer kit.

Thanks for your help guys. I have been struggling with the for over a week. What is a good source for learning the micro Framework and all its nuances? I could also use a good source for GHI information as well. Preferably something written in crayon or magic marker because I am having a hard time understanding the high level information in GHI’s docs(even found it wrong in one case).

I didn’t find the NTP client on code-share. Would guys like to share it with everyone here? http://code.tinyclr.com/

Gus,

I will share this week end.
It is actualy on code.tinyclr.com, but within a package of “misc functions”, and it is not under a reliable form (blocking calls without timeouts, no try-catch, etc.

Added here : http://code.tinyclr.com/project/305/ntp-time-adjustement-for-wiz5100/

Brilliant :smiley: Thanks