<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/dimm/kind.H $             */
/*                                                                        */
/* 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 kind.H
/// @brief Encapsulation for dimms of all types
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#ifndef _GEN_MSS_KIND_H_
#define _GEN_MSS_KIND_H_

#include <fapi2.H>

#include <generic/memory/lib/mss_generic_attribute_getters.H>
#include <generic/memory/lib/utils/c_str.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>

namespace mss
{

namespace dimm
{

///
/// @class mss::dimm::kind
/// @tparam MC the MC type
/// @brief A class containing information about a dimm like ranks, density, configuration - what kind of dimm is it?
///
template<mss::mc_type MC = DEFAULT_MC_TYPE>
class kind
{
    public:

        ///
        /// @brief Generate a vector of DIMM kind from a vector of DIMM
        /// @param[in] i_dimm a vector of DIMM
        /// @return std::vector of dimm::kind relating to the DIMM passed in
        ///
        static std::vector<kind> vector(const std::vector<fapi2::Target<fapi2::TARGET_TYPE_DIMM>>& i_dimm)
        {
            std::vector<kind> l_kinds;

            for (const auto& d : i_dimm)
            {
                l_kinds.push_back( kind(d) );
            }

            return l_kinds;
        }

        ///
        /// @brief operator=() - assign kinds (needed to sort vectors of kinds)
        /// @param[in] i_rhs the right hand side of the assignment statement
        /// @return reference to this
        ///
        inline kind& operator=(const kind& i_rhs)
        {
            iv_target = i_rhs.iv_target;
            iv_master_ranks = i_rhs.iv_master_ranks;
            iv_total_ranks = i_rhs.iv_total_ranks;
            iv_dram_density = i_rhs.iv_dram_density;
            iv_dram_width = i_rhs.iv_dram_width;
            iv_dram_generation = i_rhs.iv_dram_generation;
            iv_dimm_type = i_rhs.iv_dimm_type;
            iv_rows = i_rhs.iv_rows;
            iv_size = i_rhs.iv_size;
            iv_mfgid = i_rhs.iv_mfgid;
            iv_stack_type = i_rhs.iv_stack_type;
            iv_hybrid = i_rhs.iv_hybrid;
            iv_hybrid_memory_type = i_rhs.iv_hybrid_memory_type;
            iv_rcd_mfgid = i_rhs.iv_rcd_mfgid;
            iv_module_height = i_rhs.iv_module_height;
            return *this;
        }

        ///
        /// @brief operator==() - are two kinds the same?
        /// @param[in] i_rhs the right hand side of the comparison statement
        /// @return bool true iff the two kind are of the same kind
        /// @warning this does not compare the targets (iv_target,) just the values
        /// Also does not compare the mfgid as that's not really part of the DIMM kind but is additional information
        ///
        inline bool operator==(const kind& i_rhs) const
        {
            return ((iv_master_ranks == i_rhs.iv_master_ranks) &&
                    (iv_total_ranks == i_rhs.iv_total_ranks) &&
                    (iv_dram_density == i_rhs.iv_dram_density) &&
                    (iv_dram_width == i_rhs.iv_dram_width) &&
                    (iv_dram_generation == i_rhs.iv_dram_generation) &&
                    (iv_dimm_type == i_rhs.iv_dimm_type) &&
                    (iv_rows == i_rhs.iv_rows) &&
                    (iv_size == i_rhs.iv_size) &&
                    (iv_stack_type == i_rhs.iv_stack_type) &&
                    (iv_hybrid == i_rhs.iv_hybrid) &&
                    (iv_hybrid_memory_type == i_rhs.iv_hybrid_memory_type) &&
                    (iv_rcd_mfgid == i_rhs.iv_rcd_mfgid) &&
                    (iv_module_height == i_rhs.iv_module_height));
        }

        ///
        /// @brief operator!=() - are two kinds different?
        /// @param[in] i_rhs the right hand side of the comparison statement
        /// @return bool true iff the two kind are of different
        /// @warning this does not compare the targets (iv_target,) just the values
        ///
        inline bool operator!=(const kind& i_rhs) const
        {
            return !(this->operator==(i_rhs));
        }

        ///
        /// @brief Construct a dimm::kind data structure - information about the kind of DIMM this is
        /// @param[in] i_target a DIMM target
        ///
        kind(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target):
            iv_target(i_target)
        {
            FAPI_TRY( mss::attr::get_dram_gen(i_target, iv_dram_generation) );
            FAPI_TRY( mss::attr::get_dimm_type(i_target, iv_dimm_type) );
            FAPI_TRY( mss::attr::get_dram_density(i_target, iv_dram_density) );
            FAPI_TRY( mss::attr::get_dram_width(i_target, iv_dram_width) );
            FAPI_TRY( mss::attr::get_num_master_ranks_per_dimm(i_target, iv_master_ranks) );
            FAPI_TRY( mss::attr::get_logical_ranks_per_dimm(i_target, iv_total_ranks) );
            FAPI_TRY( mss::attr::get_dram_row_bits(i_target, iv_rows) );
            FAPI_TRY( mss::attr::get_dimm_size(i_target, iv_size) );
            FAPI_TRY( mss::attr::get_dram_mfg_id(i_target, iv_mfgid) );
            FAPI_TRY( mss::attr::get_prim_stack_type( i_target, iv_stack_type) );
            FAPI_TRY( mss::attr::get_hybrid( i_target, iv_hybrid ));
            FAPI_TRY( mss::attr::get_hybrid_memory_type( i_target, iv_hybrid_memory_type ));
            FAPI_TRY( mss::attr::get_rcd_mfg_id(i_target, iv_rcd_mfgid) );
            FAPI_TRY( mss::attr::get_dram_module_height(i_target, iv_module_height) );
            return;

        fapi_try_exit:
            // Not 100% sure what to do here ...
            FAPI_ERR("error initializing DIMM structure: %s 0x%016lx", mss::c_str(i_target), uint64_t(fapi2::current_err));
            fapi2::Assert(false);
        }

        ///
        /// @brief Construct a DIMM kind used to identify this DIMM for tables.
        /// @param[in] i_master_ranks number of master ranks on the DIMM
        /// @param[in] i_total_ranks total number of ranks on the DIMM
        /// @param[in] i_dram_density density of the DRAM
        /// @param[in] i_dram_width width of the DRAM
        /// @param[in] i_dram_generation DRAM generation
        /// @param[in] i_dimm_type DIMM type (e.g. RDIMM)
        /// @param[in] i_rows number of rows in the DRAM
        /// @param[in] i_size the overal size of the DIMM in GB
        /// @param[in] i_mfgid the dram manufacturer id of the dimm, defaulted to 0
        /// @param[in] i_stack_type dram die type, single die package or 3DS
        /// @param[in] i_hybrid, default not hybrid
        /// @param[in] i_hybrid_memory_type, defult none
        /// @param[in] i_rcd_mfgid dimm register and data buffer manufacturer id, default 0
        /// @note can't be constexpr as fapi2::Target doesn't have a constexpr ctor.
        ///
        kind( const uint8_t i_master_ranks,
              const uint8_t i_total_ranks,
              const uint8_t i_dram_density,
              const uint8_t i_dram_width,
              const uint8_t i_dram_generation,
              const uint8_t i_dimm_type,
              const uint8_t i_rows,
              const uint32_t i_size,
              const uint16_t i_mfgid = 0,
              const uint8_t i_stack_type = fapi2::ENUM_ATTR_EFF_PRIM_STACK_TYPE_SDP,
              const uint8_t i_hybrid = fapi2::ENUM_ATTR_EFF_HYBRID_NOT_HYBRID,
              const uint8_t i_hybrid_memory_type = fapi2::ENUM_ATTR_EFF_HYBRID_MEMORY_TYPE_NONE,
              const uint16_t i_rcd_mfgid = 0,
              const uint8_t i_module_height = 0
            ):
            iv_target(0),
            iv_master_ranks(i_master_ranks),
            iv_total_ranks(i_total_ranks),
            iv_dram_density(i_dram_density),
            iv_dram_width(i_dram_width),
            iv_dram_generation(i_dram_generation),
            iv_dimm_type(i_dimm_type),
            iv_rows(i_rows),
            // TK consider calculating size rather than requiring it be set.
            iv_size(i_size),
            iv_mfgid(i_mfgid),
            iv_stack_type(i_stack_type),
            iv_hybrid(i_hybrid),
            iv_hybrid_memory_type(i_hybrid_memory_type),
            iv_rcd_mfgid(i_rcd_mfgid),
            iv_module_height(i_module_height)
        {
            // Bit of an idiot-check to be sure a hand-crafted dimm::kind make sense wrt slaves, masters, packages, etc.
            // Both of these are checked in eff_config. If they are messed up, they should be caught there
            if (iv_master_ranks > iv_total_ranks)
            {
                FAPI_ERR("Not enough total ranks? master: %d total: %d",
                         iv_master_ranks,
                         iv_total_ranks);
                fapi2::Assert(false);
            }

            if ((iv_total_ranks % iv_master_ranks) != 0)
            {
                FAPI_ERR("total or master ranks seems incorrect. master: %d total: %d",
                         iv_master_ranks,
                         iv_total_ranks);
                fapi2::Assert(false);
            }
        }

        fapi2::Target<fapi2::TARGET_TYPE_DIMM> iv_target;
        uint8_t iv_master_ranks;
        uint8_t iv_total_ranks;
        uint8_t iv_dram_density;
        uint8_t iv_dram_width;
        uint8_t iv_dram_generation;
        uint8_t iv_dimm_type;
        uint8_t iv_rows;
        uint32_t iv_size;
        uint16_t iv_mfgid;
        uint8_t iv_stack_type;
        uint8_t iv_hybrid;
        uint8_t iv_hybrid_memory_type;
        uint16_t iv_rcd_mfgid;
        uint8_t iv_module_height;

        ///
        /// @brief equal_config
        /// @param[in] i_input_compare the i_kind to compare against
        /// @return bool true iff the two kind are of the same kind for xlate purposes
        /// @warning this does not compare the targets (iv_target,), mfgid, prim_stack_type nor hybrid type
        ///
        inline bool equal_config(const kind& i_input_compare) const
        {
            return ((iv_master_ranks == i_input_compare.iv_master_ranks) &&
                    (iv_total_ranks == i_input_compare.iv_total_ranks) &&
                    (iv_dram_density == i_input_compare.iv_dram_density) &&
                    (iv_dram_width == i_input_compare.iv_dram_width) &&
                    (iv_dram_generation == i_input_compare.iv_dram_generation) &&
                    (iv_dimm_type == i_input_compare.iv_dimm_type) &&
                    (iv_rows == i_input_compare.iv_rows) &&
                    (iv_size == i_input_compare.iv_size));
        }
};

}

}
#endif
<commit_msg>Add snapshot of ocmb/explorer for master-p10 branch<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/dimm/kind.H $             */
/*                                                                        */
/* 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 kind.H
/// @brief Encapsulation for dimms of all types
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#ifndef _GEN_MSS_KIND_H_
#define _GEN_MSS_KIND_H_

#include <fapi2.H>

#include <generic/memory/lib/mss_generic_attribute_getters.H>
#include <generic/memory/lib/utils/c_str.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>

namespace mss
{

namespace dimm
{

///
/// @class mss::dimm::kind
/// @tparam MC the MC type
/// @brief A class containing information about a dimm like ranks, density, configuration - what kind of dimm is it?
///
template<mss::mc_type MC = DEFAULT_MC_TYPE>
class kind
{
    public:

        ///
        /// @brief Generate a vector of DIMM kind from a vector of DIMM
        /// @param[in] i_dimm a vector of DIMM
        /// @return std::vector of dimm::kind relating to the DIMM passed in
        ///
        static std::vector<kind> vector(const std::vector<fapi2::Target<fapi2::TARGET_TYPE_DIMM>>& i_dimm)
        {
            std::vector<kind> l_kinds;

            for (const auto& d : i_dimm)
            {
                l_kinds.push_back( kind(d) );
            }

            return l_kinds;
        }

        ///
        /// @brief operator=() - assign kinds (needed to sort vectors of kinds)
        /// @param[in] i_rhs the right hand side of the assignment statement
        /// @return reference to this
        ///
        inline kind& operator=(const kind& i_rhs)
        {
            iv_target = i_rhs.iv_target;
            iv_master_ranks = i_rhs.iv_master_ranks;
            iv_total_ranks = i_rhs.iv_total_ranks;
            iv_dram_density = i_rhs.iv_dram_density;
            iv_dram_width = i_rhs.iv_dram_width;
            iv_dram_generation = i_rhs.iv_dram_generation;
            iv_dimm_type = i_rhs.iv_dimm_type;
            iv_rows = i_rhs.iv_rows;
            iv_size = i_rhs.iv_size;
            iv_mfgid = i_rhs.iv_mfgid;
            iv_stack_type = i_rhs.iv_stack_type;
            iv_hybrid = i_rhs.iv_hybrid;
            iv_hybrid_memory_type = i_rhs.iv_hybrid_memory_type;
            iv_rcd_mfgid = i_rhs.iv_rcd_mfgid;
            iv_module_height = i_rhs.iv_module_height;
            return *this;
        }

        ///
        /// @brief operator==() - are two kinds the same?
        /// @param[in] i_rhs the right hand side of the comparison statement
        /// @return bool true iff the two kind are of the same kind
        /// @warning this does not compare the targets (iv_target,) just the values
        /// Also does not compare the mfgid as that's not really part of the DIMM kind but is additional information
        ///
        inline bool operator==(const kind& i_rhs) const
        {
            return ((iv_master_ranks == i_rhs.iv_master_ranks) &&
                    (iv_total_ranks == i_rhs.iv_total_ranks) &&
                    (iv_dram_density == i_rhs.iv_dram_density) &&
                    (iv_dram_width == i_rhs.iv_dram_width) &&
                    (iv_dram_generation == i_rhs.iv_dram_generation) &&
                    (iv_dimm_type == i_rhs.iv_dimm_type) &&
                    (iv_rows == i_rhs.iv_rows) &&
                    (iv_size == i_rhs.iv_size) &&
                    (iv_stack_type == i_rhs.iv_stack_type) &&
                    (iv_hybrid == i_rhs.iv_hybrid) &&
                    (iv_hybrid_memory_type == i_rhs.iv_hybrid_memory_type) &&
                    (iv_rcd_mfgid == i_rhs.iv_rcd_mfgid) &&
                    (iv_module_height == i_rhs.iv_module_height));
        }

        ///
        /// @brief operator!=() - are two kinds different?
        /// @param[in] i_rhs the right hand side of the comparison statement
        /// @return bool true iff the two kind are of different
        /// @warning this does not compare the targets (iv_target,) just the values
        ///
        inline bool operator!=(const kind& i_rhs) const
        {
            return !(this->operator==(i_rhs));
        }

        ///
        /// @brief Construct a dimm::kind data structure - information about the kind of DIMM this is
        /// @param[in] i_target a DIMM target
        ///
        kind(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target):
            iv_target(i_target)
        {
            FAPI_TRY( mss::attr::get_dram_gen(i_target, iv_dram_generation) );
            FAPI_TRY( mss::attr::get_dimm_type(i_target, iv_dimm_type) );
            FAPI_TRY( mss::attr::get_dram_density(i_target, iv_dram_density) );
            FAPI_TRY( mss::attr::get_dram_width(i_target, iv_dram_width) );
            FAPI_TRY( mss::attr::get_num_master_ranks_per_dimm(i_target, iv_master_ranks) );
            FAPI_TRY( mss::attr::get_logical_ranks_per_dimm(i_target, iv_total_ranks) );
            FAPI_TRY( mss::attr::get_dram_row_bits(i_target, iv_rows) );
            FAPI_TRY( mss::attr::get_dimm_size(i_target, iv_size) );
            FAPI_TRY( mss::attr::get_dram_mfg_id(i_target, iv_mfgid) );
            FAPI_TRY( mss::attr::get_prim_stack_type( i_target, iv_stack_type) );
            FAPI_TRY( mss::attr::get_hybrid( i_target, iv_hybrid ));
            FAPI_TRY( mss::attr::get_hybrid_memory_type( i_target, iv_hybrid_memory_type ));
            FAPI_TRY( mss::attr::get_rcd_mfg_id(i_target, iv_rcd_mfgid) );
            FAPI_TRY( mss::attr::get_dram_module_height(i_target, iv_module_height) );
            return;

        fapi_try_exit:
            // Not 100% sure what to do here ...
            FAPI_ERR("error initializing DIMM structure: %s 0x%016lx", mss::c_str(i_target), uint64_t(fapi2::current_err));
            fapi2::Assert(false);
        }

        ///
        /// @brief Construct a DIMM kind used to identify this DIMM for tables.
        /// @param[in] i_master_ranks number of master ranks on the DIMM
        /// @param[in] i_total_ranks total number of ranks on the DIMM
        /// @param[in] i_dram_density density of the DRAM
        /// @param[in] i_dram_width width of the DRAM
        /// @param[in] i_dram_generation DRAM generation
        /// @param[in] i_dimm_type DIMM type (e.g. RDIMM)
        /// @param[in] i_rows number of rows in the DRAM
        /// @param[in] i_size the overal size of the DIMM in GB
        /// @param[in] i_mfgid the dram manufacturer id of the dimm, defaulted to 0
        /// @param[in] i_stack_type dram die type, single die package or 3DS
        /// @param[in] i_hybrid, default not hybrid
        /// @param[in] i_hybrid_memory_type, defult none
        /// @param[in] i_rcd_mfgid dimm register and data buffer manufacturer id, default 0
        /// @note can't be constexpr as fapi2::Target doesn't have a constexpr ctor.
        ///
        kind( const uint8_t i_master_ranks,
              const uint8_t i_total_ranks,
              const uint8_t i_dram_density,
              const uint8_t i_dram_width,
              const uint8_t i_dram_generation,
              const uint8_t i_dimm_type,
              const uint8_t i_rows,
              const uint32_t i_size,
              const uint16_t i_mfgid = 0,
              const uint8_t i_stack_type = fapi2::ENUM_ATTR_MEM_EFF_PRIM_STACK_TYPE_SDP,
              const uint8_t i_hybrid = fapi2::ENUM_ATTR_MEM_EFF_HYBRID_NOT_HYBRID,
              const uint8_t i_hybrid_memory_type = fapi2::ENUM_ATTR_MEM_EFF_HYBRID_MEMORY_TYPE_NONE,
              const uint16_t i_rcd_mfgid = 0,
              const uint8_t i_module_height = 0
            ):
            iv_target(0),
            iv_master_ranks(i_master_ranks),
            iv_total_ranks(i_total_ranks),
            iv_dram_density(i_dram_density),
            iv_dram_width(i_dram_width),
            iv_dram_generation(i_dram_generation),
            iv_dimm_type(i_dimm_type),
            iv_rows(i_rows),
            // TK consider calculating size rather than requiring it be set.
            iv_size(i_size),
            iv_mfgid(i_mfgid),
            iv_stack_type(i_stack_type),
            iv_hybrid(i_hybrid),
            iv_hybrid_memory_type(i_hybrid_memory_type),
            iv_rcd_mfgid(i_rcd_mfgid),
            iv_module_height(i_module_height)
        {
            // Bit of an idiot-check to be sure a hand-crafted dimm::kind make sense wrt slaves, masters, packages, etc.
            // Both of these are checked in eff_config. If they are messed up, they should be caught there
            if (iv_master_ranks > iv_total_ranks)
            {
                FAPI_ERR("Not enough total ranks? master: %d total: %d",
                         iv_master_ranks,
                         iv_total_ranks);
                fapi2::Assert(false);
            }

            if ((iv_total_ranks % iv_master_ranks) != 0)
            {
                FAPI_ERR("total or master ranks seems incorrect. master: %d total: %d",
                         iv_master_ranks,
                         iv_total_ranks);
                fapi2::Assert(false);
            }
        }

        fapi2::Target<fapi2::TARGET_TYPE_DIMM> iv_target;
        uint8_t iv_master_ranks;
        uint8_t iv_total_ranks;
        uint8_t iv_dram_density;
        uint8_t iv_dram_width;
        uint8_t iv_dram_generation;
        uint8_t iv_dimm_type;
        uint8_t iv_rows;
        uint32_t iv_size;
        uint16_t iv_mfgid;
        uint8_t iv_stack_type;
        uint8_t iv_hybrid;
        uint8_t iv_hybrid_memory_type;
        uint16_t iv_rcd_mfgid;
        uint8_t iv_module_height;

        ///
        /// @brief equal_config
        /// @param[in] i_input_compare the i_kind to compare against
        /// @return bool true iff the two kind are of the same kind for xlate purposes
        /// @warning this does not compare the targets (iv_target,), mfgid, prim_stack_type nor hybrid type
        ///
        inline bool equal_config(const kind& i_input_compare) const
        {
            return ((iv_master_ranks == i_input_compare.iv_master_ranks) &&
                    (iv_total_ranks == i_input_compare.iv_total_ranks) &&
                    (iv_dram_density == i_input_compare.iv_dram_density) &&
                    (iv_dram_width == i_input_compare.iv_dram_width) &&
                    (iv_dram_generation == i_input_compare.iv_dram_generation) &&
                    (iv_dimm_type == i_input_compare.iv_dimm_type) &&
                    (iv_rows == i_input_compare.iv_rows) &&
                    (iv_size == i_input_compare.iv_size));
        }
};

}

}
#endif
<|endoftext|>


<commit_before>#include "rapid_pbd/world.h"

#include <string>
#include <vector>

#include "rapid_pbd_msgs/Action.h"
#include "rapid_pbd_msgs/Landmark.h"
#include "rapid_pbd_msgs/Program.h"
#include "rapid_pbd_msgs/Step.h"
#include "transform_graph/graph.h"

#include "rapid_pbd/joint_state.h"
#include "rapid_pbd/robot_config.h"

#include "ros/ros.h"

namespace msgs = rapid_pbd_msgs;

namespace rapid {
namespace pbd {
void GetWorld(const RobotConfig& robot_config, const msgs::Program& program,
              size_t step_id, World* world) {
  world->scene_id = "";
  JointState js(program.start_joint_state);
  world->joint_state = js;
  world->surface_box_landmarks.clear();

  for (size_t step_i = 0; step_i <= step_id; ++step_i) {
    if (program.steps.size() == 0) {
      break;
    }
    const msgs::Step& step = program.steps[step_i];
    if (step.scene_id != "") {
      world->scene_id = step.scene_id;
    }

    for (size_t action_i = 0; action_i < step.actions.size(); ++action_i) {
      const msgs::Action& action = step.actions[action_i];
      if (action.type == msgs::Action::ACTUATE_GRIPPER) {
        std::vector<std::string> joint_names;
        robot_config.gripper_joints_for_group(action.actuator_group,
                                              &joint_names);
        std::vector<double> positions;
        if (action.gripper_command.position > 0.0001) {
          robot_config.gripper_open_positions(&positions);
        } else {
          robot_config.gripper_close_positions(&positions);
        }
        for (size_t i = 0; i < joint_names.size(); ++i) {
          world->joint_state.SetPosition(joint_names[i], positions[i]);
        }
      } else if (action.type == msgs::Action::MOVE_TO_JOINT_GOAL) {
        const trajectory_msgs::JointTrajectory& trajectory =
            action.joint_trajectory;
        if (trajectory.points.size() == 0) {
          continue;
        }
        for (size_t i = 0; i < trajectory.joint_names.size(); ++i) {
          const std::string& name = trajectory.joint_names[i];
          double position = trajectory.points[0].positions[i];
          world->joint_state.SetPosition(name, position);
        }
      } else if (action.type == msgs::Action::MOVE_TO_CARTESIAN_GOAL) {
        std::vector<std::string> joint_names;
        std::vector<double> joint_values;

        transform_graph::Graph graph;
        graph.Add("landmark",
                  transform_graph::RefFrame(robot_config.base_link()),
                  action.landmark.pose_stamped.pose);
        graph.Add("ee", transform_graph::RefFrame("landmark"), action.pose);
        transform_graph::Transform ee_in_base;
        graph.ComputeDescription(
            transform_graph::LocalFrame("ee"),
            transform_graph::RefFrame(robot_config.base_link()), &ee_in_base);
        geometry_msgs::Pose pose;
        ee_in_base.ToPose(&pose);
        bool success = robot_config.ComputeIk(action.actuator_group, pose,
                                              &joint_names, &joint_values);
        if (!success) {
          ROS_ERROR(
              "Failed to compute IK for actuator %s on step %ld, action %ld",
              action.actuator_group.c_str(), step_i, action_i);
          continue;
        }
        for (size_t j = 0; j < joint_names.size(); ++j) {
          const std::string& name = joint_names[j];
          double position = joint_values[j];
          world->joint_state.SetPosition(name, position);
        }
      }
    }

    std::vector<msgs::Landmark> surface_boxes;
    for (size_t landmark_i = 0; landmark_i < step.landmarks.size();
         ++landmark_i) {
      const msgs::Landmark& landmark = step.landmarks[landmark_i];
      if (landmark.type == msgs::Landmark::SURFACE_BOX) {
        surface_boxes.push_back(landmark);
      }
      // Deal with other landmark types here
    }
    // Replace all surface objects if there are any.
    if (surface_boxes.size() > 0) {
      world->surface_box_landmarks = surface_boxes;
    }
  }
}
}  // namespace pbd
}  // namespace rapid
<commit_msg>Added TODO<commit_after>#include "rapid_pbd/world.h"

#include <string>
#include <vector>

#include "rapid_pbd_msgs/Action.h"
#include "rapid_pbd_msgs/Landmark.h"
#include "rapid_pbd_msgs/Program.h"
#include "rapid_pbd_msgs/Step.h"
#include "transform_graph/graph.h"

#include "rapid_pbd/joint_state.h"
#include "rapid_pbd/robot_config.h"

#include "ros/ros.h"

namespace msgs = rapid_pbd_msgs;

namespace rapid {
namespace pbd {
void GetWorld(const RobotConfig& robot_config, const msgs::Program& program,
              size_t step_id, World* world) {
  world->scene_id = "";
  JointState js(program.start_joint_state);
  world->joint_state = js;
  world->surface_box_landmarks.clear();

  // TODO: If this gets noticeably slow, change it so that it searches backward
  // instead of simulating forward. The channels to search are:
  // - Gripper action / actuator group
  // - Joint/Cartesian arm action / actuator group
  // - Scene ID
  // - Landmarks
  for (size_t step_i = 0; step_i <= step_id; ++step_i) {
    if (program.steps.size() == 0) {
      break;
    }
    const msgs::Step& step = program.steps[step_i];
    if (step.scene_id != "") {
      world->scene_id = step.scene_id;
    }

    for (size_t action_i = 0; action_i < step.actions.size(); ++action_i) {
      const msgs::Action& action = step.actions[action_i];
      if (action.type == msgs::Action::ACTUATE_GRIPPER) {
        std::vector<std::string> joint_names;
        robot_config.gripper_joints_for_group(action.actuator_group,
                                              &joint_names);
        std::vector<double> positions;
        if (action.gripper_command.position > 0.0001) {
          robot_config.gripper_open_positions(&positions);
        } else {
          robot_config.gripper_close_positions(&positions);
        }
        for (size_t i = 0; i < joint_names.size(); ++i) {
          world->joint_state.SetPosition(joint_names[i], positions[i]);
        }
      } else if (action.type == msgs::Action::MOVE_TO_JOINT_GOAL) {
        const trajectory_msgs::JointTrajectory& trajectory =
            action.joint_trajectory;
        if (trajectory.points.size() == 0) {
          continue;
        }
        for (size_t i = 0; i < trajectory.joint_names.size(); ++i) {
          const std::string& name = trajectory.joint_names[i];
          double position = trajectory.points[0].positions[i];
          world->joint_state.SetPosition(name, position);
        }
      } else if (action.type == msgs::Action::MOVE_TO_CARTESIAN_GOAL) {
        std::vector<std::string> joint_names;
        std::vector<double> joint_values;

        transform_graph::Graph graph;
        graph.Add("landmark",
                  transform_graph::RefFrame(robot_config.base_link()),
                  action.landmark.pose_stamped.pose);
        graph.Add("ee", transform_graph::RefFrame("landmark"), action.pose);
        transform_graph::Transform ee_in_base;
        graph.ComputeDescription(
            transform_graph::LocalFrame("ee"),
            transform_graph::RefFrame(robot_config.base_link()), &ee_in_base);
        geometry_msgs::Pose pose;
        ee_in_base.ToPose(&pose);
        bool success = robot_config.ComputeIk(action.actuator_group, pose,
                                              &joint_names, &joint_values);
        if (!success) {
          ROS_ERROR(
              "Failed to compute IK for actuator %s on step %ld, action %ld",
              action.actuator_group.c_str(), step_i, action_i);
          continue;
        }
        for (size_t j = 0; j < joint_names.size(); ++j) {
          const std::string& name = joint_names[j];
          double position = joint_values[j];
          world->joint_state.SetPosition(name, position);
        }
      }
    }

    std::vector<msgs::Landmark> surface_boxes;
    for (size_t landmark_i = 0; landmark_i < step.landmarks.size();
         ++landmark_i) {
      const msgs::Landmark& landmark = step.landmarks[landmark_i];
      if (landmark.type == msgs::Landmark::SURFACE_BOX) {
        surface_boxes.push_back(landmark);
      }
      // Deal with other landmark types here
    }
    // Replace all surface objects if there are any.
    if (surface_boxes.size() > 0) {
      world->surface_box_landmarks = surface_boxes;
    }
  }
}
}  // namespace pbd
}  // namespace rapid
<|endoftext|>


<commit_before>/*
*   Copyright 2020 Google LLC
*
*   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
*
*       https://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.
*/

