summaryrefslogtreecommitdiff
path: root/src/libpcp_qwt/src/qwt_sampling_thread.cpp
blob: 4cffb3dee3fa46ad74bdd3ea0d70c84c4a787781 (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
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
 * Qwt Widget Library
 * Copyright (C) 1997   Josef Wilgen
 * Copyright (C) 2002   Uwe Rathmann
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the Qwt License, Version 1.0
 *****************************************************************************/

#include "qwt_sampling_thread.h"
#include "qwt_system_clock.h"

class QwtSamplingThread::PrivateData
{
public:
    QwtSystemClock clock;

    double interval;
    bool isStopped;
};


//! Constructor
QwtSamplingThread::QwtSamplingThread( QObject *parent ):
    QThread( parent )
{
    d_data = new PrivateData;
    d_data->interval = 1000; // 1 second
    d_data->isStopped = true;
}

//! Destructor
QwtSamplingThread::~QwtSamplingThread()
{
    delete d_data;
}

/*!
   Change the interval (in ms), when sample() is called.
   The default interval is 1000.0 ( = 1s )

   \param interval Interval
   \sa interval()
*/
void QwtSamplingThread::setInterval( double interval )
{
    if ( interval < 0.0 )
        interval = 0.0;

    d_data->interval = interval;
}

/*!
   \return Interval (in ms), between 2 calls of sample()
   \sa setInterval()
*/
double QwtSamplingThread::interval() const
{
    return d_data->interval;
}

/*!
   \return Time (in ms) since the thread was started
   \sa QThread::start(), run()
*/
double QwtSamplingThread::elapsed() const
{
    if ( d_data->isStopped )
        return 0.0;

    return d_data->clock.elapsed();
}

/*!
   Terminate the collecting thread
   \sa QThread::start(), run()
*/
void QwtSamplingThread::stop()
{
    d_data->isStopped = true;
}

/*!
   Loop collecting samples started from QThread::start()
   \sa stop()
*/
void QwtSamplingThread::run()
{
    d_data->clock.start();
    d_data->isStopped = false;

    while ( !d_data->isStopped )
    {
        const double elapsed = d_data->clock.elapsed();
        sample( elapsed / 1000.0 );

        if ( d_data->interval > 0.0 )
        {
            const double msecs =
                d_data->interval - ( d_data->clock.elapsed() - elapsed );

            if ( msecs > 0.0 )
                usleep( qRound( 1000.0 * msecs ) );
        }
    }
}