<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_scominit.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_io_xbus_scominit.C
/// @brief Invoke XBUS initfile
///
//----------------------------------------------------------------------------
// *HWP HWP Owner       : Chris Steffen <cwsteffen@us.ibm.com>
// *HWP HWP Backup Owner: Gary Peterson <garyp@us.ibm.com>
// *HWP FW Owner        : Sumit Kumar <sumit_kumar@in.ibm.com>
// *HWP Team            : IO
// *HWP Level           : 2
// *HWP Consumed by     : FSP:HB
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
//
//   Invoke XBUS scominit file.
//
// Procedure Prereq:
//   - System clocks are running.
// @endverbatim
//----------------------------------------------------------------------------

//------------------------------------------------------------------------------
//  Includes
//------------------------------------------------------------------------------
#include <p9_io_regs.H>
#include <p9_io_scom.H>
#include <p9_io_xbus_scominit.H>
#include <p9_xbus_g0_scom.H>
#include <p9_xbus_g1_scom.H>

enum
{
    ENUM_ATTR_XBUS_GROUP_0,
    ENUM_ATTR_XBUS_GROUP_1
};

//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

/**
 * @brief Sets ATTR_IO_XBUS_MASTER_MODE based on fabric chip id and fabric group id
 * @param[in] i_target    Fapi2 Target
 * @param[in] i_ctarget   Fapi2 Connected Target
 * @retval    ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode set_rx_master_mode(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget );

/**
 * @brief Gets the value of the ATTR_PROC_FABRIC_GROUP_ID and passes back by reference
 * @param[in] i_target    Fapi2 Target
 * @param[in] o_group_id  Group ID
 * @retval    ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode p9_get_proc_fabric_group_id(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    uint8_t&                                        o_group_id );

/**
 * @brief Gets the value of the ATTR_PROC_FABRIC_CHIP_ID and passes back by refernce
 * @param[in] i_target    Fapi2 Target
 * @param[in] o_chip_id   Chip ID
 * @retval    ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode p9_get_proc_fabric_chip_id(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    uint8_t&                                        o_chip_id );

/**
 * @brief HWP that calls the XBUS SCOM initfiles
 * Should be called for all valid/connected XBUS endpoints
 * @param[in] i_target           Reference to XBUS chiplet target
 * @param[in] i_connected_target Reference to connected XBUS chiplet target
 * @param[in] i_group            Reference to XBUS group-0/1
 * @return FAPI2_RC_SUCCESS on success, error otherwise
 */
fapi2::ReturnCode p9_io_xbus_scominit(
    const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_target,
    const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_connected_target,
    const uint8_t i_group)
{
    // mark HWP entry
    FAPI_INF("p9_io_xbus_scominit: Entering ...");
    const uint8_t     LANE_00  = 0;
    fapi2::ReturnCode rc       = fapi2::FAPI2_RC_SUCCESS;

    // get system target
    const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_system_target;

    // assert IO reset to power-up bus endpoint logic
    // read-modify-write, set single reset bit (HW auto-clears)
    // on writeback
    FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_target, i_group, LANE_00, 1 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_target, i_group, LANE_00, 1 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_connected_target, i_group, LANE_00, 1 ),
              "I/O Xbus Scominit: Connected Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_connected_target, i_group, LANE_00, 1 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );

    // Delay 1ns, 1 Million cycles -- Needed in sim, may not be needed in hw.
    FAPI_TRY( fapi2::delay( 1, 1000000 ) );

    FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_target, i_group, LANE_00, 0 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_target, i_group, LANE_00, 0 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_connected_target, i_group, LANE_00, 0 ),
              "I/O Xbus Scominit: Connected Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_connected_target, i_group, LANE_00, 0 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );

    // Set rx master/slave attribute prior to calling the scominit procedures.
    // The scominit procedure will reference the attribute to set the register field.
    FAPI_TRY( set_rx_master_mode( i_target, i_connected_target ),
              "Setting Rx Master Mode Attribute Failed." );

    switch(i_group)
    {
        case ENUM_ATTR_XBUS_GROUP_0:
            FAPI_INF("Group 0:Invoke FAPI procedure core: input_target");
            FAPI_EXEC_HWP(rc, p9_xbus_g0_scom, i_target, l_system_target);

            FAPI_INF("Group 0:Invoke FAPI procedure core: connected_target");
            FAPI_EXEC_HWP(rc, p9_xbus_g0_scom, i_connected_target, l_system_target);
            break;

        case ENUM_ATTR_XBUS_GROUP_1:
            FAPI_INF("Group 1:Invoke FAPI procedure core: input_target");
            FAPI_EXEC_HWP(rc, p9_xbus_g1_scom, i_target, l_system_target);

            FAPI_INF("Group 1:Invoke FAPI procedure core: connected_target");
            FAPI_EXEC_HWP(rc, p9_xbus_g1_scom, i_connected_target, l_system_target);
            break;
    }

    // mark HWP exit
    FAPI_INF("p9_io_xbus_scominit: ...Exiting");

fapi_try_exit:
    return fapi2::current_err;
}

