Fix array static_assertion with newer compilers (#363)

Signed-off-by: Michael Carroll <17b9e1c64588c7fa6419b4d29dc1f4426279ba01@openrobotics.org>

// generated from ros1_bridge/resource/interface_factories.cpp.em

@###############################################
@#
@# Factory template specializations for a
@# specific message type
@#
@# EmPy template for generating
@# <pkgname>__<type>__<interfacename>__factories.cpp
@#
@###############################################
@# Start of Template
@#
@# Context:
@#  - ros2_package_name (str)
@#    The ROS 2 package name of this file
@#  - mappings (list of ros1_bridge.Mapping)
@#    Mapping between messages as well as their fields
@###############################################
@
@{
from ros1_bridge import camel_case_to_lower_case_underscore
from rosidl_parser.definition import AbstractNestedType
from rosidl_parser.definition import AbstractSequence
from rosidl_parser.definition import BoundedSequence
from rosidl_parser.definition import NamespacedType
}@
#include "@(ros2_package_name)_factories.hpp"

#include <algorithm>

#include "rclcpp/rclcpp.hpp"

// include builtin interfaces
#include <ros1_bridge/convert_builtin_interfaces.hpp>

// include ROS 1 services
@[for service in mapped_services]@
#include <@(service["ros1_package"])/@(service["ros1_name"]).h>
@[end for]@

// include ROS 2 services
@[for service in mapped_services]@
#include <@(service["ros2_package"])/srv/@(camel_case_to_lower_case_underscore(service["ros2_name"])).hpp>
@[end for]@

namespace ros1_bridge
{

std::shared_ptr<FactoryInterface>
get_factory_@(ros2_package_name)__@(interface_type)__@(interface.message_name)(const std::string & ros1_type_name, const std::string & ros2_type_name)
{
@[if not mapped_msgs]@
  (void)ros1_type_name;
  (void)ros2_type_name;
@[else]@
  // mapping from string to specialized template
@[end if]@
@[for m in mapped_msgs]@
  if (
    (ros1_type_name == "@(m.ros1_msg.package_name)/@(m.ros1_msg.message_name)" ||
     ros1_type_name == "") &&
    ros2_type_name == "@(m.ros2_msg.package_name)/msg/@(m.ros2_msg.message_name)")
  {
    return std::make_shared<
      Factory<
        @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name),
        @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name)
      >
    >("@(m.ros1_msg.package_name)/@(m.ros1_msg.message_name)", ros2_type_name);
  }
@[end for]@
  return std::shared_ptr<FactoryInterface>();
}

std::unique_ptr<ServiceFactoryInterface>
get_service_factory_@(ros2_package_name)__@(interface_type)__@(interface.message_name)(const std::string & ros_id, const std::string & package_name, const std::string & service_name)
{
@[if not mapped_services]@
  (void)ros_id;
  (void)package_name;
  (void)service_name;
@[end if]@
@[for service in mapped_services]@
  if (
    (
      ros_id == "ros1" &&
      package_name == "@(service["ros1_package"])" &&
      service_name == "@(service["ros1_name"])"
    ) || (
      ros_id == "ros2" &&
      package_name == "@(service["ros2_package"])" &&
      service_name == "srv/@(service["ros2_name"])"
    )
  ) {
    return std::unique_ptr<ServiceFactoryInterface>(new ServiceFactory<
      @(service["ros1_package"])::@(service["ros1_name"]),
      @(service["ros2_package"])::srv::@(service["ros2_name"])
    >);
  }
@[end for]@
  return nullptr;
}
@
// conversion functions for available interfaces
@[for m in mapped_msgs]@

template<>
void
Factory<
  @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name),
  @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name)
>::convert_1_to_2(
  const @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name) & ros1_msg,
  @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name) & ros2_msg)
{
@[  if not m.fields_1_to_2]@
  (void)ros1_msg;
  (void)ros2_msg;
@[  end if]@
@[  for ros1_fields, ros2_fields in m.fields_1_to_2.items()]@
@{
ros1_field_selection = '.'.join((str(field.name) for field in ros1_fields))
ros2_field_selection = '.'.join((str(field.name) for field in ros2_fields))

if isinstance(ros2_fields[-1].type, NamespacedType):
    namespaces = ros2_fields[-1].type.namespaces
    assert len(namespaces) == 2 and namespaces[1] == 'msg', \
      "messages not using the '<pkg_name>, msg, <type_name>' triplet are not supported"
}
@[    if not isinstance(ros2_fields[-1].type, AbstractNestedType)]@
  // convert non-array field
@[      if not isinstance(ros2_fields[-1].type, NamespacedType)]@
  // convert primitive field
  ros2_msg.@(ros2_field_selection) = ros1_msg.@(ros1_field_selection);
@[      elif ros2_fields[-1].type.namespaces[0] == 'builtin_interfaces']@
  // convert builtin field
  ros1_bridge::convert_1_to_2(ros1_msg.@(ros1_field_selection), ros2_msg.@(ros2_field_selection));
@[      else]@
  // convert sub message field
  Factory<
    @(ros1_fields[-1].pkg_name)::@(ros1_fields[-1].msg_name),
    @(ros2_fields[-1].type.namespaces[0])::msg::@(ros2_fields[-1].type.name)
  >::convert_1_to_2(
    ros1_msg.@(ros1_field_selection), ros2_msg.@(ros2_field_selection));
@[      end if]@
@[    else]@
  // convert array or sequence field
@[      if isinstance(ros2_fields[-1].type, AbstractSequence)]@
  // dynamically sized sequence, ensure destination sequence/vector size is large enough
@[        if isinstance(ros2_fields[-1].type, BoundedSequence)]@
  // bounded size sequence, check that the ros 1 vector size is not larger than the upper bound for the target
  assert(ros1_msg.@(ros1_field_selection).size() <= @(ros2_fields[-1].type.maximum_size));
@[        end if]@
  // resize ros2 field to match the ros1 field
  ros2_msg.@(ros2_field_selection).resize(ros1_msg.@(ros1_field_selection).size());
@[      else]@
  // statically sized array
  static_assert(
    std::tuple_size<decltype(ros2_msg.@(ros2_field_selection))>::value >= (ros1_msg.@(ros1_field_selection).static_size),
    "destination array not large enough for source array"
  );
@[      end if]@
@[      if not isinstance(ros2_fields[-1].type.value_type, NamespacedType)]@
  // convert primitive array elements
  std::copy(
    ros1_msg.@(ros1_field_selection).begin(),
    ros1_msg.@(ros1_field_selection).end(),
    ros2_msg.@(ros2_field_selection).begin());
@[      else]@
  // copy element wise since the type is different
  {
    auto ros1_it = ros1_msg.@(ros1_field_selection).cbegin();
    auto ros2_it = ros2_msg.@(ros2_field_selection).begin();
    for (
      ;
      ros1_it != ros1_msg.@(ros1_field_selection).cend() &&
      ros2_it != ros2_msg.@(ros2_field_selection).end();
      ++ros1_it, ++ros2_it
    )
    {
      // convert sub message element
@[        if ros2_fields[-1].type.value_type.namespaces[0] == 'builtin_interfaces']@
      ros1_bridge::convert_1_to_2(*ros1_it, *ros2_it);
@[        else]@
      Factory<
        @(ros1_fields[-1].pkg_name)::@(ros1_fields[-1].msg_name),
        @(ros2_fields[-1].type.value_type.namespaces[0])::msg::@(ros2_fields[-1].type.value_type.name)
      >::convert_1_to_2(
        *ros1_it, *ros2_it);
@[        end if]@
    }
  }
@[      end if]@
@[    end if]@
@[  end for]@
}

template<>
void
Factory<
  @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name),
  @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name)
>::convert_2_to_1(
  const @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name) & ros2_msg,
  @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name) & ros1_msg)
{
@[  if not m.fields_2_to_1]@
  (void)ros2_msg;
  (void)ros1_msg;
@[  end if]@
@[  for ros2_fields, ros1_fields in m.fields_2_to_1.items()]@
@{
ros2_field_selection = '.'.join((str(field.name) for field in ros2_fields))
ros1_field_selection = '.'.join((str(field.name) for field in ros1_fields))

if isinstance(ros2_fields[-1].type, NamespacedType):
    namespaces = ros2_fields[-1].type.namespaces
    assert len(namespaces) == 2 and namespaces[1] == 'msg', \
      "messages not using the '<pkg_name>, msg, <type_name>' triplet are not supported"
}
@[    if not isinstance(ros2_fields[-1].type, AbstractNestedType)]@
  // convert non-array field
@[      if not isinstance(ros2_fields[-1].type, NamespacedType)]@
  // convert primitive field
  ros1_msg.@(ros1_field_selection) = ros2_msg.@(ros2_field_selection);
@[      elif ros2_fields[-1].type.namespaces[0] == 'builtin_interfaces']@
  // convert builtin field
  ros1_bridge::convert_2_to_1(ros2_msg.@(ros2_field_selection), ros1_msg.@(ros1_field_selection));
@[      else]@
  // convert sub message field
  Factory<
    @(ros1_fields[-1].pkg_name)::@(ros1_fields[-1].msg_name),
    @(ros2_fields[-1].type.namespaces[0])::msg::@(ros2_fields[-1].type.name)
  >::convert_2_to_1(
    ros2_msg.@(ros2_field_selection), ros1_msg.@(ros1_field_selection));
@[      end if]@
@[    else]@
  // convert array or sequence field
@[      if isinstance(ros2_fields[-1].type, AbstractSequence)]@
  // dynamically sized sequence, ensure destination vector size is large enough
  // resize ros1 field to match the ros2 field
  ros1_msg.@(ros1_field_selection).resize(ros2_msg.@(ros2_field_selection).size());
@[      else]@
  // statically sized array
  static_assert(
    (ros1_msg.@(ros1_field_selection).static_size) >= std::tuple_size<decltype(ros2_msg.@(ros2_field_selection))>::value,
    "destination array not large enough for source array"
  );
@[      end if]@
@[      if not isinstance(ros2_fields[-1].type.value_type, NamespacedType)]@
  // convert primitive array elements
  std::copy(
    ros2_msg.@(ros2_field_selection).begin(),
    ros2_msg.@(ros2_field_selection).end(),
    ros1_msg.@(ros1_field_selection).begin());
@[      else]@
  // copy element wise since the type is different
  {
    auto ros2_it = ros2_msg.@(ros2_field_selection).cbegin();
    auto ros1_it = ros1_msg.@(ros1_field_selection).begin();
    for (
      ;
      ros2_it != ros2_msg.@(ros2_field_selection).cend() &&
      ros1_it != ros1_msg.@(ros1_field_selection).end();
      ++ros2_it, ++ros1_it
    )
    {
      // convert sub message element
@[        if ros2_fields[-1].type.value_type.namespaces[0] == 'builtin_interfaces']@
      ros1_bridge::convert_2_to_1(*ros2_it, *ros1_it);
@[        else]@
      Factory<
        @(ros1_fields[-1].pkg_name)::@(ros1_fields[-1].msg_name),
        @(ros2_fields[-1].type.value_type.namespaces[0])::msg::@(ros2_fields[-1].type.value_type.name)
      >::convert_2_to_1(
        *ros2_it, *ros1_it);
@[        end if]@
    }
  }
@[      end if]@
@[    end if]@
@[  end for]@
}
@[end for]@
@
@[for service in mapped_services]@

@[  for frm, to in [("1", "2"), ("2", "1")]]@
@[    for type in ["Request", "Response"]]@
template <>
void ServiceFactory<
  @(service["ros1_package"])::@(service["ros1_name"]),
  @(service["ros2_package"])::srv::@(service["ros2_name"])
