#include "beepthread.h"
#include "../ytCore/yt_unit_shm.h"

YT_UNIT_SHM *ytShm;

bool load_shm()
{
    int shmid;
    key_t key;
    if((key = ftok(SHM_PATH,(int)SHM_PORT))==-1)
        return false;
    if((shmid = shmget(key,sizeof(YT_UNIT_SHM),IPC_CREAT|0666))==-1)
        return false;
    ytShm = (YT_UNIT_SHM *)shmat(shmid,NULL,0);
    return true;
}

BeepThread::BeepThread(QObject *parent, Ycapi *api) :
    QThread(parent)
{
    this->api = api;
    load_shm();
}

void BeepThread::setBeep(int type)
{
//    this->type = type;
}

void BeepThread::run()
{
    while(1)
    {
        if(ytShm->dogTimeList.dogTime[63].LASTFEED!=0x00){
            type = BtnBeep;
            ytShm->dogTimeList.dogTime[63].LASTFEED=0x00;
//            printf("Btn Beep\n");
            emit btn_click();
        }
        switch(type)
        {
        case NoBeep:
            break;
        case OkBeep:
            api->BeepOn(true);
            usleep(50000);
            api->BeepOn(false);
            usleep(50000);
            api->BeepOn(true);
            usleep(150000);
            api->BeepOn(false);
            break;
        case BtnBeep:
            api->BeepOn(true);
            usleep(100000);
            api->BeepOn(false);
            break;
        case WrongBeep:
            api->BeepOn(true);
            usleep(150000);
            api->BeepOn(false);
            usleep(50000);
            api->BeepOn(true);
            usleep(50000);
            api->BeepOn(false);
            break;
        }
        type = NoBeep;
        usleep(500000);
    }
}
