/*--------------------------------------------------------------------------*/
Tbool CSystemBase::setSystemDate(const NTime::CDate& a_crDate, const Tbool a_cIsUTC/* = true */)
{ CALL
  SYSTEMTIME system_time;

  // Get system time in UTC or local time form.
  if (a_cIsUTC)
    GetSystemTime(&system_time);
  else
    GetLocalTime(&system_time);

  // Update time fields.
  system_time.wYear = a_crDate.getClearYears();
  system_time.wMonth = a_crDate.getClearMonths() + 1;
  system_time.wDay = a_crDate.getClearDays() + 1;

  // Set system time in UTC or local time form.
  BOOL result = (a_cIsUTC) ? SetSystemTime(&system_time) : SetLocalTime(&system_time);
  if (result == FALSE)
  {
    WARNING(STR("Cannot set system time in %x form (%u years, %u months, %u days).") COMMA ((a_cIsUTC ? STR("UTC") : STR("local time"))) COMMA a_crDate.getClearYears() COMMA a_crDate.getClearMonths() COMMA a_crDate.getClearDays());
    return false;
  }

  // Reset start process time stamp.
  CSystemBase::ms_ProcessTimeStamp = CSystemBase::getSystemTimeStamp();

  return true;
}
Example #2
0
bool SetTime::set_system_time(int year,int mon,int day,int hour,int minute,int second)//
{
    GetSystemTime(backups1);
    //qDebug()<<year<<" "<<mon<<" "<<day<<" "<<hour<<" "<<minute<<" "<<second;
    //qDebug()<<backups1->wMonth<<" "<<backups1->wDay<<" "<<backups1->wHour<<" "<<backups1->wMinute<<" "<<backups1->wSecond;
    //qDebug()<<QDateTime::currentDateTime();
    st->wYear=year;//year;
    st->wMonth=mon;//mon;
    st->wDay=day;//day;
    st->wHour=hour;//hour;
    st->wMinute=minute;//minute;
    st->wSecond=second;//second

    //qDebug()<<st->wYear<<" "<<st->wMonth<<" "<<st->wDay<<" "<<st->wHour<<" "<<st->wMinute<<" "<<st->wSecond;
    if(!SetSystemTime(st))
        return false;
    else{
        GetSystemTime(backups2);
        qDebug()<<"back2:"<<backups2->wMonth<<backups2->wDay<<backups2->wHour<<backups2->wMinute<<backups2->wSecond;
        setting->setValue("back1_year",backups1->wYear);
        setting->setValue("back1_mon",backups1->wMonth);
        setting->setValue("back1_day",backups1->wDay);
        setting->setValue("back1_hour",backups1->wHour);
        setting->setValue("back1_min",backups1->wMinute);
        setting->setValue("back1_second",backups1->wSecond);
        setting->setValue("back2_year",backups2->wYear);
        setting->setValue("back2_mon",backups2->wMonth);
        setting->setValue("back2_day",backups2->wDay);
        setting->setValue("back2_hour",backups2->wHour);
        setting->setValue("back2_min",backups2->wMinute);
        setting->setValue("back2_second",backups2->wSecond);
        return true;
    }
}
/*--------------------------------------------------------------------------*/
Tbool CSystemBase::setSystemTime(const NTime::CTime& a_crTime, const Tbool a_cIsUTC/* = true */)
{ CALL
  SYSTEMTIME system_time;

  // Get system time in UTC or local time form.
  if (a_cIsUTC)
    GetSystemTime(&system_time);
  else
    GetLocalTime(&system_time);

  // Update time fields.
  system_time.wHour = a_crTime.getClearHours();
  system_time.wMinute = a_crTime.getClearMinutes();
  system_time.wSecond = a_crTime.getClearSeconds();
  system_time.wMilliseconds = a_crTime.getClearMilliseconds();

  // Set system time in UTC or local time form.
  BOOL result = (a_cIsUTC) ? SetSystemTime(&system_time) : SetLocalTime(&system_time);
  if (result == FALSE)
  {
    WARNING(STR("Cannot set system time in %x form (%u hours, %u minutes, %u seconds, %u milliseconds).") COMMA ((a_cIsUTC ? STR("UTC") : STR("local time"))) COMMA a_crTime.getClearHours() COMMA a_crTime.getClearMinutes() COMMA a_crTime.getClearSeconds() COMMA a_crTime.getClearMilliseconds());
    return false;
  }

  // Reset start process time stamp.
  CSystemBase::ms_ProcessTimeStamp = CSystemBase::getSystemTimeStamp();

  return true;
}
Example #4
0
bool SetTime::recover_system_time()
{
    backups1->wYear=setting->getValue("back1_year",2013);
    backups1->wMonth=setting->getValue("back1_mon",1);
    backups1->wDay=setting->getValue("back1_day",1);
    backups1->wHour=setting->getValue("back1_hour",0);
    backups1->wMinute=setting->getValue("back1_min",0);
    backups1->wSecond=setting->getValue("back1_second",0);
    backups2->wYear=setting->getValue("back2_year",2013);
    backups2->wMonth=setting->getValue("back2_mon",1);
    backups2->wDay=setting->getValue("back2_day",1);
    backups2->wHour=setting->getValue("back2_hour",0);
    backups2->wMinute=setting->getValue("back2_min",0);
    backups2->wSecond=setting->getValue("back2_second",0);
    qDebug()<<"back1:"<<backups1->wMonth<<backups1->wDay<<backups1->wHour<<backups1->wMinute<<backups1->wSecond;
    qDebug()<<"back2:"<<backups2->wMonth<<backups2->wDay<<backups2->wHour<<backups2->wMinute<<backups2->wSecond;
    GetSystemTime(st);
    qDebug()<<"st:"<<st->wMonth<<st->wDay<<st->wHour<<st->wMinute<<st->wSecond;
    st=time_addition(time_subduction(st,backups2),backups1);
    qDebug()<<"st:"<<st->wMonth<<st->wDay<<st->wHour<<st->wMinute<<st->wSecond;
    if(!SetSystemTime(st))
        return false;
    else
        return true;
}
Example #5
0
void SetTimeFromTP(ULONG ulTime)	// 根据时间协议返回的时间设置系统时间
{
	// Windows文件时间是一个64位的值,它是从1601年1月1日中午12:00到现在的时间间隔,
	// 单位是1/1000 0000秒,即1000万分之1秒(100-nanosecond )
	FILETIME ft;
	SYSTEMTIME st;

	// 首先将基准时间(1900年1月1日0点0分0秒0毫秒)转化为Windows文件时间	
	st.wYear = 1900;
	st.wMonth = 1;
	st.wDay = 1;
	st.wHour = 0;
	st.wMinute = 0;
	st.wSecond = 0;
	st.wMilliseconds = 0;
	SystemTimeToFileTime(&st, &ft);

	// 然后将Time Protocol使用的基准时间加上以及逝去的时间,即ulTime
	LONGLONG *pLLong = (LONGLONG *)&ft;
	// 注意,文件时间单位是1/1000 0000秒,即1000万分之1秒(100-nanosecond )
	*pLLong += (LONGLONG)10000000 * ulTime; 

	// 再将时间转化回来,更新系统时间
	FileTimeToSystemTime(&ft, &st);	
	SetSystemTime(&st);
}
Example #6
0
File: Time.c Project: xpika/winhugs
static void hugsprim_SetSystemTime_1(HugsStackPtr hugs_root)
{
    HsPtr arg1;
    HsBool res1;
    arg1 = hugs->getPtr();
    res1 = SetSystemTime(arg1);
    hugs->putBool(res1);
    hugs->returnIO(hugs_root,1);
}
Example #7
0
Time::Time ()
{	
	if ( !m_Started ) {
		m_Started = true;			
		SetSystemTime ();				// Get base time from wall clock
		start_timing ( m_CurrTime );	// Start timing from base time
	}
	m_CurrTime = 0;
}
Example #8
0
RTDECL(int) RTTimeSet(PCRTTIMESPEC pTime)
{
    FILETIME    FileTime;
    SYSTEMTIME  SysTime;
    if (FileTimeToSystemTime(RTTimeSpecGetNtFileTime(pTime, &FileTime), &SysTime))
    {
        if (SetSystemTime(&SysTime))
            return VINF_SUCCESS;
    }
    return RTErrConvertFromWin32(GetLastError());
}
Example #9
0
BOOL SetNewTime(WORD hour, WORD minutes,WORD second)
{
    SYSTEMTIME st;

    GetSystemTime(&st);       // gets current time
    st.wHour = hour;          // adjusts hours 
    st.wMinute = minutes;     // and minutes
	st.wSecond = second;
    if (!SetSystemTime(&st))  // sets system time
        return FALSE;
    return TRUE;
}
Example #10
0
// Sets this date as the current system date and time
int32_t rfDate_SetToSystem(RF_Date* d)
{
    SYSTEMTIME st;
    RF_DATE_TO_SYSTEMTIME(d,st)

    if(SetSystemTime(&st) == 0)
    {
        RF_WIN32_GETSYSERROR(strBuff)
        LOG_ERROR("Setting the system time from an RF_Date in Windows failed with Windows Error(%lu):\n%s",RE_DATE_SET_SYSTEMTIME,i_ERROR_CODE,strBuff);
        LocalFree(strBuff);
        return RF_FAILURE;
    }
    return RF_SUCCESS;
}
Example #11
0
void reset_winnt_time(void) {

	/* restore the clock frequency back to its original value */
	if (!SetSystemTimeAdjustment(0, TRUE)) {
		msyslog(LOG_ERR, "Failed to reset clock state, SetSystemTimeAdjustment(): %m");
	}
        /************ Added back in 2003-01-26 *****************/
	/* read the current system time, and write it back to
           force CMOS update: */
	{
		SYSTEMTIME st;
		GetSystemTime(&st);
		SetSystemTime(&st);
	}
}
Example #12
0
int settimeofday (struct timeval *tv,struct timezone *tz) 
	{
#if defined(_WIN32)
   SYSTEMTIME bigTime;
   struct tm* myCUT;
//   OSVERSIONINFO myVInfo;

   /* in this case, we want to STAY in universal time anyhow */
   myCUT = gmtime(&(tv->tv_sec));
   if (myCUT == NULL)
	   return 0;

   bigTime.wYear = 1900+myCUT->tm_year;
   bigTime.wMonth = 1+myCUT->tm_mon;
   /* wDayOfWeek is supposedly ignored for SetSystemTime, but we have it.. */
   bigTime.wDayOfWeek = myCUT->tm_wday;
   bigTime.wDay = myCUT->tm_mday;
   bigTime.wHour = myCUT->tm_hour;
   bigTime.wMinute = myCUT->tm_min;
   bigTime.wSecond = myCUT->tm_sec;
   bigTime.wMilliseconds = 0;
   /* under NT, SetSystemTime requires privileges */
   /* myVINfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
   GetVersionEx(&myVInfo);
   if (myVInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) */
   if (!SetSystemTime(&bigTime))
	   return 0;
#else
   struct _dostime_t dostime;      
   struct _dosdate_t dosdate;
   struct tm *newtime;

   newtime = localtime((time_t *)&(tv->tv_sec));
   dostime.hour = newtime->tm_hour;
   dostime.minute = newtime->tm_min;   
   dostime.second = newtime->tm_sec;
   dostime.hsecond = 0;
   dosdate.day = newtime->tm_mday;
   dosdate.month = 1+newtime->tm_mon; 		/* burp! Microsft really sucks */
   dosdate.year = 1900+newtime->tm_year;	/* burp! Microsoft sucks again... */
   dosdate.dayofweek = newtime->tm_wday;
	
   if (_dos_setdate(&dosdate) == 0 && _dos_settime(&dostime) == 0)
   	return 0;
#endif
   	
	return 1;    
	}       
