#ifndef ACSCONTROLLER_H
#define ACSCONTROLLER_H

#include "SDK/ACSC.h"

#include <QObject>

class AcsController : public QObject
{
    Q_OBJECT
public:
    explicit AcsController(QObject *parent = nullptr);

    //class1: communication functions;
    HANDLE openCommSimulator() {return m_handler = acsc_OpenCommSimulator();};
    HANDLE openCommEthernetTCP(char* Address, int Port) {return m_handler = acsc_OpenCommEthernetTCP(Address,Port);};
    int closeComm(HANDLE Handle) {return acsc_CloseComm(Handle);};

    int getConnectionsList(ACSC_CONNECTION_DESC* ConnectionsList, int MaxNumConnections, int* NumConnections) \
        {return acsc_GetConnectionsList(ConnectionsList, MaxNumConnections, NumConnections);};

    int terminateConnection(ACSC_CONNECTION_DESC* Connection) \
        {return acsc_TerminateConnection(Connection); };

    int getErrorString(HANDLE Handle, int ErrorCode, char* ErrorStr, int Count, int* Received) \
        {return acsc_GetErrorString(Handle, ErrorCode, ErrorStr, Count, Received);};

    //class2: axis/motor management functions
    int enable(HANDLE Handle, int Axis, ACSC_WAITBLOCK* Wait) {return acsc_Enable(Handle, Axis, Wait);};
    int disable(HANDLE Handle, int Axis, ACSC_WAITBLOCK* Wait) {return acsc_Disable(Handle, Axis, Wait);};
    int disableAll(HANDLE Handle, ACSC_WAITBLOCK* Wait) {return acsc_DisableAll(Handle, Wait);};

    int enableM(HANDLE Handle, int* Axes, ACSC_WAITBLOCK* Wait) \
        {return acsc_EnableM(Handle, Axes, Wait); };

    int disableM(HANDLE Handle, int* Axes, ACSC_WAITBLOCK* Wait) \
        {return acsc_DisableM(Handle, Axes, Wait); };

    //class3: wait for condition functions
    int waitMotorEnabled(HANDLE Handle, int Axis, int State, int Timeout) \
        {return acsc_WaitMotorEnabled(Handle, Axis, State, Timeout);};

    //class4: error diagnostic functions
    int getMotorError(HANDLE Handle, int Axis, int* Error, ACSC_WAITBLOCK* Wait) \
        {return acsc_GetMotorError(Handle, Axis, Error, Wait);};

    int getMotionError(HANDLE Handle, int Axis, int* Error, ACSC_WAITBLOCK* Wait) \
        {return acsc_GetMotionError(Handle, Axis, Error, Wait);};

    //class5: setting and reading motion parameters functions
    int setTargetPosition(HANDLE Handle, int Axis, double TargetPosition, ACSC_WAITBLOCK* Wait) \
        {return acsc_SetTargetPosition(Handle, Axis, TargetPosition, Wait);};

    int getTargetPosition(HANDLE Handle, int Axis, double* TargetPosition, ACSC_WAITBLOCK* Wait) \
        {return acsc_GetTargetPosition(Handle, Axis, TargetPosition, Wait);};

    int setFPosition(HANDLE Handle, int Axis, double FPosition, ACSC_WAITBLOCK* Wait) \
        {return acsc_SetFPosition(Handle, Axis, FPosition, Wait); };

    int getFPosition(HANDLE Handle, int Axis, double* FPosition, ACSC_WAITBLOCK* Wait) \
        {return acsc_GetFPosition(Handle, Axis, FPosition, Wait);};

    int setRPosition(HANDLE Handle, int Axis, double RPosition, ACSC_WAITBLOCK* Wait) \
        {return acsc_SetRPosition(Handle, Axis, RPosition, Wait); };

    int getRPosition(HANDLE Handle, int Axis, double* RPosition, ACSC_WAITBLOCK* Wait) \
        {return acsc_GetRPosition(Handle, Axis, RPosition, Wait);};

