// Start =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// General information section.
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// $Author:yongkiang$ User who last changed the file
// $Date:1/2/2013 12:17:41 PM$ Date and time of last check in
// $Revision:1.0$ Visual SourceSafe version number
// $Workfile::   run.h                                                 $ Filename
// End =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
#if !defined __RUN_H__
#define __RUN_H__

#include "RunTask.h"
#include "OutputController.h"
#include "Utility.h"

enum MODE
{
    MODE_POWER_UP,
    MODE_AUTO,
    MODE_MAINTENANCE,
    MODE_UNKNOWN
};

enum STATE
{
    STATE_RUN,
    STATE_STOP
};

enum
{
    SLOW_SPEED,
    NORMAL_SPEED
};

// motor profile
enum
{
    HOME_START_SPEED,
    HOME_MAX_SPEED,
    HOME_ACC,
    HOME_DEC,
    HOME_PERCENTAGE,

    SLOW_START_SPEED,
    SLOW_MAX_SPEED,
    SLOW_ACC,
    SLOW_DEC,
    SLOW_PERCENTAGE,

    NORMAL_START_SPEED,
    NORMAL_MAX_SPEED,
    NORMAL_ACC,
    NORMAL_DEC,
    NORMAL_PERCENTAGE,

    SLOW_START_SPEED_LIMIT,
    SLOW_MAX_SPEED_LIMIT,
    SLOW_ACC_LIMIT,
    SLOW_DEC_LIMIT,
    SLOW_PERCENTAGE_LIMIT,

    NORMAL_START_SPEED_LIMIT,
    NORMAL_MAX_SPEED_LIMIT,
    NORMAL_ACC_LIMIT,
    NORMAL_DEC_LIMIT,
    NORMAL_PERCENTAGE_LIMIT,
};

#define MAX_WARNING_PER_MODULE  10

#ifdef  BUILD_MCCTRDLL
#define     MCCTRDLLCLASS   __declspec(dllexport)
#else
#define     MCCTRDLLCLASS   __declspec(dllimport)
#endif

#define     OPE_STATUS_UPDATE   100

class MCCTRDLLCLASS CRun : public CRunTask
{
public:
// Gary 26Aug10 V1.14.01, new method to inform UI of OPE status/signal
    bool PostOPESignal(unsigned int uinSignal);

    bool         IsMaintenanceOperationCompleted();
    void         StopMaintenanceOperation();
    void         StartMaintenanceOperation();
    bool         PostGeneralMessageToGUI(WPARAM wParam, LPARAM lParam);
    bool         PostMessageToGUI(int nMsg, WPARAM wParam, LPARAM lParam);
    void         WarningEx(int nWarningNo, bool bSet = true);
    void         UpdateMaintenanceMessage(int nMsg, bool bClearDisplay = false);
    bool         IsMaintenanceMode();
    bool         IsPowerUpMode();
    bool         IsAutoMode();
    int          GetMode();
    virtual void OnStopComplete();
    void         GetModuleEnable(CString csFilename, CString csSectionName, CString csKeyName);
    bool         IsModuleEnable();
    int          GetMaintenanceMoveProfile();
    void         MaintenanceCheckMotorComplete();     // request to start check maintenance motor move complete
    void         MaintenanceCheckMotorHomeComplete(); // request to start check maintenance motor move complete
    void         ResetPowerUpComplete(void);
    void         EndCloseLot(void);
    void         OnCloseLot(void);
    void         CloseLotComplete(void);
    BOOL         IsCloseLot(void);
    BOOL         IsCloseLotComplete(void);

//  reset close lot event
    void ResetCloseLot();

    void         Warning(int nID, BOOL bClear = FALSE);
    BOOL         GetCountJam(void);
    void         PowerUpRestart(void);
    void         AutoRestart(void);
    BOOL         IsJamCode(void);
    int          GetWarning(void);
    int          GetJam(void);
    BOOL         IsWarning(void);
    BOOL         IsPowerUpComplete(void);
    void         PowerUpComplete(void);
    virtual void InitParameters(void);

    CRun(int nID, CString csName, struct stModule *pstModule, int *iSequenceModuleNo = NULL);
    virtual ~CRun();

// gary 05jun03
    inline CString GetName(void)
    {
        return m_csName;
    }

    inline int GetID(void)
    {
        return m_nModuleId;
    }

    virtual BOOL PowerUpOperation(void);
    virtual BOOL AutoOperation(void);
    virtual BOOL MaintenanceOperation(void);

    void OnPowerUp(void);
    void OnStop(void);
    void OnJamReset(void);
    void OnAuto(void);
    BOOL IsStop(void);
    BOOL IsJam(void);
    BOOL GetWarningClear(void);

//  get warning code
    int GetWarningCode();

// Operations
    void Jam(int nJamID, bool bCount = true); // default count in jam

// Run state
    int GetState();