/**
 * @brief Sets ATTR_IO_XBUS_MASTER_MODE based on fabric chip id and fabric group id
 * @param[in] i_target    Fapi2 Target
 * @param[in] i_ctarget   Fapi2 Connected Target
 * @retval    ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode set_rx_master_mode(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget )
{
    FAPI_IMP( "I/O Xbus Scominit: Set Master Mode Enter." );
    uint8_t  l_primary_group_id   = 0;
    uint8_t  l_primary_chip_id    = 0;
    uint32_t l_primary_id         = 0;
    uint8_t  l_primary_attr       = 0;
    uint8_t  l_connected_group_id = 0;
    uint8_t  l_connected_chip_id  = 0;
    uint32_t l_connected_id       = 0;
    uint8_t  l_connected_attr     = 0;

    FAPI_TRY( p9_get_proc_fabric_group_id( i_target,  l_primary_group_id   ) );
    FAPI_TRY( p9_get_proc_fabric_group_id( i_ctarget, l_connected_group_id ) );

    FAPI_TRY( p9_get_proc_fabric_chip_id( i_target,  l_primary_chip_id   ) );
    FAPI_TRY( p9_get_proc_fabric_chip_id( i_ctarget, l_connected_chip_id ) );

    l_primary_id   = ( (uint32_t)l_primary_group_id   << 8 ) + (uint32_t)l_primary_chip_id;
    l_connected_id = ( (uint32_t)l_connected_group_id << 8 ) + (uint32_t)l_connected_chip_id;

    FAPI_DBG( "I/O Xbus Scominit: Target ID(%d) Connected ID(%d)", l_primary_id, l_connected_id );

    if( l_primary_id < l_connected_id )
    {
        l_primary_attr   = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_TRUE;
        l_connected_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_FALSE;
    }
    else
    {
        l_primary_attr   = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_FALSE;
        l_connected_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_TRUE;
    }

    FAPI_TRY( FAPI_ATTR_SET( fapi2::ATTR_IO_XBUS_MASTER_MODE, i_target, l_primary_attr ),
              "I/O Xbus Scominit: Set Primary Master Mode Attribute Failed." );
    FAPI_TRY( FAPI_ATTR_SET( fapi2::ATTR_IO_XBUS_MASTER_MODE, i_ctarget, l_connected_attr ),
              "I/O Xbus Scominit: Set Connected Master Mode Attribute Failed." );

fapi_try_exit:
    FAPI_IMP( "I/O Xbus Scominit: Set Master Mode Exit." );
    return fapi2::current_err;
}

/**
 * @brief Gets the value of the ATTR_PROC_FABRIC_GROUP_ID and passes back by reference
 * @param[in]  i_target    Fapi2 Target
 * @param[out] o_group_id  Group ID
 * @retval     ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode p9_get_proc_fabric_group_id(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    uint8_t&                                        o_group_id)
{
    FAPI_IMP("I/O Xbus Scominit: Get Proc Group Start.");

    fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc =
        i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();

    // Retrieve node attribute
    FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_PROC_FABRIC_GROUP_ID, l_proc, o_group_id ),
              "(PROC): Error getting ATTR_PROC_FABRIC_GROUP_ID, l_rc 0x%.8X",
              (uint64_t)fapi2::current_err );

fapi_try_exit:
    FAPI_IMP("I/O Xbus Scominit: Get Proc Group Exit.");
    return fapi2::current_err;
}

/**
 * @brief Gets the value of the ATTR_PROC_FABRIC_CHIP_ID and passes back by refernce
 * @param[in]  i_target    Fapi2 Target
 * @param[out] o_chip_id   Chip ID
 * @retval     ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode p9_get_proc_fabric_chip_id(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    uint8_t&                                        o_chip_id)
{
    FAPI_IMP("I/O Xbus Scominit: Get Proc Chip Id Start.");

    fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc =
        i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();

    // Retrieve pos ID attribute
    FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_PROC_FABRIC_CHIP_ID, l_proc, o_chip_id ),
              "(PROC): Error getting ATTR_PROC_FABRIC_CHIP_ID, l_rc 0x%.8X",
              (uint64_t)fapi2::current_err );

fapi_try_exit:
    FAPI_IMP("I/O Xbus Scominit: Get Proc Chip Id Exit.");
    return fapi2::current_err;
}
<commit_msg>Scominit Reset and Delay Update<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_scominit.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_io_xbus_scominit.C
/// @brief Invoke XBUS initfile
///
//----------------------------------------------------------------------------
// *HWP HWP Owner       : Chris Steffen <cwsteffen@us.ibm.com>
// *HWP HWP Backup Owner: Gary Peterson <garyp@us.ibm.com>
// *HWP FW Owner        : Sumit Kumar <sumit_kumar@in.ibm.com>
// *HWP Team            : IO
// *HWP Level           : 2
// *HWP Consumed by     : FSP:HB
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
//
//   Invoke XBUS scominit file.
//
// Procedure Prereq:
//   - System clocks are running.
// @endverbatim
//----------------------------------------------------------------------------

//------------------------------------------------------------------------------
//  Includes
//------------------------------------------------------------------------------
#include <p9_io_regs.H>
#include <p9_io_scom.H>
#include <p9_io_xbus_scominit.H>
#include <p9_xbus_g0_scom.H>
#include <p9_xbus_g1_scom.H>

enum
{
    ENUM_ATTR_XBUS_GROUP_0,
    ENUM_ATTR_XBUS_GROUP_1
};

//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

/**
 * @brief Sets ATTR_IO_XBUS_MASTER_MODE based on fabric chip id and fabric group id
 * @param[in] i_target    Fapi2 Target
 * @param[in] i_ctarget   Fapi2 Connected Target
 * @retval    ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode set_rx_master_mode(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget );

/**
 * @brief Gets the value of the ATTR_PROC_FABRIC_GROUP_ID and passes back by reference
 * @param[in] i_target    Fapi2 Target
 * @param[in] o_group_id  Group ID
 * @retval    ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode p9_get_proc_fabric_group_id(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    uint8_t&                                        o_group_id );

/**
 * @brief Gets the value of the ATTR_PROC_FABRIC_CHIP_ID and passes back by refernce
 * @param[in] i_target    Fapi2 Target
 * @param[in] o_chip_id   Chip ID
 * @retval    ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode p9_get_proc_fabric_chip_id(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    uint8_t&                                        o_chip_id );

/**
 * @brief HWP that calls the XBUS SCOM initfiles
 * Should be called for all valid/connected XBUS endpoints
 * @param[in] i_target           Reference to XBUS chiplet target
 * @param[in] i_connected_target Reference to connected XBUS chiplet target
 * @param[in] i_group            Reference to XBUS group-0/1
 * @return FAPI2_RC_SUCCESS on success, error otherwise
 */
fapi2::ReturnCode p9_io_xbus_scominit(
    const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_target,
    const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_connected_target,
    const uint8_t i_group)
{
    // mark HWP entry
    FAPI_INF("p9_io_xbus_scominit: Entering ...");
    const uint8_t     LANE_00  = 0;
    fapi2::ReturnCode rc       = fapi2::FAPI2_RC_SUCCESS;

    // get system target
    const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_system_target;

    // assert IO reset to power-up bus endpoint logic
    // read-modify-write, set single reset bit (HW auto-clears)
    // on writeback
    FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_target, i_group, LANE_00, 1 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_target, i_group, LANE_00, 1 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_connected_target, i_group, LANE_00, 1 ),
              "I/O Xbus Scominit: Connected Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_connected_target, i_group, LANE_00, 1 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );

    // Calculated HW Delay needed based on counter size and clock speed.
    // 50us -- Based on Counter Size, 40us minimum
    // 1 Million sim cycles -- Based on sim learning
    FAPI_TRY( fapi2::delay( 50000, 1000000 ) );

    FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_target, i_group, LANE_00, 0 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_target, i_group, LANE_00, 0 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_connected_target, i_group, LANE_00, 0 ),
              "I/O Xbus Scominit: Connected Set Reset Hard Failed." );
    FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_connected_target, i_group, LANE_00, 0 ),
              "I/O Xbus Scominit: Primary Set Reset Hard Failed." );

    // Set rx master/slave attribute prior to calling the scominit procedures.
    // The scominit procedure will reference the attribute to set the register field.
    FAPI_TRY( set_rx_master_mode( i_target, i_connected_target ),
              "Setting Rx Master Mode Attribute Failed." );

    switch(i_group)
    {
        case ENUM_ATTR_XBUS_GROUP_0:
            FAPI_INF("Group 0:Invoke FAPI procedure core: input_target");
            FAPI_EXEC_HWP(rc, p9_xbus_g0_scom, i_target, l_system_target);

            FAPI_INF("Group 0:Invoke FAPI procedure core: connected_target");
            FAPI_EXEC_HWP(rc, p9_xbus_g0_scom, i_connected_target, l_system_target);
            break;

        case ENUM_ATTR_XBUS_GROUP_1:
            FAPI_INF("Group 1:Invoke FAPI procedure core: input_target");
            FAPI_EXEC_HWP(rc, p9_xbus_g1_scom, i_target, l_system_target);

            FAPI_INF("Group 1:Invoke FAPI procedure core: connected_target");
            FAPI_EXEC_HWP(rc, p9_xbus_g1_scom, i_connected_target, l_system_target);
            break;
    }

    // mark HWP exit
    FAPI_INF("p9_io_xbus_scominit: ...Exiting");

fapi_try_exit:
    return fapi2::current_err;
}

/**
 * @brief Sets ATTR_IO_XBUS_MASTER_MODE based on fabric chip id and fabric group id
 * @param[in] i_target    Fapi2 Target
 * @param[in] i_ctarget   Fapi2 Connected Target
 * @retval    ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode set_rx_master_mode(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget )
{
    FAPI_IMP( "I/O Xbus Scominit: Set Master Mode Enter." );
    uint8_t  l_primary_group_id   = 0;
    uint8_t  l_primary_chip_id    = 0;
    uint32_t l_primary_id         = 0;
    uint8_t  l_primary_attr       = 0;
    uint8_t  l_connected_group_id = 0;
    uint8_t  l_connected_chip_id  = 0;
    uint32_t l_connected_id       = 0;
    uint8_t  l_connected_attr     = 0;

    FAPI_TRY( p9_get_proc_fabric_group_id( i_target,  l_primary_group_id   ) );
    FAPI_TRY( p9_get_proc_fabric_group_id( i_ctarget, l_connected_group_id ) );

    FAPI_TRY( p9_get_proc_fabric_chip_id( i_target,  l_primary_chip_id   ) );
    FAPI_TRY( p9_get_proc_fabric_chip_id( i_ctarget, l_connected_chip_id ) );

    l_primary_id   = ( (uint32_t)l_primary_group_id   << 8 ) + (uint32_t)l_primary_chip_id;
    l_connected_id = ( (uint32_t)l_connected_group_id << 8 ) + (uint32_t)l_connected_chip_id;

    FAPI_DBG( "I/O Xbus Scominit: Target ID(%d) Connected ID(%d)", l_primary_id, l_connected_id );

    if( l_primary_id < l_connected_id )
    {
        l_primary_attr   = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_TRUE;
        l_connected_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_FALSE;
    }
    else
    {
        l_primary_attr   = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_FALSE;
        l_connected_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_TRUE;
    }

    FAPI_TRY( FAPI_ATTR_SET( fapi2::ATTR_IO_XBUS_MASTER_MODE, i_target, l_primary_attr ),
              "I/O Xbus Scominit: Set Primary Master Mode Attribute Failed." );
    FAPI_TRY( FAPI_ATTR_SET( fapi2::ATTR_IO_XBUS_MASTER_MODE, i_ctarget, l_connected_attr ),
              "I/O Xbus Scominit: Set Connected Master Mode Attribute Failed." );

fapi_try_exit:
    FAPI_IMP( "I/O Xbus Scominit: Set Master Mode Exit." );
    return fapi2::current_err;
}

/**
 * @brief Gets the value of the ATTR_PROC_FABRIC_GROUP_ID and passes back by reference
 * @param[in]  i_target    Fapi2 Target
 * @param[out] o_group_id  Group ID
 * @retval     ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode p9_get_proc_fabric_group_id(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    uint8_t&                                        o_group_id)
{
    FAPI_IMP("I/O Xbus Scominit: Get Proc Group Start.");

    fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc =
        i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();

    // Retrieve node attribute
    FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_PROC_FABRIC_GROUP_ID, l_proc, o_group_id ),
              "(PROC): Error getting ATTR_PROC_FABRIC_GROUP_ID, l_rc 0x%.8X",
              (uint64_t)fapi2::current_err );

fapi_try_exit:
    FAPI_IMP("I/O Xbus Scominit: Get Proc Group Exit.");
    return fapi2::current_err;
}

/**
 * @brief Gets the value of the ATTR_PROC_FABRIC_CHIP_ID and passes back by refernce
 * @param[in]  i_target    Fapi2 Target
 * @param[out] o_chip_id   Chip ID
 * @retval     ReturnCode  Fapi2 ReturnCode
 */
