<commit_before>/*
 * Copyright 2011 Mads R. B. Kristensen <madsbk@gmail.com>
 *
 * This file is part of cphVB.
 *
 * cphVB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * cphVB 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with cphVB. If not, see <http://www.gnu.org/licenses/>.
 */

#include <cassert>
#include <cstring>
#include <iostream>
#include <cphvb.h>

#include "cphvb_vem_node.h"
#include "ArrayManager.hpp"

//Function pointers to the VE.
static cphvb_init ve_init;
static cphvb_execute ve_execute;
static cphvb_shutdown ve_shutdown;
static cphvb_reg_func ve_reg_func;

//The VE components
static cphvb_component **vem_node_components;

//Our self
static cphvb_component *vem_node_myself;

//Number of user-defined functions registered.
static cphvb_intp vem_userfunc_count = 0;

#define PLAININST (1)
#define REDUCEINST (2)

ArrayManager* arrayManager;

/* Initialize the VEM
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_init(cphvb_component *self)
{
    cphvb_intp children_count;
    cphvb_error err;
    vem_node_myself = self;

    err = cphvb_component_children(self, &children_count, &vem_node_components);
    if (children_count != 1)
    {
		std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
		return CPHVB_ERROR;
    }

    if (err != CPHVB_SUCCESS)
	    return err;

    ve_init = vem_node_components[0]->init;
    ve_execute = vem_node_components[0]->execute;
    ve_shutdown = vem_node_components[0]->shutdown;
    ve_reg_func = vem_node_components[0]->reg_func;

    //Let us initiate the simple VE and register what it supports.
    err = ve_init(vem_node_components[0]);
    if(err)
        return err;

    try
    {
        arrayManager = new ArrayManager();
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
        return CPHVB_ERROR;
    }

    return CPHVB_SUCCESS;
}

/* Shutdown the VEM, which include a instruction flush
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_shutdown(void)
{
    cphvb_error err;
    err = ve_shutdown();
    cphvb_component_free(vem_node_components[0]);//Only got one child.
    ve_init = NULL;
    ve_execute = NULL;
    ve_shutdown = NULL;
    ve_reg_func= NULL;
    cphvb_component_free_ptr(vem_node_components);
    vem_node_components = NULL;
    delete arrayManager;
    arrayManager = NULL;
    return err;
}

/* Create an array, which are handled by the VEM.
 *
 * @base Pointer to the base array. If NULL this is a base array
 * @type The type of data in the array
 * @ndim Number of dimensions
 * @start Index of the start element (always 0 for base-array)
 * @shape[CPHVB_MAXDIM] Number of elements in each dimention
 * @stride[CPHVB_MAXDIM] The stride for each dimention
 * @new_array The handler for the newly created array
 * @return Error code (CPHVB_SUCCESS, CPHVB_OUT_OF_MEMORY)
 */
cphvb_error cphvb_vem_node_create_array(cphvb_array*   base,
                                        cphvb_type     type,
                                        cphvb_intp     ndim,
                                        cphvb_index    start,
                                        cphvb_index    shape[CPHVB_MAXDIM],
                                        cphvb_index    stride[CPHVB_MAXDIM],
                                        cphvb_array**  new_array)
{

    try
    {
        *new_array = arrayManager->create(base, type, ndim, start, shape, stride);
    }
    catch(std::exception& e)
    {
        return CPHVB_OUT_OF_MEMORY;
    }
    #ifdef CPHVB_TRACE
        cphvb_component_trace_array(vem_node_myself, *new_array);
    #endif

    return CPHVB_SUCCESS;
}

/* Register a new user-defined function.
 *
 * @lib Name of the shared library e.g. libmyfunc.so
 *      When NULL the default library is used.
 * @fun Name of the function e.g. myfunc
 * @id Identifier for the new function. The bridge should set the
 *     initial value to Zero. (in/out-put)
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_reg_func(char *fun, cphvb_intp *id)
{
	cphvb_error e;
	cphvb_intp tmpid;

    if(*id == 0)//Only if parent didn't set the ID.
        tmpid = vem_userfunc_count + 1;

    e = ve_reg_func(fun, &tmpid);

    //If the call succeeded, register the id as taken and return it
    if (e == CPHVB_SUCCESS)
    {
	    if (tmpid > vem_userfunc_count)
	    	vem_userfunc_count = tmpid;
    	*id = tmpid;
    }

    return e;
}

/* Execute a list of instructions (blocking, for the time being).
 * It is required that the VEM supports all instructions in the list.
 *
 * @instruction A list of instructions to execute
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_execute(cphvb_intp count,
                                   cphvb_instruction inst_list[])
{
    cphvb_intp i;

	if (count <= 0)
		return CPHVB_SUCCESS;

    for(i=0; i<count; ++i)
    {
        cphvb_instruction* inst = &inst_list[i];
        #ifdef CPHVB_TRACE
            cphvb_component_trace_inst(vem_node_myself, inst);
        #endif
        switch(inst->opcode)
        {
        	//Special handling
			case CPHVB_FREE:
			case CPHVB_SYNC:
			case CPHVB_DISCARD:
			{
				switch(inst->opcode)
				{
					case CPHVB_FREE:
						assert(inst->operand[0]->base == NULL);
						arrayManager->freePending(inst);
						break;
					case CPHVB_DISCARD:
						arrayManager->erasePending(inst);
						break;
					case CPHVB_SYNC:
						arrayManager->changeOwnerPending(inst, cphvb_base_array(inst->operand[0]), CPHVB_SELF);
						break;
					default:
						assert(false);
				}
				break;
			}
			case CPHVB_USERFUNC:
			{
				cphvb_userfunc *uf = inst->userfunc;
				//The children should own the output arrays.
				for(int j = 0; j < uf->nout; ++j)
				{
					cphvb_array* base = cphvb_base_array(uf->operand[j]);
					base->owner = CPHVB_CHILD;
				}
				//We should own the input arrays.
				for(int j = uf->nout; j < uf->nout + uf->nin; ++j)
				{
					cphvb_array* base = cphvb_base_array(uf->operand[j]);
					if(base->owner == CPHVB_PARENT)
					{
						base->owner = CPHVB_SELF;
					}
				}
				break;
			}
			default:
			{
				cphvb_array* base = cphvb_base_array(inst->operand[0]);
				// "Regular" operation: set ownership and send down stream
				base->owner = CPHVB_CHILD;//The child owns the output ary.
				for (int j = 1; j < cphvb_operands(inst->opcode); ++j)
				{
					if(!cphvb_is_constant(inst->operand[j]) &&
					   cphvb_base_array(inst->operand[j])->owner == CPHVB_PARENT)
					{
						cphvb_base_array(inst->operand[j])->owner = CPHVB_SELF;
					}
				}
			}
        }
    }

	cphvb_error e1 = ve_execute(count, inst_list);
	cphvb_error e2 = arrayManager->flush();
	if (e1 != CPHVB_SUCCESS)
		return e1;
	else if (e2 != CPHVB_SUCCESS)
		return e2;
	else
		return CPHVB_SUCCESS;
}
<commit_msg>Minor cleanup in the VEM-NODE<commit_after>/*
 * Copyright 2011 Mads R. B. Kristensen <madsbk@gmail.com>
 *
 * This file is part of cphVB.
 *
 * cphVB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * cphVB 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with cphVB. If not, see <http://www.gnu.org/licenses/>.
 */

#include <cassert>
#include <cstring>
#include <iostream>
#include <cphvb.h>

#include "cphvb_vem_node.h"
#include "ArrayManager.hpp"

//Function pointers to the VE.
static cphvb_init ve_init;
static cphvb_execute ve_execute;
static cphvb_shutdown ve_shutdown;
static cphvb_reg_func ve_reg_func;

//The VE components
static cphvb_component **vem_node_components;

//Our self
static cphvb_component *vem_node_myself;

//Number of user-defined functions registered.
static cphvb_intp vem_userfunc_count = 0;

ArrayManager* arrayManager;