#include "proto_parser.h"
#include "proto_value.h"
#include "gmock/gmock.h"
#include "proto/example.pb.h"

#include <google/protobuf/util/message_differencer.h>

namespace wireless_android_play_analytics{

const std::string text_proto = R"pb(
# comment 1
int32_field: 1

# comment 2
field_nested_message { # comment 3
  int64_field: 100
}

field_nested_message {
  # comment 4
  # comment 5
  int64_field: 100
}

bool_field: true
bool_field: false # comment 6
)pb";

class ProtoValueTest : public ::testing::Test {
 protected:

  virtual void SetUp() {
    message_ = ProtoValue::Create(text_proto, test_);
    message_val_ = dynamic_cast<MessageValue*>(message_.get());
  }

  TestProto test_;
  std::unique_ptr<ProtoValue> message_;
  MessageValue* message_val_;
};

TEST_F(ProtoValueTest, OuterProtoTest) {
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  EXPECT_EQ(message_val_->GetName(), "");
  EXPECT_EQ(message_val_->GetCommentAboveField().size(), 0);
  EXPECT_EQ(message_val_->GetCommentBehindField(), "");
  EXPECT_EQ(message_val_->GetIndentCount(), 0);
  EXPECT_EQ(fields.size(), 5);
}

TEST_F(ProtoValueTest, FirstFieldTest) {
  // #comment 1
  // int32_field: 1
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  PrimitiveValue* int32_field =
      dynamic_cast<PrimitiveValue*>(fields[0].get());
  ASSERT_NE(int32_field, nullptr);
  EXPECT_EQ(int32_field->GetName(), "int32_field");
  ASSERT_THAT(int32_field->GetCommentAboveField(),
      testing::ElementsAreArray({"# comment 1",}));
  EXPECT_EQ(int32_field->GetCommentBehindField(), "");

  // Inititialize the value to make sure it is held by an integer.
  int int32_field_val = 1;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      int32_field_val;
  EXPECT_TRUE(absl::holds_alternative<int>(int32_field->GetVal()));
  EXPECT_EQ(int32_field->GetVal(), val);
}