fapi2::ReturnCode p9_get_proc_fabric_chip_id(
    const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
    uint8_t&                                        o_chip_id)
{
    FAPI_IMP("I/O Xbus Scominit: Get Proc Chip Id Start.");

    fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc =
        i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();

    // Retrieve pos ID attribute
    FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_PROC_FABRIC_CHIP_ID, l_proc, o_chip_id ),
              "(PROC): Error getting ATTR_PROC_FABRIC_CHIP_ID, l_rc 0x%.8X",
              (uint64_t)fapi2::current_err );

fapi_try_exit:
    FAPI_IMP("I/O Xbus Scominit: Get Proc Chip Id Exit.");
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (C) 2021 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name PX4 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.
 *
 ****************************************************************************/

/**
 * Test code for the 2nd order Butterworth low-pass filter
 * Run this test only using make tests TESTFILTER=LowPassFilter2pVector3f
 */

#include <gtest/gtest.h>
#include <matrix/matrix/math.hpp>
#include <px4_platform_common/defines.h>

#include "LowPassFilter2pVector3f.hpp"

using matrix::Vector3f;

class LowPassFilter2pVector3fTest : public ::testing::Test
{
public:
	math::LowPassFilter2pVector3f _lpf{800.f, 30.f};
	const float _sample_freq = 1000.f;
	const float _cutoff_freq = 80.f;

	const float _epsilon_near = 10e-3f;
};

TEST_F(LowPassFilter2pVector3fTest, setGet)
{
	_lpf.set_cutoff_frequency(_sample_freq, _cutoff_freq);
	EXPECT_EQ(_lpf.get_sample_freq(), _sample_freq);
	EXPECT_EQ(_lpf.get_cutoff_freq(), _cutoff_freq);
}

TEST_F(LowPassFilter2pVector3fTest, belowCutoff)
{
	_lpf.set_cutoff_frequency(_sample_freq, _cutoff_freq);

	const float signal_freq = 10.f;
	const float omega = 2.f * M_PI_F * signal_freq;
	const float phase_delay = 10.4f * M_PI_F / 180.f; // Given by simulation
	const float dt = 1.f / _sample_freq;

	float t = 0.f;

	for (int i = 0; i < 1000; i++) {
		float input = sinf(omega * t);
		float output_expected = sinf(omega * t - phase_delay);
		Vector3f out = _lpf.apply(Vector3f(0.f, input, -input));
		t = i * dt;

		// Let some time for the filter to settle
		if (i > 30) {
			EXPECT_EQ(out(0), 0.f);
			EXPECT_NEAR(out(1), output_expected, _epsilon_near);
			EXPECT_NEAR(out(2), -output_expected, _epsilon_near);
		}
	}
}

TEST_F(LowPassFilter2pVector3fTest, aboveCutoff)
{
	_lpf.set_cutoff_frequency(_sample_freq, _cutoff_freq);

	const float signal_freq = 100.f;
	const float omega = 2.f * M_PI_F * signal_freq;
	const float phase_delay = 108.5f * M_PI_F / 180.f; // Given by simulation
	const float gain = 0.52f; // = -5.66 dB, given by simulation
	const float dt = 1.f / _sample_freq;

	float t = 0.f;

	for (int i = 0; i < 1000; i++) {
		float input = sinf(omega * t);
		float output_expected = gain * sinf(omega * t - phase_delay);
		Vector3f out = _lpf.apply(Vector3f(0.f, input, -input));
		t = i * dt;

		// Let some time for the filter to settle
		if (i > 30) {
			EXPECT_EQ(out(0), 0.f);
			EXPECT_NEAR(out(1), output_expected, _epsilon_near);
			EXPECT_NEAR(out(2), -output_expected, _epsilon_near);
		}
	}
}
<commit_msg>lpf test: move to common function<commit_after>/****************************************************************************
 *
 *   Copyright (C) 2021 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name PX4 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.
 *
 ****************************************************************************/

/**
 * Test code for the 2nd order Butterworth low-pass filter
 * Run this test only using make tests TESTFILTER=LowPassFilter2pVector3f
 */

#include <gtest/gtest.h>
#include <matrix/matrix/math.hpp>
#include <px4_platform_common/defines.h>

#include "LowPassFilter2pVector3f.hpp"

using matrix::Vector3f;

class LowPassFilter2pVector3fTest : public ::testing::Test
{
public:
	void runSimulatedFilter(const Vector3f &signal_freq_hz, const Vector3f &phase_delay_deg, const Vector3f &gain_db);

	math::LowPassFilter2pVector3f _lpf{800.f, 30.f};

	const float _epsilon_near = 10e-3f;
};

void LowPassFilter2pVector3fTest::runSimulatedFilter(const Vector3f &signal_freq_hz, const Vector3f &phase_delay_deg,
		const Vector3f &gain_db)
{
	const Vector3f phase_delay = phase_delay_deg * M_PI_F / 180.f;
	const Vector3f omega = 2.f * M_PI_F * signal_freq_hz;
	Vector3f gain;

	for (int i = 0; i < 3; i++) {
		gain(i) = powf(10.f, gain_db(i) / 20.f);
	}

	const float dt = 1.f / _lpf.get_sample_freq();

	float t = 0.f;

	for (int i = 0; i < 1000; i++) {
		Vector3f input{0.f, sinf(omega(1) * t), -sinf(omega(2) * t)};
		Vector3f output_expected{0.f,
					 gain(1) *sinf(omega(1) * t - phase_delay(1)),
					 -gain(2) *sinf(omega(2) * t - phase_delay(2))};
		Vector3f out = _lpf.apply(input);
		t = i * dt;

		// Let some time for the filter to settle
		if (i > 30) {
			EXPECT_EQ(out(0), 0.f);
			EXPECT_NEAR(out(1), output_expected(1), _epsilon_near);
			EXPECT_NEAR(out(2), output_expected(2), _epsilon_near);
		}
	}
}

TEST_F(LowPassFilter2pVector3fTest, setGet)
{
	const float sample_freq = 1000.f;
	const float cutoff_freq = 80.f;

	_lpf.set_cutoff_frequency(sample_freq, cutoff_freq);
	EXPECT_EQ(_lpf.get_sample_freq(), sample_freq);
	EXPECT_EQ(_lpf.get_cutoff_freq(), cutoff_freq);
}