/* Initialize the VEM
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_init(cphvb_component *self)
{
    cphvb_intp children_count;
    cphvb_error err;
    vem_node_myself = self;

    err = cphvb_component_children(self, &children_count, &vem_node_components);
    if (children_count != 1)
    {
		std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
		return CPHVB_ERROR;
    }

    if (err != CPHVB_SUCCESS)
	    return err;

    ve_init = vem_node_components[0]->init;
    ve_execute = vem_node_components[0]->execute;
    ve_shutdown = vem_node_components[0]->shutdown;
    ve_reg_func = vem_node_components[0]->reg_func;

    //Let us initiate the simple VE and register what it supports.
    if((err = ve_init(vem_node_components[0])) != 0)
        return err;

    try
    {
        arrayManager = new ArrayManager();
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
        return CPHVB_ERROR;
    }

    return CPHVB_SUCCESS;
}

/* Shutdown the VEM, which include a instruction flush
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_shutdown(void)
{
    cphvb_error err;
    err = ve_shutdown();
    cphvb_component_free(vem_node_components[0]);//Only got one child.
    ve_init     = NULL;
    ve_execute  = NULL;
    ve_shutdown = NULL;
    ve_reg_func = NULL;
    cphvb_component_free_ptr(vem_node_components);
    vem_node_components = NULL;
    delete arrayManager;
    arrayManager = NULL;
    return err;
}

/* Create an array, which are handled by the VEM.
 *
 * @base Pointer to the base array. If NULL this is a base array
 * @type The type of data in the array
 * @ndim Number of dimensions
 * @start Index of the start element (always 0 for base-array)
 * @shape[CPHVB_MAXDIM] Number of elements in each dimention
 * @stride[CPHVB_MAXDIM] The stride for each dimention
 * @new_array The handler for the newly created array
 * @return Error code (CPHVB_SUCCESS, CPHVB_OUT_OF_MEMORY)
 */
cphvb_error cphvb_vem_node_create_array(cphvb_array*   base,
                                        cphvb_type     type,
                                        cphvb_intp     ndim,
                                        cphvb_index    start,
                                        cphvb_index    shape[CPHVB_MAXDIM],
                                        cphvb_index    stride[CPHVB_MAXDIM],
                                        cphvb_array**  new_array)
{
    try
    {
        *new_array = arrayManager->create(base, type, ndim, start, shape, stride);
    }
    catch(std::exception& e)
    {
        return CPHVB_OUT_OF_MEMORY;
    }
    #ifdef CPHVB_TRACE
        cphvb_component_trace_array(vem_node_myself, *new_array);
    #endif

    return CPHVB_SUCCESS;
}

/* Register a new user-defined function.
 *
 * @lib Name of the shared library e.g. libmyfunc.so
 *      When NULL the default library is used.
 * @fun Name of the function e.g. myfunc
 * @id Identifier for the new function. The bridge should set the
 *     initial value to Zero. (in/out-put)
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_reg_func(char *fun, cphvb_intp *id)
{
	cphvb_error e;
	cphvb_intp tmpid;

    if(*id == 0)//Only if parent didn't set the ID.
        tmpid = vem_userfunc_count + 1;

    e = ve_reg_func(fun, &tmpid);

    //If the call succeeded, register the id as taken and return it
    if (e == CPHVB_SUCCESS)
    {
	    if (tmpid > vem_userfunc_count)
	    	vem_userfunc_count = tmpid;
    	*id = tmpid;
    }

    return e;
}

/* Execute a list of instructions (blocking, for the time being).
 * It is required that the VEM supports all instructions in the list.
 *
 * @instruction A list of instructions to execute
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_execute(cphvb_intp count,
                                   cphvb_instruction inst_list[])
{
    cphvb_intp i;

	if (count <= 0)
		return CPHVB_SUCCESS;

    for(i=0; i<count; ++i)
    {
        cphvb_instruction* inst = &inst_list[i];
        #ifdef CPHVB_TRACE
            cphvb_component_trace_inst(vem_node_myself, inst);
        #endif
        switch(inst->opcode)
        {
        	//Special handling
			case CPHVB_FREE:
			case CPHVB_SYNC:
			case CPHVB_DISCARD:
			{
				switch(inst->opcode)
				{
					case CPHVB_FREE:
						assert(inst->operand[0]->base == NULL);
						arrayManager->freePending(inst);
						break;
					case CPHVB_DISCARD:
						arrayManager->erasePending(inst);
						break;
					case CPHVB_SYNC:
						arrayManager->changeOwnerPending(inst, cphvb_base_array(inst->operand[0]), CPHVB_SELF);
						break;
					default:
						assert(false);
				}
				break;
			}
			case CPHVB_USERFUNC:
			{
				cphvb_userfunc *uf = inst->userfunc;
				//The children should own the output arrays.
				for(int j = 0; j < uf->nout; ++j)
				{
					cphvb_array* base = cphvb_base_array(uf->operand[j]);
					base->owner = CPHVB_CHILD;
				}
				//We should own the input arrays.
				for(int j = uf->nout; j < uf->nout + uf->nin; ++j)
				{
					cphvb_array* base = cphvb_base_array(uf->operand[j]);
					if(base->owner == CPHVB_PARENT)
					{
						base->owner = CPHVB_SELF;
					}
				}
				break;
			}
			default:
			{
				cphvb_array* base = cphvb_base_array(inst->operand[0]);
				// "Regular" operation: set ownership and send down stream
				base->owner = CPHVB_CHILD;//The child owns the output ary.
				for (int j = 1; j < cphvb_operands(inst->opcode); ++j)
				{
					if(!cphvb_is_constant(inst->operand[j]) &&
					   cphvb_base_array(inst->operand[j])->owner == CPHVB_PARENT)
					{
						cphvb_base_array(inst->operand[j])->owner = CPHVB_SELF;
					}
				}
			}
        }
    }

	cphvb_error e1 = ve_execute(count, inst_list);
	cphvb_error e2 = arrayManager->flush();
	if (e1 != CPHVB_SUCCESS)
		return e1;
	else if (e2 != CPHVB_SUCCESS)
		return e2;
	else
		return CPHVB_SUCCESS;
}
<|endoftext|>


<commit_before>#include <catch2/catch.hpp>

#include "pressed_keys_manager.hpp"

TEST_CASE("pressed_keys_manager") {
  // empty

  {
    krbn::pressed_keys_manager manager;

    REQUIRE(manager.empty());
  }

  // key_code

  {
    krbn::pressed_keys_manager manager;

    REQUIRE(!manager.exists(krbn::key_code::a));

    manager.insert(krbn::key_code::a);
    REQUIRE(!manager.empty());

    REQUIRE(manager.exists(krbn::key_code::a));

    manager.erase(krbn::key_code::a);
    REQUIRE(manager.empty());

    REQUIRE(!manager.exists(krbn::key_code::a));
  }

  // Duplicated key_code

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::key_code::a);
    manager.insert(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.erase(krbn::key_code::a);
    REQUIRE(manager.empty());
  }

  // consumer_key_code

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::consumer_key_code::mute);
    REQUIRE(!manager.empty());

    manager.erase(krbn::consumer_key_code::mute);
    REQUIRE(manager.empty());
  }

  // pointing_button

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::pointing_button::button1);
    REQUIRE(!manager.empty());

    manager.erase(krbn::pointing_button::button1);
    REQUIRE(manager.empty());
  }

  // combination

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.insert(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.insert(krbn::consumer_key_code::mute);
    REQUIRE(!manager.empty());

    manager.insert(krbn::pointing_button::button1);
    REQUIRE(!manager.empty());

    manager.erase(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.erase(krbn::consumer_key_code::mute);
    REQUIRE(!manager.empty());

    manager.erase(krbn::pointing_button::button10);
    REQUIRE(!manager.empty());

    manager.erase(krbn::pointing_button::button1);
    REQUIRE(manager.empty());
  }
}
<commit_msg>fix tests<commit_after>#include <catch2/catch.hpp>

#include "pressed_keys_manager.hpp"

TEST_CASE("pressed_keys_manager") {
  // empty

  {
    krbn::pressed_keys_manager manager;

    REQUIRE(manager.empty());
  }

  // key_code

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.erase(krbn::key_code::a);
    REQUIRE(manager.empty());
  }

  // Duplicated key_code

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::key_code::a);
    manager.insert(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.erase(krbn::key_code::a);
    REQUIRE(manager.empty());
  }

  // consumer_key_code

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::consumer_key_code::mute);
    REQUIRE(!manager.empty());

    manager.erase(krbn::consumer_key_code::mute);
    REQUIRE(manager.empty());
  }

  // pointing_button

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::pointing_button::button1);
    REQUIRE(!manager.empty());

    manager.erase(krbn::pointing_button::button1);
    REQUIRE(manager.empty());
  }

  // combination

  {
    krbn::pressed_keys_manager manager;

    manager.insert(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.insert(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.insert(krbn::consumer_key_code::mute);
    REQUIRE(!manager.empty());

    manager.insert(krbn::pointing_button::button1);
    REQUIRE(!manager.empty());

    manager.erase(krbn::key_code::a);
    REQUIRE(!manager.empty());

    manager.erase(krbn::consumer_key_code::mute);
    REQUIRE(!manager.empty());

    manager.erase(krbn::pointing_button::button10);
    REQUIRE(!manager.empty());

    manager.erase(krbn::pointing_button::button1);
    REQUIRE(manager.empty());
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: colorlistener.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-25 18:21:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "classes/colorlistener.hxx"

//__________________________________________
// own includes

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

//__________________________________________
// interface includes

#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_INVALIDATESTYLE_HPP_
#include <com/sun/star/awt/InvalidateStyle.hpp>
#endif

//__________________________________________
// other includes

#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif

#ifndef _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//__________________________________________
// definition

namespace framework
{

DEFINE_XINTERFACE_1( ColorListener                             ,
                     OWeakObject                               ,
                     DIRECT_INTERFACE(css::lang::XEventListener))

//__________________________________________

/** initialize new instance of this class.

    It set the window, on which we must apply our detecte color changes.
    We start listening for changes and(!) window disposing here too.

    @attention  Some ressources will be created on demand!

    @param  xWindow
                reference to the window
 */

