<commit_before>/* $Id: middlewareTimerTests.cpp,v 1.1.2.5 2012/11/30 17:32:33 matthewmulhern Exp $
 *
 * OpenMAMA: The open middleware agnostic messaging API
 * Copyright (C) 2011 NYSE Technologies, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include <gtest/gtest.h>
#include "mama/mama.h"
#include "MainUnitTestC.h"
#include <iostream>
#include "bridge.h"
#include "mama/types.h"

using std::cout;
using std::endl;

class MiddlewareTimerTests : public ::testing::Test
{
protected:
    MiddlewareTimerTests(void);
    virtual ~MiddlewareTimerTests(void);

    virtual void SetUp(void);
    virtual void TearDown(void);

    mamaBridge mBridge;
};

MiddlewareTimerTests::MiddlewareTimerTests(void)
{
}

MiddlewareTimerTests::~MiddlewareTimerTests(void)
{
}

void MiddlewareTimerTests::SetUp(void)
{
	mama_loadBridge (&mBridge,getMiddleware());
}

void MiddlewareTimerTests::TearDown(void)
{
}

static void MAMACALLTYPE onTick(mamaTimer timer, void* closure)
{
}

static void MAMACALLTYPE onTimerDestroy(mamaTimer timer, void* closure)
{
}
/*===================================================================
 =               mamaTimer bridge functions                          =
 ====================================================================*/

TEST_F (MiddlewareTimerTests, create)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge,&mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

}

TEST_F (MiddlewareTimerTests, createInvalidResult)
{
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(NULL, nativeQueueHandle,
                                              action, onTimerDestroyed,
                                              interval, parent, closure));
}

TEST_F (MiddlewareTimerTests, createInvalidNativeQueueHandle)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, NULL,
                                              action, onTimerDestroyed,
                                              interval, parent, closure));
}

TEST_F (MiddlewareTimerTests, createInvalidActionCB)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,
                                              NULL, onTimerDestroyed,
                                              interval, parent, closure));
}

TEST_F (MiddlewareTimerTests, createInvalidDestroyCB)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,
                                              action, NULL,
                                              interval, parent, closure));
}

/* TODO: Determine if interval maybe a NULL value */
TEST_F (MiddlewareTimerTests, DISABLED_createInvalidInterval)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,
                                              action, onTimerDestroyed,
                                              NULL, parent, closure));
}

TEST_F (MiddlewareTimerTests, createInvalidParent)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,
                                              action, onTimerDestroyed,
                                              interval, NULL, closure));
}

TEST_F (MiddlewareTimerTests, destroy)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge, &mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerDestroy(timer));

}

TEST_F (MiddlewareTimerTests, destroyInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerDestroy(NULL));
}

TEST_F (MiddlewareTimerTests, reset)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge,&mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerReset(timer));

}

TEST_F (MiddlewareTimerTests, resetInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerReset(NULL));
}

TEST_F (MiddlewareTimerTests, setInterval)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;
    mama_f64_t    newInterval   =             10;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge,&mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerSetInterval(timer,newInterval));

}

TEST_F (MiddlewareTimerTests, setIntervalInvalidTimerBridge)
{
    mama_f64_t  interval = 500;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerSetInterval(NULL,interval));
}

/* TODO: Determine if interval can be set to a NULL value (0.0 in this case) */
TEST_F (MiddlewareTimerTests, DISABLED_setIntervalInvalidInterval)
{
    timerBridge timer = (timerBridge) NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerSetInterval(timer,NULL));
}

TEST_F (MiddlewareTimerTests, getInterval)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;
    mama_f64_t    newInterval   =             10;
    mama_f64_t    testInterval  =             5;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge,&mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerSetInterval(timer,newInterval));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerGetInterval(timer,&testInterval));

    ASSERT_EQ(testInterval, newInterval);

}

TEST_F (MiddlewareTimerTests, getIntervalInvalidTimerBridge)
{
    mama_f64_t  interval = 500;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerGetInterval(NULL,&interval));
}

TEST_F (MiddlewareTimerTests, getIntervalInvalidInterval)
{
    timerBridge timer = (timerBridge) NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerGetInterval(timer,NULL));
}
<commit_msg>UNIT TESTS: Disabling the invalid timer destroy callback test.<commit_after>/* $Id: middlewareTimerTests.cpp,v 1.1.2.5 2012/11/30 17:32:33 matthewmulhern Exp $
 *
 * OpenMAMA: The open middleware agnostic messaging API
 * Copyright (C) 2011 NYSE Technologies, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include <gtest/gtest.h>
#include "mama/mama.h"
#include "MainUnitTestC.h"
#include <iostream>
#include "bridge.h"
#include "mama/types.h"

using std::cout;
using std::endl;

class MiddlewareTimerTests : public ::testing::Test
{
protected:
    MiddlewareTimerTests(void);
    virtual ~MiddlewareTimerTests(void);

    virtual void SetUp(void);
    virtual void TearDown(void);

    mamaBridge mBridge;
};

MiddlewareTimerTests::MiddlewareTimerTests(void)
{
}

MiddlewareTimerTests::~MiddlewareTimerTests(void)
{
}

void MiddlewareTimerTests::SetUp(void)
{
	mama_loadBridge (&mBridge,getMiddleware());
}

void MiddlewareTimerTests::TearDown(void)
{
}

static void MAMACALLTYPE onTick(mamaTimer timer, void* closure)
{
}

static void MAMACALLTYPE onTimerDestroy(mamaTimer timer, void* closure)
{
}
/*===================================================================
 =               mamaTimer bridge functions                          =
 ====================================================================*/

TEST_F (MiddlewareTimerTests, create)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge,&mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

}

TEST_F (MiddlewareTimerTests, createInvalidResult)
{
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(NULL, nativeQueueHandle,
                                              action, onTimerDestroyed,
                                              interval, parent, closure));
}

TEST_F (MiddlewareTimerTests, createInvalidNativeQueueHandle)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, NULL,
                                              action, onTimerDestroyed,
                                              interval, parent, closure));
}

TEST_F (MiddlewareTimerTests, createInvalidActionCB)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,
                                              NULL, onTimerDestroyed,
                                              interval, parent, closure));
}

TEST_F (MiddlewareTimerTests, DISABLED_createInvalidDestroyCB)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,
                                              action, NULL,
                                              interval, parent, closure));
}

/* TODO: Determine if interval maybe a NULL value */
TEST_F (MiddlewareTimerTests, DISABLED_createInvalidInterval)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    mamaTimer     parent            = (mamaTimer)   NOT_NULL;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,
                                              action, onTimerDestroyed,
                                              NULL, parent, closure));
}

TEST_F (MiddlewareTimerTests, createInvalidParent)
{
    timerBridge   result            = (timerBridge) NOT_NULL;
    void*         nativeQueueHandle =               NOT_NULL;
    mamaTimerCb   action            = (mamaTimerCb) NOT_NULL;
    mamaTimerCb   onTimerDestroyed  = (mamaTimerCb) NOT_NULL;
    double        interval          =               0.0;
    void*         closure           =               NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,
                                              action, onTimerDestroyed,
                                              interval, NULL, closure));
}

TEST_F (MiddlewareTimerTests, destroy)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge, &mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerDestroy(timer));

}

TEST_F (MiddlewareTimerTests, destroyInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerDestroy(NULL));
}

TEST_F (MiddlewareTimerTests, reset)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge,&mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerReset(timer));

}

TEST_F (MiddlewareTimerTests, resetInvalid)
{
    ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerReset(NULL));
}

TEST_F (MiddlewareTimerTests, setInterval)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;
    mama_f64_t    newInterval   =             10;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge,&mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerSetInterval(timer,newInterval));

}

TEST_F (MiddlewareTimerTests, setIntervalInvalidTimerBridge)
{
    mama_f64_t  interval = 500;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerSetInterval(NULL,interval));
}

/* TODO: Determine if interval can be set to a NULL value (0.0 in this case) */
TEST_F (MiddlewareTimerTests, DISABLED_setIntervalInvalidInterval)
{
    timerBridge timer = (timerBridge) NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerSetInterval(timer,NULL));
}

