summaryrefslogtreecommitdiff
path: root/noncore/settings/netsystemtime/ntp.cpp
blob: 52fc6be8e71592a283823a5082320dc3eddf07eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#include "ntp.h"
#include <qpushbutton.h>
#include <qregexp.h>
#include <qtable.h>
#include <qlabel.h>
#include <qsocket.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qmessagebox.h>
#include <qmultilineedit.h>
#include <opie/oprocess.h>
#include <qpe/config.h>
#include <qpe/global.h>
#include <qpe/timeconversion.h>
#include <qpe/tzselect.h>
#include <qpe/timestring.h>
#include <qpe/qpedialog.h>
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>


Ntp::Ntp( QWidget* parent,  const char* name, WFlags fl )
    : SetDateTime( parent, name, fl )
{
	Config cfg("ntp",Config::User);
  cfg.setGroup("settings");
// 	_maxOffset = cfg.readNumEntry("maxOffset",5);
//  _minLookupDiff = cfg.readNumEntry("minLookupDiff",10);
	SpinBoxMinLookupDelay->setValue( cfg.readNumEntry("minLookupDiff",60) );
	SpinBoxNtpDelay->setValue( cfg.readNumEntry("ntpRefreshFreq",60) );
  LineEditNtpSrv->setText( cfg.readEntry("ntpServer", tr("time.fu-berlin.de")) );
 	ntpProcess = new OProcess( );

  QSocket *ntpSock = new QSocket( this );
  ntpSock->connectToHost( LineEditNtpSrv->text() ,123);
  connect( ntpSock, SIGNAL( error(int) ),
  					SLOT(slotCheckNtp(int)) );

  connect ( ntpProcess, SIGNAL(receivedStdout(OProcess*,char*,int)),
  					this, SLOT(getNtpOutput(OProcess*,char*,int)));
  connect ( ntpProcess, SIGNAL(processExited(OProcess*)),
  					this, SLOT(ntpFinished(OProcess*)));
  connect(runNtp, SIGNAL(clicked()), this, SLOT(slotRunNtp()));
  connect(PushButtonPredict, SIGNAL(clicked()), this, SLOT(preditctTime()));
  slotCheckNtp(-1);
//  slotRunNtp();
  readLookups();
}

Ntp::~Ntp()
{
	Config cfg("ntp",Config::User);
  cfg.setGroup("settings");
  cfg.writeEntry("ntpServer", LineEditNtpSrv->text());
  cfg.writeEntry( "minLookupDiff", SpinBoxMinLookupDelay->value() );
 	cfg.writeEntry( "ntpRefreshFreq", SpinBoxNtpDelay->value() );
}


void Ntp::slotRunNtp()
{
	Config cfg("ntp",Config::User);
  cfg.setGroup("lookups");
  int lookupDiff = TimeConversion::toUTC(QDateTime::currentDateTime()) - cfg.readNumEntry("time",0);

  if ( lookupDiff < SpinBoxNtpDelay->value()*60 )
  {
  	switch (
   	 QMessageBox::warning(this, tr("Run ntp?"),
     tr("You asked for a delay of ")+SpinBoxNtpDelay->text()+tr(" minutes, but only ")+
     QString::number(lookupDiff%60)+tr(" minutes elapsed since last loopup.")+
     "<br>"+tr("Rerun ntp?"),
     QMessageBox::Ok,QMessageBox::Cancel)
   	) {
	    	case QMessageBox::Ok:     break;
  	   	case QMessageBox::Cancel: return;
    	  default: return;
      }
  }
	TextLabelStartTime->setText(QDateTime::currentDateTime().toString());
	ntpProcess->clearArguments();
	*ntpProcess << "ntpdate" << LineEditNtpSrv->text();
	bool ret = ntpProcess->start(OProcess::NotifyOnExit,OProcess::AllOutput);
  if ( !ret ) {
     qDebug("Error while executing ntp");
  }
}

void  Ntp::getNtpOutput(OProcess *proc, char *buffer, int buflen)
{
  QString lineStr, lineStrOld;
  lineStr = buffer;
  lineStr=lineStr.left(buflen);
  if (lineStr!=lineStrOld)
  {
	        MultiLineEditntpOutPut->append(lineStr);
         	_ntpOutput += lineStr;
  }
  lineStrOld = lineStr;
}