>::translate_@(frm)_to_@(to)(
@[      if frm == "1"]@
  const @(service["ros1_package"])::@(service["ros1_name"])::@(type)& req1,
  @(service["ros2_package"])::srv::@(service["ros2_name"])::@(type)& req2
@[      else]@
  const @(service["ros2_package"])::srv::@(service["ros2_name"])::@(type)& req2,
  @(service["ros1_package"])::@(service["ros1_name"])::@(type)& req1
@[      end if]@
) {
@[      for field in service["fields"][type.lower()]]@
@[        if field["array"]]@
  req@(to).@(field["ros" + to]["name"]).resize(req@(frm).@(field["ros" + frm]["name"]).size());
  auto @(field["ros1"]["name"])1_it = req1.@(field["ros1"]["name"]).begin();
  auto @(field["ros2"]["name"])2_it = req2.@(field["ros2"]["name"]).begin();
  while (
    @(field["ros1"]["name"])1_it != req1.@(field["ros1"]["name"]).end() &&
    @(field["ros2"]["name"])2_it != req2.@(field["ros2"]["name"]).end()
  ) {
    auto & @(field["ros1"]["name"])1 = *(@(field["ros1"]["name"])1_it++);
    auto & @(field["ros2"]["name"])2 = *(@(field["ros2"]["name"])2_it++);
@[      else]@
  auto & @(field["ros1"]["name"])1 = req1.@(field["ros1"]["name"]);
  auto & @(field["ros2"]["name"])2 = req2.@(field["ros2"]["name"]);
@[        end if]@
@[        if field["basic"]]@
  @(field["ros2"]["name"])@(to) = @(field["ros1"]["name"])@(frm);
@[        else]@
  Factory<@(field["ros1"]["cpptype"]),@(field["ros2"]["cpptype"])>::convert_@(frm)_to_@(to)(@
@(field["ros2"]["name"])@(frm), @(field["ros1"]["name"])@(to));
@[        end if]@
@[        if field["array"]]@
  }
@[        end if]@
@[      end for]@
}

@[    end for]@
@[  end for]@
@[end for]@
}  // namespace ros1_bridge

// generated from ros1_bridge/resource/interface_factories.cpp.em

@###############################################
@#
@# Factory template specializations for a
@# specific message type
@#
@# EmPy template for generating
@# <pkgname>__<type>__<interfacename>__factories.cpp
@#
@###############################################
@# Start of Template
@#
@# Context:
@#  - ros2_package_name (str)
@#    The ROS 2 package name of this file
@#  - mappings (list of ros1_bridge.Mapping)
@#    Mapping between messages as well as their fields
@###############################################
@
@{
from ros1_bridge import camel_case_to_lower_case_underscore
from rosidl_parser.definition import AbstractNestedType
from rosidl_parser.definition import AbstractSequence
from rosidl_parser.definition import BoundedSequence
from rosidl_parser.definition import NamespacedType
}@
#include "@(ros2_package_name)_factories.hpp"

#include <algorithm>

#include "rclcpp/rclcpp.hpp"

// include builtin interfaces
#include <ros1_bridge/convert_builtin_interfaces.hpp>

// include ROS 1 services
@[for service in mapped_services]@
#include <@(service["ros1_package"])/@(service["ros1_name"]).h>
@[end for]@

// include ROS 2 services
@[for service in mapped_services]@
#include <@(service["ros2_package"])/srv/@(camel_case_to_lower_case_underscore(service["ros2_name"])).hpp>
@[end for]@

namespace ros1_bridge
{

std::shared_ptr<FactoryInterface>
get_factory_@(ros2_package_name)__@(interface_type)__@(interface.message_name)(const std::string & ros1_type_name, const std::string & ros2_type_name)
{
@[if not mapped_msgs]@
  (void)ros1_type_name;
  (void)ros2_type_name;
@[else]@
  // mapping from string to specialized template
@[end if]@
@[for m in mapped_msgs]@
  if (
    (ros1_type_name == "@(m.ros1_msg.package_name)/@(m.ros1_msg.message_name)" ||
     ros1_type_name == "") &&
    ros2_type_name == "@(m.ros2_msg.package_name)/msg/@(m.ros2_msg.message_name)")
  {
    return std::make_shared<
      Factory<
        @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name),
        @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name)
      >
    >("@(m.ros1_msg.package_name)/@(m.ros1_msg.message_name)", ros2_type_name);
  }
@[end for]@
  return std::shared_ptr<FactoryInterface>();
}

std::unique_ptr<ServiceFactoryInterface>
get_service_factory_@(ros2_package_name)__@(interface_type)__@(interface.message_name)(const std::string & ros_id, const std::string & package_name, const std::string & service_name)
{
@[if not mapped_services]@
  (void)ros_id;
  (void)package_name;
  (void)service_name;
@[end if]@
@[for service in mapped_services]@
  if (
    (
      ros_id == "ros1" &&
      package_name == "@(service["ros1_package"])" &&
      service_name == "@(service["ros1_name"])"
    ) || (
      ros_id == "ros2" &&
      package_name == "@(service["ros2_package"])" &&
      service_name == "srv/@(service["ros2_name"])"
    )
  ) {
    return std::unique_ptr<ServiceFactoryInterface>(new ServiceFactory<
      @(service["ros1_package"])::@(service["ros1_name"]),
      @(service["ros2_package"])::srv::@(service["ros2_name"])
    >);
  }
@[end for]@
  return nullptr;
}
@
// conversion functions for available interfaces
@[for m in mapped_msgs]@

template<>
void
Factory<
  @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name),
  @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name)
>::convert_1_to_2(
  const @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name) & ros1_msg,
  @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name) & ros2_msg)
{
@[  if not m.fields_1_to_2]@
  (void)ros1_msg;
  (void)ros2_msg;
@[  end if]@
@[  for ros1_fields, ros2_fields in m.fields_1_to_2.items()]@
@{
ros1_field_selection = '.'.join((str(field.name) for field in ros1_fields))
ros2_field_selection = '.'.join((str(field.name) for field in ros2_fields))

if isinstance(ros2_fields[-1].type, NamespacedType):
    namespaces = ros2_fields[-1].type.namespaces
    assert len(namespaces) == 2 and namespaces[1] == 'msg', \
      "messages not using the '<pkg_name>, msg, <type_name>' triplet are not supported"
}
@[    if not isinstance(ros2_fields[-1].type, AbstractNestedType)]@
  // convert non-array field
@[      if not isinstance(ros2_fields[-1].type, NamespacedType)]@
  // convert primitive field
  ros2_msg.@(ros2_field_selection) = ros1_msg.@(ros1_field_selection);
@[      elif ros2_fields[-1].type.namespaces[0] == 'builtin_interfaces']@
  // convert builtin field
  ros1_bridge::convert_1_to_2(ros1_msg.@(ros1_field_selection), ros2_msg.@(ros2_field_selection));
@[      else]@
  // convert sub message field
  Factory<
    @(ros1_fields[-1].pkg_name)::@(ros1_fields[-1].msg_name),
    @(ros2_fields[-1].type.namespaces[0])::msg::@(ros2_fields[-1].type.name)
  >::convert_1_to_2(
    ros1_msg.@(ros1_field_selection), ros2_msg.@(ros2_field_selection));
@[      end if]@
@[    else]@
  // convert array or sequence field
@[      if isinstance(ros2_fields[-1].type, AbstractSequence)]@
  // dynamically sized sequence, ensure destination sequence/vector size is large enough
@[        if isinstance(ros2_fields[-1].type, BoundedSequence)]@
  // bounded size sequence, check that the ros 1 vector size is not larger than the upper bound for the target
  assert(ros1_msg.@(ros1_field_selection).size() <= @(ros2_fields[-1].type.maximum_size));
@[        end if]@
  // resize ros2 field to match the ros1 field
  ros2_msg.@(ros2_field_selection).resize(ros1_msg.@(ros1_field_selection).size());
@[      else]@
  // statically sized array
  static_assert(
    (ros2_msg.@(ros2_field_selection).size()) >= (ros1_msg.@(ros1_field_selection).size()),
    "destination array not large enough for source array"
  );
@[      end if]@
@[      if not isinstance(ros2_fields[-1].type.value_type, NamespacedType)]@
  // convert primitive array elements
  std::copy(
    ros1_msg.@(ros1_field_selection).begin(),
    ros1_msg.@(ros1_field_selection).end(),
    ros2_msg.@(ros2_field_selection).begin());
@[      else]@
  // copy element wise since the type is different
  {
    auto ros1_it = ros1_msg.@(ros1_field_selection).cbegin();
    auto ros2_it = ros2_msg.@(ros2_field_selection).begin();
    for (
      ;
      ros1_it != ros1_msg.@(ros1_field_selection).cend() &&
      ros2_it != ros2_msg.@(ros2_field_selection).end();
      ++ros1_it, ++ros2_it
    )
    {
      // convert sub message element
@[        if ros2_fields[-1].type.value_type.namespaces[0] == 'builtin_interfaces']@
      ros1_bridge::convert_1_to_2(*ros1_it, *ros2_it);
@[        else]@
      Factory<
        @(ros1_fields[-1].pkg_name)::@(ros1_fields[-1].msg_name),
        @(ros2_fields[-1].type.value_type.namespaces[0])::msg::@(ros2_fields[-1].type.value_type.name)
      >::convert_1_to_2(
        *ros1_it, *ros2_it);
@[        end if]@
    }
  }
@[      end if]@
@[    end if]@
@[  end for]@
}

template<>
void
Factory<
  @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name),
  @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name)
>::convert_2_to_1(
  const @(m.ros2_msg.package_name)::msg::@(m.ros2_msg.message_name) & ros2_msg,
  @(m.ros1_msg.package_name)::@(m.ros1_msg.message_name) & ros1_msg)
{
@[  if not m.fields_2_to_1]@
  (void)ros2_msg;
  (void)ros1_msg;
@[  end if]@
@[  for ros2_fields, ros1_fields in m.fields_2_to_1.items()]@
@{
ros2_field_selection = '.'.join((str(field.name) for field in ros2_fields))
ros1_field_selection = '.'.join((str(field.name) for field in ros1_fields))

if isinstance(ros2_fields[-1].type, NamespacedType):
    namespaces = ros2_fields[-1].type.namespaces
    assert len(namespaces) == 2 and namespaces[1] == 'msg', \
      "messages not using the '<pkg_name>, msg, <type_name>' triplet are not supported"
}
@[    if not isinstance(ros2_fields[-1].type, AbstractNestedType)]@
  // convert non-array field
@[      if not isinstance(ros2_fields[-1].type, NamespacedType)]@
  // convert primitive field
  ros1_msg.@(ros1_field_selection) = ros2_msg.@(ros2_field_selection);
@[      elif ros2_fields[-1].type.namespaces[0] == 'builtin_interfaces']@
  // convert builtin field
  ros1_bridge::convert_2_to_1(ros2_msg.@(ros2_field_selection), ros1_msg.@(ros1_field_selection));
@[      else]@
  // convert sub message field
  Factory<
    @(ros1_fields[-1].pkg_name)::@(ros1_fields[-1].msg_name),
    @(ros2_fields[-1].type.namespaces[0])::msg::@(ros2_fields[-1].type.name)
  >::convert_2_to_1(
    ros2_msg.@(ros2_field_selection), ros1_msg.@(ros1_field_selection));
@[      end if]@
@[    else]@
  // convert array or sequence field
@[      if isinstance(ros2_fields[-1].type, AbstractSequence)]@
  // dynamically sized sequence, ensure destination vector size is large enough
  // resize ros1 field to match the ros2 field
  ros1_msg.@(ros1_field_selection).resize(ros2_msg.@(ros2_field_selection).size());
@[      else]@
  // statically sized array
  static_assert(
    (ros1_msg.@(ros1_field_selection).size()) >= (ros2_msg.@(ros2_field_selection).size()),
    "destination array not large enough for source array"
  );
@[      end if]@
@[      if not isinstance(ros2_fields[-1].type.value_type, NamespacedType)]@
  // convert primitive array elements
  std::copy(
    ros2_msg.@(ros2_field_selection).begin(),
    ros2_msg.@(ros2_field_selection).end(),
    ros1_msg.@(ros1_field_selection).begin());
@[      else]@
  // copy element wise since the type is different
  {
    auto ros2_it = ros2_msg.@(ros2_field_selection).cbegin();
    auto ros1_it = ros1_msg.@(ros1_field_selection).begin();
    for (
      ;
      ros2_it != ros2_msg.@(ros2_field_selection).cend() &&
      ros1_it != ros1_msg.@(ros1_field_selection).end();
      ++ros2_it, ++ros1_it
    )
    {
      // convert sub message element
@[        if ros2_fields[-1].type.value_type.namespaces[0] == 'builtin_interfaces']@
      ros1_bridge::convert_2_to_1(*ros2_it, *ros1_it);
@[        else]@
      Factory<
        @(ros1_fields[-1].pkg_name)::@(ros1_fields[-1].msg_name),
        @(ros2_fields[-1].type.value_type.namespaces[0])::msg::@(ros2_fields[-1].type.value_type.name)
      >::convert_2_to_1(
        *ros2_it, *ros1_it);
@[        end if]@
    }
  }
@[      end if]@
@[    end if]@
@[  end for]@
}
@[end for]@
@
@[for service in mapped_services]@