TEST_F (MiddlewareTimerTests, getInterval)
{
    timerBridge   timer         =             NULL;
    double        interval      =             1;
    mamaTimer     fakeParent    = (mamaTimer) NOT_NULL;
    void*         closure       =             NULL;
    void*         handle        =             NULL;
    mamaQueue     mDefaultQueue =             NULL;
    mama_f64_t    newInterval   =             10;
    mama_f64_t    testInterval  =             5;

    ASSERT_EQ(MAMA_STATUS_OK,
              mama_getDefaultEventQueue(mBridge,&mDefaultQueue));

    ASSERT_EQ(MAMA_STATUS_OK,
              mamaQueue_getNativeHandle(mDefaultQueue, &handle));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,
                                            onTimerDestroy, interval,
                                            fakeParent, closure));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerSetInterval(timer,newInterval));

    ASSERT_EQ(MAMA_STATUS_OK,
              mBridge->bridgeMamaTimerGetInterval(timer,&testInterval));

    ASSERT_EQ(testInterval, newInterval);

}

TEST_F (MiddlewareTimerTests, getIntervalInvalidTimerBridge)
{
    mama_f64_t  interval = 500;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerGetInterval(NULL,&interval));
}

TEST_F (MiddlewareTimerTests, getIntervalInvalidInterval)
{
    timerBridge timer = (timerBridge) NOT_NULL;

    ASSERT_EQ (MAMA_STATUS_NULL_ARG,
               mBridge->bridgeMamaTimerGetInterval(timer,NULL));
}
<|endoftext|>


<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/
#include "EulerAngleProvider2RGBAux.h"
#include "GrainTracker.h"
#include "EulerAngleProvider.h"
#include "Euler2RGB.h"

template<>
InputParameters validParams<EulerAngleProvider2RGBAux>()
{
  InputParameters params = validParams<AuxKernel>();
  params.addClassDescription("Output RGB representation of crystal orientation from user object to an AuxVariable. The entire domain must have the same crystal structure.");
  MooseEnum sd_enum = MooseEnum("100=1 010=2 001=3", "001");
  params.addParam<MooseEnum>("sd", sd_enum, "Reference sample direction");
  MooseEnum structure_enum = MooseEnum("cubic=43 hexagonal=62 tetragonal=42 trigonal=32 orthorhombic=22 monoclinic=2 triclinic=1");
  params.addRequiredParam<MooseEnum>("crystal_structure",structure_enum,"Crystal structure of the material");
  MooseEnum output_types = MooseEnum("red green blue scalar", "scalar");
  params.addParam<MooseEnum>("output_type", output_types, "Type of value that will be outputted");
  params.addRequiredParam<UserObjectName>("euler_angle_provider", "Name of Euler angle provider user object");
  params.addRequiredParam<UserObjectName>("grain_tracker", "The GrainTracker UserObject to get values from.");
  params.addParam<Point>("no_grain_color", Point(0, 0, 0), "RGB value of color used to represent area with no grains, defaults to black");
  return params;
}

EulerAngleProvider2RGBAux::EulerAngleProvider2RGBAux(const InputParameters & parameters) :
    AuxKernel(parameters),
    _sd(getParam<MooseEnum>("sd")),
    _xtal_class(getParam<MooseEnum>("crystal_structure")),
    _output_type(getParam<MooseEnum>("output_type")),
    _euler(getUserObject<EulerAngleProvider>("euler_angle_provider")),
    _grain_tracker(getUserObject<GrainTracker>("grain_tracker")),
    _no_grain_color(getParam<Point>("no_grain_color"))
{
}

void
EulerAngleProvider2RGBAux::precalculateValue()
{
  // ID of unique grain at current point
  const int grain_id = _grain_tracker.getEntityValue((isNodal() ? _current_node->id() : _current_elem->id()),
                                                              FeatureFloodCount::FieldType::UNIQUE_REGION, 0);
  // Recover euler angles for current grain
  RealVectorValue angles;
  if (grain_id >= 0)
    angles = _euler.getEulerAngles(grain_id);

  // Assign correct RGB value either from euler2RGB or from _no_grain_color
  Point RGB;
  if (grain_id < 0) //If not in a grain, return _no_grain_color
    RGB = _no_grain_color;
  else
    RGB = euler2RGB(_sd, angles(0) / 180.0 * libMesh::pi, angles(1) / 180.0 * libMesh::pi, angles(2) / 180.0 * libMesh::pi, 1.0, _xtal_class);

  // Create correct scalar output
  if (_output_type < 3)
    _value = RGB(_output_type);
  else if (_output_type == 3)
  {
      Real RGBint = 0.0;
      for (unsigned int i = 0; i < 3; ++i)
        RGBint = 256 * RGBint + (RGB(i) >= 1 ? 255 : std::floor(RGB(i) * 256.0));

      _value = RGBint;
  }
  else
    mooseError("Incorrect value for output_type in EulerAngleProvider2RGBAux");
}