void  Ntp::ntpFinished(OProcess*)
{
	Config cfg("ntp",Config::User);
  cfg.setGroup("lookups");
  int lastLookup = cfg.readNumEntry("time",0);
  int lookupCount = cfg.readNumEntry("count",-1);
  int time = TimeConversion::toUTC( QDateTime::currentDateTime() );
  cfg.writeEntry("time", time);
  cfg.setGroup("correction");
  cfg.writeEntry("time", time);
 	
  float timeShift = getTimeShift();
  if (timeShift == 0.0) return;
 	int secsSinceLast = time - lastLookup;
  TextLabelNewTime->setText(QDateTime::currentDateTime().toString());
  TextLabelTimeShift->setText(QString::number(timeShift)+tr(" seconds"));
  if ( lastLookup > 0 && secsSinceLast > 60* SpinBoxMinLookupDelay->value())
  {
	  lookupCount++;
   	cfg.writeEntry("count",lookupCount);
	  cfg.setGroup("lookup_"+QString::number(lookupCount));
    _shiftPerSec =  timeShift / secsSinceLast;
//    float nextCorr = _maxOffset / _shiftPerSec;
   	qDebug("secs since last lookup %i", secsSinceLast);qDebug("timeshift since last lookup %f", timeShift);qDebug("timeshift since per sec %f", _shiftPerSec);
		cfg.writeEntry("secsSinceLast",secsSinceLast);
		cfg.writeEntry("timeShift",QString::number(timeShift));
  }
}


float Ntp::getTimeShift()
{
	QString _offset = "offset";
  QString _sec = "sec";
  QRegExp _reOffset = QRegExp(_offset);
  QRegExp _reEndOffset = QRegExp(_sec);
  int posOffset = _reOffset.match( _ntpOutput );
  int posEndOffset = _reEndOffset.match( _ntpOutput, posOffset );
  posOffset += _offset.length() + 1;
  QString diff = _ntpOutput.mid(posOffset, posEndOffset-posOffset-1);
  qDebug("%s", _ntpOutput.latin1());
  qDebug("diff = >%s<",diff.latin1());
  return diff.toFloat();
}

void Ntp::readLookups()
{
	Config cfg("ntp",Config::User);
  cfg.setGroup("lookups");
  int lookupCount = cfg.readNumEntry("count",-1);
  float last, shift, shiftPerSec;
  qDebug("lookupCount = %i",lookupCount);
  TableLookups->setNumCols( 3 );
  TableLookups->setNumRows( lookupCount);
  TableLookups->horizontalHeader()->setLabel(1,"secsSinceLast");
  TableLookups->horizontalHeader()->setLabel(2,"timeShift");
  TableLookups->horizontalHeader()->setLabel(0,"shift/s");
  int cw = 50;//TableLookups->width()/4;
  qDebug("column width %i",cw);
  TableLookups->setColumnWidth( 0, cw+30 );
  TableLookups->setColumnWidth( 1, cw );
  TableLookups->setColumnWidth( 2, cw );
  TableLookups->sortColumn(0, false, true );
 // TableLookups->setSorting( true );
  for (int i=0; i < lookupCount; i++)
  {
	  cfg.setGroup("lookup_"+QString::number(i));
   	last = cfg.readEntry("secsSinceLast",0).toFloat();
    shift = QString(cfg.readEntry("timeShift",0)).toFloat();
//   	qDebug("%i last %f",i,last);
//   	qDebug("%i shift %f",i,shift);
    shiftPerSec =  shift / last;
    _shiftPerSec += shiftPerSec;
		TableLookups->setText( i,0,QString::number(shiftPerSec));
		TableLookups->setText( i,2,QString::number(shift));
	  TableLookups->setText( i,1,QString::number(last));
  }
  _shiftPerSec /= lookupCount+1;
  TextLabelShift->setText(QString::number(_shiftPerSec)+tr(" seconds"));
}

void Ntp::preditctTime()
{
	qDebug("current time: %s",QDateTime::currentDateTime().toString().latin1());
	Config cfg("ntp",Config::User);
  cfg.setGroup("lookups");
 	int lastTime = cfg.readNumEntry("time",0);
  setenv( "TZ", tz->currentZone(), 1 );
  int now = TimeConversion::toUTC( QDateTime::currentDateTime() );
  int corr = int((now - lastTime) * _shiftPerSec);
  predictedTime = QDateTime::currentDateTime().addSecs(corr);
 	TextLabelPredTime->setText(predictedTime.toString());
  TextLabelMainPredTime->setText(tr("Predicted time:")+"<br><b>"+predictedTime.toString()+"</b>");
}

void Ntp::setPredictTime()
{
  preditctTime();
 	setTime( predictedTime );
}

void Ntp::slotCheckNtp(int i)
{
	if (i == 0)
 	{
    TextLabelMainPredTime->hide();
    ButtonSetTime->setText( tr("Get time from network") );
	  connect( ButtonSetTime, SIGNAL(clicked()), SLOT(slotRunNtp()) );
  }else{
	  preditctTime();
		ButtonSetTime->setText( tr("Set predicted time") );
  	connect( ButtonSetTime, SIGNAL(clicked()), SLOT(setPredictTime()) );
  };
}