repo_id
stringlengths 19
138
| file_path
stringlengths 32
200
| content
stringlengths 1
12.9M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/navigation_planning.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${DIR}/apollo_base.sh"
# run function from apollo_base.sh
# run command_name module_name
run_module planning "$@" --flagfile=modules/planning/conf/planning_navi.conf --use_navigation_mode
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/apollo_docs.sh
|
#! /usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo.bashrc"
set -e
# STAGE="${STAGE:-dev}"
: ${STAGE:=dev}
APOLLO_DOCS_CFG="${APOLLO_ROOT_DIR}/apollo.doxygen"
APOLLO_DOCS_DIR="${APOLLO_ROOT_DIR}/.cache/docs"
# APOLLO_DOCS_PORT=9527 # Unused for now
function determine_docs_dir() {
local doxygen_cfg="${APOLLO_DOCS_CFG}"
local output_dir="$(awk -F '[= ]' \
'/^OUTPUT_DIRECTORY/ {print $NF}' ${doxygen_cfg})"
if [ -z "${output_dir}" ]; then
error "Oops, OUTPUT_DIRECTORY not set in ${doxygen_cfg}"
exit 1
fi
if [[ "${output_dir}" != /* ]]; then
output_dir="${APOLLO_ROOT_DIR}/${output_dir}"
fi
APOLLO_DOCS_DIR="${output_dir}"
}
function generate_docs() {
local doxygen_cfg="${APOLLO_DOCS_CFG}"
local output_dir="${APOLLO_DOCS_DIR}"
local gendoc=true
if [ -d "${output_dir}" ]; then
local answer
echo -n "Docs directory ${output_dir} already exists. Do you want to keep it (Y/n)? "
answer=$(read_one_char_from_stdin)
echo
if [ "${answer}" == "n" ]; then
rm -rf "${output_dir}"
else
gendoc=false
fi
fi
if ! $gendoc; then
return
fi
info "Generating Apollo docs..."
local doxygen_cmd="$(command -v doxygen)"
if [ -z "${doxygen_cmd}" ]; then
error "Command 'doxygen' not found. Please install it manually."
error "On Ubuntu 18.04, this can be done by running: "
error "${TAB}sudo apt-get -y update"
error "${TAB}sudo apt-get -y install doxygen"
exit 1
fi
if [ ! -d "${output_dir}" ]; then
mkdir -p "${output_dir}"
fi
local start_time="$(get_now)"
pushd "${APOLLO_ROOT_DIR}" > /dev/null
run "${doxygen_cmd}" "${doxygen_cfg}" > /dev/null
popd > /dev/null
local elapsed="$(time_elapsed_s ${start_time})"
success "Apollo docs generated. Time taken: ${elapsed}s"
}
function clean_docs() {
if [ -d "${APOLLO_DOCS_DIR}" ]; then
rm -rf "${APOLLO_DOCS_DIR}"
success "Done cleanup apollo docs in ${APOLLO_DOCS_DIR}"
else
success "Nothing to do for empty directory '${APOLLO_DOCS_DIR}'."
fi
}
function _usage() {
info "Usage:"
info "${TAB}$0 [Options]"
info "Options:"
info "${TAB}-h|--help Show this help message and exit"
info "${TAB}clean Delete generated docs"
info "${TAB}generate Generate apollo docs"
#local doclink="http://0.0.0.0:${APOLLO_DOCS_PORT}"
#info "${TAB}start Start local apollo docs server at ${doclink}"
#info "${TAB}shutdown Shutdown local apollo docs server at ${doclink}"
exit 1
}
# TODO(all): cyber/doxy-docs
function main() {
local cmd="$1"
determine_docs_dir
case "${cmd}" in
generate)
generate_docs
;;
clean)
clean_docs
;;
# start)
# start_doc_server
# ;;
# shutdown)
# shutdown_doc_server
# ;;
-h | --help)
_usage
;;
*)
_usage
;;
esac
}
main "${@}"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/recover_gcc.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
# This script is used to recover default GCC/G++ settings on Ubuntu 18.04 only.
# TODO(all): Ubuntu 20.04 Support
sudo update-alternatives --remove-all gcc
sudo update-alternatives --remove-all g++
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-7 50
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-7 50
sudo update-alternatives --install /usr/bin/cc cc /usr/bin/gcc-7 50
sudo update-alternatives --set cc /usr/bin/gcc
sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++-7 50
sudo update-alternatives --set c++ /usr/bin/g++
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/rtk_player.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
function setup() {
bash scripts/canbus.sh start
bash scripts/gps.sh start
bash scripts/localization.sh start
bash scripts/control.sh start
}
function start() {
local rtk_player_binary
NUM_PROCESSES="$(pgrep -f "record_play/rtk_player" | grep -cv '^1$')"
if [ "${NUM_PROCESSES}" -ne 0 ]; then
pkill -SIGKILL -f rtk_player
fi
if [[ -f ${TOP_DIR}/bazel-bin/modules/tools/record_play/rtk_player ]]; then
rtk_player_binary="${TOP_DIR}/bazel-bin/modules/tools/record_play/rtk_player"
elif [[ -f /opt/apollo/neo/packages/tools-dev/latest/record_play/rtk_player ]]; then
rtk_player_binary=/opt/apollo/neo/packages/tools-dev/latest/record_play/rtk_player
else
rtk_player_binary=
fi
if [[ -z ${rtk_player_binary} ]]; then
echo "can't fine rtk_player"
exit -1
fi
${rtk_player_binary}
}
function stop() {
pkill -SIGKILL -f rtk_player
}
case $1 in
setup)
setup
;;
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
start
;;
esac
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/apollo_coverage.sh
|
#! /usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
set -e
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo.bashrc"
source "${TOP_DIR}/scripts/apollo_base.sh"
BAZEL_OUT="${TOP_DIR}/bazel-out" # $(bazel info output_path)
COVERAGE_HTML="${TOP_DIR}/.cache/coverage"
COVERAGE_DAT="${BAZEL_OUT}/_coverage/_coverage_report.dat"
# Note(storypku): branch coverage seems not work when running bazel coverage
# GENHTML_OPTIONS="--rc genhtml_branch_coverage=1 --highlight --legend"
function main() {
parse_cmdline_arguments "$@"
run_bazel "Coverage" "$@"
genhtml "${COVERAGE_DAT}" --output-directory "${COVERAGE_HTML}"
success "Done bazel coverage for ${SHORTHAND_TARGETS:-Apollo}"
info "Coverage report was generated under ${COVERAGE_HTML}"
}
main "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/plot_trace.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
${TOP_DIR}/bazel-bin/modules/tools/plot_trace/plot_trace "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/cyber_launch.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${DIR}/.."
source "${DIR}/apollo_base.sh"
function start() {
LAUNCH_FILE=$1
LOG="/apollo/data/log/$(basename ${LAUNCH_FILE}).start.log"
nohup cyber_launch start "${LAUNCH_FILE}" < /dev/null > "${LOG}" 2>&1 &
}
function stop() {
LAUNCH_FILE=$1
LOG="/apollo/data/log/$(basename ${LAUNCH_FILE}).stop.log"
nohup cyber_launch stop "${LAUNCH_FILE}" < /dev/null > "${LOG}" 2>&1 &
}
# run command_name launch_file.
function run() {
case $1 in
start)
shift
start $@
;;
stop)
shift
stop $@
;;
restart)
shift
stop $@
start $@
;;
*)
echo "Unknow command: $1"
exit 1
;;
esac
}
run "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/apollo_build.sh
|
#! /usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
set -e
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
function main() {
parse_cmdline_arguments "$@"
run_bazel "Build"
if [ -z "${SHORTHAND_TARGETS}" ]; then
SHORTHAND_TARGETS="apollo"
fi
success "Done building ${SHORTHAND_TARGETS}. Enjoy!"
}
main "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/apollo_test.sh
|
#! /usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
set -e
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo.bashrc"
source "${TOP_DIR}/scripts/apollo_base.sh"
function main() {
parse_cmdline_arguments "$@"
run_bazel "Test"
success "Done testing ${SHORTHAND_TARGETS:-Apollo}. Enjoy!"
}
main "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/monitor.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
# run_module command_name module_name
run_module monitor "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/env.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
if [ -f /.dockerenv ]; then
APOLLO_IN_DOCKER=true
else
APOLLO_IN_DOCKER=false
fi
hostname
if $APOLLO_IN_DOCKER; then
set -x
echo "Inside docker"
uname -a
pip list
else
echo "Outside docker"
set -x
uname -a
docker --version
docker images | grep apollo
fi
echo "-----------env---------------"
env
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/control.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
# run function from apollo_base.sh
run_module control "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/sensor_calibration.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${DIR}/apollo_base.sh"
function calibrate_camera_camera() {
LOG="${APOLLO_ROOT_DIR}/data/log/camera_camera_calibrator.out"
MODULE="camera_camera_calibrator"
# check if the module has started
NUM_PROCESSES="$(pgrep -f "${MODULE}" | grep -cv '^1$')"
if [ "${NUM_PROCESSES}" -eq 0 ]; then
echo "Start to calibrate Camera-Camera extrinsics, Ctrl+C to exit."
eval "${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/${MODULE} \
--flagfile=${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/conf/${MODULE}.conf \
2>&1 | tee ${LOG}"
fi
}
function calibrate_lidar_camera() {
LOG="${APOLLO_ROOT_DIR}/data/log/camera_lidar_calibrator.out"
MODULE="lidar_camera_calibrator"
# check if the module has started
NUM_PROCESSES="$(pgrep -f "${MODULE}" | grep -cv '^1$')"
if [ "${NUM_PROCESSES}" -eq 0 ]; then
echo "Start to calibrate LiDAR-Camera extrinsics, Ctrl+C to exit."
eval "${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/${MODULE} \
--flagfile=${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/conf/${MODULE}.conf \
2>&1 | tee ${LOG}"
fi
}
function calibrate_radar_camera() {
LOG="${APOLLO_ROOT_DIR}/data/log/camera_radar_calibrator.out"
MODULE="radar_camera_calibrator"
# check if the module has started
NUM_PROCESSES="$(pgrep -f "${MODULE}" | grep -cv '^1$')"
if [ "${NUM_PROCESSES}" -eq 0 ]; then
echo "Start to calibrate Radar-Camera extrinsics, Ctrl+C to exit."
eval "${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/${MODULE} \
--flagfile=${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/conf/${MODULE}.conf \
2>&1 | tee ${LOG}"
fi
}
function visualize_radar_lidar() {
LOG="${APOLLO_ROOT_DIR}/data/log/radar_lidar_visualizer.out"
MODULE="radar_lidar_visualizer"
# check if the module has started
NUM_PROCESSES="$(pgrep -f "${MODULE}" | grep -cv '^1$')"
if [ "${NUM_PROCESSES}" -eq 0 ]; then
echo "Visualize Radar and LiDAR data, Ctrl+C to exit."
eval "${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/${MODULE} \
--flagfile=${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/conf/${MODULE}.conf \
2>&1 |tee ${LOG}"
fi
}
function calibrate_imu_vehicle() {
LOG="${APOLLO_ROOT_DIR}/data/log/imu_car_calibrator.out"
MODULE="imu_car_calibrator"
# check if the module has started
NUM_PROCESSES="$(pgrep -f "${MODULE}" | grep -cv '^1$')"
if [ "${NUM_PROCESSES}" -eq 0 ]; then
echo "Start to calibrate Imu-Vehicle extrinsics, Ctrl+C to exit."
eval "${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/${MODULE} \
--flagfile=${APOLLO_ROOT_DIR}/modules/calibration/${MODULE}/conf/${MODULE}.conf \
2>&1 | tee ${LOG}"
fi
}
case $1 in
all)
calibrate_camera_camera
calibrate_lidar_camera
calibrate_radar_camera
visualize_radar_lidar
calibrate_imu_vehicle
;;
camera_camera)
calibrate_camera_camera
;;
lidar_camera)
calibrate_lidar_camera
;;
radar_camera)
calibrate_radar_camera
;;
visualize)
visualize_radar_lidar
;;
imu_vehicle)
calibrate_imu_vehicle
;;
*)
calibrate_camera_camera
calibrate_lidar_camera
calibrate_radar_camera
visualize_radar_lidar
calibrate_imu_vehicle
;;
esac
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/camera_and_video.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${DIR}/.."
source "${DIR}/apollo_base.sh"
function start() {
LOG="${APOLLO_ROOT_DIR}/data/log/camera_and_video.out"
CMD="cyber_launch start /apollo/modules/drivers/camera/launch/camera_and_video.launch"
NUM_PROCESSES=$(expr "$(pgrep -f "modules/drivers/camera/dag/camera.dag" | grep -cv '^1$')" + "$(pgrep -f "modules/drivers/video/dag/video.dag" | grep -cv '^1$')")
if [ "${NUM_PROCESSES}" -eq 0 ]; then
eval "nohup ${CMD} </dev/null >${LOG} 2>&1 &"
fi
}
function stop() {
eval "nohup cyber_launch stop /apollo/modules/drivers/camera/launch/camera_and_video.launch < /dev/null 2>&1 &"
}
# run command_name module_name
function run() {
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start_driver
sleep 2
start_compensator
;;
*)
start_driver
sleep 2
start_compensator
;;
esac
}
run "$1"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/canbus_tester.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${DIR}/.."
./bazel-bin/modules/canbus/tools/canbus_tester \
--canbus_test_file=modules/canbus/testdata/canbus_test.pb.txt
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/BUILD
|
load("//tools/install:install.bzl", "install")
package(
default_visibility = ["//visibility:public"],
)
install(
name = "install_scripts",
data = [
":apollo_base",
":bootstrap",
":bridge",
":docker_utils",
":map_generation",
":recorder",
":tools",
],
data_dest = "scripts/src",
)
install(
name = "install",
data = [":cyberfile.xml"],
data_dest = "scripts",
deps = ["install_scripts"],
)
filegroup(
name = "tools",
srcs = [
"localization_online_visualizer.sh",
"msf_simple_map_creator.sh",
"rtk_player.sh",
"rtk_recorder.sh",
"record_message.py",
"record_message.sh",
],
)
filegroup(
name = "bootstrap",
srcs = [
"bootstrap.sh",
"bootstrap_lgsvl.sh",
"dreamview.sh",
"monitor.sh",
],
)
filegroup(
name = "recorder",
srcs = [
"cyberfile.xml",
"record_bag.py",
"record_bag.sh",
],
)
filegroup(
name = "bridge",
srcs = [
"bridge.sh",
],
)
filegroup(
name = "docker_utils",
srcs = [
":docker_start_user.sh",
],
)
filegroup(
name = "map_generation",
srcs = [
":create_map_from_mobileye.sh",
":create_map_from_xy.sh",
":generate_routing_topo_graph.sh",
],
)
filegroup(
name = "apollo_base",
srcs = [
"apollo.bashrc",
"apollo_base.sh",
"common.bashrc",
],
)
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/navigation_prediction.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${DIR}/apollo_base.sh"
# run function from apollo_base.sh
# run command_name module_name
run_module prediction "$@" --flagfile=modules/prediction/conf/prediction_navi.conf
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/buildifier.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source ${TOP_DIR}/scripts/apollo.bashrc
# Ubuntu 16.04+ is required.
# Usage:
# buildifier.sh <path/to/BUILD>
# Or
# buildifier.sh <dir>
# Note(storypku): buildifier was pre-installed in our docker image.
BUILDIFIER_CMD="$(which buildifier)"
if [ -z "${BUILDIFIER_CMD}" ]; then
error "Command 'buildifier' not found in your PATH."
error "If installed, check your PATH settings."
error "If not, please refer to https://github.com/bazelbuild/buildtools" \
"on how to install it manually."
exit 1
fi
# echo "Installing buildifier..."
# go get github.com/bazelbuild/buildtools/buildifier
function _bazel_family_ext() {
local __ext
__ext="$(file_ext $1)"
for ext in "bzl" "bazel" "BUILD"; do
if [ "${ext}" == "${__ext}" ]; then
return 0
fi
done
return 1
}
# Format.
for target in "$@"; do
if [ -f "${target}" ]; then
if [ "$(basename "${target}")" = "BUILD" ] || _bazel_family_ext "${target}"; then
${BUILDIFIER_CMD} -lint=fix "${target}"
fi
elif [ -d "${target}" ]; then
#${BUILDIFIER_CMD} -r -lint=fix $@
find $@ -type f \
\( -name "BUILD" -or -name "*.BUILD" -or -name "*.bzl" -or -name "*.bazel" \) \
-exec ${BUILDIFIER_CMD} -lint=fix {} +
else
error "Bazel files or directories expected, got '${target}'"
exit 1
fi
done
ok "Done buildifier on $@."
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/record_message.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
Start apollo smart recorder.
It lists all available disks mounted under /media, and prioritize them in order:
- Disk#1. Largest NVME disk
- Disk#2. Smaller NVME disk
- ...
- Disk#x. Largest Non-NVME disk
- Disk#y. Smaller Non-NVME disk
- /apollo. If no external disks are available
Run with '--help' to see more options.
"""
import argparse
import datetime
import os
import subprocess
import sys
import psutil
from pathlib import Path
def shell_cmd(cmd, alert_on_failure=True):
"""Execute shell command and return (ret-code, stdout, stderr)."""
print('SHELL > {}'.format(cmd))
proc = subprocess.Popen(cmd, shell=True, close_fds=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ret = proc.wait()
stdout = proc.stdout.read().decode('utf-8') if proc.stdout else None
stderr = proc.stderr.read().decode('utf-8') if proc.stderr else None
if alert_on_failure and stderr and ret != 0:
sys.stderr.write('{}\n'.format(stderr))
return (ret, stdout, stderr)
class ArgManager(object):
"""Arguments manager."""
def __init__(self):
"""Init."""
self.parser = argparse.ArgumentParser(
description="Manage apollo data recording.")
self.parser.add_argument('--start', default=False, action="store_true",
help='Start recorder. It is the default '
'action if no other actions are triggered. In '
'that case, the False value is ignored.')
self.parser.add_argument('--stop', default=False, action="store_true",
help='Stop recorder.')
self._args = None
def args(self):
"""Get parsed args."""
if self._args is None:
self._args = self.parser.parse_args()
return self._args
class DiskManager(object):
"""Disk manager."""
def __init__(self):
"""Manage disks."""
disks = []
for disk in psutil.disk_partitions():
if not disk.mountpoint.startswith('/media/'):
continue
disks.append({
'mountpoint': disk.mountpoint,
'available_size': DiskManager.disk_avail_size(disk.mountpoint),
'is_nvme': disk.mountpoint.startswith('/media/apollo/internal_nvme'),
})
# Prefer NVME disks and then larger disks.
self.disks = sorted(
disks, reverse=True,
key=lambda disk: (disk['is_nvme'], disk['available_size']))
@staticmethod
def disk_avail_size(disk_path):
"""Get disk available size."""
statvfs = os.statvfs(disk_path)
return statvfs.f_frsize * statvfs.f_bavail
class Recorder(object):
"""Data recorder."""
def __init__(self, args):
"""Init."""
self.args = args
self.disk_manager = DiskManager()
def start(self):
"""Start recording."""
if Recorder.is_running():
Recorder.stop(self)
print('Another smart recorder is running, stop now.')
disks = self.disk_manager.disks
disk_to_use = disks[0]['mountpoint'] if len(disks) > 0 else '/apollo'
self.record_task(disk_to_use)
def stop(self):
"""Stop recording."""
shell_cmd('pkill --signal=SIGINT -f "smart_recorder"')
def record_task(self, disk):
"""
Save the full data into <disk>/data/bag/ReusedRecordsPool,
which will be cleared every time the smart recorder get started.
Meanwhile, restore the messages we are interested in to <disk>/data/bag/<task_id> directory.
"""
flags_package_management = False
reuse_pool_dir = os.path.join(disk, 'data', 'ReusedRecordsPool')
task_id = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
task_dir = os.path.join(disk, 'data/smart_recorder', task_id)
print('Recording bag to {}'.format(task_dir))
log_dir = '/apollo/data/log'
if not Path(log_dir).exists():
os.makedirs(log_dir, exist_ok=True)
log_file = '/apollo/data/log/smart_recorder.out'
recorder_exe = '/apollo/bazel-bin/modules/data/tools/smart_recorder/smart_recorder'
if not Path(recorder_exe).exists():
flags_package_management = True
recorder_exe = "/opt/apollo/neo/packages/apollo-data-dev/latest/bin/tools/smart_recorder/smart_recorder"
if not Path(recorder_exe).exists():
print("can't find smart_recorder! Have you installed apollo-data-dev package or built it?")
exit(-1)
if not flags_package_management:
cmd = '''
source /apollo/scripts/apollo_base.sh
source /apollo/cyber/setup.bash
nohup {} --source_records_dir={} --restored_output_dir={} > {} 2>&1 &
'''.format(recorder_exe, reuse_pool_dir, task_dir, log_file)
else:
cmd = '''
nohup {} --source_records_dir={} --restored_output_dir={} > {} 2>&1 &
'''.format(recorder_exe, reuse_pool_dir, task_dir, log_file)
shell_cmd(cmd)
@staticmethod
def is_running():
"""Test if the given process running."""
_, stdout, _ = shell_cmd('pgrep -f "smart_recorder" | grep -cv \'^1$\'', False)
# If stdout is the pgrep command itself, no such process is running.
return stdout.strip() != '1' if stdout else False
def main():
"""Main entry."""
arg_manager = ArgManager()
args = arg_manager.args()
recorder = Recorder(args)
if args.stop:
recorder.stop()
else:
recorder.start()
if __name__ == '__main__':
main()
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/racobit_radar.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${DIR}/.."
source "$DIR/apollo_base.sh"
# run function from apollo_base.sh
# run command_name module_name
run_customized_path drivers/radar/racobit_radar racobit_radar "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/msf_local_map_creator.sh
|
#! /bin/bash
if [ $# -lt 4 ]; then
echo "Usage: msf_local_map_creator.sh [pcd folder] [pose file] [zone id] [map folder]"
exit 1
fi
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${DIR}/.."
source "${DIR}/apollo_base.sh"
$APOLLO_BIN_PREFIX/modules/localization/msf/local_tool/map_creation/lossless_map_creator --use_plane_inliers_only true \
--pcd_folders $1 \
--pose_files $2 \
--map_folder $4 \
--zone_id $3 \
--coordinate_type UTM \
--map_resolution_type single
$APOLLO_BIN_PREFIX/modules/localization/msf/local_tool/map_creation/lossless_map_to_lossy_map \
--srcdir $4/lossless_map \
--dstdir $4
rm -fr $4/lossless_map
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/dump_record.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
${TOP_DIR}/bazel-bin/modules/tools/rosbag/dump_record "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/msf_record_parser.sh
|
#! /bin/bash
if [ $# -lt 1 ]; then
echo "Usage: msf_record_parser.sh [records folder] [output folder]"
exit 1
fi
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${DIR}/.."
source "${DIR}/apollo_base.sh"
GNSS_LOC_TOPIC="/apollo/localization/msf_gnss"
LIDAR_LOC_TOPIC="/apollo/localization/msf_lidar"
FUSION_LOC_TOPIC="/apollo/localization/pose"
ODOMETRY_LOC_TOPIC="/apollo/sensor/gnss/odometry"
CLOUD_TOPIC="/apollo/sensor/lidar128/compensator/PointCloud2"
GNSS_LOC_FILE="gnss_loc.txt"
LIDAR_LOC_FILE="lidar_loc.txt"
FUSION_LOC_FILE="fusion_loc.txt"
ODOMETRY_LOC_FILE="odometry_loc.txt"
IN_FOLDER=$1
OUT_FOLDER=$2
function data_exporter() {
local BAG_FILE=$1
local OUT_FOLDER=$2
$APOLLO_BIN_PREFIX/modules/localization/msf/local_tool/data_extraction/cyber_record_parser \
--bag_file $BAG_FILE \
--out_folder $OUT_FOLDER \
--cloud_topic $CLOUD_TOPIC \
--gnss_loc_topic $GNSS_LOC_TOPIC \
--lidar_loc_topic $LIDAR_LOC_TOPIC \
--fusion_loc_topic $FUSION_LOC_TOPIC \
--odometry_loc_topic $ODOMETRY_LOC_TOPIC
}
cd $IN_FOLDER
for item in $(ls -l *record.* | awk '{print $9}'); do
SEGMENTS=$(echo $item | awk -F'.' '{print NF}')
DIR_NAME=$(echo $item | cut -d . -f ${SEGMENTS})
mkdir -p $OUT_FOLDER/$DIR_NAME
data_exporter "${item}" "$OUT_FOLDER/$DIR_NAME"
done
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/apollo_format.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
# Usage:
# apollo_format.sh [options] <path/to/src/dir/or/files>
# Fail on error
set -e
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo.bashrc"
FORMAT_BAZEL=0
FORMAT_CPP=0
FORMAT_MARKDOWN=0
FORMAT_PYTHON=0
FORMAT_SHELL=0
FORMAT_ALL=0
HAS_OPTION=0
function print_usage() {
echo -e "\n${RED}Usage${NO_COLOR}:
.${BOLD}$0${NO_COLOR} [OPTION] <path/to/src/dir/or/files>"
echo -e "\n${RED}Options${NO_COLOR}:
${BLUE}-p|--python ${NO_COLOR}Format Python code
${BLUE}-b|--bazel ${NO_COLOR}Format Bazel code
${BLUE}-c|--cpp ${NO_COLOR}Format cpp code
${BLUE}-s|--shell ${NO_COLOR}Format Shell code
${BLUE}-m|--markdown ${NO_COLOR}Format Markdown file
${BLUE}-a|--all ${NO_COLOR}Format all
${BLUE}-h|--help ${NO_COLOR}Show this message and exit"
}
function run_clang_format() {
bash "${TOP_DIR}/scripts/clang_format.sh" "$@"
}
function run_buildifier() {
bash "${TOP_DIR}/scripts/buildifier.sh" "$@"
}
function run_yapf() {
bash "${TOP_DIR}/scripts/yapf.sh" "$@"
}
function run_shfmt() {
bash "${TOP_DIR}/scripts/shfmt.sh" "$@"
}
function run_prettier() {
bash "${TOP_DIR}/scripts/mdfmt.sh" "$@"
}
function run_apollo_format() {
for arg in "$@"; do
if [[ -f "${arg}" ]]; then
if c_family_ext "${arg}" || proto_ext "${arg}"; then
run_clang_format "${arg}"
elif py_ext "${arg}"; then
run_yapf "${arg}"
elif prettier_ext "${arg}"; then
run_prettier "${arg}"
elif bazel_extended "${arg}"; then
run_buildifier "${arg}"
elif bash_ext "${arg}"; then
run_shfmt "${arg}"
fi
elif [[ -d "${arg}" ]]; then
if [ "${FORMAT_BAZEL}" -eq 1 ]; then
run_buildifier "${arg}"
fi
if [ "${FORMAT_CPP}" -eq 1 ]; then
run_clang_format "${arg}"
fi
if [ "${FORMAT_PYTHON}" -eq 1 ]; then
run_yapf "${arg}"
fi
if [ "${FORMAT_SHELL}" -eq 1 ]; then
run_shfmt "${arg}"
fi
if [ "${FORMAT_MARKDOWN}" -eq 1 ]; then
run_prettier "${arg}"
fi
else
warning "Ignored ${arg} as not a regular file/directory"
fi
done
}
function main() {
if [ "$#" -eq 0 ]; then
print_usage
exit 1
fi
while [ $# -gt 0 ]; do
local opt="$1"
case "${opt}" in
-p | --python)
FORMAT_PYTHON=1
HAS_OPTION=1
shift
;;
-c | --cpp)
FORMAT_CPP=1
HAS_OPTION=1
shift
;;
-b | --bazel)
FORMAT_BAZEL=1
HAS_OPTION=1
shift
;;
-s | --shell)
FORMAT_SHELL=1
HAS_OPTION=1
shift
;;
-m | --markdown)
FORMAT_MARKDOWN=1
HAS_OPTION=1
shift
;;
-a | --all)
FORMAT_ALL=1
shift
;;
-h | --help)
print_usage
exit 1
;;
*)
if [[ "${opt}" = -* ]]; then
print_usage
exit 1
else
if [ "$HAS_OPTION" -eq 0 ]; then
FORMAT_ALL=1
fi
break
fi
;;
esac
done
if [ "${FORMAT_ALL}" -eq 1 ]; then
FORMAT_BAZEL=1
FORMAT_CPP=1
FORMAT_MARKDOWN=1
FORMAT_SHELL=1
FORMAT_PYTHON=1
fi
run_apollo_format "$@"
}
main "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/manual_light.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd $DIR/..
source "${DIR}/apollo_base.sh"
function start() {
LOG="${APOLLO_ROOT_DIR}/data/log/manual_traffic_light.out"
cyber_launch start /apollo/modules/tools/manual_traffic_light/manual_traffic_light.launch
}
# run command_name module_name
function run() {
case $1 in
start)
start
;;
*)
start
;;
esac
}
run "$1"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/command_checker.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
A plug-in that looks for similar commands when the input command has
spelling mistakes.
"""
import argparse
TAB = " " * 4
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--name', required=True)
parser.add_argument('--command', required=True)
parser.add_argument('--available', type=str)
parser.add_argument('--helpmsg', default="")
return parser
def similar_words(word):
"""
return a set with spelling1 distance alternative spellings
based on http://norvig.com/spell-correct.html
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz-_0123456789'
s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in s if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in s if len(b) > 1]
replaces = [a + c + b[1:] for a, b in s for c in alphabet if b]
inserts = [a + c + b for a, b in s for c in alphabet]
return set(deletes + transposes + replaces + inserts)
class CommandChecker(object):
def __init__(self, command, available_commands, name, help_msg=""):
self.min_len = 2
self.max_len = 256
self.command = command
self.available_commands = available_commands
self.alternative_commands = []
self.name = name
self.help_message = help_msg
def spelling_suggestions(self):
""" try to correct the spelling """
if not (self.min_len <= len(self.command) <= self.max_len):
return
for w in similar_words(self.command):
for command in self.available_commands:
if w == command:
self.alternative_commands.append(command)
def print_spelling_suggestions(self, max_alt=15):
""" print spelling suggestions """
num_alternatives = len(self.alternative_commands)
if num_alternatives > max_alt:
print(
'Error: unknown command "{}", but there are {} similar ones.'.
format(self.command, num_alternatives))
return
elif num_alternatives > 0:
print('Error: unknown command "{}" for "{}"\n'.format(
self.command, self.name))
print('Did you mean the following?')
for command in self.alternative_commands:
print('{}{}'.format(TAB * 2, command))
print('')
def advise(self):
""" give advice """
self.spelling_suggestions()
if len(self.alternative_commands) > 0:
self.print_spelling_suggestions()
else:
print('Error: unknown command "{}"\n'.format(self.command))
if len(self.help_message) > 0:
print(self.help_message)
def main():
parser = get_parser()
args = parser.parse_args()
auto_checker = CommandChecker(
args.command,
args.available.split(),
args.name,
args.helpmsg,
)
auto_checker.advise()
if __name__ == "__main__":
main()
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/navigation_control.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${DIR}/apollo_base.sh"
# run function from apollo_base.sh
# run command_name module_name
run_module control "$@" --control_conf_file=modules/control/conf/navigation_lincoln.pb.txt \
--use_navigation_mode=true
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/rtk_recorder.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
function setup() {
bash ${TOP_DIR}/scripts/canbus.sh start
bash ${TOP_DIR}/scripts/gps.sh start
bash ${TOP_DIR}/scripts/localization.sh start
bash ${TOP_DIR}/scripts/control.sh start
}
function start() {
local rtk_recorder_binary
TIME="$(date +%F_%H_%M)"
if [ -f ${TOP_DIR}/data/log/garage.csv ]; then
cp ${TOP_DIR}/data/log/garage.csv ${TOP_DIR}/data/log/garage-${TIME}.csv
fi
NUM_PROCESSES="$(pgrep -f "record_play/rtk_recorder" | grep -cv '^1$')"
if [[ -f ${TOP_DIR}/bazel-bin/modules/tools/record_play/rtk_recorder ]]; then
rtk_recorder_binary="${TOP_DIR}/bazel-bin/modules/tools/record_play/rtk_recorder"
elif [[ -f /opt/apollo/neo/packages/tools-dev/latest/record_play/rtk_recorder ]]; then
rtk_recorder_binary=/opt/apollo/neo/packages/tools-dev/latest/record_play/rtk_recorder
else
rtk_recorder_binary=
fi
if [[ -z $rtk_recorder_binary ]]; then
echo "can't fine rtk_recorder"
exit -1
fi
if [ "${NUM_PROCESSES}" -eq 0 ]; then
${rtk_recorder_binary}
fi
}
function stop() {
pkill -SIGKILL -f rtk_recorder
}
case $1 in
setup)
setup
;;
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
start
;;
esac
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/generate_proto_build_file.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2022 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
for directory in $(find modules -type d -name proto);
do
python3 scripts/proto_build_generator.py "$directory/BUILD"
done
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/realtime_plot.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
${TOP_DIR}/bazel-bin/modules/tools/realtime_plot/realtime_plot "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/generate_routing_topo_graph.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${DIR}/apollo_base.sh"
# generate routing_map.bin in map directory.
${APOLLO_BIN_PREFIX}/modules/routing/topo_creator/topo_creator \
--flagfile=modules/routing/conf/routing.conf \
$@
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/delphi_esr.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${DIR}/.."
source "$DIR/apollo_base.sh"
# run function from apollo_base.sh
# run command_name module_name
run_customized_path drivers/radar/delphi_esr delphi_esr "$@" \
--canbus_driver_name="delphi_esr"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/apollo_auto_complete.bash
|
# usage: source apollo_auto_complete.bash
COMMANDS="config build build_dbg build_opt build_cpu build_gpu build_opt_gpu test coverage lint \
buildify check build_fe build_teleop build_prof doc clean format usage -h --help"
MODULES="$(find /apollo/modules/* -maxdepth 0 -type d -printf "%f ")"
MODULES="cyber ${MODULES}"
function _complete_apollo_func() {
COMPREPLY=()
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD - 1]}"
local cmds="$(echo ${COMMANDS} | xargs)"
local modules="$(echo ${MODULES} | xargs)"
if [ "${COMP_CWORD}" -eq 1 ]; then
COMPREPLY=($(compgen -W "${cmds}" -- ${cur}))
elif [ "${COMP_CWORD}" -eq 2 ]; then
case "${prev}" in
build | build_dbg | build_opt | build_cpu | build_gpu | test | coverage)
COMPREPLY=($(compgen -W "${modules}" -- ${cur}))
;;
config)
COMPREPLY=($(compgen -W "--interactive --noninteractive --help" -- ${cur}))
;;
clean)
COMPREPLY=($(compgen -W "--bazel --core --log --expunge --all --help" -- ${cur}))
;;
lint)
COMPREPLY=($(compgen -W "--py --sh --cpp --all --help" -- ${cur}))
;;
format)
COMPREPLY=($(compgen -W "--python --bazel --cpp --shell --markdown --all --help" -- ${cur}))
;;
esac
fi
}
complete -F _complete_apollo_func -o default apollo.sh
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/filter_small_channels.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
#
# Use after "apollo.sh build":
# ./filter_small_channels.sh <input_record> <output_record>
#
# The output_record will only contain channels with small data.
INPUT_RECORD=$1
OUTPUT_RECORD=$2
source "$(dirname "${BASH_SOURCE[0]}")/apollo_base.sh"
mkdir -p "$(dirname "${OUTPUT_RECORD}")"
cyber_recorder split -f "${INPUT_RECORD}" -o "${OUTPUT_RECORD}" \
-c "/apollo/canbus/chassis" \
-c "/apollo/canbus/chassis_detail" \
-c "/apollo/control" \
-c "/apollo/control/pad" \
-c "/apollo/drive_event" \
-c "/apollo/guardian" \
-c "/apollo/localization/pose" \
-c "/apollo/localization/msf_gnss" \
-c "/apollo/localization/msf_lidar" \
-c "/apollo/localization/msf_status" \
-c "/apollo/hmi/status" \
-c "/apollo/monitor" \
-c "/apollo/monitor/system_status" \
-c "/apollo/navigation" \
-c "/apollo/perception/obstacles" \
-c "/apollo/perception/traffic_light" \
-c "/apollo/planning" \
-c "/apollo/prediction" \
-c "/apollo/relative_map" \
-c "/apollo/routing_request" \
-c "/apollo/routing_response" \
-c "/apollo/routing_response_history" \
-c "/apollo/sensor/conti_radar" \
-c "/apollo/sensor/delphi_esr" \
-c "/apollo/sensor/gnss/best_pose" \
-c "/apollo/sensor/gnss/corrected_imu" \
-c "/apollo/sensor/gnss/gnss_status" \
-c "/apollo/sensor/gnss/imu" \
-c "/apollo/sensor/gnss/ins_stat" \
-c "/apollo/sensor/gnss/odometry" \
-c "/apollo/sensor/gnss/raw_data" \
-c "/apollo/sensor/gnss/rtk_eph" \
-c "/apollo/sensor/gnss/rtk_obs" \
-c "/apollo/sensor/mobileye" \
-c "/tf" \
-c "/tf_static"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/bridge.sh
|
#!/usr/bin/env bash
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
${TOP_DIR}/bazel-bin/modules/contrib/cyber_bridge/cyber_bridge
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/dreamview.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
. "${TOP_DIR}/scripts/apollo_base.sh"
# run_module command_name module_name
run_module dreamview "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/conti_radar.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${DIR}/.."
source "$DIR/apollo_base.sh"
# run function from apollo_base.sh
# run command_name module_name
run_customized_path drivers/radar/conti_radar conti_radar "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/apollo_ci.sh
|
#! /usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
set -e
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo.bashrc"
source "${TOP_DIR}/scripts/apollo_base.sh"
ARCH="$(uname -m)"
: ${USE_ESD_CAN:=false}
APOLLO_BUILD_SH="${APOLLO_ROOT_DIR}/scripts/apollo_build.sh"
APOLLO_TEST_SH="${APOLLO_ROOT_DIR}/scripts/apollo_test.sh"
APOLLO_LINT_SH="${APOLLO_ROOT_DIR}/scripts/apollo_lint.sh"
function run_ci_build() {
env USE_ESD_CAN=${USE_ESD_CAN} bash "${APOLLO_BUILD_SH}"
}
function run_ci_test() {
env USE_ESD_CAN=${USE_ESD_CAN} bash "${APOLLO_TEST_SH}" --config=unit_test
}
function run_ci_lint() {
env USE_ESD_CAN=${USE_ESD_CAN} bash "${APOLLO_LINT_SH}" --cpp
}
function main() {
local cmd="$1"
if [ -z "${cmd}" ]; then
cmd="ALL"
info "Running ALL ..."
run_ci_lint
run_ci_build
run_ci_test
elif [ "${cmd}" == "test" ]; then
info "Running CI Test ..."
run_ci_test
elif [ "${cmd}" == "build" ]; then
info "Running CI Build ..."
run_ci_build
elif [ "${cmd}" == "lint" ]; then
info "Running CI Lint ..."
run_ci_lint
fi
success "ci ${cmd} finished."
}
main "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/scripts/drive_event.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
${TOP_DIR}/bazel-bin/modules/tools/rosbag/drive_event "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/.teamcity/pull_request.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
usage: pull_request.py files pull_id
pull_request.py diff pull_id
"""
import argparse
import os
from github import Github
token = os.getenv('GITHUB_API_TOKEN')
def get_pull(pull_id):
"""
Args:
pull_id (int): Pull id.
Returns:
github.PullRequest.PullRequest
"""
github = Github(token, timeout=30)
repo = github.get_repo('ApolloAuto/apollo')
pull = repo.get_pull(pull_id)
return pull
def get_files(args):
"""
Args:
args (argparse.ArgumentParser().parse_args()): Arguments.
Returns:
None.
"""
pull = get_pull(args.pull_id)
for file in pull.get_files():
if file.filename.startswith('modules/perception/') or \
file.filename.startswith('modules/drivers/canbus/can_client/esd') or \
file.filename.startswith('modules/localization/msf')or \
file.filename.startswith('modules/planning/learning_based') or \
file.filename.startswith('modules/map/pnc_map:cuda_util_test') or \
file.filename.endswith('.sh'):
continue
else:
print(file.filename)
def diff(args):
"""
Args:
args (argparse.ArgumentParser().parse_args()): Arguments.
Returns:
None.
"""
pull = get_pull(args.pull_id)
for file in pull.get_files():
if file.filename.startswith('modules/perception/') or \
file.filename.startswith('modules/drivers/canbus/can_client/esd') or \
file.filename.startswith('modules/localization/msf')or \
file.filename.startswith('modules/planning/learning_based')or \
file.filename.startswith('modules/map/pnc_map:cuda_util_test')or \
file.filename.endswith('.sh'):
continue
else:
print('+++ {}'.format(file.filename))
print(file.patch)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
files_parser = subparsers.add_parser('files')
files_parser.add_argument('pull_id', type=int)
files_parser.set_defaults(func=get_files)
diff_parser = subparsers.add_parser('diff')
diff_parser.add_argument('pull_id', type=int)
diff_parser.set_defaults(func=diff)
args = parser.parse_args()
args.func(args)
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/.teamcity/run_ci.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
APOLLO_ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
source "${APOLLO_ROOT_DIR}/scripts/apollo.bashrc"
CACHE_ROOT_DIR="${APOLLO_ROOT_DIR}/.cache"
DOCKER_REPO="apolloauto/apollo"
DEV_INSIDE="in-dev-docker"
HOST_ARCH="$(uname -m)"
TARGET_ARCH="$(uname -m)"
DOCKER_RUN="docker run"
FAST_MODE="no"
USE_GPU_HOST=0
VOLUME_VERSION="latest"
MAP_VOLUME_CONF=
OTHER_VOLUME_CONF=
DEFAULT_MAPS=(
sunnyvale_big_loop
sunnyvale_loop
sunnyvale_with_two_offices
san_mateo
)
DEFAULT_TEST_MAPS=(
sunnyvale_big_loop
sunnyvale_loop
)
eval $(grep ^VERSION_X86_64= ${APOLLO_ROOT_DIR}/docker/scripts/dev_start.sh)
eval $(grep ^VERSION_AARCH64= ${APOLLO_ROOT_DIR}/docker/scripts/dev_start.sh)
function parse_arguments() {
while [ $# -gt 0 ]; do
local opt="$1"
shift
case "${opt}" in
-f | --fast)
FAST_MODE="yes"
;;
*)
warning "Unknown option: ${opt}"
exit 2
;;
esac
done # End while loop
}
function determine_dev_image() {
local version=""
if [ "${TARGET_ARCH}" = "x86_64" ]; then
version="${VERSION_X86_64}"
elif [ "${TARGET_ARCH}" = "aarch64" ]; then
version="${VERSION_AARCH64}"
else
error "Logic can't reach here! Please file an issue to Apollo GitHub."
exit 3
fi
APOLLO_DEV_IMAGE="${DOCKER_REPO}:${version}"
}
function check_host_environment() {
local kernel="$(uname -s)"
if [ "${kernel}" != "Linux" ]; then
warning "Running Apollo dev container on ${kernel} is UNTESTED, exiting..."
exit 1
fi
}
function setup_devices_and_mount_local_volumes() {
local __retval="$1"
[ -d "${CACHE_ROOT_DIR}" ] || mkdir -p "${CACHE_ROOT_DIR}"
source "${APOLLO_ROOT_DIR}/scripts/apollo_base.sh"
setup_device
local volumes="-v $APOLLO_ROOT_DIR:/apollo"
local os_release="$(lsb_release -rs)"
case "${os_release}" in
16.04)
warning "[Deprecated] Support for Ubuntu 16.04 will be removed" \
"in the near future. Please upgrade to ubuntu 18.04+."
volumes="${volumes} -v /dev:/dev"
;;
18.04 | 20.04 | *)
volumes="${volumes} -v /dev:/dev"
;;
esac
volumes="${volumes} -v /media:/media \
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
-v /etc/localtime:/etc/localtime:ro \
-v /usr/src:/usr/src \
-v /lib/modules:/lib/modules"
volumes="$(tr -s " " <<<"${volumes}")"
eval "${__retval}='${volumes}'"
}
function determine_gpu_use_host() {
if [ "${HOST_ARCH}" = "aarch64" ]; then
if lsmod | grep -q "^nvgpu"; then
USE_GPU_HOST=1
fi
else
# Check nvidia-driver and GPU device
local nv_driver="nvidia-smi"
if [ ! -x "$(command -v ${nv_driver})" ]; then
warning "No nvidia-driver found. CPU will be used"
elif [ -z "$(eval ${nv_driver})" ]; then
warning "No GPU device found. CPU will be used."
else
USE_GPU_HOST=1
fi
fi
# Try to use GPU inside container
local nv_docker_doc="https://github.com/NVIDIA/nvidia-docker/blob/master/README.md"
if [ ${USE_GPU_HOST} -eq 1 ]; then
DOCKER_VERSION=$(docker version --format '{{.Server.Version}}')
if [ ! -z "$(which nvidia-docker)" ]; then
DOCKER_RUN="nvidia-docker run"
elif [ ! -z "$(which nvidia-container-toolkit)" ]; then
if dpkg --compare-versions "${DOCKER_VERSION}" "ge" "19.03"; then
DOCKER_RUN="docker run --gpus all"
else
warning "You must upgrade to docker-ce 19.03+ to access GPU from container!"
USE_GPU_HOST=0
fi
else
USE_GPU_HOST=0
warning "Cannot access GPU from within container. Please install " \
"latest Docker and nvidia-container-toolkit as described by: "
warning " ${nv_docker_doc}"
fi
fi
}
function docker_pull() {
local img="$1"
info "Start pulling docker image ${img} ..."
if ! docker pull "${img}"; then
error "Failed to pull docker image : ${img}"
exit 1
fi
}
# Note(storypku): Reuse existing docker volumes for CI
function reuse_or_start_volume() {
local container="$1"
if docker ps --format "{{.Names}}" | grep -q "${container}"; then
info "Found existing volume \"${container}\", will be reused."
return
fi
local image="$2"
docker_pull "${image}"
docker run -id --rm --name "${container}" "${image}"
}
function start_map_volume() {
local map_name="$1"
local map_version="$2"
local map_volume="apollo_map_volume-${map_name}_${USER}"
if [[ ${MAP_VOLUME_CONF} == *"${map_volume}"* ]]; then
info "Map ${map_name} has already been included."
else
local map_image=
if [ "${TARGET_ARCH}" = "aarch64" ]; then
map_image="${DOCKER_REPO}:map_volume-${map_name}-${TARGET_ARCH}-${map_version}"
else
map_image="${DOCKER_REPO}:map_volume-${map_name}-${map_version}"
fi
info "Load map ${map_name} from image: ${map_image}"
reuse_or_start_volume "${map_volume}" "${map_image}"
MAP_VOLUME_CONF="${MAP_VOLUME_CONF} --volumes-from ${map_volume}"
fi
}
function mount_map_volumes() {
info "Starting mounting map volumes ..."
if [ "$FAST_MODE" = "no" ]; then
for map_name in ${DEFAULT_MAPS[@]}; do
start_map_volume "${map_name}" "${VOLUME_VERSION}"
done
else
for map_name in ${DEFAULT_TEST_MAPS[@]}; do
start_map_volume "${map_name}" "${VOLUME_VERSION}"
done
fi
}
function mount_other_volumes() {
info "Mount other volumes ..."
local volume_conf=
# AUDIO
local audio_volume="apollo_audio_volume_${USER}"
local audio_image="${DOCKER_REPO}:data_volume-audio_model-${TARGET_ARCH}-latest"
reuse_or_start_volume "${audio_volume}" "${audio_image}"
volume_conf="${volume_conf} --volumes-from ${audio_volume}"
# YOLOV4
local yolov4_volume="apollo_yolov4_volume_${USER}"
local yolov4_image="${DOCKER_REPO}:yolov4_volume-emergency_detection_model-${TARGET_ARCH}-latest"
reuse_or_start_volume "${yolov4_volume}" "${yolov4_image}"
volume_conf="${volume_conf} --volumes-from ${yolov4_volume}"
# FASTER_RCNN
local faster_rcnn_volume="apollo_faster_rcnn_volume_${USER}"
local faster_rcnn_image="${DOCKER_REPO}:faster_rcnn_volume-traffic_light_detection_model-${TARGET_ARCH}-latest"
reuse_or_start_volume "${faster_rcnn_volume}" "${faster_rcnn_image}"
volume_conf="${volume_conf} --volumes-from ${faster_rcnn_volume}"
# SMOKE
if [[ "${TARGET_ARCH}" == "x86_64" ]]; then
local smoke_volume="apollo_smoke_volume_${USER}"
local smoke_image="${DOCKER_REPO}:smoke_volume-yolo_obstacle_detection_model-${TARGET_ARCH}-latest"
reuse_or_start_volume "${smoke_volume}" "${smoke_image}"
volume_conf="${volume_conf} --volumes-from ${smoke_volume}"
fi
OTHER_VOLUME_CONF="${volume_conf}"
}
function main() {
check_host_environment
parse_arguments "$@"
determine_dev_image
if ! docker_pull "${APOLLO_DEV_IMAGE}"; then
error "Failed to pull docker image."
exit 1
fi
info "Determine whether host GPU is available ..."
determine_gpu_use_host
info "USE_GPU_HOST: ${USE_GPU_HOST}"
local local_host="$(hostname)"
local local_volumes=
setup_devices_and_mount_local_volumes local_volumes
mount_map_volumes
mount_other_volumes
set -x
${DOCKER_RUN} -i --rm \
--privileged \
-e NVIDIA_VISIBLE_DEVICES=all \
-e NVIDIA_DRIVER_CAPABILITIES=compute,video,graphics,utility \
-e DOCKER_IMG="${APOLLO_DEV_IMAGE}" \
-e USE_GPU_HOST="${USE_GPU_HOST}" \
${MAP_VOLUME_CONF} \
${OTHER_VOLUME_CONF} \
${local_volumes} \
--net host \
-w /apollo \
--add-host "${DEV_INSIDE}:127.0.0.1" \
--add-host "${local_host}:127.0.0.1" \
--hostname "${DEV_INSIDE}" \
--shm-size 2G \
--pid=host \
-v /dev/null:/dev/raw1394 \
"${APOLLO_DEV_IMAGE}" \
/bin/bash /apollo/scripts/apollo_ci.sh
if [ $? -ne 0 ]; then
error "CI failed based on image: ${APOLLO_DEV_IMAGE}"
exit 1
fi
set +x
ok "CI success based on image: ${APOLLO_DEV_IMAGE}"
}
main "$@"
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/.teamcity/coverage_lines.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
usage: coverage_lines.py info_file expected
"""
import os
import sys
def get_lines(info_file):
"""
Args:
info_file (str): File generated by lcov.
Returns:
float: Coverage rate.
"""
hits = .0
total = .0
with open(info_file) as info_file:
for line in info_file:
line = line.strip()
if not line.startswith('DA:'):
continue
line = line[3:]
print(line)
total += 1
if int(line.split(',')[1]) > 0:
hits += 1
if total == 0:
print('no data found')
exit()
return hits / total
if __name__ == '__main__':
if len(sys.argv) < 3:
exit()
info_file = sys.argv[1]
expected = float(sys.argv[2])
if not os.path.isfile(info_file):
print('info file {} is not exists, ignored'.format(info_file))
exit()
actual = get_lines(info_file)
actual = round(actual, 3)
if actual < expected:
print('expected >= {} %, actual {} %, failed'.format(
round(expected * 100, 1), round(actual * 100, 1)))
exit(1)
print('expected >= {} %, actual {} %, passed'.format(
round(expected * 100, 1), round(actual * 100, 1)))
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/.teamcity/coverage_diff.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
usage: coverage_diff.py info_file diff_file > > coverage-diff.info
"""
import sys
def get_diff_file_lines(diff_file):
"""
Args:
diff_file (str): File to get modified lines.
Returns:
dict: The diff lines of files.
"""
diff_file_lines = {}
current_file = None
current_line = -1
with open(diff_file) as diff_file:
for line in diff_file:
line = line.strip()
if line.startswith('+++ '):
current_file = line.lstrip('+++ ')
diff_file_lines[current_file] = []
continue
elif line.startswith('@@ '):
current_line = line.split()[2]
current_line = current_line.lstrip('+').split(',')[0]
current_line = int(current_line)
continue
elif line.startswith('-'):
continue
elif line.startswith('+'):
diff_file_lines[current_file].append(current_line)
current_line += 1
return diff_file_lines
def get_info_file_lines(info_file, diff_file):
"""
Args:
info_file (str): File generated by lcov.
diff_file (str): File to get modified lines.
Returns:
None
"""
diff_file_lines = get_diff_file_lines(diff_file)
current_lines = []
current_lf = 0
current_lh = 0
with open(info_file) as info_file:
for line in info_file:
line = line.strip()
if line.startswith('SF:'):
current_file = line.lstrip('SF:')
if current_file.startswith('/apollo/'):
current_file = current_file[len('/apollo/'):]
current_lines = diff_file_lines.get(current_file, [])
elif line.startswith('DA:'):
da = line.lstrip('DA:').split(',')
if int(da[0]) in current_lines:
current_lf += 1
if not line.endswith(',0'):
current_lh += 1
print(line)
continue
elif line.startswith('LF:'):
print('LF:{}'.format(current_lf))
continue
elif line.startswith('LH:'):
print('LH:{}'.format(current_lh))
continue
print(line)
if __name__ == '__main__':
if len(sys.argv) < 3:
exit()
info_file = sys.argv[1]
diff_file = sys.argv[2]
get_info_file_lines(info_file, diff_file)
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/tools/cyberfile.xml
|
<package format="2">
<name>tools</name>
<version>local</version>
<description>
The tools are mostly written in Python and relying on compiled proto modules. So
generally you need to do the following steps to make it function well.
</description>
<maintainer email="apollo-support@baidu.com">Apollo</maintainer>
<license>Apache License 2.0</license>
<url type="website">https://www.apollo.auto/</url>
<url type="repository">https://github.com/ApolloAuto/apollo</url>
<url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url>
<type>module</type>
<src_path url="https://github.com/ApolloAuto/apollo">//modules/tools</src_path>
</package>
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/tools/README.md
|
# Apollo Tools
## Prerequisites
The tools are mostly written in Python and relying on compiled proto modules. So
generally you need to do the following steps to make it function well.
`Note that all scripts in this page are referenced from Apollo root directory.`
```bash
# Compile everything including python proto libs.
apollo.sh build
# Setup PYTHONPATH properly.
source scripts/apollo_base.sh
```
## Highlight Tools
* Diagnostics
`shortcuts: scripts/diagnostics.sh`
Display input/output protobuf messages for modules.
* Plot_control
Subscribe control command message and plot recent x steering, throttle, and
brake values.
* Realtime_plot
`shortcuts: scripts/realtime_plot.sh`
Subscribe planning & control messages and plot real time trajectory, speed,
curvature/ST-graph, and acceleration/heading.
* Record_play
* Rtk_recorder
`shortcuts: scripts/run_rtk_recorder.sh`
Record vehicle trajectory and save it into a file.
* Rtk_player
`shortcuts: scripts/run_rtk_player.sh`
Read recorded trajectory and publish it as a planning trajectory.
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/tools/tools.BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "tools",
includes = ["include"],
hdrs = glob(["include/**/*.h"]),
srcs = glob(["lib/**/*.so*"]),
include_prefix = "modules/tools",
strip_include_prefix = "include",
visibility = ["//visibility:public"],
)
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/tools/BUILD
|
load("//tools/install:install.bzl", "install", "install_files", "install_src_files")
package(
default_visibility = ["//visibility:public"],
)
# install(
# name = "install",
# data_dest = "tools",
# data = [
# "//modules/tools/common:py_files",
# "//modules/tools/create_map:py_files",
# "//modules/tools/map_gen:py_files",
# "//modules/tools/record_play:py_files",
# "//modules/tools/sensor_calibration:runtime_files",
# "//modules/tools/vehicle_calibration:runtime_files",
# ":cyberfile.xml",
# ":tools.BUILD",
# ],
# rename = {
# "modules/tools/sensor_calibration/extract_data.py": "extract_data",
# "modules/tools/record_play/rtk_recorder.py": "rtk_recorder",
# "modules/tools/record_play/rtk_player.py": "rtk_player",
# "modules/tools/vehicle_calibration/preprocess.py": "preprocess",
# },
# deps = [
# ":pb_tools",
# ":pb_hdrs",
# "//modules/tools/visualizer:install",
# "//modules/tools/manual_traffic_light:install",
# "//modules/tools/prediction/fake_prediction:install",
# ],
# )
install(
name = "pb_hdrs",
data_dest = "tools/include",
data = [
"//modules/tools/navigator/dbmap/proto:dbmap_cc_proto",
"//modules/tools/prediction/data_pipelines/proto:cruise_model_cc_proto",
"//modules/tools/prediction/data_pipelines/proto:fnn_model_cc_proto",
"//modules/tools/sensor_calibration/proto:extractor_config_cc_proto",
],
)
# install_files(
# name = "pb_tools",
# dest = "tools",
# files = [
# "//modules/tools/sensor_calibration/proto:extractor_config_py_pb2",
# ],
# )
install(
name = "install",
deps = [
"//modules/tools/control_info:install",
"//modules/tools/create_map:install",
"//modules/tools/dump_gpsbin:install",
"//modules/tools/gen_vehicle_protocol:install",
"//modules/tools/localization:install",
"//modules/tools/manual_traffic_light:install",
"//modules/tools/map_datachecker:install",
"//modules/tools/map_gen:install",
"//modules/tools/mapshow:install",
"//modules/tools/mapviewers:install",
"//modules/tools/mock_routing:install",
"//modules/tools/navigation:install",
"//modules/tools/open_space_visualization:install",
"//modules/tools/perception:install",
"//modules/tools/planning/plot_trajectory:install",
"//modules/tools/plot_control:install",
"//modules/tools/plot_planning:install",
"//modules/tools/plot_trace:install",
"//modules/tools/realtime_plot:install",
"//modules/tools/record_analyzer:install",
"//modules/tools/record_parse_save:install",
"//modules/tools/record_play:install",
"//modules/tools/replay:install",
"//modules/tools/restore_video_record:install",
"//modules/tools/rosbag:install",
"//modules/tools/routing:install",
"//modules/tools/sensor_calibration:install",
"//modules/tools/vehicle_calibration:install",
"//modules/tools/visualizer:install",
":pb_hdrs"
],
data = [
":cyberfile.xml",
":tools.BUILD"
],
data_dest = "tools",
)
install_src_files(
name = "install_src",
deps = [
":install_tools_src",
":install_tools_py"
],
)
install_src_files(
name = "install_tools_src",
src_dir = ["."],
dest = "tools/src",
filter = "*",
)
install_src_files(
name = "install_tools_py",
src_dir = ["."],
dest = "tools/python/modules/tools",
filter = "*.py",
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/gen_vehicle_controller_and_manager.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
# -*- coding:utf-8 -*-
import datetime
import os
import shutil
import sys
import yaml
def gen_vehicle_controller_header(content, output_dir):
controller_header_tpl_file = "template/controller.h.tpl"
car_type = content["car_type"]
with open(controller_header_tpl_file, 'r') as tpl:
fmt = tpl.readlines()
controller_header_file = output_dir + (
"%s_controller.h" % content["car_type"].lower())
with open(controller_header_file, 'w') as header:
FMT = "".join(fmt)
fmt_val = {}
fmt_val["car_type_lower"] = car_type
fmt_val["car_type_upper"] = car_type.upper()
fmt_val["car_type_cap"] = car_type.capitalize()
control_protocol_include_list = []
control_protocol_include_fmt = "#include \"modules/canbus/vehicle/%s/protocol/%s.h\""
control_protocol_ptr_list = []
control_protocol_ptr_fmt = " %s* %s_ = nullptr;"
protocols = content["protocols"]
for pid in protocols:
p = protocols[pid]
if p["protocol_type"] == "control":
name = p["name"]
include = control_protocol_include_fmt % (car_type.lower(),
name.lower())
control_protocol_include_list.append(include)
var_classname = name.replace('_', '').capitalize()
var_ptr = control_protocol_ptr_fmt % (var_classname, name)
control_protocol_ptr_list.append(var_ptr)
control_protocol_include_list.sort()
control_protocol_ptr_list.sort()
fmt_val["control_protocol_include_list"] = "\n".join(
control_protocol_include_list)
fmt_val["control_protocol_ptr_list"] = "\n".join(
control_protocol_ptr_list)
header.write(FMT % fmt_val)
def gen_vehicle_controller_cpp(content, output_dir):
controller_cpp_tpl_file = "template/controller.cc.tpl"
with open(controller_cpp_tpl_file, 'r') as tpl:
fmt = tpl.readlines()
car_type = content["car_type"]
controller_cpp_file = output_dir + ("%s_controller.cc" % car_type.lower())
with open(controller_cpp_file, 'w') as cpp:
FMT = "".join(fmt)
fmt_val = {}
fmt_val["car_type_lower"] = car_type.lower()
fmt_val["car_type_cap"] = car_type.capitalize()
protocol_ptr_get_list = []
protocol_ptr_get_fmt = """ %(var_name)s_ = dynamic_cast<%(class_name)s*>
(message_manager_->GetMutableProtocolDataById(%(class_name)s::ID));
if (%(var_name)s_ == nullptr) {
AERROR << "%(class_name)s does not exist in the %(car_type)sMessageManager!";
return ErrorCode::CANBUS_ERROR;
}
"""
protocol_add_list = []
protocol_add_fmt = " can_sender_->AddMessage(%s::ID, %s_, false);"
protocols = content["protocols"]
for pid in protocols:
p = protocols[pid]
if p["protocol_type"] == "control":
var_name = p["name"].lower()
class_name = p["name"].replace('_', '').capitalize()
ptr_get_fmt_val = {}
ptr_get_fmt_val["var_name"] = var_name
ptr_get_fmt_val["class_name"] = class_name
ptr_get_fmt_val["car_type"] = car_type.capitalize()
ptr_get = protocol_ptr_get_fmt % ptr_get_fmt_val
protocol_ptr_get_list.append(ptr_get)
protocol_add = protocol_add_fmt % (class_name, var_name)
protocol_add_list.append(protocol_add)
protocol_ptr_get_list.sort()
protocol_add_list.sort()
fmt_val["protocol_ptr_get_list"] = "\n".join(protocol_ptr_get_list)
fmt_val["protocol_add_list"] = "\n".join(protocol_add_list)
cpp.write(FMT % fmt_val)
def gen_message_manager_header(content, output_dir):
message_manager_header_tpl_file = "template/message_manager.h.tpl"
with open(message_manager_header_tpl_file, 'r') as tpl:
fmt = tpl.readlines()
car_type = content["car_type"]
message_manager_header_file = output_dir + (
"%s_message_manager.h" % car_type.lower())
with open(message_manager_header_file, 'w') as header:
FMT = "".join(fmt)
fmt_val = {}
fmt_val["car_type_namespace"] = car_type.lower()
fmt_val["car_type_cap"] = car_type.capitalize()
fmt_val["car_type_up"] = car_type.upper()
header.write(FMT % fmt_val)
def gen_message_manager_cpp(content, output_dir):
message_manager_cpp_tpl_file = "template/message_manager.cc.tpl"
with open(message_manager_cpp_tpl_file, 'r') as tpl:
fmt = tpl.readlines()
car_type = content["car_type"]
message_manager_cpp_file = output_dir + (
"%s_message_manager.cc" % car_type.lower())
with open(message_manager_cpp_file, 'w') as cpp:
FMT = "".join(fmt)
fmt_val = {}
fmt_val["car_type_lower"] = car_type.lower()
fmt_val["car_type_cap"] = car_type.capitalize()
protocols = content["protocols"]
control_header_list = []
report_header_list = []
header_fmt = "#include \"modules/canbus/vehicle/%s/protocol/%s.h\""
control_add_list = []
report_add_list = []
add_fmt = " Add%sProtocolData<%s, true>();"
for p_name in protocols:
p = protocols[p_name]
var_name = "%s" % p["name"].lower()
class_name = p["name"].replace('_', '').capitalize()
header = header_fmt % (car_type.lower(), var_name)
if p["protocol_type"] == "control":
control_header_list.append(header)
item = add_fmt % ("Send", class_name)
control_add_list.append(item)
elif p["protocol_type"] == "report":
report_header_list.append(header)
item = add_fmt % ("Recv", class_name)
report_add_list.append(item)
control_header_list.sort()
report_header_list.sort()
control_add_list.sort()
report_add_list.sort()
fmt_val["control_header_list"] = "\n".join(control_header_list)
fmt_val["report_header_list"] = "\n".join(report_header_list)
fmt_val["control_add_list"] = "\n".join(control_add_list)
fmt_val["report_add_list"] = "\n".join(report_add_list)
cpp.write(FMT % fmt_val)
def gen_vehicle_factory_header(content, output_dir):
vehicle_factory_header_tpl_file = "template/vehicle_factory.h.tpl"
with open(vehicle_factory_header_tpl_file, 'r') as tpl:
fmt = tpl.readlines()
car_type = content["car_type"]
vehicle_factory_header_file = output_dir + (
"%s_vehicle_factory.h" % car_type.lower())
with open(vehicle_factory_header_file, 'w') as header:
FMT = "".join(fmt)
fmt_val = {}
fmt_val["car_type_cap"] = car_type.capitalize()
fmt_val["car_type_upper"] = car_type.upper()
fmt_val["car_type_lower"] = car_type.lower()
header.write(FMT % fmt_val)
def gen_vehicle_factory_cpp(content, output_dir):
vehicle_factory_cpp_tpl_file = "template/vehicle_factory.cc.tpl"
with open(vehicle_factory_cpp_tpl_file, 'r') as tpl:
fmt = tpl.readlines()
car_type = content["car_type"]
vehicle_factory_cpp_file = output_dir + (
"%s_vehicle_factory.cc" % car_type.lower())
with open(vehicle_factory_cpp_file, 'w') as cpp:
FMT = "".join(fmt)
fmt_val = {}
fmt_val["car_type_lower"] = car_type.lower()
fmt_val["car_type_cap"] = car_type.capitalize()
fmt_val["car_type_upper"] = car_type.upper()
cpp.write(FMT % fmt_val)
def gen_build_file(content, output_dir):
build_tpl_file = "template/controller_manager_BUILD.tpl"
with open(build_tpl_file, 'r') as tpl:
fmt = tpl.readlines()
car_type = content["car_type"]
build_file = output_dir + "BUILD"
with open(build_file, 'w') as fp:
FMT = "".join(fmt)
fmt_val = {}
fmt_val["car_type_lower"] = car_type.lower()
fp.write(FMT % fmt_val)
def gen_vehicle_controller_and_manager(config_file, output_dir):
print("Generating controller and manager")
with open(config_file, 'r') as fp:
content = yaml.safe_load(fp)
gen_vehicle_controller_header(content, output_dir)
gen_vehicle_controller_cpp(content, output_dir)
gen_message_manager_header(content, output_dir)
gen_message_manager_cpp(content, output_dir)
gen_vehicle_factory_header(content, output_dir)
gen_vehicle_factory_cpp(content, output_dir)
gen_build_file(content, output_dir)
if __name__ == "__main__":
if len(sys.argv) != 2:
print('Usage: python %s some_config.yml' % sys.argv[0])
sys.exit(0)
with open(sys.argv[1], 'r') as fp:
conf = yaml.safe_load(fp)
protocol_conf = conf["protocol_conf"]
output_dir = conf["output_dir"] + "vehicle/" + conf["car_type"].lower() + \
"/"
shutil.rmtree(output_dir, True)
os.makedirs(output_dir)
gen_vehicle_controller_and_manager(protocol_conf, output_dir)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/gen.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
# -*- coding:utf-8 -*-
import datetime
import os
import shutil
import sys
import yaml
from modules.tools.gen_vehicle_protocol.gen_proto_file import gen_proto_file
from modules.tools.gen_vehicle_protocol.gen_protocols import gen_protocols
from modules.tools.gen_vehicle_protocol.gen_vehicle_controller_and_manager import gen_vehicle_controller_and_manager
from modules.tools.gen_vehicle_protocol.extract_dbc_meta import extract_dbc_meta
def gen(conf):
"""
doc string:
"""
dbc_file = conf["dbc_file"]
protocol_conf_file = conf["protocol_conf"]
car_type = conf["car_type"]
black_list = conf["black_list"]
sender_list = conf["sender_list"]
sender = conf["sender"]
output_dir = conf["output_dir"]
# extract dbc file meta to an internal config file
if not extract_dbc_meta(dbc_file, protocol_conf_file, car_type, black_list,
sender_list, sender):
return
# gen proto
proto_dir = output_dir + "proto/"
gen_proto_file(protocol_conf_file, proto_dir)
# gen protocol
protocol_dir = output_dir + "vehicle/" + car_type.lower() + "/protocol/"
gen_protocols(protocol_conf_file, protocol_dir)
# gen vehicle controller and protocol_manager
vehicle_dir = output_dir + "vehicle/" + car_type.lower() + "/"
gen_vehicle_controller_and_manager(protocol_conf_file, vehicle_dir)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage:\npython %s some_config.yml" % sys.argv[0])
sys.exit(0)
with open(sys.argv[1], 'r') as fp:
conf = yaml.safe_load(fp)
gen(conf)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/gen_protocols.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
# -*- coding:utf-8 -*-
import datetime
import os
import shutil
import sys
import yaml
def gen_report_header(car_type, protocol, output_dir):
"""
doc string:
"""
report_header_tpl_file = "template/report_protocol.h.tpl"
FMT = get_tpl_fmt(report_header_tpl_file)
report_header_file = output_dir + "%s.h" % protocol["name"]
with open(report_header_file, 'w') as h_fp:
fmt_val = {}
fmt_val["car_type_lower"] = car_type.lower()
fmt_val["car_type_upper"] = car_type.upper()
fmt_val["protocol_name_upper"] = protocol["name"].upper()
fmt_val["classname"] = protocol["name"].replace('_', '').capitalize()
func_declare_list = []
for var in protocol["vars"]:
fmt = """
// config detail: %s
%s %s(const std::uint8_t* bytes, const int32_t length) const;"""
returntype = var["type"]
if var["type"] == "enum":
returntype = protocol["name"].capitalize(
) + "::" + var["name"].capitalize() + "Type"
declare = fmt % (str(var), returntype, var["name"].lower())
func_declare_list.append(declare)
fmt_val["func_declare_list"] = "\n".join(func_declare_list)
h_fp.write(FMT % fmt_val)
def gen_report_cpp(car_type, protocol, output_dir):
"""
doc string:
"""
report_cpp_tpl_file = "template/report_protocol.cc.tpl"
FMT = get_tpl_fmt(report_cpp_tpl_file)
report_cpp_file = output_dir + "%s.cc" % protocol["name"]
with open(report_cpp_file, 'w') as fp:
fmt_val = {}
fmt_val["car_type_lower"] = car_type
fmt_val["protocol_name_lower"] = protocol["name"]
classname = protocol["name"].replace('_', '').capitalize()
fmt_val["classname"] = classname
protocol_id = int(protocol["id"].upper(), 16)
if protocol_id > 2048:
fmt_val["id_upper"] = gen_esd_can_extended(protocol["id"].upper())
else:
fmt_val["id_upper"] = protocol["id"].upper()
set_var_to_protocol_list = []
func_impl_list = []
for var in protocol["vars"]:
var["name"] = var["name"].lower()
returntype = var["type"]
if var["type"] == "enum":
returntype = protocol["name"].capitalize(
) + "::" + var["name"].capitalize() + "Type"
# gen func top
fmt = """
// config detail: %s
%s %s::%s(const std::uint8_t* bytes, int32_t length) const {"""
impl = fmt % (str(var), returntype, classname, var["name"])
byte_info = get_byte_info(var)
impl = impl + gen_parse_value_impl(var, byte_info)
impl = impl + gen_report_value_offset_precision(var, protocol)
impl = impl + "}"
func_impl_list.append(impl)
proto_set_fmt = " chassis->mutable_%s()->mutable_%s()->set_%s(%s(bytes, length));"
func_name = var["name"]
proto_set = proto_set_fmt % (car_type, protocol["name"], var["name"],
func_name)
set_var_to_protocol_list.append(proto_set)
fmt_val["set_var_to_protocol_list"] = "\n".join(
set_var_to_protocol_list)
fmt_val["func_impl_list"] = "\n".join(func_impl_list)
fp.write(FMT % fmt_val)
def gen_report_value_offset_precision(var, protocol):
"""
doc string:
"""
impl = ""
if var["is_signed_var"]:
fmt = "\n x <<= %d;\n x >>= %d;\n"
# x is an int32_t var
shift_bit = 32 - var["len"]
impl = impl + fmt % (shift_bit, shift_bit)
returntype = var["type"]
if var["type"] == "enum":
returntype = protocol["name"].capitalize() + "::" + var["name"].capitalize(
) + "Type"
impl = impl + "\n " + returntype + " ret = "
if var["type"] == "enum":
impl = impl + " static_cast<" + returntype + ">(x);\n"
else:
impl = impl + "x"
if var["precision"] != 1.0:
impl = impl + " * %f" % var["precision"]
if var["offset"] != 0.0:
impl = impl + " + %f" % (var["offset"])
impl = impl + ";\n"
return impl + " return ret;\n"
def gen_parse_value_impl(var, byte_info):
"""
doc string:
"""
impl = ""
fmt = "\n Byte t%d(bytes + %d);\n"
shift_bit = 0
for i in range(0, len(byte_info)):
info = byte_info[i]
impl = impl + fmt % (i, info["byte"])
if i == 0:
impl = impl + " int32_t x = t%d.get_byte(%d, %d);\n" %\
(i, info["start_bit"], info["len"])
elif i == 1:
impl = impl + " int32_t t = t%d.get_byte(%d, %d);\n x <<= %d;\n x |= t;\n" %\
(i, info["start_bit"], info["len"], info["len"])
else:
impl = impl + " t = t%d.get_byte(%d, %d);\n x <<= %d;\n x |= t;\n" %\
(i, info["start_bit"], info["len"], info["len"])
shift_bit = shift_bit + info["len"]
return impl
def gen_control_header(car_type, protocol, output_dir):
"""
doc string:
"""
control_header_tpl_file = "template/control_protocol.h.tpl"
FMT = get_tpl_fmt(control_header_tpl_file)
control_header_file = output_dir + "%s.h" % protocol["name"]
with open(control_header_file, 'w') as h_fp:
fmt_val = {}
fmt_val["car_type_lower"] = car_type
fmt_val["car_type_upper"] = car_type.upper()
fmt_val["protocol_name_upper"] = protocol["name"].upper()
classname = protocol["name"].replace('_', '').capitalize()
fmt_val["classname"] = classname
declare_public_func_list = []
declare_private_func_list = []
declare_private_var_list = []
fmtpub = "\n // config detail: %s\n %s* set_%s(%s %s);"
fmtpri = "\n // config detail: %s\n void set_p_%s(uint8_t* data, %s %s);"
for var in protocol["vars"]:
returntype = var["type"]
if var["type"] == "enum":
returntype = protocol["name"].capitalize(
) + "::" + var["name"].capitalize() + "Type"
private_var = ""
public_func_declare = fmtpub % (str(var), classname,
var["name"].lower(), returntype,
var["name"].lower())
private_func_declare = fmtpri % (str(var), var["name"].lower(),
returntype, var["name"].lower())
private_var = " %s %s_;" % (returntype, var["name"].lower())
declare_private_var_list.append(private_var)
declare_public_func_list.append(public_func_declare)
declare_private_func_list.append(private_func_declare)
fmt_val["declare_public_func_list"] = "\n".join(
declare_public_func_list)
fmt_val["declare_private_func_list"] = "\n".join(
declare_private_func_list)
fmt_val["declare_private_var_list"] = "\n".join(
declare_private_var_list)
h_fp.write(FMT % fmt_val)
def get_byte_info(var):
"""
doc string: https://wenku.baidu.com/view/3fe9a7a4dd3383c4bb4cd293.html
u can reference this link to known the difference between motorola and intel encoding
return : the byte info of a variable in the protocol how many bytes are, and every byte use
how many bits, and bit start position
for the purpose of easily parsing value from CAN frame, the byte_info is arranged
from msb byte to lsb byte order
"""
bit = var["bit"]
byte_info = []
left_len = var["len"]
byte_idx = bit // 8
bit_start = bit % 8
if var["order"] == "motorola":
while left_len > 0:
info = {}
info["byte"] = byte_idx
info["len"] = min(bit_start + 1, left_len)
# start_bit is always the lowest bit
info["start_bit"] = bit_start - info["len"] + 1
byte_info.append(info)
left_len = left_len - info["len"]
byte_idx = byte_idx + 1
bit_start = 7
else:
while left_len > 0:
info = {}
info["byte"] = byte_idx
info["len"] = min(8 - bit_start, left_len)
info["start_bit"] = bit_start
byte_info.append(info)
left_len = left_len - info["len"]
byte_idx = byte_idx + 1
bit_start = 0
# byte_info is always construct with msb(most significant bit) byte to lsb byte
byte_info.reverse()
return byte_info
def gen_control_decode_offset_precision(var):
"""
doc string:
"""
impl = "\n"
range_info = get_range_info(var)
if var["type"] == "double":
if range_info["low"].find(".") == -1:
range_info["low"] = "%s.0" % range_info["low"]
if range_info["high"].find(".") == -1:
range_info["high"] = "%s.0" % range_info["high"]
if var["type"] != "enum" and var["type"] != "bool":
impl = impl + " %s = ProtocolData::BoundedValue(%s, %s, %s);\n" %\
(var["name"].lower(), range_info["low"],
range_info["high"], var["name"].lower())
impl = impl + " int x ="
if var["offset"] != 0.0:
impl = impl + " (%s - %f)" % (var["name"].lower(), var["offset"])
else:
impl = impl + " %s" % var["name"].lower()
if var["precision"] != 1.0:
impl = impl + " / %f" % var["precision"]
return impl + ";\n"
def gen_control_encode_one_byte_value_impl(var, byte_info):
"""
only has int and double, int can hold all the value whatever it is signed or unsigned
"""
fmt = """
Byte to_set(data + %d);
to_set.set_value(x, %d, %d);
"""
return fmt % (byte_info["byte"], byte_info["start_bit"], byte_info["len"])
def get_range_info(var):
"""
doc string:
"""
info = {}
if "physical_range" not in var.keys():
return info
items = var["physical_range"].split('|')
info["low"] = items[0].split('[')[1]
info["high"] = items[1].split(']')[0]
return info
def gen_control_encode_value_impl(var, byte_info):
"""
doc string:
"""
impl = " uint8_t t = 0;\n"
fmt = """
t = x & %s;
Byte to_set%d(data + %d);
to_set%d.set_value(t, %d, %d);
"""
shift_bit = 0
for i in range(0, len(byte_info)):
info = byte_info[i]
if i != 0:
impl = impl + " x >>= %d;\n" % shift_bit
mask_bit = "0x%X" % ((1 << info["len"]) - 1)
impl = impl + fmt % (mask_bit, i, info["byte"], i, info["start_bit"],
info["len"])
shift_bit = info["len"]
return impl
def gen_control_value_func_impl(classname, var, protocol):
"""
doc string:
"""
impl = ""
if var["len"] > 32:
print("This generator not support big than four bytes var." +
"protocol classname: %s, var_name:%s " % (
class_name, var["name"]))
return impl
fmt = """
%(classname)s* %(classname)s::set_%(var_name)s(
%(var_type)s %(var_name)s) {
%(var_name)s_ = %(var_name)s;
return this;
}
// config detail: %(config)s
void %(classname)s::set_p_%(var_name)s(uint8_t* data,
%(var_type)s %(var_name)s) {"""
fmt_val = {}
fmt_val["classname"] = classname
fmt_val["var_name"] = var["name"].lower()
returntype = var["type"]
if var["type"] == "enum":
returntype = protocol["name"].capitalize() + "::" + var["name"].capitalize(
) + "Type"
fmt_val["var_type"] = returntype
fmt_val["config"] = str(var)
impl = impl + fmt % fmt_val
impl = impl + gen_control_decode_offset_precision(var)
# get lsb to msb order
byte_info = get_byte_info(var)
byte_info.reverse()
if len(byte_info) == 1:
impl = impl + gen_control_encode_one_byte_value_impl(var, byte_info[0])
else:
impl = impl + gen_control_encode_value_impl(var, byte_info)
return impl + "}\n"
def gen_control_cpp(car_type, protocol, output_dir):
"""
doc string:
"""
control_cpp_tpl_file = "template/control_protocol.cc.tpl"
FMT = get_tpl_fmt(control_cpp_tpl_file)
control_cpp_file = output_dir + "%s.cc" % protocol["name"]
with open(control_cpp_file, 'w') as fp:
fmt_val = {}
fmt_val["car_type_lower"] = car_type
fmt_val["protocol_name_lower"] = protocol["name"]
protocol_id = int(protocol["id"].upper(), 16)
if protocol_id > 2048:
fmt_val["id_upper"] = gen_esd_can_extended(protocol["id"].upper())
else:
fmt_val["id_upper"] = protocol["id"].upper()
classname = protocol["name"].replace('_', '').capitalize()
fmt_val["classname"] = classname
set_private_var_list = []
set_private_var_init_list = []
set_func_impl_list = []
for var in protocol["vars"]:
func_impl = gen_control_value_func_impl(classname, var, protocol)
set_func_impl_list.append(func_impl)
set_private_var = " set_p_%s(data, %s_);" % (var["name"].lower(),
var["name"].lower())
set_private_var_list.append(set_private_var)
init_val = "0"
if var["type"] == "double":
init_val = "0.0"
elif var["type"] == "bool":
init_val = "false"
elif var["type"] == "enum":
if 0 in var["enum"]:
init_val = protocol["name"].capitalize(
) + "::" + var["enum"][0].upper()
else:
init_val = protocol["name"].capitalize(
) + "::" + list(var["enum"].values())[0].upper()
set_private_var_init_list.append(" %s_ = %s;" %
(var["name"].lower(), init_val))
fmt_val["set_private_var_list"] = "\n".join(set_private_var_list)
fmt_val["set_private_var_init_list"] = "\n".join(
set_private_var_init_list)
fmt_val["set_func_impl_list"] = "\n".join(set_func_impl_list)
fp.write(FMT % fmt_val)
def get_tpl_fmt(tpl_file):
"""
get fmt from tpl_file
"""
with open(tpl_file, 'r') as tpl:
fmt = tpl.readlines()
fmt = "".join(fmt)
return fmt
def gen_build_file(car_type, work_dir):
"""
doc string:
"""
build_tpl_file = "template/protocol_BUILD.tpl"
fmt = get_tpl_fmt(build_tpl_file)
with open(work_dir + "BUILD", "w") as build_fp:
fmt_var = {}
fmt_var["car_type"] = car_type.lower()
build_fp.write(fmt % fmt_var)
def gen_protocols(protocol_conf_file, protocol_dir):
"""
doc string:
"""
print("Generating protocols")
if not os.path.exists(protocol_dir):
os.makedirs(protocol_dir)
with open(protocol_conf_file, 'r') as fp:
content = yaml.safe_load(fp)
protocols = content["protocols"]
car_type = content["car_type"]
for p_name in protocols:
protocol = protocols[p_name]
if protocol["protocol_type"] == "report":
gen_report_header(car_type, protocol, protocol_dir)
gen_report_cpp(car_type, protocol, protocol_dir)
elif protocol["protocol_type"] == "control":
gen_control_header(car_type, protocol, protocol_dir)
gen_control_cpp(car_type, protocol, protocol_dir)
else:
print("Unknown protocol_type:%s" % protocol["protocol_type"])
gen_build_file(car_type, protocol_dir)
def gen_esd_can_extended(str):
"""
id string:
"""
int_id = int(str, 16)
int_id &= 0x1FFFFFFF
int_id |= 0x20000000
str = hex(int_id).replace('0x', '')
return str
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage:\npython %s some_config.yml" % sys.argv[0])
sys.exit(0)
with open(sys.argv[1], 'r') as fp:
conf = yaml.safe_load(fp)
protocol_conf = conf["protocol_conf"]
protocol_dir = conf["output_dir"] + "vehicle/" + conf["car_type"].lower(
) + "/protocol/"
shutil.rmtree(output_dir, True)
os.makedirs(output_dir)
gen_protocols(protocol_conf, protocol_dir)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/README.md
|
## Gen Vehicle Protocol Tool
It's a convinent tool to let you quickly generate a nearly complete code for a new vehicle.
You only have to do is to have the dbc file (which is a communication protocol for the car, which is usually made by the vehicle integrated company), and write a less 10 lines config for generate an encode/decode `
## Dependency
> sudo pip install pyyaml
## Usage:
The tool's input is :
* `vehicle dbc file `: like lincoln's dbc file, put it under this folder
* `generator tool config file`: for an example, a lincoln's is lincoln_conf.yml, detail you can see the example file of lincoln_conf.yml
Run:
> python gen.py lincoln_conf.yml
## Tool Framework
* `gen.py` : a central control the overall generating progress and will call the scripts below
* `extract_dbc_meta.py`: extract dbc info to an internal generator tool used yaml config, which will include a protocol name, id, how many vars in a protocol, every var's name, type, byte start, bit_start, bit_len etc. When we have these info, we can automitally generate code as we wish.
* `gen_protoco_file.py`: generate a proto file for this vehicle, which is used to store parsed info from CAN frame using these generated code.
* `gen_protocols.py`: generate protocol code (encoding and decoding CAN frame)according to the extract dbc meta.
* `gen_vehicle_controller_and_manager`: generate vehicle controller and vehicle message manager according to our recent chassis canbus framework.
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/extract_dbc_meta.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
import re
import shlex
import sys
import yaml
MAX_CAN_ID = 4096000000 # include can extended ID
STANDARD_CAN_ID = 2048
def extract_var_info(items):
"""
Desp: extract var info from line split items.
"""
car_var = {}
car_var["name"] = items[1]
car_var["bit"] = int(items[3].split('|')[0])
car_var["len"] = int(items[3].split('|')[1].split('@')[0])
order_sign = items[3].split('|')[1].split('@')[1]
if order_sign == "0+":
car_var["order"] = "motorola"
car_var["is_signed_var"] = False
elif order_sign == "0-":
car_var["order"] = "motorola"
car_var["is_signed_var"] = True
elif order_sign == "1+":
car_var["order"] = "intel"
car_var["is_signed_var"] = False
elif order_sign == "1-":
car_var["order"] = "intel"
car_var["is_signed_var"] = True
car_var["offset"] = float(items[4].split(',')[1].split(')')[0])
car_var["precision"] = float(items[4].split(',')[0].split('(')[1])
car_var["physical_range"] = items[5]
car_var["physical_unit"] = items[6].replace('_', ' ')
if car_var["len"] == 1:
car_var["type"] = "bool"
elif car_var["physical_range"].find(
".") != -1 or car_var["precision"] != 1.0:
car_var["type"] = "double"
else:
car_var["type"] = "int"
return car_var
def extract_dbc_meta(dbc_file, out_file, car_type, black_list, sender_list,
sender):
"""
the main gen_config func, use dbc file to gen a yaml file
parse every line, if the line is:
eg:BO_ 1104 BMS_0x450: 8 VCU
5 segments, and segments[0] is "BO_", then begin parse every signal in the following line
"""
sender_list = map(str, sender_list)
with open(dbc_file) as fp:
in_protocol = False
protocols = {}
protocol = {}
p_name = ""
line_num = 0
for line in fp:
items = shlex.split(line)
line_num = line_num + 1
if len(items) == 5 and items[0] == "BO_":
p_name = items[2][:-1].lower()
protocol = {}
if int(items[1]) > MAX_CAN_ID:
continue
protocol["id"] = "%x" % int(items[1])
if int(items[1]) > STANDARD_CAN_ID:
protocol["id"] = gen_can_id_extended(protocol["id"])
protocol["name"] = "%s_%s" % (p_name, protocol["id"])
protocol["sender"] = items[4]
if protocol["id"] in black_list:
continue
protocol["protocol_type"] = "report"
if protocol["id"] in sender_list or protocol["sender"] == sender:
protocol["protocol_type"] = "control"
protocol["vars"] = []
in_protocol = True
elif in_protocol:
if len(items) > 3 and items[0] == "SG_":
if items[2] == ":":
var_info = extract_var_info(items)
# current we can't process than 4 byte value
if var_info["len"] <= 32:
protocol["vars"].append(var_info)
else:
in_protocol = False
if len(protocol) != 0 and len(protocol["vars"]) != 0 and len(
protocol["vars"]) < 65:
protocols[protocol["id"]] = protocol
# print protocol
protocol = {}
if len(items) == 5 and items[0] == "CM_" and items[1] == "SG_":
protocol_id = "%x" % int(items[2])
if int(items[2]) > MAX_CAN_ID:
continue
if int(items[2]) > STANDARD_CAN_ID:
protocol_id = gen_can_id_extended(protocol_id)
for var in protocols[protocol_id]["vars"]:
if var["name"] == items[3]:
var["description"] = items[4][:-1]
if len(items) > 2 and items[0] == "VAL_":
protocol_id = "%x" % int(items[1])
if int(items[1]) > MAX_CAN_ID:
continue
if int(items[1]) > STANDARD_CAN_ID:
protocol_id = gen_can_id_extended(protocol_id)
for var in protocols[protocol_id]["vars"]:
if var["name"] == items[2]:
var["type"] = "enum"
var["enum"] = {}
for idx in range(3, len(items) - 1, 2):
enumtype = re.sub('\W+', ' ', items[idx + 1])
enumtype = enumtype.strip().replace(" ",
"_").upper()
enumtype = items[2].upper() + "_" + enumtype
var["enum"][int(items[idx])] = enumtype
cpp_reserved_key_words = ['minor', 'major', 'long', 'int']
for key in protocols:
for var in protocols[key]["vars"]:
if var["name"].lower() in cpp_reserved_key_words:
var["name"] = "MY_" + var["name"]
# print protocols
config = {}
config["car_type"] = car_type
config["protocols"] = protocols
with open(out_file, 'w') as fp_write:
fp_write.write(yaml.dump(config))
control_protocol_num =\
len([key for key in protocols.keys()
if protocols[key]["protocol_type"] == "control"])
report_protocol_num =\
len([key for key in protocols.keys()
if protocols[key]["protocol_type"] == "report"])
print("Extract car_type:%s's protocol meta info to file: %s" % (
car_type.upper(), out_file))
print("Total parsed protocols: %d" % len(protocols))
print("Control protocols: %d" % control_protocol_num)
print("Report protocols: %d" % report_protocol_num)
return True
def gen_can_id_extended(str):
"""
id string:
"""
int_id = int(str, 16)
int_id &= 0x1FFFFFFF
str = hex(int_id).replace('0x', '')
return str
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage:\npython %s your_car_parse_config_file.yml" % sys.argv[0])
sys.exit(0)
with open(sys.argv[1], 'r') as fp:
conf = yaml.safe_load(fp)
dbc_file = conf["dbc_file"]
protocol_conf_file = conf["protocol_conf"]
car_type = conf["car_type"]
black_list = conf["black_list"]
sender_list = conf["sender_list"]
sender = conf["sender"]
extract_dbc_meta(dbc_file, protocol_conf_file, car_type, black_list,
sender_list, sender)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/gen_proto_file.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
import datetime
import os
import re
import shutil
import sys
import yaml
def write_single_protocol_vars(pb_fp, p):
pb_fp.write("\nmessage %s {\n" % p["name"].capitalize())
if p["protocol_type"] == "control":
pb_fp.write("// Control Message\n")
elif p["protocol_type"] == "report":
pb_fp.write("// Report Message\n")
for var in p["vars"]:
fmt = " %s = %d;\n"
if var["type"] == "enum":
pb_fp.write(" enum %s {\n" % (var["name"].capitalize() + "Type"))
for key in sorted(var["enum"]):
pb_fp.write(fmt % (var["enum"][key], int(key)))
pb_fp.write(" }\n")
var_seq = 1
for var in p["vars"]:
fmt = " optional %s %s = %d;\n"
t = var["type"]
if t == "int":
t = "int32"
pb_fp.write(" // ")
if "description" in var:
pb_fp.write("%s " % var["description"])
pb_fp.write("[%s] %s\n" %
(var["physical_unit"], var["physical_range"]))
if t == "enum":
pb_fp.write(fmt % (var["name"].capitalize() + "Type",
var["name"].lower(), var_seq))
else:
pb_fp.write(fmt % (t, var["name"].lower(), var_seq))
var_seq = var_seq + 1
pb_fp.write("}\n")
def update_detail_pb(car_type):
with open("../../canbus/proto/chassis_detail.proto", 'r+') as pb_fp:
importline = "import \"modules/canbus/proto/" + car_type.lower(
) + ".proto\";\n"
vehicleline = " " + car_type.capitalize() + " " + car_type.lower()
lines = pb_fp.readlines()
importfound = False
vehiclefound = False
oneof = "oneof vehicle"
index = 0
startidx = 0
for l in lines:
if importline in l:
importfound = True
if vehicleline in l:
vehiclefound = True
if oneof in l:
startidx = index
index = index + 1
startidx = startidx + 1
count = 0
while not "}" in lines[startidx]:
count = int(lines[startidx].split()[-1][:-1])
startidx = startidx + 1
count = count + 1
if not vehiclefound:
lines.insert(startidx, vehicleline + " = " + str(count) + ";\n")
if not importfound:
lines.insert(4, importline)
pb_fp.seek(0)
for l in lines:
pb_fp.write(l)
def gen_proto_file(config_file, work_dir):
"""
config_file: the config file is generated with dbc
work_dir: the protobuf file will be output
"""
print("Generating proto file")
if not os.path.exists(work_dir):
os.makedirs(work_dir)
with open(config_file, 'r') as fp:
content = yaml.safe_load(fp)
protocols = content["protocols"]
car_type = content["car_type"]
with open("%s/%s.proto" % (work_dir, car_type.lower()), 'w') as pb_fp:
pb_fp.write("syntax = \"proto2\";\n\npackage apollo.canbus;\n")
for pid in protocols:
p = protocols[pid]
write_single_protocol_vars(pb_fp, p)
pb_fp.write("\nmessage %s {\n" % car_type.capitalize())
pb_var_seq = 1
for p_name in protocols:
p = protocols[p_name]
pb_fp.write(" optional %s %s = %d;" %
(p["name"].capitalize(), p["name"], pb_var_seq))
if protocols[p_name]["protocol_type"] == "control":
pb_fp.write(" // control message")
if protocols[p_name]["protocol_type"] == "report":
pb_fp.write(" // report message")
pb_fp.write("\n")
pb_var_seq = pb_var_seq + 1
pb_fp.write("}\n")
# update_detail_pb(car_type)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage:\npython %s some_config.yml" % sys.argv[0])
sys.exit(0)
with open(sys.argv[1], 'r') as fp:
conf = yaml.safe_load(fp)
protocol_conf = conf["protocol_conf"]
work_dir = conf["output_dir"] + "proto/"
gen_proto_file(protocol_conf, work_dir)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "extract_dbc_meta",
srcs = ["extract_dbc_meta.py"],
)
py_binary(
name = "gen",
srcs = ["gen.py"],
deps = [
":extract_dbc_meta",
":gen_proto_file",
":gen_protocols",
":gen_vehicle_controller_and_manager",
],
)
py_binary(
name = "gen_proto_file",
srcs = ["gen_proto_file.py"],
)
py_binary(
name = "gen_protocols",
srcs = ["gen_protocols.py"],
)
py_binary(
name = "gen_vehicle_controller_and_manager",
srcs = ["gen_vehicle_controller_and_manager.py"],
)
install(
name = "install",
py_dest = "tools/gen_vehicle_protocol",
data_dest = "tools/gen_vehicle_protocol",
data = [":data"],
targets = [
":gen",
]
)
filegroup(
name = "data",
srcs = glob([
"*.yml",
]) + ["README.md"] + glob(["template/*"]),
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/lincoln_conf.yml
|
dbc_file: lincoln.dbc
protocol_conf: lincoln.yml
car_type: lincoln
sender_list: []
sender: MAB
black_list: []
output_dir: output/
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/gem_conf.yml
|
dbc_file: gem.dbc
protocol_conf: gem.yml
car_type: gem
sender_list: []
sender: MAB
black_list: []
output_dir: output/
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/control_protocol.cc.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/%(car_type_lower)s/protocol/%(protocol_name_lower)s.h"
#include "modules/drivers/canbus/common/byte.h"
namespace apollo {
namespace canbus {
namespace %(car_type_lower)s {
using ::apollo::drivers::canbus::Byte;
const int32_t %(classname)s::ID = 0x%(id_upper)s;
// public
%(classname)s::%(classname)s() { Reset(); }
uint32_t %(classname)s::GetPeriod() const {
// TODO(All) : modify every protocol's period manually
static const uint32_t PERIOD = 20 * 1000;
return PERIOD;
}
void %(classname)s::UpdateData(uint8_t* data) {
%(set_private_var_list)s
}
void %(classname)s::Reset() {
// TODO(All) : you should check this manually
%(set_private_var_init_list)s
}
%(set_func_impl_list)s
} // namespace %(car_type_lower)s
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/control_protocol.h.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include "modules/drivers/canbus/can_comm/protocol_data.h"
#include "modules/common_msgs/chassis_msgs/chassis_detail.pb.h"
namespace apollo {
namespace canbus {
namespace %(car_type_lower)s {
class %(classname)s : public ::apollo::drivers::canbus::ProtocolData<
::apollo::canbus::ChassisDetail> {
public:
static const int32_t ID;
%(classname)s();
uint32_t GetPeriod() const override;
void UpdateData(uint8_t* data) override;
void Reset() override;
%(declare_public_func_list)s
private:
%(declare_private_func_list)s
private:
%(declare_private_var_list)s
};
} // namespace %(car_type_lower)s
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/vehicle_factory.cc.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/%(car_type_lower)s/%(car_type_lower)s_vehicle_factory.h"
#include "modules/canbus/vehicle/%(car_type_lower)s/%(car_type_lower)s_controller.h"
#include "modules/canbus/vehicle/%(car_type_lower)s/%(car_type_lower)s_message_manager.h"
#include "cyber/common/log.h"
#include "modules/common/util/util.h"
namespace apollo {
namespace canbus {
std::unique_ptr<VehicleController>
%(car_type_cap)sVehicleFactory::CreateVehicleController() {
return std::unique_ptr<VehicleController>(new %(car_type_lower)s::%(car_type_cap)sController());
}
std::unique_ptr<MessageManager<::apollo::canbus::ChassisDetail>>
%(car_type_cap)sVehicleFactory::CreateMessageManager() {
return std::unique_ptr<MessageManager<::apollo::canbus::ChassisDetail>>(
new %(car_type_lower)s::%(car_type_cap)sMessageManager());
}
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/message_manager.h.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include "modules/common_msgs/chassis_msgs/chassis_detail.pb.h"
#include "modules/drivers/canbus/can_comm/message_manager.h"
namespace apollo {
namespace canbus {
namespace %(car_type_namespace)s {
using ::apollo::drivers::canbus::MessageManager;
class %(car_type_cap)sMessageManager
: public MessageManager<::apollo::canbus::ChassisDetail> {
public:
%(car_type_cap)sMessageManager();
virtual ~%(car_type_cap)sMessageManager();
};
} // namespace %(car_type_namespace)s
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/controller.cc.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/%(car_type_lower)s/%(car_type_lower)s_controller.h"
#include "modules/common_msgs/basic_msgs/vehicle_signal.pb.h"
#include "cyber/common/log.h"
#include "modules/canbus/vehicle/%(car_type_lower)s/%(car_type_lower)s_message_manager.h"
#include "modules/canbus/vehicle/vehicle_controller.h"
#include "cyber/time/time.h"
#include "modules/drivers/canbus/can_comm/can_sender.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"
namespace apollo {
namespace canbus {
namespace %(car_type_lower)s {
using ::apollo::drivers::canbus::ProtocolData;
using ::apollo::common::ErrorCode;
using ::apollo::control::ControlCommand;
namespace {
const int32_t kMaxFailAttempt = 10;
const int32_t CHECK_RESPONSE_STEER_UNIT_FLAG = 1;
const int32_t CHECK_RESPONSE_SPEED_UNIT_FLAG = 2;
}
ErrorCode %(car_type_cap)sController::Init(
const VehicleParameter& params,
CanSender<::apollo::canbus::ChassisDetail> *const can_sender,
MessageManager<::apollo::canbus::ChassisDetail> *const message_manager) {
if (is_initialized_) {
AINFO << "%(car_type_cap)sController has already been initiated.";
return ErrorCode::CANBUS_ERROR;
}
vehicle_params_.CopyFrom(
common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param());
params_.CopyFrom(params);
if (!params_.has_driving_mode()) {
AERROR << "Vehicle conf pb not set driving_mode.";
return ErrorCode::CANBUS_ERROR;
}
if (can_sender == nullptr) {
return ErrorCode::CANBUS_ERROR;
}
can_sender_ = can_sender;
if (message_manager == nullptr) {
AERROR << "protocol manager is null.";
return ErrorCode::CANBUS_ERROR;
}
message_manager_ = message_manager;
// sender part
%(protocol_ptr_get_list)s
%(protocol_add_list)s
// need sleep to ensure all messages received
AINFO << "%(car_type_cap)sController is initialized.";
is_initialized_ = true;
return ErrorCode::OK;
}
%(car_type_cap)sController::~%(car_type_cap)sController() {}
bool %(car_type_cap)sController::Start() {
if (!is_initialized_) {
AERROR << "%(car_type_cap)sController has NOT been initiated.";
return false;
}
const auto& update_func = [this] { SecurityDogThreadFunc(); };
thread_.reset(new std::thread(update_func));
return true;
}
void %(car_type_cap)sController::Stop() {
if (!is_initialized_) {
AERROR << "%(car_type_cap)sController stops or starts improperly!";
return;
}
if (thread_ != nullptr && thread_->joinable()) {
thread_->join();
thread_.reset();
AINFO << "%(car_type_cap)sController stopped.";
}
}
Chassis %(car_type_cap)sController::chassis() {
chassis_.Clear();
ChassisDetail chassis_detail;
message_manager_->GetSensorData(&chassis_detail);
// 21, 22, previously 1, 2
if (driving_mode() == Chassis::EMERGENCY_MODE) {
set_chassis_error_code(Chassis::NO_ERROR);
}
chassis_.set_driving_mode(driving_mode());
chassis_.set_error_code(chassis_error_code());
// 3
chassis_.set_engine_started(true);
/* ADD YOUR OWN CAR CHASSIS OPERATION
*/
return chassis_;
}
void %(car_type_cap)sController::Emergency() {
set_driving_mode(Chassis::EMERGENCY_MODE);
ResetProtocol();
}
ErrorCode %(car_type_cap)sController::EnableAutoMode() {
if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE) {
AINFO << "already in COMPLETE_AUTO_DRIVE mode";
return ErrorCode::OK;
}
return ErrorCode::OK;
/* ADD YOUR OWN CAR CHASSIS OPERATION
brake_60_->set_enable();
throttle_62_->set_enable();
steering_64_->set_enable();
can_sender_->Update();
const int32_t flag =
CHECK_RESPONSE_STEER_UNIT_FLAG | CHECK_RESPONSE_SPEED_UNIT_FLAG;
if (!CheckResponse(flag, true)) {
AERROR << "Failed to switch to COMPLETE_AUTO_DRIVE mode.";
Emergency();
set_chassis_error_code(Chassis::CHASSIS_ERROR);
return ErrorCode::CANBUS_ERROR;
}
set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE);
AINFO << "Switch to COMPLETE_AUTO_DRIVE mode ok.";
return ErrorCode::OK;
*/
}
ErrorCode %(car_type_cap)sController::DisableAutoMode() {
ResetProtocol();
can_sender_->Update();
set_driving_mode(Chassis::COMPLETE_MANUAL);
set_chassis_error_code(Chassis::NO_ERROR);
AINFO << "Switch to COMPLETE_MANUAL ok.";
return ErrorCode::OK;
}
ErrorCode %(car_type_cap)sController::EnableSteeringOnlyMode() {
if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE ||
driving_mode() == Chassis::AUTO_STEER_ONLY) {
set_driving_mode(Chassis::AUTO_STEER_ONLY);
AINFO << "Already in AUTO_STEER_ONLY mode.";
return ErrorCode::OK;
}
/* ADD YOUR OWN CAR CHASSIS OPERATION
brake_60_->set_disable();
throttle_62_->set_disable();
steering_64_->set_enable();
can_sender_->Update();
if (!CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, true)) {
AERROR << "Failed to switch to AUTO_STEER_ONLY mode.";
Emergency();
set_chassis_error_code(Chassis::CHASSIS_ERROR);
return ErrorCode::CANBUS_ERROR;
}
set_driving_mode(Chassis::AUTO_STEER_ONLY);
AINFO << "Switch to AUTO_STEER_ONLY mode ok.";
return ErrorCode::OK;
*/
}
ErrorCode %(car_type_cap)sController::EnableSpeedOnlyMode() {
if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE ||
driving_mode() == Chassis::AUTO_SPEED_ONLY) {
set_driving_mode(Chassis::AUTO_SPEED_ONLY);
AINFO << "Already in AUTO_SPEED_ONLY mode";
return ErrorCode::OK;
}
/* ADD YOUR OWN CAR CHASSIS OPERATION
brake_60_->set_enable();
throttle_62_->set_enable();
steering_64_->set_disable();
can_sender_->Update();
if (!CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, true)) {
AERROR << "Failed to switch to AUTO_SPEED_ONLY mode.";
Emergency();
set_chassis_error_code(Chassis::CHASSIS_ERROR);
return ErrorCode::CANBUS_ERROR;
}
set_driving_mode(Chassis::AUTO_SPEED_ONLY);
AINFO << "Switch to AUTO_SPEED_ONLY mode ok.";
return ErrorCode::OK;
*/
}
// NEUTRAL, REVERSE, DRIVE
void %(car_type_cap)sController::Gear(Chassis::GearPosition gear_position) {
if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE &&
driving_mode() != Chassis::AUTO_SPEED_ONLY) {
AINFO << "This drive mode no need to set gear.";
return;
}
/* ADD YOUR OWN CAR CHASSIS OPERATION
switch (gear_position) {
case Chassis::GEAR_NEUTRAL: {
gear_66_->set_gear_neutral();
break;
}
case Chassis::GEAR_REVERSE: {
gear_66_->set_gear_reverse();
break;
}
case Chassis::GEAR_DRIVE: {
gear_66_->set_gear_drive();
break;
}
case Chassis::GEAR_PARKING: {
gear_66_->set_gear_park();
break;
}
case Chassis::GEAR_LOW: {
gear_66_->set_gear_low();
break;
}
case Chassis::GEAR_NONE: {
gear_66_->set_gear_none();
break;
}
case Chassis::GEAR_INVALID: {
AERROR << "Gear command is invalid!";
gear_66_->set_gear_none();
break;
}
default: {
gear_66_->set_gear_none();
break;
}
}
*/
}
// brake with pedal
// pedal:0.00~99.99 unit:
void %(car_type_cap)sController::Brake(double pedal) {
// double real_value = vehicle_params_.max_acceleration() * acceleration / 100;
// TODO(All) : Update brake value based on mode
if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE &&
driving_mode() != Chassis::AUTO_SPEED_ONLY) {
AINFO << "The current drive mode does not need to set brake pedal.";
return;
}
/* ADD YOUR OWN CAR CHASSIS OPERATION
brake_60_->set_pedal(pedal);
*/
}
// drive with pedal
// pedal:0.00~99.99 unit:
void %(car_type_cap)sController::Throttle(double pedal) {
if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE &&
driving_mode() != Chassis::AUTO_SPEED_ONLY) {
AINFO << "The current drive mode does not need to set throttle pedal.";
return;
}
/* ADD YOUR OWN CAR CHASSIS OPERATION
throttle_62_->set_pedal(pedal);
*/
}
// confirm the car is driven by acceleration command or drive/brake pedal
// drive with acceleration/deceleration
// acc:-7.0 ~ 5.0, unit:m/s^2
void %(car_type_cap)sController::Acceleration(double acc) {
if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE ||
driving_mode() != Chassis::AUTO_SPEED_ONLY) {
AINFO << "The current drive mode does not need to set acceleration.";
return;
}
/* ADD YOUR OWN CAR CHASSIS OPERATION
*/
}
// %(car_type_lower)s default, +470 ~ -470, left:+, right:-
// need to be compatible with control module, so reverse
// steering with angle
// angle:-99.99~0.00~99.99, unit:, left:+, right:-
void %(car_type_cap)sController::Steer(double angle) {
if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE &&
driving_mode() != Chassis::AUTO_STEER_ONLY) {
AINFO << "The current driving mode does not need to set steer.";
return;
}
// const double real_angle =
// vehicle_params_.max_steer_angle() / M_PI * 180 * angle / 100.0;
// reverse sign
/* ADD YOUR OWN CAR CHASSIS OPERATION
steering_64_->set_steering_angle(real_angle)->set_steering_angle_speed(200);
*/
}
// steering with new angle speed
// angle:-99.99~0.00~99.99, unit:, left:+, right:-
// angle_spd:0.00~99.99, unit:deg/s
void %(car_type_cap)sController::Steer(double angle, double angle_spd) {
if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE &&
driving_mode() != Chassis::AUTO_STEER_ONLY) {
AINFO << "The current driving mode does not need to set steer.";
return;
}
/* ADD YOUR OWN CAR CHASSIS OPERATION
const double real_angle =
vehicle_params_.max_steer_angle() / M_PI * 180 * angle / 100.0;
const double real_angle_spd = ProtocolData<::apollo::canbus::ChassisDetail>::BoundedValue(
vehicle_params_.min_steer_angle_rate(), vehicle_params_.max_steer_angle_rate(),
vehicle_params_.max_steer_angle_rate() * angle_spd / 100.0);
steering_64_->set_steering_angle(real_angle)
->set_steering_angle_speed(real_angle_spd);
*/
}
void %(car_type_cap)sController::SetEpbBreak(const ControlCommand& command) {
if (command.parking_brake()) {
// None
} else {
// None
}
}
void %(car_type_cap)sController::SetBeam(const ControlCommand& command) {
if (command.signal().high_beam()) {
// None
} else if (command.signal().low_beam()) {
// None
} else {
// None
}
}
void %(car_type_cap)sController::SetHorn(const ControlCommand& command) {
if (command.signal().horn()) {
// None
} else {
// None
}
}
void %(car_type_cap)sController::SetTurningSignal(const ControlCommand& command) {
// Set Turn Signal
/* ADD YOUR OWN CAR CHASSIS OPERATION
auto signal = command.signal().turn_signal();
if (signal == common::VehicleSignal::TURN_LEFT) {
turnsignal_68_->set_turn_left();
} else if (signal == common::VehicleSignal::TURN_RIGHT) {
turnsignal_68_->set_turn_right();
} else {
turnsignal_68_->set_turn_none();
}
*/
}
void %(car_type_cap)sController::ResetProtocol() {
message_manager_->ResetSendMessages();
}
bool %(car_type_cap)sController::CheckChassisError() {
/* ADD YOUR OWN CAR CHASSIS OPERATION
*/
return false;
}
void %(car_type_cap)sController::SecurityDogThreadFunc() {
int32_t vertical_ctrl_fail = 0;
int32_t horizontal_ctrl_fail = 0;
if (can_sender_ == nullptr) {
AERROR << "Failed to run SecurityDogThreadFunc() because can_sender_ is "
"nullptr.";
return;
}
while (!can_sender_->IsRunning()) {
std::this_thread::yield();
}
std::chrono::duration<double, std::micro> default_period{50000};
int64_t start = 0;
int64_t end = 0;
while (can_sender_->IsRunning()) {
start = ::apollo::cyber::Time::Now().ToMicrosecond();
const Chassis::DrivingMode mode = driving_mode();
bool emergency_mode = false;
// 1. horizontal control check
if ((mode == Chassis::COMPLETE_AUTO_DRIVE ||
mode == Chassis::AUTO_STEER_ONLY) &&
CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, false) == false) {
++horizontal_ctrl_fail;
if (horizontal_ctrl_fail >= kMaxFailAttempt) {
emergency_mode = true;
set_chassis_error_code(Chassis::MANUAL_INTERVENTION);
}
} else {
horizontal_ctrl_fail = 0;
}
// 2. vertical control check
if ((mode == Chassis::COMPLETE_AUTO_DRIVE ||
mode == Chassis::AUTO_SPEED_ONLY) &&
!CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, false)) {
++vertical_ctrl_fail;
if (vertical_ctrl_fail >= kMaxFailAttempt) {
emergency_mode = true;
set_chassis_error_code(Chassis::MANUAL_INTERVENTION);
}
} else {
vertical_ctrl_fail = 0;
}
if (CheckChassisError()) {
set_chassis_error_code(Chassis::CHASSIS_ERROR);
emergency_mode = true;
}
if (emergency_mode && mode != Chassis::EMERGENCY_MODE) {
set_driving_mode(Chassis::EMERGENCY_MODE);
message_manager_->ResetSendMessages();
}
end = ::apollo::cyber::Time::Now().ToMicrosecond();
std::chrono::duration<double, std::micro> elapsed{end - start};
if (elapsed < default_period) {
std::this_thread::sleep_for(default_period - elapsed);
} else {
AERROR
<< "Too much time consumption in %(car_type_cap)sController looping process:"
<< elapsed.count();
}
}
}
bool %(car_type_cap)sController::CheckResponse(const int32_t flags, bool need_wait) {
/* ADD YOUR OWN CAR CHASSIS OPERATION
*/
return false;
}
void %(car_type_cap)sController::set_chassis_error_mask(const int32_t mask) {
std::lock_guard<std::mutex> lock(chassis_mask_mutex_);
chassis_error_mask_ = mask;
}
int32_t %(car_type_cap)sController::chassis_error_mask() {
std::lock_guard<std::mutex> lock(chassis_mask_mutex_);
return chassis_error_mask_;
}
Chassis::ErrorCode %(car_type_cap)sController::chassis_error_code() {
std::lock_guard<std::mutex> lock(chassis_error_code_mutex_);
return chassis_error_code_;
}
void %(car_type_cap)sController::set_chassis_error_code(
const Chassis::ErrorCode& error_code) {
std::lock_guard<std::mutex> lock(chassis_error_code_mutex_);
chassis_error_code_ = error_code;
}
} // namespace %(car_type_lower)s
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/report_protocol.cc.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/%(car_type_lower)s/protocol/%(protocol_name_lower)s.h"
#include "glog/logging.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace %(car_type_lower)s {
using ::apollo::drivers::canbus::Byte;
%(classname)s::%(classname)s() {}
const int32_t %(classname)s::ID = 0x%(id_upper)s;
void %(classname)s::Parse(const std::uint8_t* bytes, int32_t length,
ChassisDetail* chassis) const {
%(set_var_to_protocol_list)s
}
%(func_impl_list)s
} // namespace %(car_type_lower)s
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/vehicle_factory.h.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file %(car_type_lower)s_vehicle_factory.h
*/
#pragma once
#include <memory>
#include "modules/canbus/proto/vehicle_parameter.pb.h"
#include "modules/canbus/vehicle/abstract_vehicle_factory.h"
#include "modules/canbus/vehicle/vehicle_controller.h"
#include "modules/drivers/canbus/can_comm/message_manager.h"
/**
* @namespace apollo::canbus
* @brief apollo::canbus
*/
namespace apollo {
namespace canbus {
/**
* @class %(car_type_cap)sVehicleFactory
*
* @brief this class is inherited from AbstractVehicleFactory. It can be used to
* create controller and message manager for %(car_type_lower)s vehicle.
*/
class %(car_type_cap)sVehicleFactory : public AbstractVehicleFactory {
public:
/**
* @brief destructor
*/
virtual ~%(car_type_cap)sVehicleFactory() = default;
/**
* @brief create %(car_type_lower)s vehicle controller
* @returns a unique_ptr that points to the created controller
*/
std::unique_ptr<VehicleController> CreateVehicleController() override;
/**
* @brief create %(car_type_lower)s message manager
* @returns a unique_ptr that points to the created message manager
*/
std::unique_ptr<MessageManager<::apollo::canbus::ChassisDetail>>
CreateMessageManager() override;
};
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/report_protocol.h.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include "modules/drivers/canbus/can_comm/protocol_data.h"
#include "modules/common_msgs/chassis_msgs/chassis_detail.pb.h"
namespace apollo {
namespace canbus {
namespace %(car_type_lower)s {
class %(classname)s : public ::apollo::drivers::canbus::ProtocolData<
::apollo::canbus::ChassisDetail> {
public:
static const int32_t ID;
%(classname)s();
void Parse(const std::uint8_t* bytes, int32_t length,
ChassisDetail* chassis) const override;
private:
%(func_declare_list)s
};
} // namespace %(car_type_lower)s
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/protocol_BUILD.tpl
|
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
cc_library(
name = "canbus_%(car_type)s_protocol",
srcs = glob([
"*.cc",
]),
hdrs = glob([
"*.h",
]),
deps = [
"//modules/drivers/canbus/common:canbus_common",
"//modules/common_msgs/chassis_msgs:chassis_detail_cc_proto",
"//modules/drivers/canbus/can_comm:message_manager_base",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/controller_manager_BUILD.tpl
|
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
cc_library(
name = "%(car_type_lower)s_vehicle_factory",
srcs = [
"%(car_type_lower)s_vehicle_factory.cc",
],
hdrs = [
"%(car_type_lower)s_vehicle_factory.h",
],
deps = [
":%(car_type_lower)s_controller",
":%(car_type_lower)s_message_manager",
"//modules/canbus/vehicle:abstract_vehicle_factory",
],
)
cc_library(
name = "%(car_type_lower)s_message_manager",
srcs = [
"%(car_type_lower)s_message_manager.cc",
],
hdrs = [
"%(car_type_lower)s_message_manager.h",
],
deps = [
"//modules/drivers/canbus/common:canbus_common",
"//modules/common_msgs/chassis_msgs:chassis_detail_cc_proto",
"//modules/drivers/canbus/can_comm:message_manager_base",
"//modules/canbus/vehicle/%(car_type_lower)s/protocol:canbus_%(car_type_lower)s_protocol",
],
)
cc_library(
name = "%(car_type_lower)s_controller",
srcs = [
"%(car_type_lower)s_controller.cc",
],
hdrs = [
"%(car_type_lower)s_controller.h",
],
deps = [
":%(car_type_lower)s_message_manager",
"//modules/drivers/canbus/can_comm:can_sender",
"//modules/drivers/canbus/common:canbus_common",
"//modules/common_msgs/chassis_msgs:chassis_detail_cc_proto",
"//modules/drivers/canbus/can_comm:message_manager_base",
"//modules/canbus/vehicle:vehicle_controller_base",
"//modules/canbus/vehicle/%(car_type_lower)s/protocol:canbus_%(car_type_lower)s_protocol",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/controller.h.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include <memory>
#include <thread>
#include "modules/canbus/vehicle/vehicle_controller.h"
#include "modules/canbus/proto/canbus_conf.pb.h"
#include "modules/common_msgs/chassis_msgs/chassis.pb.h"
#include "modules/canbus/proto/vehicle_parameter.pb.h"
#include "modules/common_msgs/basic_msgs/error_code.pb.h"
#include "modules/common_msgs/control_msgs/control_cmd.pb.h"
%(control_protocol_include_list)s
namespace apollo {
namespace canbus {
namespace %(car_type_lower)s {
class %(car_type_cap)sController final : public VehicleController {
public:
explicit %(car_type_cap)sController() {};
virtual ~%(car_type_cap)sController();
::apollo::common::ErrorCode Init(
const VehicleParameter& params,
CanSender<::apollo::canbus::ChassisDetail> *const can_sender,
MessageManager<::apollo::canbus::ChassisDetail> *const message_manager) override;
bool Start() override;
/**
* @brief stop the vehicle controller.
*/
void Stop() override;
/**
* @brief calculate and return the chassis.
* @returns a copy of chassis. Use copy here to avoid multi-thread issues.
*/
Chassis chassis() override;
private:
// main logical function for operation the car enter or exit the auto driving
void Emergency() override;
::apollo::common::ErrorCode EnableAutoMode() override;
::apollo::common::ErrorCode DisableAutoMode() override;
::apollo::common::ErrorCode EnableSteeringOnlyMode() override;
::apollo::common::ErrorCode EnableSpeedOnlyMode() override;
// NEUTRAL, REVERSE, DRIVE
void Gear(Chassis::GearPosition state) override;
// brake with new acceleration
// acceleration:0.00~99.99, unit:
// acceleration_spd: 60 ~ 100, suggest: 90
void Brake(double acceleration) override;
// drive with old acceleration
// gas:0.00~99.99 unit:
void Throttle(double throttle) override;
// drive with acceleration/deceleration
// acc:-7.0~5.0 unit:m/s^2
void Acceleration(double acc) override;
// steering with old angle speed
// angle:-99.99~0.00~99.99, unit:, left:+, right:-
void Steer(double angle) override;
// steering with new angle speed
// angle:-99.99~0.00~99.99, unit:, left:+, right:-
// angle_spd:0.00~99.99, unit:deg/s
void Steer(double angle, double angle_spd) override;
// set Electrical Park Brake
void SetEpbBreak(const ::apollo::control::ControlCommand& command) override;
void SetBeam(const ::apollo::control::ControlCommand& command) override;
void SetHorn(const ::apollo::control::ControlCommand& command) override;
void SetTurningSignal(
const ::apollo::control::ControlCommand& command) override;
void ResetProtocol();
bool CheckChassisError();
private:
void SecurityDogThreadFunc();
virtual bool CheckResponse(const int32_t flags, bool need_wait);
void set_chassis_error_mask(const int32_t mask);
int32_t chassis_error_mask();
Chassis::ErrorCode chassis_error_code();
void set_chassis_error_code(const Chassis::ErrorCode& error_code);
private:
// control protocol
%(control_protocol_ptr_list)s
Chassis chassis_;
std::unique_ptr<std::thread> thread_;
bool is_chassis_error_ = false;
std::mutex chassis_error_code_mutex_;
Chassis::ErrorCode chassis_error_code_ = Chassis::NO_ERROR;
std::mutex chassis_mask_mutex_;
int32_t chassis_error_mask_ = 0;
};
} // namespace %(car_type_lower)s
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol
|
apollo_public_repos/apollo/modules/tools/gen_vehicle_protocol/template/message_manager.cc.tpl
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/%(car_type_lower)s/%(car_type_lower)s_message_manager.h"
%(control_header_list)s
%(report_header_list)s
namespace apollo {
namespace canbus {
namespace %(car_type_lower)s {
%(car_type_cap)sMessageManager::%(car_type_cap)sMessageManager() {
// Control Messages
%(control_add_list)s
// Report Messages
%(report_add_list)s
}
%(car_type_cap)sMessageManager::~%(car_type_cap)sMessageManager() {}
} // namespace %(car_type_lower)s
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/dump_gpsbin/dump_gpsbin.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
Extract messages of gps topic from data record file,
and save them into specified binary file
Usage:
dump_gpsbin.py --input_file=a.record --output_dir=dir
See the gflags for more optional args.
"""
import os
import sys
import time
import gflags
import glog
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import record
from modules.common_msgs.sensor_msgs.gnss_pb2 import RawData
# Requried flags.
gflags.DEFINE_string('input_file', None, 'Input record file path.')
# Optional flags.
gflags.DEFINE_string('output_dir', './', 'Output directory path.')
# Stable flags which rarely change.
gflags.DEFINE_string('gps_raw_data_channel',
'/apollo/sensor/gnss/raw_data',
'gps raw data channel.')
def process_record_file(args):
"""Read record file and extract the message with specified channels"""
freader = record.RecordReader(args.input_file)
glog.info('#processing record file {}'.format(args.input_file))
time.sleep(1)
output_file = os.path.join(args.output_dir, 'gpsimu.bin')
with open(output_file, 'wb') as outfile:
for channel, message, _type, _timestamp in freader.read_messages():
if channel == args.gps_raw_data_channel:
raw_data = RawData()
raw_data.ParseFromString(message)
outfile.write(raw_data.data)
def main():
"""Entry point."""
gflags.FLAGS(sys.argv)
process_record_file(gflags.FLAGS)
return
if __name__ == '__main__':
main()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/dump_gpsbin/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "dump_gpsbin",
srcs = ["dump_gpsbin.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/sensor_msgs:gnss_py_pb2",
],
)
install(
name = "install",
py_dest = "tools/dump_gpsbin",
targets = [":dump_gpsbin"]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/restore_video_record/README.md
|
# Video Records Restoring Tool
## Restore
This tool converts video frames from source record file into images and then restores them to the generated record file.
```bash
python restore_video_record.py --from_record=<src record file> --to_record=<dst record file>
```
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/restore_video_record/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "readme",
srcs = glob([
"README.md",
]),
)
py_binary(
name = "restore_video_record",
srcs = ["restore_video_record.py"],
deps = [
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/sensor_msgs:sensor_image_py_pb2",
],
)
install(
name = "install",
data = [":readme"],
data_dest = "tools/restore_video_record",
py_dest = "tools/restore_video_record",
targets = [
":restore_video_record",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/restore_video_record/restore_video_record.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
""" Restore record file by replacing its video frames with image frames. """
import datetime
import errno
import glob
import os
import shutil
import time
from absl import app
from absl import flags
from absl import logging
import cv2
from cyber.python.cyber_py3.record import RecordReader, RecordWriter
from modules.common_msgs.sensor_msgs.sensor_image_pb2 import CompressedImage
flags.DEFINE_string('from_record', None, 'The source record file that needs to be restored.')
flags.DEFINE_string('to_record', None, 'The restored record file.')
# The compressed channels that have videos we need to decode
IMAGE_FRONT_6MM_CHANNEL = '/apollo/sensor/camera/front_6mm/image/compressed'
IMAGE_FRONT_12MM_CHANNEL = '/apollo/sensor/camera/front_12mm/image/compressed'
IMAGE_REAR_6MM_CHANNEL = '/apollo/sensor/camera/rear_6mm/image/compressed'
IMAGE_LEFT_FISHEYE_CHANNEL = '/apollo/sensor/camera/left_fisheye/image/compressed'
IMAGE_RIGHT_FISHEYE_CHANNEL = '/apollo/sensor/camera/right_fisheye/image/compressed'
VIDEO_FRONT_6MM_CHANNEL = '/apollo/sensor/camera/front_6mm/video/compressed'
VIDEO_FRONT_12MM_CHANNEL = '/apollo/sensor/camera/front_12mm/video/compressed'
VIDEO_REAR_6MM_CHANNEL = '/apollo/sensor/camera/rear_6mm/video/compressed'
VIDEO_LEFT_FISHEYE_CHANNEL = '/apollo/sensor/camera/left_fisheye/video/compressed'
VIDEO_RIGHT_FISHEYE_CHANNEL = '/apollo/sensor/camera/right_fisheye/video/compressed'
VIDEO_CHANNELS = [
IMAGE_FRONT_6MM_CHANNEL,
IMAGE_FRONT_12MM_CHANNEL,
IMAGE_REAR_6MM_CHANNEL,
IMAGE_LEFT_FISHEYE_CHANNEL,
IMAGE_RIGHT_FISHEYE_CHANNEL,
VIDEO_FRONT_6MM_CHANNEL,
VIDEO_FRONT_12MM_CHANNEL,
VIDEO_REAR_6MM_CHANNEL,
VIDEO_LEFT_FISHEYE_CHANNEL,
VIDEO_RIGHT_FISHEYE_CHANNEL,
]
VIDEO_IMAGE_MAP = {
IMAGE_FRONT_6MM_CHANNEL: IMAGE_FRONT_6MM_CHANNEL,
IMAGE_FRONT_12MM_CHANNEL: IMAGE_FRONT_12MM_CHANNEL,
IMAGE_REAR_6MM_CHANNEL: IMAGE_REAR_6MM_CHANNEL,
IMAGE_LEFT_FISHEYE_CHANNEL: IMAGE_LEFT_FISHEYE_CHANNEL,
IMAGE_RIGHT_FISHEYE_CHANNEL: IMAGE_RIGHT_FISHEYE_CHANNEL,
VIDEO_FRONT_6MM_CHANNEL: IMAGE_FRONT_6MM_CHANNEL,
VIDEO_FRONT_12MM_CHANNEL: IMAGE_FRONT_12MM_CHANNEL,
VIDEO_REAR_6MM_CHANNEL: IMAGE_REAR_6MM_CHANNEL,
VIDEO_LEFT_FISHEYE_CHANNEL: IMAGE_LEFT_FISHEYE_CHANNEL,
VIDEO_RIGHT_FISHEYE_CHANNEL: IMAGE_RIGHT_FISHEYE_CHANNEL,
}
class VideoConverter(object):
"""Convert video into images."""
def __init__(self, work_dir, topic):
# Initial type of video frames that defined in apollo video drive proto
# The initial frame has meta data information shared by the following tens of frames
self.initial_frame_type = 1
self.image_ids = []
self.first_initial_found = False
video_dir = os.path.join(work_dir, 'videos')
self.video_file = os.path.join(video_dir, '{}.h265'.format(topic))
self.image_dir = '{}_images'.format(self.video_file)
makedirs(video_dir)
makedirs(self.image_dir)
self.frame_writer = open(self.video_file, 'wb+')
def close_writer(self):
"""Close the video frames writer"""
self.frame_writer.close()
def write_frame(self, py_message):
"""Write video frames into binary format file"""
if not self.first_initial_found:
proto = image_message_to_proto(py_message)
if proto.frame_type != self.initial_frame_type:
return
self.first_initial_found = True
self.frame_writer.write(py_message.message)
self.image_ids.append(get_message_id(py_message.timestamp, py_message.topic))
def decode(self):
"""Decode video file into images"""
video_decoder_exe = '/apollo/bazel-bin/modules/drivers/video/tools/decode_video/video2jpg'
return_code = os.system('{} --input_video={} --output_dir={}'.format(
video_decoder_exe, self.video_file, self.image_dir))
if return_code != 0:
logging.error('Failed to execute video2jpg for video {}'.format(self.video_file))
return False
generated_images = sorted(glob.glob('{}/*.jpg'.format(self.image_dir)))
if len(generated_images) != len(self.image_ids):
logging.error('Mismatch between original {} and generated frames {}'.format(
len(self.image_ids), len(generated_images)))
return False
for idx in range(len(generated_images)):
os.rename(generated_images[idx], os.path.join(self.image_dir, self.image_ids[idx]))
return True
def move_images(self, overall_image_dir):
"""Move self's images to overall image dir"""
for image_file in os.listdir(self.image_dir):
shutil.move(os.path.join(self.image_dir, image_file),
os.path.join(overall_image_dir, image_file))
def restore_record(input_record, output_record):
"""Entrance of processing."""
# Define working dirs that store intermediate results in the middle of processing
work_dir = 'restore_video_work_dir_{}'.format(
datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H-%M-%S'))
# Decode videos
converters = {}
for topic in VIDEO_CHANNELS:
converters[topic] = VideoConverter(work_dir, topic)
reader = RecordReader(input_record)
for message in reader.read_messages():
if message.topic in VIDEO_CHANNELS:
converters[message.topic].write_frame(message)
image_dir = os.path.join(work_dir, 'images')
makedirs(image_dir)
for topic in VIDEO_CHANNELS:
converters[topic].close_writer()
converters[topic].decode()
converters[topic].move_images(image_dir)
# Restore target record file
writer = RecordWriter(0, 0)
writer.open(output_record)
topic_descs = {}
counter = 0
reader = RecordReader(input_record)
for message in reader.read_messages():
message_content = message.message
message_topic = message.topic
if message.topic in VIDEO_CHANNELS:
message_content = retrieve_image(image_dir, message)
message_topic = VIDEO_IMAGE_MAP[message.topic]
if not message_content:
continue
counter += 1
if counter % 1000 == 0:
logging.info('rewriting {} th message to record {}'.format(counter, output_record))
writer.write_message(message_topic, message_content, message.timestamp)
if message_topic not in topic_descs:
topic_descs[message_topic] = reader.get_protodesc(message_topic)
writer.write_channel(message_topic, message.data_type, topic_descs[message_topic])
writer.close()
logging.info('All Done, converted record: {}'.format(output_record))
def retrieve_image(image_dir, message):
"""Actually change the content of message from video bytes to image bytes"""
message_id = get_message_id(message.timestamp, message.topic)
message_path = os.path.join(image_dir, message_id)
if not os.path.exists(message_path):
logging.error('message {} not found in image dir'.format(message_id))
return None
img_bin = cv2.imread(message_path)
# Check by using NoneType explicitly to avoid ambitiousness
if img_bin is None:
logging.error('failed to read original message: {}'.format(message_path))
return None
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 95]
result, encode_img = cv2.imencode('.jpg', img_bin, encode_param)
if not result:
logging.error('failed to encode message {}'.format(message_id))
return None
message_proto = image_message_to_proto(message)
message_proto.format = '; jpeg compressed bgr8'
message_proto.data = message_proto.data.replace(message_proto.data[:], bytearray(encode_img))
return message_proto.SerializeToString()
def get_message_id(timestamp, topic):
"""Unify the way to get a unique identifier for the given message"""
return '{}{}'.format(timestamp, topic.replace('/', '_'))
def image_message_to_proto(py_message):
"""Message to prototype"""
message_proto = CompressedImage()
message_proto.ParseFromString(py_message.message)
return message_proto
def makedirs(dir_path):
"""Make directories recursively."""
if os.path.exists(dir_path):
return
try:
os.makedirs(dir_path)
except OSError as error:
if error.errno != errno.EEXIST:
logging.error('Failed to makedir ' + dir_path)
raise
def main(argv):
"""Main process."""
if not flags.FLAGS.from_record or not os.path.exists(flags.FLAGS.from_record):
logging.error('Please provide valid source record file.')
return
to_record = flags.FLAGS.to_record
if not to_record:
to_record = '{}_restored'.format(flags.FLAGS.from_record)
logging.warn('The default restored record file is set as {}'.format(to_record))
restore_record(flags.FLAGS.from_record, to_record)
if __name__ == '__main__':
app.run(main)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_play/rtk_player.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
Generate Planning Path
"""
import argparse
import atexit
import logging
import math
import os
import sys
import time
from numpy import genfromtxt
import scipy.signal as signal
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import cyber_time
from modules.tools.common.logger import Logger
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.config_msgs import vehicle_config_pb2
from modules.common_msgs.basic_msgs import drive_state_pb2
from modules.common_msgs.basic_msgs import pnc_point_pb2
from modules.common_msgs.control_msgs import pad_msg_pb2
from modules.common_msgs.localization_msgs import localization_pb2
from modules.common_msgs.planning_msgs import planning_pb2
import modules.tools.common.proto_utils as proto_utils
# TODO(all): hard-coded path temporarily. Better approach needed.
APOLLO_ROOT = "/apollo"
SEARCH_INTERVAL = 5000
CHANGE_TO_COM = False
class RtkPlayer(object):
"""
rtk player class
"""
def __init__(self, record_file, node, speedmultiplier, completepath,
replan):
"""Init player."""
self.firstvalid = False
self.logger = Logger.get_logger(tag="RtkPlayer")
self.logger.info("Load record file from: %s" % record_file)
try:
file_handler = open(record_file, 'r')
except (FileNotFoundError, IOError) as ex:
self.logger.error("Error opening {}: {}".format(record_file, ex))
sys.exit(1)
self.data = genfromtxt(file_handler, delimiter=',', names=True)
file_handler.close()
self.localization = localization_pb2.LocalizationEstimate()
self.chassis = chassis_pb2.Chassis()
self.padmsg = pad_msg_pb2.PadMessage()
self.localization_received = False
self.chassis_received = False
self.planning_pub = node.create_writer('/apollo/planning',
planning_pb2.ADCTrajectory)
self.speedmultiplier = speedmultiplier / 100
self.terminating = False
self.sequence_num = 0
b, a = signal.butter(6, 0.05, 'low')
self.data['acceleration'] = signal.filtfilt(b, a,
self.data['acceleration'])
self.start = 0
self.end = 0
self.closestpoint = 0
self.automode = False
self.replan = (replan == 't')
self.completepath = (completepath == 't')
self.estop = False
self.logger.info("Planning Ready")
vehicle_config = vehicle_config_pb2.VehicleConfig()
proto_utils.get_pb_from_text_file(
"/apollo/modules/common/data/vehicle_param.pb.txt", vehicle_config)
self.vehicle_param = vehicle_config.vehicle_param
def localization_callback(self, data):
"""
New localization Received
"""
self.localization.CopyFrom(data)
self.carx = self.localization.pose.position.x
self.cary = self.localization.pose.position.y
self.carz = self.localization.pose.position.z
self.localization_received = True
def chassis_callback(self, data):
"""
New chassis Received
"""
self.chassis.CopyFrom(data)
self.automode = (self.chassis.driving_mode
== chassis_pb2.Chassis.COMPLETE_AUTO_DRIVE)
self.chassis_received = True
def padmsg_callback(self, data):
"""
New message received
"""
if self.terminating is True:
self.logger.info("terminating when receive padmsg")
return
self.padmsg.CopyFrom(data)
def restart(self):
self.logger.info("before replan self.start=%s, self.closestpoint=%s" %
(self.start, self.closestpoint))
self.logger.debug("replan!")
self.closestpoint = self.closest_dist()
self.start = max(self.closestpoint - 1, 0)
self.logger.debug("replan_start: %s" % self.start)
self.starttime = cyber_time.Time.now().to_sec()
self.logger.debug("at time %s" % self.starttime)
self.end = self.next_gear_switch_time(self.start, len(self.data))
self.logger.debug("replan_end: %s" % self.end)
self.logger.info("finish replan at time %s, self.closestpoint=%s" %
(self.starttime, self.closestpoint))
def closest_dist(self):
shortest_dist_sqr = float('inf')
self.logger.info("before closest self.start=%s" % (self.start))
search_start = max(self.start - SEARCH_INTERVAL // 2, 0)
search_end = min(self.start + SEARCH_INTERVAL // 2, len(self.data))
self.logger.debug("search_start: %s" % search_start)
self.logger.debug("search_end: %s" % search_end)
closest_dist_point = self.start
self.logger.debug("self.start: %s" % self.start)
for i in range(search_start, search_end):
dist_sqr = (self.carx - self.data['x'][i]) ** 2 + \
(self.cary - self.data['y'][i]) ** 2
if dist_sqr <= shortest_dist_sqr and self.data['gear'][i] == self.chassis.gear_location:
closest_dist_point = i
shortest_dist_sqr = dist_sqr
# failed to find a trajectory matches current gear position
if shortest_dist_sqr == float('inf'):
self.logger.info(
'no trajectory point matches current gear position, check gear position')
return closest_dist_point + 1 # remain current start point
return closest_dist_point
def closest_time(self):
time_elapsed = cyber_time.Time.now().to_sec() - self.starttime
closest_time = self.start
time_diff = self.data['time'][closest_time] - \
self.data['time'][self.closestpoint]
while time_diff < time_elapsed and closest_time < (len(self.data) - 1):
closest_time = closest_time + 1
time_diff = self.data['time'][closest_time] - \
self.data['time'][self.closestpoint]
return closest_time
def next_gear_switch_time(self, start, end):
for i in range(start, end):
# trajectory with gear switch
# include gear_neutral at the beginning of a trajectory
if (i < end - 1
and self.data['gear'][i] in {1, 2}
and self.data['gear'][i + 1] != self.data['gear'][i]):
self.logger.debug("enter i in while loop: [ %s ]" % i)
self.logger.debug(
"self.data['gear'][i] != 1: %s" % self.data['gear'][i])
self.logger.debug(
"self.data['gear'][i] != 2: %s" % self.data['gear'][i])
# find next gear = 1 or 2
i += 1
while i < end and (self.data['gear'][i] != 1) and (self.data['gear'][i] != 2):
i += 1
self.logger.debug("i in while loop: [ %s ]" % i)
return i - 1
# trajectory without gear switch
self.logger.debug("i at end: [ %s ]" % i)
return min(i, end - 1)
def publish_planningmsg(self):
"""
Generate New Path
"""
if not self.localization_received:
self.logger.warning(
"localization not received yet when publish_planningmsg")
return
planningdata = planning_pb2.ADCTrajectory()
now = cyber_time.Time.now().to_sec()
planningdata.header.timestamp_sec = now
planningdata.header.module_name = "planning"
planningdata.header.sequence_num = self.sequence_num
self.sequence_num = self.sequence_num + 1
self.logger.debug(
"publish_planningmsg: before adjust start: self.start=%s, self.end=%s"
% (self.start, self.end))
if self.replan or self.sequence_num <= 1 or not self.automode:
self.logger.info(
"trigger replan: self.replan=%s, self.sequence_num=%s, self.automode=%s"
% (self.replan, self.sequence_num, self.automode))
self.restart()
else:
timepoint = self.closest_time()
distpoint = self.closest_dist()
if self.data['gear'][timepoint] == self.data['gear'][distpoint]:
self.start = max(min(timepoint, distpoint), 0)
elif self.data['gear'][timepoint] == self.chassis.gear_location:
self.start = timepoint
else:
self.start = distpoint
self.logger.debug("timepoint:[%s]" % timepoint)
self.logger.debug("distpoint:[%s]" % distpoint)
self.logger.debug(
"trajectory start point: [%s], gear is [%s]" % (self.start, self.data['gear'][self.start]))
self.end = self.next_gear_switch_time(self.start, len(self.data))
self.logger.debug("len of data: ", len(self.data))
self.logger.debug("trajectory end point: [%s], gear is [%s]" %
(self.end, self.data['gear'][self.end]))
xdiff_sqr = (self.data['x'][timepoint] - self.carx)**2
ydiff_sqr = (self.data['y'][timepoint] - self.cary)**2
if xdiff_sqr + ydiff_sqr > 4.0:
self.logger.info("trigger replan: distance larger than 2.0")
self.restart()
if self.completepath:
self.start = 0
self.end = len(self.data) - 1
self.logger.debug(
"publish_planningmsg: after adjust start: self.start=%s, self.end=%s"
% (self.start, self.end))
planningdata.total_path_length = self.data['s'][self.end] - \
self.data['s'][self.start]
self.logger.info("total number of planning data point: %d" %
(self.end - self.start))
planningdata.total_path_time = self.data['time'][self.end] - \
self.data['time'][self.start]
planningdata.gear = int(self.data['gear'][self.closest_time()])
planningdata.engage_advice.advice = \
drive_state_pb2.EngageAdvice.READY_TO_ENGAGE
for i in range(self.start, self.end):
adc_point = pnc_point_pb2.TrajectoryPoint()
adc_point.path_point.x = self.data['x'][i]
adc_point.path_point.y = self.data['y'][i]
adc_point.path_point.z = self.data['z'][i]
adc_point.v = self.data['speed'][i] * self.speedmultiplier
adc_point.a = self.data['acceleration'][i] * self.speedmultiplier
adc_point.path_point.kappa = self.data['curvature'][i]
adc_point.path_point.dkappa = self.data['curvature_change_rate'][i]
adc_point.path_point.theta = self.data['theta'][i]
adc_point.path_point.s = self.data['s'][i]
if CHANGE_TO_COM:
# translation vector length(length / 2 - back edge to center)
adc_point.path_point.x = adc_point.path_point.x + \
(self.vehicle_param.length // 2 - self.vehicle_param.back_edge_to_center) * \
math.cos(adc_point.path_point.theta)
adc_point.path_point.y = adc_point.path_point.y + \
(self.vehicle_param.length // 2 - self.vehicle_param.back_edge_to_center) * \
math.sin(adc_point.path_point.theta)
if planningdata.gear == chassis_pb2.Chassis.GEAR_REVERSE:
adc_point.v = -adc_point.v
adc_point.path_point.s = -adc_point.path_point.s
time_diff = self.data['time'][i] - \
self.data['time'][self.closestpoint]
adc_point.relative_time = time_diff / self.speedmultiplier - (
now - self.starttime)
planningdata.trajectory_point.extend([adc_point])
planningdata.estop.is_estop = self.estop
self.planning_pub.write(planningdata)
self.logger.debug("Generated Planning Sequence: "
+ str(self.sequence_num - 1))
def shutdown(self):
"""
shutdown cyber
"""
self.terminating = True
self.logger.info("Shutting Down...")
time.sleep(0.2)
def quit(self, signum, frame):
"""
shutdown the keypress thread
"""
sys.exit(0)
def main():
"""
Main cyber
"""
parser = argparse.ArgumentParser(
description='Generate Planning Trajectory from Data File')
parser.add_argument(
'-s',
'--speedmulti',
help='Speed multiplier in percentage (Default is 100) ',
type=float,
default='100')
parser.add_argument(
'-c', '--complete', help='Generate complete path (t/F)', default='F')
parser.add_argument(
'-r',
'--replan',
help='Always replan based on current position(t/F)',
default='F')
args = vars(parser.parse_args())
node = cyber.Node("rtk_player")
Logger.config(
log_file=os.path.join(APOLLO_ROOT, 'data/log/rtk_player.log'),
use_stdout=True,
log_level=logging.DEBUG)
record_file = os.path.join(APOLLO_ROOT, 'data/log/garage.csv')
player = RtkPlayer(record_file, node, args['speedmulti'],
args['complete'].lower(), args['replan'].lower())
atexit.register(player.shutdown)
node.create_reader('/apollo/canbus/chassis', chassis_pb2.Chassis,
player.chassis_callback)
node.create_reader('/apollo/localization/pose',
localization_pb2.LocalizationEstimate,
player.localization_callback)
node.create_reader('/apollo/control/pad', pad_msg_pb2.PadMessage,
player.padmsg_callback)
while not cyber.is_shutdown():
now = cyber_time.Time.now().to_sec()
player.publish_planningmsg()
sleep_time = 0.1 - (cyber_time.Time.now().to_sec() - now)
if sleep_time > 0:
time.sleep(sleep_time)
if __name__ == '__main__':
cyber.init()
main()
cyber.shutdown()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_play/rtk_recorder.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
Record GPS and IMU data
"""
import atexit
import logging
import math
import os
import sys
import time
from cyber.python.cyber_py3 import cyber
from gflags import FLAGS
from modules.tools.common.logger import Logger
import modules.tools.common.proto_utils as proto_utils
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.config_msgs import vehicle_config_pb2
from modules.common_msgs.localization_msgs import localization_pb2
APOLLO_ROOT = "/apollo"
class RtkRecord(object):
"""
rtk recording class
"""
def write(self, data):
"""Wrap file write function to flush data to disk"""
self.file_handler.write(data)
self.file_handler.flush()
def __init__(self, record_file):
self.firstvalid = False
self.logger = Logger.get_logger("RtkRecord")
self.record_file = record_file
self.logger.info("Record file to: " + record_file)
try:
self.file_handler = open(record_file, 'w')
except IOError:
self.logger.error("Open file %s failed" % (record_file))
self.file_handler.close()
sys.exit(1)
self.write("x,y,z,speed,acceleration,curvature,"
"curvature_change_rate,time,theta,gear,s,throttle,brake,steering\n")
self.localization = localization_pb2.LocalizationEstimate()
self.chassis = chassis_pb2.Chassis()
self.chassis_received = False
self.cars = 0.0
self.startmoving = False
self.terminating = False
self.carcurvature = 0.0
self.prev_carspeed = 0.0
vehicle_config = vehicle_config_pb2.VehicleConfig()
proto_utils.get_pb_from_text_file(
"/apollo/modules/common/data/vehicle_param.pb.txt", vehicle_config)
self.vehicle_param = vehicle_config.vehicle_param
def chassis_callback(self, data):
"""
New message received
"""
if self.terminating is True:
self.logger.info("terminating when receive chassis msg")
return
self.chassis.CopyFrom(data)
#self.chassis = data
if math.isnan(self.chassis.speed_mps):
self.logger.warning("find nan speed_mps: %s" % str(self.chassis))
if math.isnan(self.chassis.steering_percentage):
self.logger.warning(
"find nan steering_percentage: %s" % str(self.chassis))
self.chassis_received = True
def localization_callback(self, data):
"""
New message received
"""
if self.terminating is True:
self.logger.info("terminating when receive localization msg")
return
if not self.chassis_received:
self.logger.info(
"chassis not received when localization is received")
return
self.localization.CopyFrom(data)
#self.localization = data
carx = self.localization.pose.position.x
cary = self.localization.pose.position.y
carz = self.localization.pose.position.z
cartheta = self.localization.pose.heading
if math.isnan(self.chassis.speed_mps):
self.logger.warning("find nan speed_mps: %s" % str(self.chassis))
return
if math.isnan(self.chassis.steering_percentage):
self.logger.warning(
"find nan steering_percentage: %s" % str(self.chassis))
return
carspeed = self.chassis.speed_mps
caracceleration = self.localization.pose.linear_acceleration_vrf.y
speed_epsilon = 1e-9
if abs(self.prev_carspeed) < speed_epsilon \
and abs(carspeed) < speed_epsilon:
caracceleration = 0.0
carsteer = self.chassis.steering_percentage
carmax_steer_angle = self.vehicle_param.max_steer_angle
carsteer_ratio = self.vehicle_param.steer_ratio
carwheel_base = self.vehicle_param.wheel_base
curvature = math.tan(math.radians(carsteer / 100
* math.degrees(carmax_steer_angle)) / carsteer_ratio) / carwheel_base
if abs(carspeed) >= speed_epsilon:
carcurvature_change_rate = (curvature - self.carcurvature) / (
carspeed * 0.01)
else:
carcurvature_change_rate = 0.0
self.carcurvature = curvature
cartime = self.localization.header.timestamp_sec
cargear = self.chassis.gear_location
if abs(carspeed) >= speed_epsilon:
if self.startmoving is False:
self.logger.info(
"carspeed !=0 and startmoving is False, Start Recording")
self.startmoving = True
if self.startmoving:
self.cars += carspeed * 0.01
self.write(
"%s, %s, %s, %s, %s, %s, %s, %.4f, %s, %s, %s, %s, %s, %s\n" %
(carx, cary, carz, carspeed, caracceleration, self.carcurvature,
carcurvature_change_rate, cartime, cartheta, cargear,
self.cars, self.chassis.throttle_percentage,
self.chassis.brake_percentage,
self.chassis.steering_percentage))
self.logger.debug(
"started moving and write data at time %s" % cartime)
else:
self.logger.debug("not start moving, do not write data to file")
self.prev_carspeed = carspeed
def shutdown(self):
"""
shutdown node
"""
self.terminating = True
self.logger.info("Shutting Down...")
self.logger.info("File is written into %s" % self.record_file)
self.file_handler.close()
def main(argv):
"""
Main node
"""
node = cyber.Node("rtk_recorder")
argv = FLAGS(argv)
log_dir = "/apollo/data/log"
if len(argv) > 1:
log_dir = argv[1]
if not os.path.exists(log_dir):
os.makedirs(log_dir)
Logger.config(
log_file=os.path.join(APOLLO_ROOT, 'data/log/rtk_recorder.log'),
use_stdout=True,
log_level=logging.DEBUG)
print("runtime log is in %s%s" % (log_dir, "rtk_recorder.log"))
record_file = log_dir + "/garage.csv"
recorder = RtkRecord(record_file)
atexit.register(recorder.shutdown)
node.create_reader('/apollo/canbus/chassis',
chassis_pb2.Chassis,
recorder.chassis_callback)
node.create_reader('/apollo/localization/pose',
localization_pb2.LocalizationEstimate,
recorder.localization_callback)
while not cyber.is_shutdown():
time.sleep(0.002)
if __name__ == '__main__':
cyber.init()
main(sys.argv)
cyber.shutdown()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_play/README.md
|
# Record and Play Tool
## Prerequisite
Run the following command from your Apollo root dir:
```bash
bash apollo.sh build
source scripts/apollo_base.sh
```
## Recorder
This tool records trajectory information from gateway into a csv file, the file
name is defined in filename_path.
## Player
This tool reads information from a csv file and publishes planning trajectory in
the same format as real planning node.
Default enable recorder and play under `/apollo` utilizing:
```bash
bash scripts/rtk_recorder.sh
```
and
```bash
bash scripts/rtk_player.sh
```
Or using button on Dreamview
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_play/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "readme",
srcs = glob([
"README.md",
]),
)
py_binary(
name = "rtk_player",
srcs = ["rtk_player.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/config_msgs:vehicle_config_py_pb2",
"//modules/common_msgs/basic_msgs:drive_state_py_pb2",
"//modules/common_msgs/basic_msgs:pnc_point_py_pb2",
"//modules/common_msgs/control_msgs:pad_msg_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
"//modules/common_msgs/planning_msgs:planning_py_pb2",
"//modules/tools/common:logger",
"//modules/tools/common:proto_utils",
],
)
py_binary(
name = "rtk_recorder",
srcs = ["rtk_recorder.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
"//modules/tools/common:logger",
"//modules/tools/common:proto_utils",
],
)
install(
name = "install",
data = [":readme"],
data_dest = "tools/record_play",
py_dest = "tools/record_play",
targets = [
":rtk_player",
":rtk_recorder"
],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/data_collector.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
Data Collector
"""
import os
import signal
import sys
import time
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import cyber_time
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.control_msgs import control_cmd_pb2
from modules.common_msgs.localization_msgs import localization_pb2
from modules.tools.vehicle_calibration.plot_data import Plotter
class DataCollector(object):
"""
DataCollector Class
"""
def __init__(self, node):
self.sequence_num = 0
self.control_pub = node.create_writer('/apollo/control',
control_cmd_pb2.ControlCommand)
time.sleep(0.3)
self.controlcmd = control_cmd_pb2.ControlCommand()
self.canmsg_received = False
self.localization_received = False
self.case = 'a'
self.in_session = False
self.outfile = ""
def run(self, cmd):
signal.signal(signal.SIGINT, self.signal_handler)
self.in_session = True
self.cmd = list(map(float, cmd))
out = ''
if self.cmd[0] > 0:
out += 't'
else:
out += 'b'
out = out + str(int(self.cmd[0]))
if self.cmd[2] > 0:
out += 't'
else:
out += 'b'
out += str(int(self.cmd[2])) + 'r'
i = 0
self.outfile = out + str(i) + '_recorded.csv'
while os.path.exists(self.outfile):
i += 1
self.outfile = out + str(i) + '_recorded.csv'
self.file = open(self.outfile, 'w')
self.file.write(
"time,io,ctlmode,ctlbrake,ctlthrottle,ctlgear_location," +
"vehicle_speed,engine_rpm,driving_mode,throttle_percentage," +
"brake_percentage,gear_location,imu\n"
)
print('Send Reset Command.')
self.controlcmd.header.module_name = "control"
self.controlcmd.header.sequence_num = self.sequence_num
self.sequence_num = self.sequence_num + 1
self.controlcmd.header.timestamp_sec = cyber_time.Time.now().to_sec()
self.controlcmd.pad_msg.action = 2
self.control_pub.write(self.controlcmd)
time.sleep(0.2)
# Set Default Message
print('Send Default Command.')
self.controlcmd.pad_msg.action = 1
self.controlcmd.throttle = 0
self.controlcmd.brake = 0
self.controlcmd.steering_rate = 100
self.controlcmd.steering_target = 0
self.controlcmd.gear_location = chassis_pb2.Chassis.GEAR_DRIVE
self.canmsg_received = False
self.case = 'a'
while self.in_session:
now = cyber_time.Time.now().to_sec()
self.publish_control()
sleep_time = 0.01 - (cyber_time.Time.now().to_sec() - now)
if sleep_time > 0:
time.sleep(sleep_time)
def signal_handler(self, signal, frame):
self.in_session = False
def callback_localization(self, data):
"""
New Localization
"""
self.acceleration = data.pose.linear_acceleration_vrf.y
self.localization_received = True
def callback_canbus(self, data):
"""
New CANBUS
"""
if not self.localization_received:
print('No Localization Message Yet')
return
timenow = data.header.timestamp_sec
self.vehicle_speed = data.speed_mps
self.engine_rpm = data.engine_rpm
self.throttle_percentage = data.throttle_percentage
self.brake_percentage = data.brake_percentage
self.gear_location = data.gear_location
self.driving_mode = data.driving_mode
self.canmsg_received = True
if self.in_session:
self.write_file(timenow, 0)
def publish_control(self):
"""
New Control Command
"""
if not self.canmsg_received:
print('No CAN Message Yet')
return
self.controlcmd.header.sequence_num = self.sequence_num
self.sequence_num += 1
if self.case == 'a':
if self.cmd[0] > 0:
self.controlcmd.throttle = self.cmd[0]
self.controlcmd.brake = 0
else:
self.controlcmd.throttle = 0
self.controlcmd.brake = -self.cmd[0]
if self.vehicle_speed >= self.cmd[1]:
self.case = 'd'
elif self.case == 'd':
if self.cmd[2] > 0:
self.controlcmd.throttle = self.cmd[0]
self.controlcmd.brake = 0
else:
self.controlcmd.throttle = 0
self.controlcmd.brake = -self.cmd[2]
if self.vehicle_speed == 0:
self.in_session = False
self.controlcmd.header.timestamp_sec = cyber_time.Time.now().to_sec()
self.control_pub.write(self.controlcmd)
self.write_file(self.controlcmd.header.timestamp_sec, 1)
if self.in_session == False:
self.file.close()
def write_file(self, time, io):
"""
Write Message to File
"""
self.file.write(
"%.4f,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n" %
(time, io, 1, self.controlcmd.brake, self.controlcmd.throttle,
self.controlcmd.gear_location, self.vehicle_speed, self.engine_rpm,
self.driving_mode, self.throttle_percentage, self.brake_percentage,
self.gear_location, self.acceleration))
def main():
"""
Main function
"""
node = cyber.Node("data_collector")
data_collector = DataCollector(node)
plotter = Plotter()
node.create_reader('/apollo/localization/pose',
localization_pb2.LocalizationEstimate,
data_collector.callback_localization)
node.create_reader('/apollo/canbus/chassis', chassis_pb2.Chassis,
data_collector.callback_canbus)
print('Enter q to quit.')
print('Enter p to plot result from last run.')
print('Enter x to remove result from last run.')
print('Enter x y z, where x is acceleration command, ' +
'y is speed limit, z is decceleration command.')
print('Positive number for throttle and negative number for brake.')
while True:
cmd = input("Enter commands: ").split()
if len(cmd) == 0:
print('Quiting.')
break
elif len(cmd) == 1:
if cmd[0] == "q":
break
elif cmd[0] == "p":
print('Plotting result.')
if os.path.exists(data_collector.outfile):
plotter.process_data(data_collector.outfile)
plotter.plot_result()
else:
print('File does not exist: %s' % data_collector.outfile)
elif cmd[0] == "x":
print('Removing last result.')
if os.path.exists(data_collector.outfile):
os.remove(data_collector.outfile)
else:
print('File does not exist: %s' % date_collector.outfile)
elif len(cmd) == 3:
data_collector.run(cmd)
if __name__ == '__main__':
cyber.init()
main()
cyber.shutdown()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/process_data.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
rm $DIR/result.csv
for f in `ls ${1}/*_recorded.csv`
do
echo "Processing $f"
python -W ignore $DIR/process_data.py $f
done
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/preprocess.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
This module provides the preprocessing function of vehicle calibration data
"""
import os
import re
import shutil
import time
from absl import app
from absl import flags
from absl import logging
from datetime import datetime
from cyber.python.cyber_py3 import cyber
from modules.dreamview.proto import preprocess_table_pb2
from modules.tools.vehicle_calibration.sanity_check import sanity_check
flags.DEFINE_string('vehicle_type', '', 'The vehicle type to be calibrated')
flags.DEFINE_string('data_path', '/apollo/output', 'Default output data path')
flags.DEFINE_string('calibration_data_path',
'/apollo/modules/calibration/data',
'Default vehicle configuration file directory')
flags.DEFINE_string('config_file_name', 'vehicle_param.pb.txt',
'Default vehicle configuration file name')
flags.DEFINE_string('record_root_path', '/apollo/data/bag',
'Default record root path')
flags.DEFINE_integer(
'record_num', 1, 'The number of record folders '
'required for this calibration task')
FLAGS = flags.FLAGS
def main(argv):
cyber.init("Preprocessor")
preprocessor = Preprocessor()
task_dir = preprocessor.create_tree()
preprocessor.sanity_check_path(task_dir)
cyber.shutdown()
class Preprocessor(object):
def __init__(self):
self.record_num = FLAGS.record_num
self.vehicle_type = self.folder_case(FLAGS.vehicle_type)
self.config_file = self.get_config_path()
self.node = cyber.Node("vehicle_calibration_preprocessor")
self.writer = self.node.create_writer("/apollo/dreamview/progress",
preprocess_table_pb2.Progress,
10)
self.progress = preprocess_table_pb2.Progress()
self.progress.percentage = 0.0
self.progress.log_string = "Press the button to start preprocessing"
@staticmethod
def folder_case(str):
"""Convert a string from title case to folder case"""
return "_".join(str.lower().split(" "))
def create_if_not_exists(self, path):
"""Create dir if path does not exists"""
try:
if not os.path.exists(path):
os.makedirs(path)
self.log_and_publish(f'Sucessfully created {path}')
except OSError:
self.log_and_publish(f'Failed to create: {path}', 'error')
return path
def get_config_path(self):
"""Get the configuration file of the specified vehicle type"""
return os.path.join(FLAGS.calibration_data_path, self.vehicle_type,
FLAGS.config_file_name)
def get_records_info(self):
"""Get records required for calibration"""
res = []
for dir in os.listdir(FLAGS.record_root_path):
match = re.match(r'(^\d{4}-\d{2}-\d{2})-(\d{2}-\d{2}-\d{2}_s$)',
dir)
if match is not None:
record_info = {}
record_info['rel_path'] = match.group()
record_info['abs_path'] = os.path.join(FLAGS.record_root_path,
match.group())
record_info['prefix'] = match.group(1)
res.append(record_info)
if len(res) < self.record_num:
self.log_and_publish(
f'The number of records in {FLAGS.record_root_path} '
f'is less than {self.record_num}', 'error')
res = sorted(res, key=lambda record: record['rel_path'],
reverse=True)[:self.record_num]
return res
def log_and_publish(self,
str,
logging_level="info",
status=preprocess_table_pb2.Status.UNKNOWN):
"""Publish the str by cyber writer"""
if logging_level == 'info':
logging.info(str)
elif logging_level == 'warn':
logging.warn(str)
elif logging_level == 'error':
logging.error(str)
elif logging_level == 'fatal':
logging.fatal(str)
else:
logging.info(str)
self.progress.log_string = str
self.progress.status = status
self.writer.write(self.progress)
time.sleep(0.5)
def create_tree(self):
"""Create file tree according to a specific order"""
task_dir = self.create_if_not_exists(
os.path.join(FLAGS.data_path,
'task' + datetime.now().strftime("-%Y-%m-%d-%H-%M")))
vehicle_dir = self.create_if_not_exists(
os.path.join(task_dir, self.vehicle_type))
records_dir = self.create_if_not_exists(
os.path.join(vehicle_dir, "Records"))
shutil.copy(self.config_file, vehicle_dir)
records_info = self.get_records_info()
finished_records = 0
self.progress.log_string = 'Start preprocessing...'
for iter in records_info:
sub_dir = self.create_if_not_exists(
os.path.join(records_dir, iter['prefix']))
shutil.copytree(iter['abs_path'],
os.path.join(sub_dir, iter['rel_path']))
finished_records += 1
self.progress.percentage = (
finished_records / self.record_num) * 80.0
self.writer.write(self.progress)
self.log_and_publish(
f'The file tree has been successfully created at {task_dir}.')
return task_dir
def sanity_check_path(self, path):
"""Sanity check wrapper"""
result, log_str = sanity_check(path)
if result is True:
self.progress.percentage = 100.0
self.progress.status = preprocess_table_pb2.Status.SUCCESS
else:
self.progress.status = preprocess_table_pb2.Status.FAIL
self.progress.log_string = log_str
self.writer.write(self.progress)
time.sleep(0.5)
if __name__ == "__main__":
app.run(main)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/result2pb.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
import sys
import numpy as np
import modules.tools.common.proto_utils as proto_utils
from modules.control.proto import calibration_table_pb2
from modules.control.proto.control_conf_pb2 import ControlConf
def load_calibration_raw_data(fn):
speed_table = {}
with open(fn, 'r') as f:
for line in f:
items = line.split(',')
cmd = round(float(items[0]))
speed = float(items[1])
acc = round(float(items[2]), 2)
if speed in speed_table:
cmd_table = speed_table[speed]
if cmd in cmd_table:
cmd_table[cmd].append(acc)
else:
cmd_table[cmd] = [acc]
else:
cmd_table = {}
cmd_table[cmd] = [acc]
speed_table[speed] = cmd_table
for speed in speed_table:
cmd_table = speed_table[speed]
for cmd in cmd_table:
cmd_table[cmd] = round(np.mean(cmd_table[cmd]), 2)
# After this the acc_list converted to an average float number.
speed_table2 = {}
for speed in speed_table:
cmd_table = speed_table[speed]
acc_table = {}
for cmd in cmd_table:
acc = cmd_table[cmd]
if acc in acc_table:
acc_table[acc].append(cmd)
else:
acc_table[acc] = [cmd]
speed_table2[speed] = acc_table
return speed_table2
def load_calibration_raw_data_old(fn):
speed_table = {}
with open(fn, 'r') as f:
for line in f:
items = line.split(',')
cmd = round(float(items[0]))
speed = float(items[1])
acc = round(float(items[2]), 2)
if speed in speed_table:
acc_table = speed_table[speed]
if acc in acc_table:
acc_table[acc].append(cmd)
else:
acc_table[acc] = [cmd]
else:
acc_table = {}
acc_table[acc] = [cmd]
speed_table[speed] = acc_table
return speed_table
def get_calibration_table_pb(speed_table):
calibration_table_pb = calibration_table_pb2.ControlCalibrationTable()
speeds = list(speed_table.keys())
speeds.sort()
for speed in speeds:
acc_table = speed_table[speed]
accs = list(acc_table.keys())
accs.sort()
for acc in accs:
cmds = acc_table[acc]
cmd = np.mean(cmds)
item = calibration_table_pb.calibration.add()
item.speed = speed
item.acceleration = acc
item.command = cmd
return calibration_table_pb
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Usage: %s old_control_conf.pb.txt result.csv" % sys.argv[0])
sys.exit(0)
ctl_conf_pb = proto_utils.get_pb_from_text_file(sys.argv[1], ControlConf())
speed_table_dict = load_calibration_raw_data(sys.argv[2])
calibration_table_pb = get_calibration_table_pb(speed_table_dict)
ctl_conf_pb.lon_controller_conf.calibration_table.CopyFrom(
calibration_table_pb)
with open('control_conf.pb.txt', 'w') as f:
f.write(str(ctl_conf_pb))
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/plot_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
This module provide function to plot the speed control info from log csv file
"""
import sys
import matplotlib.pyplot as plt
import numpy as np
import tkinter.filedialog
from modules.tools.vehicle_calibration.process import get_start_index
from modules.tools.vehicle_calibration.process import preprocess
from modules.tools.vehicle_calibration.process import process
class Plotter(object):
"""
Plot the speed info
"""
def __init__(self):
"""
Init the speed info
"""
np.set_printoptions(precision=3)
self.file = open('temp_result.csv', 'a')
def process_data(self, filename):
"""
Load the file and preprocess th data
"""
self.data = preprocess(filename)
self.tablecmd, self.tablespeed, self.tableacc, self.speedsection, self.accsection, self.timesection = process(
self.data)
def plot_result(self):
"""
Plot the desired data
"""
fig, axarr = plt.subplots(2, 1, sharex=True)
plt.tight_layout()
fig.subplots_adjust(hspace=0)
axarr[0].plot(
self.data['time'], self.data['ctlbrake'], label='Brake CMD')
axarr[0].plot(
self.data['time'],
self.data['brake_percentage'],
label='Brake Output')
axarr[0].plot(
self.data['time'], self.data['ctlthrottle'], label='Throttle CMD')
axarr[0].plot(
self.data['time'],
self.data['throttle_percentage'],
label='Throttle Output')
axarr[0].plot(
self.data['time'],
self.data['engine_rpm'] / 100,
label='Engine RPM')
axarr[0].legend(fontsize='medium')
axarr[0].grid(True)
axarr[0].set_title('Command')
axarr[1].plot(
self.data['time'],
self.data['vehicle_speed'],
label='Vehicle Speed')
for i in range(len(self.timesection)):
axarr[1].plot(
self.timesection[i],
self.speedsection[i],
label='Speed Segment')
axarr[1].plot(
self.timesection[i], self.accsection[i], label='IMU Segment')
axarr[1].legend(fontsize='medium')
axarr[1].grid(True)
axarr[1].set_title('Speed')
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
# plt.tight_layout(pad=0.20)
fig.canvas.mpl_connect('key_press_event', self.press)
plt.show()
def press(self, event):
"""
Keyboard events during plotting
"""
if event.key == 'q' or event.key == 'Q':
self.file.close()
plt.close()
if event.key == 'w' or event.key == 'W':
for i in range(len(self.tablecmd)):
for j in range(len(self.tablespeed[i])):
self.file.write("%s, %s, %s\n" %
(self.tablecmd[i], self.tablespeed[i][j],
self.tableacc[i][j]))
print("Finished writing results")
def main():
"""
demo
"""
if len(sys.argv) == 2:
# Get the latest file
file_path = sys.argv[1]
else:
file_path = tkinter.filedialog.askopenfilename(
initialdir="/home/caros/.ros",
filetypes=(("csv files", ".csv"), ("all files", "*.*")))
print('File path: %s' % file_path)
plotter = Plotter()
plotter.process_data(file_path)
print('Finished reading the file.')
plotter.plot_result()
if __name__ == '__main__':
main()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/sanity_check.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
This is a tool to sanity check the vechicle calibration files
"""
import fnmatch
import math
import os
import google.protobuf.text_format as text_format
from absl import logging
from cyber.python.cyber_py3.record import RecordReader
import modules.common_msgs.config_msgs.vehicle_config_pb2 as vehicle_config_pb2
import modules.tools.common.proto_utils as proto_utils
import modules.tools.common.file_utils as file_utils
# could be a list
ConfFile = 'vehicle_param.pb.txt'
CHASSIS_CHANNEL = '/apollo/canbus/chassis'
LOCALIZATION_CHANNEL = '/apollo/localization/pose'
CHANNELS = {CHASSIS_CHANNEL, LOCALIZATION_CHANNEL}
def is_record_file(path):
"""Naive check if a path is a record."""
return path.endswith('.record') or fnmatch.fnmatch(path, '*.record.?????')
def get_vehicle(path):
return [
subdir for subdir in os.listdir(path)
if os.path.isdir(os.path.join(path, subdir))
]
def missing_input_path(path):
input_size = file_utils.getInputDirDataSize(path)
if input_size == 0:
return True
return False
def list_records(path):
logging.info("in list_records:%s" % path)
records = []
for (dirpath, _, filenames) in os.walk(path):
logging.info('filenames: %s' % filenames)
logging.info('dirpath %s' % dirpath)
for filename in filenames:
end_file = os.path.join(dirpath, filename)
logging.info("end_files: %s" % end_file)
if is_record_file(end_file):
records.append(end_file)
return records
def missing_file(path):
vehicles = get_vehicle(path)
logging.info(f'vehicles {vehicles}')
result = []
for vehicle in vehicles:
# config file
conf = os.path.join(path, vehicle, ConfFile)
logging.info(f'vehicles conf {conf}')
if not os.path.exists(conf):
logging.error(f'Missing configuration file in {vehicle}')
result.append(ConfFile)
# record file
logging.info("list of records:" %
list_records(os.path.join(path, vehicle)))
if len(list_records(os.path.join(path, vehicle))) == 0:
logging.error(f'No record files in {vehicle}')
result.append('record')
if len(result):
return True, result
return False, []
def parse_error(path):
vehicles = get_vehicle(path)
pb_value = vehicle_config_pb2.VehicleConfig()
for vehicle in vehicles:
conf = os.path.join(path, vehicle, ConfFile)
try:
proto_utils.get_pb_from_text_file(conf, pb_value)
return False
except text_format.ParseError:
logging.error(
f'Error: Cannot parse {conf} as binary or text proto')
return True
def check_vehicle_id(conf):
# print(conf.HasField('vehicle_id.other_unique_id'))
vehicle_id = conf.vehicle_param.vehicle_id
if vehicle_id.vin or vehicle_id.plate or vehicle_id.other_unique_id:
return True
logging.error('Error: No vehicle ID')
return False
def missing_field(path):
vehicles = get_vehicle(path)
logging.info(f'vehicles in missing field: {vehicles}')
result = []
for vehicle in vehicles:
conf_file = os.path.join(path, vehicle, ConfFile)
logging.info(f'conf_file: {conf_file}')
# reset for each vehicle to avoid overwrited
pb_value = vehicle_config_pb2.VehicleConfig()
conf = proto_utils.get_pb_from_text_file(conf_file, pb_value)
logging.info(f'vehicles conf {conf}')
if not check_vehicle_id(conf):
result.append("vehicle_id")
# required field
fields = [
conf.vehicle_param.brake_deadzone,
conf.vehicle_param.throttle_deadzone,
conf.vehicle_param.max_acceleration,
conf.vehicle_param.max_deceleration
]
# for value in conf.vehicle_param:
# has field is always true since a default value is given
for field in fields:
if math.isnan(field):
result.append(field)
if len(result):
return True, result
return False, result
def missing_message_data(path, channels=CHANNELS):
result = []
for record in list_records(path):
logging.info(f'reading records {record}')
reader = RecordReader(record)
for channel in channels:
logging.info(f'has {reader.get_messagenumber(channel)} messages')
if reader.get_messagenumber(channel) == 0:
result.append(record)
if len(result):
return True, result
return False, []
def sanity_check(input_folder):
err_msg = None
path_flag = missing_input_path(input_folder)
field_flag, field_result = missing_field(input_folder)
channel_flag, channel_result = missing_message_data(input_folder)
file_flag, file_result = missing_file(input_folder)
if path_flag:
err_msg = f'Input path {input_folder} folder structure is wrong'
if file_flag:
err_msg = f'One or more files are missing in {input_folder}'
elif parse_error(input_folder):
err_msg = f'Config file cannot be parsed in {input_folder}'
elif field_flag:
err_msg = f'One or more fields are missing in {input_folder}'
elif channel_flag:
err_msg = (
'Messages are missing in records channels apollo/chassis or '
f'apollo/localization/pose, records are {channel_result}')
else:
info_msg = f'{input_folder} Passed sanity check.'
logging.info(info_msg)
return True, info_msg
logging.error(err_msg)
return False, err_msg
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/plot_grid.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
import math
import sys
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm as cmx
from matplotlib import colors as mcolors
markers = [
"o", "v", "^", "<", ">", "1", "2", "3", "4", "8", "s", "p", "*", "+", "x",
"d", "|", "_"
]
if len(sys.argv) < 2:
print('Usage: %s result.csv' % sys.argv[0])
sys.exit(0)
fn = sys.argv[1]
speed_table = {}
with open(fn, 'r') as f:
for line in f:
items = line.split(',')
cmd = round(float(items[0]))
speed = float(items[1])
acc = round(float(items[2]), 2)
if speed in speed_table:
cmd_table = speed_table[speed]
if cmd in cmd_table:
cmd_table[cmd].append(acc)
else:
cmd_table[cmd] = [acc]
else:
cmd_table = {}
cmd_table[cmd] = [acc]
speed_table[speed] = cmd_table
for speed in speed_table:
cmd_dict = speed_table[speed]
speed_list = []
acc_list = []
for cmd in cmd_dict:
for acc in cmd_dict[cmd]:
speed_list.append(speed)
acc_list.append(acc)
plt.plot(speed_list, acc_list, 'b.')
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/preprocess.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd -P)"
PREPROCESS_BIN=/opt/apollo/neo/packages/tools-dev/latest/vehicle_calibration/preprocess
if [[ ! -f "${PREPROCESS_BIN}" ]]; then
PREPROCESS_BIN=${TOP_DIR}/bazel-bin/modules/tools/vehicle_calibration/preprocess
fi
if [[ -f "${PREPROCESS_BIN}" ]]; then
"${PREPROCESS_BIN}" "$@"
else
bazel run //modules/tools/vehicle_calibration:preprocess -- "$@"
fi
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/process_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
This module provide function to plot the speed control info from log csv file
"""
import math
import sys
import numpy as np
import tkinter.filedialog
from modules.tools.vehicle_calibration.process import get_start_index
from modules.tools.vehicle_calibration.process import preprocess
from modules.tools.vehicle_calibration.process import process
class Plotter(object):
"""
plot the speed info
"""
def __init__(self, filename):
"""
init the speed info
"""
np.set_printoptions(precision=3)
self.file = open('result.csv', 'a')
self.file_one = open(filename + ".result", 'w')
def process_data(self, filename):
"""
load the file and preprocess th data
"""
self.data = preprocess(filename)
self.tablecmd, self.tablespeed, self.tableacc, self.speedsection, self.accsection, self.timesection = process(
self.data)
def save_data(self):
"""
save_data
"""
for i in range(len(self.tablecmd)):
for j in range(len(self.tablespeed[i])):
self.file.write("%s, %s, %s\n" %
(self.tablecmd[i], self.tablespeed[i][j],
self.tableacc[i][j]))
self.file_one.write("%s, %s, %s\n" %
(self.tablecmd[i], self.tablespeed[i][j],
self.tableacc[i][j]))
def main():
"""
demo
"""
if len(sys.argv) == 2:
# get the latest file
file_path = sys.argv[1]
else:
file_path = tkinter.filedialog.askopenfilename(
initialdir="/home/caros/.ros",
filetypes=(("csv files", ".csv"), ("all files", "*.*")))
plotter = Plotter(file_path)
plotter.process_data(file_path)
plotter.save_data()
print('save result to:', file_path + ".result")
if __name__ == '__main__':
main()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/process.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
This module provide function to plot the speed control info from log csv file
"""
import math
import warnings
import numpy as np
import scipy.signal as signal
warnings.simplefilter('ignore', np.RankWarning)
SPEED_INTERVAL = 0.2
SPEED_DELAY = 130 # Speed report delay relative to IMU information
def preprocess(filename):
data = np.genfromtxt(filename, delimiter=',', names=True)
data = data[np.where(data['io'] == 0)[0]]
data = data[np.argsort(data['time'])]
data['time'] = data['time'] - data['time'][get_start_index(data)]
b, a = signal.butter(6, 0.05, 'low')
data['imu'] = signal.filtfilt(b, a, data['imu'])
data['imu'] = np.append(data['imu'][-SPEED_DELAY // 10:],
data['imu'][0:-SPEED_DELAY // 10])
return data
def get_start_index(data):
if np.all(data['vehicle_speed'] == 0):
return 0
start_ind = np.where(data['brake_percentage'] == 40)
if len(start_ind[0] > 0):
ind = start_ind[0][0]
while ind < len(data):
if data['brake_percentage'][ind] == 40:
ind += 1
else:
break
return ind
else:
ind = 0
while ind < len(data):
if abs(data['vehicle_speed'][ind]) < 0.01:
ind += 1
else:
break
return ind
def process(data):
"""
process data
"""
np.set_printoptions(precision=3)
if np.all(data['vehicle_speed'] == 0):
print("All Speed = 0")
return [], [], [], [], [], []
start_index = get_start_index(data)
# print "Start index: ", start_index
data = data[start_index:]
data['time'] = data['time'] - data['time'][0]
transition = np.where(
np.logical_or(
np.diff(data['ctlbrake']) != 0, np.diff(data['ctlthrottle']) != 0))[
0]
transition = np.insert(np.append(transition, len(data) - 1), 0, 0)
# print "Transition indexes: ", transition
speedsegments = []
timesegments = []
accsegments = []
tablespeed = []
tableacc = []
tablecmd = []
for i in range(len(transition) - 1):
# print "process transition index:", data['time'][transition[i]], ":", data['time'][transition[i + 1]]
speedsection = data['vehicle_speed'][transition[i]:transition[i +
1] + 1]
timesection = data['time'][transition[i]:transition[i + 1] + 1]
brake = data['ctlbrake'][transition[i] + 1]
throttle = data['ctlthrottle'][transition[i] + 1]
imusection = data['imu'][transition[i]:transition[i + 1] + 1]
if brake == 0 and throttle == 0:
continue
# print "Brake CMD: ", brake, " Throttle CMD: ", throttle
firstindex = 0
while speedsection[firstindex] == 0:
firstindex += 1
firstindex = max(firstindex - 2, 0)
speedsection = speedsection[firstindex:]
timesection = timesection[firstindex:]
imusection = imusection[firstindex:]
if speedsection[0] < speedsection[-1]:
is_increase = True
lastindex = np.argmax(speedsection)
else:
is_increase = False
lastindex = np.argmin(speedsection)
speedsection = speedsection[0:lastindex + 1]
timesection = timesection[0:lastindex + 1]
imusection = imusection[0:lastindex + 1]
speedmin = np.min(speedsection)
speedmax = np.max(speedsection)
speedrange = np.arange(
max(0, round(speedmin / SPEED_INTERVAL) * SPEED_INTERVAL),
min(speedmax, 10.01), SPEED_INTERVAL)
# print "Speed min, max", speedmin, speedmax, is_increase, firstindex, lastindex, speedsection[-1]
accvalue = []
for value in speedrange:
val_ind = 0
if is_increase:
while val_ind < len(
speedsection) - 1 and value > speedsection[val_ind]:
val_ind += 1
else:
while val_ind < len(
speedsection) - 1 and value < speedsection[val_ind]:
val_ind += 1
if val_ind == 0:
imu_value = imusection[val_ind]
else:
slope = (imusection[val_ind] - imusection[val_ind - 1]) / (
speedsection[val_ind] - speedsection[val_ind - 1])
imu_value = imusection[val_ind - 1] + slope * (
value - speedsection[val_ind - 1])
accvalue.append(imu_value)
if brake == 0:
cmd = throttle
else:
cmd = -brake
# print "Overall CMD: ", cmd
# print "Time: ", timesection
# print "Speed: ", speedrange
# print "Acc: ", accvalue
# print cmd
tablecmd.append(cmd)
tablespeed.append(speedrange)
tableacc.append(accvalue)
speedsegments.append(speedsection)
accsegments.append(imusection)
timesegments.append(timesection)
return tablecmd, tablespeed, tableacc, speedsegments, accsegments, timesegments
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
install(
name = "install",
data = ["runtime_files"],
data_dest = "tools/vehicle_calibration",
py_dest = "tools/vehicle_calibration",
targets = [
":data_collector",
":plot_data",
":plot_grid",
":plot_results",
":preprocess",
":process_data",
":result2pb",
]
)
py_binary(
name = "data_collector",
srcs = ["data_collector.py"],
deps = [
":plot_data",
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/control_msgs:control_cmd_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
py_binary(
name = "plot_data",
srcs = ["plot_data.py"],
deps = [
":process",
],
)
py_binary(
name = "plot_grid",
srcs = ["plot_grid.py"],
)
py_binary(
name = "plot_results",
srcs = ["plot_results.py"],
)
py_binary(
name = "preprocess",
srcs = ["preprocess.py"],
deps = [
":sanity_check",
"//cyber/python/cyber_py3:cyber",
"//modules/dreamview/proto:preprocess_table_py_pb2",
],
)
py_library(
name = "process",
srcs = ["process.py"],
)
py_binary(
name = "process_data",
srcs = ["process_data.py"],
deps = [
":process",
],
)
py_binary(
name = "result2pb",
srcs = ["result2pb.py"],
deps = [
"//modules/control/proto:calibration_table_py_pb2",
"//modules/control/proto:control_conf_py_pb2",
"//modules/tools/common:proto_utils",
],
)
py_library(
name = "sanity_check",
srcs = ["sanity_check.py"],
deps = [
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/config_msgs:vehicle_config_py_pb2",
"//modules/tools/common:file_utils",
"//modules/tools/common:proto_utils",
],
)
filegroup(
name = "runtime_files",
srcs = glob([
"calibration_data_sample/**",
"*.py",
"*.sh",
]),
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/result2pb.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd -P)"
if [[ -f "/opt/apollo/neo/packages/tools-dev/latest/vehicle_calibration/result2pb" ]]; then
/opt/apollo/neo/packages/tools-dev/latest/vehicle_calibration/result2pb /opt/apollo/neo/packages/control-dev/latest/conf/control_conf.pb.txt $1
else
${TOP_DIR}/bazel-bin/modules/tools/vehicle_calibration/result2pb ${TOP_DIR}/modules/control/conf/control_conf.pb.txt $1
fi
echo "Created control conf file: control_conf_pb.txt"
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/plot_results.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
import math
import sys
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm as cmx
from matplotlib import colors as mcolors
markers = [
"o", "v", "^", "<", ">", "1", "2", "3", "4", "8", "s", "p", "*", "+", "x",
"d", "|", "_"
]
if len(sys.argv) < 2:
print("Usage: python plot_results.py result.csv")
sys.exit(0)
with open(sys.argv[1], 'r') as f:
cmd_table = {}
for line in f:
items = line.split(',')
cmd = round(float(items[0]))
speed = float(items[1])
acc = float(items[2])
if cmd in cmd_table:
speed_table = cmd_table[cmd]
if speed in speed_table:
speed_table[speed].append(acc)
else:
speed_table[speed] = [acc]
else:
speed_table = {}
speed_table[speed] = [acc]
cmd_table[cmd] = speed_table
NCURVES = len(cmd_table)
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = list(range(NCURVES))
jet = cm = plt.get_cmap('brg')
cNorm = mcolors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
cnt = 0
cmds = list(cmd_table.keys())
cmds.sort()
fig, ax = plt.subplots()
for cmd in cmds:
print('ctrl cmd = %s' % cmd)
speed_table = cmd_table[cmd]
X = []
Y = []
speeds = list(speed_table.keys())
speeds.sort()
for speed in speeds:
X.append(speed)
Y.append(np.mean(speed_table[speed]))
colorVal = scalarMap.to_rgba(values[cnt])
ax.plot(
X,
Y,
c=colorVal,
linestyle=':',
marker=markers[cnt % len(markers)],
label="cmd=" + str(cmd))
cnt += 1
ax.legend(loc='upper center', shadow=True, bbox_to_anchor=(0.5, 1.1), ncol=5)
plt.ylabel("acc")
plt.xlabel("speed")
plt.grid()
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t55b30.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 55.0
c: vehicle_speed >= 12.0
a: throttle = 0.0
t: 1.0
a: brake = 30.0
c: vehicle_speed == 0.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t15b13.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 15.0
c: vehicle_speed >= 10.0
a: throttle = 0.0
t: 1.0
a: brake = 13.0
c: vehicle_speed == 0.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t40b13.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 40.0
c: vehicle_speed >= 10.0
a: throttle = 0.0
t: 1.0
a: brake = 13.0
c: vehicle_speed == 0.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t40b17.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 40.0
c: vehicle_speed >= 12.0
a: throttle = 0.0
t: 1.0
a: brake = 17.0
c: vehicle_speed == 0.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t17b13.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 17.0
c: vehicle_speed >= 10.0
a: throttle = 0.0
t: 1.0
a: brake = 13.0
c: vehicle_speed == 0.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t80b30.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 80.0
c: vehicle_speed >= 12.0
a: throttle = 0.0
t: 1.0
a: brake = 30.0
c: vehicle_speed == 0.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t45b30.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 45.0
c: vehicle_speed >= 12.0
a: throttle = 0.0
t: 1.0
a: brake = 30.0
c: vehicle_speed == 0.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t40b15.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 40.0
c: vehicle_speed >= 12.0
a: throttle = 0.0
t: 1.0
a: brake = 15.0
c: vehicle_speed == 0.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/b20_up.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 20.0
a: throttle = 0.0
c: vehicle_speed >= 10.0
| 0
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration
|
apollo_public_repos/apollo/modules/tools/vehicle_calibration/calibration_data_sample/t17_down.txt
|
a: gear_location = chassis_pb2.Chassis.GEAR_DRIVE
a: brake = 40.0
a: steering_target = 0.0
a: throttle = 0.0
c: vehicle_speed == 0.0
t: 2.0
a: brake = 0.0
a: throttle = 60.0
c: vehicle_speed >= 10.0
a: throttle = 17.0
a: brake = 0.0
c: vehicle_speed == 0.0
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.