Example #13
0
File: timesync.c Project: PADL/krb5
int
settimeofday(
    struct timeval *tv,
    struct timezone *tz
    )
{
    SYSTEMTIME systime;
    struct tm *newtime;

    newtime = gmtime((time_t *)&(tv->tv_sec));
    systime.wYear = 1900+newtime->tm_year;
    systime.wMonth = 1+newtime->tm_mon;
    systime.wDay = newtime->tm_mday;
    systime.wHour = newtime->tm_hour;
    systime.wMinute = newtime->tm_min;
    systime.wSecond = newtime->tm_sec;
    systime.wMilliseconds = 0;
    return SetSystemTime(&systime);
}
Example #14
0
BOOL CSNTPClient::SetClientTime( const CNtpTime & NewTime )
{
	BOOL bSuccess	= FALSE;
// AR 22-07-2000
#ifndef _WIN32_WCE
	if( EnableSetTimePrivilege() )
	{
#endif	// _WIN32_WCE
		SYSTEMTIME st	= NewTime;
		bSuccess	= SetSystemTime( &st );
		if( !bSuccess )
			TRACE( _T( "Failed in call to set the system time\n" ) );
// AR 22-07-2000
#ifndef _WIN32_WCE
	}
	RevertSetTimePrivilege();
#endif	// _WIN32_WCE
	return bSuccess;
}
Example #15
0
INT32_T set_systime_sec(const TIME_T* tm_sec_ptr)
{
#ifdef LINUX_OS
    struct timespec tp;

    tp.tv_sec = *tm_sec_ptr;
    tp.tv_nsec = 0;
    if (clock_settime(CLOCK_REALTIME, &tp) != 0)
    {
        return AII_ERROR;
    }
#endif

#ifdef VXWORKS_OS
    struct timespec tp;

    tp.tv_sec = *tm_sec_ptr;
    tp.tv_nsec = 0;
    if (clock_settime(CLOCK_REALTIME, &tp) != OK)
    {
        return AII_ERROR;
    }
#endif
#ifdef WINDOWS_OS_32
    FILETIME WinFileTime;
    SYSTEMTIME WinSysTime;
    TIME_T hund_nano_num;
    
    hund_nano_num = *tm_sec_ptr * 10000000;
    memcpy(&WinFileTime, &hund_nano_num, min(sizeof(FILETIME), sizeof(TIME_T)));
    if (FileTimeToSystemTime(&WinFileTime, &WinSysTime) == 0)
    {
        return AII_ERROR;
    }

    if (SetSystemTime(&WinSysTime) == 0)
    {
        return AII_ERROR;
    }
    
#endif
}
/*--------------------------------------------------------------------------*/
Tbool CSystemBase::setSystemDateTime(const NTime::CDateTime& a_crDateTime, const Tbool a_cIsUTC/* = true */)
{ CALL
  SYSTEMTIME system_time;

  // Get system time in UTC or local time form.
  if (a_cIsUTC)
    GetSystemTime(&system_time);
  else
    GetLocalTime(&system_time);

  // Update time fields.
  system_time.wYear = a_crDateTime.getDate().getClearYears();
  system_time.wMonth = a_crDateTime.getDate().getClearMonths() + 1;
  system_time.wDay = a_crDateTime.getDate().getClearDays() + 1;
  system_time.wHour = a_crDateTime.getTime().getClearHours();
  system_time.wMinute = a_crDateTime.getTime().getClearMinutes();
  system_time.wSecond = a_crDateTime.getTime().getClearSeconds();
  system_time.wMilliseconds = a_crDateTime.getTime().getClearMilliseconds();

  // Set system time in UTC or local time form.
  //
  // The system uses UTC internally. Therefore, when  you  call  SetLocalTime,
  // the system  uses  the  current  time  zone  information  to  perform  the
  // conversion, including the daylight saving time  setting.  Note  that  the
  // system uses the daylight saving time setting of the current time, not the
  // new time you are setting. Therefore, to ensure the correct  result,  call
  // SetLocalTime a second time, now that  the  first  call  has  updated  the
  // daylight saving time setting.
  //
  BOOL result = (a_cIsUTC) ? SetSystemTime(&system_time) : (SetLocalTime(&system_time) && SetLocalTime(&system_time));
  if (result == FALSE)
  {
    WARNING(STR("Cannot set system time in %x form (%u years, %u months, %u days, %u hours, %u minutes, %u seconds, %u milliseconds).") COMMA ((a_cIsUTC ? STR("UTC") : STR("local time"))) COMMA a_crDateTime.getDate().getClearYears() COMMA a_crDateTime.getDate().getClearMonths() COMMA a_crDateTime.getDate().getClearDays() COMMA a_crDateTime.getTime().getClearHours() COMMA a_crDateTime.getTime().getClearMinutes() COMMA a_crDateTime.getTime().getClearSeconds() COMMA a_crDateTime.getTime().getClearMilliseconds());
    return false;
  }

  // Reset start process time stamp.
  CSystemBase::ms_ProcessTimeStamp = CSystemBase::getSystemTimeStamp();

  return true;
}
void SetSystemTimeDialog::onSetSystemTime()
{
    qDebug()<<"设置系统时间";
   SYSTEMTIME st;
   GetSystemTime(&st);
  // qDebug()<<st.wYear<<st.wMonth<<st.wDay<<st.wHour<<st.wMinute<<st.wSecond;
   QDateTime tempdatetime;
   tempdatetime.setDate(ui->dateEdit->date());
   tempdatetime.setTime(ui->timeEdit->time());
   QDateTime datetime = tempdatetime.addSecs(-8*60*60);
   qDebug()<<"datetime"<<datetime;
   st.wYear = datetime.date().year();
   st.wMonth= datetime.date().month();
   st.wDay = datetime.date().day();
   st.wHour = datetime.time().hour();
   st.wMinute = datetime.time().minute();
   st.wSecond = datetime.time().second();
  // qDebug()<<st.wYear<<st.wMonth<<st.wDay<<st.wHour<<st.wMinute<<st.wSecond;
   qDebug()<<"SetSystemTime(&st)"<<SetSystemTime(&st);
   qDebug()<<datetime.date().year()<<datetime.date().month()<<datetime.date().day()<<datetime.time().hour()<<datetime.time().minute()<<datetime.time().second();
   this->accept();
}
Example #18
0
int
ntp_set_tod(
	struct timespec *tp
	)
{
	SYSTEMTIME st;
	union {
		FILETIME ft;
		ULONGLONG ull;
	} t;

	t.ull = FILETIME_1970 +
		(ULONGLONG)tv->tv_sec * 10 * 1000 * 1000 +
		(ULONGLONG)tv->tv_nsec / 100;

	if (!FileTimeToSystemTime(&t.ft, &st) || !SetSystemTime(&st)) {
		msyslog(LOG_ERR, "SetSystemTime failed: %m");
		return -1;
	}

	return 0;
}
Example #19
0
/*---------------------------------------------------------------------
	時計を合わせる
---------------------------------------------------------------------*/
void adjust_time(double offset) {
#if defined(_OS9000)
	time_t utime;

	utime = time(NULL);
	utime += offset / 1000;

	_os_setime(utime);
#else
	SYSTEMTIME st;
	FILETIME ft9;
	char bufNow[96];

	strcpy(bufNow, strltime());

	GetSystemTime(&st);
	SystemTimeToFileTime(&st, &ft9);
	*(__int64*)&ft9 += offset * FT_MSEC;
	FileTimeToSystemTime(&ft9, &st);
	SetSystemTime(&st);

	KLogWriteE("adjust: %s -> %s", bufNow, strltime());
#endif
}
Example #20
0
/*---------------------------------------------------
	set system time to received data
---------------------------------------------------*/
void SynchronizeSystemTime(DWORD seconds, DWORD fractions)
{
	FILETIME ft, ftold;
	SYSTEMTIME st, st_dif, lt;
	char s[1024];
	DWORD sr_time;
	DWORDLONG dif;
	BOOL b;

	// timeout ?
	sr_time = GetTickCount() - dwTickCountOnSend;
	if(sr_time >= (DWORD)nTimeout)
	{
		wsprintf(s, "timeout (%04d)", sr_time);
		Log(s); return;
	}

	// current time
	GetSystemTimeAsFileTime(&ftold);

	// NTP data -> FILETIME
	*(DWORDLONG*)&ft =
		// seconds from 1900/01/01 �� 100 nano-seconds from 1601/01/01
		M32x32to64(seconds, 10000000) + 94354848000000000i64;

	// difference
	if(nMinuteDif > 0)
		*(DWORDLONG*)&ft += M32x32to64(nMinuteDif * 60, 10000000);
	else if(nMinuteDif < 0)
		*(DWORDLONG*)&ft -= M32x32to64(-nMinuteDif * 60, 10000000);

	// set system time
	b = FileTimeToSystemTime(&ft, &st);
	if(b)
	{
		/* fractions: (2 ** 32 / 1000) */
		st.wMilliseconds = (WORD)(fractions / 4294967);
		b = SetSystemTime(&st);
	}
	if(!b)
	{
		Log("failed to set time"); return;
	}

	GetLocalTime(&lt);
	nLastDay = lt.wDay;
	SetMyRegLong("SNTP", "LastDay", nLastDay);

	SystemTimeToFileTime(&st, &ft);
	// delayed or advanced
	b = (*(DWORDLONG*)&ft > *(DWORDLONG*)&ftold);
	// get difference
	if(b) dif = *(DWORDLONG*)&ft - *(DWORDLONG*)&ftold;
	else  dif = *(DWORDLONG*)&ftold - *(DWORDLONG*)&ft;
	FileTimeToSystemTime((FILETIME*)&dif, &st_dif);

	// save log
	strcpy(s, "synchronized ");
	if(st_dif.wYear == 1601 && st_dif.wMonth == 1 &&
		st_dif.wDay == 1 && st_dif.wHour == 0)
	{
		strcat(s, b?"+":"-");
		wsprintf(s + strlen(s), "%02d:%02d.%03d ",
			st_dif.wMinute, st_dif.wSecond, st_dif.wMilliseconds);
	}
	wsprintf(s + strlen(s), "(%04d)", sr_time);
	Log(s);

	GetMyRegStr("SNTP", "Sound", s, 1024, "");
	PlayFile(g_hwndMain, s, 0);
}
Example #21
0
BOOL MyConnect(HWND hDlg)
{
    WSADATA wsaData;
    SOCKADDR_IN myaddr, serveraddr;
    int nRtn;
    SOCKET s;
    HOSTENT *lpHostent;
    unsigned int addr;
    MYPACKET packet;
    int fromlen;
    time_t server_tm;
    struct tm *lpgtime;
    SYSTEMTIME st;

    // �@ WinSockを初期化
    nRtn = WSAStartup(MAKEWORD(1, 1), &wsaData);
    if (nRtn != 0) {
        MessageBox(hDlg, 
            "Winsock初期化失敗です", 
            szAppName, 
            MB_OK | MB_ICONEXCLAMATION);
        return FALSE;
    }

    // �A ソケットをオープン
    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s == INVALID_SOCKET) {
        MessageBox(hDlg, "socket失敗", 
            szAppName, MB_OK | MB_ICONEXCLAMATION);
        WSACleanup();
        return FALSE;
    }

    // �B SOCKADDR_IN構造体のメンバをセット
    memset(&myaddr, 0, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(port);
    myaddr.sin_addr.s_addr = INADDR_ANY;

    // �C ソケットに名前を付ける
    nRtn = bind(s, (SOCKADDR *)&myaddr, sizeof(myaddr));
    if (nRtn != 0) {
        MessageBox(hDlg, "bind Error", 
            szAppName, MB_OK | MB_ICONEXCLAMATION);
        closesocket(s);
        WSACleanup();
        return FALSE;
    }

    // �D ホスト情報を取得
    lpHostent = gethostbyname(szServer);
    if (lpHostent == NULL) {
        addr = inet_addr(szServer);
        lpHostent = gethostbyaddr((char *)&addr, 4, AF_INET);
        if (lpHostent == NULL) {
            MessageBox(hDlg, "ホストを特定できません",
                szAppName, MB_OK | MB_ICONEXCLAMATION);
            closesocket(s);
            WSACleanup();
            return FALSE;
        }
    }

    // �E SOCKADDR_IN構造体のメンバにサーバ情報をセット
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(sport);
    serveraddr.sin_addr.s_addr = 
        *((unsigned long *)lpHostent->h_addr);

    // �F Control_Wordメンバに0x0B000000をセット
    memset(&packet, 0, sizeof(MYPACKET));
    packet.Control_Word = htonl(0x0B000000);

    // �G パケットを送信
    nRtn = sendto(s, (const char *)&packet, sizeof(MYPACKET), 
        0, (SOCKADDR *)&serveraddr,sizeof(serveraddr));
    if (nRtn == SOCKET_ERROR) {
        MessageBox(hDlg, "パケット送信エラーです", szAppName,
            MB_OK | MB_ICONEXCLAMATION);
        closesocket(s);
        WSACleanup();
        return FALSE;
    }

    // �H サーバからの返事を待機
    fromlen = sizeof(SOCKADDR_IN);
    nRtn = recvfrom(s, (char *)&packet, sizeof(MYPACKET), 
        0, (SOCKADDR *)&serveraddr, &fromlen);
    if (nRtn == SOCKET_ERROR) {
        MessageBox(hDlg, "受信エラーです", 
            szAppName, MB_OK | MB_ICONEXCLAMATION);
        closesocket(s);
        WSACleanup();
        return FALSE;
    }

    // サーバから返された時刻を変数に保管
    server_tm =
        ntohl(packet.transmit_timestamp_seconds) - 2208988800;
    // サーバからの時刻をtm構造体に変換
    lpgtime = gmtime(&server_tm);

    // SYSTEMTIME構造体のメンバをセット
    st.wYear = lpgtime->tm_year + 1900;
    st.wMonth = lpgtime->tm_mon + 1;
    st.wDay = lpgtime->tm_mday;
    st.wHour = lpgtime->tm_hour;
    st.wMinute = lpgtime->tm_min;
    st.wSecond = lpgtime->tm_sec;
    st.wMilliseconds = 0;

    // コンピュータの時刻を、サーバから取得した時刻に合わせる
    if (SetSystemTime(&st) != 0) {
        MessageBox(hDlg, "システム時間をサーバ時間に合わせました",
            szAppName, MB_OK);
    }

    closesocket(s);          // ソケットをクローズ
    WSACleanup();            // WinSockのリソースを解放

    return TRUE;
}
//---------------------------------------------------------------------------
void GPSDialog::gpsDataAvailable(void)
{
    if(gps->isValid()) {
        if(ui->setTimeCb->isChecked()) {
            ui->setTimeCb->setChecked(false);

            bool rc = false;

#ifdef Q_OS_WIN

            SYSTEMTIME st;
            QDateTime  rx_dt = gps->getrxtime(true);
            QDate rx_date    = rx_dt.date();
            QTime rx_time    = rx_dt.time();

            st.wYear         = rx_date.year();
            st.wMonth        = rx_date.month();
            st.wDayOfWeek    = rx_date.dayOfWeek(); // ignored
            st.wDay          = rx_date.day();

            st.wHour         = rx_time.hour();
            st.wMinute       = rx_time.minute();
            st.wSecond       = rx_time.second();
            st.wMilliseconds = rx_time.msec();

            rc = SetSystemTime(&st);

#else // unix

            const time_t tt = gps->rxtime_t();

            if(stime(&tt) == 0)
                rc = true;

#endif // #ifdef Q_OS_WIN

#if defined(DEBUG_GPS)
            if(rc == false)
                qDebug("** Failed to set system time [%s:%d]\n", __FILE__, __LINE__);
            else
                qDebug("** New system time set to GPS time [%s:%d]\n", __FILE__, __LINE__);
#endif

        }

        if(ui->setQTHCB->isChecked()) {
#if 0 // fixme
           ui->setQTHCB->setChecked(false);

           TStation *qth = mw->getQTH();

           qth->lat(gps->latitude_d());
           qth->lon(gps->longitude_d());
           qth->alt(gps->altitude_d());

           mw->updateQTH();
#endif
        }

    } // if(gps->isValid())

    ui->qualityLabel->setText(gps->quality());
    ui->timeLabel->setText(gps->time(!ui->utcTimeCb->isChecked()));
    ui->diffLabel->setText(gps->timediff());
    ui->satsLabel->setText(gps->sats_in_view());
    ui->lonLabel->setText(gps->longitude(ui->dmsCb->isChecked()));
    ui->altLabel->setText(gps->altitude());
    ui->latLabel->setText(gps->latitude(ui->dmsCb->isChecked()));
    ui->speedLabel->setText(gps->speedStr());
    ui->courceLabel->setText(gps->cource());
    ui->geoHeightLabel->setText(gps->mean_sea_level());
    ui->magvarLabel->setText(gps->magnetic());


}
Example #23
0
int main(int argc, char *argv[])
{
  CURL    *curl;
  conf_t  conf[1];
  int     OptionIndex;
  struct  tm *lt;
  struct  tm *gmt;
  time_t  tt;
  time_t  tt_local;
  time_t  tt_gmt;
  double  tzonediffFloat;
  int     tzonediffWord;
  char    timeBuf[61];
  char    tzoneBuf[16];
  int     RetValue;

  OptionIndex     = 0;
  ShowAllHeader   = 0;    /* Do not show HTTP Header */
  AutoSyncTime    = 0;    /* Do not synchronise computer clock */
  RetValue        = 0;    /* Successful Exit */
  conf_init(conf);

  if (argc > 1) {
    while (OptionIndex < argc) {
      if (strncmp(argv[OptionIndex], "--server=", 9) == 0)
        snprintf(conf->timeserver, MAX_STRING, "%s", &argv[OptionIndex][9]);

      if (strcmp(argv[OptionIndex], "--showall") == 0)
        ShowAllHeader = 1;

      if (strcmp(argv[OptionIndex], "--synctime") == 0)
        AutoSyncTime = 1;

      if (strncmp(argv[OptionIndex], "--proxy-user="******"%s", &argv[OptionIndex][13]);

      if (strncmp(argv[OptionIndex], "--proxy=", 8) == 0)
        snprintf(conf->http_proxy, MAX_STRING, "%s", &argv[OptionIndex][8]);

      if ((strcmp(argv[OptionIndex], "--help") == 0) ||
          (strcmp(argv[OptionIndex], "/?") == 0)) {
        showUsage();
        return 0;
      }
      OptionIndex++;
    }
  }

  if (*conf->timeserver == 0)     /* Use default server for time information */
    snprintf(conf->timeserver, MAX_STRING, "%s", DefaultTimeServer[0]);

  /* Init CURL before usage */
  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();
  if (curl) {
    SyncTime_CURL_Init(curl, conf->http_proxy, conf->proxy_user);

    /* Calculating time diff between GMT and localtime */
    tt       = time(0);
    lt       = localtime(&tt);
    tt_local = mktime(lt);
    gmt      = gmtime(&tt);
    tt_gmt   = mktime(gmt);
    tzonediffFloat = difftime(tt_local, tt_gmt);
    tzonediffWord  = (int)(tzonediffFloat/3600.0);

    if ((double)(tzonediffWord * 3600) == tzonediffFloat)
      snprintf(tzoneBuf, 15, "%+03d'00'", tzonediffWord);
    else
      snprintf(tzoneBuf, 15, "%+03d'30'", tzonediffWord);

    /* Get current system time and local time */
    GetSystemTime(&SYSTime);
    GetLocalTime(&LOCALTime);
    snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
             DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
             MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
             LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
             LOCALTime.wMilliseconds);

    fprintf(stderr, "Fetch: %s\n\n", conf->timeserver);
    fprintf(stderr, "Before HTTP. Date: %s%s\n\n", timeBuf, tzoneBuf);

    /* HTTP HEAD command to the Webserver */
    SyncTime_CURL_Fetch(curl, conf->timeserver, "index.htm",
                        HTTP_COMMAND_HEAD);

    GetLocalTime(&LOCALTime);
    snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
             DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
             MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
             LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
             LOCALTime.wMilliseconds);
    fprintf(stderr, "\nAfter  HTTP. Date: %s%s\n", timeBuf, tzoneBuf);

    if (AutoSyncTime == 3) {
      /* Synchronising computer clock */
      if (!SetSystemTime(&SYSTime)) {  /* Set system time */
        fprintf(stderr, "ERROR: Unable to set system time.\n");
        RetValue = 1;
      }
      else {
        /* Successfully re-adjusted computer clock */
        GetLocalTime(&LOCALTime);
        snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
                 DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
                 MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
                 LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
                 LOCALTime.wMilliseconds);
        fprintf(stderr, "\nNew System's Date: %s%s\n", timeBuf, tzoneBuf);
      }
    }

    /* Cleanup before exit */
    conf_init(conf);
    curl_easy_cleanup(curl);
  }
  return RetValue;
}
Example #24
0
/** 
 * @brief  Function to set time to the system or specific
 * hardware PTP timer (based on system capabilities
 * and architecture) base on ptpv2d system
 * internal time format
 *
 * @param[in]  time        Pointer to TimeInternal structure with time in seconds and nanoseconds TAI time
 * @param[in]  utc_offset Integer16 value of number of UTC leap seconds since January 1, 1970
 */
