#include "relay.h"
#include "../microcontroller.h"

//Relay

Microcontroller* Relay::micro_ = nullptr;

Relay::Relay(uint8_t id, QString name, uint16_t address, bool state, QObject* parent): Item(0, name, state, parent),
	id_(id), address_(address)
{
	itemId_ = address | ((uint32_t)id << 16);
}

void Relay::enactValue(uint8_t value)
{
	qDebug()<<"Relay"<<__func__<<micro_;
	if(micro_)
	{
		if(value)
			micro_->relayOn(id_);
		else
			micro_->relayOff(id_);
	}
}

void Relay::store(QJsonObject& json)
{
	json["Type"] = "Relay";
	Item::store(json);
	json["Id"] = static_cast<double>(id_);
	json["Address"] = address_;
}

void Relay::load(const QJsonObject& json, const bool preserve)
{
	Item::load(json, preserve);
	id_ = static_cast<uint8_t>(json["Id"].toInt(0));
	address_ = static_cast<uint16_t>(json["Address"].toInt(0));
	itemId_ = address_ | (static_cast<uint32_t>(id_) << 16);
}

uint16_t Relay::getAddress() const
{
	return address_;
}

uint8_t Relay::getId() const
{
	return id_;
}

void Relay::setId(uint8_t id)
{
	id_=id;
	itemId_ = address_ | ((uint32_t)id << 16);
}