Real
EulerAngleProvider2RGBAux::computeValue()
{
  return _value;
}
<commit_msg>Check grain id validity (#8402)<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/
#include "EulerAngleProvider2RGBAux.h"
#include "GrainTracker.h"
#include "EulerAngleProvider.h"
#include "Euler2RGB.h"

template<>
InputParameters validParams<EulerAngleProvider2RGBAux>()
{
  InputParameters params = validParams<AuxKernel>();
  params.addClassDescription("Output RGB representation of crystal orientation from user object to an AuxVariable. The entire domain must have the same crystal structure.");
  MooseEnum sd_enum = MooseEnum("100=1 010=2 001=3", "001");
  params.addParam<MooseEnum>("sd", sd_enum, "Reference sample direction");
  MooseEnum structure_enum = MooseEnum("cubic=43 hexagonal=62 tetragonal=42 trigonal=32 orthorhombic=22 monoclinic=2 triclinic=1");
  params.addRequiredParam<MooseEnum>("crystal_structure",structure_enum,"Crystal structure of the material");
  MooseEnum output_types = MooseEnum("red green blue scalar", "scalar");
  params.addParam<MooseEnum>("output_type", output_types, "Type of value that will be outputted");
  params.addRequiredParam<UserObjectName>("euler_angle_provider", "Name of Euler angle provider user object");
  params.addRequiredParam<UserObjectName>("grain_tracker", "The GrainTracker UserObject to get values from.");
  params.addParam<Point>("no_grain_color", Point(0, 0, 0), "RGB value of color used to represent area with no grains, defaults to black");
  return params;
}

EulerAngleProvider2RGBAux::EulerAngleProvider2RGBAux(const InputParameters & parameters) :
    AuxKernel(parameters),
    _sd(getParam<MooseEnum>("sd")),
    _xtal_class(getParam<MooseEnum>("crystal_structure")),
    _output_type(getParam<MooseEnum>("output_type")),
    _euler(getUserObject<EulerAngleProvider>("euler_angle_provider")),
    _grain_tracker(getUserObject<GrainTracker>("grain_tracker")),
    _no_grain_color(getParam<Point>("no_grain_color"))
{
}

void
EulerAngleProvider2RGBAux::precalculateValue()
{
  // ID of unique grain at current point
  const int grain_id = _grain_tracker.getEntityValue((isNodal() ? _current_node->id() : _current_elem->id()),
                                                              FeatureFloodCount::FieldType::UNIQUE_REGION, 0);

  // Recover Euler angles for current grain and assign correct
  // RGB value either from euler2RGB or from _no_grain_color
  Point RGB;
  if (grain_id >= 0 && grain_id < _euler.getGrainNum())
  {
    const RealVectorValue & angles = _euler.getEulerAngles(grain_id);
    RGB = euler2RGB(_sd, angles(0) / 180.0 * libMesh::pi, angles(1) / 180.0 * libMesh::pi, angles(2) / 180.0 * libMesh::pi, 1.0, _xtal_class);
  }
  else
    RGB = _no_grain_color;

  // Create correct scalar output
  if (_output_type < 3)
    _value = RGB(_output_type);
  else if (_output_type == 3)
  {
      Real RGBint = 0.0;
      for (unsigned int i = 0; i < 3; ++i)
        RGBint = 256 * RGBint + (RGB(i) >= 1 ? 255 : std::floor(RGB(i) * 256.0));

      _value = RGBint;
  }
  else
    mooseError("Incorrect value for output_type in EulerAngleProvider2RGBAux");
}

Real
EulerAngleProvider2RGBAux::computeValue()
{
  return _value;
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------//
/*
  Copyright (c) 2014, Stuart R. Slattery
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  *: Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  *: Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

  *: Neither the name of the Oak Ridge National Laboratory nor the
  names of its contributors may be used to endorse or promote products
  derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
 * \file   consistent_interpolation.cpp
 * \author Stuart Slattery
 * \brief  STK file-based consistent interpolation example.
 */
//---------------------------------------------------------------------------//

#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cstdlib>

#include "DTK_STKMeshDOFVector.hpp"
#include "DTK_STKMeshHelpers.hpp"
#include "DTK_STKMeshManager.hpp"
#include "DTK_ConsistentInterpolationOperator.hpp"

#include <Teuchos_GlobalMPISession.hpp>
#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_XMLParameterListCoreHelpers.hpp"
#include "Teuchos_ParameterList.hpp"
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_DefaultMpiComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_VerboseObject.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <Teuchos_TimeMonitor.hpp>

#include <Tpetra_MultiVector.hpp>

#include <Intrepid_FieldContainer.hpp>

#include <stk_util/parallel/Parallel.hpp>

#include <stk_mesh/base/MetaData.hpp>
#include <stk_mesh/base/BulkData.hpp>
#include <stk_mesh/base/Types.hpp>
#include <stk_mesh/base/FieldBase.hpp>
#include <stk_mesh/base/Field.hpp>
#include <stk_mesh/base/GetEntities.hpp>
#include <stk_mesh/base/Selector.hpp>
#include <stk_topology/topology.hpp>

#include <stk_io/IossBridge.hpp>
#include <stk_io/StkMeshIoBroker.hpp>

#include <init/Ionit_Initializer.h>
#include <Ioss_SubSystem.h>

//---------------------------------------------------------------------------//
// Example driver.
//---------------------------------------------------------------------------//
int main(int argc, char* argv[])
{
    // INITIALIZATION
    // --------------

    // Setup communication.
    Teuchos::GlobalMPISession mpiSession(&argc,&argv);

    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();

    // Read in command line options.
    std::string xml_input_filename;
    Teuchos::CommandLineProcessor clp(false);
    clp.setOption( "xml-in-file",
		   &xml_input_filename,
		   "The XML file to read into a parameter list" );
    clp.parse(argc,argv);

    // Build the parameter list from the xml input.
    Teuchos::RCP<Teuchos::ParameterList> plist =
	Teuchos::rcp( new Teuchos::ParameterList() );
    Teuchos::updateParametersFromXmlFile(
	xml_input_filename, Teuchos::inoutArg(*plist) );

    // Read command-line options
    std::string source_mesh_input_file =
	plist->get<std::string>("Source Mesh Input File");
    std::string source_mesh_output_file =
	plist->get<std::string>("Source Mesh Output File");
    std::string source_mesh_part_name =
	plist->get<std::string>("Source Mesh Part");
    std::string target_mesh_input_file =
	plist->get<std::string>("Target Mesh Input File");
    std::string target_mesh_output_file =
	plist->get<std::string>("Target Mesh Output File");
    std::string target_mesh_part_name =
	plist->get<std::string>("Target Mesh Part");

    // Get the raw mpi communicator (basic typedef in STK).
    Teuchos::RCP<const Teuchos::MpiComm<int> > mpi_comm =
	Teuchos::rcp_dynamic_cast<const Teuchos::MpiComm<int> >( comm );
    Teuchos::RCP<const Teuchos::OpaqueWrapper<MPI_Comm> > opaque_comm =
	mpi_comm->getRawMpiComm();
    stk::ParallelMachine parallel_machine = (*opaque_comm)();

    // SOURCE MESH READ
    // ----------------

    // Load the source mesh.
    stk::io::StkMeshIoBroker src_broker( parallel_machine );
    std::size_t src_input_index = src_broker.add_mesh_database(
	source_mesh_input_file, "exodus", stk::io::READ_MESH );
    src_broker.set_active_mesh( src_input_index );
    src_broker.create_input_mesh();

    // Add a nodal field to the source part.
    stk::mesh::Field<double>& source_field =
	src_broker.meta_data().declare_field<stk::mesh::Field<double> >(
	    stk::topology::NODE_RANK, "u_src" );
    stk::mesh::Part* src_part =
	src_broker.meta_data().get_part( source_mesh_part_name );
    stk::mesh::put_field( source_field, *src_part );

    // Create the source bulk data.
    src_broker.populate_bulk_data();
    Teuchos::RCP<stk::mesh::BulkData> src_bulk_data =
	Teuchos::rcpFromRef( src_broker.bulk_data() );

    // Put some data in the source field. We will use the distance of the node
    // from the origin as the data.
    stk::mesh::Selector src_stk_selector( *src_part );
    stk::mesh::BucketVector src_part_buckets =
	src_stk_selector.get_buckets( stk::topology::NODE_RANK );
    std::vector<stk::mesh::Entity> src_part_nodes;
    stk::mesh::get_selected_entities(
	src_stk_selector, src_part_buckets, src_part_nodes );
    Intrepid::FieldContainer<double> src_node_coords =
	DataTransferKit::STKMeshHelpers::getEntityNodeCoordinates(
	    Teuchos::Array<stk::mesh::Entity>(src_part_nodes), *src_bulk_data );
    double* src_field_data;
    int num_src_part_nodes = src_part_nodes.size();
    for ( int n = 0; n < num_src_part_nodes; ++n )
    {
	src_field_data = stk::mesh::field_data( source_field, src_part_nodes[n] );
	src_field_data[0] = src_node_coords(n,0,0)*src_node_coords(n,0,0) +
			    src_node_coords(n,0,1)*src_node_coords(n,0,1) +
			    src_node_coords(n,0,2)*src_node_coords(n,0,2);
    }

    // TARGET MESH READ
    // ----------------

    // Load the target mesh.
    stk::io::StkMeshIoBroker tgt_broker( parallel_machine );
    std::size_t tgt_input_index = tgt_broker.add_mesh_database(
    	target_mesh_input_file, "exodus", stk::io::READ_MESH );
    tgt_broker.set_active_mesh( tgt_input_index );
    tgt_broker.create_input_mesh();

    // Add a nodal field to the target part.
    stk::mesh::Field<double>& target_field =
    	tgt_broker.meta_data().declare_field<stk::mesh::Field<double> >(
    	    stk::topology::NODE_RANK, "u_tgt" );
    stk::mesh::Part* tgt_part =
	tgt_broker.meta_data().get_part( target_mesh_part_name );
    stk::mesh::put_field( target_field, *tgt_part );

    // Create the target bulk data.
    tgt_broker.populate_bulk_data();
    Teuchos::RCP<stk::mesh::BulkData> tgt_bulk_data =
    	Teuchos::rcpFromRef( tgt_broker.bulk_data() );

    // SOLUTION TRANSFER SETUP
    // -----------------------

    // Solution transfer parameters.
    Teuchos::RCP<Teuchos::ParameterList> parameters = Teuchos::parameterList();

    // Create a manager for the source part elements.
    DataTransferKit::STKMeshManager src_manager(
	src_bulk_data, src_stk_selector, DataTransferKit::ENTITY_TYPE_VOLUME );

    // Create a manager for the target part nodes.
    stk::mesh::Selector tgt_stk_selector( *tgt_part );
    DataTransferKit::STKMeshManager tgt_manager(
	tgt_bulk_data, tgt_stk_selector, DataTransferKit::ENTITY_TYPE_NODE );

    // Create a solution vector for the source.
    Teuchos::RCP<Tpetra::MultiVector<double,int,std::size_t> > src_vector =
    	DataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField<double>(
    	    *src_bulk_data, source_field, 1 );

    // Create a solution vector for the target.
    Teuchos::RCP<Tpetra::MultiVector<double,int,std::size_t> > tgt_vector =
    	DataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField<double>(
    	    *tgt_bulk_data, target_field, 1 );

    // SOLUTION TRANSFER
    // -----------------

    // Create a consistent interpolation operator.
    DataTransferKit::ConsistentInterpolationOperator<double> interpolation_operator;

    // Setup the consistent interpolation operator.
    interpolation_operator.setup( src_vector->getMap(),
				  src_manager.functionSpace(),
				  tgt_vector->getMap(),
				  tgt_manager.functionSpace(),
				  parameters );

    // Apply the consistent interpolation operator.
    interpolation_operator.apply( *src_vector, *tgt_vector );

    // Push the target vector onto the target mesh.
    DataTransferKit::STKMeshDOFVector::pushTpetraMultiVectorToSTKField(
    	*tgt_vector, *tgt_bulk_data, target_field );

    // SOURCE MESH WRITE
    // -----------------

    std::size_t src_output_index = src_broker.create_output_mesh(
	source_mesh_output_file, stk::io::WRITE_RESULTS );
    src_broker.add_field( src_output_index, source_field );
    src_broker.begin_output_step( src_output_index, 0.0 );
    src_broker.write_defined_output_fields( src_output_index );
    src_broker.end_output_step( src_output_index );

    // TARGET MESH WRITE
    // -----------------

    std::size_t tgt_output_index = tgt_broker.create_output_mesh(
    	target_mesh_output_file, stk::io::WRITE_RESULTS );
    tgt_broker.add_field( tgt_output_index, target_field );
    tgt_broker.begin_output_step( tgt_output_index, 0.0 );
    tgt_broker.write_defined_output_fields( tgt_output_index );
    tgt_broker.end_output_step( tgt_output_index );
}

//---------------------------------------------------------------------------//
// end tstSTK_Mesh.cpp
//---------------------------------------------------------------------------//
<commit_msg>adding error calculation to interpolation<commit_after>//---------------------------------------------------------------------------//
/*
  Copyright (c) 2014, Stuart R. Slattery
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  *: Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  *: Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

  *: Neither the name of the Oak Ridge National Laboratory nor the
  names of its contributors may be used to endorse or promote products
  derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
 * \file   consistent_interpolation.cpp
 * \author Stuart Slattery
 * \brief  STK file-based consistent interpolation example.
 */
//---------------------------------------------------------------------------//

#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cstdlib>

#include "DTK_STKMeshDOFVector.hpp"
#include "DTK_STKMeshHelpers.hpp"
#include "DTK_STKMeshManager.hpp"
#include "DTK_ConsistentInterpolationOperator.hpp"

#include <Teuchos_GlobalMPISession.hpp>
#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_XMLParameterListCoreHelpers.hpp"
#include "Teuchos_ParameterList.hpp"
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_DefaultMpiComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_VerboseObject.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <Teuchos_TimeMonitor.hpp>

#include <Tpetra_MultiVector.hpp>

#include <Intrepid_FieldContainer.hpp>

#include <stk_util/parallel/Parallel.hpp>

#include <stk_mesh/base/MetaData.hpp>
#include <stk_mesh/base/BulkData.hpp>
#include <stk_mesh/base/Types.hpp>
#include <stk_mesh/base/FieldBase.hpp>
#include <stk_mesh/base/Field.hpp>
#include <stk_mesh/base/GetEntities.hpp>
#include <stk_mesh/base/Selector.hpp>
#include <stk_topology/topology.hpp>

#include <stk_io/IossBridge.hpp>
#include <stk_io/StkMeshIoBroker.hpp>

#include <init/Ionit_Initializer.h>
#include <Ioss_SubSystem.h>

//---------------------------------------------------------------------------//
// Data field function.
//---------------------------------------------------------------------------//
double dataFunction( double x, double y, double z )
{
    return std::abs(x) + std::abs(y) + std::abs(z) + 1.0;
}

//---------------------------------------------------------------------------//
// Example driver.
//---------------------------------------------------------------------------//
int main(int argc, char* argv[])
{
    // INITIALIZATION
    // --------------

    // Setup communication.
    Teuchos::GlobalMPISession mpiSession(&argc,&argv);

    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();

    // Read in command line options.
    std::string xml_input_filename;
    Teuchos::CommandLineProcessor clp(false);
    clp.setOption( "xml-in-file",
		   &xml_input_filename,
		   "The XML file to read into a parameter list" );
    clp.parse(argc,argv);

    // Build the parameter list from the xml input.
    Teuchos::RCP<Teuchos::ParameterList> plist =
	Teuchos::rcp( new Teuchos::ParameterList() );
    Teuchos::updateParametersFromXmlFile(
	xml_input_filename, Teuchos::inoutArg(*plist) );

    // Read command-line options
    std::string source_mesh_input_file =
	plist->get<std::string>("Source Mesh Input File");
    std::string source_mesh_output_file =
	plist->get<std::string>("Source Mesh Output File");
    std::string source_mesh_part_name =
	plist->get<std::string>("Source Mesh Part");
    std::string target_mesh_input_file =
	plist->get<std::string>("Target Mesh Input File");
    std::string target_mesh_output_file =
	plist->get<std::string>("Target Mesh Output File");
    std::string target_mesh_part_name =
	plist->get<std::string>("Target Mesh Part");

    // Get the raw mpi communicator (basic typedef in STK).
    Teuchos::RCP<const Teuchos::MpiComm<int> > mpi_comm =
	Teuchos::rcp_dynamic_cast<const Teuchos::MpiComm<int> >( comm );
    Teuchos::RCP<const Teuchos::OpaqueWrapper<MPI_Comm> > opaque_comm =
	mpi_comm->getRawMpiComm();
    stk::ParallelMachine parallel_machine = (*opaque_comm)();

    // SOURCE MESH READ
    // ----------------

    // Load the source mesh.
    stk::io::StkMeshIoBroker src_broker( parallel_machine );
    std::size_t src_input_index = src_broker.add_mesh_database(
	source_mesh_input_file, "exodus", stk::io::READ_MESH );
    src_broker.set_active_mesh( src_input_index );
    src_broker.create_input_mesh();

    // Add a nodal field to the source part.
    stk::mesh::Field<double>& source_field =
	src_broker.meta_data().declare_field<stk::mesh::Field<double> >(
	    stk::topology::NODE_RANK, "u_src" );
    stk::mesh::Part* src_part =
	src_broker.meta_data().get_part( source_mesh_part_name );
    stk::mesh::put_field( source_field, *src_part );

    // Create the source bulk data.
    src_broker.populate_bulk_data();
    Teuchos::RCP<stk::mesh::BulkData> src_bulk_data =
	Teuchos::rcpFromRef( src_broker.bulk_data() );

    // Put some data in the source field. We will use the distance of the node
    // from the origin as the data.
    stk::mesh::Selector src_stk_selector( *src_part );
    stk::mesh::BucketVector src_part_buckets =
	src_stk_selector.get_buckets( stk::topology::NODE_RANK );
    std::vector<stk::mesh::Entity> src_part_nodes;
    stk::mesh::get_selected_entities(
	src_stk_selector, src_part_buckets, src_part_nodes );
    Intrepid::FieldContainer<double> src_node_coords =
	DataTransferKit::STKMeshHelpers::getEntityNodeCoordinates(
	    Teuchos::Array<stk::mesh::Entity>(src_part_nodes), *src_bulk_data );
    double* src_field_data;
    int num_src_part_nodes = src_part_nodes.size();
    for ( int n = 0; n < num_src_part_nodes; ++n )
    {
	src_field_data = stk::mesh::field_data( source_field, src_part_nodes[n] );
	src_field_data[0] = dataFunction( src_node_coords(n,0,0),
					  src_node_coords(n,0,1),
					  src_node_coords(n,0,2) );
    }

    // TARGET MESH READ
    // ----------------

    // Load the target mesh.
    stk::io::StkMeshIoBroker tgt_broker( parallel_machine );
    std::size_t tgt_input_index = tgt_broker.add_mesh_database(
    	target_mesh_input_file, "exodus", stk::io::READ_MESH );
    tgt_broker.set_active_mesh( tgt_input_index );
    tgt_broker.create_input_mesh();

    // Add a nodal field to the target part.
    stk::mesh::Field<double>& target_field =
    	tgt_broker.meta_data().declare_field<stk::mesh::Field<double> >(
    	    stk::topology::NODE_RANK, "u_tgt" );
    stk::mesh::Part* tgt_part =
	tgt_broker.meta_data().get_part( target_mesh_part_name );
    stk::mesh::put_field( target_field, *tgt_part );

    // Add an error nodal field to the target part.
    stk::mesh::Field<double>& target_error_field =
    	tgt_broker.meta_data().declare_field<stk::mesh::Field<double> >(
    	    stk::topology::NODE_RANK, "u_err" );
    stk::mesh::put_field( target_error_field, *tgt_part );

    // Create the target bulk data.
    tgt_broker.populate_bulk_data();
    Teuchos::RCP<stk::mesh::BulkData> tgt_bulk_data =
    	Teuchos::rcpFromRef( tgt_broker.bulk_data() );

    // SOLUTION TRANSFER SETUP
    // -----------------------

    // Solution transfer parameters.
    Teuchos::RCP<Teuchos::ParameterList> parameters = Teuchos::parameterList();

    // Create a manager for the source part elements.
    DataTransferKit::STKMeshManager src_manager(
	src_bulk_data, src_stk_selector, DataTransferKit::ENTITY_TYPE_VOLUME );

    // Create a manager for the target part nodes.
    stk::mesh::Selector tgt_stk_selector( *tgt_part );
    DataTransferKit::STKMeshManager tgt_manager(
	tgt_bulk_data, tgt_stk_selector, DataTransferKit::ENTITY_TYPE_NODE );

    // Create a solution vector for the source.
    Teuchos::RCP<Tpetra::MultiVector<double,int,std::size_t> > src_vector =
    	DataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField<double>(
    	    *src_bulk_data, source_field, 1 );

    // Create a solution vector for the target.
    Teuchos::RCP<Tpetra::MultiVector<double,int,std::size_t> > tgt_vector =
    	DataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField<double>(
    	    *tgt_bulk_data, target_field, 1 );

    // SOLUTION TRANSFER
    // -----------------

    // Create a consistent interpolation operator.
    DataTransferKit::ConsistentInterpolationOperator<double> interpolation_operator;

    // Setup the consistent interpolation operator.
    interpolation_operator.setup( src_vector->getMap(),
				  src_manager.functionSpace(),
				  tgt_vector->getMap(),
				  tgt_manager.functionSpace(),
				  parameters );

    // Apply the consistent interpolation operator.
    interpolation_operator.apply( *src_vector, *tgt_vector );

    // Push the target vector onto the target mesh.
    DataTransferKit::STKMeshDOFVector::pushTpetraMultiVectorToSTKField(
    	*tgt_vector, *tgt_bulk_data, target_field );

    // COMPUTE THE SOLUTION ERROR
    // --------------------------

    stk::mesh::BucketVector tgt_part_buckets =
	tgt_stk_selector.get_buckets( stk::topology::NODE_RANK );
    std::vector<stk::mesh::Entity> tgt_part_nodes;
    stk::mesh::get_selected_entities(
	tgt_stk_selector, tgt_part_buckets, tgt_part_nodes );
    Intrepid::FieldContainer<double> tgt_node_coords =
	DataTransferKit::STKMeshHelpers::getEntityNodeCoordinates(
	    Teuchos::Array<stk::mesh::Entity>(tgt_part_nodes), *tgt_bulk_data );
    double* tgt_field_data;
    double* err_field_data;
    int num_tgt_part_nodes = tgt_part_nodes.size();
    double error_l2_norm = 0.0;
    double field_l2_norm = 0.0;
    for ( int n = 0; n < num_tgt_part_nodes; ++n )
    {
	double gold_value = dataFunction( tgt_node_coords(n,0,0),
					  tgt_node_coords(n,0,1),
					  tgt_node_coords(n,0,2) );
	tgt_field_data = stk::mesh::field_data( target_field, tgt_part_nodes[n] );
	err_field_data = stk::mesh::field_data( target_error_field, tgt_part_nodes[n] );
	err_field_data[0] = tgt_field_data[0] - gold_value;
	error_l2_norm += err_field_data[0] * err_field_data[0];
	field_l2_norm += tgt_field_data[0] * tgt_field_data[0];
	err_field_data[0] /= gold_value;
    }
    error_l2_norm = std::sqrt( error_l2_norm );
    field_l2_norm = std::sqrt( field_l2_norm );
    std::cout << "|e|_2 / |f|_2: " << error_l2_norm / field_l2_norm << std::endl;

    // SOURCE MESH WRITE
    // -----------------

    std::size_t src_output_index = src_broker.create_output_mesh(
	source_mesh_output_file, stk::io::WRITE_RESULTS );
    src_broker.add_field( src_output_index, source_field );
    src_broker.begin_output_step( src_output_index, 0.0 );
    src_broker.write_defined_output_fields( src_output_index );
    src_broker.end_output_step( src_output_index );

    // TARGET MESH WRITE
    // -----------------

    std::size_t tgt_output_index = tgt_broker.create_output_mesh(
    	target_mesh_output_file, stk::io::WRITE_RESULTS );
    tgt_broker.add_field( tgt_output_index, target_field );
    tgt_broker.add_field( tgt_output_index, target_error_field );
    tgt_broker.begin_output_step( tgt_output_index, 0.0 );
    tgt_broker.write_defined_output_fields( tgt_output_index );
    tgt_broker.end_output_step( tgt_output_index );
}

//---------------------------------------------------------------------------//
// end tstSTK_Mesh.cpp
//---------------------------------------------------------------------------//
<|endoftext|>


<commit_before>#include "thruster_tortuga.h"

ThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){
    ros::Rate loop_rate(rate);
    subscriber = n.subscribe("/qubo/thruster_input", 1000, &ThrusterTortugaNode::thrusterCallBack, this);

    ROS_DEBUG("Opening sensorboard");
    sensor_file = "/dev/sensor";
    fd = openSensorBoard(sensor_file.c_str());
    ROS_DEBUG("Opened sensorboard with fd %d.", fd);
    checkError(syncBoard(fd));
    ROS_DEBUG("Synced with the Board");

    //GH: This is not the correct use of checkError.
    //It should be called on the return value of a function call, not on the file descriptor.
    //checkError(fd);

    // Unsafe all the thrusters
    ROS_DEBUG("Unsafing all thrusters");
    for (int i = 6; i <= 11; i++) {
        checkError(setThrusterSafety(fd, i));
    }

    ROS_DEBUG("Unsafed all thrusters");

    for(int i = 0; i < NUM_THRUSTERS; i++){
      thruster_powers.data[i] = 0;
    }

}

ThrusterTortugaNode::~ThrusterTortugaNode(){
    //Stop all the thrusters
    ROS_DEBUG("Stopping thrusters");
    readSpeedResponses(fd);
    setSpeeds(fd, 0, 0, 0, 0, 0, 0);
    ROS_DEBUG("Safing thrusters");
    // Safe all the thrusters
    for (int i = 0; i <= 5; i++) {
        checkError(setThrusterSafety(fd, i));
    }
    ROS_DEBUG("Safed thrusters");
    //Close the sensorboard
    close(fd);
}

void ThrusterTortugaNode::update(){
    //I think we need to initialize thrusters and stuff before this will work
    ros::spinOnce();
    // setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);
    // ROS_DEBUG("fd = %x",fd);

    ROS_DEBUG("Setting thruster speeds");
    int retR = readSpeedResponses(fd);
    ROS_DEBUG("Read speed before: %x", retR);
    int retS = setSpeeds(fd, 128, 128, 128, 128, 128, 128);
    ROS_DEBUG("Set speed status: %x", retS);
    usleep(20*1000);
    int retA = readSpeedResponses(fd);
    ROS_DEBUG("Read speed after: %x", retA);

    ROS_DEBUG("thruster state = %x", readThrusterState(fd));
    ROS_DEBUG("set speed returns %x", retS);
    ROS_DEBUG("read speed returns %x", retR);
}

void ThrusterTortugaNode::publish(){
    // setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);
}

void ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){
    //SG: TODO change this shit
  for(int i = 0 ;i < NUM_THRUSTERS; i++){
    thruster_powers.data[i] = new_powers.data[i];
  }
}

