/*
 * SmartHome server: Plug-in thermostat
 *
 * Copyright (C) 2010 Daniel Pisi <dan.pisi@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of version 2 of the GNU General Public License
 * as published by the Free Software Foundation.
 *
 */

/**
 * @file shthermostat.cpp
 * @brief Implements a simple thermostat
 * @author Daniel Pisi
 */

#include "shthermostat.h"

// -----------------------------------------------------------------------------

/**
 * \brief Constructor of ShThermostat
 */
ShThermostat::ShThermostat()
{
    mDesiredTemp  = 20;
    mMeasuredTemp = 20;
    mHysteresis   = 1;
    mOutput       = -1;
}
// -----------------------------------------------------------------------------

/**
 * \brief Initialization of the plug-in
 * \param param Defines a thermostat hysteresis
 * \return true if the plug-in has been initialized successfully
 */
bool ShThermostat::init(QString param)
{
    qDebug("Thermostat initialized");
    return true;
}
// -----------------------------------------------------------------------------

/**
 * \brief Updates the output of thermostat plug-in
 */
void ShThermostat::updateOutput()
{
    if ((mOutput != 0) && (mMeasuredTemp >= mDesiredTemp + mHysteresis/2.0))
    {
        mOutput = 0;
        outputUpdated("Y", "0");
    }
    else if ((mOutput != 1) && (mMeasuredTemp <= mDesiredTemp - mHysteresis/2.0))
    {
        mOutput = 1;
        outputUpdated("Y", "1");
    }
}
// -----------------------------------------------------------------------------

/**
 * \brief Processes incoming messages (input changes)
 * \param message Shared pointer to the message
 */
void ShThermostat::processMessage(ShMessagePtr message)
{
    qDebug("Thermostat: Processing message from object %d, signal = %s, value = %s",
           message->senderId(), qPrintable(message->signal()), qPrintable(message->value().toString()));

    if (message->msgType() == ShMessage::mtValue)
    {
        double *tempPtr = NULL;

        if (message->signal() == "W")
            tempPtr = &mDesiredTemp;
        else if (message->signal() == "X")
            tempPtr = &mMeasuredTemp;
        else
        {
            errorMessage(message, "Invalid signal");
            return;
        }

        bool ok = false;
        double temp = message->value().toDouble(&ok);

        if (ok)
        {
            *tempPtr = temp;
            updateOutput();

            if (message->requireAck())
                ackMessage(message);
        }
        else
            errorMessage(message, "Invalid value");
    }
}
// -----------------------------------------------------------------------------

Q_EXPORT_PLUGIN2(thermostat, ShThermostat);