    void InMaintenance();                                                // this function will be executed in Maintenance Mode
    void OnMaintenance(bool bMaintenance);                               // call this function to set to Maintenance Mode

    void MaintenanceHomeMotor(int iMaintModuleNo, int iMotorNo);         // Function to home motor in Maintenance Mode
    void MaintenanceMoveMotor(int iMaintModuleNo, int iMotorNo, int iPos, double dPos,
                              int iSpeed);                               // Function to Move motor in Maintenance Mode
    void MaintenanceStopMotor(int iMaintModuleNo, int iMotorNo);         // Function to Stop motor in Maintenance Mode
    void MaintenanceOutput(int iMaintModuleNo, int iOutputNo, bool bOn); // Function to trigger output

//  Function to turn on/off motor in manitenance Mode
    void MaintenanceMotorOnOff(int iMaintModuleNo, int iMtrNo, bool bOn);

    bool IsMaintenanceHomeMotor();             // Function to check home motor in maintenance mode
    bool IsMaintenanceMoveMotorHomeComplete(); // Function to check motor move complete in maintenance mode

    bool IsMaintenanceMoveMotor();             // Function to check move motor in maintenance mode
    bool IsMaintenanceMoveMotorComplete();     // Function to check motor move complete in maintenance mode

    bool IsMaintenanceStopMotor();             // Function to check stop motor in maintenance mode
    bool IsMaintenanceOutput();                // Function to trigger output in maintenance mode
    bool IsMaintenanceOnOffMtr();              // Function to check turn on/off motor in maintenance mode
//  check if all maintenance operation completed
    bool IsMaintOperCompleted();

    double GetMaintenanceMoveMotorPos();       // Function to get Move Motor Position in maintenance mode

//  Function to get Move Motor Position in maintenance mode
    int GetMaintenanceMoveMotorPosIndex();
    int GetMaintenanceMoveMtrNo();             // Function to get Motor to move in maintenance mode
    int GetMaintenanceOutputToTrigger();       // Function to get output number to trigger in maintenance mode

//  Function to get output on/off status in maintenance mode
    bool GetMaintenanceOutputTriggerState();
    int  GetMaintenanceModuleNo();             // Function to get Maintenance module no
//  Function to get turn motor on/off state during maintenance mode
    bool GetMaintenanceOnOffState();

    void ClearMaintStopMtrFlag();              // clear m_bMaintenanceStopMtr flag
    void ClearMaintHmMtrFlag();                // clear m_bMaintenanceHmMtr flag

    void ClearMaintHmMtrCompleteFlag();        // clear m_bCheckMaintenanceHmMtrComplete flag

    void ClearMaintMoveMtrFlag();              // clear m_bMaintenanceMoveMtr flag

    void ClearMaintMoveMtrCompleteFlag();      // clear m_bCheckMaintenanceMoveMtrComplete flag

    void ClearMaintTriggerOutputFlag();        // clear m_bMaintenanceTriggerOutput flag
    void ClearMaintOnOffMtrFlag();             // clear m_bMaintenanceOnOffMtr flag

//  check if all module no material
    bool IsAllModuleNoMaterial();

//  runctrl call this function to clear no material flag
    void ClearAllNoMaterial();

//  check if jam has not been registered before
    BOOL IsJamNotRegistered();

//  open lot has been trigger by GUI
    virtual void OnOpenLot();

//  runctrl call power up restart
    virtual void OnPowerUpRestart();

//  set CUnitCntArray size. only one module should override this method!
    virtual void SetUnitCntArraySize();

//  clear auto restart flag
    void ClearAutoRestart();

//  check if machine has restart
    BOOL IsAutoRestart();

//  clear power up restart
    void ClearPowerUpRestart();

//  check if machine has restart
    BOOL IsPowerUpRestart();

//  send com data to modules in maintenance mode
    virtual void OnMaintenanceSendCom(LPCTSTR lpcComPort, int iBaudRate, int iDataBits,
                                      LPCTSTR lpcParity, float fStopBits, LPCTSTR lpcFlowCtrl, LPCTSTR lpcSendMsg);

//  send open com to modules in maintenance mode
    virtual void OnMaintenanceOpenCom(LPCTSTR lpcComPort, int iBaudRate, int iDataBits,
                                      LPCTSTR lpcParity, float fStopBits, LPCTSTR lpcFlowCtrl);

//  send close com to modules in maintenance mode
    virtual void OnMaintenanceCloseCom(LPCTSTR lpcComPort, int iBaudRate, int iDataBits,
                                       LPCTSTR lpcParity, float fStopBits, LPCTSTR lpcFlowCtrl);

//  send packet to modules in maintenance mode
    virtual void OnMaintenanceSendPacket(LPCTSTR IpAddress, int iPortNo, LPCTSTR lpcSendMsg);

//  send connect port to modules in maintenance mode
    virtual void OnMaintenanceConnectPort(LPCTSTR IpAddress, int iPortNo);

//  send connect port to modules in maintenance mode
    virtual void OnMaintenanceDisconnectPort(LPCTSTR IpAddress, int iPortNo);

//  get main application window handler
    void GetHwnd();

//  Get General Message
    virtual void GetGenMsg(int iMsg);

//  CRunCtrl inform all run modules that close lot has completed.
//  For run modules to do clean up after close lot
    virtual void OnCloseLotCompleted();

//  Get the previous mode
    int GetPrevMode();

/// For run modules to do clean up Before close applications
    virtual bool OnDestroy()
    {
        return true;
    }

/// For run modules to do clean up when estop button pressed
    virtual bool OnEStopPressed()
    {
        return true;
    }

/// For run modules to do necessary actions when curtain sensors acivated
    virtual bool OnCurtainSensorActivated()
    {
        return true;
    }

/// To inform run module that system is in jog mode
    virtual bool OnSysJogMode(bool bEnable);

//  determine whether to trace data
    bool m_bTraceData;

//  determine whether to trace timing data
    bool m_bTraceTimingData;

//  CRunCtrl inform all run modules that power up has completed.
//  For run modules to do clean up after system power up
    virtual void OnPowerUpCompleted();

protected:
    stModule *m_pstModule;
    HWND      m_hwndMainApp;
    int      *m_iSequenceModuleNo; // integer array to keep track which module belong to which sequence

//  get the module ID
    int GetModuleId();

//  run module to set home motor in maintenance mode
    void SetMaintenanceHomeMotor(int iMotorNo);

//  individual module call this function to set to no material
    void SetNoMaterial(bool bNoMaterial);

//  call this function to return the no material status of module
    bool GetNoMaterialStatus(int iModuleNo);

//  if repeat jam only display jam, else new jam display and count this jam
    void CallJam(int iJamNo);

//  clear jam occured before flag
    void ClearJamOccuredBeforeFlag();

// event to request motor stop in Maintenance Mode
    CEvt m_evtMaintStop;
    CEvt m_evtMcStop;
    CEvt m_evtEol;
    CEvt m_evtSysJogMode;

private:
    void InPowerUp(void);
    void InAuto(void);
    UINT RunThread();