TEST_F(LowPassFilter2pVector3fTest, belowAndAboveCutoff)
{
	const float sample_freq = 1000.f;
	const float cutoff_freq = 80.f;
	_lpf.set_cutoff_frequency(sample_freq, cutoff_freq);

	const Vector3f signal_freq_hz{0.f, 10.f, 100.f};
	const Vector3f phase_delay_deg = Vector3f{0.f, 10.4f, 108.5f}; // Given by simulation
	const Vector3f gain_db{0.f, 0.f, -5.66f}; // given by simulation
	runSimulatedFilter(signal_freq_hz, phase_delay_deg, gain_db);
}
<|endoftext|>


<commit_before>/*
 *   Copyright (c) 2006, Mathieu Champlon
 *   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 the
 *     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 THE COPYRIGHT
 *   OWNERS 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.
 */

#ifndef xeumeuleu_translate_hpp
#define xeumeuleu_translate_hpp

#define XEUMEULEU_TRANSCODER_ENCODING "utf-8"
#define XEUMEULEU_TRANSCODER_BUFFER_SIZE 128

#include <xeumeuleu/bridges/xerces/detail/xerces.hpp>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>

namespace xml
{
// =============================================================================
/** @class  translate
    @brief  String translation helpers
*/
// Created: MAT 2006-01-04
// =============================================================================
class translate
{
public:
    //! @name Constructors/Destructor
    //@{
    explicit translate( const std::string& str )
        : transcoder_( create() )
        , s_         ( transcode( str ) )
        , ch_        ( &s_[0] )
    {}
    explicit translate( const XMLCh* const ch )
        : transcoder_( create() )
        , ch_        ( ch )
    {}
    translate( const translate& rhs )
        : transcoder_( create() )
        , s_         ( rhs.s_ )
        , ch_        ( s_.empty() ? rhs.ch_ : &s_[0] )
    {}
    //@}

    //! @name Operators
    //@{
    operator const XMLCh*() const
    {
        return ch_;
    }
    operator std::string() const
    {
        std::string result;
        const XMLSize_t size = XERCES_CPP_NAMESPACE::XMLString::stringLen( ch_ );
        XMLByte s[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ];
        XMLSize_t done = 0;
        while( done < size )
        {
            Count_t read = 0;
            Count_t written = transcoder_->transcodeTo(
                ch_ + done, size - done,
                s, XEUMEULEU_TRANSCODER_BUFFER_SIZE,
                read, XERCES_CPP_NAMESPACE::XMLTranscoder::UnRep_RepChar );
            if( read == 0 )
                throw xml::exception( "failed to transcode string" );
            done += read;
            result.append( reinterpret_cast< const char* >( s ), written );
        }
        return result;
    }

    bool operator==( const XMLCh* const ch ) const
    {
        return XERCES_CPP_NAMESPACE::XMLString::equals( ch, ch_ );
    }
    bool operator==( const std::string& str ) const
    {
        return translate( str ) == ch_;
    }
    bool operator!=( const XMLCh* const ch ) const
    {
        return ! XERCES_CPP_NAMESPACE::XMLString::equals( ch, ch_ );
    }
    bool operator!=( const std::string& str ) const
    {
        return translate( str ) != ch_;
    }
    //@}

private:
    //! @name Helpers
    //@{
    XERCES_CPP_NAMESPACE::XMLTranscoder* create() const
    {
        XERCES_CPP_NAMESPACE::XMLTransService::Codes result;
        XERCES_CPP_NAMESPACE::Janitor< XERCES_CPP_NAMESPACE::XMLTranscoder > transcoder(
            XERCES_CPP_NAMESPACE::XMLPlatformUtils::fgTransService->makeNewTranscoderFor(
                XEUMEULEU_TRANSCODER_ENCODING, result, 16 * 1024 ) );
        if( result != XERCES_CPP_NAMESPACE::XMLTransService::Ok )
            throw xml::exception( std::string( "unable to create transcoder for " ) + XEUMEULEU_TRANSCODER_ENCODING );
        return transcoder.release();
    }
    std::vector< XMLCh > transcode( const std::string& str ) const
    {
        std::vector< XMLCh > result;
        const XMLByte* in = reinterpret_cast< const XMLByte* >( str.c_str() );
        const XMLSize_t length = str.length();
        XMLCh s[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ];
        unsigned char sizes[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ];
        XMLSize_t done = 0;
        while( done < length )
        {
            Count_t read = 0;
            XMLSize_t written = transcoder_->transcodeFrom(
                in + done, length - done,
                s, XEUMEULEU_TRANSCODER_BUFFER_SIZE,
                read, sizes );
            if( read == 0 )
                throw xml::exception( "failed to transcode string" );
            done += read;
            std::copy( s, s + written, std::back_inserter( result ) );
        }
        result.resize( result.size() + 4 );
        return result;
    }
    //@}

private:
    //! @name Copy/Assignment
    //@{
    translate& operator=( const translate& ); //!< Assignment operator
    //@}

private:
    //! @name Member data
    //@{
    XERCES_CPP_NAMESPACE::Janitor< XERCES_CPP_NAMESPACE::XMLTranscoder > transcoder_;
    const std::vector< XMLCh > s_;
    const XMLCh* const ch_;
    //@}
};

inline bool operator==( const XMLCh* const ch, const translate& tr )
{
    return tr == ch;
}
inline bool operator==( const std::string& str, const translate& tr )
{
    return tr == str;
}

inline bool operator!=( const XMLCh* const ch, const translate& tr )
{
    return tr != ch;
}
inline bool operator!=( const std::string& str, const translate& tr )
{
    return tr != str;
}

inline std::string operator+( const translate& tr, const std::string& str )
{
    return std::string( tr ) + str;
}
inline std::string operator+( const std::string& str, const translate& tr )
{
    return str + std::string( tr );
}

}

#endif // xeumeuleu_translate_hpp
<commit_msg>Build translated string more simply and efficiently<commit_after>/*
 *   Copyright (c) 2006, Mathieu Champlon
 *   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 the
 *     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 THE COPYRIGHT
 *   OWNERS 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.
 */

#ifndef xeumeuleu_translate_hpp
#define xeumeuleu_translate_hpp

#define XEUMEULEU_TRANSCODER_ENCODING "utf-8"
#define XEUMEULEU_TRANSCODER_BUFFER_SIZE 128

#include <xeumeuleu/bridges/xerces/detail/xerces.hpp>
#include <vector>
#include <string>

namespace xml
{
// =============================================================================
/** @class  translate
    @brief  String translation helpers
*/
// Created: MAT 2006-01-04
// =============================================================================
class translate
{
public:
    //! @name Constructors/Destructor
    //@{
    explicit translate( const std::string& str )
        : transcoder_( create() )
        , s_         ( transcode( str ) )
        , ch_        ( &s_[0] )
    {}
    explicit translate( const XMLCh* const ch )
        : transcoder_( create() )
        , ch_        ( ch )
    {}
    translate( const translate& rhs )
        : transcoder_( create() )
        , s_         ( rhs.s_ )
        , ch_        ( s_.empty() ? rhs.ch_ : &s_[0] )
    {}
    //@}

    //! @name Operators
    //@{
    operator const XMLCh*() const
    {
        return ch_;
    }
    operator std::string() const
    {
        std::string result;
        const XMLSize_t size = XERCES_CPP_NAMESPACE::XMLString::stringLen( ch_ );
        XMLByte s[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ];
        XMLSize_t done = 0;
        while( done < size )
        {
            Count_t read = 0;
            Count_t written = transcoder_->transcodeTo(
                ch_ + done, size - done,
                s, XEUMEULEU_TRANSCODER_BUFFER_SIZE,
                read, XERCES_CPP_NAMESPACE::XMLTranscoder::UnRep_RepChar );
            if( read == 0 )
                throw xml::exception( "failed to transcode string" );
            done += read;
            result.append( reinterpret_cast< const char* >( s ), written );
        }
        return result;
    }

