/*
 * QrfeSL900aTag.cpp
 *
 *  Created on: 27.09.2013
 *      Author: stefan.detter
 */

#include "../inc/tag/specific/QrfeSL900aTag.h"

#include "../inc/QrfeReaderInterface.h"


QrfeSL900aTag::QrfeSL900aTag(QString tagId, QrfeGen2AdvancedManipulatorInterface *reader, QObject* parent)
	: QrfeGen2Tag(tagId, reader, parent)
{
}

QrfeSL900aTag::~QrfeSL900aTag()
{
}


QrfeGlobal::TMIResult QrfeSL900aTag::getSensorValue(const QByteArray& passwd, SENSOR_TYPE sensor, bool& adError, uchar& rangeLimit, ushort& sensorValue)
{
	if(passwd.size() != 4)
    {
        return QrfeGlobal::TMI_ERROR;
    }

	QrfeGlobal::TMIResult res;

	m_reader->getReaderInterface()->setAntennaPower(true);

	QByteArray handle;
    res = ((QrfeGen2AdvancedManipulatorInterface*)m_gen2reader)->getTagHandle(m_tagId, handle);
	if(res != QrfeGlobal::TMI_OK)
	{
		m_reader->getReaderInterface()->setAntennaPower(false);
		return res;
	}

	res = getSensorValue(handle, passwd, sensor, adError, rangeLimit, sensorValue);

	m_reader->getReaderInterface()->setAntennaPower(false);

	return res;
}

QrfeGlobal::TMIResult QrfeSL900aTag::getSensorValue(const QByteArray& handle, const QByteArray& passwd, SENSOR_TYPE sensor, bool& adError, uchar& rangeLimit, ushort& sensorValue)
{
	QrfeGlobal::TMIResult res;

	adError = 0;
	rangeLimit = 0;
	sensorValue = 0;

	if(passwd.size() != 4)
    {
        return QrfeGlobal::TMI_ERROR;
    }

	QByteArray cmd;
	cmd.append((uchar)0xE0);
	cmd.append((uchar)0xAD);

	QByteArray txBits;
	txBits.append((char)sensor);

	bool headerBit = true;
	QByteArray rxBytes;

    res = ((QrfeGen2AdvancedManipulatorInterface*)m_gen2reader)->customGen2Command(handle, cmd, passwd, 8, txBits, headerBit, rxBytes);
	if(res != QrfeGlobal::TMI_OK)
	{
		return res;
	}

	if(headerBit == true || rxBytes.size() < 2)
	{
		return QrfeGlobal::TMI_ERROR;
	}

	adError 	= (((uchar)rxBytes.at(0) & 0x80) > 0);
	rangeLimit	= (((uchar)rxBytes.at(0) & 0x7C) >> 2);
	sensorValue += ((ushort)((uchar)rxBytes.at(0) & 0x03)) << 8;
	sensorValue += (uchar)rxBytes.at(1);

	return QrfeGlobal::TMI_OK;
}