    int getFVelocity(HANDLE Handle, int Axis, double* FVelocity, ACSC_WAITBLOCK* Wait) \
        {return acsc_GetFVelocity(Handle, Axis, FVelocity, Wait);};

    int getRVelocity(HANDLE Handle, int Axis, double* RVelocity, ACSC_WAITBLOCK* Wait) \
        {return acsc_GetRVelocity(Handle, Axis, RVelocity, Wait);};

    //class6: point to point Motion function
    int toPoint(HANDLE Handle, int Flags, int Axis, double Point, ACSC_WAITBLOCK* Wait) \
        {return acsc_ToPoint(Handle, Flags, Axis, Point, Wait); };

    int toPointM(HANDLE Handle, int Flags, int* Axes, double* Point, ACSC_WAITBLOCK* Wait) \
        {return acsc_ToPointM(Handle, Flags, Axes, Point, Wait);};

    //class7: jog function
    int jog(HANDLE Handle, int Flags, int Axis, double Velocity, ACSC_WAITBLOCK* Wait) \
        {return acsc_Jog(Handle, Flags, Axis, Velocity, Wait); };

    int jogM(HANDLE Handle, int Flags, int* Axes, int* Direction, double Velocity, ACSC_WAITBLOCK* Wait) \
        {return acsc_JogM(Handle, Flags, Axes, Direction, Velocity, Wait); };

    //class8: motion management functions
    int halt(HANDLE Handle, int Axis, ACSC_WAITBLOCK* Wait) \
        {return acsc_Halt(Handle, Axis, Wait); };

    int haltM(HANDLE Handle, int* Axes, ACSC_WAITBLOCK* Wait) \
        {return acsc_HaltM(Handle, Axes, Wait);};

    //class9: read and write variables functions
    int readInteger(HANDLE Handle, int NBuf, char* Var, int From1, int To1, int From2, int To2, int* Values, ACSC_WAITBLOCK* Wait) \
        {return acsc_ReadInteger(Handle, NBuf, Var, From1, To1, From2, To2, Values, Wait);};

    int writeInteger(HANDLE Handle, int NBuf, char* Var, int From1, int To1, int From2, int To2, int* Values, ACSC_WAITBLOCK* Wait) \
        {return acsc_WriteInteger(Handle, NBuf, Var, From1, To1, From2, To2, Values, Wait); };

    int readReal(HANDLE Handle, int NBuf, char* Var, int From1, int To1, int From2, int To2, double* Values, ACSC_WAITBLOCK* Wait) \
        {return acsc_ReadReal(Handle, NBuf, Var, From1, To1, From2, To2, Values, Wait);};

    int writeReal(HANDLE Handle, int NBuf, char* Var, int From1, int To1, int From2, int To2, double* Values, ACSC_WAITBLOCK* Wait) \
        {return acsc_WriteReal(Handle, NBuf, Var, From1, To1, From2, To2, Values, Wait); };

    HANDLE m_handler;
    int m_nretOK;

signals:

};

#endif // ACSCONTROLLER_H
#include "acscontroller.h"

AcsController::AcsController(QObject *parent)
    : QObject{parent}
    ,m_handler(NULL)
{

}