    bool operator==( const XMLCh* const ch ) const
    {
        return XERCES_CPP_NAMESPACE::XMLString::equals( ch, ch_ );
    }
    bool operator==( const std::string& str ) const
    {
        return translate( str ) == ch_;
    }
    bool operator!=( const XMLCh* const ch ) const
    {
        return ! XERCES_CPP_NAMESPACE::XMLString::equals( ch, ch_ );
    }
    bool operator!=( const std::string& str ) const
    {
        return translate( str ) != ch_;
    }
    //@}

private:
    //! @name Helpers
    //@{
    XERCES_CPP_NAMESPACE::XMLTranscoder* create() const
    {
        XERCES_CPP_NAMESPACE::XMLTransService::Codes result;
        XERCES_CPP_NAMESPACE::Janitor< XERCES_CPP_NAMESPACE::XMLTranscoder > transcoder(
            XERCES_CPP_NAMESPACE::XMLPlatformUtils::fgTransService->makeNewTranscoderFor(
                XEUMEULEU_TRANSCODER_ENCODING, result, 16 * 1024 ) );
        if( result != XERCES_CPP_NAMESPACE::XMLTransService::Ok )
            throw xml::exception( std::string( "unable to create transcoder for " ) + XEUMEULEU_TRANSCODER_ENCODING );
        return transcoder.release();
    }
    std::vector< XMLCh > transcode( const std::string& str ) const
    {
        std::vector< XMLCh > result;
        const XMLByte* in = reinterpret_cast< const XMLByte* >( str.c_str() );
        const XMLSize_t length = str.length();
        XMLCh s[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ];
        unsigned char sizes[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ];
        XMLSize_t done = 0;
        while( done < length )
        {
            Count_t read = 0;
            XMLSize_t written = transcoder_->transcodeFrom(
                in + done, length - done,
                s, XEUMEULEU_TRANSCODER_BUFFER_SIZE,
                read, sizes );
            if( read == 0 )
                throw xml::exception( "failed to transcode string" );
            done += read;
            result.insert( result.end(), s, s + written );
        }
        result.resize( result.size() + 4 );
        return result;
    }
    //@}

private:
    //! @name Copy/Assignment
    //@{
    translate& operator=( const translate& ); //!< Assignment operator
    //@}

private:
    //! @name Member data
    //@{
    XERCES_CPP_NAMESPACE::Janitor< XERCES_CPP_NAMESPACE::XMLTranscoder > transcoder_;
    const std::vector< XMLCh > s_;
    const XMLCh* const ch_;
    //@}
};

inline bool operator==( const XMLCh* const ch, const translate& tr )
{
    return tr == ch;
}
inline bool operator==( const std::string& str, const translate& tr )
{
    return tr == str;
}

inline bool operator!=( const XMLCh* const ch, const translate& tr )
{
    return tr != ch;
}
inline bool operator!=( const std::string& str, const translate& tr )
{
    return tr != str;
}

inline std::string operator+( const translate& tr, const std::string& str )
{
    return std::string( tr ) + str;
}
inline std::string operator+( const std::string& str, const translate& tr )
{
    return str + std::string( tr );
}

}

#endif // xeumeuleu_translate_hpp
<|endoftext|>


<commit_before>/*
 *   Copyright (c) 2009, Mathieu Champlon
 *   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 the
 *     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 THE COPYRIGHT
 *   OWNERS 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.
 */

#ifndef xeumeuleu_attribute_output_hpp
#define xeumeuleu_attribute_output_hpp

#include <xeumeuleu/streams/exception.hpp>
#include <xeumeuleu/streams/detail/output_base.hpp>
#include <string>

namespace xml
{
// =============================================================================
/** @class  output_base
    @brief  Attribute output implementation
*/
// Created: MAT 2009-11-27
// =============================================================================
class attribute_output : public output_base
{
public:
    //! @name Constructors/Destructor
    //@{
    attribute_output( output_base& output, const std::string& attribute )
        : output_   ( output )
        , attribute_( attribute )
    {}
    virtual ~attribute_output()
    {}
    //@}

    //! @name Operations
    //@{
    virtual void start( const std::string& /*tag*/ )
    {
        throw xml::exception( "Invalid 'start' while writing attribute" );
    }
    virtual void end()
    {
        throw xml::exception( "Invalid 'end' while writing attribute" );
    }

    virtual void write( const std::string& value ) { output_.attribute( attribute_, value ); }
    virtual void write( bool value ) { output_.attribute( attribute_, value ); }
    virtual void write( int value ) { output_.attribute( attribute_, value ); }
    virtual void write( long value ) { output_.attribute( attribute_, value ); }
    virtual void write( long long value ) { output_.attribute( attribute_, value ); }
    virtual void write( float value ) { output_.attribute( attribute_, value ); }
    virtual void write( double value ) { output_.attribute( attribute_, value ); }
    virtual void write( long double value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned int value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned long value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned long long value ) { output_.attribute( attribute_, value ); }

    virtual void cdata( const std::string& /*value*/ )
    {
        throw xml::exception( "Invalid 'cdata' while writing attribute" );
    }
    virtual void instruction( const std::string& /*target*/, const std::string& /*data*/ )
    {
        throw xml::exception( "Invalid 'instruction' while writing attribute" );
    }

    virtual void attribute( const std::string& /*name*/, const std::string& /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, bool /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, int /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, float /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, double /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long double /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned int /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned long long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }

    virtual void copy( const input_base& /*input*/ )
    {
        throw xml::exception( "Invalid 'copy' while writing attribute" );
    }

    virtual std::auto_ptr< output_base > branch() const
    {
        throw xml::exception( "Invalid 'branch' while writing attribute" );
    }
    //@}

private:
    //! @name Copy/Assignment
    //@{
    attribute_output( const attribute_output& );            //!< Copy constructor
    attribute_output& operator=( const attribute_output& ); //!< Assignment operator
    //@}

private:
    //! @name Member data
    //@{
    output_base& output_;
    const std::string& attribute_;
    //@}
};

}

#endif // xeumeuleu_attribute_output_hpp
/*
 *   Copyright (c) 2009, Mathieu Champlon
 *   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 the
 *     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 THE COPYRIGHT
 *   OWNERS 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.
 */

#ifndef xeumeuleu_attribute_output_hpp
#define xeumeuleu_attribute_output_hpp

#include <xeumeuleu/streams/exception.hpp>
#include <xeumeuleu/streams/detail/output_base.hpp>
#include <string>

namespace xml
{
// =============================================================================
/** @class  output_base
    @brief  Attribute output implementation
*/
// Created: MAT 2009-11-27
// =============================================================================
class attribute_output : public output_base
{
public:
    //! @name Constructors/Destructor
    //@{
    attribute_output( output_base& output, const std::string& attribute )
        : output_   ( output )
        , attribute_( attribute )
    {}
    virtual ~attribute_output()
    {}
    //@}

    //! @name Operations
    //@{
    virtual void start( const std::string& /*tag*/ )
    {
        throw xml::exception( "Invalid 'start' while writing attribute" );
    }
    virtual void end()
    {
        throw xml::exception( "Invalid 'end' while writing attribute" );
    }

    virtual void write( const std::string& value ) { output_.attribute( attribute_, value ); }
    virtual void write( bool value ) { output_.attribute( attribute_, value ); }
    virtual void write( int value ) { output_.attribute( attribute_, value ); }
    virtual void write( long value ) { output_.attribute( attribute_, value ); }
    virtual void write( long long value ) { output_.attribute( attribute_, value ); }
    virtual void write( float value ) { output_.attribute( attribute_, value ); }
    virtual void write( double value ) { output_.attribute( attribute_, value ); }
    virtual void write( long double value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned int value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned long value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned long long value ) { output_.attribute( attribute_, value ); }

    virtual void cdata( const std::string& /*value*/ )
    {
        throw xml::exception( "Invalid 'cdata' while writing attribute" );
    }
    virtual void instruction( const std::string& /*target*/, const std::string& /*data*/ )
    {
        throw xml::exception( "Invalid 'instruction' while writing attribute" );
    }

    virtual void attribute( const std::string& /*name*/, const std::string& /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, bool /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, int /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, float /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, double /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long double /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned int /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned long long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }

    virtual void copy( const input_base& /*input*/ )
    {
        throw xml::exception( "Invalid 'copy' while writing attribute" );
    }