    struct stWarning
    {
        int m_nWarningCode;   // warning code
        bool m_bWarningClear; // warning state, to clear or display
        bool m_bWarning;      // is there warning
    };

    CArray<stWarning, stWarning> m_astWarning;

// Gary 03jun03 start
    BOOL m_bWarningClear;
    BOOL m_bCountJam;
    BOOL m_bJamCode;
    BOOL m_bWarning;
    BOOL m_bPowerUpComplete;
    BOOL m_bJamflag;
    BOOL m_bAutoRestart;
    BOOL m_bPowerUpRestart;
    int  m_nMode;
    int  m_nPrevMode;
    int  m_nState;
    int  m_nJamCode;
    int  m_nWarningCode;
// Gary 03jun03 end

// gary 05jun03
    int m_nModuleId;

// Run Events
    int m_state;

    CString m_csName;
    BOOL    m_bCloseLotComplete;

    bool m_bMaintenanceHmMtr;                // true = Home Motor in maintenance mode

    bool m_bCheckMaintenanceHmMtrComplete;   // true = check motor home move complete

    bool m_bMaintenanceMoveMtr;              // true = Move motor to position in maintenance mode

    bool m_bCheckMaintenanceMoveMtrComplete; // true = check motor move complete

    double m_dMaintMovePos;                  // Pos of the motor to move in maintenance mode
    int    m_iMaintMovePos;                  // Pos index of the motor to move in maintenance mode
    int    m_iMaintenanceMtrNo;              // Motor number to move in maintenance mode
    bool   m_bMaintenanceStopMtr;            // true = Stop Motor in maintenance mode
    bool   m_bOn;                            // true = on, false = false
    int    m_iOutputNo;                      // output no to trigger
    bool   m_bMaintenanceTriggerOutput;      // true = Trigger output in maintenance mode
    int    m_iMaintModule;                   // Maintenance module no

    bool m_bMtrOn;                           // true = turn mtr on, false = turn mtr off during maintenance mode
    bool m_bMaintenanceOnOffMtr;             // true = On/Off Motor in maintenance mode

    int m_iMaintenanceMovePosSpeed;

//  all module no material status
//  true = current module no material, false = current module got material
    static bool *m_bNoMaterial;
    static int   m_iNoOfInstance; // keep track no of instance of this class

//  to determine whether jam has been registered
//  true = registered , false = unregistered
    bool m_bJamRegistered;

//  to determine whether this is a repeat jam
//  true = repeat jam do not count this jam, false = new jam count this jam
    bool m_bJamOccuredBefore;

    bool m_bModuleEnable;

// mutex to lock the warning message array
    CMutex m_WarningMutex;

// Gary 12Aug09
// flag to determine if maintenance operation is completed
    bool m_bMaintenanceOperationCompleted;
};

#endif // !defined __RUN_H__