TEST_F(ProtoValueTest, SecondFieldTest) {
  //  # comment 2
  // field_nested_message { # comment 3
  //   int64_field: 100
  // }
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  MessageValue* field_nested_message =
      dynamic_cast<MessageValue*>(fields[1].get());
  ASSERT_NE(field_nested_message, nullptr);
  EXPECT_EQ(field_nested_message->GetName(), "field_nested_message");
  EXPECT_THAT(field_nested_message->GetCommentAboveField(),
      testing::ElementsAreArray({"# comment 2"}));
  EXPECT_EQ(field_nested_message->GetCommentBehindField(), "# comment 3");
  EXPECT_EQ(field_nested_message->GetIndentCount(), 0);
  const std::vector<std::unique_ptr<ProtoValue>>& field_nested_message_fields =
      field_nested_message->GetFields();

  // int64_field is the nested primitive field of field_nested message with no
  // comments.
  PrimitiveValue* int64_field =
      dynamic_cast<PrimitiveValue*>(field_nested_message_fields[0].get());
  // Iniitialize the value with int64_t to ensure it is held by int64_t.
  int64_t int64_field_val = 100;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      int64_field_val;
  EXPECT_EQ(field_nested_message_fields.size(), 1);
  ASSERT_NE(int64_field, nullptr);
  EXPECT_EQ(int64_field->GetName(), "int64_field");
  EXPECT_EQ(int64_field->GetCommentAboveField().size(), 0);
  EXPECT_EQ(int64_field->GetCommentBehindField(), "");
  // Since this field is nested it should have indentation of 1.
  EXPECT_EQ(int64_field->GetIndentCount(), 1);
  EXPECT_TRUE(absl::holds_alternative<int64_t>(int64_field->GetVal()));
  EXPECT_EQ(int64_field->GetVal(), val);
}