    virtual std::auto_ptr< output_base > branch() const
    {
        throw xml::exception( "Invalid 'branch' while writing attribute" );
    }
    //@}

private:
    //! @name Copy/Assignment
    //@{
    attribute_output( const attribute_output& );            //!< Copy constructor
    attribute_output& operator=( const attribute_output& ); //!< Assignment operator
    //@}

private:
    //! @name Member data
    //@{
    output_base& output_;
    const std::string& attribute_;
    //@}
};

}

#endif // xeumeuleu_attribute_output_hpp
<commit_msg>Clean-up<commit_after>/*
 *   Copyright (c) 2009, Mathieu Champlon
 *   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 the
 *     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 THE COPYRIGHT
 *   OWNERS 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.
 */

#ifndef xeumeuleu_attribute_output_hpp
#define xeumeuleu_attribute_output_hpp

#include <xeumeuleu/streams/exception.hpp>
#include <xeumeuleu/streams/detail/output_base.hpp>
#include <string>

namespace xml
{
// =============================================================================
/** @class  output_base
    @brief  Attribute output implementation
*/
// Created: MAT 2009-11-27
// =============================================================================
class attribute_output : public output_base
{
public:
    //! @name Constructors/Destructor
    //@{
    attribute_output( output_base& output, const std::string& attribute )
        : output_   ( output )
        , attribute_( attribute )
    {}
    virtual ~attribute_output()
    {}
    //@}

    //! @name Operations
    //@{
    virtual void start( const std::string& /*tag*/ )
    {
        throw xml::exception( "Invalid 'start' while writing attribute" );
    }
    virtual void end()
    {
        throw xml::exception( "Invalid 'end' while writing attribute" );
    }

    virtual void write( const std::string& value ) { output_.attribute( attribute_, value ); }
    virtual void write( bool value ) { output_.attribute( attribute_, value ); }
    virtual void write( int value ) { output_.attribute( attribute_, value ); }
    virtual void write( long value ) { output_.attribute( attribute_, value ); }
    virtual void write( long long value ) { output_.attribute( attribute_, value ); }
    virtual void write( float value ) { output_.attribute( attribute_, value ); }
    virtual void write( double value ) { output_.attribute( attribute_, value ); }
    virtual void write( long double value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned int value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned long value ) { output_.attribute( attribute_, value ); }
    virtual void write( unsigned long long value ) { output_.attribute( attribute_, value ); }

    virtual void cdata( const std::string& /*value*/ )
    {
        throw xml::exception( "Invalid 'cdata' while writing attribute" );
    }
    virtual void instruction( const std::string& /*target*/, const std::string& /*data*/ )
    {
        throw xml::exception( "Invalid 'instruction' while writing attribute" );
    }

    virtual void attribute( const std::string& /*name*/, const std::string& /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, bool /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, int /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, float /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, double /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, long double /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned int /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }
    virtual void attribute( const std::string& /*name*/, unsigned long long /*value*/ )
    {
        throw xml::exception( "Invalid 'attribute' while writing attribute" );
    }

    virtual void copy( const input_base& /*input*/ )
    {
        throw xml::exception( "Invalid 'copy' while writing attribute" );
    }

    virtual std::auto_ptr< output_base > branch() const
    {
        throw xml::exception( "Invalid 'branch' while writing attribute" );
    }
    //@}

private:
    //! @name Copy/Assignment
    //@{
    attribute_output( const attribute_output& );            //!< Copy constructor
    attribute_output& operator=( const attribute_output& ); //!< Assignment operator
    //@}

private:
    //! @name Member data
    //@{
    output_base& output_;
    const std::string& attribute_;
    //@}
};

}

#endif // xeumeuleu_attribute_output_hpp
<|endoftext|>


<commit_before>#ifndef QCAN_NETWORK_HPP_
#define QCAN_NETWORK_HPP_

#include <QTcpServer>
#include <QTcpSocket>
#include <QMutex>
#include <QPointer>
#include <QTimer>

#include "qcan_frame.hpp"
#include "qcan_frame_api.hpp"
#include "qcan_frame_error.hpp"

class QCanInterface;

//-----------------------------------------------------------------------------
/*!
** \class QCanNetwork
** \brief CAN network representation
**
** This class represents a CAN network with a unique bitrate.
** It supports one physical CAN interface, which can be assigned
** during run-time to the CAN network and a limited number of
** virtual CAN interfaces (sockets).
**
*/

class QCanNetwork : public QObject
{
   Q_OBJECT
public:

   /*!
   ** Create new CAN network with unique channel number.
   */
   QCanNetwork(QObject * pclParentV = Q_NULLPTR,
               uint16_t  uwPortV = QCAN_TCP_DEFAULT_PORT);

	~QCanNetwork();

	/*!
	** \param   pclCanIfV - Pointer to physical CAN interface
	** \see     removeInterface()
	**
	** Add a physical CAN interface to the CAN network.
	** Each CAN network supports only one physical CAN interface.
	** The CAN interface is removed from the network by calling
	** the removeInterface() method.
	*/
	bool addInterface(QCanInterface * pclCanIfV);

	int32_t  bitrate(void)           {return (slBitrateP);      };

	uint32_t dispatcherTime(void)    {return (ulDispatchTimeP); };

   bool hasErrorFramesSupport(void);

   bool hasFastDataSupport(void);

   bool hasListenOnlySupport(void);

   bool isErrorFramesEnabled(void)  {return (btErrorFramesEnabledP); };

   bool isFastDataEnabled(void)     {return (btFastDataEnabledP);    };

   bool isListenOnlyEnabled(void)   {return (btListenOnlyEnabledP);  };

   bool isNetworkEnabled(void)      {return (btNetworkEnabledP);     };

	/*!
	** Show actual network load in percent.
	**
	*/
	uint8_t  load();

	QString  name()   { return(clNetNameP); };

   /*!
   ** \see     addInterface()
   **
   ** Remove a physical CAN interface from the CAN network.
   */
	void removeInterface(void);

	void setBitrate(int32_t slBitrateV, int32_t slBrsClockV);

	void setDispatcherTime(uint32_t ulTimeV);

   void setErrorFramesEnabled(bool btEnableV = true);

   void setFastDataEnabled(bool btEnableV = true);

   void setListenOnlyEnabled(bool btEnableV = true);

   void setNetworkEnabled(bool btEnableV = true);

public slots:

   void onSocketConnect(void);

   void onSocketDisconnect(void);
   void onTimerEvent(void);

signals:
   void  showApiFrames(uint32_t ulFrameTotalV);
   void  showCanFrames(uint32_t ulFrameTotalV);
   void  showErrFrames(uint32_t ulFrameTotalV);
   void  showLoad(uint8_t ubLoadV, uint32_t ulMsgPerSecV);

protected:

private:

   bool  handleApiFrame(int32_t & slSockSrcR, QCanFrameApi & clApiFrameR);
   bool  handleCanFrame(int32_t & slSockSrcR, QByteArray & clSockDataR);
   bool  handleErrFrame(int32_t & slSockSrcR, QCanFrameError & clErrorFrameR);

   QPointer<QCanInterface> pclInterfaceP;
   QPointer<QTcpServer>    pclTcpSrvP;
   QVector<QTcpSocket *> * pclTcpSockListP;
   QHostAddress            clTcpHostAddrP;
   uint16_t                uwTcpPortP;
   static uint8_t          ubNetIdP;
   QString                 clNetNameP;
   QMutex                  clTcpSockMutexP;
   QTimer                  clDispatchTmrP;
   uint32_t                ulDispatchTimeP;
   int32_t                 slBitrateP;
   int32_t                 slBrsClockP;

   uint32_t                ulCntFrameApiP;
   uint32_t                ulCntFrameCanP;
   uint32_t                ulCntFrameErrP;

   bool                    btErrorFramesEnabledP;
   bool                    btFastDataEnabledP;
   bool                    btListenOnlyEnabledP;
   bool                    btNetworkEnabledP;
};