ColorListener::ColorListener( const css::uno::Reference< css::awt::XWindow >& xWindow )
    : ThreadHelpBase(&Application::GetSolarMutex())
    , SfxListener   (                             )
    , m_xWindow     (xWindow                      )
    , m_bListen     (sal_False                    )
    , m_pConfig     (NULL                         )
{
    impl_startListening();
    impl_applyColor();
}

//__________________________________________

/** deinitialize new instance of this class.

    Because it's done at different places ... we use an impl method!

    see impl_die()
 */

ColorListener::~ColorListener()
{
    impl_die();
}

//__________________________________________

/** callback for color changes.

    @param  rBroadcaster
                should be our referenced config item (or any helper of it!)

    @param  rHint
                transport an ID, which identify the broadcasted message
 */

void ColorListener::Notify( SfxBroadcaster& rBroadCaster, const SfxHint& rHint )
{
    if (((SfxSimpleHint&)rHint).GetId()==SFX_HINT_COLORS_CHANGED)
        impl_applyColor();
}

void ColorListener::impl_applyColor()
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);

    if (m_pConfig)
    {
        css::uno::Reference< css::awt::XWindowPeer > xPeer(m_xWindow, css::uno::UNO_QUERY);
        ::svtools::ColorConfigValue aBackgroundColor = m_pConfig->GetColorValue( ::svtools::APPBACKGROUND );
        if (xPeer.is())
        {
            xPeer->setBackground(aBackgroundColor.nColor);
            xPeer->invalidate(
                css::awt::InvalidateStyle::UPDATE | css::awt::InvalidateStyle::CHILDREN | css::awt::InvalidateStyle::NOTRANSPARENT );
        }
    }

    aReadLock.unlock();
    /* } SAFE */
}

//__________________________________________

/** callback for window destroy.

    We must react here automaticly and forget our window reference.
    We can die immediatly too. Because there is nothing to do any longer.

    @param  aEvent
                must referr to our window.

    @throw  ::com::sun::star::uno::RuntimeException
                if event source doesn't points to our internal saved window.
 */
void SAL_CALL ColorListener::disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException)
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);

    if (aEvent.Source!=m_xWindow)
        throw css::uno::RuntimeException(
            DECLARE_ASCII(""),
            css::uno::Reference< css::uno::XInterface >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );

    impl_die();

    aReadLock.unlock();
    /* } SAFE */
}

//__________________________________________

/** starts listening for color changes and window destroy.

    We create the needed config singleton on demand here.
 */

void ColorListener::impl_startListening()
{
    /* SAFE { */
    WriteGuard aWriteLock(m_aLock);

    if (!m_bListen)
    {
        if (!m_pConfig)
            m_pConfig = new ::svtools::ColorConfig();

        StartListening(*(SfxBroadcaster*)m_pConfig);

        css::uno::Reference< css::lang::XComponent > xDispose(m_xWindow, css::uno::UNO_QUERY);
        if (xDispose.is())
            xDispose->addEventListener( css::uno::Reference< css::lang::XEventListener >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );

        m_bListen = sal_True;
    }

    aWriteLock.unlock();
    /* } SAFE */
}

//__________________________________________

/** stops listening for color changes and window destroy.
 */
void ColorListener::impl_stopListening()
{
    /* SAFE { */
    WriteGuard aWriteLock(m_aLock);

    if (m_bListen)
    {
        EndListeningAll();

        delete m_pConfig;
        m_pConfig = NULL;

        css::uno::Reference< css::lang::XComponent > xDispose(m_xWindow, css::uno::UNO_QUERY);
        if (xDispose.is())
            xDispose->removeEventListener( css::uno::Reference< css::lang::XEventListener >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );

        m_bListen = sal_False;
    }

    aWriteLock.unlock();
    /* } SAFE */
}

//__________________________________________

/** release all used references.

    Free all used memory and release any used references.
    Of course cancel all existing listener connections, to be
    shure never be called again.
 */
void ColorListener::impl_die()
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);

    // Attention: Deleting of our broadcaster will may force a Notify() call.
    // To supress that, we have to disable our listener connection first.
    impl_stopListening();
    m_xWindow = css::uno::Reference< css::awt::XWindow >();

    aReadLock.unlock();
    /* } SAFE */
}

} // namespace framework
<commit_msg>INTEGRATION: CWS mav4 (1.2.10); FILE MERGED 2003/04/23 13:17:52 as 1.2.10.1: #109052# HACK: refresh background color if it was changed by 3rdparty!<commit_after>/*************************************************************************
 *
 *  $RCSfile: colorlistener.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-24 13:33:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "classes/colorlistener.hxx"

//__________________________________________
// own includes

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

//__________________________________________
// interface includes

#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_INVALIDATESTYLE_HPP_
#include <com/sun/star/awt/InvalidateStyle.hpp>
#endif

//__________________________________________
// other includes

#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif

#ifndef _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif

//__________________________________________
// definition

namespace framework
{

DEFINE_XINTERFACE_1( ColorListener                             ,
                     OWeakObject                               ,
                     DIRECT_INTERFACE(css::lang::XEventListener))

//__________________________________________

/** initialize new instance of this class.

    It set the window, on which we must apply our detecte color changes.
    We start listening for changes and(!) window disposing here too.

    @attention  Some ressources will be created on demand!

    @param  xWindow
                reference to the window
 */

ColorListener::ColorListener( const css::uno::Reference< css::awt::XWindow >& xWindow )
    : ThreadHelpBase(&Application::GetSolarMutex())
    , SfxListener   (                             )
    , m_xWindow     (xWindow                      )
    , m_bListen     (sal_False                    )
    , m_pConfig     (NULL                         )
{
    impl_startListening();
    impl_applyColor(sal_True);
}

//__________________________________________

/** deinitialize new instance of this class.

    Because it's done at different places ... we use an impl method!

    see impl_die()
 */

ColorListener::~ColorListener()
{
    impl_die();
}

//__________________________________________

/** callback for color changes.

    @param  rBroadcaster
                should be our referenced config item (or any helper of it!)

    @param  rHint
                transport an ID, which identify the broadcasted message
 */

void ColorListener::Notify( SfxBroadcaster& rBroadCaster, const SfxHint& rHint )
{
    if (((SfxSimpleHint&)rHint).GetId()==SFX_HINT_COLORS_CHANGED)
        impl_applyColor(sal_True);
}

void ColorListener::impl_applyColor( sal_Bool bInvalidate )
{
    /* SAFE { */
    WriteGuard aWriteLock(m_aLock);

    if (m_pConfig)
    {
        css::uno::Reference< css::awt::XWindowPeer > xPeer(m_xWindow, css::uno::UNO_QUERY);
        ::svtools::ColorConfigValue aBackgroundColor = m_pConfig->GetColorValue( ::svtools::APPBACKGROUND );
        if (xPeer.is())
        {
            m_nColor = aBackgroundColor.nColor;
            xPeer->setBackground(m_nColor);
            if (bInvalidate)
            {
                xPeer->invalidate(
                    css::awt::InvalidateStyle::UPDATE | css::awt::InvalidateStyle::CHILDREN | css::awt::InvalidateStyle::NOTRANSPARENT );
            }
        }
    }

    aWriteLock.unlock();
    /* } SAFE */
}

//__________________________________________

/** callback for window destroy.

    We must react here automaticly and forget our window reference.
    We can die immediatly too. Because there is nothing to do any longer.

    @param  aEvent
                must referr to our window.

    @throw  ::com::sun::star::uno::RuntimeException
                if event source doesn't points to our internal saved window.
 */
void SAL_CALL ColorListener::disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException)
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);

    if (aEvent.Source!=m_xWindow)
        throw css::uno::RuntimeException(
            DECLARE_ASCII(""),
            css::uno::Reference< css::uno::XInterface >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );

    impl_die();

    aReadLock.unlock();
    /* } SAFE */
}

IMPL_LINK( ColorListener, impl_SettingsChanged, void*, pVoid )
{
    VclWindowEvent* pEvent = (VclWindowEvent*)pVoid;
    if (pEvent->GetId() != VCLEVENT_APPLICATION_DATACHANGED)
        return 0L;

    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    Window* pWindow = VCLUnoHelper::GetWindow(m_xWindow);
    if (!pWindow)
        return 0L;

    OutputDevice* pDevice = (OutputDevice*)pWindow;
    long nNewColor = (long)(pDevice->GetBackground().GetColor().GetColor());

    if (m_nColor != nNewColor)
        impl_applyColor(sal_False);
    aReadLock.unlock();
    /* } SAFE */

    return 0L;
}

