Timestamps on ConnectPort X2

Since you can’t set the time on the ConnectPort X2, the following is a quick helper class I wrote (based on a Python Cookbook script). On instancing the class, it connects to a network time protocol (NTP) server for the current UTC time. Comments welcome, this is a quick hack …

[pre]

copyright 2008 EDM Studio Inc.

This program is free software: you can redistribute it and/or modify

it under the terms of the GNU General Public License as published by

the Free Software Foundation, either version 3 of the License, or

(at your option) any later version.

This program is distributed in the hope that it will be useful,

but WITHOUT ANY WARRANTY; without even the implied warranty of

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

GNU General Public License for more details.

You should have received a copy of the GNU General Public License

along with this program. If not, see .

import sys
from socket import socket, AF_INET, SOCK_DGRAM, error
from time import time, sleep, ctime
import struct

DEFAULT_NTP_SERVER = ‘pool.ntp.org

class TimeStamper(object):
“”“UTC time stamps for Digi Connect Port with external network connection”“”

TIME1970 = 2208988800L  # Thanks to F.Lundh

def __init__(self, ntpserver=DEFAULT_NTP_SERVER):

    # retrieve current UTC time from specified NTP server
    client = socket(AF_INET, SOCK_DGRAM)
    client.sendto('\x1b' + 47*'\0', (ntpserver, 123))

    data, address = client.recvfrom(1024)
    if data:
        self.utcboot = struct.unpack( '!12I', data )[10] - TimeStamper.TIME1970
        client.close()
    else:
        raise error, "Couldn't retrieve time from specified server"

    # what is this, uptime?
    self.digiboot = time()


def __repr__(self):
    """String representation of current UTC time"""
    return '%s' % ctime(self.time())


def time(self):
    """Current time in UTC"""

    elapsed = time() - self.digiboot
    return self.utcboot + elapsed

#----------------------------------------------------------------------
if name == “main”:

ts = TimeStamper()
print '%s' % ctime(ts.time())

sleep(5.5) # sleep seems to be integer amounts on digi device ...
print '%s' % ctime(ts.time())

[/pre]