#endif   // QCAN_NETWORK_HPP_
<commit_msg>Add documentation<commit_after>//============================================================================//
// File:          qcan_network.hpp                                            //
// Description:   QCAN classes - CAN network                                  //
//                                                                            //
// Copyright (C) MicroControl GmbH & Co. KG                                   //
// 53844 Troisdorf - Germany                                                  //
// www.microcontrol.net                                                       //
//                                                                            //
//----------------------------------------------------------------------------//
// Redistribution and use in source and binary forms, with or without         //
// modification, are permitted provided that the following conditions         //
// are met:                                                                   //
// 1. Redistributions of source code must retain the above copyright          //
//    notice, this list of conditions, the following disclaimer and           //
//    the referenced file 'LICENSE'.                                          //
// 2. 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.    //
// 3. Neither the name of MicroControl nor the names of its contributors      //
//    may be used to endorse or promote products derived from this software   //
//    without specific prior written permission.                              //
//                                                                            //
// Provided that this notice is retained in full, this software may be        //
// distributed under the terms of the GNU Lesser General Public License       //
// ("LGPL") version 3 as distributed in the 'LICENSE' file.                   //
//                                                                            //
//============================================================================//

#ifndef QCAN_NETWORK_HPP_
#define QCAN_NETWORK_HPP_

/*----------------------------------------------------------------------------*\
** Include files                                                              **
**                                                                            **
\*----------------------------------------------------------------------------*/
#include <QTcpServer>
#include <QTcpSocket>
#include <QMutex>
#include <QPointer>
#include <QTimer>

#include "qcan_frame.hpp"
#include "qcan_frame_api.hpp"
#include "qcan_frame_error.hpp"

/*----------------------------------------------------------------------------*\
** Referenced classes                                                         **
**                                                                            **
\*----------------------------------------------------------------------------*/
class QCanInterface;

//-----------------------------------------------------------------------------
/*!
** \file    qcan_network.hpp
** \brief   CAN network
**
** This file ...
**
*/

//-----------------------------------------------------------------------------
/*!
** \class QCanNetwork
** \brief CAN network representation
**
** This class represents a CAN network with a unique bitrate.
** It supports one physical CAN interface, which can be assigned
** during run-time to the CAN network and a limited number of
** virtual CAN interfaces (sockets). Clients can connect to a QCanNetwork
** via the QCanSocket class.
**
*/
class QCanNetwork : public QObject
{
   Q_OBJECT
public:

   /*!
   ** Create new CAN network with unique channel number.
   */
   QCanNetwork(QObject * pclParentV = Q_NULLPTR,
               uint16_t  uwPortV = QCAN_TCP_DEFAULT_PORT);

	~QCanNetwork();

	/*!
	** \see     removeInterface()
	**
	** The function adds a physical CAN interface to the CAN network.
	** Each CAN network supports only one physical CAN interface.
	** The CAN interface is removed from the network by calling
	** the removeInterface() method. The parameter \c pclCanIfV is a pointer
	** to an instance of a QCanInterface class.
	**

	** The function returns \c true if the CAN interface is added, otherwise
	** it will return \c false.
	*/
	bool addInterface(QCanInterface * pclCanIfV);

   /*!
   ** \see     setBitrate()
   **
   ** This function returns the current bit-rate of the CAN network.
   ** For classic CAN, the return value defines the bit-rate for the
   ** complete frame.
   ** For CAN FD the return value defines the bit-rate for
   ** the arbitration phase.
   **

   ** If no bit-rate is configured, the function will return
   ** QCan::eCAN_BITRATE_NONE.
   */
	int32_t  bitrate(void)           {return (slBitrateP);      };

   /*!
   ** \see     setDispatcherTime()
   **
   ** This function returns the current dispatcher time for the
   ** internal CAN frame handler in milli-seconds.
   */
	uint32_t dispatcherTime(void)    {return (ulDispatchTimeP); };

   bool hasErrorFramesSupport(void);

   bool hasFastDataSupport(void);

   bool hasListenOnlySupport(void);

   bool isErrorFramesEnabled(void)  {return (btErrorFramesEnabledP); };

   bool isFastDataEnabled(void)     {return (btFastDataEnabledP);    };

   bool isListenOnlyEnabled(void)   {return (btListenOnlyEnabledP);  };

   /*!
   ** \see     setNetworkEnabled()
   **
   ** This function returns \c true if the network is enabled,
   ** otherwise it returns \c false.
   */
   bool isNetworkEnabled(void)      {return (btNetworkEnabledP);     };

	QString  name()   { return(clNetNameP); };

	void reset(void);

   /*!
   ** \see     addInterface()
   **
   ** Remove a physical CAN interface from the CAN network.
   */
	void removeInterface(void);

   /*!
   ** \see     bitrate()
   **
   ** This function sets the bit-rate for the CAN network. For classic CAN,
   ** the parameter \c slBitrateV defines the bit-rate for the complete frame,
   ** the parameter \c slBrsClockV is not evaluated in that case.
   ** For CAN FD the parameter \c slBitrateV defines the bit-rate for
   ** the arbitration phase, the parameter \c slBrsClockV defines the
   ** bit-rate for the data phase.
   **

   ** For selection of pre-defined bit-rates the value can be taken from
   ** the enumeration QCan::CAN_Bitrate_e.
   */
	void setBitrate(int32_t slBitrateV,
	                int32_t slBrsClockV = QCan::eCAN_BITRATE_NONE);

   /*!
   ** \see     dispatcherTime()
   **
   ** This function sets the dispatcher time for the internal CAN frame
   ** handler in milli-seconds.
   */
	void setDispatcherTime(uint32_t ulTimeV);

   void setErrorFramesEnabled(bool btEnableV = true);

   void setFastDataEnabled(bool btEnableV = true);

   void setListenOnlyEnabled(bool btEnableV = true);

   /*!
   ** \see     isNetworkEnabled()
   **
   ** This function enables the dispatching of CAN frames if \c btEnable is
   ** \c true. It is disabled for <c>btEnable = false</c>.
   */
   void setNetworkEnabled(bool btEnableV = true);

public slots:
   /*!
   ** This function is called upon socket connection.
   */
   void onSocketConnect(void);

   /*!
   ** This function is called upon socket disconnection.
   */
   void onSocketDisconnect(void);

   void onTimerEvent(void);

signals:
   /*!
   ** This signal is emitted ..
   */
   void  showApiFrames(uint32_t ulFrameTotalV);
   void  showCanFrames(uint32_t ulFrameTotalV);
   void  showErrFrames(uint32_t ulFrameTotalV);
   void  showLoad(uint8_t ubLoadV, uint32_t ulMsgPerSecV);

protected:

private:

   bool  handleApiFrame(int32_t & slSockSrcR, QCanFrameApi & clApiFrameR);
   bool  handleCanFrame(int32_t & slSockSrcR, QByteArray & clSockDataR);
   bool  handleErrFrame(int32_t & slSockSrcR, QCanFrameError & clErrorFrameR);

   QPointer<QCanInterface> pclInterfaceP;
   QPointer<QTcpServer>    pclTcpSrvP;
   QVector<QTcpSocket *> * pclTcpSockListP;
   QHostAddress            clTcpHostAddrP;
   uint16_t                uwTcpPortP;
   static uint8_t          ubNetIdP;
   QString                 clNetNameP;
   QMutex                  clTcpSockMutexP;
   QTimer                  clDispatchTmrP;
   uint32_t                ulDispatchTimeP;
   int32_t                 slBitrateP;
   int32_t                 slBrsClockP;

   uint32_t                ulCntFrameApiP;
   uint32_t                ulCntFrameCanP;
   uint32_t                ulCntFrameErrP;

   bool                    btErrorFramesEnabledP;
   bool                    btFastDataEnabledP;
   bool                    btListenOnlyEnabledP;
   bool                    btNetworkEnabledP;
};

#endif   // QCAN_NETWORK_HPP_
<|endoftext|>


<commit_before>/* Lantern - A path tracer
*
* Lantern is the legal property of Adrian Astley
* Copyright Adrian Astley 2015 - 2016
*/

#include "renderer/renderer.h"

#include "common/global_args.h"

#include "scene/mesh_elements.h"

#include "graphics/atomic_frame_buffer.h"

