#include "modulesystime.h"
#include <cstdlib>
#include <QFile>
#include <QTextStream>
#include <QDebug>

ModuleSysTime::ModuleSysTime(QObject *parent) : QObject(parent)
{
    QTimer::singleShot(1000, this, SLOT(onTimerTimeOutPingNet()));
}

void ModuleSysTime::onTimerTimeOutPingNet()
{
    qDebug("ping net: timeout 5s ping 202.108.22.5 > /home/net_check");

    std::system("timeout 5s ping www.baidu.com -n > /home/net_check");

    QTimer::singleShot(5000, this, SLOT(onTimerTimeOutCheckNet()));
}

void ModuleSysTime::onTimerTimeOutCheckNet()
{
    qDebug("onTimerTimeOutCheckNet");

    QFile file_read_net("/home/net_check");
    QString net_check = "";
    if(file_read_net.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&file_read_net);//创建一个对象让它去读文件
        QString ping1=in.readLine();
        QString ping2=in.readLine();
        net_check=ping2.left(2);
    }
    file_read_net.close();

    if (net_check=="64")
    {
        qDebug("file_write: /home/data/net_ok.txt  success!");

        QFile file_write("/home/data/net_ok.txt");//网络连接正常
        if(file_write.open(QFile::WriteOnly))
        {
            QTextStream setWIFI_data(&file_write);
            setWIFI_data<<"1"<<endl;
        }
        file_write.close();

        std::system("timeout 10s ntpdate ntp.aliyun.com &");

        QTimer::singleShot(10000, this, SLOT(onTimerTimeOutWaitNetTime()));
        //给底板校时
        return;
    }
    else
    {
        qDebug("file_write: /home/data/net_ok.txt  fail!");
        QFile file_write("/home/data/net_ok.txt");//网络连接错误
        if(file_write.open(QFile::WriteOnly))
        {
            QTextStream setWIFI_data(&file_write);
            setWIFI_data<<"0"<<endl;
        }
        file_write.close();

        qDebug("sigArmRtcTimeUpdate(false)!");
        emit sigArmRtcTimeUpdate(false);
    }

    QTimer::singleShot(1000, this, SLOT(onTimerTimeOutPingNet()));
}

void ModuleSysTime::onTimerTimeOutWaitNetTime()
{
    qDebug("sigArmRtcTimeUpdate(true)!");

    emit sigArmRtcTimeUpdate(true);
    QTimer::singleShot(1000, this, SLOT(onTimerTimeOutPingNet()));
}



