Boost logo

Boost :

From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2008-08-26 11:10:40


andrea carbone wrote:
> Hello,
>
> I need to handle the states of a process.
> The process will be implemented in a class containing all required methods
> and data.
> Think for example to sensor management.
> Init (connect the device).
> Setup (configuration).
> Idle (nop).
> AcquireSingleData,
> AcquireMultiData ...
> etc.
>
> I need a unique instance of the sensor object.
>
> How can I make all the states aware of this unique instance?
> Avoiding singletons ... if possible.
>
> Is there some way in boost::fsm to automatically realize this design?

No, the library does not provide any way to control instancing of FSM or
other objects, if that is what you mean. However, if you already have a
singleton of your object that represents the sensor, you can pass a
reference or pointer to it in an initialization event to the FSM.

  struct Sensor : noncopyable
  {
    // Returns the singleton instance
    static Sensor* get();

  private:
    Sensor();
  };

  struct InitEvent { Sensor* pSensor; };

  typedef mpl::vector<
    Uninitialized,
    Init,
    Setup,
    ...
>::type States_t;

  // The struct contains common data for all states
  struct Common
  {
    Sensor* m_pSensor;
  };

  struct Uninitialized :
    fsm::state< Uninitialized, States_t >,
    virtual Common
  {
    void on_process(InitEvent const& evt)
    {
      m_pSensor = evt.pSensor;
      switch_to< Init >();
    }
  };

  ...

  fsm::state_machine< States_t > fsm;
  fsm.process(InitEvent(Sensor::get()));

Alternatively, you can set the pointer directly in the FSM by using the
"get" method of the state machine.

  fsm.get< Common >().m_pSensor = Sensor::get();

But I would prefer the former way since it expresses the intent more
clearly.

Note that the pointer to the sensor is stored in a virtual base class of
all states, which means that every state uses the single m_pSensor pointer.

I hope that helps.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk