/** \file
 *
 *  Contains the MassServo class declaration.
 *
 *  MassServo.h should only be included by MassServo.cpp
 *  Other classes should include MassServoIF.h
 *
 *  Copyright (c) 2007,2008,2009 MBARI
 *  MBARI Proprietary Information.  All Rights Reserved
 */

#ifndef MASSSERVO_H_
#define MASSSERVO_H_

#include "EZServoServo.h"
#include "io/UartStream.h"

class UniversalDataWriter;

/**
 *  This is the device driver for the EZServo that controls the vehicle's
 *  movable mass.  Since it shares the same RS-485 bus with the other EZServos,
 *  it is a child class of EZServoServo, which has a static instance of
 *  the StdUart class to interact with the bus.
 *
 *  MassServo.h should only be included by MassServo.cpp
 *  Other classes should include MassServoIF.h
 *
 *  \ingroup modules_controller
 */
class MassServo : public EZServoServo
{
public:
    MassServo( const Module* module );
    virtual ~MassServo();

    virtual void run();

    /// Do what needs to be done to run
    /// Similar to initialize, in old init/run/uninit sequence
    virtual RunState start();

    /// Might follow a STOP...START sequence
    virtual RunState starting();

    /// Pause for a short period (indicated by pauseTime)
    virtual RunState pause();

    /// Should eventually follow a PAUSE request: should set continueTime
    virtual RunState paused();

    /// Resume from PAUSE
    virtual RunState resume();

    /// Might follow a PAUSE...RESUME sequence
    virtual RunState resuming();

    /// Should eventually follow a START request or RESETTING
    virtual RunState runnable();

    /// Might occur in case of Error
    virtual RunState resetting()
    {
        return stop();
    }

    /// Initial state -- can be later followed by START
    virtual RunState stop();

    virtual RunState stopping();

    /// Initial state -- can be later followed by START
    virtual RunState stopped();

    // Shuts down motor controllers
    void uninitialize( void );

    /// Should return [myNamespace]::SIMULATE_HARDWARE, or [myNamespace]::POWER, etc
    virtual ConfigURI getConfigURI( ConfigOption configOption ) const;

private:

    // Note that the copy constructor below is private and not given a body.
    // Any attempt to call it will return a compiler error.
    MassServo( const MassServo& old ); // disallow copy constructor

    // Instance of load controller
    LoadControl loadControl_;

    // The outputs themselves
    UniversalDataWriter* massPositionWriter_;

    // The inputs
    DataReader* massPositionReader_;

    // Configuration readers
    ConfigReader* totalTksCfgReader_;          // Total encoder ticks for full mass shift travel
    ConfigReader* tksPerMMCfgReader_;          // Number of ticks for one rotation (1 mm of travel)
    ConfigReader* deviationDistanceCfgReader_; // Deviation allowed between expected and actual
    ConfigReader* massDeadbandCfgReader_;

    // returns true if data is requested from one of the readers
    bool isDataRequested();

    // returns true if a new position has been commanded
    bool isNeeded();

    typedef enum
    {
        INITIALIZE,   // Program basic initialization into EEPROM
        WAIT,         // Wait for EEPROM write to finish
        HOME,         // Do any centering/homing, etc if needed
        EXECUTE,      // Execute any stored programs
        VERIFY,       // Confirm operable and no errors
        DONE,         // Ready to run
    } StartupSequence;

    StartupSequence startup_;

    // indicates whether things are ok to run
    bool ok_;

    // Actual and commanded positions
    float actualMassPosition_;
    float cmdMassPosition_;

    // Debugging outputs
    bool debug_;

    // Timeouts
    Timespan homingTimeout_;

    //------------------- vehicle parameters --------------------------*/
    // Mass Shift
    float totalTksCfg_;      // Total encoder ticks for full mass shift travel
    float tksPerMMCfg_;      // Number of ticks for 1 mm of travel //*** DEBUG real motor is ~ 272 ticks/mm
    float deviationDistCfg_; // Number of encoder ticks deviation allowed between expected and actual
    float massDeadbandCfg_;

    //-----------------------------------------------------------------*/

    // Mass shift variables
    float lastCmdMassPos_;   // Stores the previous commanded position from control
    float lastActMassPos_;   // Stores the previous actual position of the mass shifter
    bool massShiftHomed_;    // True = mass shifter is done being initialized and homing

    // read vehicle config variables
    virtual bool readConfig( void );

    // Initialization routines. Returns true if initialization completed without error
    bool initMass( void );

    bool massRdy_;

    // Calls EZServoServo::checkResponse for status and sets errors as applicable.
    // If error == OVERLOAD_ERROR, calls initMass().
    bool checkResponse( bool checkForReady );

    // Waits for the mass to complete a transit
    bool waitForHoming( void );

};

#endif /*MASSSERVO_H_*/