#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,m_nSelectedAxisNo(0)
{
    ui->setupUi(this);

    initImageLabel();
    initRadioButton();

    m_Timer = new QTimer(this);
    connect(m_Timer,&QTimer::timeout, this, &Widget::timerOut);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::initRadioButton()
{
    ui->buttonGroup->addButton(ui->radioButtonSimulator,0);
    ui->buttonGroup->addButton(ui->radioButtonTcpIp ,1);
    connect(ui->radioButtonSimulator, SIGNAL(clicked()), this,SLOT(slotClickedBtnGroup()));
    connect(ui->radioButtonTcpIp, SIGNAL(clicked()), this,SLOT(slotClickedBtnGroup()));
}

void Widget::initImageLabel()
{
    QString filenameOff(":/images/Images/Off.bmp");
    QImage* img=new QImage;
    img->load(filenameOff);
    qpixmap_off = QPixmap::fromImage(*img);

    QString filenameOn(":/images/Images/On.bmp");
    img->load(filenameOn);
    qpixmap_on = QPixmap::fromImage(*img);

    QString filenameError(":/images/Images/Error.bmp");
    img->load(filenameError);
    qpixmap_error = QPixmap::fromImage(*img);

    ui->lbl_sys_left0->setPixmap(qpixmap_off);
    ui->lbl_sys_left1->setPixmap(qpixmap_off);
    ui->lbl_sys_left2->setPixmap(qpixmap_off);
    ui->lbl_sys_left3->setPixmap(qpixmap_off);
    ui->lbl_sys_left4->setPixmap(qpixmap_off);
    ui->lbl_sys_left5->setPixmap(qpixmap_off);
    ui->lbl_sys_left6->setPixmap(qpixmap_off);
    ui->lbl_sys_left7->setPixmap(qpixmap_off);

    ui->lbl_sys_right0->setPixmap(qpixmap_off);
    ui->lbl_sys_right1->setPixmap(qpixmap_off);
    ui->lbl_sys_right2->setPixmap(qpixmap_off);
    ui->lbl_sys_right3->setPixmap(qpixmap_off);
    ui->lbl_sys_right4->setPixmap(qpixmap_off);
    ui->lbl_sys_right5->setPixmap(qpixmap_off);
    ui->lbl_sys_right6->setPixmap(qpixmap_off);
    ui->lbl_sys_right7->setPixmap(qpixmap_off);

    ui->lbl_sys_emergency->setPixmap(qpixmap_off);

    ui->lbl_gen_input0->setPixmap(qpixmap_off);
    ui->lbl_gen_input1->setPixmap(qpixmap_off);
    ui->lbl_gen_input2->setPixmap(qpixmap_off);
    ui->lbl_gen_input3->setPixmap(qpixmap_off);
    ui->lbl_gen_input4->setPixmap(qpixmap_off);
    ui->lbl_gen_input5->setPixmap(qpixmap_off);
    ui->lbl_gen_input6->setPixmap(qpixmap_off);
    ui->lbl_gen_input7->setPixmap(qpixmap_off);

    ui->lbl_gen_output0->setPixmap(qpixmap_off);
    ui->lbl_gen_output1->setPixmap(qpixmap_off);
    ui->lbl_gen_output2->setPixmap(qpixmap_off);
    ui->lbl_gen_output3->setPixmap(qpixmap_off);
    ui->lbl_gen_output4->setPixmap(qpixmap_off);
    ui->lbl_gen_output5->setPixmap(qpixmap_off);
    ui->lbl_gen_output6->setPixmap(qpixmap_off);
    ui->lbl_gen_output7->setPixmap(qpixmap_off);

    ui->lbl_motorStatus_moving->setPixmap(qpixmap_off);
    ui->lbl_motorStatus_acceleration->setPixmap(qpixmap_off);
    ui->lbl_motorStatus_inPosition->setPixmap(qpixmap_off);
    ui->lbl_motorStatus_enabled->setPixmap(qpixmap_off);

    delete img;
}

void Widget::on_pushButtonConnect_clicked()
{
    double SysInfo = 0.0;

    terminatePrevConnect();

    switch(m_nConnectType)
    {
    // Simulation Mode
    case 0:
        m_hAcsComm = m_controller.openCommSimulator();
        break;

        // Ethernet
    case 1:
        // Connect to the controller via TCP socket
        int port = ui->lineEditPort->text().toInt() == 0 ? ACSC_SOCKET_STREAM_PORT:ui->lineEditPort->text().toInt();
        m_hAcsComm = m_controller.openCommEthernetTCP((char*)ui->lineEditIpAddr->text().toLatin1().data(), port);

        // UDP Socket (ACS is supporting only 1 UDP channel)
        //m_hAcsComm = acsc_OpenCommEthernetUDP((char*)LPCTSTR(m_strIPAddress), ACSC_SOCKET_DGRAM_PORT);
        break;
    }

    // After connecting, if you got an invalid handle
    if(m_hAcsComm == ACSC_INVALID)
    {
        qDebug() << "Connection Error";
        return;
    }

    qDebug() << "Open Connection Successfully";

    // Get maximum number of axes
    SysInfo = 0.0;
    acsc_SysInfo(m_hAcsComm, 13, &SysInfo, NULL);
    g_nTotalAxes = (int)SysInfo;

    for(int i=0; i< g_nTotalAxes; i++)
    {
        ui->comboBoxAxis->addItem(QString::number(i));
    }
    ui->comboBoxAxis->setCurrentIndex(0);

    m_nSelectedAxisNo = 0;

    // Get total number of buffers
    SysInfo = 0.0;
    acsc_SysInfo(m_hAcsComm, 10, &SysInfo, NULL);
    g_nTotalBuffer = (int)SysInfo;

    for(int i=0; i< g_nTotalBuffer; i++)
    {
        ui->comboBoxBuffer->addItem(QString::number(i));
    }

    m_bConnected = TRUE;
    ui->comboBoxBuffer->setCurrentIndex(0);

    updateParameters(0);

    m_Timer->start(UPDATE_TIMER_INTERVAL);
}

void Widget::updateParameters(int nAxisIndex)
{
    double Vel, Acc, Dec, Jerk, KDec; // , FPos, RPos, FVel, PE;

    //==================================================================================
    // Velocity
    //==================================================================================
    if(acsc_GetVelocity(m_hAcsComm, nAxisIndex, &Vel, NULL))
    {
        QString strVelocity = QString::number(Vel,'f',4);
        ui->lineEditVeloccity->setText(strVelocity);
    }
    else
    {
        qDebug() << "Get Velocity Error";
    }

    //==================================================================================
    // Acceleration
    //==================================================================================
    if(acsc_GetAcceleration(m_hAcsComm, nAxisIndex, &Acc, NULL))
    {
        QString strAcc = QString::number(Acc,'f',4);
        ui->lineEditAcceleration->setText(strAcc);
    }
    else
    {
        qDebug() << "Get Acceleration Error";
    }


    //==================================================================================
    // Deceleration
    //==================================================================================
    if(acsc_GetDeceleration(m_hAcsComm, nAxisIndex, &Dec, NULL))
    {
        QString strDec = QString::number(Dec,'f',4);
        ui->lineEditDeceleration->setText(strDec);
    }
    else
    {
        qDebug() << "Get Deceleration Error";
    }

    //==================================================================================
    // Kill Deceleration
    //==================================================================================
    if(acsc_GetKillDeceleration(m_hAcsComm, nAxisIndex, &KDec, NULL))
    {
        QString strKillDec = QString::number(KDec,'f',4);
        ui->lineEditKillDeceleration->setText(strKillDec);
    }
    else
    {
        qDebug() << "Get Kill Deceleration Error";
    }

    //==================================================================================
    // Jerk
    //==================================================================================
    if(acsc_GetJerk(m_hAcsComm, nAxisIndex, &Jerk, NULL))
    {
        QString strJerk = QString::number(Jerk,'f',4);
        ui->lineEditJerk->setText(strJerk);
    }
    else
    {
        qDebug() << "Get Jerk Erorr";
    }
}

void Widget::slotClickedBtnGroup()
{
    switch(ui->buttonGroup->checkedId())
    {
    case 0:
        m_nConnectType = 0;
        qDebug() << QString::fromLocal8Bit("Simulator");
        break;
    case 1:
        m_nConnectType = 1;
        qDebug() << QString::fromLocal8Bit("Tcp/IP");
        break;
    }
}

void Widget::terminatePrevConnect()
{
    char tmpSeperator[2] = "\\";
    char *pSeperator = &tmpSeperator[0];
    char *pToken = NULL;
    char pApplicationName[256] = { 0x00, };

    int nConnections;
    ACSC_CONNECTION_DESC ConnectionList[10];

    if(!m_controller.getConnectionsList(ConnectionList, 10, &nConnections)) printf("Error %d\n", acsc_GetLastError());

    for (int i = 0; i < nConnections; i++)
    {
        // Sperate names (if the application name is "USERNAME\ACS.Fremwork.exe" in UMD list, you need to seprate it.)
        pToken = strtok(ConnectionList[i].Application, pSeperator);
        sprintf(pApplicationName, pToken);
        while (pToken)
        {
            pToken = strtok(NULL, pSeperator);	// Find next
            if(pToken != NULL)
            {
                sprintf(pApplicationName, pToken);
            }
        }

        // Clear connection without MMI application studio
        if((strcmp(pApplicationName, "ACS.Framework.exe")) != 0)
        {
            // Terminate connection from UDM
            if(!m_controller.terminateConnection(&(ConnectionList[i])))
            {
                printf("Error closing communication of %s application: %d\n", ConnectionList[i].Application, acsc_GetLastError());
            }
            else
            {
                printf("Communication of %s application is successfully closed!\n", ConnectionList[i].Application);
            }
        }
    }
}

void Widget::timerOut()
{
    QString strTemp;
    std::string strCmd;

    if(m_bConnected == FALSE) return;
    //==================================================================================
    // Read Feedback(FPOS), Reference position(RPOS), Feedback velocity(FVEL), Motor status(MST)
    //==================================================================================
    // Instruction 1. User libarary functions - acsc_GetFPosition, acsc_GetRPosition, ....
    // Instruction 2. Read ACS variable - Already defined almost things (FPOS, RPOS, ...)
    //                Motion parameters and state is array (Max length is total number of axes)
    //
    // * Library function can read only 1 axis information, so if you want to read several axes, you have to call the function many times.
    //   (This may cause communication dealy.)
    //   Recommand (if you want to read many axes) : read/write variable using acsc_ReadInteger, acsc_ReadReal, acsc_WriteInteger, acsc_WriteReal...

    // Feedback Position
    // ACSPL+ Variable : FPOS, C-Lib : acsc_GetFPosition()
    // - Read feedback position of total axes at once
    strCmd = "FPOS";
    m_controller.readReal(m_hAcsComm, -1, &strCmd[0], 0, g_nTotalAxes - 1, -1, -1, m_FPosition, NULL);

    // If you are using the get function,
    // acsc_GetFPosition(m_hAcsComm, 0, &m_FPosition[0], NULL);
    // acsc_GetFPosition(m_hAcsComm, 1, &m_FPosition[1], NULL);
    // acsc_GetFPosition(m_hAcsComm, 2, &m_FPosition[2], NULL);
    // acsc_GetFPosition(m_hAcsComm, 3, &m_FPosition[3], NULL);
    // ...

    // Reference Position
    // ACSPL+ Variable : RPOS, C-Lib : acsc_GetRPosition()
    strCmd = "RPOS";
    m_controller.readReal(m_hAcsComm, -1, &strCmd[0], 0, g_nTotalAxes - 1, -1, -1, m_RPosition, NULL);

    // Feedback Velocity
    // ACSPL+ Variable : FVEL, C-Lib : acsc_GetFVelocity()
    strCmd = "FVEL";
    m_controller.readReal(m_hAcsComm, -1, &strCmd[0], 0, g_nTotalAxes - 1, -1, -1, m_FVelocity, NULL);

    // Position Error
    // ACSPL+ Variable : PE, C-Lib : there is no function
    strCmd = "PE";
    m_controller.readReal(m_hAcsComm, -1, &strCmd[0],   0, g_nTotalAxes - 1, -1, -1, m_PositionErr, NULL);

    // Motor State
    // ACSPL+ : MST, C-Lib : acsc_GetMotorState()
    // Return value is integer, you have to use bitmask
    //
    // if (m_MotorStatus[0] & ACSC_MST_MOVE )
    // {
    //     Moving state
    // }
    // else
    // {
    //     Stand.. (in position)
    // }
    strCmd = "MST";
    m_controller.readInteger(m_hAcsComm, -1, &strCmd[0],  0, g_nTotalAxes -1, -1, -1, m_MotorStatus, NULL);

    // Motor Error Code
    // ACSPL+ : MERR, C-Lib : acsc_GetMotorError()
    strCmd = "MERR";
    m_controller.readInteger(m_hAcsComm, -1, &strCmd[0], 0, g_nTotalAxes -1, -1, -1, m_MotorError, NULL);

    //==================================================================================
    // Update dialog : Reference, Feedback position, Feedback velocity, Position Error
    //==================================================================================
    strTemp = QString::number(m_RPosition[m_nSelectedAxisNo] , 'f' ,4);
    ui->lineEditRPOS->setText(strTemp);

    strTemp = QString::number(m_FPosition[m_nSelectedAxisNo] , 'f' ,4);
    ui->lineEditApos->setText(strTemp);

    strTemp = QString::number(m_FVelocity[m_nSelectedAxisNo] , 'f' ,4);
    ui->lineEditAVelocity->setText(strTemp);

    strTemp = QString::number(m_PositionErr[m_nSelectedAxisNo] , 'f' ,4);
    ui->lineEditPositionError->setText(strTemp);
    //==================================================================================
    // Update dialog : Motor Status
    //==================================================================================
    if(m_MotorStatus[m_nSelectedAxisNo] & ACSC_MST_ENABLE)
    {
        ui->lbl_motorStatus_enabled->setPixmap(qpixmap_on);
    }
    else {
        ui->lbl_motorStatus_enabled->setPixmap(qpixmap_off);
    }

    if(m_MotorStatus[m_nSelectedAxisNo] & ACSC_MST_MOVE)
    {
        ui->lbl_motorStatus_moving->setPixmap(qpixmap_on);
    }
    else {
        ui->lbl_motorStatus_moving->setPixmap(qpixmap_off);
    }

    if(m_MotorStatus[m_nSelectedAxisNo] & ACSC_MST_ACC)
    {
        ui->lbl_motorStatus_acceleration->setPixmap(qpixmap_on);
    }
    else {
        ui->lbl_motorStatus_acceleration->setPixmap(qpixmap_off);
    }

    if(m_MotorStatus[m_nSelectedAxisNo] & ACSC_MST_INPOS)
    {
        ui->lbl_motorStatus_inPosition->setPixmap(qpixmap_on);
    }
    else {
        ui->lbl_motorStatus_inPosition->setPixmap(qpixmap_off);
    }

    //==================================================================================
    // Read General Input 8 bits, Output 8 bits at once (ACSPL Variable : IN(0), OUT(0))
    //==================================================================================
    acsc_GetInputPort(m_hAcsComm,  GPIO_PORT_NO, &m_GeneralInput,  NULL);
    acsc_GetOutputPort(m_hAcsComm, GPIO_PORT_NO, &m_GeneralOutput, NULL);
    updateGeneralIO();

//    //==================================================================================
//    // Left, Right Limit state
//    //  - ACSPL Variable : FAULT(MAX_AXIS_COUNT)
//    //  - acsc_GetFault : this function is reading fault informaton one by one
//    //  - if you are using acsc_ReadInteger function, you can read all informations at once
//    //==================================================================================
//    for(int iAxis = 0; iAxis < g_nTotalAxes; iAxis++)
//    {
//        acsc_GetFaultMask(m_hAcsComm, iAxis, &m_FaultMask, NULL);
//        acsc_GetFault(m_hAcsComm, iAxis, &m_MotorFault, NULL);

//        UpdateRightLimit(iAxis);
//        UpdateLeftLimit(iAxis);
//    }
//    // acsc_ReadInteger(m_hAcsComm, "FAULT", 0, g_nTotalAxes - 1, -1, -1, FaultArray, NULL);

//    //==================================================================================
//    // For updating Emergency Stop state (from System fault)
//    //  - ACSPL variable : S_FAULT
//    //   1. acsc_GetFault : Axis number is -1 (ACSC_NONE)
//    //   2. acsc_ReadInteger : ACS Variable  'S_FAULT', range 0 to 0
//    //==================================================================================
//    acsc_GetFaultMask(m_hAcsComm, ACSC_NONE, &m_EmergencyMask, NULL);
//    acsc_GetFault(m_hAcsComm, ACSC_NONE, &m_EmergencyFault, NULL);
//    UpdateEmergency();
}

void Widget::updateGeneralIO()
{
//    CStatic *picIn, *picOut;
//    CButton *btnOut;
//    int MaskBit = ACSC_MASK_INPUT_0;

//    picIn  = &m_picIn0;
//    picOut = &m_picOut0;
//    btnOut = &m_btnOut0;

//    for(int i = 0; i < MAX_GPIO_COUNT; i++)
//    {
//        // Input
//        if(m_GeneralInput & MaskBit) picIn[i].SetBitmap(BITMAP_ON);
//        else picIn[i].SetBitmap(BITMAP_OFF);

//        // Ouput
//        if(m_GeneralOutput & MaskBit)
//        {
//            picOut[i].SetBitmap(BITMAP_ON);
//            btnOut[i].SetWindowText(_T("OFF"));
//        }
//        else
//        {
//            picOut[i].SetBitmap(BITMAP_OFF);
//            btnOut[i].SetWindowText(_T("ON"));
//        }
//        MaskBit = MaskBit << 1;
//    }
}

void Widget::on_pushButtonDisconnect_clicked()
{
    m_Timer->stop();

    if(m_hAcsComm != ACSC_INVALID)
    {
        if(m_controller.closeComm(m_hAcsComm))
        {
            m_hAcsComm = ACSC_INVALID;
            m_bConnected = FALSE;

            qDebug() << "Close connection!!";
        }
    }
}

void Widget::on_pushButtonEnable_clicked()
{
    int Error;
    char ErrorStr[256];
    char MsgsStr[256];
    int Received;
    // Axis Enable command
    if (!m_controller.enable(m_hAcsComm, m_nSelectedAxisNo, NULL))
    {
        qDebug() << "Axis enable error";
    }
    // Waiting until enabled
    if (!m_controller.waitMotorEnabled(m_hAcsComm, m_nSelectedAxisNo, 1, TIMEOUT_MOTOR_ENABLED))

    if (m_controller.getMotorError(m_hAcsComm, m_nSelectedAxisNo, &Error, NULL))
    {
        if (Error > 0)
        {
            if (m_controller.getErrorString(m_hAcsComm, Error, ErrorStr, 255, &Received))
            {
                ErrorStr[Received] = '\0';
                sprintf_s(MsgsStr, "Error = % d ,%s", Error, ErrorStr);
                qDebug() << MsgsStr;
                return;
            }
        }
    }
    else
    {
        qDebug() << "Axis enable error";
    }

    // If you want to enable several axes..
    // Ex) eanble (0, 1, 5, 7)
    // int AxisList[] = { 0, 1, 5, 7, -1 };		!! You must set '-1' at the last of array.
    // acsc_EnableM(m_hAcsComm, AxisList, NULL);
}


void Widget::on_pushButtonDisable_clicked()
{
    // Axis disable command
    if(!m_controller.disable(m_hAcsComm, m_nSelectedAxisNo, NULL))
    {
        qDebug() << "Axis disable error";
    }
    // Waiting until disabled
    if(!m_controller.waitMotorEnabled(m_hAcsComm, m_nSelectedAxisNo, 0, TIMEOUT_MOTOR_ENABLED))
    {
        qDebug() << "Axis enable error";
    }

    // If you want to disable several axes..
    // Ex) disable (0, 1, 5, 7)
    // int AxisList[] = { 0, 1, 5, 7, -1 };		!! You must set '-1' at the last of array.
    // acsc_DisableM(m_hAcsComm, AxisList, NULL);
}


void Widget::on_pushButtonDisableAll_clicked()
{
    if(!m_controller.disableAll(m_hAcsComm, NULL))
    {
        qDebug() << "All axes disable error";
    }
}


void Widget::on_pushButtonBuffStart_clicked()
{

}


void Widget::on_pushButtonBuffStop_clicked()
{

}


void Widget::on_pushButtonSetZeroAPOS_clicked()
{
    if(!m_controller.setFPosition(m_hAcsComm, m_nSelectedAxisNo, 0, NULL))
    {
        qDebug() << "Set Feedback Position error";
    }
}


void Widget::on_pushButtonStop_clicked()
{
    if(!m_controller.halt(m_hAcsComm, m_nSelectedAxisNo, NULL))
    {
        qDebug() << "Halt command error";
    }
}


void Widget::on_pushButtonStopAll_clicked()
{
    int Axes[MAX_AXIS_COUNT + 1];
    for (int i = 0; i < g_nTotalAxes; i++)
    {
        // Set all axes
        Axes[i] = i;
    }
    // Add '-1' at the last of array
    Axes[g_nTotalAxes] = -1;

    if(!m_controller.haltM(m_hAcsComm, Axes, NULL))
    {
        qDebug() << "HaltM command error";
    }
}


void Widget::on_pushButtonMoveToPosition_clicked()
{
    // If motor is moving state,
    if(m_MotorStatus[m_nSelectedAxisNo] & ACSC_MST_MOVE) return;

    // Seconds arguement '0', it means absolute position (no option)
    double distance = ui->lineEditPosOrDistance->text().toDouble();
    if(!m_controller.toPoint(m_hAcsComm, 0, m_nSelectedAxisNo, distance, NULL))
    {
        qDebug() << "Move to Position (Absolute position) command error";
    }
}


void Widget::on_pushButtonMoveDec_clicked()
{
    // If motor is moving state,
    if(m_MotorStatus[m_nSelectedAxisNo] & ACSC_MST_MOVE) return;

    double distance = ui->lineEditPosOrDistance->text().toDouble();
    // Move relative position (from current position)
    if(!m_controller.toPoint(m_hAcsComm, ACSC_AMF_RELATIVE, m_nSelectedAxisNo, distance * (-1), NULL))
    {
        qDebug() << "Move Decrement command error";
    }
}


void Widget::on_pushButtonMoveInc_clicked()
{
    // If motor is moving state,
    if(m_MotorStatus[m_nSelectedAxisNo] & ACSC_MST_MOVE) return;

    double distance = ui->lineEditPosOrDistance->text().toDouble();
    // Move relative position (from current position)
    if(!m_controller.toPoint(m_hAcsComm, ACSC_AMF_RELATIVE, m_nSelectedAxisNo, distance, NULL))
    {
        qDebug() << "Move Decrement command error";
    }
}


void Widget::on_pushButtonNegtive_clicked()
{
    double m_dJogVelocity = ui->lineEditJogVelocity->text().toDouble();
    bool m_bSetJogVelocity = ui->checkBoxJogUseVelocity->isChecked();
    if(m_bSetJogVelocity)
    {
        // Jog command with velocity
        if(!m_controller.jog(m_hAcsComm, ACSC_AMF_VELOCITY, m_nSelectedAxisNo, m_dJogVelocity * (-1), NULL))
        {
            qDebug() << "Jog negative, velocity move command error";
        }
    }
    else
    {
        // Jog command without velocity
        if(!m_controller.jog(m_hAcsComm, 0, m_nSelectedAxisNo, ACSC_NEGATIVE_DIRECTION, NULL))
        {
            qDebug()<< "Jog negative move command error";
        }
    }
}


void Widget::on_pushButtonPositive_clicked()
{
    double m_dJogVelocity = ui->lineEditJogVelocity->text().toDouble();
    bool m_bSetJogVelocity = ui->checkBoxJogUseVelocity->isChecked();

    if(m_bSetJogVelocity)
    {
        if(!m_controller.jog(m_hAcsComm, ACSC_AMF_VELOCITY, m_nSelectedAxisNo, m_dJogVelocity, NULL))
        {
            qDebug() << "Jog positive, velocity move command error";
        }
    }
    else
    {
        if(!m_controller.jog(m_hAcsComm, 0, m_nSelectedAxisNo, ACSC_POSITIVE_DIRECTION, NULL))
        {
            qDebug() << "Jog positive move command error";
        }
    }
}


void Widget::on_pushButtonMotinEnd_clicked()
{

}


void Widget::on_pushButtonProgramEnd_clicked()
{

}


void Widget::on_pushButtonInput_clicked()
{

}


void Widget::on_pushButtonSend_clicked()
{

}

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6