//ssh robot@192.168.10.12
<commit_msg>we now actually use the values we subscribe to.. also added some more debug output<commit_after>#include "thruster_tortuga.h"

ThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){
    ros::Rate loop_rate(rate);
    subscriber = n.subscribe("/qubo/thruster_input", 1000, &ThrusterTortugaNode::thrusterCallBack, this);

    ROS_DEBUG("Opening sensorboard");
    sensor_file = "/dev/sensor";
    fd = openSensorBoard(sensor_file.c_str());
    ROS_DEBUG("Opened sensorboard with fd %d.", fd);
    checkError(syncBoard(fd));
    ROS_DEBUG("Synced with the Board");

    //GH: This is not the correct use of checkError.
    //It should be called on the return value of a function call, not on the file descriptor.
    //checkError(fd);

    // Unsafe all the thrusters
    ROS_DEBUG("Unsafing all thrusters");
    for (int i = 6; i <= 11; i++) {
        checkError(setThrusterSafety(fd, i));
    }

    ROS_DEBUG("Unsafed all thrusters");

    for(int i = 0; i < NUM_THRUSTERS; i++){
      thruster_powers.data[i] = 0;
    }

}

ThrusterTortugaNode::~ThrusterTortugaNode(){
    //Stop all the thrusters
    ROS_DEBUG("Stopping thrusters");
    readSpeedResponses(fd);
    setSpeeds(fd, 0, 0, 0, 0, 0, 0);
    ROS_DEBUG("Safing thrusters");
    // Safe all the thrusters
    for (int i = 0; i <= 5; i++) {
        checkError(setThrusterSafety(fd, i));
    }
    ROS_DEBUG("Safed thrusters");
    //Close the sensorboard
    close(fd);
}

