MIRA
tutorials/MeanCalculator.C


Tutorial: Creating a Unit that Subscribes to Data

#include <fw/MicroUnit.h>
#include <deque>
using namespace mira;
namespace tutorials {
class MeanCalculator : public MicroUnit
{
MIRA_OBJECT(MeanCalculator)
public:
MeanCalculator();
template<typename Reflector>
void reflect(Reflector& r)
{
}
protected:
virtual void initialize();
private:
void onNewData(ChannelRead<float> data);
private:
std::deque<float> mQueue;
Channel<float> mMeanChannel;
};
MeanCalculator::MeanCalculator()
{
}
void MeanCalculator::initialize()
{
subscribe<float>("FloatChannel", &MeanCalculator::onNewData);
mMeanChannel = publish<float>("MeanChannel");
}
void MeanCalculator::onNewData(ChannelRead<float> data)
{
mQueue.push_back(data->value());
if (mQueue.size() > 10)
mQueue.pop_front();
float sum = 0.0;
foreach(float f, mQueue)
sum += f;
float mean = sum / mQueue.size();
std::cout << "MeanCalculator: " << mean << std::endl;
ChannelWrite<float> w = mMeanChannel.write();
w->value() = mean;
}
}
MIRA_CLASS_SERIALIZATION(tutorials::MeanCalculator, mira::MicroUnit );