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

#include "Run.h"
#include "Runtask.h"
#include "MyStringArray.h"
#include "CheckSwitch.h"
#include "structure.h"
#include "EMS.h"
#include "LotMsg.h"
#include "SemiE10RS.h"

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

// Gary 25Aug10 V1.14.01, OPE machine status
enum OPE_MACHINE_STATUS
{
    OPE_APPLICATION_START,
    OPE_IDLE,
    OPE_LOT_OPEN,
    OPE_LOT_CLOSE,
    OPE_MC_START,
    OPE_MC_AUTO_STOP,
    OPE_MC_MANUAL_STOP,
    OPE_MC_JAM_STOP,
    OPE_MC_EMERGENCY_STOP,
    OPE_MC_JAM,
    OPE_MC_JAM_RESET,
    OPE_MC_STOP_DUE_TO_WARNING,
    OPE_NO_MATERIAL_MODE,
    OPE_PRODUCTION_MODE,
    OPE_SCHEDULED_ACTIVITY_MODE,
    OPE_ENGINEERING_MODE,
};

// Gary 25Aug10 V1.14.01, OPE machine stop mode
enum MC_STOP_MODE
{
    MC_STOP_MODE_AUTO,
    MC_STOP_MODE_MANUAL,
    MC_STOP_MODE_JAM,
};

class MCCTRDLLCLASS CRunCtrl : public CRunTask
{
public:
    CRunCtrl(int numRun, CRun **run, CLotMsg *pLotMsg);
    ~CRunCtrl();

public:
// Gary 22Jul11, V1.15.02
// method to query if lot is opened
    bool IsLotOpened();

// Gary 22Jul11, V1.15.02
// method to informed runctrl that lot is opened and ready for run and
// it is used only during recovery when application restarted during processing
// of a lot.
// During normal operation, this method is not used.
    void LotOpened();

    bool IsMaintenanceOperationCompleted(int nModuleNo);
    void StopMaintenanceOperation(int nModuleNo);
    void StartMaintenanceOperation(int nModuleNo);
    void UpdateEMSUnitCount();
    void SetEMSOutput(int nNo, COutput *pOutput);
    void SetEMSInput(int nNo, CInput *pInput);
    bool CanMachineRun();
    void InformAllRunCurtainSensorActivated();
    void DisableJogMode();
    void EnableJogMode();
    bool SetOutputState(int nOutput, bool bState);
    bool IsHardwareSafetyBypass();
    bool IsStopButtonActivated(void);
    void BypassDoor(BOOL bState);
    void BypassCurtain(BOOL bState);
    void SetSystemOutput(int nOutput, COutput *pOutput);
    bool IsEngineeringBypass();
    bool IsCurtainBypass();
    bool IsDoorBypass();
    void SetSystemInput(int nSwitch, CInput *pInput);
    void ResetPowerUpComplete(void);
    void SetModuleWarning(BOOL bState);
    void SetSystemWarning(BOOL bState);
    void SetIndicator(int nIndicator, COutput *output);
    void GetLightStatus(CUIntArray *nLight);
    void InitParameters(void);
    void CloseLot(void);
    void EmStopRelease(void);
// Operations
    int Start();
// void Stop();

// Gary 26Aug10 V1.14.01, added parameter to indicate if the stop operation is Manual or Auto Stop
    void Stop(bool bAuto = true);

    void Reset();
    void Restart();
    void EmStop();

//  GUI will call this function to set all sequence to Maintenance Mode
    void SetMaintenanceMode();

//  GUI will call this function to clear all sequence Maintenance Mode
    void ResetMaintenanceMode();

//  Gui will call this function to home motor in Maintenance Mode
    void MaintenanceHomeMotor(int iRunSeqNo, int iMaintModuleNo, int iMotor);

//  Gui will call this function to Move motor in Maintenance Mode
    void MaintenanceMoveMotor(int iRunSeqNo, int iMaintModuleNo, int iMotor, int iPos,
                              double dPos, int iSpeed);

//  GUI will call this function to Stop motor in Maintenance Mode
    void MaintenanceStopMotor(int iRunSeqNo, int iMaintModuleNo, int iMotor);

//  GUI will call this function to on/off output in Maintenance Mode
    void MaintenanceOutput(int iRunSeqNo, int iMaintModuleNo, int iOutputNo, bool bOn);

//  GUI will call this function to turn on/off motor in  Maintenance Mode
    void MaintenanceMotorOnOff(int iRunSeqNo, int iMaintModuleNo, int iMtrNo, bool bOn);

    void StopAllMotor();

// Purging

// Threads
    UINT RunThread();

// Utilities
    int  GetMcState();
    BOOL IsModified();
    void DisplayMsg(CDC *pDC, CString& msg, int xOff, int yOff, BOOL debug = false, BOOL debug_jam = false);