TEST_F(ProtoValueTest, ThirdFieldTest) {
  //  field_nested_message {
  //   # comment 4
  //   # comment 5
  //   int64_field: 100
  // }
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  MessageValue* field_nested_message =
      dynamic_cast<MessageValue*>(fields[2].get());
  ASSERT_NE(field_nested_message, nullptr);
  EXPECT_EQ(field_nested_message->GetName(), "field_nested_message");
  EXPECT_EQ(field_nested_message->GetCommentAboveField().size(), 0);
  EXPECT_EQ(field_nested_message->GetCommentBehindField(), "");
  EXPECT_EQ(field_nested_message->GetIndentCount(), 0);
  const std::vector<std::unique_ptr<ProtoValue>>& field_nested_message_fields =
      field_nested_message->GetFields();

  // This int64_field is a nested primitive with multiple comments above.
  PrimitiveValue* int64_field =
      dynamic_cast<PrimitiveValue*>(field_nested_message_fields[0].get());
  int64_t int64_field_val = 100;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      int64_field_val;
  EXPECT_EQ(1, field_nested_message_fields.size());
  ASSERT_NE(int64_field, nullptr);
  EXPECT_EQ(int64_field->GetName(), "int64_field");
  EXPECT_THAT(int64_field->GetCommentAboveField(),
      testing::ElementsAreArray({"# comment 4", "# comment 5"}));
  EXPECT_EQ(int64_field->GetCommentBehindField(), "");
  EXPECT_EQ(int64_field->GetIndentCount(), 1);
  EXPECT_TRUE(absl::holds_alternative<int64_t>(int64_field->GetVal()));
  EXPECT_EQ(int64_field->GetVal(), val);
}

TEST_F(ProtoValueTest, FourthFieldTest) {
  // bool_field: true
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  PrimitiveValue* bool_field =
      dynamic_cast<PrimitiveValue*>(fields[3].get());
  ASSERT_NE(nullptr, bool_field);
  EXPECT_EQ(bool_field->GetName(), "bool_field");
  EXPECT_EQ(bool_field->GetCommentAboveField().size(), 0);
  EXPECT_EQ(bool_field->GetCommentBehindField(), "");
  EXPECT_EQ(bool_field->GetIndentCount(), 0);
  bool bool_field_val = true;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      bool_field_val;
  EXPECT_TRUE(absl::holds_alternative<bool>(bool_field->GetVal()));
  EXPECT_EQ(bool_field->GetVal(), val);
}

TEST_F(ProtoValueTest, FifthFieldTest) {
  // bool_field: false # comment 6
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  PrimitiveValue* bool_field =
      dynamic_cast<PrimitiveValue*>(fields[4].get());
  ASSERT_NE(nullptr, bool_field);
  EXPECT_EQ(bool_field->GetName(), "bool_field");
  EXPECT_EQ(bool_field->GetCommentAboveField().size(), 0);
  EXPECT_EQ(bool_field->GetCommentBehindField(), "# comment 6");
  EXPECT_EQ(bool_field->GetIndentCount(), 0);
  bool bool_field_val = false;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      bool_field_val;
  EXPECT_TRUE(absl::holds_alternative<bool>(bool_field->GetVal()));
  EXPECT_EQ(bool_field->GetVal(), val);
}

} // namespace wireless_android_play_analytics