void ThrusterTortugaNode::update(){
    //I think we need to initialize thrusters and stuff before this will work
    ros::spinOnce();
    // setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);
    // ROS_DEBUG("fd = %x",fd);

    ROS_DEBUG("Setting thruster speeds");
    int retR = readSpeedResponses(fd);
    ROS_DEBUG("Read speed before: %x", retR);
    for(int i = 0 ;i < NUM_THRUSTERS; i++){
      ROS_DEBUG("thruster value %i = %i\n" i, thruster_powers.data[i])
    }
    int retS = setSpeeds(fd, thruster_powers.data[0], , thruster_powers.data[1], thruster_powers.data[2], thruster_powers[3], thruster_powers[4]);
    ROS_DEBUG("Set speed status: %x", retS);
    usleep(20*1000);
    int retA = readSpeedResponses(fd);
    ROS_DEBUG("Read speed after: %x", retA);

    ROS_DEBUG("thruster state = %x", readThrusterState(fd));
    ROS_DEBUG("set speed returns %x", retS);
    ROS_DEBUG("read speed returns %x", retR);

}

void ThrusterTortugaNode::publish(){
    // setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);
}

void ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){
  for(int i = 0 ;i < NUM_THRUSTERS; i++){
    thruster_powers.data[i] = new_powers.data[i];
  }
}