@[  for frm, to in [("1", "2"), ("2", "1")]]@
@[    for type in ["Request", "Response"]]@
template <>
void ServiceFactory<
  @(service["ros1_package"])::@(service["ros1_name"]),
  @(service["ros2_package"])::srv::@(service["ros2_name"])
>::translate_@(frm)_to_@(to)(
@[      if frm == "1"]@
  const @(service["ros1_package"])::@(service["ros1_name"])::@(type)& req1,
  @(service["ros2_package"])::srv::@(service["ros2_name"])::@(type)& req2
@[      else]@
  const @(service["ros2_package"])::srv::@(service["ros2_name"])::@(type)& req2,
  @(service["ros1_package"])::@(service["ros1_name"])::@(type)& req1
@[      end if]@
) {
@[      for field in service["fields"][type.lower()]]@
@[        if field["array"]]@
  req@(to).@(field["ros" + to]["name"]).resize(req@(frm).@(field["ros" + frm]["name"]).size());
  auto @(field["ros1"]["name"])1_it = req1.@(field["ros1"]["name"]).begin();
  auto @(field["ros2"]["name"])2_it = req2.@(field["ros2"]["name"]).begin();
  while (
    @(field["ros1"]["name"])1_it != req1.@(field["ros1"]["name"]).end() &&
    @(field["ros2"]["name"])2_it != req2.@(field["ros2"]["name"]).end()
  ) {
    auto & @(field["ros1"]["name"])1 = *(@(field["ros1"]["name"])1_it++);
    auto & @(field["ros2"]["name"])2 = *(@(field["ros2"]["name"])2_it++);
@[      else]@
  auto & @(field["ros1"]["name"])1 = req1.@(field["ros1"]["name"]);
  auto & @(field["ros2"]["name"])2 = req2.@(field["ros2"]["name"]);
@[        end if]@
@[        if field["basic"]]@
  @(field["ros2"]["name"])@(to) = @(field["ros1"]["name"])@(frm);
@[        else]@
  Factory<@(field["ros1"]["cpptype"]),@(field["ros2"]["cpptype"])>::convert_@(frm)_to_@(to)(@
@(field["ros2"]["name"])@(frm), @(field["ros1"]["name"])@(to));
@[        end if]@
@[        if field["array"]]@
  }
@[        end if]@
@[      end for]@
}

@[    end for]@
@[  end for]@
@[end for]@
}  // namespace ros1_bridge