int main(int argc, char *argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<commit_msg>added field detail to test comments<commit_after>/*
*   Copyright 2020 Google LLC
*
*   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
*
*       https://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.
*/

#include "proto_parser.h"
#include "proto_value.h"
#include "gmock/gmock.h"
#include "proto/example.pb.h"

#include <google/protobuf/util/message_differencer.h>

namespace wireless_android_play_analytics{

const std::string text_proto = R"pb(
# comment 1
int32_field: 1

# comment 2
field_nested_message { # comment 3
  int64_field: 100
}

field_nested_message {
  # comment 4
  # comment 5
  int64_field: 100
}

bool_field: true
bool_field: false # comment 6
)pb";

class ProtoValueTest : public ::testing::Test {
 protected:

  virtual void SetUp() {
    message_ = ProtoValue::Create(text_proto, test_);
    message_val_ = dynamic_cast<MessageValue*>(message_.get());
  }

  TestProto test_;
  std::unique_ptr<ProtoValue> message_;
  MessageValue* message_val_;
};

TEST_F(ProtoValueTest, OuterProtoTest) {
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  EXPECT_EQ(message_val_->GetName(), "");
  EXPECT_EQ(message_val_->GetCommentAboveField().size(), 0);
  EXPECT_EQ(message_val_->GetCommentBehindField(), "");
  EXPECT_EQ(message_val_->GetIndentCount(), 0);
  EXPECT_EQ(fields.size(), 5);
}

TEST_F(ProtoValueTest, FirstFieldTest) {
  // Field detail:
  //
  // # comment 1
  // int32_field: 1
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  PrimitiveValue* int32_field =
      dynamic_cast<PrimitiveValue*>(fields[0].get());
  ASSERT_NE(int32_field, nullptr);
  EXPECT_EQ(int32_field->GetName(), "int32_field");
  ASSERT_THAT(int32_field->GetCommentAboveField(),
      testing::ElementsAreArray({"# comment 1",}));
  EXPECT_EQ(int32_field->GetCommentBehindField(), "");

  // Inititialize the value to make sure it is held by an integer.
  int int32_field_val = 1;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      int32_field_val;
  EXPECT_TRUE(absl::holds_alternative<int>(int32_field->GetVal()));
  EXPECT_EQ(int32_field->GetVal(), val);
}

TEST_F(ProtoValueTest, SecondFieldTest) {
  // Field detail:
  //
  // # comment 2
  // field_nested_message { # comment 3
  //   int64_field: 100
  // }
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  MessageValue* field_nested_message =
      dynamic_cast<MessageValue*>(fields[1].get());
  ASSERT_NE(field_nested_message, nullptr);
  EXPECT_EQ(field_nested_message->GetName(), "field_nested_message");
  EXPECT_THAT(field_nested_message->GetCommentAboveField(),
      testing::ElementsAreArray({"# comment 2"}));
  EXPECT_EQ(field_nested_message->GetCommentBehindField(), "# comment 3");
  EXPECT_EQ(field_nested_message->GetIndentCount(), 0);
  const std::vector<std::unique_ptr<ProtoValue>>& field_nested_message_fields =
      field_nested_message->GetFields();

  // int64_field is the nested primitive field of field_nested message with no
  // comments.
  PrimitiveValue* int64_field =
      dynamic_cast<PrimitiveValue*>(field_nested_message_fields[0].get());
  // Iniitialize the value with int64_t to ensure it is held by int64_t.
  int64_t int64_field_val = 100;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      int64_field_val;
  EXPECT_EQ(field_nested_message_fields.size(), 1);
  ASSERT_NE(int64_field, nullptr);
  EXPECT_EQ(int64_field->GetName(), "int64_field");
  EXPECT_EQ(int64_field->GetCommentAboveField().size(), 0);
  EXPECT_EQ(int64_field->GetCommentBehindField(), "");
  // Since this field is nested it should have indentation of 1.
  EXPECT_EQ(int64_field->GetIndentCount(), 1);
  EXPECT_TRUE(absl::holds_alternative<int64_t>(int64_field->GetVal()));
  EXPECT_EQ(int64_field->GetVal(), val);
}

TEST_F(ProtoValueTest, ThirdFieldTest) {
  // Field detail:
  //
  // field_nested_message {
  //   # comment 4
  //   # comment 5
  //   int64_field: 100
  // }
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  MessageValue* field_nested_message =
      dynamic_cast<MessageValue*>(fields[2].get());
  ASSERT_NE(field_nested_message, nullptr);
  EXPECT_EQ(field_nested_message->GetName(), "field_nested_message");
  EXPECT_EQ(field_nested_message->GetCommentAboveField().size(), 0);
  EXPECT_EQ(field_nested_message->GetCommentBehindField(), "");
  EXPECT_EQ(field_nested_message->GetIndentCount(), 0);
  const std::vector<std::unique_ptr<ProtoValue>>& field_nested_message_fields =
      field_nested_message->GetFields();

  // This int64_field is a nested primitive with multiple comments above.
  PrimitiveValue* int64_field =
      dynamic_cast<PrimitiveValue*>(field_nested_message_fields[0].get());
  int64_t int64_field_val = 100;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      int64_field_val;
  EXPECT_EQ(1, field_nested_message_fields.size());
  ASSERT_NE(int64_field, nullptr);
  EXPECT_EQ(int64_field->GetName(), "int64_field");
  EXPECT_THAT(int64_field->GetCommentAboveField(),
      testing::ElementsAreArray({"# comment 4", "# comment 5"}));
  EXPECT_EQ(int64_field->GetCommentBehindField(), "");
  EXPECT_EQ(int64_field->GetIndentCount(), 1);
  EXPECT_TRUE(absl::holds_alternative<int64_t>(int64_field->GetVal()));
  EXPECT_EQ(int64_field->GetVal(), val);
}

TEST_F(ProtoValueTest, FourthFieldTest) {
  // Field detail:
  //
  // bool_field: true
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  PrimitiveValue* bool_field =
      dynamic_cast<PrimitiveValue*>(fields[3].get());
  ASSERT_NE(nullptr, bool_field);
  EXPECT_EQ(bool_field->GetName(), "bool_field");
  EXPECT_EQ(bool_field->GetCommentAboveField().size(), 0);
  EXPECT_EQ(bool_field->GetCommentBehindField(), "");
  EXPECT_EQ(bool_field->GetIndentCount(), 0);
  bool bool_field_val = true;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      bool_field_val;
  EXPECT_TRUE(absl::holds_alternative<bool>(bool_field->GetVal()));
  EXPECT_EQ(bool_field->GetVal(), val);
}

TEST_F(ProtoValueTest, FifthFieldTest) {
  // Field detail:
  //
  // bool_field: false # comment 6
  const std::vector<std::unique_ptr<ProtoValue>>& fields =
      message_val_->GetFields();
  PrimitiveValue* bool_field =
      dynamic_cast<PrimitiveValue*>(fields[4].get());
  ASSERT_NE(nullptr, bool_field);
  EXPECT_EQ(bool_field->GetName(), "bool_field");
  EXPECT_EQ(bool_field->GetCommentAboveField().size(), 0);
  EXPECT_EQ(bool_field->GetCommentBehindField(), "# comment 6");
  EXPECT_EQ(bool_field->GetIndentCount(), 0);
  bool bool_field_val = false;
  absl::variant<double, float, int, unsigned int, int64_t, uint64_t, bool,
      const google::protobuf::EnumValueDescriptor *, std::string> val =
      bool_field_val;
  EXPECT_TRUE(absl::holds_alternative<bool>(bool_field->GetVal()));
  EXPECT_EQ(bool_field->GetVal(), val);
}

} // namespace wireless_android_play_analytics

