Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

N+ hangs sometimes when try to receive Time


  • Please log in to reply
9 replies to this topic

#1 Ellen

Ellen

    Advanced Member

  • Members
  • PipPipPip
  • 65 posts
  • LocationRotterdam, Netherlands

Posted 14 August 2012 - 09:03 AM

Hello,

How can i resolve hanging my N+ when i want to sync my Netduino with a time server.

Function call:

Utility.SetLocalTime(NTPTime("time-a.nist.gov"))
"time-a.nist.gov" : ntp ok, time,daytime busy, not recommended

He will sometimes hang when receive :

s.Receive(ntpData)

I can choose out of many servers but that is for now not the point.
http://tf.nist.gov/tf-cgi/servers.cgi

How to resolve?
Thanks in advance, Ellen



        Private Shared Function NTPTime(ByVal TimeServer As [String]) As DateTime

            Dim ep As New IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList(0), 123)
            Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
            Dim ntpData As Byte() = New Byte(47) {}
            Array.Clear(ntpData, 0, 48)

            ntpData(0) = &H1B
            s.SendTimeout = 5000

            s.SendTo(ntpData, ep)
            s.Receive(ntpData)     'with debugging, HERE he will stop.'

            Dim offsetTransmitTime As Byte = 40

            Dim intpart As Long = 0
            Dim fractpart As Long = 0

            For i As Integer = 0 To 3
                intpart = (intpart << 8) Or ntpData(offsetTransmitTime + i)
            Next

            For i As Integer = 4 To 7
                fractpart = (fractpart << 8) Or ntpData(offsetTransmitTime + i)
            Next

            Dim milliseconds As Long = CLng(intpart * 1000 + (fractpart * 1000) / &H100000000L)

            s.Close()

            Dim timeSpan__1 As TimeSpan = TimeSpan.FromTicks(CLng(milliseconds) * TimeSpan.TicksPerMillisecond)
            Dim dT As New DateTime(1900, 1, 1)
            dT += timeSpan__1

            'daylight saving'
            If dT.Month < 3 OrElse dT.Month > 10 Then
                Return dT.AddHours(1)
            End If
            If dT.Month > 3 AndAlso dT.Month < 10 Then
                Return dT.AddHours(2)
            End If
            If dT.Month = 3 Then
                '      in march'
                If (dT.Day - CInt(dT.DayOfWeek)) < 25 Then
                    Return dT.AddHours(1)
                End If
                If (CInt(dT.DayOfWeek) = 0) AndAlso (dT.Hour < 2) Then
                    Return dT.AddHours(1)
                End If
                Return dT.AddHours(2)
            End If
            '      in october'
            If (dT.Day - CInt(dT.DayOfWeek)) < 25 Then
                Return dT.AddHours(2)
            End If
            If (CInt(dT.DayOfWeek) = 0) AndAlso (dT.Hour < 2) Then
                Return dT.AddHours(2)
            End If

            Return dT.AddHours(1)
        End Function




#2 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 14 August 2012 - 09:27 AM

Hi Ellen, Is your app hanging on Utility.SetLocalTime or on the NTPTime call? What does the NTPTime code look like? Chris

#3 Ellen

Ellen

    Advanced Member

  • Members
  • PipPipPip
  • 65 posts
  • LocationRotterdam, Netherlands

Posted 14 August 2012 - 10:32 AM

Hi Ellen,

Is your app hanging on Utility.SetLocalTime or on the NTPTime call?

What does the NTPTime code look like?

Chris


No he hangs on a earlier somewhere on this forum copied NTPTime call (source code I had included above), at s.Receive(ntpData)

I think i need to call the Socket.ReceiveTimeout Property because the default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.

In other words, with a ?bad connection? i can wait until i have gray hair. :blink:

#4 skarphedinnos

skarphedinnos

    Member

  • Members
  • PipPip
  • 26 posts
  • LocationIceland

Posted 24 October 2012 - 12:39 AM

Hi. I have been trying this NTP for couple of days now. I have the same problem, the program hangs on s.Receive(ntpData). I have tried various NTP servers, both server names and ip addresses. The ND is connected to ethernet on laptop using bridged connection between the ethernet and wifi. If I put some NTP server name I can see it's IP while debugging. BTW I'm using latest firmware(4.201). Any ideas? Or can someone post code with NTP server that is currently working? Thanks, Skarphedinn.

#5 fesp

fesp

    New Member

  • Members
  • Pip
  • 6 posts

Posted 05 March 2013 - 06:43 AM

Did you ever solve this? I'm facing the same problem...



#6 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 05 March 2013 - 07:28 AM

Hi fesp,

Did you ever solve this? I'm facing the same problem...

Are you using a Netduino Plus or a Netduino Plus 2? If NP2, it also incorporates the built-in NETMF classes for NTP. Chris

#7 fesp

fesp

    New Member

  • Members
  • Pip
  • 6 posts

Posted 05 March 2013 - 08:11 PM

It's a Netduino Plus (4.2.0.1). I just ordered an NP2 and it should be arriving tomorrow. But I'd really like to get it working with this device. I have seen it working before, but that was probably with an earlier firmware version. Can it be related to that?



#8 baxter

baxter

    Advanced Member

  • Members
  • PipPipPip
  • 415 posts

Posted 05 March 2013 - 09:39 PM

Hi fesp,

 

Attached is a routine using the NIST DayTime protocol it uses TCP and port 13. It has always been reliable for me on startup for both the Plus 1 and 2 to set the Netduino clock. It is setup for 3 servers and tries each server three times. 

 

Baxter