//__________________________________________

/** starts listening for color changes and window destroy.

    We create the needed config singleton on demand here.
 */

void ColorListener::impl_startListening()
{
    /* SAFE { */
    WriteGuard aWriteLock(m_aLock);

    if (!m_bListen)
    {
        Application::AddEventListener( LINK( this, ColorListener, impl_SettingsChanged ) );

        if (!m_pConfig)
            m_pConfig = new ::svtools::ColorConfig();

        StartListening(*(SfxBroadcaster*)m_pConfig);

        css::uno::Reference< css::lang::XComponent > xDispose(m_xWindow, css::uno::UNO_QUERY);
        if (xDispose.is())
            xDispose->addEventListener( css::uno::Reference< css::lang::XEventListener >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );

        m_bListen = sal_True;
    }

    aWriteLock.unlock();
    /* } SAFE */
}

//__________________________________________

/** stops listening for color changes and window destroy.
 */
void ColorListener::impl_stopListening()
{
    /* SAFE { */
    WriteGuard aWriteLock(m_aLock);

    if (m_bListen)
    {
        Application::RemoveEventListener( LINK( this, ColorListener, impl_SettingsChanged ) );

        EndListeningAll();

        delete m_pConfig;
        m_pConfig = NULL;

        css::uno::Reference< css::lang::XComponent > xDispose(m_xWindow, css::uno::UNO_QUERY);
        if (xDispose.is())
            xDispose->removeEventListener( css::uno::Reference< css::lang::XEventListener >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY) );

        m_bListen = sal_False;
    }

    aWriteLock.unlock();
    /* } SAFE */
}

//__________________________________________

/** release all used references.

    Free all used memory and release any used references.
    Of course cancel all existing listener connections, to be
    shure never be called again.
 */
void ColorListener::impl_die()
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);

    // Attention: Deleting of our broadcaster will may force a Notify() call.
    // To supress that, we have to disable our listener connection first.
    impl_stopListening();
    m_xWindow = css::uno::Reference< css::awt::XWindow >();

    aReadLock.unlock();
    /* } SAFE */
}

} // namespace framework
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: registertemp.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:07:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
//  includes of my own project
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_
#include <macros/registration.hxx>
#endif

/*=================================================================================================================
    Add new include and new register info to for new services.

    Example:

        #ifndef __YOUR_SERVICE_1_HXX_
        #include <service1.hxx>
        #endif

        #ifndef __YOUR_SERVICE_2_HXX_
        #include <service2.hxx>
        #endif

        COMPONENTGETIMPLEMENTATIONENVIRONMENT

        COMPONENTWRITEINFO  (   COMPONENTINFO( Service1 )
                                 COMPONENTINFO( Service2 )
                            )

        COMPONENTGETFACTORY (   IFFACTORIE( Service1 )
                                 else
                                IFFACTORIE( Service2 )
                             )
=================================================================================================================*/

#ifndef __FRAMEWORK_SERVICES_MEDIATYPEDETECTIONHELPER_HXX_
#include <services/mediatypedetectionhelper.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_SUBSTPATHVARS_HXX_
#include <services/substitutepathvars.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_PATHSETTINGS_HXX_
#include <services/pathsettings.hxx>
#endif

COMPONENTGETIMPLEMENTATIONENVIRONMENT

COMPONENTWRITEINFO  (   COMPONENTINFO( ::framework::MediaTypeDetectionHelper    )
                        COMPONENTINFO( ::framework::SubstitutePathVariables     )
                        COMPONENTINFO( ::framework::PathSettings                )
                    )

COMPONENTGETFACTORY (   IFFACTORY( ::framework::MediaTypeDetectionHelper        )   else
                        IFFACTORY( ::framework::SubstitutePathVariables         )   else
                        IFFACTORY( ::framework::PathSettings                    )
                    )
<commit_msg>INTEGRATION: CWS changefileheader (1.11.262); FILE MERGED 2008/04/01 10:58:11 thb 1.11.262.2: #i85898# Stripping all external header guards 2008/03/28 15:35:25 rt 1.11.262.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: registertemp.cxx,v $
 * $Revision: 1.12 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
//  includes of my own project
//_________________________________________________________________________________________________________________
#include <macros/registration.hxx>

/*=================================================================================================================
    Add new include and new register info to for new services.

    Example:

        #ifndef __YOUR_SERVICE_1_HXX_
        #include <service1.hxx>
        #endif

        #ifndef __YOUR_SERVICE_2_HXX_
        #include <service2.hxx>
        #endif

        COMPONENTGETIMPLEMENTATIONENVIRONMENT

        COMPONENTWRITEINFO  (   COMPONENTINFO( Service1 )
                                 COMPONENTINFO( Service2 )
                            )

        COMPONENTGETFACTORY (   IFFACTORIE( Service1 )
                                 else
                                IFFACTORIE( Service2 )
                             )
=================================================================================================================*/
#include <services/mediatypedetectionhelper.hxx>
#include <services/substitutepathvars.hxx>
#include <services/pathsettings.hxx>

COMPONENTGETIMPLEMENTATIONENVIRONMENT

COMPONENTWRITEINFO  (   COMPONENTINFO( ::framework::MediaTypeDetectionHelper    )
                        COMPONENTINFO( ::framework::SubstitutePathVariables     )
                        COMPONENTINFO( ::framework::PathSettings                )
                    )

COMPONENTGETFACTORY (   IFFACTORY( ::framework::MediaTypeDetectionHelper        )   else
                        IFFACTORY( ::framework::SubstitutePathVariables         )   else
                        IFFACTORY( ::framework::PathSettings                    )
                    )
<|endoftext|>


<commit_before>#include <mbed.h>
#include <cmsis_os.h>
#include <memory>

#include "SharedSPI.hpp"
#include "CC1201Radio.hpp"
#include "logger.hpp"
#include "pins.hpp"
#include "usb-interface.hpp"
#include "watchdog.hpp"
#include "RJBaseUSBDevice.hpp"

#define RJ_WATCHDOG_TIMER_VALUE 2  // seconds

using namespace std;

// USBHID interface.  The false at the end tells it not to connect initially
RJBaseUSBDevice usbLink(RJ_BASE2015_VENDOR_ID, RJ_BASE2015_PRODUCT_ID,
                        RJ_BASE2015_RELEASE);

bool initRadio() {
    // setup SPI bus
    shared_ptr<SharedSPI> sharedSPI =
        make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
    sharedSPI->format(8, 0);  // 8 bits per transfer

    // RX/TX leds
    auto rxTimeoutLED = make_shared<FlashingTimeoutLED>(LED1);
    auto txTimeoutLED = make_shared<FlashingTimeoutLED>(LED2);

    // Startup the CommModule interface
    CommModule::Instance = make_shared<CommModule>(rxTimeoutLED, txTimeoutLED);
    shared_ptr<CommModule> commModule = CommModule::Instance;

    // Create a new physical hardware communication link
    global_radio =
        new CC1201(sharedSPI, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings,
                   sizeof(preferredSettings) / sizeof(registerSetting_t));

    return global_radio->isConnected();
}

void radioRxHandler(rtp::packet* pkt) {
    // write packet content out to endpoint 1
    vector<uint8_t> buffer;
    pkt->pack(&buffer);
    bool success = usbLink.writeNB(1, buffer.data(), buffer.size(),
                                   MAX_PACKET_SIZE_EPBULK);

    if (!success) {
        LOG(WARN, "Failed to transfer received packet over usb");
    }
}

int main() {
    // set baud rate to higher value than the default for faster terminal
    Serial s(RJ_SERIAL_RXTX);
    s.baud(57600);

    // Set the default logging configurations
    isLogging = RJ_LOGGING_EN;
    rjLogLevel = INIT;

    LOG(INIT, "Base station starting...");

    if (initRadio()) {
        LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq());

        // register handlers for any ports we might use
        for (rtp::port port :
             {rtp::port::CONTROL, rtp::port::PING, rtp::port::LEGACY}) {
            CommModule::Instance->setRxHandler(&radioRxHandler, port);
            CommModule::Instance->setTxHandler((CommLink*)global_radio,
                                               &CommLink::sendPacket, port);
        }
    } else {
        LOG(FATAL, "No radio interface found!");
    }

    DigitalOut radioStatusLed(LED4, global_radio->isConnected());

    // set callbacks for usb control transfers
    usbLink.writeRegisterCallback = [](uint8_t reg, uint8_t val) {
        global_radio->writeReg(reg, val);
    };
    usbLink.readRegisterCallback = [](uint8_t reg) {
        return global_radio->readReg(reg);
    };
    usbLink.strobeCallback = [](uint8_t strobe) {
        global_radio->strobe(strobe);
    };

    LOG(INIT, "Initializing USB interface...");
    usbLink.connect();  // note: this blocks until the link is connected
    LOG(INIT, "Initialized USB interface!");

    // Set the watdog timer's initial config
    Watchdog::Set(RJ_WATCHDOG_TIMER_VALUE);

    LOG(INIT, "Listening for commands over USB");

    uint8_t buf[MAX_PACKET_SIZE_EPBULK];
    uint32_t bufSize;

    while (true) {
        // make sure we can always reach back to main by renewing the watchdog
        // timer periodically
        Watchdog::Renew();

        // attempt to read data from endpoint 2
        // if data is available, write it into @pkt and send it
        if (usbLink.readEP_NB(2, buf, &bufSize, sizeof(buf))) {
            // construct packet from buffer received over USB
            rtp::packet pkt;
            pkt.recv(buf, bufSize);

            // transmit!
            CommModule::Instance->send(pkt);
        }
    }
}
<commit_msg>checkstyle patch<commit_after>#include <mbed.h>
#include <cmsis_os.h>
#include <memory>