int main(int argc, char *argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<|endoftext|>


<commit_before><commit_msg>Fix frame timestamp in VideoCapture::get<commit_after><|endoftext|>


<commit_before>#include "exampleLogging.h"
#include <unistd.h>

#include "ivi-logging-types.h"
#include <iostream>

// If an application is not multi-instance, we can define its unique identifier
LOG_DEFINE_APP_IDS("MyAp", "This is a small application showing how to use ivi-logging");

// Instantiate a log context and define it as default for this module
LOG_DECLARE_DEFAULT_CONTEXT(mainContext, "MAIN", "This is a description of that logging context");

// Instantiate another context which can be used instead of the previous one if specified
LOG_DECLARE_CONTEXT(anotherContext, "CXT2", "Another context");

namespace MyNamespace {

// Instantiate a log context and define it as default for this module
LOG_DECLARE_DEFAULT_CONTEXT(defaultContextForSpecificNamespace, "MAI2", "This is a description of that logging context");

void MyFunction() {
	log_info() << "My function called";
}

}

struct MyClass {

	// Define the log context to be used for that class. This overrides any default context which might have previously be set
	LOG_DECLARE_CLASS_CONTEXT("CCTX", "This is a class-specific context");

	void doSomething() {
		log_debug() << "We are doing something"; // This log uses the class log context
	}

};

struct MySubClass : MyClass {

	// Define the log context to be used for that class. This overrides any default context which might have previously be set
	LOG_DECLARE_CLASS_CONTEXT("CC", "This is a class-specific context for our sub-class");

	void doSomethingElse() {
		log_debug() << "We are doing something else";
		log_verbose() << "This is a verbose log";
	}

};

struct MyClassWithImportedContext {

    // Define the log context to be used for that class. This overrides any default context which might have previously be set
    LOG_SET_CLASS_CONTEXT(anotherContext);

    void doSomething() {
        log_debug() << "We are doing something. Imported context"; // This log uses the class log context
    }

};

struct SecondClassWithImportedContext {

    // Define the log context to be used for that class. This overrides any default context which might have previously be set
    LOG_SET_CLASS_CONTEXT(anotherContext);

    void doSomething() {
        log_debug() << "We are doing something. Imported context"; // This log uses the class log context
    }

};

void myFunction() {

	// Redefines the context to use for this scope (this function)
	LOG_DECLARE_DEFAULT_LOCAL_CONTEXT("CXT3", "Function-specific logging context");

	log_info() << "myFunction log 1";
	log_warn() << "myFunction log 2";

}

int generateDataForLogging() {
	static int count = 0;
	printf("generateDataForLogging called %i time(s)\n", ++count);
	return 100;
}

int main(int argc, const char** argv) {

	log_debug().writeFormatted("This log is using a format string, similar to the printf syntax. This is an int : %i", 345);
	log_error().writeFormatted("Another way to use the printf variant %i", 7345).writeFormatted(". Done");

	log_error("This one is mixed. Here is a float : ") << 5.7F;
	log_warn() << 5.7;
	log_warn() << "Test string";

	myFunction();

	myFunction2();

	MySubClass o;
	o.doSomething();
	o.doSomethingElse();

    MyClassWithImportedContext o2;
    o2.doSomething();

    SecondClassWithImportedContext o3;
    o3.doSomething();

	std::string stdString = "That is a std::string";
	log_error().write("Values can be passed at once to the write method. ", stdString, " / " , 1234);

	std::vector<char> charVector;
	for (char i = '0'; i <= '0' + 40; i++)
		charVector.push_back(i);

	log_warn() << "This is a vector of chars : " << charVector;

	MyNamespace::MyFunction();

	log_fatal() << "A fatal log";

	std::vector<MyClass*> vectorOfPointers;
	vectorOfPointers.push_back(new MyClass());
	vectorOfPointers.push_back(new MyClass());

	log_debug() << vectorOfPointers;

	log_warn() << generateDataForLogging();
	log_verbose() << generateDataForLogging();

	log_info() << "A log with std::endl" << std::endl;
	log_info() << "A log with std::ends" << std::ends;
	log_info() << "A log with std::flush" << std::flush;

	disableConsoleLogging();
	log_error() << "This log should not visible in the console";

	log_info() << "Sleeping";

	sleep(10);

}
<commit_msg>Improve example<commit_after>#include "exampleLogging.h"
#include <unistd.h>

#include "ivi-logging-types.h"
#include <iostream>

// If an application is not multi-instance, we can define its unique identifier
LOG_DEFINE_APP_IDS("MyAp", "This is a small application showing how to use ivi-logging");

// Instantiate a log context and define it as default for this module
LOG_DECLARE_DEFAULT_CONTEXT(mainContext, "MAIN", "This is a description of that logging context");

// Instantiate another context which can be used instead of the previous one if specified
LOG_DECLARE_CONTEXT(anotherContext, "CXT2", "Another context");

namespace MyNamespace {

// Instantiate a log context and define it as default for this module
LOG_DECLARE_DEFAULT_CONTEXT(defaultContextForSpecificNamespace, "MAI2", "This is a description of that logging context");

void MyFunction() {
	log_info() << "My function called";
}

}

struct MyClass {

	// Define the log context to be used for that class. This overrides any default context which might have previously be set
	LOG_DECLARE_CLASS_CONTEXT("CCTX", "This is a class-specific context");

	void doSomething() {
		log_debug() << "We are doing something"; // This log uses the class log context
	}

};

struct MySubClass : MyClass {

	// Define the log context to be used for that class. This overrides any default context which might have previously be set
	LOG_DECLARE_CLASS_CONTEXT("CC", "This is a class-specific context for our sub-class");

	void doSomethingElse() {
		log_debug() << "We are doing something else";
		log_verbose() << "This is a verbose log";
	}

};

struct MyClassWithImportedContext {

    // Define the log context to be used for that class. This overrides any default context which might have previously be set
    LOG_SET_CLASS_CONTEXT(anotherContext);

    void doSomething() {
        log_debug() << "We are doing something. Imported context"; // This log uses the class log context
    }

};

struct SecondClassWithImportedContext {

    // Define the log context to be used for that class. This overrides any default context which might have previously be set
    LOG_SET_CLASS_CONTEXT(anotherContext);

    void doSomething() {
        log_debug() << "We are doing something. Imported context"; // This log uses the class log context
    }

};

void myFunction() {

	// Redefines the context to use for this scope (this function)
	LOG_DECLARE_DEFAULT_LOCAL_CONTEXT("CXT3", "Function-specific logging context");

	log_info() << "myFunction log 1";
	log_warn() << "myFunction log 2";

}

int generateDataForLogging() {
	static int count = 0;
	printf("generateDataForLogging called %i time(s)\n", ++count);
	return 100;
}

int main(int argc, const char** argv) {

	log_debug().writeFormatted("This log is using a format string, similar to the printf syntax. This is an int : %i", 345);
	log_error().writeFormatted("Another way to use the printf variant %i", 7345).writeFormatted(". Done");

	log_error("This one is mixed. Here is a float : ") << 5.7F;
	log_warn() << 5.7;
	log_warn() << "Test string";

	myFunction();

	myFunction2();

	MySubClass o;
	o.doSomething();
	o.doSomethingElse();

    MyClassWithImportedContext o2;
    o2.doSomething();

    SecondClassWithImportedContext o3;
    o3.doSomething();

	std::string stdString = "That is a std::string";
	log_error().write("Values can be passed at once to the write method. ", stdString, " / " , 1234);

	std::vector<char> charVector;
	for (char i = '0'; i <= '0' + 40; i++)
		charVector.push_back(i);

	log_warn() << "This is a vector of chars : " << charVector;

	MyNamespace::MyFunction();

	log_fatal() << "A fatal log";

	std::vector<MyClass*> vectorOfPointers;
	vectorOfPointers.push_back(new MyClass());
	vectorOfPointers.push_back(new MyClass());

	log_debug() << vectorOfPointers;

	log_warn() << generateDataForLogging();
	log_verbose() << generateDataForLogging();

	log_info() << "A log with std::endl" << std::endl;
	log_info() << "A log with std::ends" << std::ends;
	log_info() << "A log with std::flush" << std::flush;

    static const int DURATION = 10000;

    log_info() << "Waiting " << DURATION << " seconds";

    for(int i = DURATION ; i>0 ; i--) {
        log_info() << i << " seconds before termination";
        sleep(1);
    }

	disableConsoleLogging();
	log_error() << "This log should not visible in the console";

	log_info() << "We are done. Bye";

}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014, Ford Motor Company
 * 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 Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sstream>

#include "transport_manager/transport_adapter/transport_adapter_impl.h"
#include "transport_manager/usb/usb_device_scanner.h"
#include "transport_manager/usb/usb_device.h"
#include "transport_manager/usb/common.h"

#include "utils/logger.h"

namespace transport_manager {
namespace transport_adapter {

CREATE_LOGGERPTR_GLOBAL(logger_, "UsbDeviceScanner")

class AoaInitSequence : public UsbControlTransferSequence {
 public:
  AoaInitSequence();
  virtual ~AoaInitSequence() {
  }

 private:
  class AoaGetProtocolRequest;
  class AoaSendIdString;
  class AoaTurnIntoAccessoryMode;
};

void UsbDeviceScanner::OnDeviceArrived(PlatformUsbDevice* device) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (IsAppleDevice(device)) {
    SupportedDeviceFound(device);
  } else {
    if (IsGoogleAccessory(device)) {
      SupportedDeviceFound(device);
    } else {
      TurnIntoAccessoryMode(device);
    }
  }
}

void UsbDeviceScanner::OnDeviceLeft(PlatformUsbDevice* device) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "PlatformUsbDevice " << device);
  bool list_changed = false;
  devices_mutex_.Acquire();
  for (Devices::iterator it = devices_.begin(); it != devices_.end(); ++it) {
    if (device == *it) {
      devices_.erase(it);
      list_changed = true;
      break;
    }
  }
  devices_mutex_.Release();
  if (list_changed) {
    UpdateList();
  }
}

UsbDeviceScanner::UsbDeviceScanner(TransportAdapterController* controller)
    : controller_(controller) {
}

UsbDeviceScanner::~UsbDeviceScanner() {
}

class AoaInitSequence::AoaGetProtocolRequest : public UsbControlInTransfer {
  virtual ~AoaGetProtocolRequest() {
  }
  virtual RequestType Type() const {
    return VENDOR;
  }
  virtual uint8_t Request() const {
    return 51;
  }
  virtual uint16_t Value() const {
    return 0;
  }
  virtual uint16_t Index() const {
    return 0;
  }
  virtual uint16_t Length() const {
    return 2;
  }
  virtual bool OnCompleted(unsigned char* data) const {
    const int protocol_version = data[1] << 8 | data[0];
    LOG4CXX_DEBUG(logger_, "AOA protocol version " << protocol_version);
    if (protocol_version == 0) {
      // AOA protocol not supported
      return false;
    }
    return true;
  }
};

class AoaInitSequence::AoaSendIdString : public UsbControlOutTransfer {
 public:
  AoaSendIdString(uint16_t index, const char* string, uint16_t length)
      : index_(index),
        string_(string),
        length_(length) {
  }

 private:
  virtual ~AoaSendIdString() {
  }
  virtual RequestType Type() const {
    return VENDOR;
  }
  virtual uint8_t Request() const {
    return 52;
  }
  virtual uint16_t Value() const {
    return 0;
  }
  virtual uint16_t Index() const {
    return index_;
  }
  virtual uint16_t Length() const {
    return length_;
  }
  virtual const char* Data() const {
    return string_;
  }
  uint16_t index_;
  const char* string_;
  uint16_t length_;
};

class AoaInitSequence::AoaTurnIntoAccessoryMode : public UsbControlOutTransfer {
  virtual ~AoaTurnIntoAccessoryMode() {
  }
  virtual RequestType Type() const {
    return VENDOR;
  }
  virtual uint8_t Request() const {
    return 53;
  }
  virtual uint16_t Value() const {
    return 0;
  }
  virtual uint16_t Index() const {
    return 0;
  }
  virtual uint16_t Length() const {
    return 0;
  }
  virtual const char* Data() const {
    return 0;
  }
};

#ifdef MODIFY_FUNCTION_SIGN
static char manufacturer[] = "Ford";
static char model_name[] = "HMI";
static char description[] = "Human machine interface";
static char version[] = "1.0";
static char uri[] = "http://www.ford.com";
static char serial_num[] = "N000000";
#else
static char manufacturer[] = "SDL";
static char model_name[] = "Core";
static char description[] = "SmartDeviceLink Core Component USB";
static char version[] = "1.0";
static char uri[] = "http://www.smartdevicelink.org";
static char serial_num[] = "N000000";
#endif