Call it like this,Try    Using NIST_Time As DayTimeNIST = New DayTimeNIST("utcnist2.colorado.edu", -8)        NIST_Time.UTC_offset = -8        NIST_Time.GetTimeFromNIST()        Debug.Print("Clock set: " & NIST_Time.successful)        Debug.Print("Server used: " & NIST_Time.TimeServer)        Debug.Print("Time from NIST  " & NIST_Time.networkDateTime)        Debug.Print("Current time set from DayTimeNIST: " & DateTime.Now.ToString)    End UsingCatch    Debug.Print("no IP Address")             End Try============Imports Microsoft.SPOTImports Microsoft.SPOT.HardwareImports SecretLabs.NETMF.Hardware'Imports SecretLabs.NETMF.Hardware.NetduinoPlusImports SecretLabs.NETMF.Hardware.NetduinoImports System.ThreadingImports System.NetImports System.TextImports System.Net.SocketsImports Microsoft.SPOT.Net.NetworkInformation''' <summary>''' Set Netduino Plus time using NIST Daytime Protocol''' Upon return from getTimeNIST, the clock is running''' with the correction for daylight savings or''' standard time and the input UTC offset.''' </summary>''' <remarks></remarks>Public Class DayTimeNIST    Implements IDisposable    Private disposed As Boolean = False    'these servers are always reliable for Daytime protocol    Private Servers() As String = {"wwv.nist.gov", "utcnist2.colorado.edu", "utcnist.colorado.edu"}    Private ServerIndex As Integer = 0 'server index    Private buffer(51) As Byte 'Size of Daytime Protocol response    Public Sub New()        Me.TimeServer = Servers(ServerIndex)        ServerIndex += 1    End Sub    Public Sub New(ByVal tServer As String, ByVal offsetUTC As Integer)        Me.TimeServer = tServer.Trim        Me.UTC_offset = offsetUTC    End Sub    Public Property TimeServer As String    Public Property UTC_offset As Integer = -8 'Default: Pacific Time (US & Canada)    Public Property successful As Boolean = False    Public Property networkDateTime As String    Public Sub GetTimeFromNIST()        'format of Daytime string: JJJJJ YR-MO-DA HH:MM:SS TT L H msADV UTC(NIST) OTM        Dim nBytes As Integer = 0        Dim count As Integer = 0        Dim StdTime As Integer = 0        Dim s1() As String = {}        Dim s2() As String = {}        Dim s3() As String = {}        Dim success As Boolean = False        ' Connect to timeserver         Do While (nBytes = 0)            count += 1            Using s As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)                s.ReceiveTimeout = 500                Dim ep As IPEndPoint = New IPEndPoint(Dns.GetHostEntry(Me.TimeServer).AddressList(0), 13)                s.Connect(ep)                nBytes = s.Receive(buffer)                s.Close()            End Using            If (nBytes <> 0) Then                Dim Response As String = Encoding.UTF8.GetChars(buffer)                s1 = Response.Split(" "c)                s2 = s1(1).Split("-"c) 'yr, mo, day                s3 = s1(2).Split(":"c) 'hr, min, sec                Dim DST As Integer = CInt(s1(3))                'Set the correct daylight or standard time                If (DST = 0 Or DST > 51) Then 'on standard time                    StdTime = 0                ElseIf (DST <= 50 And DST > 1) Then                    StdTime = 1                End If                Dim dt As DateTime = New DateTime(2000 + CInt(s2(0)), CInt(s2(1)), CInt(s2(2)),                                          CInt(s3(0)), CInt(s3(1)), CInt(s3(2))).AddHours(Me.UTC_offset + StdTime)                Utility.SetLocalTime(dt)                Me.networkDateTime = Response                Me.successful = True                Exit Do            End If            Debug.Print("count = " & count.ToString)            If (count = 3) Then                If (ServerIndex <= 2) Then                    Me.TimeServer = Servers(ServerIndex)                    ServerIndex += 1 'point to next server                    Debug.Print("Trying a different server : " & Me.TimeServer)                    count = 0                Else                    Debug.Print("tried 3 servers something is wrong")                    Me.successful = false                    Exit Do                End If            End If            Thread.Sleep(5000) 'per NIST instructions do not query more than once every 4 sec        Loop    End Sub#Region "IDisposable Support"    Private disposedValue As Boolean ' To detect redundant calls    ' IDisposable    Protected Overridable Sub Dispose(disposing As Boolean)        If Not Me.disposedValue Then            If disposing Then                ' TODO: dispose managed state (managed objects).                Debug.Print("disposing Daytime Client ")                Debug.Print("GC: " & Debug.GC(True).ToString)            End If            ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.            ' TODO: set large fields to null.        End If        Me.disposedValue = True    End Sub    ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.    'Protected Overrides Sub Finalize()    '    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.    '    Dispose(False)    '    MyBase.Finalize()    'End Sub    ' This code added by Visual Basic to correctly implement the disposable pattern.    Public Sub Dispose() Implements IDisposable.Dispose        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.        Dispose(True)        GC.SuppressFinalize(Me)    End Sub#End RegionEnd Class

 



#9 fesp

fesp

    New Member

  • Members
  • Pip
  • 6 posts

Posted 06 March 2013 - 07:38 PM

Thanks Baxter, that works! I guess I'll be using this code from now on.

Wonder if the problem has anything to do with TCP vs UDP...



#10 baxter

baxter

    Advanced Member

  • Members
  • PipPipPip
  • 415 posts

Posted 06 March 2013 - 11:06 PM

Glad to help...

I think it does. I recall some issues with UDP. They may have gone away with the latest software.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.