namespace Lantern {

Renderer::Renderer(GlobalArgs *globalArgs)
	: m_globalArgs(globalArgs),
	  m_device(rtcNewDevice(nullptr)),
	  m_scene(nullptr) {
}

Renderer::~Renderer() {
	if (!m_scene) {
		rtcDeleteScene(m_scene);
	}
	rtcDeleteDevice(m_device);
}

void Renderer::SetScene() {
	m_scene = rtcDeviceNewScene(m_device, RTC_SCENE_STATIC, RTC_INTERSECT1);

	// Create a cube
	uint id = rtcNewTriangleMesh(m_scene, RTC_GEOMETRY_STATIC, 12, 8);

	Vertex *vertices = (Vertex *)rtcMapBuffer(m_scene, id, RTC_VERTEX_BUFFER);
	vertices[0].X = -1; vertices[0].Y = -1; vertices[0].Z = -1;
	vertices[1].X = -1; vertices[1].Y = -1; vertices[1].Z = +1;
	vertices[2].X = -1; vertices[2].Y = +1; vertices[2].Z = -1;
	vertices[3].X = -1; vertices[3].Y = +1; vertices[3].Z = +1;
	vertices[4].X = +1; vertices[4].Y = -1; vertices[4].Z = -1;
	vertices[5].X = +1; vertices[5].Y = -1; vertices[5].Z = +1;
	vertices[6].X = +1; vertices[6].Y = +1; vertices[6].Z = -1;
	vertices[7].X = +1; vertices[7].Y = +1; vertices[7].Z = +1;
	rtcUnmapBuffer(m_scene, id, RTC_VERTEX_BUFFER);

	Triangle* triangles = (Triangle*)rtcMapBuffer(m_scene, id, RTC_INDEX_BUFFER);

	// left side
	triangles[0].V0 = 0; triangles[0].V1 = 2; triangles[0].V2 = 1;
	triangles[1].V0 = 1; triangles[1].V1 = 2; triangles[1].V2 = 3;

	// right side
	triangles[2].V0 = 4; triangles[2].V1 = 5; triangles[2].V2 = 6;
	triangles[3].V0 = 5; triangles[3].V1 = 7; triangles[3].V2 = 6;

	// bottom side
	triangles[4].V0 = 0; triangles[4].V1 = 1; triangles[4].V2 = 4;
	triangles[5].V0 = 1; triangles[5].V1 = 5; triangles[5].V2 = 4;

	// top side
	triangles[6].V0 = 2; triangles[6].V1 = 6; triangles[6].V2 = 3;
	triangles[7].V0 = 3; triangles[7].V1 = 6; triangles[7].V2 = 7;

	// front side
	triangles[8].V0 = 0; triangles[8].V1 = 4; triangles[8].V2 = 2;
	triangles[9].V0 = 2; triangles[9].V1 = 4; triangles[9].V2 = 6;

	// back side
	triangles[10].V0 = 1; triangles[10].V1 = 3; triangles[10].V2 = 5;
	triangles[11].V0 = 3; triangles[11].V1 = 7; triangles[11].V2 = 5;

	rtcUnmapBuffer(m_scene, id, RTC_INDEX_BUFFER);

	rtcCommit(m_scene);
}

void Renderer::Start() {
	uint width = m_globalArgs->FrameBuffer->Width();
	uint height = m_globalArgs->FrameBuffer->Height();

	for (uint y = 0; y < height; ++y) {
		for (uint x = 0; x < width; ++x) {
			float3 color = float3(1.0f, 0.0f, 0.0f);
			m_globalArgs->FrameBuffer->SplatPixel(x, y, color);
		}
	}

	m_globalArgs->RenderChanged.store(true);
}

} // End of namespace Lantern
<commit_msg>Add something more exciting to look at<commit_after>/* Lantern - A path tracer
*
* Lantern is the legal property of Adrian Astley
* Copyright Adrian Astley 2015 - 2016
*/

#include "renderer/renderer.h"

#include "common/global_args.h"

#include "scene/mesh_elements.h"

#include "graphics/atomic_frame_buffer.h"

namespace Lantern {

Renderer::Renderer(GlobalArgs *globalArgs)
	: m_globalArgs(globalArgs),
	  m_device(rtcNewDevice(nullptr)),
	  m_scene(nullptr) {
}

Renderer::~Renderer() {
	if (!m_scene) {
		rtcDeleteScene(m_scene);
	}
	rtcDeleteDevice(m_device);
}

void Renderer::SetScene() {
	m_scene = rtcDeviceNewScene(m_device, RTC_SCENE_STATIC, RTC_INTERSECT1);

	// Create a cube
	uint id = rtcNewTriangleMesh(m_scene, RTC_GEOMETRY_STATIC, 12, 8);

	Vertex *vertices = (Vertex *)rtcMapBuffer(m_scene, id, RTC_VERTEX_BUFFER);
	vertices[0].X = -1; vertices[0].Y = -1; vertices[0].Z = -1;
	vertices[1].X = -1; vertices[1].Y = -1; vertices[1].Z = +1;
	vertices[2].X = -1; vertices[2].Y = +1; vertices[2].Z = -1;
	vertices[3].X = -1; vertices[3].Y = +1; vertices[3].Z = +1;
	vertices[4].X = +1; vertices[4].Y = -1; vertices[4].Z = -1;
	vertices[5].X = +1; vertices[5].Y = -1; vertices[5].Z = +1;
	vertices[6].X = +1; vertices[6].Y = +1; vertices[6].Z = -1;
	vertices[7].X = +1; vertices[7].Y = +1; vertices[7].Z = +1;
	rtcUnmapBuffer(m_scene, id, RTC_VERTEX_BUFFER);

	Triangle* triangles = (Triangle*)rtcMapBuffer(m_scene, id, RTC_INDEX_BUFFER);

	// left side
	triangles[0].V0 = 0; triangles[0].V1 = 2; triangles[0].V2 = 1;
	triangles[1].V0 = 1; triangles[1].V1 = 2; triangles[1].V2 = 3;

	// right side
	triangles[2].V0 = 4; triangles[2].V1 = 5; triangles[2].V2 = 6;
	triangles[3].V0 = 5; triangles[3].V1 = 7; triangles[3].V2 = 6;

	// bottom side
	triangles[4].V0 = 0; triangles[4].V1 = 1; triangles[4].V2 = 4;
	triangles[5].V0 = 1; triangles[5].V1 = 5; triangles[5].V2 = 4;

	// top side
	triangles[6].V0 = 2; triangles[6].V1 = 6; triangles[6].V2 = 3;
	triangles[7].V0 = 3; triangles[7].V1 = 6; triangles[7].V2 = 7;

	// front side
	triangles[8].V0 = 0; triangles[8].V1 = 4; triangles[8].V2 = 2;
	triangles[9].V0 = 2; triangles[9].V1 = 4; triangles[9].V2 = 6;

	// back side
	triangles[10].V0 = 1; triangles[10].V1 = 3; triangles[10].V2 = 5;
	triangles[11].V0 = 3; triangles[11].V1 = 7; triangles[11].V2 = 5;

	rtcUnmapBuffer(m_scene, id, RTC_INDEX_BUFFER);

	rtcCommit(m_scene);
}

void Renderer::Start() {
	uint width = m_globalArgs->FrameBuffer->Width();
	uint height = m_globalArgs->FrameBuffer->Height();

	for (uint y = 0; y < height; ++y) {
		for (uint x = 0; x < width; ++x) {
			float3 color;
			if (y >= 0 && y < 100) {
				color = float3(1.0f, 0.0f, 0.0f);
			} else if (y >= 100 && y < 200) {
				color = float3(1.0f, 1.0f, 0.0f);
			} else if (y >= 200 && y < 300) {
				color = float3(0.0f, 1.0f, 0.0f);
			} else if (y >= 300 && y < 400) {
				color = float3(1.0f, 1.0f, 1.0f);
			} else if (y >= 400 && y < 500) {
				color = float3(1.0f, 0.0f, 1.0f);
			} else if (y >= 500 && y < 600) {
				color = float3(0.0f, 0.0f, 0.0f);
			} else if (y >= 600 && y < 700) {
				color = float3(0.0f, 0.0f, 1.0f);
			} else {
				color = float3(0.5f, 1.0f, 0.5f);
			}

			m_globalArgs->FrameBuffer->SplatPixel(x, y, color);
		}
	}

	m_globalArgs->RenderChanged.store(true);
}

} // End of namespace Lantern
<|endoftext|>