AoaInitSequence::AoaInitSequence()
    : UsbControlTransferSequence() {
  AddTransfer(new AoaGetProtocolRequest);
  AddTransfer(new AoaSendIdString(0, manufacturer, sizeof(manufacturer)));
  AddTransfer(new AoaSendIdString(1, model_name, sizeof(model_name)));
  AddTransfer(new AoaSendIdString(2, description, sizeof(description)));
  AddTransfer(new AoaSendIdString(3, version, sizeof(version)));
  AddTransfer(new AoaSendIdString(4, uri, sizeof(uri)));
  AddTransfer(new AoaSendIdString(5, serial_num, sizeof(serial_num)));
  AddTransfer(new AoaTurnIntoAccessoryMode);
}

void UsbDeviceScanner::TurnIntoAccessoryMode(PlatformUsbDevice* device) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "PlatformUsbDevice: " << device);
  GetUsbHandler()->StartControlTransferSequence(new AoaInitSequence, device);
}

void UsbDeviceScanner::SupportedDeviceFound(PlatformUsbDevice* device) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_TRACE(logger_, "PlatformUsbDevice: " << device);

  devices_mutex_.Acquire();
  devices_.push_back(device);
  devices_mutex_.Release();
  LOG4CXX_DEBUG(
      logger_,
      "USB device (bus number " << static_cast<int>(device->bus_number())
      << ", address " << static_cast<int>(device->address())
      << ") identified as: " << device->GetManufacturer()
      << ", " << device->GetProductName()
      << ", serial: " << device->GetSerialNumber());
  UpdateList();
}

TransportAdapter::Error UsbDeviceScanner::Init() {
  return TransportAdapter::OK;
}

TransportAdapter::Error UsbDeviceScanner::Scan() {
  return TransportAdapter::OK;
}

void UsbDeviceScanner::UpdateList() {
  LOG4CXX_AUTO_TRACE(logger_);
  DeviceVector device_vector;
  devices_mutex_.Acquire();
  for (Devices::const_iterator it = devices_.begin(); it != devices_.end();
      ++it) {
    const std::string device_name = (*it)->GetManufacturer() + " "
        + (*it)->GetProductName();
    std::ostringstream oss;
    oss << (*it)->GetManufacturer() << ":" << (*it)->GetProductName() << ":"
        << (*it)->GetSerialNumber();
    const DeviceUID device_uid = oss.str();
    DeviceSptr device(new UsbDevice(*it, device_name, device_uid));
    device_vector.push_back(device);
  }
  devices_mutex_.Release();

  LOG4CXX_DEBUG(logger_, "USB search done " << device_vector.size());
  controller_->SearchDeviceDone(device_vector);
}

void UsbDeviceScanner::Terminate() {
}