#include "SharedSPI.hpp"
#include "CC1201Radio.hpp"
#include "logger.hpp"
#include "pins.hpp"
#include "usb-interface.hpp"
#include "watchdog.hpp"
#include "RJBaseUSBDevice.hpp"

#define RJ_WATCHDOG_TIMER_VALUE 2  // seconds

using namespace std;

// USBHID interface.  The false at the end tells it not to connect initially
RJBaseUSBDevice usbLink(RJ_BASE2015_VENDOR_ID, RJ_BASE2015_PRODUCT_ID,
                        RJ_BASE2015_RELEASE);

bool initRadio() {
    // setup SPI bus
    shared_ptr<SharedSPI> sharedSPI =
        make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
    sharedSPI->format(8, 0);  // 8 bits per transfer

    // RX/TX leds
    auto rxTimeoutLED = make_shared<FlashingTimeoutLED>(LED1);
    auto txTimeoutLED = make_shared<FlashingTimeoutLED>(LED2);

    // Startup the CommModule interface
    CommModule::Instance = make_shared<CommModule>(rxTimeoutLED, txTimeoutLED);
    shared_ptr<CommModule> commModule = CommModule::Instance;

    // Create a new physical hardware communication link
    global_radio =
        new CC1201(sharedSPI, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings,
                   sizeof(preferredSettings) / sizeof(registerSetting_t));

    return global_radio->isConnected();
}

void radioRxHandler(rtp::packet* pkt) {
    // write packet content out to endpoint 1
    vector<uint8_t> buffer;
    pkt->pack(&buffer);
    bool success = usbLink.writeNB(1, buffer.data(), buffer.size(),
                                   MAX_PACKET_SIZE_EPBULK);

    if (!success) {
        LOG(WARN, "Failed to transfer received packet over usb");
    }
}

int main() {
    // set baud rate to higher value than the default for faster terminal
    Serial s(RJ_SERIAL_RXTX);
    s.baud(57600);

    // Set the default logging configurations
    isLogging = RJ_LOGGING_EN;
    rjLogLevel = INIT;

    LOG(INIT, "Base station starting...");

    if (initRadio()) {
        LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq());

        // register handlers for any ports we might use
        for (rtp::port port :
             {rtp::port::CONTROL, rtp::port::PING, rtp::port::LEGACY}) {
            CommModule::Instance->setRxHandler(&radioRxHandler, port);
            CommModule::Instance->setTxHandler((CommLink*)global_radio,
                                               &CommLink::sendPacket, port);
        }
    } else {
        LOG(FATAL, "No radio interface found!");
    }

    DigitalOut radioStatusLed(LED4, global_radio->isConnected());

    // set callbacks for usb control transfers
    usbLink.writeRegisterCallback =
        [](uint8_t reg, uint8_t val) { global_radio->writeReg(reg, val); };
    usbLink.readRegisterCallback =
        [](uint8_t reg) { return global_radio->readReg(reg); };
    usbLink.strobeCallback =
        [](uint8_t strobe) { global_radio->strobe(strobe); };

    LOG(INIT, "Initializing USB interface...");
    usbLink.connect();  // note: this blocks until the link is connected
    LOG(INIT, "Initialized USB interface!");

    // Set the watdog timer's initial config
    Watchdog::Set(RJ_WATCHDOG_TIMER_VALUE);

    LOG(INIT, "Listening for commands over USB");

    uint8_t buf[MAX_PACKET_SIZE_EPBULK];
    uint32_t bufSize;

    while (true) {
        // make sure we can always reach back to main by renewing the watchdog
        // timer periodically
        Watchdog::Renew();

        // attempt to read data from endpoint 2
        // if data is available, write it into @pkt and send it
        if (usbLink.readEP_NB(2, buf, &bufSize, sizeof(buf))) {
            // construct packet from buffer received over USB
            rtp::packet pkt;
            pkt.recv(buf, bufSize);

            // transmit!
            CommModule::Instance->send(pkt);
        }
    }
}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2009 Stephen Kelly <steveire@gmail.com>
*/

#include "filterexpression.h"

#include "parser.h"
#include "grantlee.h"
#include "filter.h"
#include "util_p.h"

using namespace Grantlee;

namespace Grantlee
{
class FilterExpressionPrivate
{
  FilterExpressionPrivate(FilterExpression *fe, int error)
    : q_ptr(fe), m_error(error)
  {
  }

  Variable m_variable;
  QList<ArgFilter> m_filters;
  int m_error;

  Q_DECLARE_PUBLIC(FilterExpression)
  FilterExpression *q_ptr;
};

}

static const char * FILTER_SEPARATOR = "|";
static const char * FILTER_ARGUMENT_SEPARATOR = ":";
static const char * VARIABLE_ATTRIBUTE_SEPARATOR = ".";
static const char * ALLOWED_VARIABLE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\\.";

static const char * varChars = "\\w\\." ;
static const char * numChars = "[-+\\.]?\\d[\\d\\.e]*";
static const QString filterSep( QRegExp::escape( FILTER_SEPARATOR ) );
static const QString argSep( QRegExp::escape( FILTER_ARGUMENT_SEPARATOR ) );
static const QString i18nOpen( QRegExp::escape( "_(" ) );
static const QString i18nClose( QRegExp::escape( ")" ) );