    BOOL IsAllPowerUp(void);

//  open lot
    void OpenLot();

//  get all SemiE10 timing
    StSemiE10 GetCurrentTimeInfo();

//  Get Semi Timing Time
    long double GetSemiE10Time(int iEvt);

//  get total uptime and down equipment state
    long double GetTotalTime();

//  get non scheduled time
    long double GetNonScheduledTime();

//  get operations time
    long double GetOperationsTime();

//  get uptime
    long double GetUptime();

//  get Downtime
    long double GetDowntime();

//  get engineering time
    long double GetEngineeringTime();

//  get manufacturing time
    long double GetManufacturingTime();

//  get productive time
    long double GetProductiveTime();

//  get standby time
    long double GetStandbyTime();

//  get unscheduled downtime
    long double GetUnscheduledDowntime();

//  get scheduled downtime
    long double GetScheduledDowntime();

//  Get Assist time in mins
    long double GetAssistTime();

//  get failure time in mins
    long double GetFailureTime();

//  get Mean Time Between Assist
    long double GetMTBA();

//  get Mean Time between Failure
    long double GetMTBF();

//  get Mean Time To Repair
    long double GetMTTR();

//  get Mean Time Between Interrupt
    long double GetMTBI();

//  get Units Per Hour
    long GetUPH();

//  get jam count
    long GetJamCnt();

//  get assist count
    long GetAssistCnt();

//  get failure count
    long GetFailureCnt();

//  record lot no to Lot time info
//  void RecordLotNo(LPCTSTR lpLotNo, LPCTSTR lpCurTime);

//  save lot info to database
    void SaveLotInfo(LPCTSTR lpLotNo, LPCTSTR lpCurTime);

//  get Lot record semie10 timing
    StSemiE10 GetLotRecord(CString csLotNo, CString csLotStartTime);

//  Delete lot record
    void DeleteLotRecord(CString csLotNumber, double dStartDateTime);

//  Get SemiE10 table name
    CString GetSemiE10TableName();

//  get all equipment substate field name
    CMyStringArray GetAllSemiE10FieldName();

//  Get SemiE10 combine lot record
    StSemiE10 GetSemiE10CombineLotRecord(CString lpLotNo);

//  Start all equipment state. Possible to start all equipment state?
    void StartAllEquipState();

//  Stop all equipment state
    void StopAllEquipState();

//  Reset all equipment state
    void ResetAllEquipState();

//  Get jam start date time
    COleDateTime GetJamStartTime();

//  Get jam End date time
    COleDateTime GetJamEndTime();

//  Get current Date time
    COleDateTime GetCurrentTime();

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

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

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

//  send packet in maintenance mode
    void MaintenanceSendPacket(LPCTSTR IpAddress, int iPortNo, LPCTSTR lpcSendMsg);

//  connect port in maintenance mode
    void MaintenanceConnectPort(LPCTSTR IpAddress, int iPortNo);

//  connect port in maintenance mode
    void MaintenanceDisconnectPort(LPCTSTR IpAddress, int iPortNo);

//  find Gui Window Handler
    void FindGuiWindow();

//  Pass General Message to one or all modules(iModuleNo = -1)
    void SetGenMsg(int iModuleNo, int iMsg);

// Attributes
    int m_mcState;

    BOOL m_bDiagnose;

    BOOL* m_pbMaintenanceMode;

    enum
    {
        ALL_MODULES = -1,
    };

// Gary 24Mar10, V1.13.4, change this object from private to public
    CSemiE10RS m_SemiE10;

// Gary 16Jun10, implement Warning Message with Buzzer disable feature, START
// as well as Authroization Level to clear Jam
    CPtrList m_ptrListJam;
    CPtrList m_ptrListWarning;

    CLotMsg *m_pLotMsg;

    CArray<int, int> m_naDisabledBuzzerMsgID;

// 0 - Operator
// 1 - Technician
// 2 - Engineer
// 3 - SuperUser
    struct JAM_AUTHORIZATION
    {
        int nJamID;
        int nAuthorizationLevel;
    };

    CArray<JAM_AUTHORIZATION, JAM_AUTHORIZATION> m_naAuthroizationLevel;

    void AddDisabledBuzzerMsg(int nMsgID);

    int GetHighestJamClearanceAuthorizationLevel();

// Gary 16Jun10, implement Warning Message with Buzzer disable feature, END
// as well as Authroization Level to clear Jam

//  Set to True to Disable CRunCtrl Door Control Seqence when Machine state is not MC_RUNNING Or MC_INITIALIZING
    void ByPassDoorControl(bool bByPassDoorCtrl);

//  return true when acknowledged that Door Control has been by passed
    bool IsDoorControlByPassed();

#if _MSC_VER >= 1600 // Version Higher than or equal to VC2010
/// Set whether run modules init parameters concurrently
    void SetConcurrentIniPara(bool bConcurrentIniPara);

/// returns true if run modules init parameters concurrently else returns false
    bool GetConcurrentIniPara();
#endif

private:
    void OnPowerUpCompleted();
    void DoorControl();
    enum
    {
        ESTOP_MC,
        STOP_MC,
        ESTOP_RELEASE_MC,
        START_MC,
        RESET_MC,
        RESTART_MC,
        MAX_MC_CTRL,
    };