//ssh robot@192.168.10.12
<|endoftext|>


<commit_before>#include "ClientSocket.hh"
#include "Server.hh"

#include <signal.h>

#include <fstream>
#include <random>
#include <string>
#include <vector>

Server server;

void handleExitSignal( int /* signal */ )
{
  server.close();
}

void unescapeQuote( std::string& quote )
{
  std::size_t position    = 0;
  std::string target      = "\\n";
  std::string replacement = "\n";
  while( ( position = quote.find( target, position ) ) != std::string::npos )
  {
    quote.replace( position, target.length(), replacement );
    position += replacement.length();
  }
}

std::vector<std::string> readQuotes( const std::string& filename )
{
  std::ifstream in( filename );
  if( !in )
    return {};

  std::vector<std::string> quotes;
  std::string line;

  while( std::getline( in, line ) )
  {
    unescapeQuote( line );
    quotes.push_back( line );
  }

  return quotes;
}

int main( int argc, char** argv )
{
  std::vector<std::string> quotes;

  if( argc > 1 )
    quotes = readQuotes( argv[1] );
  else
    quotes = { "Sorry, no quote today, mate.\n" };

  std::random_device rd;
  std::mt19937 rng( rd() );
  std::uniform_int_distribution<std::size_t> distribution( 0, quotes.size() - 1 );

  signal( SIGINT, handleExitSignal );

  server.setPort( 2048 );

  server.onAccept( [&] ( std::unique_ptr<ClientSocket> socket )
  {
    socket->write( quotes.at( distribution( rng ) ) );
    socket->close();
  } );

  server.listen();

  return 0;
}
<commit_msg>Changed QOTD port<commit_after>#include "ClientSocket.hh"
#include "Server.hh"

#include <signal.h>

#include <fstream>
#include <random>
#include <string>
#include <vector>

Server server;

void handleExitSignal( int /* signal */ )
{
  server.close();
}

void unescapeQuote( std::string& quote )
{
  std::size_t position    = 0;
  std::string target      = "\\n";
  std::string replacement = "\n";
  while( ( position = quote.find( target, position ) ) != std::string::npos )
  {
    quote.replace( position, target.length(), replacement );
    position += replacement.length();
  }
}

std::vector<std::string> readQuotes( const std::string& filename )
{
  std::ifstream in( filename );
  if( !in )
    return {};

  std::vector<std::string> quotes;
  std::string line;

  while( std::getline( in, line ) )
  {
    unescapeQuote( line );
    quotes.push_back( line );
  }

  return quotes;
}