static const QString constantString = QString(
    "(?:%3%1%4|"
    "%3%2%4|"
    "%1|"
    "%2)"
    )
    .arg("\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"")
    .arg("\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'")
    .arg(i18nOpen)
    .arg(i18nClose)
    ;

static const QString filterRawString = QString(
          "^%1|"                      /* Match "strings" and 'strings' incl i18n */
          "^[%2]+|"                   /* Match variables */
          "%3|"                       /* Match numbers */
          "%4\\w+|"                   /* Match filters */
          "%5(?:%1|[%2]+|%3|%4\\w+)"  /* Match arguments to filters, which may be strings, */
          )                           /*   variables, numbers or another filter in the chain */
 /* 1 */  .arg(constantString)
 /* 2 */  .arg(varChars)
 /* 3 */  .arg(numChars)
 /* 4 */  .arg(filterSep)
 /* 5 */  .arg(argSep);

static const QRegExp sFilterRe(filterRawString);

FilterExpression::FilterExpression(const QString &varString, Parser *parser)
  : d_ptr(new FilterExpressionPrivate(this, NoError))
{
  Q_D(FilterExpression);

  int pos = 0;
  int lastPos = 0;
  int len;
  QString subString;

  if (varString.contains("\n"))
  {
    // error.
  }

  QString vs = varString.trimmed();

  while ((pos = sFilterRe.indexIn(vs, pos)) != -1) {
    len = sFilterRe.matchedLength();
    subString = vs.mid(pos, len);
    int ssSize = subString.size();
    if (subString.startsWith(FILTER_SEPARATOR))
    {
      subString = subString.right(ssSize - 1);
      Filter *f = parser->getFilter(subString);
      if (f)
        d->m_filters << qMakePair<Filter*, Variable>(f, Variable());
      else
      {
        d->m_error = TagSyntaxError;
        return;
      }
    }
    else if (subString.startsWith(FILTER_ARGUMENT_SEPARATOR))
    {
      subString = subString.right(ssSize - 1);
      int lastFilter = d->m_filters.size();
      d->m_filters[lastFilter -1].second = Variable(subString);
    } else
    {
      // Token is _("translated"), or "constant", or a variable;
      d->m_variable = Variable(subString);
    }

    pos += len;
    lastPos = pos;
  }
  QString remainder = vs.right( vs.size() - lastPos);
  if (remainder.size() > 0)
  {
    d->m_error = TagSyntaxError;
  }
}

int FilterExpression::error() const
{
  Q_D(const FilterExpression);
  return d->m_error;
}

FilterExpression::FilterExpression(const FilterExpression &other)
  : d_ptr(new FilterExpressionPrivate(this, other.d_ptr->m_error))
{
  d_ptr->m_variable = other.d_ptr->m_variable;
  d_ptr->m_filters = other.d_ptr->m_filters;
}

FilterExpression::FilterExpression()
  : d_ptr(new FilterExpressionPrivate(this, NoError))
{
  Q_D(FilterExpression);
}

FilterExpression::~FilterExpression()
{
  delete d_ptr;
}

Variable FilterExpression::variable() const
{
  Q_D(const FilterExpression);
  return d->m_variable;
}

FilterExpression &FilterExpression::operator=(const FilterExpression &other)
{
  d_ptr->m_variable = other.d_ptr->m_variable;
  d_ptr->m_filters = other.d_ptr->m_filters;
  d_ptr->m_error = other.d_ptr->m_error;
  return *this;
}

QVariant FilterExpression::resolve(Context *c) const
{
  Q_D(const FilterExpression);
  QVariant var = d->m_variable.resolve(c);
  foreach(ArgFilter argfilter, d->m_filters)
  {
    var = argfilter.first->doFilter(var, argfilter.second.resolve(c).toString());
  }
  return var;
}

// void FilterExpression::begin(Context *c, int reversed)
// {
//   m_position = 0;
//   QVariant var = resolve(c);
//   if (!var.isValid())
//     return;
//
//   if (var.type() == QVariant::String)
//   {
//
//   } else if (var.userType() > 0)
//   {
//     // A registered user type. Signal error.
// //     void *obj = QMetaType::construct(var.userType(), (void *)var );
//
//     // Instead of all this messing, I can simply require that an object can't be iterated over.
//     // Iterate over a property instead.
//     // Or I can allow iterating over an objects children(), which is a QList<QObject>
//
// //     QMetaType::destroy(var.userType(), obj);
//     //   TODO: see if I can use QMetaType::construct for user defined types.
//   }
//   else
//   {
//     m_variantList.append(var);
//   }
// }

QVariantList FilterExpression::toList(Context *c) const
{
  QVariant var = resolve(c);
  if (!var.isValid())
    return QVariantList();

  if (var.type() == QVariant::List)
  {
    return var.toList();
  }
  if (var.type() == QVariant::String)
  {
    QString s = var.toString();

    QString::iterator i;
    QVariantList list;
    for (i = s.begin(); i != s.end(); ++i)
    {
      list << *i;
    }
    return list;
  } else if (var.userType() == QMetaType::QObjectStar)
  {
    // A registered user type. Signal error.
//     void *obj = QMetaType::construct(var.userType(), (void *)var );

    // Instead of all this messing, I can simply require that an object can't be iterated over.
    // Iterate over a property instead.
    // Or I can allow iterating over an objects children(), which is a QList<QObject *>

//     QMetaType::destroy(var.userType(), obj);
    //   TODO: see if I can use QMetaType::construct for user defined types.
  }
  else
  {
//     QVariantList list;
//     list << var;
//     return list;
    return QVariantList() << var;
//     m_variantList.append(var);
  }

}

bool FilterExpression::isTrue(Context *c) const
{
  return Util::variantIsTrue(resolve(c));
}

// QVariant FilterExpression::next()
// {
//   return m_variantList[m_position++];
//
// //   if (!var.isValid())
// //     return QVariant();
// //
// //   m_iterVariant = var;
// }

<commit_msg>No need to trim this.<commit_after>/*
    Copyright (c) 2009 Stephen Kelly <steveire@gmail.com>
*/

#include "filterexpression.h"

#include "parser.h"
#include "grantlee.h"
#include "filter.h"
#include "util_p.h"

using namespace Grantlee;

namespace Grantlee
{
class FilterExpressionPrivate
{
  FilterExpressionPrivate(FilterExpression *fe, int error)
    : q_ptr(fe), m_error(error)
  {
  }

  Variable m_variable;
  QList<ArgFilter> m_filters;
  int m_error;

  Q_DECLARE_PUBLIC(FilterExpression)
  FilterExpression *q_ptr;
};

}

static const char * FILTER_SEPARATOR = "|";
static const char * FILTER_ARGUMENT_SEPARATOR = ":";
static const char * VARIABLE_ATTRIBUTE_SEPARATOR = ".";
static const char * ALLOWED_VARIABLE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\\.";

static const char * varChars = "\\w\\." ;
static const char * numChars = "[-+\\.]?\\d[\\d\\.e]*";
static const QString filterSep( QRegExp::escape( FILTER_SEPARATOR ) );
static const QString argSep( QRegExp::escape( FILTER_ARGUMENT_SEPARATOR ) );
static const QString i18nOpen( QRegExp::escape( "_(" ) );
static const QString i18nClose( QRegExp::escape( ")" ) );

static const QString constantString = QString(
    "(?:%3%1%4|"
    "%3%2%4|"
    "%1|"
    "%2)"
    )
    .arg("\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"")
    .arg("\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'")
    .arg(i18nOpen)
    .arg(i18nClose)
    ;

static const QString filterRawString = QString(
          "^%1|"                      /* Match "strings" and 'strings' incl i18n */
          "^[%2]+|"                   /* Match variables */
          "%3|"                       /* Match numbers */
          "%4\\w+|"                   /* Match filters */
          "%5(?:%1|[%2]+|%3|%4\\w+)"  /* Match arguments to filters, which may be strings, */
          )                           /*   variables, numbers or another filter in the chain */
 /* 1 */  .arg(constantString)
 /* 2 */  .arg(varChars)
 /* 3 */  .arg(numChars)
 /* 4 */  .arg(filterSep)
 /* 5 */  .arg(argSep);

static const QRegExp sFilterRe(filterRawString);

FilterExpression::FilterExpression(const QString &varString, Parser *parser)
  : d_ptr(new FilterExpressionPrivate(this, NoError))
{
  Q_D(FilterExpression);

  int pos = 0;
  int lastPos = 0;
  int len;
  QString subString;

  if (varString.contains("\n"))
  {
    // error.
  }

  QString vs = varString; //.trimmed();

  while ((pos = sFilterRe.indexIn(vs, pos)) != -1) {
    len = sFilterRe.matchedLength();
    subString = vs.mid(pos, len);
    int ssSize = subString.size();
    if (subString.startsWith(FILTER_SEPARATOR))
    {
      subString = subString.right(ssSize - 1);
      Filter *f = parser->getFilter(subString);
      if (f)
        d->m_filters << qMakePair<Filter*, Variable>(f, Variable());
      else
      {
        d->m_error = TagSyntaxError;
        return;
      }
    }
    else if (subString.startsWith(FILTER_ARGUMENT_SEPARATOR))
    {
      subString = subString.right(ssSize - 1);
      int lastFilter = d->m_filters.size();
      d->m_filters[lastFilter -1].second = Variable(subString);
    } else
    {
      // Token is _("translated"), or "constant", or a variable;
      d->m_variable = Variable(subString);
    }

    pos += len;
    lastPos = pos;
  }
  QString remainder = vs.right( vs.size() - lastPos);
  if (remainder.size() > 0)
  {
    d->m_error = TagSyntaxError;
  }
}

int FilterExpression::error() const
{
  Q_D(const FilterExpression);
  return d->m_error;
}

FilterExpression::FilterExpression(const FilterExpression &other)
  : d_ptr(new FilterExpressionPrivate(this, other.d_ptr->m_error))
{
  d_ptr->m_variable = other.d_ptr->m_variable;
  d_ptr->m_filters = other.d_ptr->m_filters;
}

FilterExpression::FilterExpression()
  : d_ptr(new FilterExpressionPrivate(this, NoError))
{
  Q_D(FilterExpression);
}

FilterExpression::~FilterExpression()
{
  delete d_ptr;
}

Variable FilterExpression::variable() const
{
  Q_D(const FilterExpression);
  return d->m_variable;
}

FilterExpression &FilterExpression::operator=(const FilterExpression &other)
{
  d_ptr->m_variable = other.d_ptr->m_variable;
  d_ptr->m_filters = other.d_ptr->m_filters;
  d_ptr->m_error = other.d_ptr->m_error;
  return *this;
}

QVariant FilterExpression::resolve(Context *c) const
{
  Q_D(const FilterExpression);
  QVariant var = d->m_variable.resolve(c);
  foreach(ArgFilter argfilter, d->m_filters)
  {
    var = argfilter.first->doFilter(var, argfilter.second.resolve(c).toString());
  }
  return var;
}

// void FilterExpression::begin(Context *c, int reversed)
// {
//   m_position = 0;
//   QVariant var = resolve(c);
//   if (!var.isValid())
//     return;
//
//   if (var.type() == QVariant::String)
//   {
//
//   } else if (var.userType() > 0)
//   {
//     // A registered user type. Signal error.
// //     void *obj = QMetaType::construct(var.userType(), (void *)var );
//
//     // Instead of all this messing, I can simply require that an object can't be iterated over.
//     // Iterate over a property instead.
//     // Or I can allow iterating over an objects children(), which is a QList<QObject>
//
// //     QMetaType::destroy(var.userType(), obj);
//     //   TODO: see if I can use QMetaType::construct for user defined types.
//   }
//   else
//   {
//     m_variantList.append(var);
//   }
// }

QVariantList FilterExpression::toList(Context *c) const
{
  QVariant var = resolve(c);
  if (!var.isValid())
    return QVariantList();

  if (var.type() == QVariant::List)
  {
    return var.toList();
  }
  if (var.type() == QVariant::String)
  {
    QString s = var.toString();

    QString::iterator i;
    QVariantList list;
    for (i = s.begin(); i != s.end(); ++i)
    {
      list << *i;
    }
    return list;
  } else if (var.userType() == QMetaType::QObjectStar)
  {
    // A registered user type. Signal error.
//     void *obj = QMetaType::construct(var.userType(), (void *)var );

    // Instead of all this messing, I can simply require that an object can't be iterated over.
    // Iterate over a property instead.
    // Or I can allow iterating over an objects children(), which is a QList<QObject *>

//     QMetaType::destroy(var.userType(), obj);
    //   TODO: see if I can use QMetaType::construct for user defined types.
  }
  else
  {
//     QVariantList list;
//     list << var;
//     return list;
    return QVariantList() << var;
//     m_variantList.append(var);
  }

}

bool FilterExpression::isTrue(Context *c) const
{
  return Util::variantIsTrue(resolve(c));
}

// QVariant FilterExpression::next()
// {
//   return m_variantList[m_position++];
//
// //   if (!var.isValid())
// //     return QVariant();
// //
// //   m_iterVariant = var;
// }

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_startclocks.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_mem_startclocks.C
///
/// @brief Start clocks on MBA/MCAs
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_mem_startclocks.H"
#include "p9_const_common.H"
#include "p9_misc_scom_addresses_fld.H"
#include "p9_perv_scom_addresses.H"
#include "p9_perv_scom_addresses_fld.H"
#include "p9_quad_scom_addresses_fld.H"
#include "p9_sbe_common.H"

enum P9_MEM_STARTCLOCKS_Private_Constants
{
    CLOCK_CMD = 0x1,
    STARTSLAVE = 0x1,
    STARTMASTER = 0x1,
    REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE,
    CLOCK_TYPES = 0x7,
    DONT_STARTMASTER = 0x0,
    DONT_STARTSLAVE = 0x0
};

static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
    const fapi2::buffer<uint64_t> i_pg_vector);

static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);

