gruesensorimpl.cpp Example File
grue/plugin/gruesensorimpl.cpp
#include "gruesensorimpl.h"
#include <QDebug>
#include <QTimer>
char const * const gruesensorimpl::id("grue.gruesensor");
gruesensorimpl::gruesensorimpl(QSensor *sensor)
: QSensorBackend(sensor)
, lightLevel(QAmbientLightReading::Undefined)
{
lightSensor = new QAmbientLightSensor(this);
connect(lightSensor, SIGNAL(readingChanged()), this, SLOT(lightChanged()));
lightSensor->connectToBackend();
darkTimer = new QTimer(this);
darkTimer->setInterval(1000);
connect(darkTimer, SIGNAL(timeout()), this, SLOT(increaseChance()));
timer.start();
setReading<GrueSensorReading>(&m_reading);
setDataRates(lightSensor);
addOutputRange(0, 1, 0.1);
setDescription(QLatin1String("Grue Sensor"));
}
void gruesensorimpl::start()
{
lightSensor->setDataRate(sensor()->dataRate());
lightSensor->start();
if (!lightSensor->isActive())
sensorStopped();
if (lightSensor->isBusy())
sensorBusy();
}
void gruesensorimpl::stop()
{
lightSensor->stop();
}
void gruesensorimpl::lightChanged()
{
if (lightLevel == lightSensor->reading()->lightLevel())
return;
lightLevel = lightSensor->reading()->lightLevel();
int chance = 0;
darkTimer->stop();
switch (lightSensor->reading()->lightLevel()) {
case QAmbientLightReading::Dark:
chance = 10;
darkTimer->start();
break;
default:
break;
}
if (chance != m_reading.chanceOfBeingEaten() || m_reading.timestamp() == 0) {
m_reading.setTimestamp(timer.elapsed());
m_reading.setChanceOfBeingEaten(chance);
newReadingAvailable();
}
}
void gruesensorimpl::increaseChance()
{
int chance = m_reading.chanceOfBeingEaten() + 10;
m_reading.setTimestamp(timer.elapsed());
m_reading.setChanceOfBeingEaten(chance);
newReadingAvailable();
if (chance >= 100)
darkTimer->stop();
}