fix unused variable warning in release mode (#241)

// generated from rosidl_generator_py/resource/_msg_support.c.em
// generated code does not contain a copyright notice

@#######################################################################
@# EmPy template for generating _<msg>_s.c files
@#
@# Context:
@#  - module_name
@#  - spec (rosidl_parser.MessageSpecification)
@#    Parsed specification of the .msg file
@#  - convert_camel_case_to_lower_case_underscore (function)
@#  - primitive_msg_type_to_c (function)
@#######################################################################
@
#include <Python.h>

#include <@(spec.base_type.pkg_name)/@(subfolder)/@(module_name)__struct.h>
#include <@(spec.base_type.pkg_name)/@(subfolder)/@(module_name)__functions.h>

@{
have_not_included_primitive_arrays = True
have_not_included_string = True
nested_array_dict = {}
}@
@[for field in spec.fields]@
@[  if field.type.is_array and have_not_included_primitive_arrays]@
@{have_not_included_primitive_arrays = False}@
#include <rosidl_generator_c/primitives_array.h>
#include <rosidl_generator_c/primitives_array_functions.h>

@[  end if]@
@[  if field.type.type == 'string' and have_not_included_string]@
@{have_not_included_string = False}@
#include <rosidl_generator_c/string.h>
#include <rosidl_generator_c/string_functions.h>

@[  end if]@
@{
if not field.type.is_primitive_type() and field.type.is_array:
    if field.type.type not in nested_array_dict:
        nested_array_dict[field.type.type] = field.type.pkg_name
}@
@[end for]@
@[if nested_array_dict != {}]@
// Nested array functions includes
@[  for key in nested_array_dict]@
#include <@(nested_array_dict[key])/msg/@convert_camel_case_to_lower_case_underscore(key)__functions.h>
@[  end for]@
// end nested array functions include
@[end if]@
@{
msg_typename = '%s__%s__%s' % (spec.base_type.pkg_name, subfolder, spec.base_type.type)
}@

void * @(spec.base_type.pkg_name)_@(module_name)__convert_from_py(PyObject * _pymsg)
{
@{
full_classname = '%s.%s._%s.%s' % (spec.base_type.pkg_name, subfolder, module_name, spec.base_type.type)
}@
  // check that the passed message is of the expected Python class
  {
    char full_classname_dest[@(len(full_classname) + 1)];
    {
      char * class_name = NULL;
      char * module_name = NULL;
      {
        PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
        if (class_attr) {
          PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
          if (name_attr) {
            class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
            Py_DECREF(name_attr);
          }
          PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
          if (module_attr) {
            module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
            Py_DECREF(module_attr);
          }
          Py_DECREF(class_attr);
        }
      }
      if (!class_name || !module_name) {
        return NULL;
      }
      snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
    }
    assert(strncmp(
        "@(full_classname)",
        full_classname_dest, @(len(full_classname))) == 0);
  }
  @(msg_typename) * ros_message = @(msg_typename)__create();
@[if not spec.fields]@
  (void)ros_message;
@[end if]@
@[for field in spec.fields]@
  {  // @(field.name)
    PyObject * field = PyObject_GetAttrString(_pymsg, "@(field.name)");
    if (!field) {
      return NULL;
    }
@[  if not field.type.is_primitive_type()]@
@{
nested_type = '%s__%s__%s' % (field.type.pkg_name, 'msg', field.type.type)
}@
    typedef PyObject *(* convert_from_py_signature)(void *);
    convert_from_py_signature convert_from_py = NULL;
    // get conversion function
    {
      PyObject * msg_module = PyImport_ImportModule("@(field.type.pkg_name).msg._@convert_camel_case_to_lower_case_underscore(field.type.type)");
      if (!msg_module) {
        Py_DECREF(field);
        return NULL;
      }
      PyObject * msg_class = PyObject_GetAttrString(msg_module, "@(field.type.type)");
      Py_DECREF(msg_module);
      if (!msg_class) {
        Py_DECREF(field);
        return NULL;
      }
      PyObject * msg_metaclass = PyObject_GetAttrString(msg_class, "__class__");
      Py_DECREF(msg_class);
      if (!msg_metaclass) {
        Py_DECREF(field);
        return NULL;
      }
      PyObject * convert_from_py_ = PyObject_GetAttrString(msg_metaclass, "_CONVERT_FROM_PY");
      Py_DECREF(msg_metaclass);
      if (!convert_from_py_) {
        Py_DECREF(field);
        return NULL;
      }
      convert_from_py = (convert_from_py_signature)PyCapsule_GetPointer(convert_from_py_, NULL);
      Py_DECREF(convert_from_py_);
      if (!convert_from_py) {
        Py_DECREF(field);
        return NULL;
      }
    }
@[    if field.type.is_array]@
    PyObject * seq_field = PySequence_Fast(field, "expected a sequence in '@(field.name)'");
    if (!seq_field) {
      Py_DECREF(field);
      return NULL;
    }
@[      if field.type.array_size is None or field.type.is_upper_bound]@
    Py_ssize_t size = PySequence_Size(field);
    if (-1 == size) {
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
    if (!@(nested_type)__Array__init(&(ros_message->@(field.name)), size)) {
      PyErr_SetString(PyExc_RuntimeError, "unable to create @(nested_type)__Array ros_message");
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
    @(nested_type) * dest = ros_message->@(field.name).data;
@[      else]@
    Py_ssize_t size = @(field.type.array_size);
    @(nested_type) * dest = ros_message->@(field.name);
@[      end if]@
    for (Py_ssize_t i = 0; i < size; ++i) {
      @(nested_type) * item = (@(nested_type) *) convert_from_py(
        PySequence_Fast_GET_ITEM(seq_field, i));
      if (!item) {
        Py_DECREF(seq_field);
        Py_DECREF(field);
        return NULL;
      }
      memcpy(&dest[i], item, sizeof(@(nested_type)));
    }
    Py_DECREF(seq_field);
@[    else]@
    @(nested_type) * tmp = (@(nested_type) *) convert_from_py(field);
    if (!tmp) {
      return NULL;
    }
    ros_message->@(field.name) = *tmp;
@[    end if]@
@[  elif field.type.is_array]@
    PyObject * seq_field = PySequence_Fast(field, "expected a sequence in '@(field.name)'");
    if (!seq_field) {
      Py_DECREF(field);
      return NULL;
    }
@[    if field.type.array_size is None or field.type.is_upper_bound]@
    Py_ssize_t size = PySequence_Size(field);
    if (-1 == size) {
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
@[      if field.type.type == 'string']@
    if (!rosidl_generator_c__String__Array__init(&(ros_message->@(field.name)), size)) {
      PyErr_SetString(PyExc_RuntimeError, "unable to create String__Array ros_message");
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
@[      else]@
    if (!rosidl_generator_c__@(field.type.type)__Array__init(&(ros_message->@(field.name)), size)) {
      PyErr_SetString(PyExc_RuntimeError, "unable to create @(field.type.type)__Array ros_message");
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
@[      end if]@
    @primitive_msg_type_to_c(field.type.type) * dest = ros_message->@(field.name).data;
@[    else]@
    Py_ssize_t size = @(field.type.array_size);
    @primitive_msg_type_to_c(field.type.type) * dest = ros_message->@(field.name);
@[    end if]@
    for (Py_ssize_t i = 0; i < size; ++i) {
      PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
      if (!item) {
        Py_DECREF(seq_field);
        Py_DECREF(field);
        return NULL;
      }
@[    if field.type.type == 'char']@
      assert(PyUnicode_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = PyUnicode_1BYTE_DATA(item)[0];
@[    elif field.type.type == 'byte']@
      assert(PyBytes_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = PyBytes_AS_STRING(item)[0];
@[    elif field.type.type == 'string']@
      assert(PyUnicode_Check(item));
      rosidl_generator_c__String__assign(&dest[i], (char *)PyUnicode_1BYTE_DATA(item));
@[    elif field.type.type == 'bool']@
      assert(PyBool_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = (item == Py_True);
@[    elif field.type.type in ['float32', 'float64']]@
      assert(PyFloat_Check(item));
@[      if field.type.type == 'float32']@
      @primitive_msg_type_to_c(field.type.type) tmp = (float)PyFloat_AS_DOUBLE(item);
@[      else]@
      @primitive_msg_type_to_c(field.type.type) tmp = PyFloat_AS_DOUBLE(item);
@[      end if]@
@[    elif field.type.type in [
        'int8',
        'int16',
        'int32',
    ]]@
      assert(PyLong_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = (@(primitive_msg_type_to_c(field.type.type)))PyLong_AsLong(item);
@[    elif field.type.type in [
        'uint8',
        'uint16',
        'uint32',
    ]]@
      assert(PyLong_Check(item));
@[      if field.type.type == 'uint32']@
      @primitive_msg_type_to_c(field.type.type) tmp = PyLong_AsUnsignedLong(item);
@[      else]@
      @primitive_msg_type_to_c(field.type.type) tmp = (@(primitive_msg_type_to_c(field.type.type)))PyLong_AsUnsignedLong(item);
@[      end if]
@[    elif field.type.type == 'int64']@
      assert(PyLong_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = PyLong_AsLongLong(item);
@[    elif field.type.type == 'uint64']@
      assert(PyLong_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = PyLong_AsUnsignedLongLong(item);
@[    end if]@
@[    if field.type.type != 'string']@
      memcpy(&dest[i], &tmp, sizeof(@primitive_msg_type_to_c(field.type.type)));
@[    end if]@
    }
    Py_DECREF(seq_field);
@[  elif field.type.type == 'char']@
    assert(PyUnicode_Check(field));
    ros_message->@(field.name) = PyUnicode_1BYTE_DATA(field)[0];
@[  elif field.type.type == 'byte']@
    assert(PyBytes_Check(field));
    ros_message->@(field.name) = PyBytes_AS_STRING(field)[0];
@[  elif field.type.type == 'string']@
    assert(PyUnicode_Check(field));
    rosidl_generator_c__String__assign(&ros_message->@(field.name), (char *)PyUnicode_1BYTE_DATA(field));
@[  elif field.type.type == 'bool']@
    assert(PyBool_Check(field));
    ros_message->@(field.name) = (Py_True == field);
@[  elif field.type.type in ['float32', 'float64']]@
    assert(PyFloat_Check(field));
@[    if field.type.type == 'float32']@
    ros_message->@(field.name) = (float)PyFloat_AS_DOUBLE(field);
@[    else]@
    ros_message->@(field.name) = PyFloat_AS_DOUBLE(field);
@[    end if]@
@[  elif field.type.type in [
        'int8',
        'int16',
        'int32',
    ]]@
    assert(PyLong_Check(field));
    ros_message->@(field.name) = (@(primitive_msg_type_to_c(field.type.type)))PyLong_AsLong(field);
@[  elif field.type.type in [
        'uint8',
        'uint16',
        'uint32',
    ]]@
    assert(PyLong_Check(field));
@[    if field.type.type == 'uint32']@
    ros_message->@(field.name) = PyLong_AsUnsignedLong(field);
@[    else]@
    ros_message->@(field.name) = (@(primitive_msg_type_to_c(field.type.type)))PyLong_AsUnsignedLong(field);
@[    end if]@
@[  elif field.type.type == 'int64']@
    assert(PyLong_Check(field));
    ros_message->@(field.name) = PyLong_AsLongLong(field);
@[  elif field.type.type == 'uint64']@
    assert(PyLong_Check(field));
    ros_message->@(field.name) = PyLong_AsUnsignedLongLong(field);
@[  else]@
    assert(false);
@[  end if]@
    Py_DECREF(field);
  }
@[end for]@

  return ros_message;
}

void @(spec.base_type.pkg_name)_@(module_name)__destroy_ros_message(void * raw_ros_message)
{
  @(msg_typename) * ros_message = (@(msg_typename) *)raw_ros_message;
  @(msg_typename)__destroy(ros_message);
}

PyObject * @(spec.base_type.pkg_name)_@(module_name)__convert_to_py(void * raw_ros_message)
{
  /* NOTE(esteve): Call constructor of @(spec.base_type.type) */
  PyObject * _pymessage = NULL;
  {
    PyObject * pymessage_module = PyImport_ImportModule("@(spec.base_type.pkg_name).@(subfolder)._@(module_name)");
    assert(pymessage_module);
    PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "@(spec.base_type.type)");
    assert(pymessage_class);
    Py_DECREF(pymessage_module);
    _pymessage = PyObject_CallObject(pymessage_class, NULL);
    Py_DECREF(pymessage_class);
    if (!_pymessage) {
      return NULL;
    }
  }
  @(msg_typename) * ros_message = (@(msg_typename) *)raw_ros_message;
@[if not spec.fields]@
  (void)ros_message;
@[end if]@
@[for field in spec.fields]@
  {  // @(field.name)
    PyObject * field = NULL;
@[  if not field.type.is_primitive_type()]@
@{
nested_type = '%s__%s__%s' % (field.type.pkg_name, 'msg', field.type.type)
}@
    typedef PyObject *(* convert_to_py_signature)(void *);
    convert_to_py_signature convert_to_py = NULL;
    // get conversion function
    {
      PyObject * msg_module = PyImport_ImportModule("@(field.type.pkg_name).msg._@convert_camel_case_to_lower_case_underscore(field.type.type)");
      if (!msg_module) {
        return NULL;
      }
      PyObject * msg_class = PyObject_GetAttrString(msg_module, "@(field.type.type)");
      Py_DECREF(msg_module);
      if (!msg_class) {
        return NULL;
      }
      PyObject * msg_metaclass = PyObject_GetAttrString(msg_class, "__class__");
      Py_DECREF(msg_class);
      if (!msg_metaclass) {
        return NULL;
      }
      PyObject * convert_to_py_ = PyObject_GetAttrString(msg_metaclass, "_CONVERT_TO_PY");
      Py_DECREF(msg_metaclass);
      if (!convert_to_py_) {
        return NULL;
      }
      convert_to_py = (convert_to_py_signature)PyCapsule_GetPointer(convert_to_py_, NULL);
      Py_DECREF(convert_to_py_);
      if (!convert_to_py) {
        return NULL;
      }
    }
@[    if field.type.is_array]@
@[      if field.type.array_size is None or field.type.is_upper_bound]@
    size_t size = ros_message->@(field.name).size;
@[      else]@
    size_t size = @(field.type.array_size);
@[      end if]@
    field = PyList_New(size);
    if (!field) {
      return NULL;
    }
    @(nested_type) * item;
    for (size_t i = 0; i < size; ++i) {
@[      if field.type.array_size is None or field.type.is_upper_bound]@
      item = &(ros_message->@(field.name).data[i]);
@[      else]@
      item = &(ros_message->@(field.name)[i]);
@[      end if]@
      PyObject * pyitem = convert_to_py(item);
      if (!pyitem) {
        Py_DECREF(field);
        return NULL;
      }
      int rc = PyList_SetItem(field, i, pyitem);
      (void)rc;
      assert(rc == 0);
    }
    assert(PySequence_Check(field));
@[    else]@
    field = convert_to_py(&ros_message->@(field.name));
    if (!field) {
      return NULL;
    }
@[    end if]@
@[  elif field.type.is_array]@
@[    if field.type.array_size is None or field.type.is_upper_bound]@
    size_t size = ros_message->@(field.name).size;
    @primitive_msg_type_to_c(field.type.type) * src = ros_message->@(field.name).data;
@[    else]@
    size_t size = @(field.type.array_size);
    @primitive_msg_type_to_c(field.type.type) * src = ros_message->@(field.name);
@[    end if]@
    field = PyList_New(size);
    if (!field) {
      return NULL;
    }
    for (size_t i = 0; i < size; ++i) {
@[    if field.type.type == 'char']@
      int rc = PyList_SetItem(field, i, Py_BuildValue("C", src[i]));
      (void)rc;
      assert(rc == 0);
@[    elif field.type.type == 'byte']@
      int rc = PyList_SetItem(field, i, PyBytes_FromStringAndSize((const char *)&src[i], 1));
      (void)rc;
      assert(rc == 0);
@[    elif field.type.type == 'string']@
      int rc = PyList_SetItem(field, i, PyUnicode_FromString(src[i].data));
      (void)rc;
      assert(rc == 0);
@[    elif field.type.type == 'bool']@
@# using PyBool_FromLong because PyList_SetItem will steal ownership of the passed item
      int rc = PyList_SetItem(field, i, PyBool_FromLong(src[i] ? 1 : 0));
      (void)rc;
      assert(rc == 0);
@[    elif field.type.type in ['float32', 'float64']]@
      int rc = PyList_SetItem(field, i, PyFloat_FromDouble(src[i]));
      (void)rc;
      assert(rc == 0);
@[    elif field.type.type in [
        'int8',
        'int16',
        'int32',
    ]]@
      int rc = PyList_SetItem(field, i, PyLong_FromLong(src[i]));
      (void)rc;
      assert(rc == 0);
@[    elif field.type.type in [
        'uint8',
        'uint16',
        'uint32',
    ]]@
      int rc = PyList_SetItem(field, i, PyLong_FromUnsignedLong(src[i]));
      (void)rc;
      assert(rc == 0);
@[    elif field.type.type == 'int64']@
      int rc = PyList_SetItem(field, i, PyLong_FromLongLong(src[i]));
      (void)rc;
      assert(rc == 0);
@[    elif field.type.type == 'uint64']@
      int rc = PyList_SetItem(field, i, PyLong_FromUnsignedLongLong(src[i]));
      (void)rc;
      assert(rc == 0);
@[    end if]@
    }
    assert(PySequence_Check(field));
@[  elif field.type.type == 'char']@
    field = Py_BuildValue("C", ros_message->@(field.name));
    if (!field) {
      return NULL;
    }
@[  elif field.type.type == 'byte']@
    field = PyBytes_FromStringAndSize((const char *)&ros_message->@(field.name), 1);
    if (!field) {
      return NULL;
    }
@[  elif field.type.type == 'string']@
    field = PyUnicode_FromString(ros_message->@(field.name).data);
@[  elif field.type.type == 'bool']@
@# using PyBool_FromLong allows treating the variable uniformly by calling Py_DECREF on it later
    field = PyBool_FromLong(ros_message->@(field.name) ? 1 : 0);
@[  elif field.type.type in ['float32', 'float64']]@
    field = PyFloat_FromDouble(ros_message->@(field.name));
@[  elif field.type.type in [
        'int8',
        'int16',
        'int32',
    ]]@
    field = PyLong_FromLong(ros_message->@(field.name));
@[  elif field.type.type in [
        'uint8',
        'uint16',
        'uint32',
    ]]@
    field = PyLong_FromUnsignedLong(ros_message->@(field.name));
@[  elif field.type.type == 'int64']@
    field = PyLong_FromLongLong(ros_message->@(field.name));
@[  elif field.type.type == 'uint64']@
    field = PyLong_FromUnsignedLongLong(ros_message->@(field.name));
@[  else]@
    assert(false);
@[  end if]@
    {
      int rc = PyObject_SetAttrString(_pymessage, "@(field.name)", field);
      Py_DECREF(field);
      if (rc) {
        return NULL;
      }
    }
  }
@[end for]@

  // ownership of _pymessage is transferred to the caller
  return _pymessage;
}

// generated from rosidl_generator_py/resource/_msg_support.c.em
// generated code does not contain a copyright notice

@#######################################################################
@# EmPy template for generating _<msg>_s.c files
@#
@# Context:
@#  - module_name
@#  - spec (rosidl_parser.MessageSpecification)
@#    Parsed specification of the .msg file
@#  - convert_camel_case_to_lower_case_underscore (function)
@#  - primitive_msg_type_to_c (function)
@#######################################################################
@
#include <Python.h>

#include <@(spec.base_type.pkg_name)/@(subfolder)/@(module_name)__struct.h>
#include <@(spec.base_type.pkg_name)/@(subfolder)/@(module_name)__functions.h>

@{
have_not_included_primitive_arrays = True
have_not_included_string = True
nested_array_dict = {}
}@
@[for field in spec.fields]@
@[  if field.type.is_array and have_not_included_primitive_arrays]@
@{have_not_included_primitive_arrays = False}@
#include <rosidl_generator_c/primitives_array.h>
#include <rosidl_generator_c/primitives_array_functions.h>

@[  end if]@
@[  if field.type.type == 'string' and have_not_included_string]@
@{have_not_included_string = False}@
#include <rosidl_generator_c/string.h>
#include <rosidl_generator_c/string_functions.h>

@[  end if]@
@{
if not field.type.is_primitive_type() and field.type.is_array:
    if field.type.type not in nested_array_dict:
        nested_array_dict[field.type.type] = field.type.pkg_name
}@
@[end for]@
@[if nested_array_dict != {}]@
// Nested array functions includes
@[  for key in nested_array_dict]@
#include <@(nested_array_dict[key])/msg/@convert_camel_case_to_lower_case_underscore(key)__functions.h>
@[  end for]@
// end nested array functions include
@[end if]@
@{
msg_typename = '%s__%s__%s' % (spec.base_type.pkg_name, subfolder, spec.base_type.type)
}@

void * @(spec.base_type.pkg_name)_@(module_name)__convert_from_py(PyObject * _pymsg)
{
@{
full_classname = '%s.%s._%s.%s' % (spec.base_type.pkg_name, subfolder, module_name, spec.base_type.type)
}@
  // check that the passed message is of the expected Python class
  {
    char full_classname_dest[@(len(full_classname) + 1)];
    {
      char * class_name = NULL;
      char * module_name = NULL;
      {
        PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
        if (class_attr) {
          PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
          if (name_attr) {
            class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
            Py_DECREF(name_attr);
          }
          PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
          if (module_attr) {
            module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
            Py_DECREF(module_attr);
          }
          Py_DECREF(class_attr);
        }
      }
      if (!class_name || !module_name) {
        return NULL;
      }
      snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
    }
    assert(strncmp(
        "@(full_classname)",
        full_classname_dest, @(len(full_classname))) == 0);
  }
  @(msg_typename) * ros_message = @(msg_typename)__create();
@[if not spec.fields]@
  (void)ros_message;
@[end if]@
@[for field in spec.fields]@
  {  // @(field.name)
    PyObject * field = PyObject_GetAttrString(_pymsg, "@(field.name)");
    if (!field) {
      return NULL;
    }
@[  if not field.type.is_primitive_type()]@
@{
nested_type = '%s__%s__%s' % (field.type.pkg_name, 'msg', field.type.type)
}@
    typedef PyObject *(* convert_from_py_signature)(void *);
    convert_from_py_signature convert_from_py = NULL;
    // get conversion function
    {
      PyObject * msg_module = PyImport_ImportModule("@(field.type.pkg_name).msg._@convert_camel_case_to_lower_case_underscore(field.type.type)");
      if (!msg_module) {
        Py_DECREF(field);
        return NULL;
      }
      PyObject * msg_class = PyObject_GetAttrString(msg_module, "@(field.type.type)");
      Py_DECREF(msg_module);
      if (!msg_class) {
        Py_DECREF(field);
        return NULL;
      }
      PyObject * msg_metaclass = PyObject_GetAttrString(msg_class, "__class__");
      Py_DECREF(msg_class);
      if (!msg_metaclass) {
        Py_DECREF(field);
        return NULL;
      }
      PyObject * convert_from_py_ = PyObject_GetAttrString(msg_metaclass, "_CONVERT_FROM_PY");
      Py_DECREF(msg_metaclass);
      if (!convert_from_py_) {
        Py_DECREF(field);
        return NULL;
      }
      convert_from_py = (convert_from_py_signature)PyCapsule_GetPointer(convert_from_py_, NULL);
      Py_DECREF(convert_from_py_);
      if (!convert_from_py) {
        Py_DECREF(field);
        return NULL;
      }
    }
@[    if field.type.is_array]@
    PyObject * seq_field = PySequence_Fast(field, "expected a sequence in '@(field.name)'");
    if (!seq_field) {
      Py_DECREF(field);
      return NULL;
    }
@[      if field.type.array_size is None or field.type.is_upper_bound]@
    Py_ssize_t size = PySequence_Size(field);
    if (-1 == size) {
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
    if (!@(nested_type)__Array__init(&(ros_message->@(field.name)), size)) {
      PyErr_SetString(PyExc_RuntimeError, "unable to create @(nested_type)__Array ros_message");
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
    @(nested_type) * dest = ros_message->@(field.name).data;
@[      else]@
    Py_ssize_t size = @(field.type.array_size);
    @(nested_type) * dest = ros_message->@(field.name);
@[      end if]@
    for (Py_ssize_t i = 0; i < size; ++i) {
      @(nested_type) * item = (@(nested_type) *) convert_from_py(
        PySequence_Fast_GET_ITEM(seq_field, i));
      if (!item) {
        Py_DECREF(seq_field);
        Py_DECREF(field);
        return NULL;
      }
      memcpy(&dest[i], item, sizeof(@(nested_type)));
    }
    Py_DECREF(seq_field);
@[    else]@
    @(nested_type) * tmp = (@(nested_type) *) convert_from_py(field);
    if (!tmp) {
      return NULL;
    }
    ros_message->@(field.name) = *tmp;
@[    end if]@
@[  elif field.type.is_array]@
    PyObject * seq_field = PySequence_Fast(field, "expected a sequence in '@(field.name)'");
    if (!seq_field) {
      Py_DECREF(field);
      return NULL;
    }
@[    if field.type.array_size is None or field.type.is_upper_bound]@
    Py_ssize_t size = PySequence_Size(field);
    if (-1 == size) {
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
@[      if field.type.type == 'string']@
    if (!rosidl_generator_c__String__Array__init(&(ros_message->@(field.name)), size)) {
      PyErr_SetString(PyExc_RuntimeError, "unable to create String__Array ros_message");
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
@[      else]@
    if (!rosidl_generator_c__@(field.type.type)__Array__init(&(ros_message->@(field.name)), size)) {
      PyErr_SetString(PyExc_RuntimeError, "unable to create @(field.type.type)__Array ros_message");
      Py_DECREF(seq_field);
      Py_DECREF(field);
      return NULL;
    }
@[      end if]@
    @primitive_msg_type_to_c(field.type.type) * dest = ros_message->@(field.name).data;
@[    else]@
    Py_ssize_t size = @(field.type.array_size);
    @primitive_msg_type_to_c(field.type.type) * dest = ros_message->@(field.name);
@[    end if]@
    for (Py_ssize_t i = 0; i < size; ++i) {
      PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
      if (!item) {
        Py_DECREF(seq_field);
        Py_DECREF(field);
        return NULL;
      }
@[    if field.type.type == 'char']@
      assert(PyUnicode_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = PyUnicode_1BYTE_DATA(item)[0];
@[    elif field.type.type == 'byte']@
      assert(PyBytes_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = PyBytes_AS_STRING(item)[0];
@[    elif field.type.type == 'string']@
      assert(PyUnicode_Check(item));
      rosidl_generator_c__String__assign(&dest[i], (char *)PyUnicode_1BYTE_DATA(item));
@[    elif field.type.type == 'bool']@
      assert(PyBool_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = (item == Py_True);
@[    elif field.type.type in ['float32', 'float64']]@
      assert(PyFloat_Check(item));
@[      if field.type.type == 'float32']@
      @primitive_msg_type_to_c(field.type.type) tmp = (float)PyFloat_AS_DOUBLE(item);
@[      else]@
      @primitive_msg_type_to_c(field.type.type) tmp = PyFloat_AS_DOUBLE(item);
@[      end if]@
@[    elif field.type.type in [
        'int8',
        'int16',
        'int32',
    ]]@
      assert(PyLong_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = (@(primitive_msg_type_to_c(field.type.type)))PyLong_AsLong(item);
@[    elif field.type.type in [
        'uint8',
        'uint16',
        'uint32',
    ]]@
      assert(PyLong_Check(item));
@[      if field.type.type == 'uint32']@
      @primitive_msg_type_to_c(field.type.type) tmp = PyLong_AsUnsignedLong(item);
@[      else]@
      @primitive_msg_type_to_c(field.type.type) tmp = (@(primitive_msg_type_to_c(field.type.type)))PyLong_AsUnsignedLong(item);
@[      end if]
@[    elif field.type.type == 'int64']@
      assert(PyLong_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = PyLong_AsLongLong(item);
@[    elif field.type.type == 'uint64']@
      assert(PyLong_Check(item));
      @primitive_msg_type_to_c(field.type.type) tmp = PyLong_AsUnsignedLongLong(item);
@[    end if]@
@[    if field.type.type != 'string']@
      memcpy(&dest[i], &tmp, sizeof(@primitive_msg_type_to_c(field.type.type)));
@[    end if]@
    }
    Py_DECREF(seq_field);
@[  elif field.type.type == 'char']@
    assert(PyUnicode_Check(field));
    ros_message->@(field.name) = PyUnicode_1BYTE_DATA(field)[0];
@[  elif field.type.type == 'byte']@
    assert(PyBytes_Check(field));
    ros_message->@(field.name) = PyBytes_AS_STRING(field)[0];
@[  elif field.type.type == 'string']@
    assert(PyUnicode_Check(field));
    rosidl_generator_c__String__assign(&ros_message->@(field.name), (char *)PyUnicode_1BYTE_DATA(field));
@[  elif field.type.type == 'bool']@
    assert(PyBool_Check(field));
    ros_message->@(field.name) = (Py_True == field);
@[  elif field.type.type in ['float32', 'float64']]@
    assert(PyFloat_Check(field));
@[    if field.type.type == 'float32']@
    ros_message->@(field.name) = (float)PyFloat_AS_DOUBLE(field);
@[    else]@
    ros_message->@(field.name) = PyFloat_AS_DOUBLE(field);
@[    end if]@
@[  elif field.type.type in [
        'int8',
        'int16',
        'int32',
    ]]@
    assert(PyLong_Check(field));
    ros_message->@(field.name) = (@(primitive_msg_type_to_c(field.type.type)))PyLong_AsLong(field);
@[  elif field.type.type in [
        'uint8',
        'uint16',
        'uint32',
    ]]@
    assert(PyLong_Check(field));
@[    if field.type.type == 'uint32']@
    ros_message->@(field.name) = PyLong_AsUnsignedLong(field);
@[    else]@
    ros_message->@(field.name) = (@(primitive_msg_type_to_c(field.type.type)))PyLong_AsUnsignedLong(field);
@[    end if]@
@[  elif field.type.type == 'int64']@
    assert(PyLong_Check(field));
    ros_message->@(field.name) = PyLong_AsLongLong(field);
@[  elif field.type.type == 'uint64']@
    assert(PyLong_Check(field));
    ros_message->@(field.name) = PyLong_AsUnsignedLongLong(field);
@[  else]@
    assert(false);
@[  end if]@
    Py_DECREF(field);
  }
@[end for]@

  return ros_message;
}

void @(spec.base_type.pkg_name)_@(module_name)__destroy_ros_message(void * raw_ros_message)
{
  @(msg_typename) * ros_message = (@(msg_typename) *)raw_ros_message;
  @(msg_typename)__destroy(ros_message);
}

PyObject * @(spec.base_type.pkg_name)_@(module_name)__convert_to_py(void * raw_ros_message)
{
  /* NOTE(esteve): Call constructor of @(spec.base_type.type) */
  PyObject * _pymessage = NULL;
  {
    PyObject * pymessage_module = PyImport_ImportModule("@(spec.base_type.pkg_name).@(subfolder)._@(module_name)");
    assert(pymessage_module);
    PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "@(spec.base_type.type)");
    assert(pymessage_class);
    Py_DECREF(pymessage_module);
    _pymessage = PyObject_CallObject(pymessage_class, NULL);
    Py_DECREF(pymessage_class);
    if (!_pymessage) {
      return NULL;
    }
  }
  @(msg_typename) * ros_message = (@(msg_typename) *)raw_ros_message;
@[if not spec.fields]@
  (void)ros_message;
@[end if]@
@[for field in spec.fields]@
  {  // @(field.name)
    PyObject * field = NULL;
@[  if not field.type.is_primitive_type()]@
@{
nested_type = '%s__%s__%s' % (field.type.pkg_name, 'msg', field.type.type)
}@
    typedef PyObject *(* convert_to_py_signature)(void *);
    convert_to_py_signature convert_to_py = NULL;
    // get conversion function
    {
      PyObject * msg_module = PyImport_ImportModule("@(field.type.pkg_name).msg._@convert_camel_case_to_lower_case_underscore(field.type.type)");
      if (!msg_module) {
        return NULL;
      }
      PyObject * msg_class = PyObject_GetAttrString(msg_module, "@(field.type.type)");
      Py_DECREF(msg_module);
      if (!msg_class) {
        return NULL;
      }
      PyObject * msg_metaclass = PyObject_GetAttrString(msg_class, "__class__");
      Py_DECREF(msg_class);
      if (!msg_metaclass) {
        return NULL;
      }
      PyObject * convert_to_py_ = PyObject_GetAttrString(msg_metaclass, "_CONVERT_TO_PY");
      Py_DECREF(msg_metaclass);
      if (!convert_to_py_) {
        return NULL;
      }
      convert_to_py = (convert_to_py_signature)PyCapsule_GetPointer(convert_to_py_, NULL);
      Py_DECREF(convert_to_py_);
      if (!convert_to_py) {
        return NULL;
      }
    }
@[    if field.type.is_array]@
@[      if field.type.array_size is None or field.type.is_upper_bound]@
    size_t size = ros_message->@(field.name).size;
@[      else]@
    size_t size = @(field.type.array_size);
@[      end if]@
    field = PyList_New(size);
    if (!field) {
      return NULL;
    }
    @(nested_type) * item;
    for (size_t i = 0; i < size; ++i) {
@[      if field.type.array_size is None or field.type.is_upper_bound]@
      item = &(ros_message->@(field.name).data[i]);
@[      else]@
      item = &(ros_message->@(field.name)[i]);
@[      end if]@
      PyObject * pyitem = convert_to_py(item);
      if (!pyitem) {
        Py_DECREF(field);
        return NULL;
      }
      int rc = PyList_SetItem(field, i, pyitem);
      assert(rc == 0);
    }
    assert(PySequence_Check(field));
@[    else]@
    field = convert_to_py(&ros_message->@(field.name));
    if (!field) {
      return NULL;
    }
@[    end if]@
@[  elif field.type.is_array]@
@[    if field.type.array_size is None or field.type.is_upper_bound]@
    size_t size = ros_message->@(field.name).size;
    @primitive_msg_type_to_c(field.type.type) * src = ros_message->@(field.name).data;
@[    else]@
    size_t size = @(field.type.array_size);
    @primitive_msg_type_to_c(field.type.type) * src = ros_message->@(field.name);
@[    end if]@
    field = PyList_New(size);
    if (!field) {
      return NULL;
    }
    for (size_t i = 0; i < size; ++i) {
@[    if field.type.type == 'char']@
      int rc = PyList_SetItem(field, i, Py_BuildValue("C", src[i]));
      assert(rc == 0);
@[    elif field.type.type == 'byte']@
      int rc = PyList_SetItem(field, i, PyBytes_FromStringAndSize((const char *)&src[i], 1));
      assert(rc == 0);
@[    elif field.type.type == 'string']@
      int rc = PyList_SetItem(field, i, PyUnicode_FromString(src[i].data));
      assert(rc == 0);
@[    elif field.type.type == 'bool']@
@# using PyBool_FromLong because PyList_SetItem will steal ownership of the passed item
      int rc = PyList_SetItem(field, i, PyBool_FromLong(src[i] ? 1 : 0));
      assert(rc == 0);
@[    elif field.type.type in ['float32', 'float64']]@
      int rc = PyList_SetItem(field, i, PyFloat_FromDouble(src[i]));
      assert(rc == 0);
@[    elif field.type.type in [
        'int8',
        'int16',
        'int32',
    ]]@
      int rc = PyList_SetItem(field, i, PyLong_FromLong(src[i]));
      assert(rc == 0);
@[    elif field.type.type in [
        'uint8',
        'uint16',
        'uint32',
    ]]@
      int rc = PyList_SetItem(field, i, PyLong_FromUnsignedLong(src[i]));
      assert(rc == 0);
@[    elif field.type.type == 'int64']@
      int rc = PyList_SetItem(field, i, PyLong_FromLongLong(src[i]));
      assert(rc == 0);
@[    elif field.type.type == 'uint64']@
      int rc = PyList_SetItem(field, i, PyLong_FromUnsignedLongLong(src[i]));
      assert(rc == 0);
@[    end if]@
    }
    assert(PySequence_Check(field));
@[  elif field.type.type == 'char']@
    field = Py_BuildValue("C", ros_message->@(field.name));
    if (!field) {
      return NULL;
    }
@[  elif field.type.type == 'byte']@
    field = PyBytes_FromStringAndSize((const char *)&ros_message->@(field.name), 1);
    if (!field) {
      return NULL;
    }
@[  elif field.type.type == 'string']@
    field = PyUnicode_FromString(ros_message->@(field.name).data);
@[  elif field.type.type == 'bool']@
@# using PyBool_FromLong allows treating the variable uniformly by calling Py_DECREF on it later
    field = PyBool_FromLong(ros_message->@(field.name) ? 1 : 0);
@[  elif field.type.type in ['float32', 'float64']]@
    field = PyFloat_FromDouble(ros_message->@(field.name));
@[  elif field.type.type in [
        'int8',
        'int16',
        'int32',
    ]]@
    field = PyLong_FromLong(ros_message->@(field.name));
@[  elif field.type.type in [
        'uint8',
        'uint16',
        'uint32',
    ]]@
    field = PyLong_FromUnsignedLong(ros_message->@(field.name));
@[  elif field.type.type == 'int64']@
    field = PyLong_FromLongLong(ros_message->@(field.name));
@[  elif field.type.type == 'uint64']@
    field = PyLong_FromUnsignedLongLong(ros_message->@(field.name));
@[  else]@
    assert(false);
@[  end if]@
    {
      int rc = PyObject_SetAttrString(_pymessage, "@(field.name)", field);
      Py_DECREF(field);
      if (rc) {
        return NULL;
      }
    }
  }
@[end for]@

  // ownership of _pymessage is transferred to the caller
  return _pymessage;
}


[REFACTOR] Clean up example to better test operator templating. At least for now..


generate markdown for triggered jobs (#65)

<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description>
    Note: The Windows jobs ignore the middleware selection flags.
  </description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <com.sonyericsson.rebuild.RebuildSettings plugin="rebuild@@1.25">
      <autoRebuild>false</autoRebuild>
      <rebuildDisabled>false</rebuildDisabled>
    </com.sonyericsson.rebuild.RebuildSettings>
    <org.jenkinsci.plugins.requeuejob.RequeueJobProperty plugin="jobrequeue@@1.1">
      <requeueJob>true</requeueJob>
    </org.jenkinsci.plugins.requeuejob.RequeueJobProperty>
@(SNIPPET(
    'property_parameter-definition',
    ci_scripts_default_branch=ci_scripts_default_branch,
    default_repos_url=default_repos_url,
    use_connext_default=use_connext_default,
    disable_connext_static_default=disable_connext_static_default,
    disable_connext_dynamic_default=disable_connext_dynamic_default,
    use_osrf_connext_debs_default=use_osrf_connext_debs_default,
    use_fastrtps_default=use_fastrtps_default,
    use_opensplice_default=use_opensplice_default,
    cmake_build_type=cmake_build_type,
    ament_build_args_default=ament_build_args_default,
    ament_test_args_default=ament_test_args_default,
    enable_c_coverage_default=enable_c_coverage_default,
))@
  </properties>
  <scm class="hudson.scm.NullSCM"/>
  <assignedNode>@(label_expression)</assignedNode>
  <canRoam>false</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.plugins.groovy.SystemGroovy plugin="groovy@@2.0">
      <source class="hudson.plugins.groovy.StringSystemScriptSource">
        <script plugin="script-security@@1.27">
          <script>// PREDICT TRIGGERED BUILDS AND GENERATE MARKDOWN FOR BUILD STATUS

import jenkins.model.Jenkins

def predict_build_number(job_name) {
  p = Jenkins.instance.getItemByFullName(job_name)
  if (!p) {
    return 0
  }
  build_number = p.getNextBuildNumber()
  if (p.isInQueue()) {
    // assuming the queued builds don't get cancelled
    for (item in Jenkins.instance.getQueue().getItems()) {
      if (item.task.getName() == job_name) {
        build_number += 1
      }
    }
  }
  return build_number
}

build_numbers = [:]
@[for os_name in os_specific_data.keys()]@
build_numbers["@(os_name)"] = predict_build_number("ci_@(os_name)")
@[end for]@

for (item in build_numbers) {
  name = item.key[0].toUpperCase() + item.key[1..-1].toLowerCase()
  if (name == "Osx") {
    name = "macOS"
  }
  job_name = "ci_${item.key}"
  build_number = item.value
  println "* ${name} [![Build Status](http://ci.ros2.org/buildStatus/icon?job=${job_name}&build=${build_number})](http://ci.ros2.org/job/${job_name}/${build_number}/)"
}
</script>
          <sandbox>false</sandbox>
        </script>
      </source>
    </hudson.plugins.groovy.SystemGroovy>
  </builders>
  <publishers>
@[for os_name, os_data in os_specific_data.items()]@
    <hudson.plugins.parameterizedtrigger.BuildTrigger plugin="parameterized-trigger@@2.33">
      <configs>
        <hudson.plugins.parameterizedtrigger.BuildTriggerConfig>
          <configs>
            <hudson.plugins.parameterizedtrigger.CurrentBuildParameters/>
@[if os_name == 'linux-aarch64']@
            <hudson.plugins.parameterizedtrigger.BooleanParameters>
              <configs>
                <hudson.plugins.parameterizedtrigger.BooleanParameterConfig>
                  <name>CI_USE_CONNEXT</name>
                  <value>false</value>
                </hudson.plugins.parameterizedtrigger.BooleanParameterConfig>
              </configs>
            </hudson.plugins.parameterizedtrigger.BooleanParameters>
@[end if]@
          </configs>
          <projects>@(os_data['job_name'])</projects>
          <condition>SUCCESS</condition>
          <triggerWithNoParameters>false</triggerWithNoParameters>
          <triggerFromChildProjects>false</triggerFromChildProjects>
        </hudson.plugins.parameterizedtrigger.BuildTriggerConfig>
      </configs>
    </hudson.plugins.parameterizedtrigger.BuildTrigger>
@[end for]@
  </publishers>
  <buildWrappers/>
</project>

<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description>
    Note: The Windows jobs ignore the middleware selection flags.
  </description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <com.sonyericsson.rebuild.RebuildSettings plugin="rebuild@@1.25">
      <autoRebuild>false</autoRebuild>
      <rebuildDisabled>false</rebuildDisabled>
    </com.sonyericsson.rebuild.RebuildSettings>
    <org.jenkinsci.plugins.requeuejob.RequeueJobProperty plugin="jobrequeue@@1.1">
      <requeueJob>true</requeueJob>
    </org.jenkinsci.plugins.requeuejob.RequeueJobProperty>
@(SNIPPET(
    'property_parameter-definition',
    ci_scripts_default_branch=ci_scripts_default_branch,
    default_repos_url=default_repos_url,
    use_connext_default=use_connext_default,
    disable_connext_static_default=disable_connext_static_default,
    disable_connext_dynamic_default=disable_connext_dynamic_default,
    use_osrf_connext_debs_default=use_osrf_connext_debs_default,
    use_fastrtps_default=use_fastrtps_default,
    use_opensplice_default=use_opensplice_default,
    cmake_build_type=cmake_build_type,
    ament_build_args_default=ament_build_args_default,
    ament_test_args_default=ament_test_args_default,
    enable_c_coverage_default=enable_c_coverage_default,
))@
  </properties>
  <scm class="hudson.scm.NullSCM"/>
  <assignedNode>@(label_expression)</assignedNode>
  <canRoam>false</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders/>
  <publishers>
@[for os_name, os_data in os_specific_data.items()]@
    <hudson.plugins.parameterizedtrigger.BuildTrigger plugin="parameterized-trigger@@2.33">
      <configs>
        <hudson.plugins.parameterizedtrigger.BuildTriggerConfig>
          <configs>
            <hudson.plugins.parameterizedtrigger.CurrentBuildParameters/>
@[if os_name == 'linux-aarch64']@
            <hudson.plugins.parameterizedtrigger.BooleanParameters>
              <configs>
                <hudson.plugins.parameterizedtrigger.BooleanParameterConfig>
                  <name>CI_USE_CONNEXT</name>
                  <value>false</value>
                </hudson.plugins.parameterizedtrigger.BooleanParameterConfig>
              </configs>
            </hudson.plugins.parameterizedtrigger.BooleanParameters>
@[end if]@
          </configs>
          <projects>@(os_data['job_name'])</projects>
          <condition>SUCCESS</condition>
          <triggerWithNoParameters>false</triggerWithNoParameters>
          <triggerFromChildProjects>false</triggerFromChildProjects>
        </hudson.plugins.parameterizedtrigger.BuildTriggerConfig>
      </configs>
    </hudson.plugins.parameterizedtrigger.BuildTrigger>
@[end for]@
  </publishers>
  <buildWrappers/>
</project>


msg: rtps: improve verbosity when the the client is not capable of parsing a specific ID

@###############################################
@#
@# EmPy template for generating microRTPS_client.cpp file
@#
@###############################################
@# Start of Template
@#
@# Context:
@#  - msgs (List) list of all msg files
@#  - multi_topics (List) list of all multi-topic names
@#  - ids (List) list of all RTPS msg ids
@###############################################
@{
import os

import genmsg.msgs

from px_generate_uorb_topic_helper import * # this is in Tools/
from px_generate_uorb_topic_files import MsgScope # this is in Tools/

topic_names = [s.short_name for s in spec]
send_topics = [(alias[idx] if alias[idx] else s.short_name) for idx, s in enumerate(spec) if scope[idx] == MsgScope.SEND]
send_base_types = [s.short_name for idx, s in enumerate(spec) if scope[idx] == MsgScope.SEND]
recv_topics = [(alias[idx] if alias[idx] else s.short_name) for idx, s in enumerate(spec) if scope[idx] == MsgScope.RECEIVE]
receive_base_types = [s.short_name for idx, s in enumerate(spec) if scope[idx] == MsgScope.RECEIVE]
}@
/****************************************************************************
 *
 * Copyright (c) 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
 * Copyright (c) 2018-2019 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 of the copyright holder 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 "microRTPS_transport.h"
#include "microRTPS_client.h"

#include <inttypes.h>
#include <cstdio>
#include <ctime>
#include <pthread.h>

#include <ucdr/microcdr.h>
#include <px4_time.h>
#include <uORB/uORB.h>

#include <uORB/Publication.hpp>
#include <uORB/Subscription.hpp>
@[for topic in list(set(topic_names))]@
#include <uORB/topics/@(topic).h>
#include <uORB_microcdr/topics/@(topic).h>
@[end for]@

void* send(void *data);

uint8_t last_remote_msg_seq = 0;
uint8_t last_msg_seq = 0;

@[if recv_topics]@
// Publishers for received messages
struct RcvTopicsPubs
{
@[    for idx, topic in enumerate(recv_topics)]@
    uORB::Publication<@(receive_base_types[idx])_s> @(topic)_pub{ORB_ID(@(topic))};
@[    end for]@
};
@[end if]@

@[if send_topics]@
// Subscribers for messages to send
struct SendTopicsSubs
{
@[    for idx, topic in enumerate(send_topics)]@
    uORB::Subscription @(topic)_sub{ORB_ID(@(topic))};
@[    end for]@
};
@[end if]@

@[if send_topics]@
void* send(void* /*unused*/)
{
    char data_buffer[BUFFER_SIZE] = {};
    uint64_t sent = 0, total_sent = 0;
    int loop = 0, read = 0;
    uint32_t length = 0;
    size_t header_length = 0;
    SendTopicsSubs *subs = new SendTopicsSubs();

    // ucdrBuffer to serialize using the user defined buffer
    ucdrBuffer writer;
    header_length = transport_node->get_header_length();
    ucdr_init_buffer(&writer, reinterpret_cast<uint8_t*>(&data_buffer[header_length]), BUFFER_SIZE - header_length);

    struct timespec begin;
    px4_clock_gettime(CLOCK_REALTIME, &begin);

    while (!_should_exit_task)
    {
@[for idx, topic in enumerate(send_topics)]@
        {
            @(send_base_types[idx])_s @(topic)_data;
            if (subs->@(topic)_sub.update(&@(topic)_data)) {
@[if topic == 'Timesync' or topic == 'timesync']@
                if(@(topic)_data.sys_id == 0 && @(topic)_data.seq != last_remote_msg_seq && @(topic)_data.tc1 == 0) {
                    last_remote_msg_seq = @(topic)_data.seq;

                    @(topic)_data.timestamp = hrt_absolute_time();
                    @(topic)_data.sys_id = 1;
                    @(topic)_data.seq = last_msg_seq;
                    @(topic)_data.tc1 = hrt_absolute_time() * 1000ULL;
                    @(topic)_data.ts1 = @(topic)_data.ts1;

                    last_msg_seq++;
@[end if]@
                    // copy raw data into local buffer. Payload is shifted by header length to make room for header
                    serialize_@(send_base_types[idx])(&writer, &@(topic)_data, &data_buffer[header_length], &length);
                    if (0 < (read = transport_node->write(static_cast<char>(@(rtps_message_id(ids, topic))), data_buffer, length)))
                    {
                        total_sent += read;
                        ++sent;
                    }
@[if topic == 'Timesync' or topic == 'timesync']@
                }
@[end if]@
             }
        }
@[end for]@
        px4_usleep(_options.sleep_ms * 1000);
        ++loop;
    }

    struct timespec end;
    px4_clock_gettime(CLOCK_REALTIME, &end);
    double elapsed_secs = end.tv_sec - begin.tv_sec + (end.tv_nsec - begin.tv_nsec) / 1e9;
    PX4_INFO("SENT: %" PRIu64 " messages in %d LOOPS, %" PRIu64 " bytes in %.03f seconds - %.02fKB/s",
                sent, loop, total_sent, elapsed_secs, total_sent / (1e3 * elapsed_secs));

    delete subs;

    return nullptr;
}

static int launch_send_thread(pthread_t &sender_thread)
{
    pthread_attr_t sender_thread_attr;
    pthread_attr_init(&sender_thread_attr);
    pthread_attr_setstacksize(&sender_thread_attr, PX4_STACK_ADJUSTED(2250));
    struct sched_param param;
    (void)pthread_attr_getschedparam(&sender_thread_attr, &param);
    param.sched_priority = SCHED_PRIORITY_DEFAULT;
    (void)pthread_attr_setschedparam(&sender_thread_attr, &param);
    pthread_create(&sender_thread, &sender_thread_attr, send, nullptr);
    if (pthread_setname_np(sender_thread, "micrortps_client_send"))
    {
        PX4_ERR("Could not set pthread name (%d)", errno);
    }
    pthread_attr_destroy(&sender_thread_attr);

    return 0;
}
@[end if]@

void micrortps_start_topics(struct timespec &begin, uint64_t &total_read, uint64_t &received, int &loop)
{
@[if recv_topics]@
    char data_buffer[BUFFER_SIZE] = {};
    int read = 0;
    uint8_t topic_ID = 255;
    RcvTopicsPubs *pubs = new RcvTopicsPubs();

    // Set the main task name to 'micrortps_client_rcv' in case there is
    // data to receive
    px4_prctl(PR_SET_NAME, "micrortps_client_rcv", px4_getpid());

    // ucdrBuffer to deserialize using the user defined buffer
    ucdrBuffer reader;
    ucdr_init_buffer(&reader, reinterpret_cast<uint8_t*>(data_buffer), BUFFER_SIZE);
@[end if]@

    px4_clock_gettime(CLOCK_REALTIME, &begin);
    _should_exit_task = false;
@[if send_topics]@

    // create a thread for sending data to the simulator
    pthread_t sender_thread;
    launch_send_thread(sender_thread);
@[end if]@

    while (!_should_exit_task)
    {
@[if recv_topics]@
        while (0 < (read = transport_node->read(&topic_ID, data_buffer, BUFFER_SIZE)))
        {
            total_read += read;
            switch (topic_ID)
            {
@[for idx, topic in enumerate(recv_topics)]@
                case @(rtps_message_id(ids, topic)):
                {
                    @(receive_base_types[idx])_s @(topic)_data;
                    deserialize_@(receive_base_types[idx])(&reader, &@(topic)_data, data_buffer);
                    pubs->@(topic)_pub.publish(@(topic)_data);
                    ++received;
                }
                break;
@[end for]@
                default:
                    PX4_WARN("Unexpected topic ID '%hhu' to getMsg. Please make sure the client is capable of parsing the message associated to the topic ID '%hhu'", topic_ID, topic_ID);
                break;
            }
        }
@[end if]@

        // loop forever if informed loop number is negative
        if (_options.loops >= 0 && loop >= _options.loops) break;

        px4_usleep(_options.sleep_ms * 1000);
        ++loop;
    }
@[if recv_topics]@
    delete pubs;
@[end if]@
@[if send_topics]@
    _should_exit_task = true;
    pthread_join(sender_thread, nullptr);
@[end if]@
}

@###############################################
@#
@# EmPy template for generating microRTPS_client.cpp file
@#
@###############################################
@# Start of Template
@#
@# Context:
@#  - msgs (List) list of all msg files
@#  - multi_topics (List) list of all multi-topic names
@#  - ids (List) list of all RTPS msg ids
@###############################################
@{
import os

import genmsg.msgs

from px_generate_uorb_topic_helper import * # this is in Tools/
from px_generate_uorb_topic_files import MsgScope # this is in Tools/

topic_names = [s.short_name for s in spec]
send_topics = [(alias[idx] if alias[idx] else s.short_name) for idx, s in enumerate(spec) if scope[idx] == MsgScope.SEND]
send_base_types = [s.short_name for idx, s in enumerate(spec) if scope[idx] == MsgScope.SEND]
recv_topics = [(alias[idx] if alias[idx] else s.short_name) for idx, s in enumerate(spec) if scope[idx] == MsgScope.RECEIVE]
receive_base_types = [s.short_name for idx, s in enumerate(spec) if scope[idx] == MsgScope.RECEIVE]
}@
/****************************************************************************
 *
 * Copyright (c) 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
 * Copyright (c) 2018-2019 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 of the copyright holder 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 "microRTPS_transport.h"
#include "microRTPS_client.h"

#include <inttypes.h>
#include <cstdio>
#include <ctime>
#include <pthread.h>

#include <ucdr/microcdr.h>
#include <px4_time.h>
#include <uORB/uORB.h>

#include <uORB/Publication.hpp>
#include <uORB/Subscription.hpp>
@[for topic in list(set(topic_names))]@
#include <uORB/topics/@(topic).h>
#include <uORB_microcdr/topics/@(topic).h>
@[end for]@

void* send(void *data);

uint8_t last_remote_msg_seq = 0;
uint8_t last_msg_seq = 0;

@[if recv_topics]@
// Publishers for received messages
struct RcvTopicsPubs
{
@[    for idx, topic in enumerate(recv_topics)]@
    uORB::Publication<@(receive_base_types[idx])_s> @(topic)_pub{ORB_ID(@(topic))};
@[    end for]@
};
@[end if]@

@[if send_topics]@
// Subscribers for messages to send
struct SendTopicsSubs
{
@[    for idx, topic in enumerate(send_topics)]@
    uORB::Subscription @(topic)_sub{ORB_ID(@(topic))};
@[    end for]@
};
@[end if]@

@[if send_topics]@
void* send(void* /*unused*/)
{
    char data_buffer[BUFFER_SIZE] = {};
    uint64_t sent = 0, total_sent = 0;
    int loop = 0, read = 0;
    uint32_t length = 0;
    size_t header_length = 0;
    SendTopicsSubs *subs = new SendTopicsSubs();

    // ucdrBuffer to serialize using the user defined buffer
    ucdrBuffer writer;
    header_length = transport_node->get_header_length();
    ucdr_init_buffer(&writer, reinterpret_cast<uint8_t*>(&data_buffer[header_length]), BUFFER_SIZE - header_length);

    struct timespec begin;
    px4_clock_gettime(CLOCK_REALTIME, &begin);

    while (!_should_exit_task)
    {
@[for idx, topic in enumerate(send_topics)]@
        {
            @(send_base_types[idx])_s @(topic)_data;
            if (subs->@(topic)_sub.update(&@(topic)_data)) {
@[if topic == 'Timesync' or topic == 'timesync']@
                if(@(topic)_data.sys_id == 0 && @(topic)_data.seq != last_remote_msg_seq && @(topic)_data.tc1 == 0) {
                    last_remote_msg_seq = @(topic)_data.seq;

                    @(topic)_data.timestamp = hrt_absolute_time();
                    @(topic)_data.sys_id = 1;
                    @(topic)_data.seq = last_msg_seq;
                    @(topic)_data.tc1 = hrt_absolute_time() * 1000ULL;
                    @(topic)_data.ts1 = @(topic)_data.ts1;

                    last_msg_seq++;
@[end if]@
                    // copy raw data into local buffer. Payload is shifted by header length to make room for header
                    serialize_@(send_base_types[idx])(&writer, &@(topic)_data, &data_buffer[header_length], &length);
                    if (0 < (read = transport_node->write(static_cast<char>(@(rtps_message_id(ids, topic))), data_buffer, length)))
                    {
                        total_sent += read;
                        ++sent;
                    }
@[if topic == 'Timesync' or topic == 'timesync']@
                }
@[end if]@
             }
        }
@[end for]@
        px4_usleep(_options.sleep_ms * 1000);
        ++loop;
    }

    struct timespec end;
    px4_clock_gettime(CLOCK_REALTIME, &end);
    double elapsed_secs = end.tv_sec - begin.tv_sec + (end.tv_nsec - begin.tv_nsec) / 1e9;
    PX4_INFO("SENT: %" PRIu64 " messages in %d LOOPS, %" PRIu64 " bytes in %.03f seconds - %.02fKB/s",
                sent, loop, total_sent, elapsed_secs, total_sent / (1e3 * elapsed_secs));

    delete subs;

    return nullptr;
}

static int launch_send_thread(pthread_t &sender_thread)
{
    pthread_attr_t sender_thread_attr;
    pthread_attr_init(&sender_thread_attr);
    pthread_attr_setstacksize(&sender_thread_attr, PX4_STACK_ADJUSTED(2250));
    struct sched_param param;
    (void)pthread_attr_getschedparam(&sender_thread_attr, &param);
    param.sched_priority = SCHED_PRIORITY_DEFAULT;
    (void)pthread_attr_setschedparam(&sender_thread_attr, &param);
    pthread_create(&sender_thread, &sender_thread_attr, send, nullptr);
    if (pthread_setname_np(sender_thread, "micrortps_client_send"))
    {
        PX4_ERR("Could not set pthread name (%d)", errno);
    }
    pthread_attr_destroy(&sender_thread_attr);

    return 0;
}
@[end if]@

void micrortps_start_topics(struct timespec &begin, uint64_t &total_read, uint64_t &received, int &loop)
{
@[if recv_topics]@
    char data_buffer[BUFFER_SIZE] = {};
    int read = 0;
    uint8_t topic_ID = 255;
    RcvTopicsPubs *pubs = new RcvTopicsPubs();

    // Set the main task name to 'micrortps_client_rcv' in case there is
    // data to receive
    px4_prctl(PR_SET_NAME, "micrortps_client_rcv", px4_getpid());

    // ucdrBuffer to deserialize using the user defined buffer
    ucdrBuffer reader;
    ucdr_init_buffer(&reader, reinterpret_cast<uint8_t*>(data_buffer), BUFFER_SIZE);
@[end if]@

    px4_clock_gettime(CLOCK_REALTIME, &begin);
    _should_exit_task = false;
@[if send_topics]@

    // create a thread for sending data to the simulator
    pthread_t sender_thread;
    launch_send_thread(sender_thread);
@[end if]@

    while (!_should_exit_task)
    {
@[if recv_topics]@
        while (0 < (read = transport_node->read(&topic_ID, data_buffer, BUFFER_SIZE)))
        {
            total_read += read;
            switch (topic_ID)
            {
@[for idx, topic in enumerate(recv_topics)]@
                case @(rtps_message_id(ids, topic)):
                {
                    @(receive_base_types[idx])_s @(topic)_data;
                    deserialize_@(receive_base_types[idx])(&reader, &@(topic)_data, data_buffer);
                    pubs->@(topic)_pub.publish(@(topic)_data);
                    ++received;
                }
                break;
@[end for]@
                default:
                    PX4_WARN("Unexpected topic ID\n");
                break;
            }
        }
@[end if]@

        // loop forever if informed loop number is negative
        if (_options.loops >= 0 && loop >= _options.loops) break;

        px4_usleep(_options.sleep_ms * 1000);
        ++loop;
    }
@[if recv_topics]@
    delete pubs;
@[end if]@
@[if send_topics]@
    _should_exit_task = true;
    pthread_join(sender_thread, nullptr);
@[end if]@
}


Yet another quaternion lookat fix. I think this is the last one.


fix missing linkage folder when checking for dependencies

#!/usr/bin/make -f
# -*- makefile -*-
# Sample debian/rules that uses debhelper.
# This file was originally written by Joey Hess and Craig Small.
# As a special exception, when this file is copied by dh-make into a
# dh-make output file, you may use that output file without restriction.
# This special exception was added by Craig Small in version 0.37 of dh-make.

# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1
export DH_OPTIONS=-v --buildsystem=cmake
export CMAKE_PREFIX_PATH=@(INSTALL_PREFIX)
# TODO: remove the LDFLAGS override.  It's here to avoid esoteric problems
# of this sort:
#  https://code.ros.org/trac/ros/ticket/2977
#  https://code.ros.org/trac/ros/ticket/3842
export LDFLAGS=

%:
	dh  $@@

#
#  The CATKIN=YES is needed to make it possible for
#  ROS packages to build under rosmake and catkin
#
override_dh_auto_configure:
	dh_auto_configure -- \
		-DCMAKE_INSTALL_PREFIX="@(INSTALL_PREFIX)" \
		-DCMAKE_PREFIX_PATH="@(INSTALL_PREFIX)"

override_dh_auto_test:
	echo -- Running tests. Even if one of them fails the build is not canceled.
	dh_auto_test || true

override_dh_shlibdeps:
	dh_shlibdeps -l$(CURDIR)/debian/@(Package)/@(INSTALL_PREFIX)/lib/


Try bootstraping rosdep after it is installed

@(TEMPLATE(
    'snippet/add_generated_comment.Dockerfile.em',
    user_name=user_name,
    tag_name=tag_name,
    source_template_name=template_name,
))@
@(TEMPLATE(
    'snippet/from_base_image.Dockerfile.em',
    template_packages=template_packages,
    os_name=os_name,
    os_code_name=os_code_name,
    arch=arch,
    base_image=base_image,
    maintainer_name=maintainer_name,
))@
@(TEMPLATE(
    'snippet/setup_tzdata.Dockerfile.em',
    os_name=os_name,
    os_code_name=os_code_name,
))@
@{
template_dependencies = [
    'dirmngr',
    'gnupg2',
    'lsb-release',
]
# add 'python3-pip' to 'template_dependencies' if pip dependencies are declared
if 'pip3_install' in locals():
    if isinstance(pip3_install, list) and pip3_install != []:
        template_dependencies.append('python3-pip')
}@
@(TEMPLATE(
    'snippet/install_upstream_package_list.Dockerfile.em',
    packages=template_dependencies,
    upstream_packages=upstream_packages if 'upstream_packages' in locals() else [],
))@
@
# setup keys
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 421C365BD9FF1F717815A3895523BAEEB01FA116

# setup sources.list
RUN . /etc/os-release \
    && echo "deb http://repo.ros2.org/$ID/main `lsb_release -sc` main" > /etc/apt/sources.list.d/ros2-latest.list

# setup environment
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8

@{
# add colcon packages to 'ros2_repo_packages' if colcon is used
if 'colcon_args' in locals():
    colcon_packages = [
        'python3-colcon-common-extensions',
    ]
    ros2_repo_packages.extend(colcon_packages)
}@
@[if 'ros2_repo_packages' in locals()]@
@[  if ros2_repo_packages]@
# install packages from the ROS repositories
RUN apt-get update && apt-get install -y --no-install-recommends \
    @(' \\\n    '.join(sorted(ros2_repo_packages)))@  \
    && rm -rf /var/lib/apt/lists/*

@[  end if]@
@[end if]@
@
@[if 'pip3_install' in locals()]@
@[  if pip3_install]@
# install python packages
RUN pip3 install -U \
    @(' \\\n    '.join(pip3_install))@

@[  end if]@
@[end if]@
@
@[if 'vcs' in locals()]@
@[  if vcs]@

@[if 'rosdep' in locals()]@
@[  if 'rosdistro_index_url' in rosdep]@
# bootstrap rosdep
ENV ROSDISTRO_INDEX_URL @(rosdep['rosdistro_index_url'])
RUN rosdep init \
    && rosdep update
@[  end if]@
@[end if]@

# clone source
ENV ROS2_WS @(ws)
RUN mkdir -p $ROS2_WS/src
WORKDIR $ROS2_WS
@(TEMPLATE(
    'snippet/vcs_import.Dockerfile.em',
    vcs=vcs,
    ws='src',
))@

@[  end if]@
@[end if]@
@
@[if 'rosdep' in locals()]@
@[  if 'install' in rosdep]@
@(TEMPLATE(
    'snippet/install_rosdep_dependencies.Dockerfile.em',
    install_args=rosdep['install'],
))@
@[  end if]@
@[end if]@

@[if 'colcon_args' in locals()]@
@[  if colcon_args]@
# build source
WORKDIR $ROS2_WS
RUN colcon \
    @(' \\\n    '.join(colcon_args))@

@[  end if]@
@[end if]@
# setup bashrc
RUN cp /etc/skel/.bashrc ~/

@[if 'entrypoint_name' in locals()]@
@[  if entrypoint_name]@
@{
entrypoint_file = entrypoint_name.split('/')[-1]
}@
# setup entrypoint
COPY ./@entrypoint_file /

ENTRYPOINT ["/@entrypoint_file"]
@[  end if]@
@[end if]@
@{
cmds = [
'bash',
]
}@
CMD ["@(' && '.join(cmds))"]

@(TEMPLATE(
    'snippet/add_generated_comment.Dockerfile.em',
    user_name=user_name,
    tag_name=tag_name,
    source_template_name=template_name,
))@
@(TEMPLATE(
    'snippet/from_base_image.Dockerfile.em',
    template_packages=template_packages,
    os_name=os_name,
    os_code_name=os_code_name,
    arch=arch,
    base_image=base_image,
    maintainer_name=maintainer_name,
))@
@(TEMPLATE(
    'snippet/setup_tzdata.Dockerfile.em',
    os_name=os_name,
    os_code_name=os_code_name,
))@
@{
template_dependencies = [
    'dirmngr',
    'gnupg2',
    'lsb-release',
]
# add 'python3-pip' to 'template_dependencies' if pip dependencies are declared
if 'pip3_install' in locals():
    if isinstance(pip3_install, list) and pip3_install != []:
        template_dependencies.append('python3-pip')
}@
@(TEMPLATE(
    'snippet/install_upstream_package_list.Dockerfile.em',
    packages=template_dependencies,
    upstream_packages=upstream_packages if 'upstream_packages' in locals() else [],
))@
@
# setup keys
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 421C365BD9FF1F717815A3895523BAEEB01FA116

# setup sources.list
RUN . /etc/os-release \
    && echo "deb http://repo.ros2.org/$ID/main `lsb_release -sc` main" > /etc/apt/sources.list.d/ros2-latest.list

# setup environment
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8

@[if 'rosdep' in locals()]@
@[  if 'rosdistro_index_url' in rosdep]@
# bootstrap rosdep
ENV ROSDISTRO_INDEX_URL @(rosdep['rosdistro_index_url'])
RUN rosdep init \
    && rosdep update
@[  end if]@
@[end if]@

@{
# add colcon packages to 'ros2_repo_packages' if colcon is used
if 'colcon_args' in locals():
    colcon_packages = [
        'python3-colcon-common-extensions',
    ]
    ros2_repo_packages.extend(colcon_packages)
}@
@[if 'ros2_repo_packages' in locals()]@
@[  if ros2_repo_packages]@
# install packages from the ROS repositories
RUN apt-get update && apt-get install -y --no-install-recommends \
    @(' \\\n    '.join(sorted(ros2_repo_packages)))@  \
    && rm -rf /var/lib/apt/lists/*

@[  end if]@
@[end if]@
@
@[if 'pip3_install' in locals()]@
@[  if pip3_install]@
# install python packages
RUN pip3 install -U \
    @(' \\\n    '.join(pip3_install))@

@[  end if]@
@[end if]@
@
@[if 'vcs' in locals()]@
@[  if vcs]@

# clone source
ENV ROS2_WS @(ws)
RUN mkdir -p $ROS2_WS/src
WORKDIR $ROS2_WS
@(TEMPLATE(
    'snippet/vcs_import.Dockerfile.em',
    vcs=vcs,
    ws='src',
))@

@[  end if]@
@[end if]@
@
@[if 'rosdep' in locals()]@
@[  if 'install' in rosdep]@
@(TEMPLATE(
    'snippet/install_rosdep_dependencies.Dockerfile.em',
    install_args=rosdep['install'],
))@
@[  end if]@
@[end if]@

@[if 'colcon_args' in locals()]@
@[  if colcon_args]@
# build source
WORKDIR $ROS2_WS
RUN colcon \
    @(' \\\n    '.join(colcon_args))@

@[  end if]@
@[end if]@
# setup bashrc
RUN cp /etc/skel/.bashrc ~/

@[if 'entrypoint_name' in locals()]@
@[  if entrypoint_name]@
@{
entrypoint_file = entrypoint_name.split('/')[-1]
}@
# setup entrypoint
COPY ./@entrypoint_file /

ENTRYPOINT ["/@entrypoint_file"]
@[  end if]@
@[end if]@
@{
cmds = [
'bash',
]
}@
CMD ["@(' && '.join(cmds))"]