static fapi2::ReturnCode p9_mem_startclocks_flushmode(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);

static fapi2::ReturnCode p9_mem_startclocks_regions_setup(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
    const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
    fapi2::buffer<uint64_t>& o_regions_enabled_after_pg);

fapi2::ReturnCode p9_mem_startclocks(const
                                     fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
    uint8_t l_sync_mode = 0;
    fapi2::buffer<uint64_t> l_pg_vector;
    fapi2::buffer<uint64_t> l_clock_regions;
    FAPI_DBG("Entering ...");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode),
             "Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");

    FAPI_TRY(p9_sbe_common_get_pg_vector(i_target_chip, l_pg_vector));
    FAPI_DBG("pg targets vector: %#018lX", l_pg_vector);

    if (!l_sync_mode)
    {
        for (auto l_trgt_chplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
             (fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))
        {

            FAPI_INF("Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets");
            FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt));

            FAPI_INF("Call module align chiplets for Mc chiplets");
            FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt));

            FAPI_TRY(p9_mem_startclocks_regions_setup(l_trgt_chplt,
                     REGIONS_ALL_EXCEPT_VITAL_NESTPLL, l_clock_regions));

            FAPI_INF("Call module clock start stop for MC01, MC23.");
            FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD,
                                                    DONT_STARTSLAVE, DONT_STARTMASTER, l_clock_regions,
                                                    CLOCK_TYPES));

            FAPI_INF("Call p9_mem_startclocks_fence_setup_function for Mc chiplets ");
            FAPI_TRY(p9_mem_startclocks_fence_setup_function(l_trgt_chplt, l_pg_vector));

            FAPI_INF("Call p9_mem_startclocks_flushmode for Mc chiplets");
            FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt));

            FAPI_INF("Call p9_sbe_common_configure_chiplet_FIR for MC chiplets");
            FAPI_TRY(p9_sbe_common_configure_chiplet_FIR(l_trgt_chplt));

        }
    }

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief --drop chiplet fence
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
    const fapi2::buffer<uint64_t> i_pg_vector)
{
    uint8_t l_read_attrunitpos = 0;
    fapi2::buffer<uint64_t> l_data64;
    FAPI_DBG("Entering ...");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target_chiplet,
                           l_read_attrunitpos));

    if ( l_read_attrunitpos == 0x07 )
    {
        if ( i_pg_vector.getBit<5>() == 1 )
        {
            FAPI_DBG("Drop chiplet fence");
            //Setting NET_CTRL0 register value
            l_data64.flush<1>();
            l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>();  //NET_CTRL0.FENCE_EN = 0
            FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
        }
    }

    if ( l_read_attrunitpos == 0x08 )
    {
        if ( i_pg_vector.getBit<3>() == 1 )
        {
            FAPI_DBG("Drop chiplet fence");
            //Setting NET_CTRL0 register value
            l_data64.flush<1>();
            l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>();  //NET_CTRL0.FENCE_EN = 0
            FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
        }
    }

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief --drop vital fence
/// --reset abstclk muxsel and syncclk muxsel
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
    fapi2::buffer<uint64_t> l_data64;
    FAPI_DBG("Entering ...");

    // Local variable and constant definition
    fapi2::buffer <uint16_t> l_attr_pg;
    fapi2::buffer <uint16_t> l_cplt_ctrl_init;

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg));

    l_attr_pg.invert();
    l_attr_pg.extractToRight<4, 11>(l_cplt_ctrl_init);

    FAPI_DBG("Drop partial good fences");
    //Setting CPLT_CTRL1 register value
    l_data64.flush<0>();
    l_data64.writeBit<PEC_CPLT_CTRL1_TC_VITL_REGION_FENCE>(l_attr_pg.getBit<3>());
    //CPLT_CTRL1.TC_ALL_REGIONS_FENCE = l_cplt_ctrl_init
    l_data64.insertFromRight<4, 11>(l_cplt_ctrl_init);
    FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64));

    FAPI_DBG("reset abistclk_muxsel and syncclk_muxsel");
    //Setting CPLT_CTRL0 register value
    l_data64.flush<0>();
    //CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1
    l_data64.writeBit<PEC_CPLT_CTRL0_CTRL_CC_ABSTCLK_MUXSEL_DC>(1);
    //CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1
    l_data64.writeBit<PEC_CPLT_CTRL0_TC_UNIT_SYNCCLK_MUXSEL_DC>(1);
    FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief will force all chiplets out of flush
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
    fapi2::buffer<uint64_t> l_data64;
    FAPI_DBG("Entering ...");

    FAPI_DBG("Clear flush_inhibit to go in to flush mode");
    //Setting CPLT_CTRL0 register value
    l_data64.flush<0>();
    //CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0
    l_data64.setBit<PEC_CPLT_CTRL0_CTRL_CC_FLUSHMODE_INH_DC>();
    FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief Region value settings : The anding of REGIONS_ALL_EXCEPT_VITAL_NESTPLL, ATTR_PG
//  disables PLL region and retains enabled regions info from chiplet pg attribute.
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @param[in]     i_regions_except_vital_pll   regions except vital and pll
/// @param[out]    o_regions_enabled_after_pg   enabled regions value after anding with ATTR_PG
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_regions_setup(const
        fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
        const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
        fapi2::buffer<uint64_t>& o_regions_enabled_after_pg)
{
    fapi2::buffer<uint16_t> l_read_attr = 0;
    fapi2::buffer<uint16_t> l_read_attr_invert = 0;
    fapi2::buffer<uint16_t> l_read_attr_shift1_right = 0;

    FAPI_DBG("p9_mem_startclocks_regions_setup: Entering ...");

    FAPI_DBG("Reading ATTR_PG");
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_read_attr));

    if ( l_read_attr == 0x0 )
    {
        o_regions_enabled_after_pg = static_cast<uint64_t>(i_regions_except_vital_pll) ;
    }
    else
    {
        l_read_attr_invert = l_read_attr.invert();
        l_read_attr_shift1_right = (l_read_attr_invert >> 1);
        o_regions_enabled_after_pg = (i_regions_except_vital_pll & l_read_attr_shift1_right);
    }

    FAPI_DBG("p9_mem_startclocks_regions_setup : Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<commit_msg>p9_mem_startclocks -- restore fabric group/node ID in async mode<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_startclocks.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_mem_startclocks.C
///
/// @brief Start clocks on MBA/MCAs
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_mem_startclocks.H"
#include "p9_const_common.H"
#include "p9_misc_scom_addresses_fld.H"
#include "p9_perv_scom_addresses.H"
#include "p9_perv_scom_addresses_fld.H"
#include "p9_quad_scom_addresses_fld.H"
#include "p9_sbe_common.H"

enum P9_MEM_STARTCLOCKS_Private_Constants
{
    CLOCK_CMD = 0x1,
    STARTSLAVE = 0x1,
    STARTMASTER = 0x1,
    REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE,
    CLOCK_TYPES = 0x7,
    DONT_STARTMASTER = 0x0,
    DONT_STARTSLAVE = 0x0
};

static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
    const fapi2::buffer<uint64_t> i_pg_vector);