void setTime(TimeInternal *time, Integer16 utc_offset)
{
#ifdef CONFIG_MPC831X
  mpc831x_set_curr_time(time);
#elif defined(__WINDOWS__)
    unsigned long long U64WindowsTime;
    FILETIME           WindowsUTCTime;
    SYSTEMTIME         WindowsSystemTime;


    U64WindowsTime = (unsigned long long) time->seconds;
    
    // Change epoch in seconds from January 1, 1970
    // to Windows January 1, 1901

    U64WindowsTime += 11644473600ULL;

    // Change seconds from January 1, 1970 TAI time to UTC time
    
    U64WindowsTime  -= (unsigned long long) utc_offset;

    // Convert seconds to 100 ns increments since January 1, 1601

    U64WindowsTime *= 10000000ULL;

    // Add in nanoseconds converted to 100 ns increments

    U64WindowsTime += (unsigned long long)(time->nanoseconds / 100U);

    // Convert unsigned long long 64 bit variable to
    // File time structure time

    WindowsUTCTime.dwLowDateTime  = (unsigned long)(U64WindowsTime & (unsigned long long)0xFFFFFFFF);
    WindowsUTCTime.dwHighDateTime = (unsigned long)(U64WindowsTime >> 32);

    // Convert Windows UTC "file time" to Windows UTC "system time"

    FileTimeToSystemTime(&WindowsUTCTime, &WindowsSystemTime);

    // Now finally we can set the windows system time
    SetSystemTime(&WindowsSystemTime); // Sets the current system time

#else
  // Linux time type, simply need to convert nanoseconds
  // to microseconds, subtract the TAI time UTC offset
  // (leap seconds since January 1, 1970) and set
  // the time
  struct timeval tv;
  
  tv.tv_sec  = time->seconds;
  tv.tv_usec = time->nanoseconds/1000;

  /* PTP uses TAI, gettime of day is UTC, so adjust by subtracting 
   * UTC offset from TAI to adjust for leap seconds
   */
  tv.tv_sec  -= utc_offset;
  settimeofday(&tv, 0);
#endif  

  NOTIFY("setTime: resetting clock to UTC %ds %dns\n", time->seconds, time->nanoseconds);
}
Example #25
0
File: time.c Project: DeadZen/qse
int qse_settime (const qse_ntime_t* t)
{
#if defined(_WIN32)
	FILETIME ft;
	SYSTEMTIME st;

	/**((qse_int64_t*)&ft) = ((t + EPOCH_DIFF_MSECS) * (10 * 1000));*/
	*((qse_int64_t*)&ft) = 
		(QSE_SEC_TO_NSEC(t->sec + EPOCH_DIFF_SECS) / 100)  + (t->nsec / 100);
	if (FileTimeToSystemTime (&ft, &st) == FALSE) return -1;
	if (SetSystemTime(&st) == FALSE) return -1;
	return 0;

#elif defined(__OS2__)

	APIRET rc;
	DATETIME dt;
	qse_btime_t bt;

	if (qse_localtime (t, &bt) <= -1) return -1;

	QSE_MEMSET (&dt, 0, QSE_SIZEOF(dt));
	dt.year = bt.year + QSE_BTIME_YEAR_BASE;
	dt.month = bt.mon + 1;
	dt.day = bt.mday;
	dt.hours = bt.hour;
	dt.minutes = bt.min;
	dt.seconds = bt.sec;
	dt.hundredths = QSE_NSEC_TO_MSEC(t->nsec) / 10;

	rc = DosSetDateTime (&dt);
	return (rc != NO_ERROR)? -1: 0;

#elif defined(__DOS__)

	struct dostime_t dt;
	struct dosdate_t dd;
	qse_btime_t bt;

	if (qse_localtime (t, &bt) <= -1) return -1;

	dd.year = bt.year + QSE_BTIME_YEAR_BASE;
	dd.month = bt.mon + 1;
	dd.day = bt.mday;
	dt.hour = bt.hour;
	dt.minute = bt.min;
	dt.second = bt.sec;
	dt.hsecond = QSE_NSEC_TO_MSEC(t->nsec) / 10;

	if (_dos_settime (&dt) != 0) return -1;
	if (_dos_setdate (&dd) != 0) return -1;

	return 0;

#elif defined(HAVE_SETTIMEOFDAY)
	struct timeval tv;
	int n;

	tv.tv_sec = t->sec;
	tv.tv_usec = QSE_NSEC_TO_USEC(t->nsec);

/*
#if defined(CLOCK_REALTIME) && defined(HAVE_CLOCK_SETTIME)
	{
		int r = clock_settime (CLOCK_REALTIME, ts);
		if (r == 0 || errno == EPERM) return r;
	}
#elif defined(HAVE_STIME)
	return stime (&ts->tv_sec);
#else
*/
	n = QSE_SETTIMEOFDAY (&tv, QSE_NULL);
	if (n == -1) return -1;
	return 0;

#else

	time_t tv;
	tv = t->sec;
	return (QSE_STIME (&tv) == -1)? -1: 0;
#endif
}
Example #26
0
/*---------------------------------------------------
  set system time to received data
---------------------------------------------------*/
void SynchronizeSystemTime(HWND hwndSNTP, struct NTP_Packet *pnp)
{
	HOSTTIME ht, htofs, htdelay;
	SYSTEMTIME st, st_dif, st_delay;
	DWORD sr_time;
	char s[MAX_PATH];
	BOOL b;
	
	// timeout ?
	sr_time = m_dwTickCountOnRecv - m_dwTickCountOnSend;
	if(sr_time >= (DWORD)m_nTimeOut)
	{
		wsprintf(s, "timeout (%04d)", sr_time);
		Log(hwndSNTP, s);
		PostMessage(hwndSNTP, SNTPM_ERROR, 0, 0);
		return;
	}
	
	GetLocalClockOffset(pnp, &htofs, &htdelay);
	
	// difference
	htofs += Int32x32To64(m_nMinuteDif * 60, HOSTTIME_TICK);
	
	// current time
	GetRealSystemTimeAsFileTime((FILETIME*)&ht);
	ht += htofs;
	
	// set system time
	b = FileTimeToSystemTime((FILETIME*)&ht, &st);
	if(b)
		b = SetSystemTime(&st);
	if(!b)
	{
		if(GetLastError() == ERROR_PRIVILEGE_NOT_HELD)
			Log(hwndSNTP, "failed to set time (administrator privilege required)");
		else
			Log(hwndSNTP, "failed to set time");
		PostMessage(hwndSNTP, SNTPM_ERROR, 0, 0);
		return;
	}
	
	// delayed or advanced
	b = (htofs >= 0);
	if(!b)
		htofs = -htofs;
	FileTimeToSystemTime((FILETIME*)&htofs, &st_dif);
	
	// save log
	strcpy(s, "synchronized ");
	if(st_dif.wYear == 1601 && st_dif.wMonth == 1 &&
		st_dif.wDay == 1 && st_dif.wHour == 0)
	{
		strcat(s, b?"+":"-");
		wsprintf(s + strlen(s), "%02d:%02d.%03d ",
			st_dif.wMinute, st_dif.wSecond, st_dif.wMilliseconds);
	}
	FileTimeToSystemTime((FILETIME*)&htdelay, &st_delay);
	// "(Send-Receive time) [Network delay]"
	wsprintf(s + strlen(s), "(%04d) [%04d]", sr_time,
			st_delay.wSecond * 1000 + st_delay.wMilliseconds);
	
	Log(hwndSNTP, s);
	
	if(m_soundfile[0])
	{
		HWND hwndTClockMain = GetTClockMainWindow();
		
		if(hwndTClockMain)
			SendStringToOther(hwndTClockMain, hwndSNTP,
				m_soundfile, COPYDATA_SOUND);
	}
	
	PostMessage(hwndSNTP, SNTPM_SUCCESS, 0, 0);
}
Example #27
0
void rlTime::setLocalTime()
{
#ifdef RLUNIX
  struct timeval tv;
  struct tm t;

  t.tm_mday  = day;
  t.tm_mon   = month - 1;
  t.tm_year  = year - 1900;
  t.tm_hour  = hour;
  t.tm_min   = minute;
  t.tm_sec   = second;
  tv.tv_sec  = mktime(&t);
  tv.tv_usec = 1000 * millisecond;
  settimeofday(&tv,NULL);
#endif

#ifdef __VMS
  VAX_BIN_TIME vbt;
  struct dsc$descriptor_s  d_time;
  char smonth[12][4],buf[64];

  // Initialize month array
  memset (smonth   , 0, sizeof(smonth));
  memcpy (smonth  [0], "JAN", 3);
  memcpy (smonth  [1], "FEB", 3);
  memcpy (smonth  [2], "MAR", 3);
  memcpy (smonth  [3], "APR", 3);
  memcpy (smonth  [4], "MAY", 3);
  memcpy (smonth  [5], "JUN", 3);
  memcpy (smonth  [6], "JUL", 3);
  memcpy (smonth  [7], "AUG", 3);
  memcpy (smonth  [8], "SEP", 3);
  memcpy (smonth  [9], "OCT", 3);
  memcpy (smonth [10], "NOV", 3);
  memcpy (smonth [11], "DEC", 3);
  // Create time buffer
  sprintf(buf, "%02d-%3.3s-%04d %02d:%02d:%02d.%02d",
                day,
                smonth[month-1],
                year,
                hour,
                minute,
                second,
                millisecond / 10);

  // Fill string descriptor
  d_time.dsc$w_length  = strlen(buf);
  d_time.dsc$b_dtype   = DSC$K_DTYPE_T;
  d_time.dsc$b_class   = DSC$K_CLASS_S;
  d_time.dsc$a_pointer = buf;
  // Convert time buf to VAX bin time
  sys$bintim(&d_time, &vbt);
  // Set the system time
  sys$setime(&vbt);
#endif

#ifdef RLWIN32
  SYSTEMTIME st;
  st.wDay          = day;
  st.wMonth        = month;
  st.wYear         = year;
  st.wHour         = hour;
  st.wMinute       = minute;
  st.wSecond       = second;
  st.wMilliseconds = millisecond;
  SetSystemTime(&st);
#endif
}