    void SetLightStatus(void);
    void InitLocalParameters(void);
    BOOL IsCloseLotComplete(void);
    BOOL IsWarning(void);
// Operations
    void        JamResetAllRun(void);
    void        RestartAllRun();
    void        SuspendAllRun();
    bool        ResumeAllRun();
    inline void SetMcState(int state);
    BOOL        IsJam();

// Run Time Operations
    void StartRunTime();
    void StopRunTime(int state);

// Machine State
    BOOL CheckMachineState();
    void SaveMachineState();

    void EndAllRun(void);

//  check current mode is to set or reset maintenance mode
    void CheckMaintMode();

//  start jam time
    void StartJamTime();

//  update time for euipment time calculation
    void UpdateTime();

//  Emergency stop release control
    void EmStopReleaseCtrl(void);

//  start machine control
    int StartCtrl();

//  stop machine control
// void StopCtrl();

// Gary 26Aug10 V1.14.01, added parameter to indicate if the stop operation is Manual or Auto Stop
    void StopCtrl(int nStopCode);

//  jam reset machine control
    void ResetCtrl();

//  restart machine control
    void RestartCtrl();

//  Emstop machine control
    void EmStopCtrl();

//  check current machine control
    void CheckMcCtrl();

//  reset all machine contrl flag
    void ResetMcCtrlFlag();

//  check current machine no material
    void CheckMcNoMaterial();

//  post jam reset message to gui
    void PostJamResetToGui();

//  check whether to post clear no material warning
    void CheckClearNoMaterialWarn();

//  inform all run modules close lot has completed
    void OnCloseLotCompleted();

/// Inform all Run Modules EStop Pressed
    void InformAllRunEStopPressed();

// Gary 16Aug10 V1.14.01, method to inform UI of OPE Status
    bool PostOPESignal(unsigned int uintSignal);

    bool PostOPEStopCode(int nStopCode);

//  Attributes
    int m_machineStateCheckCount;

    CMutex m_maintMutex;  // mutex to synchronised set or reset maintenance mode
    CMutex m_mcCtrlMutex; // mutex to synchronised machine control

// run modules
    int    m_numRun;
    CRun **m_run;
    BOOL   m_bCloseLot;

    LIGHT_CONFIG m_lightConfig[NUM_MC_STATE];
    LIGHT_CONFIG m_currentLightStatus;
    BOOL         m_bBlink;

    COutput *m_copLightRed;
    COutput *m_copLightAmber;
    COutput *m_copLightGreen;
    COutput *m_copBuzzer;

    COutput *m_copStartIndicator;
    COutput *m_copStopIndicator;
    COutput *m_copResetIndicator;

    BOOL m_bSystemWarning;
    BOOL m_bModuleWarning;

    bool m_bResetMaintMode;    // flag to detemine reset maintenance mode
    bool m_bMaintMode;         // flag to determine set to maintenance mode
    bool m_bCloseLotCompleted; // flag to determine close lot completed
    bool m_bInMaintenanceMode; // flag to indicate at least one module is in maintenance

// Gary 24Mar10, V1.13.4, change this object from private to public
// CSemiE10RS m_SemiE10;

    bool m_bMcCtrl[MAX_MC_CTRL]; // flag to determine machine control

//  flag to determine whether no material warning has been post to GUI before
//  true  = post no material warning before
//  false = have not post no material warning
    bool m_bPostNoMaterial;

    COleDateTime m_odtCurrentTime;  // current time
    COleDateTime m_odtJamStartTime; // jam Start time
    COleDateTime m_odtJamEndTime;   // jam end time

    HWND m_hwndMainApp;             // gui window handler

    CCheckSwitch m_runCheckSwitch;

    CEMS m_runEMS;

// indicate if in Jog Mode for stepping purpose
    bool m_bJogMode;

// flag to disable buzzer during warning in Machine Stop Mode
    bool m_bBuzzerOff;

// Gary 26Aug10 V1.14.01, flag to indicate if it's a manual/auto stop
    bool m_bAutoStopRequested;

// Gary 22Jul11, V1.15.02, flag to indicate if a lot is open and machine is allowed to operate
    bool m_bLotOpened;

// true = By Pass Door Control when  machine state is not initialising or not running
    bool m_bByPassDoorControl;

//  true = runctrl acknowledged control of door lock has been by passed
    bool m_bDoorControlByPassed;

#if _MSC_VER > 1200 // Version Higher than VC6
/// true == call run modules initparameters concurrently else call run modules initparameters sequently as in VC6 MITLIB
    bool m_bConcurrentIniPara;
#endif
};

#endif // !defined __RUNCTRL_H__