static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);

static fapi2::ReturnCode p9_mem_startclocks_flushmode(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);

static fapi2::ReturnCode p9_mem_startclocks_regions_setup(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
    const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
    fapi2::buffer<uint64_t>& o_regions_enabled_after_pg);

fapi2::ReturnCode p9_mem_startclocks(const
                                     fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
    uint8_t l_sync_mode = 0;
    fapi2::buffer<uint64_t> l_pg_vector;
    fapi2::buffer<uint64_t> l_clock_regions;
    FAPI_DBG("Entering ...");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode),
             "Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");

    FAPI_TRY(p9_sbe_common_get_pg_vector(i_target_chip, l_pg_vector));
    FAPI_DBG("pg targets vector: %#018lX", l_pg_vector);

    if (!l_sync_mode)
    {
        uint32_t l_fbc_system_id;
        uint8_t l_fbc_group_id;
        uint8_t l_fbc_chip_id;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_SYSTEM_ID, i_target_chip, l_fbc_system_id),
                 "Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_SYSTEM_ID)");
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_GROUP_ID, i_target_chip, l_fbc_group_id),
                 "Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_GROUP_ID)");
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_CHIP_ID, i_target_chip, l_fbc_chip_id),
                 "Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_CHIP_ID)");

        for (auto l_trgt_chplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
             (fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))
        {

            FAPI_INF("Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets");
            FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt));

            FAPI_INF("Call module align chiplets for Mc chiplets");
            FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt));

            FAPI_TRY(p9_mem_startclocks_regions_setup(l_trgt_chplt,
                     REGIONS_ALL_EXCEPT_VITAL_NESTPLL, l_clock_regions));

            FAPI_INF("Call module clock start stop for MC01, MC23.");
            FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD,
                                                    DONT_STARTSLAVE, DONT_STARTMASTER, l_clock_regions,
                                                    CLOCK_TYPES));

            FAPI_INF("Call p9_mem_startclocks_fence_setup_function for Mc chiplets ");
            FAPI_TRY(p9_mem_startclocks_fence_setup_function(l_trgt_chplt, l_pg_vector));

            FAPI_INF("Call p9_mem_startclocks_flushmode for Mc chiplets");
            FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt));

            FAPI_INF("Call p9_sbe_common_configure_chiplet_FIR for MC chiplets");
            FAPI_TRY(p9_sbe_common_configure_chiplet_FIR(l_trgt_chplt));

            FAPI_INF("Reset FBC chiplet configuration");
            fapi2::buffer<uint64_t> l_cplt_conf0;
            FAPI_TRY(fapi2::getScom(l_trgt_chplt, PERV_CPLT_CONF0, l_cplt_conf0),
                     "Error from getScom (PERV_CPLT_CONF0)");
            l_cplt_conf0.insertFromRight<PERV_1_CPLT_CONF0_TC_UNIT_SYS_ID_DC, PERV_1_CPLT_CONF0_TC_UNIT_SYS_ID_DC_LEN>
            (l_fbc_system_id)
            .insertFromRight<PERV_1_CPLT_CONF0_TC_UNIT_GROUP_ID_DC, PERV_1_CPLT_CONF0_TC_UNIT_GROUP_ID_DC_LEN>(l_fbc_group_id)
            .insertFromRight<PERV_1_CPLT_CONF0_TC_UNIT_CHIP_ID_DC, PERV_1_CPLT_CONF0_TC_UNIT_CHIP_ID_DC_LEN>(l_fbc_chip_id);
            FAPI_TRY(fapi2::putScom(l_trgt_chplt, PERV_CPLT_CONF0, l_cplt_conf0),
                     "Error from putScom (PERV_CPLT_CONF0)");
        }
    }

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief --drop chiplet fence
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
    const fapi2::buffer<uint64_t> i_pg_vector)
{
    uint8_t l_read_attrunitpos = 0;
    fapi2::buffer<uint64_t> l_data64;
    FAPI_DBG("Entering ...");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target_chiplet,
                           l_read_attrunitpos));

    if ( l_read_attrunitpos == 0x07 )
    {
        if ( i_pg_vector.getBit<5>() == 1 )
        {
            FAPI_DBG("Drop chiplet fence");
            //Setting NET_CTRL0 register value
            l_data64.flush<1>();
            l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>();  //NET_CTRL0.FENCE_EN = 0
            FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
        }
    }

    if ( l_read_attrunitpos == 0x08 )
    {
        if ( i_pg_vector.getBit<3>() == 1 )
        {
            FAPI_DBG("Drop chiplet fence");
            //Setting NET_CTRL0 register value
            l_data64.flush<1>();
            l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>();  //NET_CTRL0.FENCE_EN = 0
            FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
        }
    }

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief --drop vital fence
/// --reset abstclk muxsel and syncclk muxsel
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
    fapi2::buffer<uint64_t> l_data64;
    FAPI_DBG("Entering ...");

    // Local variable and constant definition
    fapi2::buffer <uint16_t> l_attr_pg;
    fapi2::buffer <uint16_t> l_cplt_ctrl_init;

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg));

    l_attr_pg.invert();
    l_attr_pg.extractToRight<4, 11>(l_cplt_ctrl_init);

    FAPI_DBG("Drop partial good fences");
    //Setting CPLT_CTRL1 register value
    l_data64.flush<0>();
    l_data64.writeBit<PEC_CPLT_CTRL1_TC_VITL_REGION_FENCE>(l_attr_pg.getBit<3>());
    //CPLT_CTRL1.TC_ALL_REGIONS_FENCE = l_cplt_ctrl_init
    l_data64.insertFromRight<4, 11>(l_cplt_ctrl_init);
    FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64));

    FAPI_DBG("reset abistclk_muxsel and syncclk_muxsel");
    //Setting CPLT_CTRL0 register value
    l_data64.flush<0>();
    //CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1
    l_data64.writeBit<PEC_CPLT_CTRL0_CTRL_CC_ABSTCLK_MUXSEL_DC>(1);
    //CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1
    l_data64.writeBit<PEC_CPLT_CTRL0_TC_UNIT_SYNCCLK_MUXSEL_DC>(1);
    FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief will force all chiplets out of flush
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
    fapi2::buffer<uint64_t> l_data64;
    FAPI_DBG("Entering ...");

    FAPI_DBG("Clear flush_inhibit to go in to flush mode");
    //Setting CPLT_CTRL0 register value
    l_data64.flush<0>();
    //CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0
    l_data64.setBit<PEC_CPLT_CTRL0_CTRL_CC_FLUSHMODE_INH_DC>();
    FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief Region value settings : The anding of REGIONS_ALL_EXCEPT_VITAL_NESTPLL, ATTR_PG
//  disables PLL region and retains enabled regions info from chiplet pg attribute.
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @param[in]     i_regions_except_vital_pll   regions except vital and pll
/// @param[out]    o_regions_enabled_after_pg   enabled regions value after anding with ATTR_PG
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_regions_setup(const
        fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
        const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
        fapi2::buffer<uint64_t>& o_regions_enabled_after_pg)
{
    fapi2::buffer<uint16_t> l_read_attr = 0;
    fapi2::buffer<uint16_t> l_read_attr_invert = 0;
    fapi2::buffer<uint16_t> l_read_attr_shift1_right = 0;

    FAPI_DBG("p9_mem_startclocks_regions_setup: Entering ...");

    FAPI_DBG("Reading ATTR_PG");
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_read_attr));

    if ( l_read_attr == 0x0 )
    {
        o_regions_enabled_after_pg = static_cast<uint64_t>(i_regions_except_vital_pll) ;
    }
    else
    {
        l_read_attr_invert = l_read_attr.invert();
        l_read_attr_shift1_right = (l_read_attr_invert >> 1);
        o_regions_enabled_after_pg = (i_regions_except_vital_pll & l_read_attr_shift1_right);
    }

    FAPI_DBG("p9_mem_startclocks_regions_setup : Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<|endoftext|>