#include "TedsWriterDevceDetector.h"
#include "LQError.h"

TedsWriterDevceDetector::TedsWriterDevceDetector(QObject *parent) :
    QObject{parent}, m_checkTmr{this} {

}

void TedsWriterDevceDetector::start() {
    connect(&m_checkTmr, &QTimer::timeout, this, &TedsWriterDevceDetector::checkDevice);
    m_checkTmr.start(500);
}



void TedsWriterDevceDetector::checkDevice() {
    LQError err;
    if (!m_connected) {
        m_dev.detect(err);
        if (err.isSuccess()) {
            m_teds_detected = m_dev.checkTedsPresent(err);
            if (err.isSuccess()) {
                m_connected = true;
                Q_EMIT connectionStatusChanged(m_connected);
                if (m_teds_detected) {
                    Q_EMIT tedsMemStatusChanged(m_teds_detected);
                }
            } else {
                m_dev.close();
            }
        }
    } else {
        bool mem_det = m_dev.checkTedsPresent(err);
        if (mem_det != m_teds_detected) {
            m_teds_detected = mem_det;
            Q_EMIT tedsMemStatusChanged(mem_det);
        }
        if (!err.isSuccess()) {
            m_connected = false;
            Q_EMIT connectionStatusChanged(m_connected);
        }
    }
}
