Main Site Documentation

Update Time Problem


#1

Hi guys,

Just got a Cobra and I am trying to covert some of the Panda II code over for use in a new app. The time update method is my first problem. I need to update the time on the Cobra. Here’s the error:

DCHP - IP Address = 192.168.0.101 … Net Mask = 255.255.255.0 … Gateway = 192.168.0.1
#### Exception System.Net.Sockets.SocketException - CLR_E_FAIL (1) ####
#### Message:
#### Microsoft.SPOT.Net.SocketNative::getaddrinfo [IP: 0000] ####
#### System.Net.Dns::GetHostEntry [IP: 0008] ####
#### FEZ_Cobra_Console_NTP_Time.Program+myTime::NTPTime [IP: 0008] ####
#### FEZ_Cobra_Console_NTP_Time.Program::Main [IP: 0060] ####
#### SocketException ErrorCode = -1
#### SocketException ErrorCode = -1
A first chance exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll
#### SocketException ErrorCode = -1
#### SocketException ErrorCode = -1
#### Exception System.NullReferenceException - CLR_E_NULL_REFERENCE (1) ####
#### Message:
#### FEZ_Cobra_Console_NTP_Time.Program+myTime::NTPTime [IP: 0119] ####
#### FEZ_Cobra_Console_NTP_Time.Program::Main [IP: 0060] ####
A first chance exception of type ‘System.NullReferenceException’ occurred in FEZ Cobra Console Application.exe
Updated Time: 01/01/2009 00:01:54

Would someone point out the error in the program.

Thanks,

K

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

using Microsoft.SPOT;
using Microsoft.SPOT.Time;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.Hardware;

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


namespace FEZ_Cobra_Console_NTP_Time
{
    public class Program
    {
    private static bool timeUpdate = false;


        public static void Main()
        {
            
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface NI = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];

            if (NI.IsDhcpEnabled == false)
            {
                Debug.Print("DCHP - IP Address = " + NI.IPAddress + " ... Net Mask = " + NI.SubnetMask + " ... Gateway = " + NI.GatewayAddress);
            }

            while (true)
            {
                if (timeUpdate == false)
                {
                    myTime Update = new myTime();
                    Update.NTPTime("time-a.nist.gov", -300);
                    timeUpdate = true;
                    Debug.Print("Updated Time: " + DateTime.Now.ToString()); //displays updated time in VS2010 output window
                }

                
            }

        }



        public class myTime
        {
            public 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
                    s.SendTo(ntpData, rep);


                    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;


            }
        }
    }
}


#2

Use this on the cobra for ntp: http://www.tinyclr.com/forum/10/1294/#/1/msg13535


#3

Fist of all, the NTPTime method can be made static so that you don’t create a new object every time you want to get the time.

Could you check that your DHCP server gives you a valid DNS address.
The first exception is at Dns.GetHostEntry(TimeServer), so the address can not be resolved.
The second exception is at

catch
                {
                    try { s.Close(); }
                    catch { }
                }

because s is null when the first exception is thrown. You should check if s is different then null before closing.


#4

Got the code from http://www.tinyclr.com/forum/10/1294/#/1/msg13535 and the problem still exists. With the new code(as well as the old code) the error resides in this line of code :

EndPoint ep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);

What am I missing?

The image below is the network settings via MFDeploy.exe and here’s the code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

using Microsoft.SPOT;
using Microsoft.SPOT.Time;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.Hardware;

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


namespace FEZ_Cobra_Console_NTP_Time
{
    public class Program
    {
    private static bool timeUpdate = false;


        public static void Main()
        {
            
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface NI = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];

            if (NI.IsDhcpEnabled == false)
            {
                Debug.Print("Static: \nIP Address = " + NI.IPAddress + " \nNet Mask = " + NI.SubnetMask + " \nGateway = " + NI.GatewayAddress);
            }

            while (true)
            {
                if (timeUpdate == false)
                {
                    //myTime Update = new myTime();
                    //Update.NTPTime("time-a.nist.gov", -300);
                    Utility.SetLocalTime(NTPTime("time-a.nist.gov"));
                    timeUpdate = true;
                    Debug.Print("Updated Time: " + DateTime.Now.ToString()); //displays updated time in VS2010 output window
                }

                
            }

        }


        public static DateTime NTPTime(String TimeServer)
        {
            // Find endpoint for timeserver
            EndPoint 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;
        }       
    }
}


#5

In the image there is no DNS address set. You could use 8.8.8.8 or 8.8.4.4 (google public dns servers)


#6

Thanks! That fixed it but I still don’t understand. The code for my Panda didn’t have a DNS server set and it worked(using a static IP). The only difference that I can see is that the Panda is using a GHI assembly and the Cobra is using a Microsoft assembly.


#7

If you want to resolve a domain name, you can’t do it without DNS (which requires a DNS address). I’m sure it was set (or maybe GHI uses a public DNS if none is set?).