bool UsbDeviceScanner::IsInitialised() const {
  return true;
}

}  // namespace
}  // namespace
<commit_msg>Revert usb_device_scanner.cc to use SyncProxyTester of SDL4.0.<commit_after>/*
 * Copyright (c) 2014, Ford Motor Company
 * 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 Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sstream>

#include "transport_manager/transport_adapter/transport_adapter_impl.h"
#include "transport_manager/usb/usb_device_scanner.h"
#include "transport_manager/usb/usb_device.h"
#include "transport_manager/usb/common.h"

#include "utils/logger.h"

namespace transport_manager {
namespace transport_adapter {

CREATE_LOGGERPTR_GLOBAL(logger_, "UsbDeviceScanner")

class AoaInitSequence : public UsbControlTransferSequence {
 public:
  AoaInitSequence();
  virtual ~AoaInitSequence() {
  }

 private:
  class AoaGetProtocolRequest;
  class AoaSendIdString;
  class AoaTurnIntoAccessoryMode;
};

void UsbDeviceScanner::OnDeviceArrived(PlatformUsbDevice* device) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (IsAppleDevice(device)) {
    SupportedDeviceFound(device);
  } else {
    if (IsGoogleAccessory(device)) {
      SupportedDeviceFound(device);
    } else {
      TurnIntoAccessoryMode(device);
    }
  }
}

void UsbDeviceScanner::OnDeviceLeft(PlatformUsbDevice* device) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "PlatformUsbDevice " << device);
  bool list_changed = false;
  devices_mutex_.Acquire();
  for (Devices::iterator it = devices_.begin(); it != devices_.end(); ++it) {
    if (device == *it) {
      devices_.erase(it);
      list_changed = true;
      break;
    }
  }
  devices_mutex_.Release();
  if (list_changed) {
    UpdateList();
  }
}

UsbDeviceScanner::UsbDeviceScanner(TransportAdapterController* controller)
    : controller_(controller) {
}

UsbDeviceScanner::~UsbDeviceScanner() {
}

class AoaInitSequence::AoaGetProtocolRequest : public UsbControlInTransfer {
  virtual ~AoaGetProtocolRequest() {
  }
  virtual RequestType Type() const {
    return VENDOR;
  }
  virtual uint8_t Request() const {
    return 51;
  }
  virtual uint16_t Value() const {
    return 0;
  }
  virtual uint16_t Index() const {
    return 0;
  }
  virtual uint16_t Length() const {
    return 2;
  }
  virtual bool OnCompleted(unsigned char* data) const {
    const int protocol_version = data[1] << 8 | data[0];
    LOG4CXX_DEBUG(logger_, "AOA protocol version " << protocol_version);
    if (protocol_version == 0) {
      // AOA protocol not supported
      return false;
    }
    return true;
  }
};

class AoaInitSequence::AoaSendIdString : public UsbControlOutTransfer {
 public:
  AoaSendIdString(uint16_t index, const char* string, uint16_t length)
      : index_(index),
        string_(string),
        length_(length) {
  }

 private:
  virtual ~AoaSendIdString() {
  }
  virtual RequestType Type() const {
    return VENDOR;
  }
  virtual uint8_t Request() const {
    return 52;
  }
  virtual uint16_t Value() const {
    return 0;
  }
  virtual uint16_t Index() const {
    return index_;
  }
  virtual uint16_t Length() const {
    return length_;
  }
  virtual const char* Data() const {
    return string_;
  }
  uint16_t index_;
  const char* string_;
  uint16_t length_;
};

class AoaInitSequence::AoaTurnIntoAccessoryMode : public UsbControlOutTransfer {
  virtual ~AoaTurnIntoAccessoryMode() {
  }
  virtual RequestType Type() const {
    return VENDOR;
  }
  virtual uint8_t Request() const {
    return 53;
  }
  virtual uint16_t Value() const {
    return 0;
  }
  virtual uint16_t Index() const {
    return 0;
  }
  virtual uint16_t Length() const {
    return 0;
  }
  virtual const char* Data() const {
    return 0;
  }
};

static char manufacturer[] = "SDL";
static char model_name[] = "Core";
static char description[] = "SmartDeviceLink Core Component USB";
static char version[] = "1.0";
static char uri[] = "http://www.smartdevicelink.org";
static char serial_num[] = "N000000";

AoaInitSequence::AoaInitSequence()
    : UsbControlTransferSequence() {
  AddTransfer(new AoaGetProtocolRequest);
  AddTransfer(new AoaSendIdString(0, manufacturer, sizeof(manufacturer)));
  AddTransfer(new AoaSendIdString(1, model_name, sizeof(model_name)));
  AddTransfer(new AoaSendIdString(2, description, sizeof(description)));
  AddTransfer(new AoaSendIdString(3, version, sizeof(version)));
  AddTransfer(new AoaSendIdString(4, uri, sizeof(uri)));
  AddTransfer(new AoaSendIdString(5, serial_num, sizeof(serial_num)));
  AddTransfer(new AoaTurnIntoAccessoryMode);
}

void UsbDeviceScanner::TurnIntoAccessoryMode(PlatformUsbDevice* device) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "PlatformUsbDevice: " << device);
  GetUsbHandler()->StartControlTransferSequence(new AoaInitSequence, device);
}

void UsbDeviceScanner::SupportedDeviceFound(PlatformUsbDevice* device) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_TRACE(logger_, "PlatformUsbDevice: " << device);

  devices_mutex_.Acquire();
  devices_.push_back(device);
  devices_mutex_.Release();
  LOG4CXX_DEBUG(
      logger_,
      "USB device (bus number " << static_cast<int>(device->bus_number())
      << ", address " << static_cast<int>(device->address())
      << ") identified as: " << device->GetManufacturer()
      << ", " << device->GetProductName()
      << ", serial: " << device->GetSerialNumber());
  UpdateList();
}

TransportAdapter::Error UsbDeviceScanner::Init() {
  return TransportAdapter::OK;
}

TransportAdapter::Error UsbDeviceScanner::Scan() {
  return TransportAdapter::OK;
}

void UsbDeviceScanner::UpdateList() {
  LOG4CXX_AUTO_TRACE(logger_);
  DeviceVector device_vector;
  devices_mutex_.Acquire();
  for (Devices::const_iterator it = devices_.begin(); it != devices_.end();
      ++it) {
    const std::string device_name = (*it)->GetManufacturer() + " "
        + (*it)->GetProductName();
    std::ostringstream oss;
    oss << (*it)->GetManufacturer() << ":" << (*it)->GetProductName() << ":"
        << (*it)->GetSerialNumber();
    const DeviceUID device_uid = oss.str();
    DeviceSptr device(new UsbDevice(*it, device_name, device_uid));
    device_vector.push_back(device);
  }
  devices_mutex_.Release();

  LOG4CXX_DEBUG(logger_, "USB search done " << device_vector.size());
  controller_->SearchDeviceDone(device_vector);
}

void UsbDeviceScanner::Terminate() {
}

bool UsbDeviceScanner::IsInitialised() const {
  return true;
}

}  // namespace
}  // namespace
<|endoftext|>


<commit_before>/*************************************************************************/
/*  detect_prime.cpp                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifdef X11_ENABLED
#if defined(OPENGL_ENABLED)

#include "detect_prime.h"

#include "core/print_string.h"
#include "core/ustring.h"

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glx.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <cstring>

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092

typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *);

struct vendor {
	const char *glxvendor;
	int priority;
};

vendor vendormap[] = {
	{ "Advanced Micro Devices, Inc.", 30 },
	{ "NVIDIA Corporation", 30 },
	{ "X.Org", 30 },
	{ "Intel Open Source Technology Center", 20 },
	{ "Intel", 20 },
	{ "nouveau", 10 },
	{ "Mesa Project", 0 },
	{ NULL, 0 }
};

// Runs inside a child. Exiting will not quit the engine.
void create_context() {
	Display *x11_display = XOpenDisplay(NULL);
	Window x11_window;
	GLXContext glx_context;

	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB");

	static int visual_attribs[] = {
		GLX_RENDER_TYPE, GLX_RGBA_BIT,
		GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
		GLX_DOUBLEBUFFER, true,
		GLX_RED_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_DEPTH_SIZE, 24,
		None
	};

	int fbcount;
	GLXFBConfig fbconfig = 0;
	XVisualInfo *vi = NULL;

	XSetWindowAttributes swa;
	swa.event_mask = StructureNotifyMask;
	swa.border_pixel = 0;
	unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;

	GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
	if (!fbc)
		exit(1);

	vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

	fbconfig = fbc[0];

	static int context_attribs[] = {
		GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
		GLX_CONTEXT_MINOR_VERSION_ARB, 3,
		GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
		GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
		None
	};

	glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, NULL, true, context_attribs);

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, 10, 10, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa);

	if (!x11_window)
		exit(1);

	glXMakeCurrent(x11_display, x11_window, glx_context);
	XFree(vi);
}

int detect_prime() {
	pid_t p;
	int priorities[2];
	String vendors[2];
	String renderers[2];

	vendors[0] = "Unknown";
	vendors[1] = "Unknown";
	renderers[0] = "Unknown";
	renderers[1] = "Unknown";

	for (int i = 0; i < 2; ++i) {
		int fdset[2];

		if (pipe(fdset) == -1) {
			print_verbose("Failed to pipe(), using default GPU");
			return 0;
		}

		// Fork so the driver initialization can crash without taking down the engine.
		p = fork();

		if (p > 0) {
			// Main thread

			int stat_loc = 0;
			char string[201];
			string[200] = '\0';

			close(fdset[1]);

			waitpid(p, &stat_loc, 0);

			if (!stat_loc) {
				// No need to do anything complicated here. Anything less than
				// PIPE_BUF will be delivered in one read() call.
				// Leave it 'Unknown' otherwise.
				if (read(fdset[0], string, sizeof(string) - 1) > 0) {
					vendors[i] = string;
					renderers[i] = string + strlen(string) + 1;
				}
			}

			close(fdset[0]);

		} else {
			// In child, exit() here will not quit the engine.

			char string[201];

			close(fdset[0]);

			if (i) setenv("DRI_PRIME", "1", 1);
			create_context();

			const char *vendor = (const char *)glGetString(GL_VENDOR);
			const char *renderer = (const char *)glGetString(GL_RENDERER);

			unsigned int vendor_len = strlen(vendor) + 1;
			unsigned int renderer_len = strlen(renderer) + 1;

			if (vendor_len + renderer_len >= sizeof(string)) {
				renderer_len = 200 - vendor_len;
			}

			memcpy(&string, vendor, vendor_len);
			memcpy(&string[vendor_len], renderer, renderer_len);

			if (write(fdset[1], string, vendor_len + renderer_len) == -1) {
				print_verbose("Couldn't write vendor/renderer string.");
			}
			close(fdset[1]);
			exit(0);
		}
	}

	int preferred = 0;
	int priority = 0;

	if (vendors[0] == vendors[1]) {
		print_verbose("Only one GPU found, using default.");
		return 0;
	}

	for (int i = 1; i >= 0; --i) {
		vendor *v = vendormap;
		while (v->glxvendor) {
			if (v->glxvendor == vendors[i]) {
				priorities[i] = v->priority;

				if (v->priority >= priority) {
					priority = v->priority;
					preferred = i;
				}
			}
			++v;
		}
	}

	print_verbose("Found renderers:");
	for (int i = 0; i < 2; ++i) {
		print_verbose("Renderer " + itos(i) + ": " + renderers[i] + " with priority: " + itos(priorities[i]));
	}

	print_verbose("Using renderer: " + renderers[preferred]);
	return preferred;
}

#endif
#endif
<commit_msg>Add 'AMD' GPU vendor name to PRIME detector<commit_after>/*************************************************************************/
/*  detect_prime.cpp                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifdef X11_ENABLED
#if defined(OPENGL_ENABLED)

#include "detect_prime.h"

#include "core/print_string.h"
#include "core/ustring.h"

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glx.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <cstring>

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092

typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *);

struct vendor {
	const char *glxvendor;
	int priority;
};

vendor vendormap[] = {
	{ "Advanced Micro Devices, Inc.", 30 },
	{ "AMD", 30 },
	{ "NVIDIA Corporation", 30 },
	{ "X.Org", 30 },
	{ "Intel Open Source Technology Center", 20 },
	{ "Intel", 20 },
	{ "nouveau", 10 },
	{ "Mesa Project", 0 },
	{ NULL, 0 }
};

// Runs inside a child. Exiting will not quit the engine.
void create_context() {
	Display *x11_display = XOpenDisplay(NULL);
	Window x11_window;
	GLXContext glx_context;

	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB");

	static int visual_attribs[] = {
		GLX_RENDER_TYPE, GLX_RGBA_BIT,
		GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
		GLX_DOUBLEBUFFER, true,
		GLX_RED_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_DEPTH_SIZE, 24,
		None
	};

	int fbcount;
	GLXFBConfig fbconfig = 0;
	XVisualInfo *vi = NULL;

	XSetWindowAttributes swa;
	swa.event_mask = StructureNotifyMask;
	swa.border_pixel = 0;
	unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;

	GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
	if (!fbc)
		exit(1);

	vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

	fbconfig = fbc[0];

	static int context_attribs[] = {
		GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
		GLX_CONTEXT_MINOR_VERSION_ARB, 3,
		GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
		GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
		None
	};

	glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, NULL, true, context_attribs);

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, 10, 10, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa);

	if (!x11_window)
		exit(1);

	glXMakeCurrent(x11_display, x11_window, glx_context);
	XFree(vi);
}

int detect_prime() {
	pid_t p;
	int priorities[2] = {};
	String vendors[2];
	String renderers[2];

	vendors[0] = "Unknown";
	vendors[1] = "Unknown";
	renderers[0] = "Unknown";
	renderers[1] = "Unknown";

	for (int i = 0; i < 2; ++i) {
		int fdset[2];

		if (pipe(fdset) == -1) {
			print_verbose("Failed to pipe(), using default GPU");
			return 0;
		}

		// Fork so the driver initialization can crash without taking down the engine.
		p = fork();

		if (p > 0) {
			// Main thread

			int stat_loc = 0;
			char string[201];
			string[200] = '\0';

			close(fdset[1]);

			waitpid(p, &stat_loc, 0);

			if (!stat_loc) {
				// No need to do anything complicated here. Anything less than
				// PIPE_BUF will be delivered in one read() call.
				// Leave it 'Unknown' otherwise.
				if (read(fdset[0], string, sizeof(string) - 1) > 0) {
					vendors[i] = string;
					renderers[i] = string + strlen(string) + 1;
				}
			}

			close(fdset[0]);

		} else {
			// In child, exit() here will not quit the engine.

			char string[201];

			close(fdset[0]);

			if (i) setenv("DRI_PRIME", "1", 1);
			create_context();

			const char *vendor = (const char *)glGetString(GL_VENDOR);
			const char *renderer = (const char *)glGetString(GL_RENDERER);

			unsigned int vendor_len = strlen(vendor) + 1;
			unsigned int renderer_len = strlen(renderer) + 1;

			if (vendor_len + renderer_len >= sizeof(string)) {
				renderer_len = 200 - vendor_len;
			}

			memcpy(&string, vendor, vendor_len);
			memcpy(&string[vendor_len], renderer, renderer_len);

			if (write(fdset[1], string, vendor_len + renderer_len) == -1) {
				print_verbose("Couldn't write vendor/renderer string.");
			}
			close(fdset[1]);
			exit(0);
		}
	}

	int preferred = 0;
	int priority = 0;

	if (vendors[0] == vendors[1]) {
		print_verbose("Only one GPU found, using default.");
		return 0;
	}

	for (int i = 1; i >= 0; --i) {
		vendor *v = vendormap;
		while (v->glxvendor) {
			if (v->glxvendor == vendors[i]) {
				priorities[i] = v->priority;

				if (v->priority >= priority) {
					priority = v->priority;
					preferred = i;
				}
			}
			++v;
		}
	}

	print_verbose("Found renderers:");
	for (int i = 0; i < 2; ++i) {
		print_verbose("Renderer " + itos(i) + ": " + renderers[i] + " with priority: " + itos(priorities[i]));
	}

	print_verbose("Using renderer: " + renderers[preferred]);
	return preferred;
}

#endif
#endif
<|endoftext|>