int main( int argc, char** argv )
{
  std::vector<std::string> quotes;

  if( argc > 1 )
    quotes = readQuotes( argv[1] );
  else
    quotes = { "Sorry, no quote today, mate.\n" };

  std::random_device rd;
  std::mt19937 rng( rd() );
  std::uniform_int_distribution<std::size_t> distribution( 0, quotes.size() - 1 );

  signal( SIGINT, handleExitSignal );

  server.setPort( 1041 );

  server.onAccept( [&] ( std::unique_ptr<ClientSocket> socket )
  {
    socket->write( quotes.at( distribution( rng ) ) );
    socket->close();
  } );

  server.listen();

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 */

/** @file
 * Implementiation of a PL390 GIC
 */

#ifndef __DEV_ARM_GIC_PL390_H__
#define __DEV_ARM_GIC_PL390_H__

#include "base/bitunion.hh"
#include "cpu/intr_control.hh"
#include "dev/arm/base_gic.hh"
#include "dev/io_device.hh"
#include "dev/platform.hh"
#include "params/Pl390.hh"

/** @todo this code only assumes one processor for now. Low word
 * of intEnabled and pendingInt need to be replicated per CPU.
 * bottom 31 interrupts (7 words) need to be replicated for
 * for interrupt priority register, processor target registers
 * interrupt config registers  */

class Pl390 : public BaseGic
{
  protected:
    // distributor memory addresses
    static const int ICDDCR     = 0x000; // control register
    static const int ICDICTR    = 0x004; // controller type
    static const int ICDIIDR    = 0x008; // implementer id
    static const int ICDISER_ST = 0x100; // interrupt set enable
    static const int ICDISER_ED = 0x17c;
    static const int ICDICER_ST = 0x180; // interrupt clear enable
    static const int ICDICER_ED = 0x1fc;
    static const int ICDISPR_ST = 0x200; // set pending interrupt
    static const int ICDISPR_ED = 0x27c;
    static const int ICDICPR_ST = 0x280; // clear pending interrupt
    static const int ICDICPR_ED = 0x2fc;
    static const int ICDABR_ST  = 0x300; // active bit registers
    static const int ICDABR_ED  = 0x37c;
    static const int ICDIPR_ST  = 0x400; // interrupt priority registers
    static const int ICDIPR_ED  = 0x7f8;
    static const int ICDIPTR_ST = 0x800; // processor target registers
    static const int ICDIPTR_ED = 0xbf8;
    static const int ICDICFR_ST = 0xc00; // interrupt config registers
    static const int ICDICFR_ED = 0xcfc;
    static const int ICDSGIR    = 0xf00; // software generated interrupt
    static const int DIST_SIZE  = 0xfff;

    // cpu memory addressesa
    static const int ICCICR  = 0x00; // CPU control register
    static const int ICCPMR  = 0x04; // Interrupt priority mask
    static const int ICCBPR  = 0x08; // binary point register
    static const int ICCIAR  = 0x0C; // interrupt ack register
    static const int ICCEOIR = 0x10; // end of interrupt
    static const int ICCRPR  = 0x14; // runing priority
    static const int ICCHPIR = 0x18; // highest pending interrupt
    static const int ICCABPR = 0x1c; // aliased binary point
    static const int ICCIIDR = 0xfc; // cpu interface id register
    static const int CPU_SIZE  = 0xff;

    static const int SGI_MAX = 16;  // Number of Software Gen Interrupts
    static const int PPI_MAX = 16;  // Number of Private Peripheral Interrupts

    /** Mask off SGI's when setting/clearing pending bits */
    static const int SGI_MASK = 0xFFFF0000;

    /** Mask for bits that config N:N mode in ICDICFR's */
    static const int NN_CONFIG_MASK = 0x55555555;

    static const int CPU_MAX = 8;   // Max number of supported CPU interfaces
    static const int SPURIOUS_INT = 1023;
    static const int INT_BITS_MAX = 32;
    static const int INT_LINES_MAX = 1020;

    BitUnion32(SWI)
        Bitfield<3,0> sgi_id;
        Bitfield<23,16> cpu_list;
        Bitfield<25,24> list_type;
    EndBitUnion(SWI)

    BitUnion32(IAR)
        Bitfield<9,0> ack_id;
        Bitfield<12,10> cpu_id;
    EndBitUnion(IAR)

    /** Distributor address GIC listens at */
    Addr distAddr;

    /** CPU address GIC listens at */
    /** @todo is this one per cpu? */
    Addr cpuAddr;

    /** Latency for a distributor operation */
    Tick distPioDelay;

    /** Latency for a cpu operation */
    Tick cpuPioDelay;

    /** Latency for a interrupt to get to CPU */
    Tick intLatency;

    /** Gic enabled */
    bool enabled;

    /** Number of itLines enabled */
    uint32_t itLines;

    uint32_t itLinesLog2;

    /** interrupt enable bits for all possible 1020 interupts.
     * one bit per interrupt, 32 bit per word = 32 words */
    uint32_t intEnabled[INT_BITS_MAX];

    /** interrupt pending bits for all possible 1020 interupts.
     * one bit per interrupt, 32 bit per word = 32 words */
    uint32_t pendingInt[INT_BITS_MAX];

    /** interrupt active bits for all possible 1020 interupts.
     * one bit per interrupt, 32 bit per word = 32 words */
    uint32_t activeInt[INT_BITS_MAX];

    /** read only running priroity register, 1 per cpu*/
    uint32_t iccrpr[CPU_MAX];

    /** an 8 bit priority (lower is higher priority) for each
     * of the 1020 possible supported interrupts.
     */
    uint8_t intPriority[INT_LINES_MAX];

    /** an 8 bit cpu target id for each shared peripheral interrupt
     * of the 1020 possible supported interrupts.
     */
    uint8_t cpuTarget[INT_LINES_MAX];

    /** 2 bit per interrupt signaling if it's level or edge sensitive
     * and if it is 1:N or N:N */
    uint32_t intConfig[INT_BITS_MAX*2];

    /** CPU enabled */
    bool cpuEnabled[CPU_MAX];

    /** CPU priority */
    uint8_t cpuPriority[CPU_MAX];

    /** Binary point registers */
    uint8_t cpuBpr[CPU_MAX];

    /** highest interrupt that is interrupting CPU */
    uint32_t cpuHighestInt[CPU_MAX];

    /** One bit per cpu per software interrupt that is pending for each possible
     * sgi source. Indexed by SGI number. Each byte in generating cpu id and
     * bits in position is destination id. e.g. 0x4 = CPU 0 generated interrupt
     * for CPU 2. */
    uint64_t cpuSgiPending[SGI_MAX];
    uint64_t cpuSgiActive[SGI_MAX];

    /** One bit per private peripheral interrupt. Only upper 16 bits
     * will be used since PPI interrupts are numberred from 16 to 32 */
    uint32_t cpuPpiPending[CPU_MAX];
    uint32_t cpuPpiActive[CPU_MAX];

    /** Banked interrupt prioirty registers for SGIs and PPIs */
    uint8_t bankedIntPriority[CPU_MAX][SGI_MAX + PPI_MAX];

    /** IRQ Enable Used for debug */
    bool irqEnable;

    /** software generated interrupt
     * @param data data to decode that indicates which cpus to interrupt
     */
    void softInt(int ctx_id, SWI swi);

    /** See if some processor interrupt flags need to be enabled/disabled
     * @param hint which set of interrupts needs to be checked
     */
    void updateIntState(int hint);

    /** Update the register that records priority of the highest priority
     *  active interrupt*/
    void updateRunPri();

    /** generate a bit mask to check cpuSgi for an interrupt. */
    uint64_t genSwiMask(int cpu);

    int intNumToWord(int num) const { return num >> 5; }
    int intNumToBit(int num) const { return num % 32; }

    /** Post an interrupt to a CPU
     */
    void postInt(uint32_t cpu, Tick when);

    /** Event definition to post interrupt to CPU after a delay
    */
    class PostIntEvent : public Event
    {
      private:
        uint32_t cpu;
        Platform *platform;
      public:
        PostIntEvent( uint32_t c, Platform* p)
            : cpu(c), platform(p)
        { }
        void process() { platform->intrctrl->post(cpu, ArmISA::INT_IRQ, 0);}
        const char *description() const { return "Post Interrupt to CPU"; }
    };
    PostIntEvent *postIntEvent[CPU_MAX];

  public:
    typedef Pl390Params Params;
    const Params *
    params() const
    {
        return dynamic_cast<const Params *>(_params);
    }
    Pl390(const Params *p);

    /** Return the address ranges used by the Gic
     * This is the distributor address + all cpu addresses
     */
    virtual AddrRangeList getAddrRanges() const;

    /** A PIO read to the device, immediately split up into
     * readDistributor() or readCpu()
     */
    virtual Tick read(PacketPtr pkt);

    /** A PIO read to the device, immediately split up into
     * writeDistributor() or writeCpu()
     */
    virtual Tick write(PacketPtr pkt);

    /** Handle a read to the distributor poriton of the GIC
     * @param pkt packet to respond to
     */
    Tick readDistributor(PacketPtr pkt);

    /** Handle a read to the cpu poriton of the GIC
     * @param pkt packet to respond to
     */
    Tick readCpu(PacketPtr pkt);

    /** Handle a write to the distributor poriton of the GIC
     * @param pkt packet to respond to
     */
    Tick writeDistributor(PacketPtr pkt);

    /** Handle a write to the cpu poriton of the GIC
     * @param pkt packet to respond to
     */
    Tick writeCpu(PacketPtr pkt);

    /** Post an interrupt from a device that is connected to the Gic.
     * Depending on the configuration, the gic will pass this interrupt
     * on through to a CPU.
     * @param number number of interrupt to send */
    void sendInt(uint32_t number);

    /** Interface call for private peripheral interrupts  */
    void sendPPInt(uint32_t num, uint32_t cpu);

    /** Clear an interrupt from a device that is connected to the Gic
     * Depending on the configuration, the gic may de-assert it's cpu line
     * @param number number of interrupt to send */
    void clearInt(uint32_t number);

    /* Various functions fer testing and debugging */
    void driveSPI(uint32_t spi);
    void driveLegIRQ(bool state);
    void driveLegFIQ(bool state);
    void driveIrqEn(bool state);

    virtual void serialize(std::ostream &os);
    virtual void unserialize(Checkpoint *cp, const std::string &section);

};

#endif //__DEV_ARM_GIC_H__
<commit_msg>arm: Don't export private GIC methods<commit_after>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 */

/** @file
 * Implementiation of a PL390 GIC
 */

#ifndef __DEV_ARM_GIC_PL390_H__
#define __DEV_ARM_GIC_PL390_H__

#include "base/bitunion.hh"
#include "cpu/intr_control.hh"
#include "dev/arm/base_gic.hh"
#include "dev/io_device.hh"
#include "dev/platform.hh"
#include "params/Pl390.hh"

/** @todo this code only assumes one processor for now. Low word
 * of intEnabled and pendingInt need to be replicated per CPU.
 * bottom 31 interrupts (7 words) need to be replicated for
 * for interrupt priority register, processor target registers
 * interrupt config registers  */

class Pl390 : public BaseGic
{
  protected:
    // distributor memory addresses
    static const int ICDDCR     = 0x000; // control register
    static const int ICDICTR    = 0x004; // controller type
    static const int ICDIIDR    = 0x008; // implementer id
    static const int ICDISER_ST = 0x100; // interrupt set enable
    static const int ICDISER_ED = 0x17c;
    static const int ICDICER_ST = 0x180; // interrupt clear enable
    static const int ICDICER_ED = 0x1fc;
    static const int ICDISPR_ST = 0x200; // set pending interrupt
    static const int ICDISPR_ED = 0x27c;
    static const int ICDICPR_ST = 0x280; // clear pending interrupt
    static const int ICDICPR_ED = 0x2fc;
    static const int ICDABR_ST  = 0x300; // active bit registers
    static const int ICDABR_ED  = 0x37c;
    static const int ICDIPR_ST  = 0x400; // interrupt priority registers
    static const int ICDIPR_ED  = 0x7f8;
    static const int ICDIPTR_ST = 0x800; // processor target registers
    static const int ICDIPTR_ED = 0xbf8;
    static const int ICDICFR_ST = 0xc00; // interrupt config registers
    static const int ICDICFR_ED = 0xcfc;
    static const int ICDSGIR    = 0xf00; // software generated interrupt
    static const int DIST_SIZE  = 0xfff;

    // cpu memory addressesa
    static const int ICCICR  = 0x00; // CPU control register
    static const int ICCPMR  = 0x04; // Interrupt priority mask
    static const int ICCBPR  = 0x08; // binary point register
    static const int ICCIAR  = 0x0C; // interrupt ack register
    static const int ICCEOIR = 0x10; // end of interrupt
    static const int ICCRPR  = 0x14; // runing priority
    static const int ICCHPIR = 0x18; // highest pending interrupt
    static const int ICCABPR = 0x1c; // aliased binary point
    static const int ICCIIDR = 0xfc; // cpu interface id register
    static const int CPU_SIZE  = 0xff;

    static const int SGI_MAX = 16;  // Number of Software Gen Interrupts
    static const int PPI_MAX = 16;  // Number of Private Peripheral Interrupts

    /** Mask off SGI's when setting/clearing pending bits */
    static const int SGI_MASK = 0xFFFF0000;

    /** Mask for bits that config N:N mode in ICDICFR's */
    static const int NN_CONFIG_MASK = 0x55555555;

    static const int CPU_MAX = 8;   // Max number of supported CPU interfaces
    static const int SPURIOUS_INT = 1023;
    static const int INT_BITS_MAX = 32;
    static const int INT_LINES_MAX = 1020;

    BitUnion32(SWI)
        Bitfield<3,0> sgi_id;
        Bitfield<23,16> cpu_list;
        Bitfield<25,24> list_type;
    EndBitUnion(SWI)

    BitUnion32(IAR)
        Bitfield<9,0> ack_id;
        Bitfield<12,10> cpu_id;
    EndBitUnion(IAR)

    /** Distributor address GIC listens at */
    Addr distAddr;

    /** CPU address GIC listens at */
    /** @todo is this one per cpu? */
    Addr cpuAddr;

    /** Latency for a distributor operation */
    Tick distPioDelay;

    /** Latency for a cpu operation */
    Tick cpuPioDelay;

    /** Latency for a interrupt to get to CPU */
    Tick intLatency;

    /** Gic enabled */
    bool enabled;

    /** Number of itLines enabled */
    uint32_t itLines;

    uint32_t itLinesLog2;

    /** interrupt enable bits for all possible 1020 interupts.
     * one bit per interrupt, 32 bit per word = 32 words */
    uint32_t intEnabled[INT_BITS_MAX];

    /** interrupt pending bits for all possible 1020 interupts.
     * one bit per interrupt, 32 bit per word = 32 words */
    uint32_t pendingInt[INT_BITS_MAX];

    /** interrupt active bits for all possible 1020 interupts.
     * one bit per interrupt, 32 bit per word = 32 words */
    uint32_t activeInt[INT_BITS_MAX];

    /** read only running priroity register, 1 per cpu*/
    uint32_t iccrpr[CPU_MAX];

    /** an 8 bit priority (lower is higher priority) for each
     * of the 1020 possible supported interrupts.
     */
    uint8_t intPriority[INT_LINES_MAX];

    /** an 8 bit cpu target id for each shared peripheral interrupt
     * of the 1020 possible supported interrupts.
     */
    uint8_t cpuTarget[INT_LINES_MAX];

    /** 2 bit per interrupt signaling if it's level or edge sensitive
     * and if it is 1:N or N:N */
    uint32_t intConfig[INT_BITS_MAX*2];

    /** CPU enabled */
    bool cpuEnabled[CPU_MAX];

    /** CPU priority */
    uint8_t cpuPriority[CPU_MAX];

    /** Binary point registers */
    uint8_t cpuBpr[CPU_MAX];

    /** highest interrupt that is interrupting CPU */
    uint32_t cpuHighestInt[CPU_MAX];

    /** One bit per cpu per software interrupt that is pending for each possible
     * sgi source. Indexed by SGI number. Each byte in generating cpu id and
     * bits in position is destination id. e.g. 0x4 = CPU 0 generated interrupt
     * for CPU 2. */
    uint64_t cpuSgiPending[SGI_MAX];
    uint64_t cpuSgiActive[SGI_MAX];

    /** One bit per private peripheral interrupt. Only upper 16 bits
     * will be used since PPI interrupts are numberred from 16 to 32 */
    uint32_t cpuPpiPending[CPU_MAX];
    uint32_t cpuPpiActive[CPU_MAX];

    /** Banked interrupt prioirty registers for SGIs and PPIs */
    uint8_t bankedIntPriority[CPU_MAX][SGI_MAX + PPI_MAX];

    /** IRQ Enable Used for debug */
    bool irqEnable;

    /** software generated interrupt
     * @param data data to decode that indicates which cpus to interrupt
     */
    void softInt(int ctx_id, SWI swi);

    /** See if some processor interrupt flags need to be enabled/disabled
     * @param hint which set of interrupts needs to be checked
     */
    void updateIntState(int hint);

    /** Update the register that records priority of the highest priority
     *  active interrupt*/
    void updateRunPri();

    /** generate a bit mask to check cpuSgi for an interrupt. */
    uint64_t genSwiMask(int cpu);

    int intNumToWord(int num) const { return num >> 5; }
    int intNumToBit(int num) const { return num % 32; }

    /** Post an interrupt to a CPU
     */
    void postInt(uint32_t cpu, Tick when);

    /** Event definition to post interrupt to CPU after a delay
    */
    class PostIntEvent : public Event
    {
      private:
        uint32_t cpu;
        Platform *platform;
      public:
        PostIntEvent( uint32_t c, Platform* p)
            : cpu(c), platform(p)
        { }
        void process() { platform->intrctrl->post(cpu, ArmISA::INT_IRQ, 0);}
        const char *description() const { return "Post Interrupt to CPU"; }
    };
    PostIntEvent *postIntEvent[CPU_MAX];

  public:
    typedef Pl390Params Params;
    const Params *
    params() const
    {
        return dynamic_cast<const Params *>(_params);
    }
    Pl390(const Params *p);

    /** @{ */
    /** Return the address ranges used by the Gic
     * This is the distributor address + all cpu addresses
     */
    virtual AddrRangeList getAddrRanges() const;

    /** A PIO read to the device, immediately split up into
     * readDistributor() or readCpu()
     */
    virtual Tick read(PacketPtr pkt);

    /** A PIO read to the device, immediately split up into
     * writeDistributor() or writeCpu()
     */
    virtual Tick write(PacketPtr pkt);
    /** @} */

    /** @{ */
    /** Post an interrupt from a device that is connected to the Gic.
     * Depending on the configuration, the gic will pass this interrupt
     * on through to a CPU.
     * @param number number of interrupt to send */
    void sendInt(uint32_t number);

    /** Interface call for private peripheral interrupts  */
    void sendPPInt(uint32_t num, uint32_t cpu);

    /** Clear an interrupt from a device that is connected to the Gic
     * Depending on the configuration, the gic may de-assert it's cpu line
     * @param number number of interrupt to send */
    void clearInt(uint32_t number);
    /** @} */

    /** @{ */
    /* Various functions fer testing and debugging */
    void driveSPI(uint32_t spi);
    void driveLegIRQ(bool state);
    void driveLegFIQ(bool state);
    void driveIrqEn(bool state);
    /** @} */

    virtual void serialize(std::ostream &os);
    virtual void unserialize(Checkpoint *cp, const std::string &section);

  protected:
    /** Handle a read to the distributor poriton of the GIC
     * @param pkt packet to respond to
     */
    Tick readDistributor(PacketPtr pkt);

    /** Handle a read to the cpu poriton of the GIC
     * @param pkt packet to respond to
     */
    Tick readCpu(PacketPtr pkt);

    /** Handle a write to the distributor poriton of the GIC
     * @param pkt packet to respond to
     */
    Tick writeDistributor(PacketPtr pkt);

    /** Handle a write to the cpu poriton of the GIC
     * @param pkt packet to respond to
     */
    Tick writeCpu(PacketPtr pkt);
};

#endif //__DEV_ARM_GIC_H__
<|endoftext|>