summaryrefslogtreecommitdiff
path: root/library/alarmserver.cpp
blob: a1a714279e1f315af5f5cb01368c39309d0c3793 (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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/**********************************************************************
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#include <qdir.h>
#include <qfile.h>
#include <qmessagebox.h>
#include <qtextstream.h>


#include "qpeapplication.h"
#include "global.h"
#include "resource.h"

#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
#include "qcopenvelope_qws.h"
#endif
#include "alarmserver.h"
#include <qpe/timeconversion.h>

#include <sys/types.h>
#include <sys/stat.h>

#include <stdlib.h>
#include <unistd.h>

struct timerEventItem {
    time_t UTCtime;
    QCString channel, message;
    int data;
    bool operator==( const timerEventItem &right ) const
    {
        return ( UTCtime == right.UTCtime
                 && channel == right.channel
                 && message == right.message
                 && data == right.data );
    }
};

class TimerReceiverObject : public QObject
{
public:
  TimerReceiverObject() { }
  ~TimerReceiverObject() { }
  void resetTimer();
  void setTimerEventItem();
  void deleteTimer();
protected:
  void timerEvent( QTimerEvent *te );
private:
    QString atfilename;
};

TimerReceiverObject *timerEventReceiver = NULL;
QList<timerEventItem> timerEventList;
timerEventItem *nearestTimerEvent = NULL;


// set the timer to go off on the next event in the list
void setNearestTimerEvent()
{
    nearestTimerEvent = NULL;
    QListIterator<timerEventItem> it( timerEventList );
    if ( *it )
	nearestTimerEvent = *it;
    for ( ; *it; ++it )
	if ( (*it)->UTCtime < nearestTimerEvent->UTCtime )
	    nearestTimerEvent = *it;
    if (nearestTimerEvent)
	timerEventReceiver->resetTimer();
    else
	timerEventReceiver->deleteTimer();
}


//store current state to file
//Simple implementation. Should run on a timer.

static void saveState()
{
    QString savefilename = Global::applicationFileName( "AlarmServer", "saveFile" );
    if ( timerEventList.isEmpty() ) {
	unlink( savefilename );
	return;
    }

    QFile savefile(savefilename+".new");
    if ( savefile.open(IO_WriteOnly) ) {
	QDataStream ds( &savefile );

	//save

	QListIterator<timerEventItem> it( timerEventList );
	for ( ; *it; ++it ) {
	    ds << it.current()->UTCtime;
	    ds << it.current()->channel;
	    ds << it.current()->message;
	    ds << it.current()->data;
	}


	savefile.close();
	unlink( savefilename );
	QDir d; d.rename(savefilename+".new",savefilename);

    }
}

/*!
  Sets up the alarm server. Restoring to previous state (session management).
 */
void AlarmServer::initialize()
{
    //read autosave file and put events in timerEventList

    QString savefilename = Global::applicationFileName( "AlarmServer", "saveFile" );

    QFile savefile(savefilename);
    if ( savefile.open(IO_ReadOnly) ) {
	QDataStream ds( &savefile );
	while ( !ds.atEnd() ) {
	    timerEventItem *newTimerEventItem = new timerEventItem;
	    ds >> newTimerEventItem->UTCtime;
	    ds >> newTimerEventItem->channel;
	    ds >> newTimerEventItem->message;
	    ds >> newTimerEventItem->data;
	    timerEventList.append( newTimerEventItem );
	}
	savefile.close();
	if (!timerEventReceiver)
	    timerEventReceiver = new TimerReceiverObject;
	setNearestTimerEvent();
    }
}




static const char* atdir = "/var/spool/at/";

static bool triggerAtd( bool writeHWClock = FALSE )
{
    QFile trigger(QString(atdir) + "trigger");
    if ( trigger.open(IO_WriteOnly|IO_Raw) ) {

	const char* data =
#ifdef QT_QWS_CUSTOM
	//custom atd only writes HW Clock if we write a 'W'
	    ( writeHWClock ) ? "W\n" :
#endif
	    data = "\n";
	int len = strlen(data);
	int total_written = trigger.writeBlock(data,len);
	if ( total_written != len ) {
	    QMessageBox::critical( 0, QObject::tr( "Out of Space" ),
				   QObject::tr( "Unable to schedule alarm.\nFree some memory and try again." ) );
	    trigger.close();
	    QFile::remove( trigger.name() );
	    return FALSE;
	}
	return TRUE;
    }
    return FALSE;
}

void TimerReceiverObject::deleteTimer()
{
    if ( !atfilename.isEmpty() ) {
	unlink( atfilename );
	atfilename = QString::null;
	triggerAtd( FALSE );
    }
}

void TimerReceiverObject::resetTimer()
{
    const int maxsecs = 2147000;
    int total_written;
    QDateTime nearest = TimeConversion::fromUTC(nearestTimerEvent->UTCtime);
    QDateTime now = QDateTime::currentDateTime();
    int secs = TimeConversion::secsTo( now, nearest );
    if ( secs > maxsecs ) {
	// too far for millisecond timing
	secs = maxsecs;
    }

    // System timer (needed so that we wake from deep sleep),
    // from the Epoch in seconds.
    //
    int at_secs = TimeConversion::toUTC(nearest);
    // qDebug("reset timer to %d seconds from Epoch",at_secs);
    QString fn = atdir + QString::number(at_secs) + "."
		 + QString::number(getpid());
    if ( fn != atfilename ) {
	QFile atfile(fn+".new");
	if ( atfile.open(IO_WriteOnly|IO_Raw) ) {
	    // just wake up and delete the at file
	    QString cmd = "#!/bin/sh\nrm " + fn;
	    total_written = atfile.writeBlock(cmd.latin1(),cmd.length());
	    if ( total_written != int(cmd.length()) ) {
		QMessageBox::critical( 0, tr("Out of Space"),
				       tr("Unable to schedule alarm.\n"
					  "Please free up space and try again") );
		atfile.close();
		QFile::remove( atfile.name() );
		return;
	    }
	    atfile.close();
	    unlink( atfilename );
	    QDir d; d.rename(fn+".new",fn);
	    chmod(fn.latin1(),0755);
	    atfilename = fn;
	    triggerAtd( FALSE );
	} else {
	    qWarning("Cannot open atd file %s",fn.latin1());
	}
    }
    // Qt timers (does the actual alarm)
    // from now in milliseconds
    //
    qDebug("AlarmServer waiting %d seconds",secs);
    startTimer( 1000 * secs + 500 );
}

void TimerReceiverObject::timerEvent( QTimerEvent * )
{
    bool needSave = FALSE;
    killTimers();
    if (nearestTimerEvent) {
        if ( nearestTimerEvent->UTCtime
	     <= TimeConversion::toUTC(QDateTime::currentDateTime()) ) {
	    QCopEnvelope e( nearestTimerEvent->channel,
			    nearestTimerEvent->message );
	    e << TimeConversion::fromUTC( nearestTimerEvent->UTCtime )
	      << nearestTimerEvent->data;
	    timerEventList.remove( nearestTimerEvent );
	    needSave = TRUE;
	}
        setNearestTimerEvent();
    } else {
        resetTimer();
    }
    if ( needSave )
	saveState();
}

/*!
  \class AlarmServer alarmserver.h
  \brief The AlarmServer class provides alarms to be scheduled.

  Applications which wish to be informed when a certain time instant
  passes use the functions of AlarmServer to request so.
*/

/*!
  Schedules an alarm for \a when. Soon after this time,
  \a message will be sent to \a channel, with \a data as
  a parameter. \a message must be of the form "someMessage(int)".

  \sa deleteAlarm()
*/
void AlarmServer::addAlarm ( QDateTime when, const QCString& channel,
			     const QCString& message, int data)
{
    if ( qApp->type() == QApplication::GuiServer ) {
	bool needSave = FALSE;
	// Here we are the server so either it has been directly called from
	// within the server or it has been sent to us from a client via QCop
	if (!timerEventReceiver)
	    timerEventReceiver = new TimerReceiverObject;

	timerEventItem *newTimerEventItem = new timerEventItem;
	newTimerEventItem->UTCtime = TimeConversion::toUTC( when );
	newTimerEventItem->channel = channel;
	newTimerEventItem->message = message;
	newTimerEventItem->data = data;
	// explore the case of already having the event in here...
	QListIterator<timerEventItem> it( timerEventList );
	for ( ; *it; ++it )
	    if ( *(*it) == *newTimerEventItem )
		return;
	// if we made it here, it is okay to add the item...
	timerEventList.append( newTimerEventItem );
	needSave = TRUE;
	// quicker than using setNearestTimerEvent()
	if ( nearestTimerEvent ) {
	    if (newTimerEventItem->UTCtime < nearestTimerEvent->UTCtime) {
	        nearestTimerEvent = newTimerEventItem;
	        timerEventReceiver->killTimers();
	        timerEventReceiver->resetTimer();
	    }
	} else {
	    nearestTimerEvent = newTimerEventItem;
	    timerEventReceiver->resetTimer();
	}
	if ( needSave )
	    saveState();
    } else {
        QCopEnvelope e( "QPE/System", "addAlarm(QDateTime,QCString,QCString,int)" );
        e << when << channel << message << data;
    }
}

/*!
  Deletes previously scheduled alarms which match \a when, \a channel, \a message,
  and \a data.

  Passing null values for \a when, \a channel, or \a message indicates "any".
  Passing -1 for \a data indicates "any".

  \sa deleteAlarm()
*/
void AlarmServer::deleteAlarm (QDateTime when, const QCString& channel, const QCString& message, int data)
{
    if ( qApp->type() == QApplication::GuiServer) {
	bool needSave = FALSE;
	if ( timerEventReceiver != NULL ) {
	    timerEventReceiver->killTimers();

	    // iterate over the list of events
	    QListIterator<timerEventItem> it( timerEventList );
	    time_t deleteTime = TimeConversion::toUTC( when );
	    for ( ; *it; ++it ) {
		// if its a match, delete it
		if ( ( (*it)->UTCtime == deleteTime || when.isNull() )
		    && ( channel.isNull() || (*it)->channel == channel )
		    && ( message.isNull() || (*it)->message == message )
		    && ( data==-1 || (*it)->data == data ) )
		{
		    // if it's first, then we need to update the timer
		    if ( (*it) == nearestTimerEvent ) {
			timerEventList.remove(*it);
			setNearestTimerEvent();
		    } else {
			timerEventList.remove(*it);
		    }
		    needSave = TRUE;
		}
	    }
	    if ( nearestTimerEvent )
		timerEventReceiver->resetTimer();
	}
	if ( needSave )
	    saveState();
    } else {
        QCopEnvelope e( "QPE/System", "deleteAlarm(QDateTime,QCString,QCString,int)" );
        e << when << channel << message << data;
    }
}

/*!
  Writes the system clock to the hardware clock.
*/
void Global::writeHWClock()
{
    if ( !triggerAtd( TRUE ) ) {
	// atd not running? set it ourselves
	system("/sbin/hwclock --systohc"); // ##### UTC?
    }
}